From d9b20bcd0d6006eb365224b0509d44ef38611d46 Mon Sep 17 00:00:00 2001 From: Henry Date: Sun, 2 Aug 2026 19:59:10 +0200 Subject: feat: add validate feature Signed-off-by: Henry --- crates/parser/src/conversion.rs | 77 ++++++++++++++++++++++++++++++++--------- 1 file changed, 61 insertions(+), 16 deletions(-) (limited to 'crates/parser/src/conversion.rs') diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index db8d2aa..600976a 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -1,10 +1,10 @@ -use crate::{Result, module::FunctionCode, visit::process_operators_and_validate}; +use crate::validation::{FuncValidator, FuncValidatorAllocations, ValidatorResources}; +#[cfg(feature = "validate")] +use crate::visit::process_operators_and_validate; +use crate::{Result, module::FunctionCode, visit::process_operators}; use alloc::{boxed::Box, format, string::ToString, vec::Vec}; use tinywasm_types::*; -use wasmparser::{ - CompositeInnerType, FuncValidator, FuncValidatorAllocations, OperatorsReader, OperatorsReaderAllocations, - ValidatorResources, -}; +use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations}; pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result { let kind = match element.kind { @@ -116,28 +116,48 @@ pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result, + count: u32, + ty: wasmparser::ValType, +) -> Result<()> { + let size = crate::visit::OperandSize::from(ty); + let count = + usize::try_from(count).map_err(|_| crate::ParseError::Other("local declaration count is too large".into()))?; + local_types.reserve(count); + local_types.extend(core::iter::repeat_n(size, count)); + Ok(()) +} + pub(crate) fn convert_module_code( func: wasmparser::FunctionBody<'_>, - mut validator: Option>, + validator: Option>, reader_allocs: OperatorsReaderAllocations, metadata: &crate::visit::ModuleMetadata, ty_idx: u32, ) -> Result<(FunctionCode, Option, OperatorsReaderAllocations)> { let locals_reader = func.get_locals_reader()?; - let pos = locals_reader.original_position(); + #[cfg(feature = "validate")] + let locals_position = locals_reader.original_position(); let signature = metadata.signature(ty_idx)?.clone(); let mut local_types = signature.params.clone(); - for (i, local) in locals_reader.into_iter().enumerate() { + #[cfg(feature = "validate")] + let mut validator = validator; + + #[cfg(feature = "validate")] + for (local_index, local) in locals_reader.into_iter().enumerate() { let local = local?; if let Some(validator) = validator.as_mut() { - validator.define_locals(pos + i, local.0, local.1)?; + validator.define_locals(locals_position + local_index, local.0, local.1)?; } - let size = crate::visit::OperandSize::from(local.1); - let count = usize::try_from(local.0) - .map_err(|_| crate::ParseError::Other("local declaration count is too large".into()))?; - local_types.reserve(count); - local_types.extend(core::iter::repeat_n(size, count)); + extend_local_types(&mut local_types, local.0, local.1)?; + } + + #[cfg(not(feature = "validate"))] + for local in locals_reader { + let local = local?; + extend_local_types(&mut local_types, local.0, local.1)?; } // maps a local's address to the index in the type's locals array @@ -154,8 +174,33 @@ pub(crate) fn convert_module_code( *count = count.checked_add(1).ok_or_else(|| crate::ParseError::Other(error.into()))?; } - let (body, data, validator_allocs, reader_allocs) = - process_operators_and_validate(validator, func, local_types, local_addr_map, metadata, ty_idx, reader_allocs)?; + #[cfg(feature = "validate")] + let (body, data, validator_allocs, reader_allocs) = match validator { + Some(validator) => { + let (body, data, validator_allocs, reader_allocs) = process_operators_and_validate( + validator, + func, + local_types, + local_addr_map, + metadata, + ty_idx, + reader_allocs, + )?; + (body, data, Some(validator_allocs), reader_allocs) + } + None => { + let (body, data, reader_allocs) = + process_operators(func, local_types, local_addr_map, metadata, ty_idx, reader_allocs)?; + (body, data, None, reader_allocs) + } + }; + #[cfg(not(feature = "validate"))] + let (body, data, validator_allocs, reader_allocs) = { + let _ = validator; + let (body, data, reader_allocs) = + process_operators(func, local_types, local_addr_map, metadata, ty_idx, reader_allocs)?; + (body, data, None, reader_allocs) + }; Ok(( FunctionCode { instructions: body, data, locals: local_counts, uses_local_memory: false }, validator_allocs, -- cgit v1.3.1 From d0c74255f9d6c57a243cf34037af0e8f371504b3 Mon Sep 17 00:00:00 2001 From: Henry Gressmann Date: Sat, 8 Aug 2026 15:43:26 +0200 Subject: feat: initial support for the webassembly gc proposal (#50) Signed-off-by: Henry --- CHANGELOG.md | 3 +- Cargo.lock | 32 +- Cargo.toml | 2 - README.md | 48 ++- crates/cli/src/wast_runner.rs | 55 ++- crates/parser/src/conversion.rs | 142 ++++++- crates/parser/src/lib.rs | 1 + crates/parser/src/macros.rs | 32 ++ crates/parser/src/module.rs | 43 +- crates/parser/src/optimize.rs | 1 + crates/parser/src/visit.rs | 184 +++++++- crates/tinywasm/Cargo.toml | 2 - crates/tinywasm/src/engine.rs | 10 + crates/tinywasm/src/error.rs | 25 ++ crates/tinywasm/src/func.rs | 64 ++- crates/tinywasm/src/imports.rs | 35 +- crates/tinywasm/src/instance.rs | 6 +- crates/tinywasm/src/interpreter/executor.rs | 332 ++++++++++++++- .../tinywasm/src/interpreter/stack/value_stack.rs | 28 +- crates/tinywasm/src/interpreter/values.rs | 54 ++- crates/tinywasm/src/reference.rs | 50 ++- crates/tinywasm/src/store/element.rs | 6 +- crates/tinywasm/src/store/function.rs | 8 + crates/tinywasm/src/store/gc/arena.rs | 263 ++++++++++++ crates/tinywasm/src/store/gc/mod.rs | 92 ++++ crates/tinywasm/src/store/gc/object.rs | 218 ++++++++++ crates/tinywasm/src/store/mod.rs | 470 +++++++++------------ crates/tinywasm/src/store/state.rs | 385 +++++++++++++++++ crates/tinywasm/src/store/table.rs | 104 +---- crates/tinywasm/src/store/types.rs | 204 +++++++++ crates/tinywasm/tests/gc_refs.rs | 120 ++++++ crates/tinywasm/tests/generated/wasm-2.csv | 2 +- crates/tinywasm/tests/generated/wasm-3.csv | 2 +- .../tests/generated/wasm-extended-const.csv | 2 +- .../tests/generated/wasm-function-references.csv | 2 +- crates/tinywasm/tests/generated/wasm-gc.csv | 1 + crates/tinywasm/tests/generated/wasm-latest.csv | 1 + crates/tinywasm/tests/generated/wasm-threads.csv | 1 + crates/tinywasm/tests/internal_refs.rs | 9 +- crates/types/src/archive.rs | 2 +- crates/types/src/instructions.rs | 37 ++ crates/types/src/lib.rs | 96 +---- crates/types/src/reference.rs | 109 +++-- crates/types/src/types.rs | 158 +++++++ crates/types/src/value.rs | 34 +- 45 files changed, 2770 insertions(+), 705 deletions(-) create mode 100644 crates/tinywasm/src/store/gc/arena.rs create mode 100644 crates/tinywasm/src/store/gc/mod.rs create mode 100644 crates/tinywasm/src/store/gc/object.rs create mode 100644 crates/tinywasm/src/store/state.rs create mode 100644 crates/tinywasm/src/store/types.rs create mode 100644 crates/tinywasm/tests/gc_refs.rs create mode 100644 crates/types/src/types.rs (limited to 'crates/parser/src/conversion.rs') diff --git a/CHANGELOG.md b/CHANGELOG.md index b58768f..38d4dd8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,12 +10,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Added support for the WebAssembly function-references proposal +- Added support for the WebAssembly garbage-collection proposal - Added `WasmValue::ty` and `WasmValue::matches_type` - Added a `validate` feature to `tinywasm` and `tinywasm-parser` (enabled by default) to optionally skip wasmparser validation for faster parsing of trusted modules. ### Changed -- Function types are now stored separately and resolved through `Function::ty(&Store)`. +- Module types now use one dense recursive type space, while function types are resolved through `Function::ty(&Store)`. ### Fixed diff --git a/Cargo.lock b/Cargo.lock index 680b8fb..df0e601 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,9 +4,9 @@ version = 4 [[package]] name = "aho-corasick" -version = "1.1.4" +version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" dependencies = [ "memchr", ] @@ -171,9 +171,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.6.5" +version = "4.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "301b56658598e48f3648647ac6fc887be7e7108eddfa4e9b63fcf3ec58c0cadf" +checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca" dependencies = [ "clap_builder", "clap_derive", @@ -181,9 +181,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.6.5" +version = "4.6.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94a65403d1a1bd28f7dc68eb8506e8874808ee5eecb59298de588e2e1407a078" +checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889" dependencies = [ "anstream", "anstyle", @@ -193,9 +193,9 @@ dependencies = [ [[package]] name = "clap_complete" -version = "4.6.8" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1f84a88507dbd05c695f2cb5e8558e747179134005e9893882dec964190ed89" +checksum = "3be2ad0423bdbbb0e25bc89add796f3559706d4a95e1bc98e4d9662a957b6a19" dependencies = [ "clap", ] @@ -690,9 +690,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.16" +version = "0.4.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fcfdb36bda0c880c5931cdc7a2bcdc8ba4556847b9d912bca70bc94708711ad" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" dependencies = [ "aho-corasick", "memchr", @@ -982,9 +982,9 @@ dependencies = [ [[package]] name = "wasm-testsuite" -version = "0.7.4" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fd62746cfcc437a1bdadbe75bf29df08d5a3ae67336e4ac6cea37e0194fce47" +checksum = "9d451d78ea8b19bbed461065802e8797edf21cfb6aa2e9cbeea0aede114f8fb4" dependencies = [ "include_dir", "wast", @@ -1071,18 +1071,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.55" +version = "0.8.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5a105cd7b140f6eeec8acff2ea38135d3cab283ada58540f629fe51e46696eb" +checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.55" +version = "0.8.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fe976fb70c78cd64cccfe3a6fc142244e8a77b70959b30faf9d0ac37ee228eb" +checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index e57b6ea..ca80b66 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,12 +21,10 @@ categories = ["compilers", "embedded", "no-std", "virtualization", "wasm"] [workspace.dependencies] tinywasm = { path = "crates/tinywasm", version = "0.11.0-pre.0", default-features = false } -tinywasm-cli = { path = "crates/cli", version = "0.11.0-pre.0", default-features = false } tinywasm-parser = { path = "crates/parser", version = "0.11.0-pre.0", default-features = false } tinywasm-types = { path = "crates/types", version = "0.11.0-pre.0", default-features = false } eyre = "0.6" -indexmap = "2.14" log = "0.4" owo-colors = { version = "4.3" } pretty_env_logger = "0.5" diff --git a/README.md b/README.md index 77aaf93..484dbaf 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ See the [examples](./examples) directory and [documentation](https://docs.rs/tin With default features disabled, `tinywasm` depends only on `core`, `alloc`, and `libm`[^libm], making it usable in `no_std + alloc` environments. -Use `Engine` and `engine::Config` when you need non-default runtime settings such as fuel accounting, stack sizing, memory backend selection, or trap-on-OOM behavior. +Use `Engine` and `engine::Config` when you need non-default runtime settings such as fuel accounting, stack sizing, memory backend selection, the GC collection threshold, or trap-on-OOM behavior. [^libm]: [rust-lang/rust#137578](https://github.com/rust-lang/rust/issues/137578) — tracking issue for floating-point math support in `no_std`. @@ -75,27 +75,31 @@ The internal `twasm` bytecode format is not currently validated as an untrusted ## Supported Proposals -| Proposal | Status | `tinywasm` Version | -| --------------------------------------------------------------------------------------------------------------------------------------- | ------ | ------------------ | -| [**Multi-value**](https://github.com/WebAssembly/spec/blob/master/proposals/multi-value/Overview.md) | 🟢 | 0.2.0 | -| [**Mutable Globals**](https://github.com/WebAssembly/mutable-global/blob/master/proposals/mutable-global/Overview.md) | 🟢 | 0.2.0 | -| [**Non-trapping float-to-int Conversion**](https://github.com/WebAssembly/nontrapping-float-to-int-conversions) | 🟢 | 0.2.0 | -| [**Sign-extension operators**](https://github.com/WebAssembly/sign-extension-ops) | 🟢 | 0.2.0 | -| [**Bulk Memory Operations**](https://github.com/WebAssembly/spec/blob/master/proposals/bulk-memory-operations/Overview.md) | 🟢 | 0.4.0 | -| [**Reference Types**](https://github.com/WebAssembly/reference-types/blob/master/proposals/reference-types/Overview.md) | 🟢 | 0.7.0 | -| [**Multi-memory**](https://github.com/WebAssembly/multi-memory/blob/master/proposals/multi-memory/Overview.md) | 🟢 | 0.8.0 | -| [**Custom Page Sizes**](https://github.com/WebAssembly/custom-page-sizes/blob/main/proposals/custom-page-sizes/Overview.md) | 🟢 | 0.9.0 | -| [**Extended Const**](https://github.com/WebAssembly/extended-const/blob/main/proposals/extended-const/Overview.md) | 🟢 | 0.9.0 | -| [**Fixed-Width SIMD**](https://github.com/WebAssembly/simd/blob/main/proposals/simd/Overview.md) | 🟢 | 0.9.0 | -| [**Memory64**](https://github.com/WebAssembly/memory64/blob/master/proposals/memory64/Overview.md) | 🟢 | 0.9.0 | -| [**Tail Call**](https://github.com/WebAssembly/tail-call/blob/main/proposals/tail-call/Overview.md) | 🟢 | 0.9.0 | -| [**Relaxed SIMD**](https://github.com/WebAssembly/relaxed-simd/blob/main/proposals/relaxed-simd/Overview.md) | 🟢 | 0.9.0 | -| [**Wide Arithmetic**](https://github.com/WebAssembly/wide-arithmetic/blob/main/proposals/wide-arithmetic/Overview.md) | 🟢 | 0.9.0 | -| [**Typed Function References**](https://github.com/WebAssembly/function-references/blob/main/proposals/function-references/Overview.md) | 🚧 | `next` | -| [**Exception Handling**](https://github.com/WebAssembly/exception-handling/blob/main/proposals/exception-handling/Exceptions.md) | 🌑 | - | -| [**Garbage Collection**](https://github.com/WebAssembly/gc/blob/main/proposals/gc/Overview.md) | 🌑 | - | -| [**Stack Switching**](https://github.com/WebAssembly/stack-switching/blob/main/proposals/stack-switching/Explainer.md) | 🌑 | - | -| [**Threads**](https://github.com/WebAssembly/threads/blob/main-legacy/proposals/threads/Overview.md) | 🌑 | - | +TinyWasm targets non-JavaScript core proposals through [phase 3](https://github.com/WebAssembly/proposals). JavaScript integrations and optional embedding or tooling APIs are not included here. + +| Proposal | Status | `tinywasm` Version | +| ---------------------------------------------------------------------------------------------------------------- | ------ | ------------------ | +| [**Import/Export of Mutable Globals**](https://github.com/WebAssembly/mutable-global) | 🟢 | 0.2.0 | +| [**Multi-value**](https://github.com/WebAssembly/multi-value) | 🟢 | 0.2.0 | +| [**Non-trapping Float-to-int Conversions**](https://github.com/WebAssembly/nontrapping-float-to-int-conversions) | 🟢 | 0.2.0 | +| [**Sign-extension Operators**](https://github.com/WebAssembly/sign-extension-ops) | 🟢 | 0.2.0 | +| [**Bulk Memory Operations**](https://github.com/WebAssembly/bulk-memory-operations) | 🟢 | 0.4.0 | +| [**Reference Types**](https://github.com/WebAssembly/reference-types) | 🟢 | 0.7.0 | +| [**Fixed-width SIMD**](https://github.com/WebAssembly/simd) | 🟢 | 0.9.0 | +| [**Tail Calls**](https://github.com/WebAssembly/tail-call) | 🟢 | 0.9.0 | +| [**Extended Constant Expressions**](https://github.com/WebAssembly/extended-const) | 🟢 | 0.9.0 | +| [**Multiple Memories**](https://github.com/WebAssembly/multi-memory) | 🟢 | 0.8.0 | +| [**Relaxed SIMD**](https://github.com/WebAssembly/relaxed-simd) | 🟢 | 0.9.0 | +| [**Custom Annotation Syntax**](https://github.com/WebAssembly/annotations) | 🟢 | 0.8.0 | +| [**Memory64**](https://github.com/WebAssembly/memory64) | 🟢 | 0.9.0 | +| [**Wide Arithmetic**](https://github.com/WebAssembly/wide-arithmetic) | 🟢 | 0.9.0 | +| [**Custom Page Sizes**](https://github.com/WebAssembly/custom-page-sizes) | 🟢 | 0.9.0 | +| [**Typed Function References**](https://github.com/WebAssembly/function-references) | 🟢 | `next` | +| [**Garbage Collection**](https://github.com/WebAssembly/gc) | 🟢 | `next` | +| [**Exception Handling**](https://github.com/WebAssembly/exception-handling) | 🌑 | - | +| [**Stack Switching**](https://github.com/WebAssembly/stack-switching) | 🌑 | - | +| [**Compact Import Section**](https://github.com/WebAssembly/compact-import-section) | 🌑 | - | +| [**Threads**](https://github.com/WebAssembly/threads) | 🌑 | - | **Legend**\ 🌑 -- not available\ diff --git a/crates/cli/src/wast_runner.rs b/crates/cli/src/wast_runner.rs index c773663..ad1742e 100644 --- a/crates/cli/src/wast_runner.rs +++ b/crates/cli/src/wast_runner.rs @@ -7,7 +7,10 @@ use std::time::Duration; use eyre::{Context, Result, bail, eyre}; use log::{debug, error}; -use tinywasm::types::{ExternRef, FuncRef, MemoryType, RefType, RefValue, TableType, WasmType, WasmValue}; +use tinywasm::types::{ + AbstractHeapType as TinyAbstractHeapType, AnyRef, ExternRef, FuncRef, MemoryType, RefType, RefValue, TableType, + WasmType, WasmValue, +}; use tinywasm::{ExecProgress, Global, HostFunction, Imports, Memory, Module, ModuleInstance, Store, Table}; use wast::{QuoteWat, core::AbstractHeapType}; @@ -459,7 +462,7 @@ impl WastRunner { let expected = expected_alternatives .iter() .filter_map(|alts| alts.first()) - .find(|exp| exp.matches(&module_global)); + .find(|exp| exp.matches(&module_global, &store)); if expected.is_none() { test_group.add_result( &format!("AssertReturn(unsupported-{i})"), @@ -508,7 +511,10 @@ impl WastRunner { } if expected_alternatives.iter().any(|expected| { expected.len() == outcomes.len() - && outcomes.iter().zip(expected.iter()).all(|(outcome, exp)| exp.matches(outcome)) + && outcomes + .iter() + .zip(expected.iter()) + .all(|(outcome, exp)| exp.matches(outcome, &store)) }) { Ok(()) } else { @@ -755,16 +761,18 @@ fn wastarg2tinywasmvalue(arg: wast::WastArg) -> Result { I32(i) => WasmValue::I32(i), I64(i) => WasmValue::I64(i), V128(i) => WasmValue::V128(i.to_le_bytes()), - RefExtern(v) => ExternRef::new(v).into(), + RefExtern(v) => ExternRef::try_new(v).ok_or_else(|| eyre!("external reference address is too large"))?.into(), RefNull(t) => match t { wast::core::HeapType::Abstract { shared: false, ty: AbstractHeapType::Func } => RefValue::Null.into(), - wast::core::HeapType::Abstract { shared: false, ty: AbstractHeapType::Extern } => RefValue::Null.into(), + wast::core::HeapType::Abstract { shared: false, ty: AbstractHeapType::Extern | AbstractHeapType::Any } => { + RefValue::Null.into() + } _ => { bail!("unsupported arg type: refnull: {:?}", t); } }, - RefHost(_) => { - bail!("unsupported arg type: RefHost"); + RefHost(value) => { + RefValue::Any(AnyRef::from_host(value).ok_or_else(|| eyre!("host reference address is too large"))?).into() } }) } @@ -791,15 +799,29 @@ enum ExpectedValue { RefNull, RefFunc, RefExtern, + RefAny, + RefEq, + RefI31, + RefStruct, + RefArray, } impl ExpectedValue { - fn matches(&self, value: &WasmValue) -> bool { + fn matches(&self, value: &WasmValue, store: &Store) -> bool { match self { Self::Exact(expected) => value.eq_loose(expected), Self::RefNull => matches!(value, WasmValue::Ref(RefValue::Null)), Self::RefFunc => matches!(value, WasmValue::Ref(RefValue::Func(_))), Self::RefExtern => matches!(value, WasmValue::Ref(RefValue::Extern(_))), + Self::RefAny => matches!(value, WasmValue::Ref(RefValue::Any(_))), + Self::RefEq => { + store.value_matches_type(*value, WasmType::Ref(RefType::new_abstract(false, TinyAbstractHeapType::Eq))) + } + Self::RefI31 => matches!(value, WasmValue::Ref(RefValue::Any(value)) if value.as_i31().is_some()), + Self::RefStruct => store + .value_matches_type(*value, WasmType::Ref(RefType::new_abstract(false, TinyAbstractHeapType::Struct))), + Self::RefArray => store + .value_matches_type(*value, WasmType::Ref(RefType::new_abstract(false, TinyAbstractHeapType::Array))), } } } @@ -817,7 +839,10 @@ fn wastret2tinywasmvalues(ret: wast::WastRet) -> Result> { } fn wastretcore2tinywasmvalue(ret: wast::core::WastRetCore) -> Result { - use wast::core::WastRetCore::{F32, F64, I32, I64, RefExtern, RefFunc, RefNull, V128}; + use wast::core::WastRetCore::{ + F32, F64, I32, I64, RefAny, RefArray, RefEq, RefExtern, RefFunc, RefHost, RefI31, RefI31Shared, RefNull, + RefStruct, V128, + }; Ok(match ret { F32(f) => ExpectedValue::Exact(nanpattern2tinywasmvalue(f)?), F64(f) => ExpectedValue::Exact(nanpattern2tinywasmvalue(f)?), @@ -825,13 +850,23 @@ fn wastretcore2tinywasmvalue(ret: wast::core::WastRetCore) -> Result ExpectedValue::Exact(WasmValue::I64(i)), V128(i) => ExpectedValue::Exact(WasmValue::V128(wast_v128_to_bytes(i))), RefNull(_) => ExpectedValue::RefNull, - RefExtern(Some(v)) => ExpectedValue::Exact(ExternRef::new(v).into()), + RefExtern(Some(v)) => ExpectedValue::Exact( + ExternRef::try_new(v).ok_or_else(|| eyre!("external reference address is too large"))?.into(), + ), RefExtern(None) => ExpectedValue::RefExtern, RefFunc(Some(wast::token::Index::Num(n, _))) => ExpectedValue::Exact(FuncRef::new(n).into()), RefFunc(None) => ExpectedValue::RefFunc, RefFunc(v) => { bail!("unsupported arg type: reffunc: {:?}", v); } + RefAny => ExpectedValue::RefAny, + RefEq => ExpectedValue::RefEq, + RefI31 | RefI31Shared => ExpectedValue::RefI31, + RefStruct => ExpectedValue::RefStruct, + RefArray => ExpectedValue::RefArray, + RefHost(value) => ExpectedValue::Exact( + RefValue::Any(AnyRef::from_host(value).ok_or_else(|| eyre!("host reference address is too large"))?).into(), + ), a => { bail!("unsupported arg type {:?}", a); } diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 600976a..8bc7df1 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -2,9 +2,9 @@ use crate::validation::{FuncValidator, FuncValidatorAllocations, ValidatorResour #[cfg(feature = "validate")] use crate::visit::process_operators_and_validate; use crate::{Result, module::FunctionCode, visit::process_operators}; -use alloc::{boxed::Box, format, string::ToString, vec::Vec}; +use alloc::{boxed::Box, format, vec::Vec}; use tinywasm_types::*; -use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations}; +use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations, UnpackedIndex}; pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result { let kind = match element.kind { @@ -208,25 +208,77 @@ pub(crate) fn convert_module_code( )) } -pub(crate) fn convert_module_type(ty: wasmparser::RecGroup) -> Result { - let mut types = ty.types(); - // TODO(wasm3): Preserve recursive groups and non-function composite types instead of flattening singleton funcs. - if types.len() != 1 { - return Err(crate::ParseError::UnsupportedOperator( - "Expected exactly one type in the type section".to_string(), - )); +pub(crate) fn convert_rec_group(ty: wasmparser::RecGroup, group_start: u32, types: &mut Vec) -> Result { + let group_len = u32::try_from(ty.types().len()) + .map_err(|_| crate::ParseError::Other("recursive type group is too large".into()))?; + types.reserve(group_len as usize); + for ty in ty.into_types() { + let composite = &ty.composite_type; + if composite.shared { + return Err(crate::ParseError::UnsupportedOperator("shared composite types are unsupported".into())); + } + if composite.descriptor_idx.is_some() || composite.describes_idx.is_some() { + return Err(crate::ParseError::UnsupportedOperator("descriptor types are unsupported".into())); + } + + let supertype = + ty.supertype_idx.map(|idx| convert_type_index(idx.unpack(), group_start, group_len)).transpose()?; + let composite = match &composite.inner { + CompositeInnerType::Func(ty) => { + let params = ty + .params() + .iter() + .map(|ty| convert_valtype_in_group(ty, group_start, group_len)) + .collect::>>()?; + let results = ty + .results() + .iter() + .map(|ty| convert_valtype_in_group(ty, group_start, group_len)) + .collect::>>()?; + CompositeType::Func(FuncType::new(¶ms, &results)) + } + CompositeInnerType::Struct(ty) => CompositeType::Struct(StructType { + fields: ty + .fields + .iter() + .map(|field| convert_field_type(field, group_start, group_len)) + .collect::>()?, + }), + CompositeInnerType::Array(ty) => { + CompositeType::Array(ArrayType { field: convert_field_type(&ty.0, group_start, group_len)? }) + } + CompositeInnerType::Cont(_) => { + return Err(crate::ParseError::UnsupportedOperator("continuation types are unsupported".into())); + } + }; + types.push(SubType { is_final: ty.is_final, supertype, composite }); + } + Ok(group_len) +} + +fn convert_type_index(index: UnpackedIndex, group_start: u32, group_len: u32) -> Result { + match index { + UnpackedIndex::Module(index) => Ok(index), + UnpackedIndex::RecGroup(index) if index < group_len => { + group_start.checked_add(index).ok_or_else(|| crate::ParseError::Other("type index is too large".into())) + } + UnpackedIndex::RecGroup(index) => { + Err(crate::ParseError::Other(format!("recursive group type index out of bounds: {index}"))) + } + #[cfg(feature = "validate")] + UnpackedIndex::Id(_) => { + Err(crate::ParseError::UnsupportedOperator(format!("unsupported canonical type index: {index}"))) + } } +} - let ty = types.next().unwrap(); - let CompositeInnerType::Func(ty) = &ty.composite_type.inner else { - return Err(crate::ParseError::UnsupportedOperator(format!( - "Unsupported non-function type in type section: {}", - ty.composite_type - ))); +fn convert_field_type(field: &wasmparser::FieldType, group_start: u32, group_len: u32) -> Result { + let storage = match &field.element_type { + wasmparser::StorageType::I8 => StorageType::I8, + wasmparser::StorageType::I16 => StorageType::I16, + wasmparser::StorageType::Val(ty) => StorageType::Value(convert_valtype_in_group(ty, group_start, group_len)?), }; - let params = ty.params().iter().map(convert_valtype).collect::>>()?; - let results = ty.results().iter().map(convert_valtype).collect::>>()?; - Ok(FuncType::new(¶ms, &results)) + Ok(FieldType { storage, mutable: field.mutable }) } pub(crate) fn convert_ref_type(ty: wasmparser::RefType) -> Result { @@ -234,13 +286,23 @@ pub(crate) fn convert_ref_type(ty: wasmparser::RefType) -> Result { } pub(crate) fn convert_valtype(valtype: &wasmparser::ValType) -> Result { + convert_valtype_with_group(valtype, None) +} + +fn convert_valtype_in_group(valtype: &wasmparser::ValType, group_start: u32, group_len: u32) -> Result { + convert_valtype_with_group(valtype, Some((group_start, group_len))) +} + +fn convert_valtype_with_group(valtype: &wasmparser::ValType, group: Option<(u32, u32)>) -> Result { match valtype { wasmparser::ValType::I32 => Ok(WasmType::I32), wasmparser::ValType::I64 => Ok(WasmType::I64), wasmparser::ValType::F32 => Ok(WasmType::F32), wasmparser::ValType::F64 => Ok(WasmType::F64), wasmparser::ValType::V128 => Ok(WasmType::V128), - wasmparser::ValType::Ref(r) => Ok(WasmType::Ref(convert_ref_type(*r)?)), + wasmparser::ValType::Ref(r) => { + Ok(WasmType::Ref(convert_heap_type_with_group(r.heap_type(), r.is_nullable(), group)?)) + } } } @@ -265,6 +327,20 @@ pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result { ConstInstruction::Ref(RefValue::Func(FuncRef::new(function_index))) } + wasmparser::Operator::RefI31 => ConstInstruction::RefI31, + wasmparser::Operator::AnyConvertExtern => ConstInstruction::AnyConvertExtern, + wasmparser::Operator::ExternConvertAny => ConstInstruction::ExternConvertAny, + wasmparser::Operator::StructNew { struct_type_index } => ConstInstruction::StructNew(struct_type_index), + wasmparser::Operator::StructNewDefault { struct_type_index } => { + ConstInstruction::StructNewDefault(struct_type_index) + } + wasmparser::Operator::ArrayNew { array_type_index } => ConstInstruction::ArrayNew(array_type_index), + wasmparser::Operator::ArrayNewDefault { array_type_index } => { + ConstInstruction::ArrayNewDefault(array_type_index) + } + wasmparser::Operator::ArrayNewFixed { array_type_index, array_size } => { + ConstInstruction::ArrayNewFixed(array_type_index, array_size) + } wasmparser::Operator::I32Const { value } => ConstInstruction::I32Const(value), wasmparser::Operator::I64Const { value } => ConstInstruction::I64Const(value), wasmparser::Operator::F32Const { value } => ConstInstruction::F32Const(f32::from_bits(value.bits())), @@ -294,6 +370,14 @@ pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result Result { + convert_heap_type_with_group(heap, nullable, None) +} + +fn convert_heap_type_with_group( + heap: wasmparser::HeapType, + nullable: bool, + group: Option<(u32, u32)>, +) -> Result { match heap { wasmparser::HeapType::Abstract { shared: false, ty } => Ok(RefType::new_abstract( nullable, @@ -316,9 +400,23 @@ pub(crate) fn convert_heap_type(heap: wasmparser::HeapType, nullable: bool) -> R }, )), wasmparser::HeapType::Concrete(index) => { - let index = index.as_module_index().ok_or_else(|| { - crate::ParseError::UnsupportedOperator(format!("Unsupported non-module heap type index: {index:?}")) - })?; + let index = match index { + UnpackedIndex::Module(index) => index, + index @ UnpackedIndex::RecGroup(_) => { + let (group_start, group_len) = group.ok_or_else(|| { + crate::ParseError::UnsupportedOperator(format!( + "recursive-group heap type outside a type group: {index}" + )) + })?; + convert_type_index(index, group_start, group_len)? + } + #[cfg(feature = "validate")] + index @ UnpackedIndex::Id(_) => { + return Err(crate::ParseError::UnsupportedOperator(format!( + "unsupported canonical heap type index: {index}" + ))); + } + }; RefType::new_concrete(nullable, index) .ok_or_else(|| crate::ParseError::Other(format!("heap type index is too large: {index}"))) } diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs index 6efc112..5439558 100644 --- a/crates/parser/src/lib.rs +++ b/crates/parser/src/lib.rs @@ -174,6 +174,7 @@ impl Parser { | WasmFeatures::BULK_MEMORY_OPT | WasmFeatures::RELAXED_SIMD | WasmFeatures::GC_TYPES + | WasmFeatures::GC | WasmFeatures::REFERENCE_TYPES | WasmFeatures::MUTABLE_GLOBAL | WasmFeatures::MULTI_VALUE diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs index 4ce23bb..553f439 100644 --- a/crates/parser/src/macros.rs +++ b/crates/parser/src/macros.rs @@ -37,6 +37,27 @@ pub(crate) mod visit { $(lowering_ops!(@effect $inputs => $outputs $visit);)* lowering_ops!($($rest)*); }; + (unsupported $args:tt { $($visit:ident),* $(,)? } $($rest:tt)*) => { + $(lowering_ops!(@unsupported $args $visit);)* + lowering_ops!($($rest)*); + }; + (heap $nullable:literal $inputs:tt => $outputs:tt { + $($visit:ident => $instr:ident),* $(,)? + } $($rest:tt)*) => { + $( + fn $visit(&mut self, heap_type: wasmparser::HeapType) -> Self::Output { + let ty = convert_heap_type(heap_type, $nullable)?; + lowering_ops!(@emit self fixed $inputs => $outputs Instruction::$instr(ty)) + } + )* + lowering_ops!($($rest)*); + }; + + (@unsupported [$($argty:ty),*] $visit:ident) => { + fn $visit(&mut self $(, _: $argty)*) -> Self::Output { + Err(crate::ParseError::UnsupportedOperator(stringify!($visit).to_string())) + } + }; (@fixed [$($input:ident),*] => [$($output:ident),*] $visit:ident $(($($arg:ident: $ty:ty),+))? => $instr:ident @@ -64,6 +85,15 @@ pub(crate) mod visit { (@table $inputs:tt => $outputs:tt $($operator:tt)*) => { lowering_ops!(@resolved table_size $inputs => $outputs $($operator)*); }; + (@array_field [$($input:ident),*] => [$($output:ident),*] + $visit:ident($type_index:ident: $type_ty:ty $(, $arg:ident: $arg_ty:ty)*) => $instr:ident + ) => { + fn $visit(&mut self, $type_index: $type_ty $(, $arg: $arg_ty)*) -> Self::Output { + let size = ModuleMetadata::storage_size(self.metadata.array_field($type_index)?.storage); + lowering_ops!(@emit self address(size) [$($input),*] => [$($output),*] + Instruction::$instr($type_index $(, $arg)*).into()) + } + }; (@resolved $resolver:ident [$($input:ident),*] => [$($output:ident),*] $visit:ident($index:ident: $ty:ty) => $instr:ident ) => { @@ -110,6 +140,7 @@ pub(crate) mod visit { }; (@size Addr, $address:ident) => { $address }; + (@size Field, $address:ident) => { $address }; (@size $size:ident $(, $address:ident)?) => { OperandSize::$size }; } @@ -128,6 +159,7 @@ pub(crate) mod visit { (@@relaxed_simd $($rest:tt)* ) => {}; (@@tail_call $($rest:tt)* ) => {}; (@@function_references $($rest:tt)* ) => {}; + (@@gc $($rest:tt)* ) => {}; (@@$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*)) => { fn $visit(&mut self $($(,_: $argty)*)?) -> Self::Output { diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index a269141..237478c 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -44,11 +44,12 @@ pub(crate) struct ModuleReader<'a> { translation_metadata: Option>, has_code_section: bool, + has_type_section: bool, marker: PhantomData<&'a [u8]>, pub(crate) version: Option, pub(crate) start_func: Option, - pub(crate) func_types: Box<[FuncType]>, + pub(crate) types: TypeSection, pub(crate) code_type_addrs: Box<[u32]>, code_results: Box<[ValueCounts]>, pub(crate) exports: Arc<[Export]>, @@ -71,7 +72,7 @@ impl<'a> ModuleReader<'a> { fn translation_metadata(&mut self) -> &crate::visit::ModuleMetadata { if self.translation_metadata.is_none() { self.translation_metadata = Some(Arc::new(crate::visit::ModuleMetadata::new( - &self.func_types, + &self.types, &self.code_type_addrs, &self.imports, &self.globals, @@ -119,12 +120,25 @@ impl<'a> ModuleReader<'a> { self.start_func = Some(func); } Payload::TypeSection(reader) => { - check_section("type", !self.func_types.is_empty())?; + check_section("type", self.has_type_section)?; + self.has_type_section = true; #[cfg(feature = "validate")] if let Some(validator) = validator.as_mut() { validator.type_section(&reader)?; } - self.func_types = reader.into_iter().map(|t| convert_module_type(t?)).collect::>()?; + let mut types = Vec::with_capacity(reader.count() as usize); + let mut rec_group_lengths = Vec::with_capacity(reader.count() as usize); + for group in reader { + let group = group?; + let group_start = u32::try_from(types.len()) + .map_err(|_| ParseError::Other("type section is too large".into()))?; + let group_len = convert_rec_group(group, group_start, &mut types)?; + rec_group_lengths.push(group_len); + } + self.types = TypeSection { + types: types.into_boxed_slice(), + rec_group_lengths: rec_group_lengths.into_boxed_slice(), + }; } Payload::GlobalSection(reader) => { check_section("global", !self.globals.is_empty())?; @@ -207,10 +221,9 @@ impl<'a> ModuleReader<'a> { let mut results = Vec::with_capacity(reader.count() as usize); for ty_idx in reader { let ty_idx = ty_idx?; - let ty = self - .func_types - .get(ty_idx as usize) - .ok_or_else(|| ParseError::Other(format!("function type index out of bounds: {ty_idx}")))?; + let ty = self.types.get(ty_idx).and_then(SubType::as_func).ok_or_else(|| { + ParseError::Other(format!("function type index does not reference a function: {ty_idx}")) + })?; type_addrs.push(ty_idx); results.push(ValueCounts::from_iter(ty.results())); } @@ -227,7 +240,14 @@ impl<'a> ModuleReader<'a> { for import in reader.into_imports() { let import = convert_module_import(import?)?; match import.kind { - ImportKind::Function(_) => self.imported_func_count += 1, + ImportKind::Function(type_idx) => { + if self.types.get(type_idx).and_then(SubType::as_func).is_none() { + return Err(ParseError::Other(format!( + "function import type index does not reference a function: {type_idx}" + ))); + } + self.imported_func_count += 1; + } ImportKind::Memory(_) => self.imported_memory_count += 1, _ => {} } @@ -504,7 +524,8 @@ impl<'a> ModuleReader<'a> { .zip(self.code_type_addrs) .zip(self.code_results) .map(|((code, ty_idx), results)| { - let ty = self.func_types.get(ty_idx as usize).expect("function type was checked while parsing").clone(); + let ty = + self.types.get(ty_idx).and_then(SubType::as_func).expect("function type was checked while parsing"); let params = ValueCounts::from_iter(ty.params()); if code.uses_local_memory { local_memory_allocation = LocalMemoryAllocation::Eager; @@ -522,7 +543,7 @@ impl<'a> ModuleReader<'a> { Ok(ModuleInner { funcs, - func_types: self.func_types, + types: self.types, func_type_idxs, globals: self.globals, tables: self.tables, diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs index dcb7568..5c2d7d5 100644 --- a/crates/parser/src/optimize.rs +++ b/crates/parser/src/optimize.rs @@ -858,6 +858,7 @@ fn instruction_target_mut(instr: &mut Instruction) -> Option<&mut u32> { | Instruction::JumpIfNonZero64(ip) | Instruction::JumpIfRefNull(ip) | Instruction::JumpIfRefNonNull(ip) + | Instruction::BrOnCast(ip, _, _) | Instruction::JumpCmpStackConst32 { target_ip: ip, .. } | Instruction::JumpCmpStackConst64 { target_ip: ip, .. } | Instruction::JumpIfLocalZero32 { target_ip: ip, .. } diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index 67651f9..4437242 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -2,8 +2,8 @@ use crate::{Result, conversion::convert_heap_type, macros::visit::*}; use alloc::string::ToString; use alloc::vec::Vec; use tinywasm_types::{ - FuncType, Global, Import, ImportKind, Instruction, MemoryArch, MemoryArg, MemoryType, TableDefinition, ValueCounts, - WasmFunctionData, WasmType, + Global, Import, ImportKind, Instruction, MemoryArch, MemoryArg, MemoryType, StorageType, SubType, TableDefinition, + TypeSection, ValueCounts, WasmFunctionData, WasmType, }; use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator}; @@ -85,11 +85,12 @@ pub(crate) struct Signature { } pub(crate) struct ModuleMetadata { - signatures: Vec, + signatures: Vec>, functions: Vec, globals: Vec, memories: Vec, tables: Vec, + types: Vec, } #[derive(Default)] @@ -140,6 +141,16 @@ impl<'a> FunctionBuilder<'a> { lane_counts: ValueCounts::default(), } } + + fn visit_struct_get_impl( + &mut self, + type_index: u32, + field_index: u32, + instruction: fn(u32, u32) -> Instruction, + ) -> Result<()> { + let size = ModuleMetadata::storage_size(self.metadata.struct_field(type_index, field_index)?.storage); + self.emit(&[OperandSize::S32], &[size], instruction(type_index, field_index)) + } } #[cfg(feature = "validate")] @@ -151,7 +162,7 @@ struct ValidateThenVisit<'a, 'm> { impl ModuleMetadata { pub(crate) fn new( - types: &[FuncType], + types: &TypeSection, code_type_addrs: &[u32], imports: &[Import], globals: &[Global], @@ -178,19 +189,30 @@ impl ModuleMetadata { table_sizes.extend(tables.iter().map(|table| OperandSize::from(table.ty.arch()))); let signatures = types + .types .iter() - .map(|ty| Signature { - params: ty.params().iter().map(OperandSize::from).collect(), - results: ty.results().iter().map(OperandSize::from).collect(), + .map(|ty| { + ty.as_func().map(|ty| Signature { + params: ty.params().iter().map(OperandSize::from).collect(), + results: ty.results().iter().map(OperandSize::from).collect(), + }) }) .collect(); - Self { signatures, functions, globals: global_sizes, memories: memory_sizes, tables: table_sizes } + Self { + signatures, + functions, + globals: global_sizes, + memories: memory_sizes, + tables: table_sizes, + types: types.types.to_vec(), + } } pub(crate) fn signature(&self, idx: u32) -> Result<&Signature> { self.signatures .get(idx as usize) - .ok_or_else(|| crate::ParseError::Other(alloc::format!("type index out of bounds: {idx}"))) + .and_then(Option::as_ref) + .ok_or_else(|| crate::ParseError::Other(alloc::format!("type index is not a function type: {idx}"))) } fn function_signature(&self, idx: u32) -> Result<&Signature> { @@ -219,6 +241,36 @@ impl ModuleMetadata { .copied() .ok_or_else(|| crate::ParseError::Other(alloc::format!("{entity} index out of bounds: {idx}"))) } + + fn storage_size(storage: StorageType) -> OperandSize { + match storage { + StorageType::I8 | StorageType::I16 => OperandSize::S32, + StorageType::Value(ref ty) => OperandSize::from(ty), + } + } + + fn struct_fields(&self, idx: u32) -> Result<&[tinywasm_types::FieldType]> { + self.types + .get(idx as usize) + .and_then(SubType::as_struct) + .map(|ty| ty.fields.as_ref()) + .ok_or_else(|| crate::ParseError::Other(alloc::format!("type index is not a struct type: {idx}"))) + } + + fn struct_field(&self, type_index: u32, field_index: u32) -> Result { + self.struct_fields(type_index)? + .get(field_index as usize) + .copied() + .ok_or_else(|| crate::ParseError::Other("struct field index out of bounds".into())) + } + + fn array_field(&self, idx: u32) -> Result { + self.types + .get(idx as usize) + .and_then(SubType::as_array) + .map(|ty| ty.field) + .ok_or_else(|| crate::ParseError::Other(alloc::format!("type index is not an array type: {idx}"))) + } } #[cfg(feature = "validate")] @@ -339,8 +391,17 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fixed [] => [] { visit_data_drop(segment: u32) => DataDrop, visit_elem_drop(segment: u32) => ElemDrop } fixed [] => [S32] { visit_i32_const(value: i32) => Const32, visit_ref_func(function: u32) => RefFunc } fixed [] => [S64] { visit_i64_const(value: i64) => Const64 } + heap false [] => [S32] { visit_ref_null => RefNull } + heap false [S32] => [S32] { + visit_ref_test_non_null => RefTest, visit_ref_cast_non_null => RefCast, + } + heap true [S32] => [S32] { + visit_ref_test_nullable => RefTest, visit_ref_cast_nullable => RefCast, + } fixed [S32] => [S32] { - visit_i32_eqz => I32Eqz, visit_ref_is_null => RefIsNull, visit_i32_clz => I32Clz, + visit_ref_is_null => RefIsNull, visit_ref_as_non_null => RefAsNonNull, visit_ref_i31 => RefI31, + visit_i31_get_s => I31GetS, visit_i31_get_u => I31GetU, + visit_i32_eqz => I32Eqz, visit_i32_clz => I32Clz, visit_i32_ctz => I32Ctz, visit_i32_popcnt => I32Popcnt, visit_i32_extend8_s => I32Extend8S, visit_i32_extend16_s => I32Extend16S, visit_i32_trunc_f32_s => I32TruncF32S, visit_i32_trunc_f32_u => I32TruncF32U, visit_f32_convert_i32_s => F32ConvertI32S, @@ -349,6 +410,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { visit_f32_ceil => F32Ceil, visit_f32_floor => F32Floor, visit_f32_trunc => F32Trunc, visit_f32_nearest => F32Nearest, visit_f32_sqrt => F32Sqrt, } + effect [S32] => [S32] { visit_any_convert_extern, visit_extern_convert_any } fixed [S64] => [S64] { visit_i64_clz => I64Clz, visit_i64_ctz => I64Ctz, visit_i64_popcnt => I64Popcnt, visit_i64_extend8_s => I64Extend8S, visit_i64_extend16_s => I64Extend16S, @@ -373,7 +435,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { visit_i64_trunc_sat_f32_u => I64TruncSatF32U, } fixed [S32, S32] => [S32] { - visit_i32_eq => I32Eq, visit_i32_ne => I32Ne, visit_i32_lt_s => I32LtS, visit_i32_lt_u => I32LtU, + visit_ref_eq => RefEq, visit_i32_eq => I32Eq, visit_i32_ne => I32Ne, + visit_i32_lt_s => I32LtS, visit_i32_lt_u => I32LtU, visit_i32_gt_s => I32GtS, visit_i32_gt_u => I32GtU, visit_i32_le_s => I32LeS, visit_i32_le_u => I32LeU, visit_i32_ge_s => I32GeS, visit_i32_ge_u => I32GeU, visit_f32_eq => F32Eq, visit_f32_ne => F32Ne, visit_f32_lt => F32Lt, visit_f32_gt => F32Gt, @@ -420,6 +483,65 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { table [S32, Addr] => [Addr] { visit_table_grow(table: u32) => TableGrow } table [Addr, S32, Addr] => [] { visit_table_fill(table: u32) => TableFill } table [Addr, S32, S32] => [] { visit_table_init(elem_index: u32, table: u32) => TableInit } + fixed [] => [S32] { visit_struct_new_default(type_index: u32) => StructNewDefault } + fixed [S32] => [S32] { + visit_array_new_default(type_index: u32) => ArrayNewDefault, visit_array_len => ArrayLen, + } + fixed [S32, S32] => [S32] { + visit_array_new_data(type_index: u32, data_index: u32) => ArrayNewData, + visit_array_new_elem(type_index: u32, elem_index: u32) => ArrayNewElem, + } + fixed [S32, S32, S32, S32] => [] { + visit_array_init_data(type_index: u32, data_index: u32) => ArrayInitData, + visit_array_init_elem(type_index: u32, elem_index: u32) => ArrayInitElem, + } + fixed [S32, S32, S32, S32, S32] => [] { + visit_array_copy(type_index_dst: u32, type_index_src: u32) => ArrayCopy, + } + array_field [Field, S32] => [S32] { visit_array_new(type_index: u32) => ArrayNew } + array_field [S32, S32] => [Field] { + visit_array_get(type_index: u32) => ArrayGet, visit_array_get_s(type_index: u32) => ArrayGetS, + visit_array_get_u(type_index: u32) => ArrayGetU, + } + array_field [S32, S32, Field] => [] { visit_array_set(type_index: u32) => ArraySet } + array_field [S32, S32, Field, S32] => [] { visit_array_fill(type_index: u32) => ArrayFill } + } + + fn visit_struct_new(&mut self, type_index: u32) -> Self::Output { + let inputs = self + .metadata + .struct_fields(type_index)? + .iter() + .map(|field| ModuleMetadata::storage_size(field.storage)) + .collect::>(); + self.emit(&inputs, &[OperandSize::S32], Instruction::StructNew(type_index)) + } + + fn visit_struct_get(&mut self, type_index: u32, field_index: u32) -> Self::Output { + self.visit_struct_get_impl(type_index, field_index, Instruction::StructGet) + } + + fn visit_struct_get_s(&mut self, type_index: u32, field_index: u32) -> Self::Output { + self.visit_struct_get_impl(type_index, field_index, Instruction::StructGetS) + } + + fn visit_struct_get_u(&mut self, type_index: u32, field_index: u32) -> Self::Output { + self.visit_struct_get_impl(type_index, field_index, Instruction::StructGetU) + } + + fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Self::Output { + let size = ModuleMetadata::storage_size(self.metadata.struct_field(type_index, field_index)?.storage); + self.emit(&[OperandSize::S32, size], &[], Instruction::StructSet(type_index, field_index)) + } + + fn visit_array_new_fixed(&mut self, type_index: u32, array_size: u32) -> Self::Output { + let size = ModuleMetadata::storage_size(self.metadata.array_field(type_index)?.storage); + for _ in 0..array_size { + self.pop_expect(size)?; + } + self.push_sizes(&[OperandSize::S32])?; + self.instructions.push(Instruction::ArrayNewFixed(type_index, array_size)); + Ok(()) } fn visit_call(&mut self, function_index: u32) -> Self::Output { @@ -718,14 +840,22 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { self.emit(&[dst, src, len], &[], Instruction::MemoryCopy { dst_mem, src_mem }) } - // Reference Types - fn visit_ref_null(&mut self, ty: wasmparser::HeapType) -> Self::Output { - let instruction = Instruction::RefNull(convert_heap_type(ty, false)?); - self.emit(&[], &[OperandSize::S32], instruction) + fn visit_br_on_cast( + &mut self, + relative_depth: u32, + _from_ref_type: wasmparser::RefType, + to_ref_type: wasmparser::RefType, + ) -> Self::Output { + self.emit_cast_branch(relative_depth, to_ref_type, false) } - fn visit_ref_as_non_null(&mut self) -> Self::Output { - self.emit(&[OperandSize::S32], &[OperandSize::S32], Instruction::RefAsNonNull) + fn visit_br_on_cast_fail( + &mut self, + relative_depth: u32, + _from_ref_type: wasmparser::RefType, + to_ref_type: wasmparser::RefType, + ) -> Self::Output { + self.emit_cast_branch(relative_depth, to_ref_type, true) } fn visit_br_on_null(&mut self, relative_depth: u32) -> Self::Output { @@ -971,6 +1101,23 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { } impl FunctionBuilder<'_> { + fn emit_cast_branch( + &mut self, + relative_depth: u32, + target: wasmparser::RefType, + branch_on_fail: bool, + ) -> Result<()> { + self.pop_expect(OperandSize::S32)?; + let target = convert_heap_type(target.heap_type(), target.is_nullable())?; + let conditional_ip = self.instructions.len(); + self.instructions.push(Instruction::BrOnCast(0, target, branch_on_fail)); + self.push_sizes(&[OperandSize::S32])?; + self.emit_dropkeep_to_label(relative_depth)?; + self.emit_branch_jump_or_return(relative_depth)?; + self.patch_jump(conditional_ip, self.instructions.len()); + Ok(()) + } + fn is_unreachable(&self) -> bool { self.control_stack.last().is_none_or(|frame| frame.unreachable) } @@ -1108,7 +1255,8 @@ impl FunctionBuilder<'_> { | Instruction::JumpIfZero32(ip) | Instruction::JumpIfNonZero32(ip) | Instruction::JumpIfRefNull(ip) - | Instruction::JumpIfRefNonNull(ip) => { + | Instruction::JumpIfRefNonNull(ip) + | Instruction::BrOnCast(ip, _, _) => { *ip = target as u32; } _ => {} diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml index d1c387b..6cf9b17 100644 --- a/crates/tinywasm/Cargo.toml +++ b/crates/tinywasm/Cargo.toml @@ -70,7 +70,6 @@ name = "test-wasm-custom-page-sizes" [[test]] harness = false name = "test-wasm-function-references" -test = false [[test]] harness = false @@ -79,7 +78,6 @@ name = "test-wasm-custom" [[test]] harness = false name = "test-wasm-gc" -test = false [[test]] harness = false diff --git a/crates/tinywasm/src/engine.rs b/crates/tinywasm/src/engine.rs index 521eb80..64ef6be 100644 --- a/crates/tinywasm/src/engine.rs +++ b/crates/tinywasm/src/engine.rs @@ -123,6 +123,9 @@ pub struct Config { /// Whether memory and stack allocation failures should trap instead of degrading into normal operation failure modes. /// Defaults to `false`. pub trap_on_oom: bool, + /// Initial number of GC heap bytes that triggers collection. + /// Defaults to 1 MiB. + pub gc_collection_threshold: usize, } impl Config { @@ -181,6 +184,12 @@ impl Config { self } + /// Set the initial GC heap collection threshold in bytes. + pub fn with_gc_collection_threshold(mut self, threshold: usize) -> Self { + self.gc_collection_threshold = threshold; + self + } + /// Get the current fuel policy pub fn fuel_policy(&self) -> FuelPolicy { self.fuel_policy @@ -206,6 +215,7 @@ impl Default for Config { fuel_policy: FuelPolicy::default(), memory_backend: MemoryBackend::default(), trap_on_oom: false, + gc_collection_threshold: 1024 * 1024, } } } diff --git a/crates/tinywasm/src/error.rs b/crates/tinywasm/src/error.rs index b5885ca..ebd0470 100644 --- a/crates/tinywasm/src/error.rs +++ b/crates/tinywasm/src/error.rs @@ -133,6 +133,9 @@ pub enum Trap { max: usize, }, + /// An out-of-bounds GC array access occurred. + ArrayOutOfBounds, + /// A division by zero occurred DivisionByZero, @@ -169,9 +172,21 @@ pub enum Trap { /// A null reference was used where a non-null reference was required. NullReference, + /// A null struct reference was dereferenced. + NullStructReference, + + /// A null array reference was dereferenced. + NullArrayReference, + /// A null function reference was called. NullFunctionReference, + /// A null i31 reference was unwrapped. + NullI31Reference, + + /// A reference cast failed. + CastFailure, + /// Indirect call type mismatch IndirectCallTypeMismatch { /// The expected type @@ -191,6 +206,7 @@ impl Trap { Self::Unreachable => "unreachable", Self::MemoryOutOfBounds { .. } => "out of bounds memory access", Self::TableOutOfBounds { .. } => "out of bounds table access", + Self::ArrayOutOfBounds => "out of bounds array access", Self::DivisionByZero => "integer divide by zero", Self::InvalidConversionToInt => "invalid conversion to integer", Self::IntegerOverflow => "integer overflow", @@ -200,7 +216,11 @@ impl Trap { Self::UndefinedElement { .. } => "undefined element", Self::UninitializedElement { .. } => "uninitialized element", Self::NullReference => "null reference", + Self::NullStructReference => "null structure reference", + Self::NullArrayReference => "null array reference", Self::NullFunctionReference => "null function reference", + Self::NullI31Reference => "null i31 reference", + Self::CastFailure => "cast failure", Self::IndirectCallTypeMismatch { .. } => "indirect call type mismatch", Self::HostFunction(_) => "host function trap", Self::InvalidStore => "invalid store", @@ -291,6 +311,7 @@ impl Display for Trap { Self::TableOutOfBounds { offset, len, max } => { write!(f, "out of bounds table access: offset={offset}, len={len}, max={max}") } + Self::ArrayOutOfBounds => write!(f, "out of bounds array access"), Self::DivisionByZero => write!(f, "integer divide by zero"), Self::InvalidConversionToInt => write!(f, "invalid conversion to integer"), Self::IntegerOverflow => write!(f, "integer overflow"), @@ -302,7 +323,11 @@ impl Display for Trap { write!(f, "uninitialized element: index={index}") } Self::NullReference => write!(f, "null reference"), + Self::NullStructReference => write!(f, "null structure reference"), + Self::NullArrayReference => write!(f, "null array reference"), Self::NullFunctionReference => write!(f, "null function reference"), + Self::NullI31Reference => write!(f, "null i31 reference"), + Self::CastFailure => write!(f, "cast failure"), Self::InvalidStore => write!(f, "invalid store"), #[cfg(feature = "debug")] Self::IndirectCallTypeMismatch { expected, actual } => { diff --git a/crates/tinywasm/src/func.rs b/crates/tinywasm/src/func.rs index b6b7b14..732cafc 100644 --- a/crates/tinywasm/src/func.rs +++ b/crates/tinywasm/src/func.rs @@ -44,16 +44,25 @@ impl Function { // Execute until completion and then collect result values from the stack. InterpreterRuntime::exec(store, callframe, 0)?; - collect_call_results(&mut store.value_stack, store.state.get_type(func_instance.type_addr)) + collect_call_results( + &mut store.value_stack, + &store.state, + store.state.get_canonical_func_type(func_instance.type_addr), + ) } self.item.validate_store(store)?; validate_call_params(&store.state, store.state.get_func_type(self.addr()), params)?; + let results_may_gc = store.state.get_func(self.addr()).gc.results; store.enter_execution()?; let result = call_inner(self, store, params); store.exit_execution(); + if results_may_gc && let Ok(values) = &result { + store.state.pin_host_values(values); + } + result } @@ -97,12 +106,17 @@ impl Function { self.item.validate_store(store)?; validate_call_params(&store.state, store.state.get_func_type(self.addr()), params)?; + let results_may_gc = store.state.get_func(self.addr()).gc.results; store.enter_execution()?; let result = call_resumable_inner(self, store, params); store.exit_execution(); - Ok(FuncExecution { store, state: result? }) + let state = result?; + if results_may_gc && let FuncExecutionState::Completed { result: Some(values) } = &state { + store.state.pin_host_values(values); + } + Ok(FuncExecution { store, state }) } } @@ -188,6 +202,7 @@ impl HostFunction { let type_addr = store.register_host_type(ty); let addr = store.add_func(FunctionInstance { type_addr, + gc: store.state.func_gc_metadata(type_addr), kind: crate::store::FunctionKind::Host(Rc::new(Self { func: Box::new(func) })), }); Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 } @@ -231,6 +246,7 @@ impl HostFunction { let type_addr = store.register_host_type(&ty); let addr = store.add_func(FunctionInstance { type_addr, + gc: store.state.func_gc_metadata(type_addr), kind: crate::store::FunctionKind::Host(Rc::new(Self { func: Box::new(inner_func) })), }); Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 } @@ -328,7 +344,7 @@ impl FuncContext<'_> { validate_call_params(&self.store.state, self.store.state.get_func_type(func.addr()), args)?; let func_instance = self.store.state.get_func(func.addr()).clone(); - match func_instance.kind { + let result = match func_instance.kind { crate::store::FunctionKind::Host(host_func) => { let result = host_func.call(FuncContext { store: &mut *self.store, module_id: func.module_id }, args)?; @@ -354,9 +370,19 @@ impl FuncContext<'_> { self.store.value_stack.truncate_to_base(value_stack_base); })?; - collect_call_results(&mut self.store.value_stack, self.store.state.get_type(func_instance.type_addr)) + collect_call_results( + &mut self.store.value_stack, + &self.store.state, + self.store.state.get_canonical_func_type(func_instance.type_addr), + ) } + }; + if func_instance.gc.results + && let Ok(values) = &result + { + self.store.state.pin_host_values(values); } + result } /// Call a typed function from within the current host-function invocation. @@ -441,12 +467,19 @@ impl<'store> FuncExecution<'store> { match result? { crate::interpreter::ExecState::Completed => { - let result_ty = self.store.state.get_func(root_func_addr).type_addr; + let func = self.store.state.get_func(root_func_addr); + let result_ty = func.type_addr; + let results_may_gc = func.gc.results; self.state = FuncExecutionState::Completed { result: None }; - Ok(ExecProgress::Completed(collect_call_results( + let values = collect_call_results( &mut self.store.value_stack, - self.store.state.get_type(result_ty), - )?)) + &self.store.state, + self.store.state.get_canonical_func_type(result_ty), + )?; + if results_may_gc { + self.store.state.pin_host_values(&values); + } + Ok(ExecProgress::Completed(values)) } crate::interpreter::ExecState::Suspended(callframe) => { let FuncExecutionState::Running { exec_state, .. } = &mut self.state else { @@ -517,7 +550,7 @@ pub(crate) fn validate_host_results( type_addr: TypeAddr, result: Vec, ) -> Result> { - let expected = store.state.get_type(type_addr); + let expected = store.state.get_canonical_func_type(type_addr); if result.len() == expected.results().len() && result.iter().zip(expected.results()).all(|(&value, &ty)| store.state.value_matches_type(value, ty)) { @@ -527,9 +560,18 @@ pub(crate) fn validate_host_results( Err(Error::InvalidHostFnReturn { expected: Box::new(expected.clone()), actual: result }) } -fn collect_call_results(value_stack: &mut ValueStack, func_ty: &FuncType) -> Result> { +fn collect_call_results( + value_stack: &mut ValueStack, + state: &crate::store::State, + func_ty: &FuncType, +) -> Result> { debug_assert!(value_stack.len() >= func_ty.results().len()); // m values are on the top of the stack (Ensured by validation) - let mut res: Vec<_> = value_stack.pop_types(func_ty.results().iter().rev()).collect(); // pop in reverse order since the stack is LIFO + let mut res: Vec<_> = func_ty + .results() + .iter() + .rev() + .map(|&ty| state.attach_value(value_stack.pop_tinyvalue(ty), ty).expect("validated function result")) + .collect(); res.reverse(); // reverse to get the original order Ok(res) } diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs index 887d107..3a7c06d 100644 --- a/crates/tinywasm/src/imports.rs +++ b/crates/tinywasm/src/imports.rs @@ -157,35 +157,9 @@ impl Imports { Ok(()) } - fn ref_subtype(actual: RefType, expected: RefType) -> bool { - if actual.is_nullable() && !expected.is_nullable() { - return false; - } - match (actual.type_index(), expected.type_index()) { - (Some(actual), Some(expected)) => actual == expected, - (Some(_), None) => matches!(expected.abstract_heap_type(), Some(AbstractHeapType::Func)), - (None, Some(_)) => matches!(actual.abstract_heap_type(), Some(AbstractHeapType::NoFunc)), - (None, None) => { - actual.abstract_heap_type() == expected.abstract_heap_type() - || actual.is_func() && matches!(expected.abstract_heap_type(), Some(AbstractHeapType::Func)) - || actual.is_extern() && matches!(expected.abstract_heap_type(), Some(AbstractHeapType::Extern)) - || actual.is_exn() && matches!(expected.abstract_heap_type(), Some(AbstractHeapType::Exn)) - } - } - } - - fn value_subtype(actual: WasmType, expected: WasmType) -> bool { - match (actual, expected) { - (WasmType::Ref(actual), WasmType::Ref(expected)) => Self::ref_subtype(actual, expected), - _ => actual == expected, - } - } - fn compare_table_types(import: &Import, actual: &TableType, expected: &TableType) -> Result<()> { Self::compare_types(import, &actual.arch(), &expected.arch())?; - if !Self::ref_subtype(actual.element_type, expected.element_type) - || !Self::ref_subtype(expected.element_type, actual.element_type) - { + if actual.element_type != expected.element_type { return Err(LinkingError::incompatible_import_type(import).into()); } if actual.size_initial < expected.size_initial { @@ -275,8 +249,8 @@ impl Imports { let global = store.state.get_global(global_addr); let expected = ty.with_ty(crate::store::canonicalize_value_type(ty.ty, type_addrs)); let compatible = global.ty.mutable == ty.mutable - && Self::value_subtype(global.ty.ty, expected.ty) - && (!ty.mutable || Self::value_subtype(expected.ty, global.ty.ty)); + && store.state.value_type_is_subtype(global.ty.ty, expected.ty) + && (!ty.mutable || store.state.value_type_is_subtype(expected.ty, global.ty.ty)); if !compatible { cold_path(); return Err(LinkingError::incompatible_import_type(import).into()); @@ -306,7 +280,8 @@ impl Imports { if let Some(func) = &func_handle { func.item.validate_store(store)?; } - if store.state.get_func(func_addr).type_addr != *expected_type_addr { + if !store.state.type_addr_is_subtype(store.state.get_func(func_addr).type_addr, *expected_type_addr) + { cold_path(); return Err(LinkingError::incompatible_import_type(import).into()); } diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index ecfbacb..be38419 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -151,7 +151,7 @@ impl ModuleInstance { /// /// See pub fn instantiate_no_start(store: &mut Store, module: &Module, imports: Option) -> Result { - let type_addrs = store.register_module_types(&module.func_types); + let type_addrs = store.register_module_types(&module.types); let id = store.next_module_instance_id(); let mut addrs = imports.unwrap_or_default().link(store, module, &type_addrs)?; let local_type_addrs = module.func_type_idxs[addrs.funcs.len()..] @@ -175,9 +175,9 @@ impl ModuleInstance { store.init_globals(&mut addrs.globals, &module.globals, &addrs.funcs, &type_addrs)?; addrs.tables.extend(store.init_tables(&module.tables, &addrs.globals, &addrs.funcs, &type_addrs)?); let (elem_addrs, elem_trapped) = - store.init_elements(&addrs.tables, &addrs.funcs, &addrs.globals, &module.elements)?; + store.init_elements(&addrs.tables, &addrs.funcs, &addrs.globals, &module.elements, &type_addrs)?; let (data_addrs, data_trapped) = - store.init_data(&addrs.memories, &addrs.globals, &addrs.funcs, &module.data)?; + store.init_data(&addrs.memories, &addrs.globals, &addrs.funcs, &module.data, &type_addrs)?; let instance = ModuleInstanceInner { store_id: store.id(), diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 5e78dae..fb8fdec 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -237,6 +237,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { JumpIfNonZero64(ip) => if self.exec_jump_non_zero_64(*ip) { return Ok(None) }, JumpIfRefNull(ip) => if self.exec_jump_ref_null(*ip) { return Ok(None) }, JumpIfRefNonNull(ip) => if self.exec_jump_ref_non_null(*ip) { return Ok(None) }, + BrOnCast(ip, ty, on_fail) => if self.exec_ref_matches(*ty) == *on_fail { self.cf.instr_ptr = *ip as usize; return Ok(None); }, JumpIfLocalZero32 { target_ip, local } => if self.exec_jump_local_zero_32(*target_ip, *local) { return Ok(None) }, JumpIfLocalNonZero32 { target_ip, local } => if self.exec_jump_local_non_zero_32(*target_ip, *local) { return Ok(None) }, JumpIfLocalZero64 { target_ip, local } => if self.exec_jump_local_zero_64(*target_ip, *local) { return Ok(None) }, @@ -444,10 +445,46 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I64Popcnt => stack_op!(unary i64, |v| i64::from(v.count_ones())), // Reference types - RefFunc(func_idx) => self.exec_const(ValueRef::from_addr(Some(self.module.resolve_func_addr(*func_idx))))?, + RefFunc(func_idx) => self.exec_const(ValueRef::from_category_addr(self.module.resolve_func_addr(*func_idx)))?, RefNull(_) => self.exec_const(ValueRef::NULL)?, RefIsNull => self.exec_ref_is_null()?, RefAsNonNull => self.exec_ref_as_non_null()?, + RefI31 => stack_op!(unary i32 => ValueRef, |v| ValueRef::from_i31(v)), + I31GetS => self.exec_i31_get(true)?, + I31GetU => self.exec_i31_get(false)?, + RefEq => stack_op!(binary ValueRef => i32, |a, b| i32::from(a == b)), + RefTest(ty) => { + let value = ValueRef::stack_pop(&mut self.store.value_stack); + let ty = self.canonical_ref_type(*ty); + self.store.value_stack.push(i32::from(self.store.state.value_ref_matches(value, ty)))?; + } + RefCast(ty) => { + if !self.exec_ref_matches(*ty) { + cold_path(); + return Err(Trap::CastFailure); + } + } + // GC objects + StructNew(ty) => self.exec_struct_new(*ty, false)?, + StructNewDefault(ty) => self.exec_struct_new(*ty, true)?, + StructGet(ty, field) => self.exec_struct_get(*ty, *field, None)?, + StructGetS(ty, field) => self.exec_struct_get(*ty, *field, Some(true))?, + StructGetU(ty, field) => self.exec_struct_get(*ty, *field, Some(false))?, + StructSet(ty, field) => self.exec_struct_set(*ty, *field)?, + ArrayNew(ty) => self.exec_array_new(*ty, false)?, + ArrayNewDefault(ty) => self.exec_array_new(*ty, true)?, + ArrayNewFixed(ty, len) => self.exec_array_new_fixed(*ty, *len)?, + ArrayNewData(ty, data) => self.exec_array_new_data(*ty, *data)?, + ArrayNewElem(ty, elem) => self.exec_array_new_elem(*ty, *elem)?, + ArrayGet(ty) => self.exec_array_get(*ty, None)?, + ArrayGetS(ty) => self.exec_array_get(*ty, Some(true))?, + ArrayGetU(ty) => self.exec_array_get(*ty, Some(false))?, + ArraySet(ty) => self.exec_array_set(*ty)?, + ArrayLen => self.exec_array_len()?, + ArrayFill(ty) => self.exec_array_fill(*ty)?, + ArrayCopy(dst, src) => self.exec_array_copy(*dst, *src)?, + ArrayInitData(ty, data) => self.exec_array_init_data(*ty, *data)?, + ArrayInitElem(ty, elem) => self.exec_array_init_elem(*ty, *elem)?, MemorySize(addr) => self.exec_memory_size(*addr)?, MemoryGrow(addr) => self.exec_memory_grow(*addr)?, @@ -987,10 +1024,19 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { &mut self, host_func: Rc, type_addr: TypeAddr, + params_may_gc: bool, ) -> Result { - let ty = self.store.state.get_type(type_addr); - let mut params = self.store.value_stack.pop_types(ty.params().iter().rev()).collect::>(); + let param_types = self.store.state.get_canonical_func_type(type_addr).params(); + let mut params = Vec::new(); + params.try_reserve_exact(param_types.len()).map_err(|_| Trap::OutOfMemory)?; + for &ty in param_types.iter().rev() { + let value = self.store.value_stack.pop_tinyvalue(ty); + params.push(self.store.state.attach_value(value, ty).expect("validated host argument")); + } params.reverse(); + if params_may_gc { + self.store.state.pin_host_values(¶ms); + } let result = host_func.call(FuncContext { store: self.store, module_id: self.module.id() }, ¶ms); let res = match result.and_then(|result| crate::func::validate_host_results(self.store, type_addr, result)) { Ok(res) => res, @@ -1016,7 +1062,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { match func.kind { crate::store::FunctionKind::Wasm(wasm_func) => self.exec_call(wasm_func, addr), crate::store::FunctionKind::Host(host_func) => { - self.exec_call_host::(host_func, func.type_addr)?; + self.exec_call_host::(host_func, func.type_addr, func.gc.params)?; Ok(()) } } @@ -1031,7 +1077,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.exec_return_call(wasm_func, addr)?; Ok(false) } - crate::store::FunctionKind::Host(host_func) => self.exec_call_host::(host_func, func.type_addr), + crate::store::FunctionKind::Host(host_func) => { + self.exec_call_host::(host_func, func.type_addr, func.gc.params) + } } } @@ -1071,7 +1119,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let table_addr = self.module.resolve_table_addr(table_addr); let table_idx = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; let table = self.store.state.get_table(table_addr); - debug_assert!(table.kind.element_type.is_func(), "table is not of type funcref"); let Ok(table) = table.get(table_idx) else { cold_path(); @@ -1092,11 +1139,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { expected_type_addr: TypeAddr, ) -> Result { let func = self.store.state.get_func(func_addr).clone(); - if func.type_addr != expected_type_addr { + if !self.store.state.type_addr_is_subtype(func.type_addr, expected_type_addr) { cold_path(); return Err(Trap::IndirectCallTypeMismatch { - actual: Box::new(self.store.state.get_type(func.type_addr).clone()), - expected: Box::new(self.store.state.get_type(expected_type_addr).clone()), + actual: Box::new(self.store.state.get_canonical_func_type(func.type_addr).clone()), + expected: Box::new(self.store.state.get_canonical_func_type(expected_type_addr).clone()), }); } match func.kind { @@ -1105,7 +1152,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { false => self.exec_call(wasm_func, func_addr), }, crate::store::FunctionKind::Host(host_func) => { - return self.exec_call_host::(host_func, func.type_addr); + return self.exec_call_host::(host_func, func.type_addr, func.gc.params); } }?; Ok(false) @@ -1327,6 +1374,261 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } + fn canonical_ref_type(&self, ty: RefType) -> RefType { + let Some(type_index) = ty.type_index() else { return ty }; + RefType::new_concrete(ty.is_nullable(), self.module.resolve_type_addr(type_index)) + .expect("canonical type address fits in a reference") + } + + fn exec_ref_matches(&self, ty: RefType) -> bool { + let value = ValueRef::stack_peek(&self.store.value_stack); + self.store.state.value_ref_matches(value, self.canonical_ref_type(ty)) + } + + fn exec_i31_get(&mut self, signed: bool) -> Result<(), Trap> { + let value = ValueRef::stack_pop(&mut self.store.value_stack); + if value.is_null() { + cold_path(); + return Err(Trap::NullI31Reference); + } + let value = if signed { + value.i31_s().expect("validated i31.get operand") + } else { + value.i31_u().expect("validated i31.get operand") as i32 + }; + self.store.value_stack.push(value) + } + + fn exec_struct_new(&mut self, type_index: TypeAddr, default: bool) -> Result<(), Trap> { + let type_addr = self.module.resolve_type_addr(type_index); + let fields = &self.store.state.get_type(type_addr).as_struct().expect("validated struct.new type").fields; + let mut values = Vec::new(); + values.try_reserve_exact(fields.len()).map_err(|_| Trap::OutOfMemory)?; + if default { + values.extend(fields.iter().map(|field| default_value(field.storage))); + } else { + for field in fields.iter().rev() { + values.push(pop_value(&mut self.store.value_stack, field.storage)); + } + values.reverse(); + } + let value = self.store.state.alloc_gc_object( + type_addr, + values, + (&self.store.value_stack.stack_32).into_iter().copied(), + )?; + self.store.value_stack.push(value) + } + + fn exec_struct_get(&mut self, type_index: TypeAddr, field_index: u32, signed: Option) -> Result<(), Trap> { + let reference = ValueRef::stack_pop(&mut self.store.value_stack); + let type_addr = self.module.resolve_type_addr(type_index); + let storage = self.store.state.get_type(type_addr).as_struct().expect("validated struct.get type").fields + [field_index as usize] + .storage; + let object = self.store.state.gc_object(reference, type_addr)?; + let value = *object.values.get(field_index as usize).expect("validated struct field index"); + push_value(&mut self.store.value_stack, value, storage, signed) + } + + fn exec_struct_set(&mut self, type_index: TypeAddr, field_index: u32) -> Result<(), Trap> { + let type_addr = self.module.resolve_type_addr(type_index); + let storage = self.store.state.get_type(type_addr).as_struct().expect("validated struct.set type").fields + [field_index as usize] + .storage; + let value = pop_value(&mut self.store.value_stack, storage); + let reference = ValueRef::stack_pop(&mut self.store.value_stack); + self.store.state.gc_object(reference, type_addr)?; + self.store.state.gc.set(reference, field_index as usize, value).expect("live struct field"); + Ok(()) + } + + fn exec_array_new(&mut self, type_index: TypeAddr, default: bool) -> Result<(), Trap> { + let type_addr = self.module.resolve_type_addr(type_index); + let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.new type").field.storage; + let len = u32::stack_pop(&mut self.store.value_stack) as usize; + let value = if default { default_value(storage) } else { pop_value(&mut self.store.value_stack, storage) }; + let mut values = Vec::new(); + values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?; + values.resize(len, value); + let reference = self.store.state.alloc_gc_object( + type_addr, + values, + (&self.store.value_stack.stack_32).into_iter().copied(), + )?; + self.store.value_stack.push(reference) + } + + fn exec_array_new_fixed(&mut self, type_index: TypeAddr, len: u32) -> Result<(), Trap> { + let type_addr = self.module.resolve_type_addr(type_index); + let storage = + self.store.state.get_type(type_addr).as_array().expect("validated array.new_fixed type").field.storage; + let len = len as usize; + let mut values = Vec::new(); + values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?; + for _ in 0..len { + values.push(pop_value(&mut self.store.value_stack, storage)); + } + values.reverse(); + let reference = self.store.state.alloc_gc_object( + type_addr, + values, + (&self.store.value_stack.stack_32).into_iter().copied(), + )?; + self.store.value_stack.push(reference) + } + + fn exec_array_get(&mut self, type_index: TypeAddr, signed: Option) -> Result<(), Trap> { + let index = u32::stack_pop(&mut self.store.value_stack) as usize; + let reference = ValueRef::stack_pop(&mut self.store.value_stack); + let type_addr = self.module.resolve_type_addr(type_index); + let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.get type").field.storage; + let object = self.store.state.gc_object(reference, type_addr)?; + let value = *object.values.get(index).ok_or(Trap::ArrayOutOfBounds)?; + push_value(&mut self.store.value_stack, value, storage, signed) + } + + fn exec_array_set(&mut self, type_index: TypeAddr) -> Result<(), Trap> { + let type_addr = self.module.resolve_type_addr(type_index); + let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.set type").field.storage; + let value = pop_value(&mut self.store.value_stack, storage); + let index = u32::stack_pop(&mut self.store.value_stack) as usize; + let reference = ValueRef::stack_pop(&mut self.store.value_stack); + let object = self.store.state.gc_object(reference, type_addr)?; + if index >= object.values.len() { + return Err(Trap::ArrayOutOfBounds); + } + self.store.state.gc.set(reference, index, value).expect("live array element"); + Ok(()) + } + + fn exec_array_len(&mut self) -> Result<(), Trap> { + let reference = ValueRef::stack_pop(&mut self.store.value_stack); + if reference.is_null() { + return Err(Trap::NullArrayReference); + } + let object = self.store.state.gc.get(reference).ok_or(Trap::Other("invalid GC reference"))?; + if self.store.state.get_type(object.type_addr).as_array().is_none() { + return Err(Trap::Other("GC reference is not an array")); + } + self.store.value_stack.push(object.values.len() as i32) + } + + fn exec_array_fill(&mut self, type_index: TypeAddr) -> Result<(), Trap> { + let type_addr = self.module.resolve_type_addr(type_index); + let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.fill type").field.storage; + let len = u32::stack_pop(&mut self.store.value_stack) as usize; + let value = pop_value(&mut self.store.value_stack, storage); + let index = u32::stack_pop(&mut self.store.value_stack) as usize; + let reference = ValueRef::stack_pop(&mut self.store.value_stack); + let object = self.store.state.gc_object(reference, type_addr)?; + let end = index.checked_add(len).filter(|end| *end <= object.values.len()).ok_or(Trap::ArrayOutOfBounds)?; + self.store.state.gc.fill(reference, index..end, value).expect("live array range"); + Ok(()) + } + + fn exec_array_copy(&mut self, dst_type: TypeAddr, src_type: TypeAddr) -> Result<(), Trap> { + let len = u32::stack_pop(&mut self.store.value_stack) as usize; + let src_index = u32::stack_pop(&mut self.store.value_stack) as usize; + let src = ValueRef::stack_pop(&mut self.store.value_stack); + let dst_index = u32::stack_pop(&mut self.store.value_stack) as usize; + let dst = ValueRef::stack_pop(&mut self.store.value_stack); + let dst_type = self.module.resolve_type_addr(dst_type); + let src_type = self.module.resolve_type_addr(src_type); + let dst_len = self.store.state.gc_object(dst, dst_type)?.values.len(); + let src_object = self.store.state.gc_object(src, src_type)?; + let src_end = + src_index.checked_add(len).filter(|end| *end <= src_object.values.len()).ok_or(Trap::ArrayOutOfBounds)?; + dst_index.checked_add(len).filter(|end| *end <= dst_len).ok_or(Trap::ArrayOutOfBounds)?; + if src == dst { + self.store.state.gc.copy_within(dst, src_index..src_end, dst_index).expect("live array range"); + return Ok(()); + } + let mut values = Vec::new(); + values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?; + values.extend_from_slice(&src_object.values[src_index..src_end]); + self.store.state.gc.set_slice(dst, dst_index, &values).expect("live array range"); + Ok(()) + } + + fn exec_array_new_data(&mut self, type_index: TypeAddr, data_index: DataAddr) -> Result<(), Trap> { + let len = u32::stack_pop(&mut self.store.value_stack) as usize; + let src = u32::stack_pop(&mut self.store.value_stack) as usize; + let type_addr = self.module.resolve_type_addr(type_index); + let storage = self.store.state.get_type(type_addr).as_array().expect("validated array type").field.storage; + let data_addr = self.module.resolve_data_addr(data_index); + let data = self.store.state.data[data_addr as usize].data.as_deref().unwrap_or(&[]); + let values = decode_data(storage, data, src, len)?; + let reference = self.store.state.alloc_gc_object( + type_addr, + values, + (&self.store.value_stack.stack_32).into_iter().copied(), + )?; + self.store.value_stack.push(reference) + } + + fn exec_array_new_elem(&mut self, type_index: TypeAddr, elem_index: ElemAddr) -> Result<(), Trap> { + let len = u32::stack_pop(&mut self.store.value_stack) as usize; + let src = u32::stack_pop(&mut self.store.value_stack) as usize; + let elem_addr = self.module.resolve_elem_addr(elem_index); + let items = self.store.state.elements[elem_addr as usize].items.as_deref().unwrap_or(&[]); + let end = src.checked_add(len).filter(|end| *end <= items.len()).ok_or_else(|| Trap::TableOutOfBounds { + offset: src, + len, + max: items.len(), + })?; + let mut values = Vec::new(); + values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?; + values.extend(items[src..end].iter().copied().map(TinyWasmValue::ValueRef)); + let type_addr = self.module.resolve_type_addr(type_index); + let reference = self.store.state.alloc_gc_object( + type_addr, + values, + (&self.store.value_stack.stack_32).into_iter().copied(), + )?; + self.store.value_stack.push(reference) + } + + fn exec_array_init_data(&mut self, type_index: TypeAddr, data_index: DataAddr) -> Result<(), Trap> { + let len = u32::stack_pop(&mut self.store.value_stack) as usize; + let src = u32::stack_pop(&mut self.store.value_stack) as usize; + let dst = u32::stack_pop(&mut self.store.value_stack) as usize; + let reference = ValueRef::stack_pop(&mut self.store.value_stack); + let type_addr = self.module.resolve_type_addr(type_index); + let storage = self.store.state.get_type(type_addr).as_array().expect("validated array type").field.storage; + let object_len = self.store.state.gc_object(reference, type_addr)?.values.len(); + dst.checked_add(len).filter(|end| *end <= object_len).ok_or(Trap::ArrayOutOfBounds)?; + let data = + self.store.state.data[self.module.resolve_data_addr(data_index) as usize].data.as_deref().unwrap_or(&[]); + let values = decode_data(storage, data, src, len)?; + self.store.state.gc.set_slice(reference, dst, &values).expect("live array range"); + Ok(()) + } + + fn exec_array_init_elem(&mut self, type_index: TypeAddr, elem_index: ElemAddr) -> Result<(), Trap> { + let len = u32::stack_pop(&mut self.store.value_stack) as usize; + let src = u32::stack_pop(&mut self.store.value_stack) as usize; + let dst = u32::stack_pop(&mut self.store.value_stack) as usize; + let reference = ValueRef::stack_pop(&mut self.store.value_stack); + let type_addr = self.module.resolve_type_addr(type_index); + let object_len = self.store.state.gc_object(reference, type_addr)?.values.len(); + dst.checked_add(len).filter(|end| *end <= object_len).ok_or(Trap::ArrayOutOfBounds)?; + let items = self.store.state.elements[self.module.resolve_elem_addr(elem_index) as usize] + .items + .as_deref() + .unwrap_or(&[]); + let end = src.checked_add(len).filter(|end| *end <= items.len()).ok_or_else(|| Trap::TableOutOfBounds { + offset: src, + len, + max: items.len(), + })?; + let mut values = Vec::new(); + values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?; + values.extend(items[src..end].iter().copied().map(TinyWasmValue::ValueRef)); + self.store.state.gc.set_slice(reference, dst, &values).expect("live array range"); + Ok(()) + } + fn exec_memory_size(&mut self, addr: u32) -> Result<(), Trap> { let mem = self.store.state.get_mem(self.module.resolve_mem_addr(addr)); match mem.is_64bit() { @@ -1531,8 +1833,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_table_get(&mut self, table_index: u32) -> Result<(), Trap> { let table_addr = self.module.resolve_table_addr(table_index); let idx = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; - let v = self.store.state.get_table(table_addr).get_wasm_val(idx)?; - self.store.value_stack.push_dyn(v.into()) + let value = *self.store.state.get_table(table_addr).get(idx)?; + self.store.value_stack.push(value) } fn exec_table_set(&mut self, table_index: u32) -> Result<(), Trap> { @@ -1540,7 +1842,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let table_addr = self.module.resolve_table_addr(table_index); let idx = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; let table = self.store.state.get_table_mut(table_addr); - table.set(idx, val.addr().into()) + table.set(idx, val) } fn exec_table_size(&mut self, table_index: u32) -> Result<(), Trap> { @@ -1580,7 +1882,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let val = ::stack_pop(&mut self.store.value_stack); let table = self.store.state.get_table_mut(table_addr); let sz = table.size(); - let result = table.grow(n, val.addr().into()); + let result = table.grow(n, val); match (arch, result) { (MemoryArch::I32, Ok(())) => self.store.value_stack.push(sz as i32), (MemoryArch::I32, Err(_)) => self.store.value_stack.push(-1_i32), @@ -1595,7 +1897,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let n = self.pop_table_operand(arch)?; let val = ::stack_pop(&mut self.store.value_stack); let i = self.pop_table_operand(arch)?; - self.store.state.get_table_mut(table_addr).fill(i, n, val.addr().into()) + self.store.state.get_table_mut(table_addr).fill(i, n, val) } fn pop_table_operand(&mut self, arch: MemoryArch) -> Result { diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index 853c5e4..378dc7f 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -165,6 +165,15 @@ impl Stack { self.data.truncate(len - count); } } + +impl<'a, T: Copy + Default> IntoIterator for &'a Stack { + type Item = &'a T; + type IntoIter = core::slice::Iter<'a, T>; + + fn into_iter(self) -> Self::IntoIter { + self.data.iter() + } +} impl ValueStack { pub(crate) fn new(config: &Config) -> Self { Self { @@ -207,13 +216,6 @@ impl ValueStack { self.stack_128.select_many(counts.c128 as usize, condition); } - pub(crate) fn pop_types<'a>( - &'a mut self, - val_types: impl IntoIterator, - ) -> impl core::iter::Iterator { - val_types.into_iter().map(|val_type| self.pop_wasmvalue(*val_type)) - } - #[inline(always)] pub(crate) fn enter_locals(&mut self, params: &ValueCounts, locals: &ValueCounts) -> Result { let locals_base32 = self.stack_32.enter_locals(params.c32 as usize, locals.c32 as usize)?; @@ -246,14 +248,12 @@ impl ValueStack { Ok(()) } - pub(crate) fn pop_wasmvalue(&mut self, val_type: WasmType) -> WasmValue { + pub(crate) fn pop_tinyvalue(&mut self, val_type: WasmType) -> TinyWasmValue { match val_type { - WasmType::I32 => WasmValue::I32(i32::stack_pop(self)), - WasmType::I64 => WasmValue::I64(i64::stack_pop(self)), - WasmType::F32 => WasmValue::F32(f32::stack_pop(self)), - WasmType::F64 => WasmValue::F64(f64::stack_pop(self)), - WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::stack_pop(self)).attach_type(val_type).unwrap(), - WasmType::V128 => WasmValue::V128(Value128::stack_pop(self).0), + WasmType::I32 | WasmType::F32 => TinyWasmValue::Value32(Value32::stack_pop(self)), + WasmType::I64 | WasmType::F64 => TinyWasmValue::Value64(Value64::stack_pop(self)), + WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::stack_pop(self)), + WasmType::V128 => TinyWasmValue::Value128(Value128::stack_pop(self)), } } diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs index be2e0a1..f034906 100644 --- a/crates/tinywasm/src/interpreter/values.rs +++ b/crates/tinywasm/src/interpreter/values.rs @@ -8,8 +8,6 @@ pub(crate) type Value64 = u64; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) struct ValueRef(u32); -// TODO(wasm3): GC references need a tagged representation; this raw address is only sufficient for current refs. - impl Default for ValueRef { fn default() -> Self { Self::NULL @@ -17,7 +15,8 @@ impl Default for ValueRef { } impl ValueRef { - pub(crate) const NULL: Self = Self(u32::MAX); + const HOST_ANY_TAG: u32 = 1 << 30; + pub(crate) const NULL: Self = Self(0); #[inline] pub(crate) const fn from_raw(raw: u32) -> Self { @@ -25,16 +24,24 @@ impl ValueRef { } #[inline] - pub(crate) const fn from_addr(addr: Option) -> Self { - match addr { - Some(addr) => Self(addr), - None => Self::NULL, - } + pub(crate) const fn from_category_addr(addr: u32) -> Self { + let Some(raw) = addr.checked_add(1) else { panic!("reference address does not fit in the runtime encoding") }; + let Some(raw) = raw.checked_mul(2) else { panic!("reference address does not fit in the runtime encoding") }; + Self(raw) + } + + #[inline] + pub(crate) const fn from_i31(value: i32) -> Self { + Self(((value as u32) << 1) | 1) + } + + pub(crate) const fn is_host_any(self) -> bool { + matches!(self.addr(), Some(addr) if addr & Self::HOST_ANY_TAG != 0) } #[inline] pub(crate) const fn addr(self) -> Option { - if self.is_null() { None } else { Some(self.0) } + if self.is_null() || self.is_i31() { None } else { Some(self.0 / 2 - 1) } } #[inline] @@ -42,6 +49,21 @@ impl ValueRef { self.0 == Self::NULL.0 } + #[inline] + pub(crate) const fn is_i31(self) -> bool { + self.0 & 1 != 0 + } + + #[inline] + pub(crate) const fn i31_s(self) -> Option { + if self.is_i31() { Some((self.0 as i32) >> 1) } else { None } + } + + #[inline] + pub(crate) const fn i31_u(self) -> Option { + if self.is_i31() { Some(self.0 >> 1) } else { None } + } + #[inline] pub(crate) const fn raw(self) -> u32 { self.0 @@ -96,7 +118,7 @@ impl TinyWasmValue { } } - /// Attaches a type to the value (panics if the size of the value is not the same as the type) + /// Converts this internal value to the requested public WebAssembly type. pub fn attach_type(self, ty: WasmType) -> Option { match (self, ty) { (Self::Value32(v), WasmType::I32) => Some(WasmValue::I32(v as i32)), @@ -105,13 +127,13 @@ impl TinyWasmValue { (Self::Value64(v), WasmType::F64) => Some(WasmValue::F64(f64::from_bits(v))), (Self::ValueRef(v), WasmType::Ref(_)) if v.is_null() => Some(RefValue::Null.into()), (Self::ValueRef(v), WasmType::Ref(ty)) if ty.is_func() => { - Some(WasmValue::Ref(RefValue::Func(FuncRef::new(v.raw())))) + Some(WasmValue::Ref(RefValue::Func(FuncRef::new(v.addr()?)))) } (Self::ValueRef(v), WasmType::Ref(ty)) if ty.is_extern() => { - Some(WasmValue::Ref(RefValue::Extern(ExternRef::new(v.raw())))) + Some(WasmValue::Ref(RefValue::Extern(ExternRef::from_raw(v.raw())))) } (Self::ValueRef(v), WasmType::Ref(ty)) if ty.is_exn() => { - Some(WasmValue::Ref(RefValue::Exn(ExnRef::new(v.raw())))) + Some(WasmValue::Ref(RefValue::Exn(ExnRef::new(v.addr()?)))) } (Self::ValueRef(v), WasmType::Ref(_)) => Some(WasmValue::Ref(RefValue::Any(AnyRef::from_raw(v.raw())))), (Self::Value128(v), WasmType::V128) => Some(WasmValue::V128(v.0)), @@ -130,7 +152,11 @@ impl From<&WasmValue> for TinyWasmValue { WasmValue::I64(v) => Self::Value64(*v as u64), WasmValue::F32(v) => Self::Value32(v.to_bits()), WasmValue::F64(v) => Self::Value64(v.to_bits()), - WasmValue::Ref(value) => Self::ValueRef(ValueRef::from_addr(value.raw())), + WasmValue::Ref(RefValue::Null) => Self::ValueRef(ValueRef::NULL), + WasmValue::Ref(RefValue::Func(value)) => Self::ValueRef(ValueRef::from_category_addr(value.addr())), + WasmValue::Ref(RefValue::Extern(value)) => Self::ValueRef(ValueRef::from_raw(value.raw())), + WasmValue::Ref(RefValue::Exn(value)) => Self::ValueRef(ValueRef::from_category_addr(value.addr())), + WasmValue::Ref(RefValue::Any(value)) => Self::ValueRef(ValueRef::from_raw(value.raw())), WasmValue::V128(v) => Self::Value128((*v).into()), } } diff --git a/crates/tinywasm/src/reference.rs b/crates/tinywasm/src/reference.rs index dc54736..d8f9669 100644 --- a/crates/tinywasm/src/reference.rs +++ b/crates/tinywasm/src/reference.rs @@ -5,7 +5,8 @@ use alloc::format; use alloc::string::{String, ToString}; use alloc::vec::Vec; -use crate::store::{GlobalInstance, TableElement, TableInstance}; +use crate::interpreter::TinyWasmValue; +use crate::store::{GlobalInstance, TableInstance}; use crate::{Error, MemoryInstance, Result, Store, Trap}; use tinywasm_types::{Addr, GlobalAddr, GlobalType, MemAddr, MemoryType, TableAddr, TableType, WasmType, WasmValue}; @@ -346,12 +347,13 @@ fn table_value_to_element( state: &crate::store::State, element_type: tinywasm_types::RefType, value: WasmValue, -) -> Result { +) -> Result { if !state.value_matches_type(value, WasmType::Ref(element_type)) { return Err(Trap::Other("invalid table value type")); } let WasmValue::Ref(value) = value else { unreachable!() }; - Ok(TableElement::from(value.raw())) + let TinyWasmValue::ValueRef(value) = TinyWasmValue::from(WasmValue::Ref(value)) else { unreachable!() }; + Ok(value) } impl Table { @@ -390,20 +392,37 @@ impl Table { /// Get a table element as a wasm reference value. pub fn get(&self, store: &Store, index: TableAddr) -> Result { - Ok(self.instance(store)?.get_wasm_val(index as usize)?) + let table = self.instance(store)?; + let value = store + .state + .attach_value(TinyWasmValue::ValueRef(*table.get(index as usize)?), WasmType::Ref(table.kind.element_type)) + .expect("table value matches its element type"); + if let WasmValue::Ref(value) = value { + store.state.pin_host_ref(value); + } + Ok(value) } /// Load a range of table elements and iterate over wasm reference values. - pub fn load(&self, store: &Store, offset: usize, len: usize) -> Result> { + pub fn load<'a>( + &self, + store: &'a Store, + offset: usize, + len: usize, + ) -> Result + 'a> { let table = self.instance(store)?; let element_type = table.kind.element_type; let elements = table.load(offset, len)?; - Ok(elements - .iter() - .copied() - .map(move |element| element.to_wasm_value(element_type)) - .collect::>() - .into_iter()) + let may_contain_gc = store.state.type_may_contain_gc(WasmType::Ref(element_type)); + Ok(elements.iter().copied().map(move |value| { + if may_contain_gc { + store.state.gc.pin(value); + } + store + .state + .attach_value(TinyWasmValue::ValueRef(value), WasmType::Ref(element_type)) + .expect("table value matches its element type") + })) } /// Set a table element. @@ -460,8 +479,13 @@ impl Global { /// Get the current value of the global. pub fn get(&self, store: &Store) -> Result { let global = self.instance(store)?; - let value = global.value.attach_type(global.ty.ty); - Ok(value.unwrap_or_else(|| unreachable!("Global value type does not match global type, this is a bug"))) + let value = store.state.attach_value(global.value, global.ty.ty); + let value = + value.unwrap_or_else(|| unreachable!("Global value type does not match global type, this is a bug")); + if let WasmValue::Ref(value) = value { + store.state.pin_host_ref(value); + } + Ok(value) } /// Set the current value of the global. diff --git a/crates/tinywasm/src/store/element.rs b/crates/tinywasm/src/store/element.rs index f3a8602..4437bd4 100644 --- a/crates/tinywasm/src/store/element.rs +++ b/crates/tinywasm/src/store/element.rs @@ -1,12 +1,14 @@ -use crate::TableElement; +use crate::interpreter::ValueRef; use alloc::vec::Vec; +use tinywasm_types::RefType; /// A WebAssembly Element Instance /// /// See #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) struct ElementInstance { - pub(crate) items: Option>, // none is the element was dropped + pub(crate) items: Option>, // none is the element was dropped + pub(crate) ty: RefType, } impl ElementInstance { diff --git a/crates/tinywasm/src/store/function.rs b/crates/tinywasm/src/store/function.rs index f0e3ed9..367fadb 100644 --- a/crates/tinywasm/src/store/function.rs +++ b/crates/tinywasm/src/store/function.rs @@ -10,9 +10,17 @@ use crate::func::HostFunction; #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) struct FunctionInstance { pub(crate) type_addr: TypeAddr, + pub(crate) gc: FunctionGcMetadata, pub(crate) kind: FunctionKind, } +#[derive(Clone, Copy)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub(crate) struct FunctionGcMetadata { + pub(crate) params: bool, + pub(crate) results: bool, +} + #[derive(Clone)] #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) enum FunctionKind { diff --git a/crates/tinywasm/src/store/gc/arena.rs b/crates/tinywasm/src/store/gc/arena.rs new file mode 100644 index 0000000..b8f5961 --- /dev/null +++ b/crates/tinywasm/src/store/gc/arena.rs @@ -0,0 +1,263 @@ +//! Mark-and-sweep storage with stable handles for WebAssembly GC objects. + +use alloc::vec::Vec; +use core::cell::Cell; +use core::mem::size_of; +use core::num::NonZeroU32; + +/// A stable reference to an arena slot. +/// +/// Reclaimed slots increment their generation so stale handles cannot access a +/// new object allocated in the same slot. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub(crate) struct Handle { + index: u32, + generation: NonZeroU32, +} + +/// Adds the handles referenced by an arena object to the mark worklist. +pub(crate) trait Trace { + /// Calls `mark` for every arena object referenced by this object. + fn trace(&self, mark: &mut impl FnMut(Handle)); +} + +/// An arena allocation or capacity error. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct AllocError; + +impl core::fmt::Display for AllocError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("GC arena capacity exhausted") + } +} + +impl core::error::Error for AllocError {} + +#[inline] +fn mark(slots: &[Slot], worklist: &mut Vec, handle: Handle) { + let Some(slot) = slots.get(handle.index as usize) else { + return; + }; + if slot.generation != handle.generation || !matches!(slot.state, SlotState::Occupied { .. }) || slot.marked.get() { + return; + } + slot.marked.set(true); + worklist.push(handle.index); +} + +struct Slot { + generation: NonZeroU32, + marked: Cell, + state: SlotState, +} + +enum SlotState { + Occupied { value: T, bytes: usize }, + Free { next: Option }, + Retired, +} + +/// A mark-and-sweep arena with stable generational handles. +pub(crate) struct Arena { + slots: Vec>, + free_head: Option, + worklist: Vec, + len: usize, + allocated_bytes: usize, + collection_threshold: usize, + next_collection: usize, +} + +impl Arena { + /// Creates an empty arena with the given initial collection threshold. + pub(crate) const fn new(collection_threshold: usize) -> Self { + Self { + slots: Vec::new(), + free_head: None, + worklist: Vec::new(), + len: 0, + allocated_bytes: 0, + collection_threshold, + next_collection: collection_threshold, + } + } + + /// Allocates a value with `out_of_line_bytes` of storage owned outside its slot. + /// + /// The byte count must remain valid while the value is in the arena. + pub(crate) fn alloc(&mut self, value: T, out_of_line_bytes: usize) -> Result { + let bytes = size_of::>().checked_add(out_of_line_bytes).ok_or(AllocError)?; + let allocated_bytes = self.allocated_bytes.checked_add(bytes).ok_or(AllocError)?; + + let handle = if let Some(index) = self.free_head { + let slot = &mut self.slots[index as usize]; + let SlotState::Free { next } = slot.state else { unreachable!("free list points to an occupied slot") }; + self.free_head = next; + slot.marked.set(false); + slot.state = SlotState::Occupied { value, bytes }; + Handle { index, generation: slot.generation } + } else { + if self.slots.len() >= u32::MAX as usize { + return Err(AllocError); + } + let index = self.slots.len() as u32; + self.slots.try_reserve(1).map_err(|_| AllocError)?; + self.slots.push(Slot { + generation: NonZeroU32::MIN, + marked: Cell::new(false), + state: SlotState::Occupied { value, bytes }, + }); + Handle { index, generation: NonZeroU32::MIN } + }; + + self.len += 1; + self.allocated_bytes = allocated_bytes; + Ok(handle) + } + + /// Returns a shared reference if the handle is live and current. + pub(crate) fn get(&self, handle: Handle) -> Option<&T> { + let slot = self.slots.get(handle.index as usize)?; + if slot.generation != handle.generation { + return None; + } + match &slot.state { + SlotState::Occupied { value, .. } => Some(value), + SlotState::Free { .. } | SlotState::Retired => None, + } + } + + /// Returns an exclusive reference if the handle is live and current. + pub(crate) fn get_mut(&mut self, handle: Handle) -> Option<&mut T> { + let slot = self.slots.get_mut(handle.index as usize)?; + if slot.generation != handle.generation { + return None; + } + match &mut slot.state { + SlotState::Occupied { value, .. } => Some(value), + SlotState::Free { .. } | SlotState::Retired => None, + } + } + + /// Returns whether an allocation of this size should trigger collection. + pub(crate) fn should_collect(&self, out_of_line_bytes: usize) -> bool { + size_of::>() + .checked_add(out_of_line_bytes) + .and_then(|bytes| self.allocated_bytes.checked_add(bytes)) + .is_none_or(|bytes| bytes >= self.next_collection) + } +} + +impl Arena { + /// Collects objects that cannot be reached from `roots`. + pub(crate) fn collect(&mut self, roots: impl IntoIterator) -> Result<(), AllocError> { + self.worklist.clear(); + self.worklist.try_reserve(self.len).map_err(|_| AllocError)?; + + for root in roots { + mark(&self.slots, &mut self.worklist, root); + } + + while let Some(index) = self.worklist.pop() { + let slots = &self.slots; + let worklist = &mut self.worklist; + let SlotState::Occupied { value, .. } = &slots[index as usize].state else { + unreachable!("marked slots are occupied") + }; + value.trace(&mut |handle| mark(slots, worklist, handle)); + } + + let mut live_objects = 0; + let mut live_bytes = 0; + for (index, slot) in self.slots.iter_mut().enumerate() { + let SlotState::Occupied { bytes, .. } = &slot.state else { + continue; + }; + if slot.marked.replace(false) { + live_objects += 1; + live_bytes += bytes; + continue; + } + + if let Some(generation) = slot.generation.checked_add(1) { + slot.generation = generation; + slot.state = SlotState::Free { next: self.free_head }; + self.free_head = Some(index as u32); + } else { + slot.state = SlotState::Retired; + } + } + + self.len = live_objects; + self.allocated_bytes = live_bytes; + self.next_collection = live_bytes.saturating_mul(2).max(self.collection_threshold); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloc::vec; + + struct Object(Vec); + + impl Trace for Object { + fn trace(&self, mark: &mut impl FnMut(Handle)) { + for &handle in &self.0 { + mark(handle); + } + } + } + + #[test] + fn reuses_slots_and_rejects_stale_handles() { + let mut arena = Arena::new(1024); + let stale = arena.alloc(Object(vec![]), 0).unwrap(); + + arena.collect([]).unwrap(); + let current = arena.alloc(Object(vec![]), 0).unwrap(); + + assert_eq!(stale.index, current.index); + assert_ne!(stale.generation, current.generation); + assert!(arena.get(stale).is_none()); + assert!(arena.get(current).is_some()); + } + + #[test] + fn keeps_reachable_cycles() { + let mut arena = Arena::new(1024); + let first = arena.alloc(Object(Vec::with_capacity(1)), size_of::()).unwrap(); + let second = arena.alloc(Object(vec![first]), size_of::()).unwrap(); + arena.get_mut(first).unwrap().0.push(second); + + arena.collect([first]).unwrap(); + + assert_eq!(arena.len, 2); + assert_eq!(arena.allocated_bytes, size_of::>() * 2 + size_of::() * 2); + assert_eq!(arena.get(second).unwrap().0, [first]); + } + + #[test] + fn reclaims_unreachable_cycles() { + let mut arena = Arena::new(1024); + let first = arena.alloc(Object(Vec::with_capacity(1)), size_of::()).unwrap(); + let second = arena.alloc(Object(vec![first]), size_of::()).unwrap(); + arena.get_mut(first).unwrap().0.push(second); + + arena.collect([]).unwrap(); + + assert_eq!(arena.len, 0); + assert_eq!(arena.allocated_bytes, 0); + } + + #[test] + fn accounts_for_object_storage() { + let mut arena = Arena::new(1024); + let root = arena.alloc(Object(vec![]), 24).unwrap(); + + arena.collect([root]).unwrap(); + + assert_eq!(arena.allocated_bytes, size_of::>() + 24); + } +} diff --git a/crates/tinywasm/src/store/gc/mod.rs b/crates/tinywasm/src/store/gc/mod.rs new file mode 100644 index 0000000..2a87a5f --- /dev/null +++ b/crates/tinywasm/src/store/gc/mod.rs @@ -0,0 +1,92 @@ +mod arena; +mod object; + +use alloc::vec::Vec; +use tinywasm_types::{StorageType, WasmType}; + +use crate::Trap; +use crate::interpreter::stack::ValueStack; +use crate::interpreter::{InternalValue, TinyWasmValue, Value128, ValueRef}; + +pub(crate) use arena::{AllocError, Arena, Handle, Trace}; +pub(crate) use object::{GcHeap, GcObject}; + +/// Returns the zero value for a GC field or array element. +pub(crate) fn default_value(storage: StorageType) -> TinyWasmValue { + match storage { + StorageType::I8 | StorageType::I16 | StorageType::Value(WasmType::I32 | WasmType::F32) => { + TinyWasmValue::Value32(0) + } + StorageType::Value(WasmType::I64 | WasmType::F64) => TinyWasmValue::Value64(0), + StorageType::Value(WasmType::V128) => TinyWasmValue::Value128(Value128::from([0; 16])), + StorageType::Value(WasmType::Ref(_)) => TinyWasmValue::ValueRef(ValueRef::NULL), + } +} + +/// Pops and packs a GC field or array element from the operand stack. +pub(crate) fn pop_value(stack: &mut ValueStack, storage: StorageType) -> TinyWasmValue { + match storage { + StorageType::I8 => TinyWasmValue::Value32(i32::stack_pop(stack) as u8 as u32), + StorageType::I16 => TinyWasmValue::Value32(i32::stack_pop(stack) as u16 as u32), + StorageType::Value(WasmType::I32 | WasmType::F32) => TinyWasmValue::Value32(u32::stack_pop(stack)), + StorageType::Value(WasmType::I64 | WasmType::F64) => TinyWasmValue::Value64(u64::stack_pop(stack)), + StorageType::Value(WasmType::V128) => TinyWasmValue::Value128(Value128::stack_pop(stack)), + StorageType::Value(WasmType::Ref(_)) => TinyWasmValue::ValueRef(ValueRef::stack_pop(stack)), + } +} + +/// Extends a packed value and pushes it onto the operand stack. +pub(crate) fn push_value( + stack: &mut ValueStack, + value: TinyWasmValue, + storage: StorageType, + signed: Option, +) -> Result<(), Trap> { + let value = match (value, storage, signed) { + (TinyWasmValue::Value32(value), StorageType::I8, Some(true)) => { + TinyWasmValue::Value32(value as i8 as i32 as u32) + } + (TinyWasmValue::Value32(value), StorageType::I16, Some(true)) => { + TinyWasmValue::Value32(value as i16 as i32 as u32) + } + (TinyWasmValue::Value32(value), StorageType::I8, Some(false)) => TinyWasmValue::Value32(value & u8::MAX as u32), + (TinyWasmValue::Value32(value), StorageType::I16, Some(false)) => { + TinyWasmValue::Value32(value & u16::MAX as u32) + } + (value, _, None) => value, + _ => unreachable!("validated packed field access"), + }; + stack.push_dyn(value) +} + +/// Decodes numeric array elements from a data segment. +pub(crate) fn decode_data( + storage: StorageType, + data: &[u8], + src: usize, + len: usize, +) -> Result, Trap> { + let width = match storage { + StorageType::I8 => 1, + StorageType::I16 => 2, + StorageType::Value(WasmType::I32 | WasmType::F32) => 4, + StorageType::Value(WasmType::I64 | WasmType::F64) => 8, + StorageType::Value(WasmType::V128) => 16, + StorageType::Value(WasmType::Ref(_)) => unreachable!("array.new_data reference element"), + }; + let Some(end) = len.checked_mul(width).and_then(|bytes| src.checked_add(bytes)).filter(|&end| end <= data.len()) + else { + return Err(Trap::MemoryOutOfBounds { offset: src, len: len.saturating_mul(width), max: data.len() }); + }; + let mut values = Vec::new(); + values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?; + values.extend(data[src..end].chunks_exact(width).map(|bytes| match width { + 1 => TinyWasmValue::Value32(u32::from(bytes[0])), + 2 => TinyWasmValue::Value32(u32::from(u16::from_le_bytes(bytes.try_into().unwrap()))), + 4 => TinyWasmValue::Value32(u32::from_le_bytes(bytes.try_into().unwrap())), + 8 => TinyWasmValue::Value64(u64::from_le_bytes(bytes.try_into().unwrap())), + 16 => TinyWasmValue::Value128(Value128::from(<[u8; 16]>::try_from(bytes).unwrap())), + _ => unreachable!(), + })); + Ok(values) +} diff --git a/crates/tinywasm/src/store/gc/object.rs b/crates/tinywasm/src/store/gc/object.rs new file mode 100644 index 0000000..a3c5440 --- /dev/null +++ b/crates/tinywasm/src/store/gc/object.rs @@ -0,0 +1,218 @@ +use alloc::{boxed::Box, vec::Vec}; +use core::cell::RefCell; +use core::mem::size_of; +use core::sync::atomic::{AtomicU32, Ordering}; + +use tinywasm_types::TypeAddr; + +use crate::interpreter::{TinyWasmValue, ValueRef}; + +use super::{AllocError, Arena, Handle, Trace}; + +static NEXT_GC_REF: AtomicU32 = AtomicU32::new(0); + +pub(crate) struct GcObject { + pub(crate) type_addr: TypeAddr, + pub(crate) values: Box<[TinyWasmValue]>, + references: Option]>>, +} + +impl Trace for GcObject { + fn trace(&self, mark: &mut impl FnMut(Handle)) { + if let Some(references) = &self.references { + references.iter().flatten().copied().for_each(mark); + } + } +} + +pub(crate) struct GcHeap { + objects: Arena, + directory: Vec<(u32, Handle)>, + pinned: RefCell>, +} + +impl Default for GcHeap { + fn default() -> Self { + Self::new(1024 * 1024) + } +} + +impl GcHeap { + /// Creates a heap with the configured allocation threshold. + pub(crate) const fn new(collection_threshold: usize) -> Self { + Self { objects: Arena::new(collection_threshold), directory: Vec::new(), pinned: RefCell::new(Vec::new()) } + } + + #[inline] + /// Resolves a compact reference to its generation-checked arena handle. + pub(crate) fn handle(&self, value: ValueRef) -> Option { + let key = value.addr()?; + let index = self.directory.binary_search_by_key(&key, |entry| entry.0).ok()?; + Some(self.directory[index].1) + } + + #[inline] + pub(crate) fn get(&self, value: ValueRef) -> Option<&GcObject> { + self.objects.get(self.handle(value)?) + } + + #[inline] + pub(crate) fn get_mut(&mut self, value: ValueRef) -> Option<&mut GcObject> { + self.objects.get_mut(self.handle(value)?) + } + + /// Allocates an object and returns its compact runtime reference. + pub(crate) fn alloc( + &mut self, + type_addr: TypeAddr, + values: Vec, + trace_references: bool, + ) -> Result { + let key = + NEXT_GC_REF.try_update(Ordering::Relaxed, Ordering::Relaxed, |key| (key < (1 << 30)).then_some(key + 1)); + let Ok(key) = key else { + return Err(AllocError); + }; + let references = if trace_references { + let mut references = Vec::new(); + references.try_reserve_exact(values.len()).map_err(|_| AllocError)?; + references.extend(values.iter().map(|value| match value { + TinyWasmValue::ValueRef(value) => self.handle(*value), + _ => None, + })); + Some(references.into_boxed_slice()) + } else { + None + }; + let element_size = size_of::() + if trace_references { size_of::>() } else { 0 }; + let out_of_line_bytes = values.len().checked_mul(element_size).ok_or(AllocError)?; + let object = GcObject { type_addr, values: values.into_boxed_slice(), references }; + self.directory.try_reserve(1).map_err(|_| AllocError)?; + let handle = self.objects.alloc(object, out_of_line_bytes)?; + self.directory.push((key, handle)); + Ok(ValueRef::from_category_addr(key)) + } + + pub(crate) fn set(&mut self, object: ValueRef, index: usize, value: TinyWasmValue) -> Option<()> { + let reference = value.as_ref().and_then(|value| self.handle(value)); + let object = self.get_mut(object)?; + *object.values.get_mut(index)? = value; + if let Some(references) = &mut object.references { + references[index] = reference; + } + Some(()) + } + + /// Replaces a contiguous range and updates its traced references. + pub(crate) fn set_slice(&mut self, object: ValueRef, index: usize, values: &[TinyWasmValue]) -> Option<()> { + let object_handle = self.handle(object)?; + let end = index.checked_add(values.len())?; + let directory = &self.directory; + let object = self.objects.get_mut(object_handle)?; + object.values.get_mut(index..end)?.copy_from_slice(values); + if let Some(references) = &mut object.references { + for (reference, value) in references[index..end].iter_mut().zip(values) { + *reference = value.as_ref().and_then(|value| { + let key = value.addr()?; + let index = directory.binary_search_by_key(&key, |entry| entry.0).ok()?; + Some(directory[index].1) + }); + } + } + Some(()) + } + + /// Fills a contiguous range and updates its traced references. + pub(crate) fn fill( + &mut self, + object: ValueRef, + range: core::ops::Range, + value: TinyWasmValue, + ) -> Option<()> { + let reference = value.as_ref().and_then(|value| self.handle(value)); + let object = self.get_mut(object)?; + object.values.get_mut(range.clone())?.fill(value); + if let Some(references) = &mut object.references { + references[range].fill(reference); + } + Some(()) + } + + pub(crate) fn should_collect(&self, value_count: usize, trace_references: bool) -> bool { + let element_size = size_of::() + if trace_references { size_of::>() } else { 0 }; + let bytes = value_count.saturating_mul(element_size); + self.objects.should_collect(bytes) + } + + /// Reclaims objects unreachable from runtime and permanent host roots. + pub(crate) fn collect(&mut self, roots: impl IntoIterator) -> Result<(), AllocError> { + let pinned = self.pinned.borrow(); + let directory = &self.directory; + let root_handles = roots.into_iter().filter_map(|value| { + let key = value.addr()?; + Some(directory.get(directory.binary_search_by_key(&key, |entry| entry.0).ok()?)?.1) + }); + self.objects.collect(pinned.iter().copied().chain(root_handles))?; + drop(pinned); + self.directory.retain(|(_, handle)| self.objects.get(*handle).is_some()); + Ok(()) + } + + /// Permanently roots a managed reference exposed through the copyable host API. + pub(crate) fn pin(&self, value: ValueRef) { + if let Some(handle) = self.handle(value) { + let mut pinned = self.pinned.borrow_mut(); + if let Err(index) = pinned.binary_search(&handle) { + pinned.insert(index, handle); + } + } + } + + pub(crate) fn copy_within(&mut self, object: ValueRef, src: core::ops::Range, dst: usize) -> Option<()> { + let object = self.get_mut(object)?; + object.values.copy_within(src.clone(), dst); + if let Some(references) = &mut object.references { + references.copy_within(src, dst); + } + Some(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compact_keys_are_not_reused_after_collection() { + let mut heap = GcHeap::default(); + let stale = heap.alloc(0, Vec::new(), false).unwrap(); + heap.collect([]).unwrap(); + let current = heap.alloc(0, Vec::new(), false).unwrap(); + + assert_ne!(stale, current); + assert!(heap.get(stale).is_none()); + assert!(heap.get(current).is_some()); + } + + #[test] + fn compact_keys_do_not_resolve_in_another_heap() { + let mut first = GcHeap::default(); + let second = GcHeap::default(); + let value = first.alloc(0, Vec::new(), false).unwrap(); + + assert!(second.get(value).is_none()); + } + + #[test] + fn collection_reclaims_object_cycles() { + let mut heap = GcHeap::default(); + let first = heap.alloc(0, alloc::vec![TinyWasmValue::ValueRef(ValueRef::NULL)], true).unwrap(); + let second = heap.alloc(0, alloc::vec![TinyWasmValue::ValueRef(first)], true).unwrap(); + heap.set(first, 0, TinyWasmValue::ValueRef(second)).unwrap(); + + heap.collect([]).unwrap(); + + assert!(heap.get(first).is_none()); + assert!(heap.get(second).is_none()); + } +} diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 517a561..84c4033 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -1,4 +1,3 @@ -use alloc::sync::Arc; use alloc::{boxed::Box, format, vec::Vec}; use core::hint::cold_path; use core::sync::atomic::{AtomicUsize, Ordering}; @@ -11,36 +10,29 @@ use crate::{Engine, Error, ModuleInstance, Result, Trap}; mod data; mod element; mod function; +mod gc; mod global; mod memory; +mod state; mod table; +mod types; +pub(crate) use gc::{decode_data, default_value, pop_value, push_value}; pub use memory::{LazyLinearMemory, LinearMemory, MemoryBackend, PagedMemory, VecMemory}; pub(crate) use memory::{MemValue, MemoryInstance}; +pub(crate) use state::State; +pub(crate) use types::{canonicalize_ref_type, canonicalize_value_type}; pub(crate) use {data::*, element::*, function::*, global::*, table::*}; // global store id counter static STORE_ID: AtomicUsize = AtomicUsize::new(0); -pub(crate) fn canonicalize_ref_type(ty: RefType, type_addrs: &[TypeAddr]) -> RefType { - let Some(type_addr) = ty.type_index() else { return ty }; - let canonical = - *type_addrs.get(type_addr as usize).unwrap_or_else(|| unreachable!("invalid type address: {type_addr}")); - RefType::new_concrete(ty.is_nullable(), canonical).unwrap() -} - -pub(crate) fn canonicalize_value_type(ty: WasmType, type_addrs: &[TypeAddr]) -> WasmType { - match ty { - WasmType::Ref(ty) => WasmType::Ref(canonicalize_ref_type(ty, type_addrs)), - ty => ty, - } -} - /// Global state that can be manipulated by WebAssembly programs /// -/// Note that the state doesn't do any garbage collection - so it will grow -/// indefinitely if you keep adding modules to it. When calling temporary -/// functions, you should create a new store and then drop it when you're done (e.g. in a request handler). +/// Managed WebAssembly GC objects are collected automatically. Other Store +/// instances, such as modules, functions, memories, and tables, live until the +/// Store is dropped. GC references exposed through the copyable host value API +/// are retained for the Store's lifetime. /// /// ## Example /// ```rust @@ -80,10 +72,11 @@ impl Store { /// Create a new store pub fn new(engine: Engine) -> Self { let id = STORE_ID.fetch_add(1, Ordering::Relaxed); + let state = State { gc: gc::GcHeap::new(engine.config().gc_collection_threshold), ..State::default() }; Self { id, module_instances: Vec::new(), - state: State::default(), + state, call_stack: CallStack::new(engine.config()), value_stack: ValueStack::new(engine.config()), engine, @@ -130,140 +123,6 @@ impl Default for Store { } } -#[derive(Default)] -/// Global state that can be manipulated by WebAssembly programs -/// -/// Data should only be addressable by the module that owns it -/// See -pub(crate) struct State { - // Concrete type indexes in store instances address this canonical type space. - canonical_types: Vec, - pub(crate) funcs: Vec, - pub(crate) tables: Vec, - pub(crate) memories: Vec, - pub(crate) globals: Vec, - pub(crate) elements: Vec, - pub(crate) data: Vec, -} - -impl State { - pub(crate) fn value_matches_type(&self, value: WasmValue, expected: WasmType) -> bool { - match (value, expected) { - (WasmValue::Ref(RefValue::Null), WasmType::Ref(expected)) => expected.is_nullable(), - (WasmValue::Ref(RefValue::Func(func)), WasmType::Ref(expected)) => { - self.funcs.get(func.addr() as usize).is_some_and(|func| match expected.type_index() { - Some(expected) => func.type_addr == expected, - None => matches!(expected.abstract_heap_type(), Some(AbstractHeapType::Func)), - }) - } - (_, WasmType::Ref(expected)) if expected.is_concrete() => false, - _ => value.matches_type(expected), - } - } - - #[inline] - pub(crate) fn get_func_type(&self, addr: FuncAddr) -> &FuncType { - let type_addr = self.get_func(addr).type_addr; - Self::get(&self.canonical_types, type_addr, "canonical type") - } - - #[inline] - pub(crate) fn get_type(&self, addr: TypeAddr) -> &FuncType { - Self::get(&self.canonical_types, addr, "canonical type") - } - fn get<'a, T>(items: &'a [T], addr: Addr, kind: &str) -> &'a T { - items.get(addr as usize).unwrap_or_else(|| unreachable!("invalid {kind} address: {addr}")) - } - - fn get_mut<'a, T>(items: &'a mut [T], addr: Addr, kind: &str) -> &'a mut T { - items.get_mut(addr as usize).unwrap_or_else(|| unreachable!("invalid {kind} address: {addr}")) - } - - fn get_disjoint_mut<'a, T>(items: &'a mut [T], addr: Addr, addr2: Addr, kind: &str) -> (&'a mut T, &'a mut T) { - let [item_a, item_b] = items - .get_disjoint_mut([addr as usize, addr2 as usize]) - .unwrap_or_else(|_| unreachable!("invalid {kind} addresses: {addr}, {addr2}")); - (item_a, item_b) - } - - /// Get the function at the actual index in the store - pub(crate) fn get_func(&self, addr: FuncAddr) -> &FunctionInstance { - Self::get(&self.funcs, addr, "function") - } - - /// Get a wasm function at the actual index in the store, panicking if it's a host function (which should be guaranteed by the validator) - pub(crate) fn get_wasm_func(&self, addr: FuncAddr) -> &WasmFunctionInstance { - match self.funcs.get(addr as usize).map(|func| &func.kind) { - Some(FunctionKind::Wasm(wasm_func)) => wasm_func, - _ => unreachable!("invalid wasm function address: {addr}"), - } - } - - /// Get the memory at the actual index in the store - pub(crate) fn get_mem(&self, addr: MemAddr) -> &MemoryInstance { - Self::get(&self.memories, addr, "memory") - } - - /// Get the memory at the actual index in the store - pub(crate) fn get_mem_mut(&mut self, addr: MemAddr) -> &mut MemoryInstance { - Self::get_mut(&mut self.memories, addr, "memory") - } - - /// Get the memory at the actual index in the store - pub(crate) fn get_mems_mut(&mut self, addr: MemAddr, addr2: MemAddr) -> (&mut MemoryInstance, &mut MemoryInstance) { - Self::get_disjoint_mut(&mut self.memories, addr, addr2, "memory") - } - - /// Get the table at the actual index in the store - pub(crate) fn get_table(&self, addr: TableAddr) -> &TableInstance { - Self::get(&self.tables, addr, "table") - } - - /// Get the table at the actual index in the store - pub(crate) fn get_table_mut(&mut self, addr: TableAddr) -> &mut TableInstance { - Self::get_mut(&mut self.tables, addr, "table") - } - - /// Get two mutable tables at the actual index in the store - pub(crate) fn get_tables_mut( - &mut self, - addr: TableAddr, - addr2: TableAddr, - ) -> (&mut TableInstance, &mut TableInstance) { - Self::get_disjoint_mut(&mut self.tables, addr, addr2, "table") - } - - /// Get the data at the actual index in the store - pub(crate) fn get_data_mut(&mut self, addr: DataAddr) -> &mut DataInstance { - Self::get_mut(&mut self.data, addr, "data") - } - - /// Get the element at the actual index in the store - pub(crate) fn get_elem_mut(&mut self, addr: ElemAddr) -> &mut ElementInstance { - Self::get_mut(&mut self.elements, addr, "element") - } - - /// Get the global at the actual index in the store - pub(crate) fn get_global(&self, addr: GlobalAddr) -> &GlobalInstance { - Self::get(&self.globals, addr, "global") - } - - /// Get the global at the actual index in the store - pub(crate) fn get_global_mut(&mut self, addr: GlobalAddr) -> &mut GlobalInstance { - Self::get_mut(&mut self.globals, addr, "global") - } - - /// Get the global at the actual index in the store - pub(crate) fn get_global_val(&self, addr: GlobalAddr) -> TinyWasmValue { - self.get_global(addr).value - } - - /// Set the global at the actual index in the store - pub(crate) fn set_global_val(&mut self, addr: GlobalAddr, value: TinyWasmValue) { - self.get_global_mut(addr).value = value; - } -} - impl Store { /// Get the store's ID (unique per process) pub fn id(&self) -> usize { @@ -290,71 +149,31 @@ impl Store { pub fn set_global_val(&mut self, addr: GlobalAddr, value: TinyWasmValue) { self.state.set_global_val(addr, value); } -} - -// Linking related functions -impl Store { - pub(crate) fn register_module_types(&mut self, types: &[FuncType]) -> Box<[TypeAddr]> { - let mut type_addrs = Vec::with_capacity(types.len()); - for (local_addr, ty) in types.iter().enumerate() { - if let Some(addr) = self - .state - .canonical_types - .iter() - .position(|registered| ty.equivalent(types, registered, &self.state.canonical_types)) - { - type_addrs.push(addr as TypeAddr); - continue; - } - let addr = self.state.canonical_types.len(); - assert!(addr <= ((1 << 30) - 1), "too many canonical function types"); - type_addrs.push(addr as TypeAddr); - let canonicalize = |ty: WasmType| match ty { - WasmType::Ref(ty) if ty.is_concrete() => { - let module_ref = ty.type_index().unwrap() as usize; - // A singleton recursive group can refer to the type currently being registered. - let canonical = if module_ref == local_addr { - addr as TypeAddr - } else { - *type_addrs - .get(module_ref) - .unwrap_or_else(|| unreachable!("invalid forward type reference: {module_ref}")) - }; - WasmType::Ref(RefType::new_concrete(ty.is_nullable(), canonical).unwrap()) - } - ty => ty, - }; - let params = ty.params().iter().copied().map(canonicalize).collect::>(); - let results = ty.results().iter().copied().map(canonicalize).collect::>(); - self.state.canonical_types.push(FuncType::new(¶ms, &results)); - } - type_addrs.into_boxed_slice() - } - - pub(crate) fn register_host_type(&mut self, ty: &FuncType) -> TypeAddr { - if let Some(addr) = self.state.canonical_types.iter().position(|registered| ty == registered) { - return addr as TypeAddr; - } - let addr = self.state.canonical_types.len(); - assert!(addr <= ((1 << 30) - 1), "too many canonical function types"); - self.state.canonical_types.push(ty.clone()); - addr as TypeAddr + /// Returns whether a public value has the requested runtime type. + #[doc(hidden)] + pub fn value_matches_type(&self, value: WasmValue, ty: WasmType) -> bool { + self.state.value_matches_type(value, ty) } +} +impl Store { /// Add functions to the store, returning their addresses in the store pub(crate) fn init_funcs( &mut self, - funcs: &[Arc], + funcs: &[alloc::sync::Arc], owner: ModuleInstanceId, type_addrs: &[TypeAddr], ) -> impl ExactSizeIterator { let start = self.state.funcs.len() as FuncAddr; debug_assert_eq!(funcs.len(), type_addrs.len()); - self.state.funcs.extend(funcs.iter().zip(type_addrs).map(|(func, &type_addr)| FunctionInstance { - type_addr, - kind: FunctionKind::Wasm(WasmFunctionInstance { func: func.clone(), owner }), - })); + for (func, &type_addr) in funcs.iter().zip(type_addrs) { + self.state.funcs.push(FunctionInstance { + type_addr, + gc: self.state.func_gc_metadata(type_addr), + kind: FunctionKind::Wasm(WasmFunctionInstance { func: func.clone(), owner }), + }); + } start..start + funcs.len() as FuncAddr } @@ -370,11 +189,11 @@ impl Store { self.state.tables.reserve_exact(tables.len()); for table in tables { let init = match &table.init { - Some(expr) => match self.eval_const(expr, global_addrs, func_addrs)? { - TinyWasmValue::ValueRef(value) => TableElement::from(value.addr()), + Some(expr) => match self.eval_const(expr, global_addrs, func_addrs, type_addrs)? { + TinyWasmValue::ValueRef(value) => value, _ => return Err(Error::other("table initializer is not a reference value")), }, - None => TableElement::Uninitialized, + None => ValueRef::NULL, }; let element_type = canonicalize_ref_type(table.ty.element_type, type_addrs); let ty = match table.ty.arch() { @@ -417,7 +236,7 @@ impl Store { out.extend(start..start + globals.len() as Addr); for global in globals { - let value = match self.eval_const(&global.init, out, func_addrs) { + let value = match self.eval_const(&global.init, out, func_addrs, type_addrs) { Ok(val) => val, Err(e) => { cold_path(); @@ -431,17 +250,23 @@ impl Store { Ok(()) } - fn elem_addr(&self, item: &ElementItem, globals: &[Addr], funcs: &[FuncAddr]) -> Result> { + fn elem_value( + &mut self, + item: &ElementItem, + globals: &[Addr], + funcs: &[FuncAddr], + type_addrs: &[TypeAddr], + ) -> Result { match item { - ElementItem::Expr(expr) => match self.eval_const(expr, globals, funcs)? { - TinyWasmValue::ValueRef(v) => Ok(v.addr()), + ElementItem::Expr(expr) => match self.eval_const(expr, globals, funcs, type_addrs)? { + TinyWasmValue::ValueRef(value) => Ok(value), other => { cold_path(); Err(Error::Other(format!("expected ref type, got {other:?}"))) } }, ElementItem::Func(addr) => match funcs.get(*addr as usize) { - Some(func_addr) => Ok(Some(*func_addr)), + Some(func_addr) => Ok(ValueRef::from_category_addr(*func_addr)), None => { cold_path(); Err(Error::Other(format!( @@ -460,26 +285,31 @@ impl Store { func_addrs: &[FuncAddr], global_addrs: &[Addr], elements: &[Element], + type_addrs: &[TypeAddr], ) -> Result<(Box<[Addr]>, Option)> { let elem_count = self.state.elements.len(); - let mut elem_addrs = Vec::with_capacity(elem_count); + let mut elem_addrs = Vec::with_capacity(elements.len()); for (i, element) in elements.iter().enumerate() { - let init = element - .items - .iter() - .map(|item| Ok(TableElement::from(self.elem_addr(item, global_addrs, func_addrs)?))) - .collect::>>()?; + let elem_addr = self.state.elements.len(); + self.state.elements.push(ElementInstance { + items: Some(Vec::with_capacity(element.items.len())), + ty: canonicalize_ref_type(element.ty, type_addrs), + }); + for item in &element.items { + let value = self.elem_value(item, global_addrs, func_addrs, type_addrs)?; + self.state.elements[elem_addr].items.as_mut().unwrap().push(value); + } - let items = match &element.kind { + match &element.kind { // doesn't need to be initialized, can be initialized lazily using the `table.init` instruction - ElementKind::Passive => Some(init), + ElementKind::Passive => {} // this one is not available to the runtime but needs to be initialized to declare references - ElementKind::Declared => None, // a. Execute the instruction elm.drop i + ElementKind::Declared => self.state.elements[elem_addr].drop(), // this one is active, so we need to initialize it (essentially a `table.init` instruction) ElementKind::Active { offset, table } => { - let offset = self.eval_size_const(offset, global_addrs, func_addrs)?; + let offset = self.eval_size_const(offset, global_addrs, func_addrs, type_addrs)?; let table_addr = table_addrs .get(*table as usize) .copied() @@ -497,20 +327,26 @@ impl Store { let Ok(offset) = usize::try_from(offset) else { return Ok(( elem_addrs.into_boxed_slice(), - Some(Trap::TableOutOfBounds { offset: usize::MAX, len: init.len(), max: table.size() }), + Some(Trap::TableOutOfBounds { + offset: usize::MAX, + len: self.state.elements[elem_addr].items.as_ref().unwrap().len(), + max: table.size(), + }), )); }; - if let Err(trap) = table.init(offset, &init) { + let State { elements, tables, .. } = &mut self.state; + let init = elements[elem_addr].items.as_deref().unwrap(); + let table = &mut tables[table_addr as usize]; + if let Err(trap) = table.init(offset, init) { return Ok((elem_addrs.into_boxed_slice(), Some(trap))); } // f. Execute the instruction elm.drop i - None + elements[elem_addr].drop(); } - }; + } - self.state.elements.push(ElementInstance { items }); elem_addrs.push((i + elem_count) as Addr); } @@ -525,6 +361,7 @@ impl Store { global_addrs: &[Addr], func_addrs: &[FuncAddr], data: &[Data], + type_addrs: &[TypeAddr], ) -> Result<(Box<[Addr]>, Option)> { let data_count = self.state.data.len(); let mut data_addrs = Vec::with_capacity(data_count); @@ -535,7 +372,7 @@ impl Store { return Err(Error::Other(format!("memory {mem_addr} not found for data segment {i}"))); }; - let offset = self.eval_size_const(offset, global_addrs, func_addrs)?; + let offset = self.eval_size_const(offset, global_addrs, func_addrs, type_addrs)?; let Some(mem) = self.state.memories.get_mut(*mem_addr as usize) else { return Err(Error::Other(format!("memory {mem_addr} not found for data segment {i}"))); }; @@ -573,12 +410,13 @@ impl Store { /// Evaluate a constant expression that's either a i32 or a i64 as a global or a const instruction fn eval_size_const( - &self, + &mut self, const_instrs: &[tinywasm_types::ConstInstruction], module_global_addrs: &[Addr], module_func_addrs: &[FuncAddr], + module_type_addrs: &[TypeAddr], ) -> Result { - let value = self.eval_const(const_instrs, module_global_addrs, module_func_addrs)?; + let value = self.eval_const(const_instrs, module_global_addrs, module_func_addrs, module_type_addrs)?; match value { TinyWasmValue::Value32(i) => Ok(u64::from(i)), TinyWasmValue::Value64(i) => Ok(i), @@ -589,61 +427,56 @@ impl Store { /// Evaluate a constant expression #[inline] fn eval_const( - &self, + &mut self, const_instrs: &[tinywasm_types::ConstInstruction], module_global_addrs: &[Addr], module_func_addrs: &[FuncAddr], + module_type_addrs: &[TypeAddr], ) -> Result { use tinywasm_types::ConstInstruction::*; - let resolve_global = |idx: u32| -> Result { - let Some(addr) = module_global_addrs.get(idx as usize) else { - cold_path(); - return Err(Error::Other(format!( - "global {idx} not found. This should have been caught by the validator" - ))); - }; - - let Some(global) = self.state.globals.get(*addr as usize) else { - cold_path(); - return Err(Error::Other(format!("global {addr} not found"))); - }; - - Ok(global.value) + let global_value = |state: &State, index: u32| -> Result { + let addr = *module_global_addrs + .get(index as usize) + .ok_or_else(|| Error::Other(format!("global {index} not found")))?; + Ok(state.globals.get(addr as usize).ok_or_else(|| Error::Other(format!("global {addr} not found")))?.value) }; - - let resolve_func = |idx: u32| -> Result { - match module_func_addrs.get(idx as usize) { - Some(func_addr) => Ok(*func_addr), - None => { - cold_path(); - Err(Error::Other(format!( - "function {idx} not found. This should have been caught by the validator" - ))) - } + let func_ref = |index: u32| -> Result { + let addr = *module_func_addrs + .get(index as usize) + .ok_or_else(|| Error::Other(format!("function {index} not found")))?; + Ok(ValueRef::from_category_addr(addr)) + }; + let type_addr = |index: TypeAddr| -> Result { + module_type_addrs.get(index as usize).copied().ok_or_else(|| Error::other("GC constant type not found")) + }; + let pop_value = |stack: &mut Vec, storage: StorageType| -> Result { + let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; + match (storage, value) { + (StorageType::I8, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u8 as u32)), + (StorageType::I16, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u16 as u32)), + (StorageType::Value(WasmType::I32 | WasmType::F32), value @ TinyWasmValue::Value32(_)) + | (StorageType::Value(WasmType::I64 | WasmType::F64), value @ TinyWasmValue::Value64(_)) + | (StorageType::Value(WasmType::V128), value @ TinyWasmValue::Value128(_)) + | (StorageType::Value(WasmType::Ref(_)), value @ TinyWasmValue::ValueRef(_)) => Ok(value), + _ => Err(Error::other("type mismatch in GC constant")), } }; - if const_instrs.len() == 1 { - let val = match &const_instrs[0] { - F32Const(f) => (*f).into(), - F64Const(f) => (*f).into(), - I32Const(i) => (*i).into(), - I64Const(i) => (*i).into(), - V128Const(i) => (*i).into(), - GlobalGet(addr) => resolve_global(*addr)?, - Ref(tinywasm_types::RefValue::Null) => TinyWasmValue::ValueRef(ValueRef::NULL), + if let [instr] = const_instrs { + match instr { + I32Const(value) => return Ok(TinyWasmValue::Value32(*value as u32)), + I64Const(value) => return Ok(TinyWasmValue::Value64(*value as u64)), + F32Const(value) => return Ok(TinyWasmValue::Value32(value.to_bits())), + F64Const(value) => return Ok(TinyWasmValue::Value64(value.to_bits())), + V128Const(value) => return Ok(TinyWasmValue::Value128((*value).into())), + GlobalGet(index) => return global_value(&self.state, *index), + Ref(tinywasm_types::RefValue::Null) => return Ok(TinyWasmValue::ValueRef(ValueRef::NULL)), Ref(tinywasm_types::RefValue::Func(func)) => { - TinyWasmValue::ValueRef(ValueRef::from_raw(resolve_func(func.addr())?)) - } - Ref(_) => return Err(Error::other("unsupported reference constant")), - _ => { - cold_path(); - return Err(Error::other("unsupported const instruction")); + return Ok(TinyWasmValue::ValueRef(func_ref(func.addr())?)); } - }; - - return Ok(val); + _ => {} + } } let mut stack = Vec::new(); @@ -654,15 +487,96 @@ impl Store { F32Const(f) => stack.push(TinyWasmValue::Value32(f.to_bits())), F64Const(f) => stack.push(TinyWasmValue::Value64(f.to_bits())), V128Const(i) => stack.push(TinyWasmValue::Value128((*i).into())), - GlobalGet(addr) => stack.push(resolve_global(*addr)?), + GlobalGet(index) => stack.push(global_value(&self.state, *index)?), Ref(tinywasm_types::RefValue::Null) => stack.push(TinyWasmValue::ValueRef(ValueRef::NULL)), Ref(tinywasm_types::RefValue::Func(func)) => { - stack.push(TinyWasmValue::ValueRef(ValueRef::from_raw(resolve_func(func.addr())?))) + stack.push(TinyWasmValue::ValueRef(func_ref(func.addr())?)) } Ref(_) => { cold_path(); return Err(Error::other("unsupported reference constant")); } + RefI31 => { + let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; + let TinyWasmValue::Value32(value) = value else { + return Err(Error::other("type mismatch in const ref.i31")); + }; + stack.push(TinyWasmValue::ValueRef(ValueRef::from_i31(value as i32))); + } + AnyConvertExtern | ExternConvertAny => { + let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; + if !matches!(value, TinyWasmValue::ValueRef(_)) { + return Err(Error::other("type mismatch in const reference conversion")); + } + stack.push(value); + } + StructNew(type_index) | StructNewDefault(type_index) => { + let type_addr = type_addr(*type_index)?; + let fields = self + .state + .get_type(type_addr) + .as_struct() + .ok_or_else(|| Error::other("GC constant type is not a struct"))? + .fields + .clone(); + let default = matches!(instr, StructNewDefault(_)); + let mut values = Vec::new(); + values.try_reserve_exact(fields.len()).map_err(|_| Trap::OutOfMemory)?; + if default { + values.extend(fields.iter().map(|field| default_value(field.storage))); + } else { + for field in fields.iter().rev() { + values.push(pop_value(&mut stack, field.storage)?); + } + values.reverse(); + } + let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw); + let reference = self.state.alloc_gc_object(type_addr, values, roots)?; + stack.push(TinyWasmValue::ValueRef(reference)); + } + ArrayNew(type_index) | ArrayNewDefault(type_index) => { + let type_addr = type_addr(*type_index)?; + let storage = self + .state + .get_type(type_addr) + .as_array() + .ok_or_else(|| Error::other("GC constant type is not an array"))? + .field + .storage; + let Some(TinyWasmValue::Value32(len)) = stack.pop() else { + return Err(Error::other("type mismatch in const array length")); + }; + let value = if matches!(instr, ArrayNewDefault(_)) { + default_value(storage) + } else { + pop_value(&mut stack, storage)? + }; + let mut values = Vec::new(); + values.try_reserve_exact(len as usize).map_err(|_| Trap::OutOfMemory)?; + values.resize(len as usize, value); + let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw); + let reference = self.state.alloc_gc_object(type_addr, values, roots)?; + stack.push(TinyWasmValue::ValueRef(reference)); + } + ArrayNewFixed(type_index, len) => { + let type_addr = type_addr(*type_index)?; + let storage = self + .state + .get_type(type_addr) + .as_array() + .ok_or_else(|| Error::other("GC constant type is not an array"))? + .field + .storage; + let mut values = Vec::new(); + values.try_reserve_exact(*len as usize).map_err(|_| Trap::OutOfMemory)?; + for _ in 0..*len { + values.push(pop_value(&mut stack, storage)?); + } + values.reverse(); + let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw); + let reference = self.state.alloc_gc_object(type_addr, values, roots)?; + stack.push(TinyWasmValue::ValueRef(reference)); + } I32Add | I32Sub | I32Mul => { let rhs = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; let lhs = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs new file mode 100644 index 0000000..125cc30 --- /dev/null +++ b/crates/tinywasm/src/store/state.rs @@ -0,0 +1,385 @@ +use alloc::vec::Vec; + +use super::*; + +#[derive(Default)] +/// Global state that can be manipulated by WebAssembly programs +/// +/// Data should only be addressable by the module that owns it +/// See +pub(crate) struct State { + // Concrete type indexes in store instances address this canonical type space. + pub(crate) canonical_types: Vec, + pub(crate) canonical_rec_group_lengths: Vec, + pub(crate) funcs: Vec, + pub(crate) tables: Vec, + pub(crate) memories: Vec, + pub(crate) globals: Vec, + pub(crate) elements: Vec, + pub(crate) data: Vec, + pub(crate) gc: gc::GcHeap, +} + +impl State { + /// Returns whether values of this type can contain a managed GC object. + pub(crate) fn type_may_contain_gc(&self, ty: WasmType) -> bool { + Self::type_may_contain_gc_in(&self.canonical_types, ty) + } + + fn type_may_contain_gc_in(types: &[SubType], ty: WasmType) -> bool { + let WasmType::Ref(ty) = ty else { return false }; + if let Some(type_addr) = ty.type_index() { + return matches!(types[type_addr as usize].composite, CompositeType::Struct(_) | CompositeType::Array(_)); + } + matches!( + ty.abstract_heap_type(), + Some( + AbstractHeapType::Any + | AbstractHeapType::Eq + | AbstractHeapType::Struct + | AbstractHeapType::Array + | AbstractHeapType::Extern + ) + ) + } + + /// Precomputes whether a canonical function signature can carry GC objects. + pub(crate) fn func_gc_metadata(&self, type_addr: TypeAddr) -> FunctionGcMetadata { + let ty = self.get_canonical_func_type(type_addr); + FunctionGcMetadata { + params: ty.params().iter().copied().any(|ty| self.type_may_contain_gc(ty)), + results: ty.results().iter().copied().any(|ty| self.type_may_contain_gc(ty)), + } + } + + /// Allocates an object, collecting from all runtime roots when needed. + pub(crate) fn alloc_gc_object( + &mut self, + type_addr: TypeAddr, + values: Vec, + stack_32: impl IntoIterator, + ) -> Result { + let trace_references = match &self.get_type(type_addr).composite { + CompositeType::Struct(ty) => { + ty.fields.iter().any(|field| matches!(field.storage, StorageType::Value(WasmType::Ref(_)))) + } + CompositeType::Array(ty) => matches!(ty.field.storage, StorageType::Value(WasmType::Ref(_))), + CompositeType::Func(_) => unreachable!("GC object type is not a function"), + }; + if self.gc.should_collect(values.len(), trace_references) { + let canonical_types = &self.canonical_types; + let roots = stack_32 + .into_iter() + .map(ValueRef::from_raw) + .chain( + self.globals + .iter() + .filter(|global| Self::type_may_contain_gc_in(canonical_types, global.ty.ty)) + .filter_map(|global| global.value.as_ref()), + ) + .chain( + self.tables + .iter() + .filter(|table| { + Self::type_may_contain_gc_in(canonical_types, WasmType::Ref(table.kind.element_type)) + }) + .flat_map(|table| table.elements.iter().copied()), + ) + .chain( + self.elements + .iter() + .filter(|element| Self::type_may_contain_gc_in(canonical_types, WasmType::Ref(element.ty))) + .flat_map(|element| element.items.iter().flatten().copied()), + ) + .chain(values.iter().filter_map(|value| value.as_ref())); + self.gc.collect(roots).map_err(|_| Trap::OutOfMemory)?; + } + self.gc.alloc(type_addr, values, trace_references).map_err(|_| Trap::OutOfMemory) + } + + /// Pins a host-visible reference when it resolves to a managed GC object. + pub(crate) fn pin_host_ref(&self, value: RefValue) { + let raw = match value { + RefValue::Any(value) => value.raw(), + RefValue::Extern(value) => value.raw(), + RefValue::Null | RefValue::Func(_) | RefValue::Exn(_) => return, + }; + self.gc.pin(ValueRef::from_raw(raw)); + } + + /// Pins GC references that have crossed into host-visible values. + pub(crate) fn pin_host_values(&self, values: &[WasmValue]) { + for &value in values { + if let WasmValue::Ref(value) = value { + self.pin_host_ref(value); + } + } + } + + /// Resolves a non-null object of the expected canonical type. + pub(crate) fn gc_object(&self, reference: ValueRef, expected_type: TypeAddr) -> Result<&gc::GcObject, Trap> { + if reference.is_null() { + return Err(if self.get_type(expected_type).as_array().is_some() { + Trap::NullArrayReference + } else { + Trap::NullStructReference + }); + } + let object = self.gc.get(reference).ok_or(Trap::Other("invalid GC reference"))?; + if !self.type_addr_is_subtype(object.type_addr, expected_type) { + return Err(Trap::Other("GC reference type mismatch")); + } + Ok(object) + } + + /// Converts an internal value using canonical reference type information. + pub(crate) fn attach_value(&self, value: TinyWasmValue, ty: WasmType) -> Option { + if let (TinyWasmValue::ValueRef(value), WasmType::Ref(reference_type)) = (value, ty) + && let Some(type_addr) = reference_type.type_index() + { + if value.is_null() { + return Some(RefValue::Null.into()); + } + return match &self.get_type(type_addr).composite { + CompositeType::Func(_) => Some(RefValue::Func(FuncRef::new(value.addr()?)).into()), + CompositeType::Struct(_) | CompositeType::Array(_) => { + Some(RefValue::Any(AnyRef::from_raw(value.raw())).into()) + } + }; + } + value.attach_type(ty) + } + + /// Returns whether one canonical type is a subtype of another. + pub(crate) fn type_addr_is_subtype(&self, mut actual: TypeAddr, expected: TypeAddr) -> bool { + loop { + if actual == expected { + return true; + } + let Some(supertype) = self.get_type(actual).supertype else { return false }; + actual = supertype; + } + } + + /// Returns whether one reference type is a subtype of another. + pub(crate) fn ref_type_is_subtype(&self, actual: RefType, expected: RefType) -> bool { + if actual.is_nullable() && !expected.is_nullable() { + return false; + } + self.heap_type_is_subtype(actual, expected) + } + + /// Returns whether one value type is a subtype of another. + pub(crate) fn value_type_is_subtype(&self, actual: WasmType, expected: WasmType) -> bool { + match (actual, expected) { + (WasmType::Ref(actual), WasmType::Ref(expected)) => self.ref_type_is_subtype(actual, expected), + _ => actual == expected, + } + } + + fn heap_type_is_subtype(&self, actual: RefType, expected: RefType) -> bool { + if let Some(expected_addr) = expected.type_index() { + let Some(actual_addr) = actual.type_index() else { + return matches!( + (actual.abstract_heap_type(), &self.get_type(expected_addr).composite), + (Some(AbstractHeapType::NoFunc), CompositeType::Func(_)) + | (Some(AbstractHeapType::None), CompositeType::Struct(_) | CompositeType::Array(_)) + ); + }; + return self.type_addr_is_subtype(actual_addr, expected_addr); + } + + let expected = expected.abstract_heap_type().expect("abstract reference type"); + if let Some(actual_addr) = actual.type_index() { + return match &self.get_type(actual_addr).composite { + CompositeType::Func(_) => expected == AbstractHeapType::Func, + CompositeType::Struct(_) => { + matches!(expected, AbstractHeapType::Struct | AbstractHeapType::Eq | AbstractHeapType::Any) + } + CompositeType::Array(_) => { + matches!(expected, AbstractHeapType::Array | AbstractHeapType::Eq | AbstractHeapType::Any) + } + }; + } + + let actual = actual.abstract_heap_type().expect("abstract reference type"); + actual == expected + || match actual { + AbstractHeapType::None => matches!( + expected, + AbstractHeapType::I31 + | AbstractHeapType::Struct + | AbstractHeapType::Array + | AbstractHeapType::Eq + | AbstractHeapType::Any + ), + AbstractHeapType::I31 | AbstractHeapType::Struct | AbstractHeapType::Array => { + matches!(expected, AbstractHeapType::Eq | AbstractHeapType::Any) + } + AbstractHeapType::Eq => expected == AbstractHeapType::Any, + AbstractHeapType::NoFunc => expected == AbstractHeapType::Func, + AbstractHeapType::NoExtern => expected == AbstractHeapType::Extern, + AbstractHeapType::NoExn => expected == AbstractHeapType::Exn, + _ => false, + } + } + + /// Returns whether a runtime reference has the expected type. + pub(crate) fn value_ref_matches(&self, value: ValueRef, expected: RefType) -> bool { + if value.is_null() { + return expected.is_nullable(); + } + if expected.abstract_heap_type() == Some(AbstractHeapType::Extern) { + return true; + } + let expected_func = expected.type_index().is_some_and(|addr| self.get_type(addr).as_func().is_some()) + || expected.abstract_heap_type() == Some(AbstractHeapType::Func); + if expected_func { + let Some(func_addr) = value.addr() else { return false }; + let Some(func) = self.funcs.get(func_addr as usize) else { return false }; + let actual = RefType::new_concrete(false, func.type_addr).expect("canonical type fits"); + return self.ref_type_is_subtype(actual, expected); + } + if value.is_i31() { + let actual = RefType::new_abstract(false, AbstractHeapType::I31); + return self.ref_type_is_subtype(actual, expected); + } + if value.is_host_any() { + let actual = RefType::new_abstract(false, AbstractHeapType::Any); + return self.ref_type_is_subtype(actual, expected); + } + + let Some(object) = self.gc.get(value) else { return false }; + let actual = RefType::new_concrete(false, object.type_addr).expect("canonical type fits"); + self.ref_type_is_subtype(actual, expected) + } + + #[inline] + pub(crate) fn get_func_type(&self, addr: FuncAddr) -> &FuncType { + self.get_canonical_func_type(self.get_func(addr).type_addr) + } + + #[inline] + pub(crate) fn get_type(&self, addr: TypeAddr) -> &SubType { + Self::get(&self.canonical_types, addr, "canonical type") + } + + #[inline] + pub(crate) fn get_canonical_func_type(&self, addr: TypeAddr) -> &FuncType { + self.get_type(addr).as_func().expect("validated function address references a function type") + } + + pub(crate) fn value_matches_type(&self, value: WasmValue, expected: WasmType) -> bool { + match (value, expected) { + (WasmValue::Ref(RefValue::Null), WasmType::Ref(expected)) => expected.is_nullable(), + (WasmValue::Ref(RefValue::Func(func)), WasmType::Ref(expected)) => { + self.funcs.get(func.addr() as usize).is_some_and(|func| { + let actual = RefType::new_concrete(false, func.type_addr).expect("canonical type fits"); + self.ref_type_is_subtype(actual, expected) + }) + } + (WasmValue::Ref(RefValue::Any(_)), WasmType::Ref(expected)) + if expected.is_func() || expected.is_extern() || expected.is_exn() => + { + false + } + (WasmValue::Ref(RefValue::Any(value)), WasmType::Ref(expected)) => { + self.value_ref_matches(ValueRef::from_raw(value.raw()), expected) + } + (_, WasmType::Ref(expected)) if expected.is_concrete() => false, + _ => value.matches_type(expected), + } + } + + pub(super) fn get<'a, T>(items: &'a [T], addr: Addr, kind: &str) -> &'a T { + items.get(addr as usize).unwrap_or_else(|| unreachable!("invalid {kind} address: {addr}")) + } + + fn get_mut<'a, T>(items: &'a mut [T], addr: Addr, kind: &str) -> &'a mut T { + items.get_mut(addr as usize).unwrap_or_else(|| unreachable!("invalid {kind} address: {addr}")) + } + + fn get_disjoint_mut<'a, T>(items: &'a mut [T], addr: Addr, addr2: Addr, kind: &str) -> (&'a mut T, &'a mut T) { + let [item_a, item_b] = items + .get_disjoint_mut([addr as usize, addr2 as usize]) + .unwrap_or_else(|_| unreachable!("invalid {kind} addresses: {addr}, {addr2}")); + (item_a, item_b) + } + + /// Get the function at the actual index in the store + pub(crate) fn get_func(&self, addr: FuncAddr) -> &FunctionInstance { + Self::get(&self.funcs, addr, "function") + } + + /// Get a wasm function at the actual index in the store, panicking if it's a host function (which should be guaranteed by the validator) + pub(crate) fn get_wasm_func(&self, addr: FuncAddr) -> &WasmFunctionInstance { + match self.funcs.get(addr as usize).map(|func| &func.kind) { + Some(FunctionKind::Wasm(wasm_func)) => wasm_func, + _ => unreachable!("invalid wasm function address: {addr}"), + } + } + + /// Get the memory at the actual index in the store + pub(crate) fn get_mem(&self, addr: MemAddr) -> &MemoryInstance { + Self::get(&self.memories, addr, "memory") + } + + /// Get the memory at the actual index in the store + pub(crate) fn get_mem_mut(&mut self, addr: MemAddr) -> &mut MemoryInstance { + Self::get_mut(&mut self.memories, addr, "memory") + } + + /// Get the memory at the actual index in the store + pub(crate) fn get_mems_mut(&mut self, addr: MemAddr, addr2: MemAddr) -> (&mut MemoryInstance, &mut MemoryInstance) { + Self::get_disjoint_mut(&mut self.memories, addr, addr2, "memory") + } + + /// Get the table at the actual index in the store + pub(crate) fn get_table(&self, addr: TableAddr) -> &TableInstance { + Self::get(&self.tables, addr, "table") + } + + /// Get the table at the actual index in the store + pub(crate) fn get_table_mut(&mut self, addr: TableAddr) -> &mut TableInstance { + Self::get_mut(&mut self.tables, addr, "table") + } + + /// Get two mutable tables at the actual index in the store + pub(crate) fn get_tables_mut( + &mut self, + addr: TableAddr, + addr2: TableAddr, + ) -> (&mut TableInstance, &mut TableInstance) { + Self::get_disjoint_mut(&mut self.tables, addr, addr2, "table") + } + + /// Get the data at the actual index in the store + pub(crate) fn get_data_mut(&mut self, addr: DataAddr) -> &mut DataInstance { + Self::get_mut(&mut self.data, addr, "data") + } + + /// Get the element at the actual index in the store + pub(crate) fn get_elem_mut(&mut self, addr: ElemAddr) -> &mut ElementInstance { + Self::get_mut(&mut self.elements, addr, "element") + } + + /// Get the global at the actual index in the store + pub(crate) fn get_global(&self, addr: GlobalAddr) -> &GlobalInstance { + Self::get(&self.globals, addr, "global") + } + + /// Get the global at the actual index in the store + pub(crate) fn get_global_mut(&mut self, addr: GlobalAddr) -> &mut GlobalInstance { + Self::get_mut(&mut self.globals, addr, "global") + } + + /// Get the global at the actual index in the store + pub(crate) fn get_global_val(&self, addr: GlobalAddr) -> TinyWasmValue { + self.get_global(addr).value + } + + /// Set the global at the actual index in the store + pub(crate) fn set_global_val(&mut self, addr: GlobalAddr, value: TinyWasmValue) { + self.get_global_mut(addr).value = value; + } +} diff --git a/crates/tinywasm/src/store/table.rs b/crates/tinywasm/src/store/table.rs index 68ed99f..ece0001 100644 --- a/crates/tinywasm/src/store/table.rs +++ b/crates/tinywasm/src/store/table.rs @@ -1,4 +1,4 @@ -use crate::{Result, Trap}; +use crate::{Result, Trap, interpreter::ValueRef}; use alloc::vec::Vec; use core::ops::Range; use tinywasm_types::*; @@ -10,17 +10,17 @@ const MAX_TABLE_SIZE: usize = 10_000_000; /// See #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) struct TableInstance { - pub(crate) elements: Vec, + pub(crate) elements: Vec, pub(crate) kind: TableType, } impl TableInstance { #[cfg(test)] pub(crate) fn new(kind: TableType) -> Result { - Self::new_with_init(kind, TableElement::Uninitialized) + Self::new_with_init(kind, ValueRef::NULL) } - pub(crate) fn new_with_init(kind: TableType, init: TableElement) -> Result { + pub(crate) fn new_with_init(kind: TableType, init: ValueRef) -> Result { let size = usize::try_from(kind.size_initial).map_err(|_| Trap::OutOfMemory)?; if size > MAX_TABLE_SIZE { return Err(Trap::OutOfMemory.into()); @@ -45,27 +45,23 @@ impl TableInstance { Ok(addr..end) } - pub(crate) fn get_wasm_val(&self, addr: usize) -> Result { - Ok(self.get(addr)?.to_wasm_value(self.kind.element_type)) - } - - pub(crate) fn fill(&mut self, addr: usize, len: usize, val: TableElement) -> Result<(), Trap> { + pub(crate) fn fill(&mut self, addr: usize, len: usize, val: ValueRef) -> Result<(), Trap> { let range = self.checked_range(addr, len)?; self.elements[range].fill(val); Ok(()) } - pub(crate) fn get(&self, addr: usize) -> Result<&TableElement, Trap> { + pub(crate) fn get(&self, addr: usize) -> Result<&ValueRef, Trap> { self.elements.get(addr).ok_or_else(|| self.trap_oob(addr, 1)) } - pub(crate) fn copy_from_slice(&mut self, dst: usize, src: &[TableElement]) -> Result<(), Trap> { + pub(crate) fn copy_from_slice(&mut self, dst: usize, src: &[ValueRef]) -> Result<(), Trap> { let range = self.checked_range(dst, src.len())?; self.elements[range].copy_from_slice(src); Ok(()) } - pub(crate) fn load(&self, addr: usize, len: usize) -> Result<&[TableElement], Trap> { + pub(crate) fn load(&self, addr: usize, len: usize) -> Result<&[ValueRef], Trap> { Ok(&self.elements[self.checked_range(addr, len)?]) } @@ -76,13 +72,13 @@ impl TableInstance { Ok(()) } - pub(crate) fn set(&mut self, table_idx: usize, value: TableElement) -> Result<(), Trap> { + pub(crate) fn set(&mut self, table_idx: usize, value: ValueRef) -> Result<(), Trap> { let range = self.checked_range(table_idx, 1)?; self.elements[range.start] = value; Ok(()) } - pub(crate) fn grow(&mut self, n: usize, init: TableElement) -> Result<(), Trap> { + pub(crate) fn grow(&mut self, n: usize, init: ValueRef) -> Result<(), Trap> { let len = n.checked_add(self.elements.len()).ok_or(Trap::OutOfMemory)?; let declared_max = self.kind.size_max.and_then(|max| usize::try_from(max).ok()).unwrap_or(usize::MAX); let max = declared_max.min(MAX_TABLE_SIZE); @@ -99,52 +95,13 @@ impl TableInstance { self.elements.len() } - pub(crate) fn init(&mut self, offset: usize, init: &[TableElement]) -> Result<(), Trap> { + pub(crate) fn init(&mut self, offset: usize, init: &[ValueRef]) -> Result<(), Trap> { let range = self.checked_range(offset, init.len())?; self.elements[range].copy_from_slice(init); Ok(()) } } -#[derive(Clone, Copy)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub(crate) enum TableElement { - Uninitialized, - Initialized(TableAddr), -} - -impl From> for TableElement { - fn from(addr: Option) -> Self { - match addr { - None => Self::Uninitialized, - Some(addr) => Self::Initialized(addr), - } - } -} - -impl TableElement { - pub(crate) fn addr(&self) -> Option { - match self { - Self::Uninitialized => None, - Self::Initialized(addr) => Some(*addr), - } - } - - pub(crate) fn to_wasm_value(self, ty: RefType) -> WasmValue { - let Some(addr) = self.addr() else { return RefValue::Null.into() }; - let value = if ty.is_func() { - RefValue::Func(FuncRef::new(addr)) - } else if ty.is_extern() { - RefValue::Extern(ExternRef::new(addr)) - } else if ty.is_exn() { - RefValue::Exn(ExnRef::new(addr)) - } else { - RefValue::Any(AnyRef::from_raw(addr)) - }; - value.into() - } -} - #[cfg(test)] mod tests { use super::*; @@ -162,43 +119,17 @@ mod tests { assert_eq!(table_instance.size() as u64, kind.size_initial, "Table instance creation failed: size mismatch"); } - #[test] - fn test_get_wasm_val() { - let kind = dummy_table_type(); - let mut table_instance = TableInstance::new(kind).unwrap(); - - table_instance.set(0, TableElement::Initialized(0)).expect("Setting table element failed"); - table_instance.set(1, TableElement::Uninitialized).expect("Setting table element failed"); - - match table_instance.get_wasm_val(0) { - Ok(WasmValue::Ref(RefValue::Func(_))) => {} - _ => panic!("get_wasm_val failed to return the correct WasmValue"), - } - - match table_instance.get_wasm_val(1) { - Ok(WasmValue::Ref(RefValue::Null)) => {} - _ => panic!("get_wasm_val failed to return the correct WasmValue"), - } - - match table_instance.get_wasm_val(999) { - Err(Trap::TableOutOfBounds { .. }) => {} - _ => panic!("get_wasm_val failed to handle undefined element correctly"), - } - } - #[test] fn test_set_and_get() { let kind = dummy_table_type(); let mut table_instance = TableInstance::new(kind).unwrap(); - let result = table_instance.set(0, TableElement::Initialized(1)); + let value = ValueRef::from_raw(2); + let result = table_instance.set(0, value); assert!(result.is_ok(), "Setting table element failed"); let elem = table_instance.get(0); - assert!( - elem.is_ok() && matches!(elem.unwrap(), &TableElement::Initialized(1)), - "Getting table element failed or returned incorrect value" - ); + assert!(elem.is_ok() && elem.unwrap() == &value, "Getting table element failed or returned incorrect value"); } #[test] @@ -206,17 +137,14 @@ mod tests { let kind = dummy_table_type(); let mut table_instance = TableInstance::new(kind).unwrap(); - let init_elements = vec![TableElement::Initialized(0); 5]; + let init_elements = vec![ValueRef::from_raw(2); 5]; let result = table_instance.init(0, &init_elements); assert!(result.is_ok(), "Initializing table with elements failed"); for i in 0..5 { let elem = table_instance.get(i); - assert!( - elem.is_ok() && matches!(elem.unwrap(), &TableElement::Initialized(_)), - "Element not initialized correctly at index {i}" - ); + assert!(elem.is_ok() && !elem.unwrap().is_null(), "Element not initialized correctly at index {i}"); } } } diff --git a/crates/tinywasm/src/store/types.rs b/crates/tinywasm/src/store/types.rs new file mode 100644 index 0000000..7cee56b --- /dev/null +++ b/crates/tinywasm/src/store/types.rs @@ -0,0 +1,204 @@ +use alloc::{boxed::Box, vec::Vec}; +use tinywasm_types::*; + +use super::Store; + +pub(crate) fn canonicalize_ref_type(ty: RefType, type_addrs: &[TypeAddr]) -> RefType { + let Some(type_addr) = ty.type_index() else { return ty }; + let canonical = *type_addrs.get(type_addr as usize).expect("validated type address should exist"); + RefType::new_concrete(ty.is_nullable(), canonical).expect("canonical type addresses fit in references") +} + +pub(crate) fn canonicalize_value_type(ty: WasmType, type_addrs: &[TypeAddr]) -> WasmType { + match ty { + WasmType::Ref(ty) => WasmType::Ref(canonicalize_ref_type(ty, type_addrs)), + ty => ty, + } +} + +fn map_value_type(ty: WasmType, resolve: &mut impl FnMut(TypeAddr) -> TypeAddr) -> WasmType { + match ty { + WasmType::Ref(ty) if ty.is_concrete() => { + let addr = resolve(ty.type_index().expect("concrete reference has a type index")); + WasmType::Ref( + RefType::new_concrete(ty.is_nullable(), addr).expect("canonical type addresses fit in references"), + ) + } + ty => ty, + } +} + +fn map_field_type(field: FieldType, resolve: &mut impl FnMut(TypeAddr) -> TypeAddr) -> FieldType { + let storage = match field.storage { + StorageType::Value(ty) => StorageType::Value(map_value_type(ty, resolve)), + storage => storage, + }; + FieldType { storage, mutable: field.mutable } +} + +fn map_subtype(ty: &SubType, mut resolve: impl FnMut(TypeAddr) -> TypeAddr) -> SubType { + let supertype = ty.supertype.map(&mut resolve); + let composite = match &ty.composite { + CompositeType::Func(ty) => { + let params = ty.params().iter().copied().map(|ty| map_value_type(ty, &mut resolve)).collect::>(); + let results = ty.results().iter().copied().map(|ty| map_value_type(ty, &mut resolve)).collect::>(); + CompositeType::Func(FuncType::new(¶ms, &results)) + } + CompositeType::Struct(ty) => CompositeType::Struct(StructType { + fields: ty.fields.iter().copied().map(|field| map_field_type(field, &mut resolve)).collect(), + }), + CompositeType::Array(ty) => CompositeType::Array(ArrayType { field: map_field_type(ty.field, &mut resolve) }), + }; + SubType { is_final: ty.is_final, supertype, composite } +} + +fn subtypes_equal( + ty: &SubType, + registered: &SubType, + module_group: core::ops::Range, + canonical_group: core::ops::Range, + resolve: impl Fn(TypeAddr) -> TypeAddr + Copy, +) -> bool { + let type_addrs_equal = |ty: TypeAddr, registered: TypeAddr| { + module_group.contains(&(ty as usize)) == canonical_group.contains(&(registered as usize)) + && resolve(ty) == registered + }; + let values_equal = |ty: WasmType, registered: WasmType| match (ty, registered) { + (WasmType::Ref(ty), WasmType::Ref(registered)) if ty.is_concrete() => { + let ty_addr = ty.type_index().expect("concrete reference"); + let Some(registered_addr) = registered.type_index() else { return false }; + ty.is_nullable() == registered.is_nullable() && type_addrs_equal(ty_addr, registered_addr) + } + _ => ty == registered, + }; + let fields_equal = |ty: FieldType, registered: FieldType| { + ty.mutable == registered.mutable + && match (ty.storage, registered.storage) { + (StorageType::Value(ty), StorageType::Value(registered)) => values_equal(ty, registered), + (ty, registered) => ty == registered, + } + }; + + let supertypes_equal = match (ty.supertype, registered.supertype) { + (Some(ty), Some(registered)) => type_addrs_equal(ty, registered), + (None, None) => true, + _ => false, + }; + ty.is_final == registered.is_final + && supertypes_equal + && match (&ty.composite, ®istered.composite) { + (CompositeType::Func(ty), CompositeType::Func(registered)) => { + ty.params().len() == registered.params().len() + && ty.results().len() == registered.results().len() + && ty + .params() + .iter() + .chain(ty.results()) + .copied() + .zip(registered.params().iter().chain(registered.results()).copied()) + .all(|(ty, registered)| values_equal(ty, registered)) + } + (CompositeType::Struct(ty), CompositeType::Struct(registered)) => { + ty.fields.len() == registered.fields.len() + && ty + .fields + .iter() + .copied() + .zip(registered.fields.iter().copied()) + .all(|(ty, registered)| fields_equal(ty, registered)) + } + (CompositeType::Array(ty), CompositeType::Array(registered)) => fields_equal(ty.field, registered.field), + _ => false, + } +} + +impl Store { + pub(crate) fn register_module_types(&mut self, section: &TypeSection) -> Box<[TypeAddr]> { + let mut type_addrs = Vec::with_capacity(section.types.len()); + let mut module_group_start = 0usize; + + for &group_len in §ion.rec_group_lengths { + let group_len = group_len as usize; + let module_group_end = module_group_start.checked_add(group_len).expect("type group is too large"); + let group = section + .types + .get(module_group_start..module_group_end) + .expect("validated recursive group length fits the type section"); + + let resolve = |module_addr: TypeAddr, canonical_group_start: usize| { + let module_addr = module_addr as usize; + if (module_group_start..module_group_end).contains(&module_addr) { + (canonical_group_start + module_addr - module_group_start) as TypeAddr + } else { + *type_addrs + .get(module_addr) + .expect("validated type reference targets the current or a prior recursive group") + } + }; + + let mut canonical_group_start = 0; + let mut matching_group = None; + for &canonical_group_len in &self.state.canonical_rec_group_lengths { + let canonical_group_len = canonical_group_len as usize; + if canonical_group_len == group_len + && group.iter().zip(&self.state.canonical_types[canonical_group_start..]).all(|(ty, registered)| { + subtypes_equal( + ty, + registered, + module_group_start..module_group_end, + canonical_group_start..canonical_group_start + canonical_group_len, + |addr| resolve(addr, canonical_group_start), + ) + }) + { + matching_group = Some(canonical_group_start); + break; + } + canonical_group_start += canonical_group_len; + } + + let canonical_group_start = match matching_group { + Some(start) => start, + None => { + let start = self.state.canonical_types.len(); + assert!( + start.checked_add(group_len).is_some_and(|end| end <= (1 << 30)), + "too many canonical types" + ); + self.state + .canonical_types + .extend(group.iter().map(|ty| map_subtype(ty, |addr| resolve(addr, start)))); + self.state.canonical_rec_group_lengths.push(group_len as u32); + start + } + }; + type_addrs.extend((canonical_group_start..canonical_group_start + group_len).map(|addr| addr as TypeAddr)); + module_group_start = module_group_end; + } + debug_assert_eq!(module_group_start, section.types.len()); + type_addrs.into_boxed_slice() + } + + pub(crate) fn register_host_type(&mut self, ty: &FuncType) -> TypeAddr { + let mut group_start = 0usize; + for &group_len in &self.state.canonical_rec_group_lengths { + if group_len == 1 + && self.state.canonical_types[group_start].is_final + && self.state.canonical_types[group_start].supertype.is_none() + && self.state.canonical_types[group_start].as_func() == Some(ty) + { + return group_start as TypeAddr; + } + group_start += group_len as usize; + } + let addr = self.state.canonical_types.len(); + assert!(addr < (1 << 30), "too many canonical types"); + self.state.canonical_types.push(SubType { + is_final: true, + supertype: None, + composite: CompositeType::Func(ty.clone()), + }); + self.state.canonical_rec_group_lengths.push(1); + addr as TypeAddr + } +} diff --git a/crates/tinywasm/tests/gc_refs.rs b/crates/tinywasm/tests/gc_refs.rs new file mode 100644 index 0000000..d3f2994 --- /dev/null +++ b/crates/tinywasm/tests/gc_refs.rs @@ -0,0 +1,120 @@ +use tinywasm::types::{ExternRef, RefValue, WasmValue}; +use tinywasm::{Engine, ExecProgress, ModuleInstance, Store, engine::Config}; + +const MODULE: &str = r#" + (module + (type $node (struct (field i32))) + (type $bytes (array (mut i8))) + (func (export "new") (result anyref) + (struct.new $node (i32.const 42))) + (func (export "new-extern") (result externref) + (extern.convert_any (struct.new $node (i32.const 42)))) + (func (export "read") (param anyref) (result i32) + (struct.get $node 0 (ref.cast (ref $node) (local.get 0)))) + (func (export "read-extern") (param externref) (result i32) + (struct.get $node 0 + (ref.cast (ref $node) (any.convert_extern (local.get 0))))) + (func (export "churn") + (local $i i32) + (loop $loop + (drop (array.new_default $bytes (i32.const 16))) + (local.set $i (i32.add (local.get $i) (i32.const 1))) + (br_if $loop (i32.lt_u (local.get $i) (i32.const 100))))) + ) +"#; + +fn store() -> Store { + Store::new(Engine::new(Config::new().with_gc_collection_threshold(1))) +} + +#[test] +fn host_result_is_pinned_and_rejected_by_another_store() { + let module = tinywasm::parse_bytes(&wat::parse_str(MODULE).unwrap()).unwrap(); + let mut first_store = store(); + let first = ModuleInstance::instantiate(&mut first_store, &module, None).unwrap(); + let new = first.func_untyped(&first_store, "new").unwrap(); + let read = first.func_untyped(&first_store, "read").unwrap(); + let churn = first.func_untyped(&first_store, "churn").unwrap(); + + let value = new.call(&mut first_store, &[]).unwrap().pop().unwrap(); + assert!(matches!(value, WasmValue::Ref(RefValue::Any(_)))); + churn.call(&mut first_store, &[]).unwrap(); + assert_eq!(read.call(&mut first_store, &[value]).unwrap(), [WasmValue::I32(42)]); + + let mut second_store = store(); + let second = ModuleInstance::instantiate(&mut second_store, &module, None).unwrap(); + let other_read = second.func_untyped(&second_store, "read").unwrap(); + assert!(other_read.call(&mut second_store, &[value]).is_err()); +} + +#[test] +fn externalized_gc_result_is_pinned() { + let module = tinywasm::parse_bytes(&wat::parse_str(MODULE).unwrap()).unwrap(); + let mut store = store(); + let instance = ModuleInstance::instantiate(&mut store, &module, None).unwrap(); + let new = instance.func_untyped(&store, "new-extern").unwrap(); + let read = instance.func_untyped(&store, "read-extern").unwrap(); + let churn = instance.func_untyped(&store, "churn").unwrap(); + + let value = new.call(&mut store, &[]).unwrap().pop().unwrap(); + assert!(matches!(value, WasmValue::Ref(RefValue::Extern(_)))); + churn.call(&mut store, &[]).unwrap(); + assert_eq!(read.call(&mut store, &[value]).unwrap(), [WasmValue::I32(42)]); +} + +#[test] +fn host_externref_does_not_alias_a_gc_object() { + let module = tinywasm::parse_bytes(&wat::parse_str(MODULE).unwrap()).unwrap(); + let mut store = store(); + let instance = ModuleInstance::instantiate(&mut store, &module, None).unwrap(); + let new = instance.func_untyped(&store, "new").unwrap(); + let read = instance.func_untyped(&store, "read-extern").unwrap(); + + new.call(&mut store, &[]).unwrap(); + let host_ref = WasmValue::Ref(RefValue::Extern(ExternRef::new(0))); + assert!(read.call(&mut store, &[host_ref]).is_err()); +} + +#[test] +fn resumable_gc_result_is_pinned() { + let module = tinywasm::parse_bytes(&wat::parse_str(MODULE).unwrap()).unwrap(); + let mut store = store(); + let instance = ModuleInstance::instantiate(&mut store, &module, None).unwrap(); + let new = instance.func_untyped(&store, "new").unwrap(); + let read = instance.func_untyped(&store, "read").unwrap(); + let churn = instance.func_untyped(&store, "churn").unwrap(); + + let mut execution = new.call_resumable(&mut store, &[]).unwrap(); + let value = match execution.resume_with_fuel(1000).unwrap() { + ExecProgress::Completed(mut values) => values.pop().unwrap(), + ExecProgress::Suspended => panic!("constructor unexpectedly suspended"), + }; + drop(execution); + + churn.call(&mut store, &[]).unwrap(); + assert_eq!(read.call(&mut store, &[value]).unwrap(), [WasmValue::I32(42)]); +} + +#[test] +fn element_initializers_root_previous_gc_values() { + let module = tinywasm::parse_bytes( + &wat::parse_str( + r#" + (module + (type $node (struct (field i32))) + (table 2 (ref null $node)) + (elem (i32.const 0) (ref $node) + (struct.new $node (i32.const 1)) + (struct.new $node (i32.const 2))) + (func (export "first") (result i32) + (struct.get $node 0 (table.get 0 (i32.const 0))))) + "#, + ) + .unwrap(), + ) + .unwrap(); + let mut store = store(); + let instance = ModuleInstance::instantiate(&mut store, &module, None).unwrap(); + + assert_eq!(instance.func_untyped(&store, "first").unwrap().call(&mut store, &[]).unwrap(), [WasmValue::I32(1)]); +} diff --git a/crates/tinywasm/tests/generated/wasm-2.csv b/crates/tinywasm/tests/generated/wasm-2.csv index c2472a7..645f0d5 100644 --- a/crates/tinywasm/tests/generated/wasm-2.csv +++ b/crates/tinywasm/tests/generated/wasm-2.csv @@ -13,4 +13,4 @@ 0.9.0,28008,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":162,"failed":0},{"name":"binary-leb128.wast","passed":89,"failed":0},{"name":"binary.wast","passed":128,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":118,"failed":0},{"name":"br_table.wast","passed":174,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":61,"failed":0},{"name":"elem.wast","passed":98,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":96,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":172,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":110,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":178,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":97,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":88,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":104,"failed":0},{"name":"memory_init.wast","passed":240,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":16,"failed":0},{"name":"ref_null.wast","passed":3,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"select.wast","passed":148,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table-sub.wast","passed":2,"failed":0},{"name":"table.wast","passed":19,"failed":0},{"name":"table_copy.wast","passed":1728,"failed":0},{"name":"table_fill.wast","passed":45,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_init.wast","passed":780,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":58,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":118,"failed":0},{"name":"unreached-valid.wast","passed":7,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] 0.9.1,28008,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":162,"failed":0},{"name":"binary-leb128.wast","passed":89,"failed":0},{"name":"binary.wast","passed":128,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":118,"failed":0},{"name":"br_table.wast","passed":174,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":61,"failed":0},{"name":"elem.wast","passed":98,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":96,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":172,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":110,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":178,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":97,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":88,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":104,"failed":0},{"name":"memory_init.wast","passed":240,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":16,"failed":0},{"name":"ref_null.wast","passed":3,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"select.wast","passed":148,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table-sub.wast","passed":2,"failed":0},{"name":"table.wast","passed":19,"failed":0},{"name":"table_copy.wast","passed":1728,"failed":0},{"name":"table_fill.wast","passed":45,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_init.wast","passed":780,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":58,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":118,"failed":0},{"name":"unreached-valid.wast","passed":7,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] 0.10.0,28008,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":162,"failed":0},{"name":"binary-leb128.wast","passed":89,"failed":0},{"name":"binary.wast","passed":128,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":118,"failed":0},{"name":"br_table.wast","passed":174,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":61,"failed":0},{"name":"elem.wast","passed":98,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":96,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":172,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":110,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":178,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":97,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":88,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":104,"failed":0},{"name":"memory_init.wast","passed":240,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":16,"failed":0},{"name":"ref_null.wast","passed":3,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"select.wast","passed":148,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table-sub.wast","passed":2,"failed":0},{"name":"table.wast","passed":19,"failed":0},{"name":"table_copy.wast","passed":1728,"failed":0},{"name":"table_fill.wast","passed":45,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_init.wast","passed":780,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":58,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":118,"failed":0},{"name":"unreached-valid.wast","passed":7,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] -0.11.0-pre.0,28008,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":162,"failed":0},{"name":"binary-leb128.wast","passed":89,"failed":0},{"name":"binary.wast","passed":128,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":118,"failed":0},{"name":"br_table.wast","passed":174,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":61,"failed":0},{"name":"elem.wast","passed":98,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":96,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":172,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":110,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":178,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":97,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":88,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":104,"failed":0},{"name":"memory_init.wast","passed":240,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":16,"failed":0},{"name":"ref_null.wast","passed":3,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"select.wast","passed":148,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table-sub.wast","passed":2,"failed":0},{"name":"table.wast","passed":19,"failed":0},{"name":"table_copy.wast","passed":1728,"failed":0},{"name":"table_fill.wast","passed":45,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_init.wast","passed":780,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":58,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":118,"failed":0},{"name":"unreached-valid.wast","passed":7,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] +0.11.0-pre.0,28002,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":162,"failed":0},{"name":"binary-leb128.wast","passed":89,"failed":0},{"name":"binary.wast","passed":128,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":118,"failed":0},{"name":"br_table.wast","passed":174,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":59,"failed":0},{"name":"elem.wast","passed":96,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":96,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":172,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":108,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":178,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":97,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":88,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":104,"failed":0},{"name":"memory_init.wast","passed":240,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":16,"failed":0},{"name":"ref_null.wast","passed":3,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"select.wast","passed":148,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table-sub.wast","passed":2,"failed":0},{"name":"table.wast","passed":19,"failed":0},{"name":"table_copy.wast","passed":1728,"failed":0},{"name":"table_fill.wast","passed":45,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_init.wast","passed":780,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":58,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":118,"failed":0},{"name":"unreached-valid.wast","passed":7,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] diff --git a/crates/tinywasm/tests/generated/wasm-3.csv b/crates/tinywasm/tests/generated/wasm-3.csv index 9403d27..7d3961c 100644 --- a/crates/tinywasm/tests/generated/wasm-3.csv +++ b/crates/tinywasm/tests/generated/wasm-3.csv @@ -1,3 +1,3 @@ 0.9.0,20776,452,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":89,"failed":1},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":37,"failed":9},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] 0.10.0,20778,450,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":38,"failed":8},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] -0.11.0-pre.0,21107,121,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":12,"failed":0},{"name":"br_on_null.wast","passed":10,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":35,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":163,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":51,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":46,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":19,"failed":13},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":13,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] +0.11.0-pre.0,21151,77,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":12,"failed":0},{"name":"br_on_null.wast","passed":10,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":35,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":151,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":124,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":163,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":51,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":46,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":2,"failed":0},{"name":"type-equivalence.wast","passed":32,"failed":0},{"name":"type-rec.wast","passed":27,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":13,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] diff --git a/crates/tinywasm/tests/generated/wasm-extended-const.csv b/crates/tinywasm/tests/generated/wasm-extended-const.csv index 8677772..1e4e851 100644 --- a/crates/tinywasm/tests/generated/wasm-extended-const.csv +++ b/crates/tinywasm/tests/generated/wasm-extended-const.csv @@ -2,4 +2,4 @@ 0.9.0,290,0,[{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":111,"failed":0},{"name":"global.wast","passed":114,"failed":0}] 0.9.1,290,0,[{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":111,"failed":0},{"name":"global.wast","passed":114,"failed":0}] 0.10.0,290,0,[{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":111,"failed":0},{"name":"global.wast","passed":114,"failed":0}] -0.11.0-pre.0,290,0,[{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":111,"failed":0},{"name":"global.wast","passed":114,"failed":0}] +0.11.0-pre.0,284,0,[{"name":"data.wast","passed":63,"failed":0},{"name":"elem.wast","passed":109,"failed":0},{"name":"global.wast","passed":112,"failed":0}] diff --git a/crates/tinywasm/tests/generated/wasm-function-references.csv b/crates/tinywasm/tests/generated/wasm-function-references.csv index 3e59535..9d6dd64 100644 --- a/crates/tinywasm/tests/generated/wasm-function-references.csv +++ b/crates/tinywasm/tests/generated/wasm-function-references.csv @@ -1,3 +1,3 @@ 0.9.0,1536,331,[{"name":"binary.wast","passed":128,"failed":0},{"name":"br_on_non_null.wast","passed":0,"failed":9},{"name":"br_on_null.wast","passed":0,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call_ref.wast","passed":3,"failed":31},{"name":"data.wast","passed":59,"failed":0},{"name":"elem.wast","passed":138,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"global.wast","passed":108,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"linking.wast","passed":146,"failed":21},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":4},{"name":"return_call.wast","passed":45,"failed":0},{"name":"return_call_indirect.wast","passed":76,"failed":0},{"name":"return_call_ref.wast","passed":10,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"table-sub.wast","passed":2,"failed":1},{"name":"table.wast","passed":35,"failed":8},{"name":"type-equivalence.wast","passed":7,"failed":7},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":10}] 0.10.0,1536,331,[{"name":"binary.wast","passed":128,"failed":0},{"name":"br_on_non_null.wast","passed":0,"failed":9},{"name":"br_on_null.wast","passed":0,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call_ref.wast","passed":3,"failed":31},{"name":"data.wast","passed":59,"failed":0},{"name":"elem.wast","passed":138,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"global.wast","passed":108,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"linking.wast","passed":146,"failed":21},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":4},{"name":"return_call.wast","passed":45,"failed":0},{"name":"return_call_indirect.wast","passed":76,"failed":0},{"name":"return_call_ref.wast","passed":10,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"table-sub.wast","passed":2,"failed":1},{"name":"table.wast","passed":35,"failed":8},{"name":"type-equivalence.wast","passed":7,"failed":7},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":10}] -0.11.0-pre.0,1867,0,[{"name":"binary.wast","passed":128,"failed":0},{"name":"br_on_non_null.wast","passed":9,"failed":0},{"name":"br_on_null.wast","passed":9,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call_ref.wast","passed":34,"failed":0},{"name":"data.wast","passed":59,"failed":0},{"name":"elem.wast","passed":138,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"global.wast","passed":108,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"linking.wast","passed":167,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":4,"failed":0},{"name":"return_call.wast","passed":45,"failed":0},{"name":"return_call_indirect.wast","passed":76,"failed":0},{"name":"return_call_ref.wast","passed":50,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"table-sub.wast","passed":3,"failed":0},{"name":"table.wast","passed":43,"failed":0},{"name":"type-equivalence.wast","passed":14,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":12,"failed":0}] +0.11.0-pre.0,1866,0,[{"name":"binary.wast","passed":128,"failed":0},{"name":"br_on_non_null.wast","passed":9,"failed":0},{"name":"br_on_null.wast","passed":9,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call_ref.wast","passed":34,"failed":0},{"name":"data.wast","passed":59,"failed":0},{"name":"elem.wast","passed":138,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"global.wast","passed":108,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"linking.wast","passed":167,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":4,"failed":0},{"name":"return_call.wast","passed":45,"failed":0},{"name":"return_call_indirect.wast","passed":76,"failed":0},{"name":"return_call_ref.wast","passed":50,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"table-sub.wast","passed":3,"failed":0},{"name":"table.wast","passed":43,"failed":0},{"name":"type-equivalence.wast","passed":13,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":12,"failed":0}] diff --git a/crates/tinywasm/tests/generated/wasm-gc.csv b/crates/tinywasm/tests/generated/wasm-gc.csv index 5b2995f..ea39c56 100644 --- a/crates/tinywasm/tests/generated/wasm-gc.csv +++ b/crates/tinywasm/tests/generated/wasm-gc.csv @@ -1,2 +1,3 @@ 0.9.0,80,703,[{"name":"array.wast","passed":6,"failed":48},{"name":"array_copy.wast","passed":4,"failed":31},{"name":"array_fill.wast","passed":3,"failed":27},{"name":"array_init_data.wast","passed":2,"failed":44},{"name":"array_init_elem.wast","passed":3,"failed":33},{"name":"array_new_data.wast","passed":0,"failed":28},{"name":"array_new_elem.wast","passed":0,"failed":24},{"name":"binary-gc.wast","passed":1,"failed":0},{"name":"br_on_cast.wast","passed":6,"failed":31},{"name":"br_on_cast_fail.wast","passed":6,"failed":31},{"name":"extern.wast","passed":0,"failed":18},{"name":"i31.wast","passed":2,"failed":71},{"name":"ref_cast.wast","passed":0,"failed":45},{"name":"ref_eq.wast","passed":6,"failed":83},{"name":"ref_test.wast","passed":0,"failed":71},{"name":"struct.wast","passed":5,"failed":25},{"name":"type-subtyping.wast","passed":36,"failed":93}] 0.10.0,80,704,[{"name":"array.wast","passed":6,"failed":48},{"name":"array_copy.wast","passed":4,"failed":31},{"name":"array_fill.wast","passed":3,"failed":27},{"name":"array_init_data.wast","passed":2,"failed":44},{"name":"array_init_elem.wast","passed":3,"failed":33},{"name":"array_new_data.wast","passed":0,"failed":28},{"name":"array_new_elem.wast","passed":0,"failed":24},{"name":"binary-gc.wast","passed":1,"failed":0},{"name":"br_on_cast.wast","passed":6,"failed":31},{"name":"br_on_cast_fail.wast","passed":6,"failed":31},{"name":"extern.wast","passed":0,"failed":18},{"name":"i31.wast","passed":2,"failed":71},{"name":"ref_cast.wast","passed":0,"failed":45},{"name":"ref_eq.wast","passed":6,"failed":83},{"name":"ref_test.wast","passed":0,"failed":71},{"name":"struct.wast","passed":5,"failed":25},{"name":"type-subtyping.wast","passed":36,"failed":94}] +0.11.0-pre.0,784,0,[{"name":"array.wast","passed":54,"failed":0},{"name":"array_copy.wast","passed":35,"failed":0},{"name":"array_fill.wast","passed":30,"failed":0},{"name":"array_init_data.wast","passed":46,"failed":0},{"name":"array_init_elem.wast","passed":36,"failed":0},{"name":"array_new_data.wast","passed":28,"failed":0},{"name":"array_new_elem.wast","passed":24,"failed":0},{"name":"binary-gc.wast","passed":1,"failed":0},{"name":"br_on_cast.wast","passed":37,"failed":0},{"name":"br_on_cast_fail.wast","passed":37,"failed":0},{"name":"extern.wast","passed":18,"failed":0},{"name":"i31.wast","passed":73,"failed":0},{"name":"ref_cast.wast","passed":45,"failed":0},{"name":"ref_eq.wast","passed":89,"failed":0},{"name":"ref_test.wast","passed":71,"failed":0},{"name":"struct.wast","passed":30,"failed":0},{"name":"type-subtyping.wast","passed":130,"failed":0}] diff --git a/crates/tinywasm/tests/generated/wasm-latest.csv b/crates/tinywasm/tests/generated/wasm-latest.csv index ef7e1a2..94a8b58 100644 --- a/crates/tinywasm/tests/generated/wasm-latest.csv +++ b/crates/tinywasm/tests/generated/wasm-latest.csv @@ -1,2 +1,3 @@ 0.9.0,20777,452,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":121,"failed":0},{"name":"memory.wast","passed":89,"failed":1},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":37,"failed":9},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] 0.10.0,20697,536,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":121,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":14,"failed":35},{"name":"return_call_indirect.wast","passed":30,"failed":51},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":38,"failed":8},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] +0.11.0-pre.0,21156,77,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":12,"failed":0},{"name":"br_on_null.wast","passed":10,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":35,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":151,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":124,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":163,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":121,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":49,"failed":0},{"name":"return_call_indirect.wast","passed":81,"failed":0},{"name":"return_call_ref.wast","passed":51,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":46,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":2,"failed":0},{"name":"type-equivalence.wast","passed":32,"failed":0},{"name":"type-rec.wast","passed":27,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":13,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] diff --git a/crates/tinywasm/tests/generated/wasm-threads.csv b/crates/tinywasm/tests/generated/wasm-threads.csv index f588c66..25d09b7 100644 --- a/crates/tinywasm/tests/generated/wasm-threads.csv +++ b/crates/tinywasm/tests/generated/wasm-threads.csv @@ -1,2 +1,3 @@ 0.9.0,357,262,[{"name":"atomic.wast","passed":48,"failed":249},{"name":"exports.wast","passed":82,"failed":6},{"name":"imports.wast","passed":147,"failed":5},{"name":"memory.wast","passed":80,"failed":2}] 0.10.0,357,262,[{"name":"atomic.wast","passed":48,"failed":249},{"name":"exports.wast","passed":82,"failed":6},{"name":"imports.wast","passed":147,"failed":5},{"name":"memory.wast","passed":80,"failed":2}] +0.11.0-pre.0,357,262,[{"name":"atomic.wast","passed":48,"failed":249},{"name":"exports.wast","passed":82,"failed":6},{"name":"imports.wast","passed":147,"failed":5},{"name":"memory.wast","passed":80,"failed":2}] diff --git a/crates/tinywasm/tests/internal_refs.rs b/crates/tinywasm/tests/internal_refs.rs index 7a68f01..04279cc 100644 --- a/crates/tinywasm/tests/internal_refs.rs +++ b/crates/tinywasm/tests/internal_refs.rs @@ -149,8 +149,13 @@ fn export_func_type_index_mismatch_fixture_would_break_old_lookup() -> Result<() let module = tinywasm::parse_bytes(&wasm)?; let export = module.exports.iter().find(|export| export.name.as_ref() == "f").expect("export f not found"); - let old_lookup_ty = module.func_types.get(export.index as usize).expect("old lookup type missing"); - let func_ty = &module.func_types[module.func_type_idxs[export.index as usize] as usize]; + let old_lookup_ty = module.types.get(export.index).and_then(|ty| ty.as_func()).expect("old lookup type missing"); + let func_ty = module + .types + .get(module.func_type_idxs[export.index as usize]) + .expect("export function type index should exist") + .as_func() + .expect("export function should reference a function type"); assert_eq!(old_lookup_ty.params(), &[tinywasm::types::WasmType::I64]); assert_eq!(func_ty.params(), &[]); diff --git a/crates/types/src/archive.rs b/crates/types/src/archive.rs index 99238ab..9904a7d 100644 --- a/crates/types/src/archive.rs +++ b/crates/types/src/archive.rs @@ -7,7 +7,7 @@ use crate::Module; #[rustfmt::skip] const TWASM_MAGIC: [u8; 16] = [ TWASM_MAGIC_PREFIX[0], TWASM_MAGIC_PREFIX[1], TWASM_MAGIC_PREFIX[2], TWASM_MAGIC_PREFIX[3], TWASM_VERSION[0], TWASM_VERSION[1], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; const TWASM_MAGIC_PREFIX: &[u8; 4] = b"TWAS"; -const TWASM_VERSION: &[u8; 2] = b"04"; +const TWASM_VERSION: &[u8; 2] = b"05"; fn validate_magic(wasm: &[u8]) -> Result { if wasm.len() < TWASM_MAGIC.len() || &wasm[..TWASM_MAGIC_PREFIX.len()] != TWASM_MAGIC_PREFIX { diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index a53576e..1160fa5 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -54,6 +54,14 @@ pub enum ConstInstruction { V128Const([u8; 16]), GlobalGet(GlobalAddr), Ref(RefValue), + RefI31, + AnyConvertExtern, + ExternConvertAny, + StructNew(TypeAddr), + StructNewDefault(TypeAddr), + ArrayNew(TypeAddr), + ArrayNewDefault(TypeAddr), + ArrayNewFixed(TypeAddr, u32), I32Add, I32Sub, I32Mul, @@ -272,6 +280,35 @@ pub enum Instruction { RefFunc(FuncAddr), RefIsNull, RefAsNonNull, + RefI31, + I31GetS, + I31GetU, + RefEq, + RefTest(RefType), + RefCast(RefType), + BrOnCast(u32, RefType, bool), + + // > GC Objects + StructNew(TypeAddr), + StructNewDefault(TypeAddr), + StructGet(TypeAddr, u32), + StructGetS(TypeAddr, u32), + StructGetU(TypeAddr, u32), + StructSet(TypeAddr, u32), + ArrayNew(TypeAddr), + ArrayNewDefault(TypeAddr), + ArrayNewFixed(TypeAddr, u32), + ArrayNewData(TypeAddr, DataAddr), + ArrayNewElem(TypeAddr, ElemAddr), + ArrayGet(TypeAddr), + ArrayGetS(TypeAddr), + ArrayGetU(TypeAddr), + ArraySet(TypeAddr), + ArrayLen, + ArrayFill(TypeAddr), + ArrayCopy(TypeAddr, TypeAddr), + ArrayInitData(TypeAddr, DataAddr), + ArrayInitElem(TypeAddr, ElemAddr), // > Numeric Instructions // See diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index 0b15927..c461296 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -22,9 +22,11 @@ const fn max_page_count(page_size: u64) -> u64 { mod instructions; mod reference; +mod types; mod value; pub use instructions::*; pub use reference::*; +pub use types::*; pub use value::*; #[cfg(feature = "archive")] @@ -81,10 +83,10 @@ pub struct ModuleInner { /// Contains data from to the `code`, `func`, and `type` sections of the original WebAssembly module. pub funcs: Box<[Arc]>, - /// A vector of type definitions, indexed by `TypeAddr` + /// The dense type definitions, indexed by `TypeAddr`. /// /// Corresponds to the `type` section of the original WebAssembly module. - pub func_types: Box<[FuncType]>, + pub types: TypeSection, /// Function index to type index mapping in module index space, including imports. pub func_type_idxs: Box<[TypeAddr]>, @@ -135,7 +137,7 @@ impl Module { pub fn imports(&self) -> impl Iterator> { self.0.imports.iter().filter_map(|import| { let ty = match &import.kind { - ImportKind::Function(type_idx) => Some(ImportType::Func(self.0.func_types.get(*type_idx as usize)?)), + ImportKind::Function(type_idx) => Some(ImportType::Func(self.0.types.get(*type_idx)?.as_func()?)), ImportKind::Table(table_ty) => Some(ImportType::Table(table_ty)), ImportKind::Memory(memory_ty) => Some(ImportType::Memory(memory_ty)), ImportKind::Global(global_ty) => Some(ImportType::Global(global_ty)), @@ -178,7 +180,7 @@ impl Module { let import = imports.nth(index)?; match &import.kind { - ImportKind::Function(type_idx) => Some(ExportType::Func(module.func_types.get(*type_idx as usize)?)), + ImportKind::Function(type_idx) => Some(ExportType::Func(module.types.get(*type_idx)?.as_func()?)), ImportKind::Table(table_ty) => Some(ExportType::Table(table_ty)), ImportKind::Memory(memory_ty) => Some(ExportType::Memory(memory_ty)), ImportKind::Global(global_ty) => Some(ExportType::Global(global_ty)), @@ -194,7 +196,7 @@ impl Module { imported_type(&self.0, ExternalKind::Func, idx)? } else { let type_idx = *self.0.func_type_idxs.get(idx)?; - ExportType::Func(self.0.func_types.get(type_idx as usize)?) + ExportType::Func(self.0.types.get(type_idx)?.as_func()?) } } ExternalKind::Table => { @@ -360,90 +362,6 @@ impl ExternVal { } } -/// The type of a WebAssembly Function. -/// -/// See -#[derive(Clone, PartialEq, Eq, Default)] -#[cfg_attr(feature = "debug", derive(Debug))] -#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] -pub struct FuncType { - data: Box<[WasmType]>, - param_count: u16, -} - -impl FuncType { - /// Create a new function type. - pub fn new(params: &[WasmType], results: &[WasmType]) -> Self { - let data: Box<[WasmType]> = params.iter().cloned().chain(results.iter().cloned()).collect(); - Self { data, param_count: params.len() as u16 } - } - - /// Get the parameter types of this function type. - pub fn params(&self) -> &[WasmType] { - &self.data[..self.param_count as usize] - } - - /// Get the result types of this function type. - pub fn results(&self) -> &[WasmType] { - &self.data[self.param_count as usize..] - } - - /// Compare function types while resolving concrete references in their respective type spaces. - pub fn equivalent(&self, types: &[FuncType], other: &Self, other_types: &[FuncType]) -> bool { - fn refs_equal( - left_types: &[FuncType], - left: RefType, - right_types: &[FuncType], - right: RefType, - visited: &mut alloc::vec::Vec<(u32, u32)>, - ) -> bool { - if left.is_nullable() != right.is_nullable() { - return false; - } - match (left.type_index(), right.type_index()) { - (Some(left_idx), Some(right_idx)) => { - if visited.contains(&(left_idx, right_idx)) { - return true; - } - let (Some(left), Some(right)) = - (left_types.get(left_idx as usize), right_types.get(right_idx as usize)) - else { - return false; - }; - visited.push((left_idx, right_idx)); - funcs_equal(left, left_types, right, right_types, visited) - } - (None, None) => left.abstract_heap_type() == right.abstract_heap_type(), - _ => false, - } - } - - fn funcs_equal( - left: &FuncType, - left_types: &[FuncType], - right: &FuncType, - right_types: &[FuncType], - visited: &mut alloc::vec::Vec<(u32, u32)>, - ) -> bool { - left.params().len() == right.params().len() - && left.results().len() == right.results().len() - && left.params().iter().chain(left.results()).zip(right.params().iter().chain(right.results())).all( - |(&left, &right)| match (left, right) { - (WasmType::Ref(left), WasmType::Ref(right)) => { - refs_equal(left_types, left, right_types, right, visited) - } - _ => left == right, - }, - ) - } - - if core::ptr::eq(types, other_types) && self == other { - return true; - } - funcs_equal(self, types, other, other_types, &mut alloc::vec::Vec::new()) - } -} - #[derive(Default, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] diff --git a/crates/types/src/reference.rs b/crates/types/src/reference.rs index ee66965..884d330 100644 --- a/crates/types/src/reference.rs +++ b/crates/types/src/reference.rs @@ -1,3 +1,12 @@ +const HOST_REF_TAG: u32 = 1 << 30; + +const fn encode_host_ref(addr: u32) -> Option { + if addr >= HOST_REF_TAG - 1 { + return None; + } + Some((addr | HOST_REF_TAG).wrapping_add(1).wrapping_mul(2)) +} + /// An abstract WebAssembly heap type. /// /// This contains exactly the abstract heap types in core Wasm 3.0. @@ -31,7 +40,8 @@ pub enum AbstractHeapType { /// [nullable:1 concrete:1 payload:30] /// ``` /// -/// For concrete types, `payload` is a module type index. +/// For concrete types, `payload` is a module type index before instantiation +/// and a canonical store type address at runtime. /// Otherwise, it is an [`AbstractHeapType`]. #[derive(Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -116,9 +126,7 @@ impl RefType { #[inline] pub const fn is_func(self) -> bool { - // TODO(wasm3): Classify concrete refs from the module type definition once GC types are represented. - self.is_concrete() - || matches!(self.abstract_heap_type(), Some(AbstractHeapType::Func | AbstractHeapType::NoFunc)) + matches!(self.abstract_heap_type(), Some(AbstractHeapType::Func | AbstractHeapType::NoFunc)) } #[inline] @@ -132,6 +140,7 @@ impl RefType { } } +/// A host-facing WebAssembly reference value. #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -143,19 +152,9 @@ pub enum RefValue { Exn(ExnRef), } -impl RefValue { - /// Return the reference's raw representation, or `None` for null. - pub const fn raw(self) -> Option { - match self { - Self::Null => None, - Self::Func(value) => Some(value.addr()), - Self::Extern(value) => Some(value.addr()), - Self::Any(value) => Some(value.raw()), - Self::Exn(value) => Some(value.addr()), - } - } -} - +/// A reference to a function in a store. +/// +/// The payload is the function's store-local address. #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -173,6 +172,11 @@ impl FuncRef { } } +/// An opaque external reference. +/// +/// Packed as `[payload:31 i31:1]`. Host addresses use the upper payload +/// category, Store-managed objects use the lower category, and odd values +/// contain an externalized i31. #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -181,15 +185,35 @@ pub struct ExternRef(u32); impl ExternRef { #[inline] pub const fn new(addr: u32) -> Self { - Self(addr) + let Some(value) = Self::try_new(addr) else { panic!("external reference address is too large") }; + value } + /// Creates an external reference when `addr` fits the runtime encoding. #[inline] - pub const fn addr(self) -> u32 { + pub const fn try_new(addr: u32) -> Option { + match encode_host_ref(addr) { + Some(raw) => Some(Self(raw)), + None => None, + } + } + + #[doc(hidden)] + #[inline] + pub const fn from_raw(raw: u32) -> Self { + Self(raw) + } + + #[doc(hidden)] + #[inline] + pub const fn raw(self) -> u32 { self.0 } } +/// A reference to an exception in a store. +/// +/// The payload is the exception's store-local address. #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -207,14 +231,30 @@ impl ExnRef { } } +/// A WebAssembly `anyref` value. +/// +/// Packed as: +/// +/// ```text +/// [payload:31 i31:1] +/// ``` +/// +/// Odd values contain an inline signed i31. Non-zero even values are reserved +/// for store-managed references, and zero is reserved for null by the runtime. #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub struct AnyRef(u32); impl AnyRef { - // Odd values are inline i31s. - // Even values are GC object handles. + /// Creates a host reference when `addr` fits the runtime encoding. + #[inline] + pub const fn from_host(addr: u32) -> Option { + match encode_host_ref(addr) { + Some(raw) => Some(Self(raw)), + None => None, + } + } #[doc(hidden)] #[inline] @@ -234,22 +274,21 @@ impl AnyRef { if self.0 & 1 == 1 { Some((self.0 as i32) >> 1) } else { None } } - pub const fn from_gc_addr(addr: u32) -> Option { - match addr.checked_add(1) { - Some(raw) => match raw.checked_mul(2) { - Some(raw) => Some(Self(raw)), - None => None, - }, - None => None, - } - } - - pub const fn gc_addr(self) -> Option { - if self.0 != 0 && self.0 & 1 == 0 { Some(self.0 / 2 - 1) } else { None } - } - #[inline] pub const fn raw(self) -> u32 { self.0 } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn host_reference_encoding_is_checked_and_unique() { + assert_ne!(AnyRef::from_host(0), AnyRef::from_host(1)); + assert!(AnyRef::from_host(HOST_REF_TAG - 2).is_some()); + assert!(AnyRef::from_host(HOST_REF_TAG - 1).is_none()); + assert!(ExternRef::try_new(u32::MAX).is_none()); + } +} diff --git a/crates/types/src/types.rs b/crates/types/src/types.rs new file mode 100644 index 0000000..214ada6 --- /dev/null +++ b/crates/types/src/types.rs @@ -0,0 +1,158 @@ +use alloc::boxed::Box; + +use crate::{TypeAddr, WasmType}; + +/// The dense type index space of a WebAssembly module. +#[derive(Clone, PartialEq, Eq, Default)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct TypeSection { + /// Types in module index order. + pub types: Box<[SubType]>, + /// Number of types in each recursive group, in section order. + pub rec_group_lengths: Box<[u32]>, +} + +impl TypeSection { + #[inline] + pub fn get(&self, index: TypeAddr) -> Option<&SubType> { + self.types.get(index as usize) + } + + #[inline] + pub fn len(&self) -> usize { + self.types.len() + } + + #[inline] + pub fn is_empty(&self) -> bool { + self.types.is_empty() + } +} + +/// A type with optional declared subtyping. +#[derive(Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct SubType { + pub is_final: bool, + pub supertype: Option, + pub composite: CompositeType, +} + +impl SubType { + #[inline] + pub const fn as_func(&self) -> Option<&FuncType> { + self.composite.as_func() + } + + #[inline] + pub const fn as_struct(&self) -> Option<&StructType> { + self.composite.as_struct() + } + + #[inline] + pub const fn as_array(&self) -> Option<&ArrayType> { + self.composite.as_array() + } +} + +/// A function, struct, or array type. +#[derive(Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub enum CompositeType { + Func(FuncType), + Struct(StructType), + Array(ArrayType), +} + +impl CompositeType { + #[inline] + pub const fn as_func(&self) -> Option<&FuncType> { + match self { + Self::Func(ty) => Some(ty), + _ => None, + } + } + + #[inline] + pub const fn as_struct(&self) -> Option<&StructType> { + match self { + Self::Struct(ty) => Some(ty), + _ => None, + } + } + + #[inline] + pub const fn as_array(&self) -> Option<&ArrayType> { + match self { + Self::Array(ty) => Some(ty), + _ => None, + } + } +} + +/// The type of a WebAssembly function. +/// +/// See +#[derive(Clone, PartialEq, Eq, Default)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct FuncType { + data: Box<[WasmType]>, + param_count: u16, +} + +impl FuncType { + /// Create a new function type. + pub fn new(params: &[WasmType], results: &[WasmType]) -> Self { + let data: Box<[WasmType]> = params.iter().cloned().chain(results.iter().cloned()).collect(); + Self { data, param_count: params.len() as u16 } + } + + /// Get the parameter types of this function type. + pub fn params(&self) -> &[WasmType] { + &self.data[..self.param_count as usize] + } + + /// Get the result types of this function type. + pub fn results(&self) -> &[WasmType] { + &self.data[self.param_count as usize..] + } +} + +/// A WebAssembly struct type. +#[derive(Clone, PartialEq, Eq, Default)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct StructType { + pub fields: Box<[FieldType]>, +} + +/// A WebAssembly array type. +#[derive(Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct ArrayType { + pub field: FieldType, +} + +/// A struct field or array element type. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct FieldType { + pub storage: StorageType, + pub mutable: bool, +} + +/// A field's packed or unpacked storage type. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub enum StorageType { + I8, + I16, + Value(WasmType), +} diff --git a/crates/types/src/value.rs b/crates/types/src/value.rs index 92c660b..f0a576b 100644 --- a/crates/types/src/value.rs +++ b/crates/types/src/value.rs @@ -54,7 +54,7 @@ impl WasmValue { | (Self::V128(_), WasmType::V128) => true, (Self::Ref(RefValue::Null), WasmType::Ref(ty)) => ty.is_nullable(), (Self::Ref(RefValue::Func(_)), WasmType::Ref(ty)) => { - ty.is_concrete() || matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Func)) + matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Func)) } (Self::Ref(RefValue::Extern(_)), WasmType::Ref(ty)) => { matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Extern)) @@ -62,12 +62,42 @@ impl WasmValue { (Self::Ref(RefValue::Exn(_)), WasmType::Ref(ty)) => { matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Exn)) } - (Self::Ref(RefValue::Any(_)), WasmType::Ref(ty)) => !ty.is_func() && !ty.is_extern() && !ty.is_exn(), + (Self::Ref(RefValue::Any(value)), WasmType::Ref(ty)) => matches!( + (value.as_i31(), ty.abstract_heap_type()), + ( + Some(_), + Some(crate::AbstractHeapType::I31 | crate::AbstractHeapType::Eq | crate::AbstractHeapType::Any) + ) | (None, Some(crate::AbstractHeapType::Any)) + ), _ => false, } } } +#[cfg(test)] +mod tests { + use super::*; + use crate::{AbstractHeapType, AnyRef, FuncRef, RefType}; + + #[test] + fn concrete_references_require_store_type_information() { + let concrete = WasmType::Ref(RefType::new_concrete(false, 0).unwrap()); + + assert!(!WasmValue::from(FuncRef::new(0)).matches_type(concrete)); + assert!(!WasmValue::from(AnyRef::from_host(0).unwrap()).matches_type(concrete)); + } + + #[test] + fn i31_only_matches_its_store_independent_supertypes() { + let value = WasmValue::from(AnyRef::from_i31(0).unwrap()); + + for ty in [AbstractHeapType::I31, AbstractHeapType::Eq, AbstractHeapType::Any] { + assert!(value.matches_type(WasmType::Ref(RefType::new_abstract(false, ty)))); + } + assert!(!value.matches_type(WasmType::Ref(RefType::new_abstract(false, AbstractHeapType::Struct)))); + } +} + impl Debug for WasmValue { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { -- cgit v1.3.1 From 676be92cde66d7c20bfe11d64bfc3f5762c4c46e Mon Sep 17 00:00:00 2001 From: Henry Date: Sat, 8 Aug 2026 18:30:29 +0200 Subject: chore: store globals in different lanes based on size Signed-off-by: Henry --- CHANGELOG.md | 5 +- crates/parser/src/conversion.rs | 22 +- crates/parser/src/macros.rs | 2 +- crates/parser/src/optimize.rs | 8 +- crates/parser/src/visit.rs | 248 +++++++++------------ crates/tinywasm/src/imports.rs | 23 +- crates/tinywasm/src/interpreter/executor.rs | 50 ++--- .../tinywasm/src/interpreter/stack/value_stack.rs | 4 + crates/tinywasm/src/interpreter/values.rs | 40 +++- crates/tinywasm/src/reference.rs | 34 +-- crates/tinywasm/src/store/global.rs | 165 +++++++++++++- crates/tinywasm/src/store/mod.rs | 18 +- crates/tinywasm/src/store/state.rs | 64 ++++-- crates/tinywasm/tests/store_ownership.rs | 18 +- crates/tinywasm/tests/typed_globals.rs | 93 ++++++++ crates/types/src/instructions.rs | 7 +- crates/types/src/lib.rs | 41 +++- 17 files changed, 564 insertions(+), 278 deletions(-) create mode 100644 crates/tinywasm/tests/typed_globals.rs (limited to 'crates/parser/src/conversion.rs') diff --git a/CHANGELOG.md b/CHANGELOG.md index 38d4dd8..7ef6fb5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,16 +10,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Added support for the WebAssembly function-references proposal -- Added support for the WebAssembly garbage-collection proposal +- Added basic support for the WebAssembly garbage-collection proposal - Added `WasmValue::ty` and `WasmValue::matches_type` +- Added `ValueLane` for mapping WebAssembly value types to their physical 32-bit, 64-bit, or 128-bit storage lane. - Added a `validate` feature to `tinywasm` and `tinywasm-parser` (enabled by default) to optionally skip wasmparser validation for faster parsing of trusted modules. ### Changed - Module types now use one dense recursive type space, while function types are resolved through `Function::ty(&Store)`. +- Globals are stored in separate 32-bit, 64-bit, and 128-bit value lanes, avoiding tagged value conversion during guest execution. ### Fixed +- Directly defined imports now reject handles from a different `Store`. - Tail calls to host functions now return directly to the caller frame. ### Breaking Changes diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 8bc7df1..4073a8e 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -6,6 +6,14 @@ use alloc::{boxed::Box, format, vec::Vec}; use tinywasm_types::*; use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations, UnpackedIndex}; +pub(crate) fn value_lane(ty: wasmparser::ValType) -> ValueLane { + match ty { + wasmparser::ValType::I32 | wasmparser::ValType::F32 | wasmparser::ValType::Ref(_) => ValueLane::S32, + wasmparser::ValType::I64 | wasmparser::ValType::F64 => ValueLane::S64, + wasmparser::ValType::V128 => ValueLane::S128, + } +} + pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result { let kind = match element.kind { wasmparser::ElementKind::Active { table_index, offset_expr } => tinywasm_types::ElementKind::Active { @@ -116,12 +124,8 @@ pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result, - count: u32, - ty: wasmparser::ValType, -) -> Result<()> { - let size = crate::visit::OperandSize::from(ty); +fn extend_local_types(local_types: &mut Vec, count: u32, ty: wasmparser::ValType) -> Result<()> { + let size = value_lane(ty); let count = usize::try_from(count).map_err(|_| crate::ParseError::Other("local declaration count is too large".into()))?; local_types.reserve(count); @@ -166,9 +170,9 @@ pub(crate) fn convert_module_code( for ty in &local_types { let (count, error) = match ty { - crate::visit::OperandSize::S32 => (&mut local_counts.c32, "too many 32-bit locals"), - crate::visit::OperandSize::S64 => (&mut local_counts.c64, "too many 64-bit locals"), - crate::visit::OperandSize::S128 => (&mut local_counts.c128, "too many 128-bit locals"), + ValueLane::S32 => (&mut local_counts.c32, "too many 32-bit locals"), + ValueLane::S64 => (&mut local_counts.c64, "too many 64-bit locals"), + ValueLane::S128 => (&mut local_counts.c128, "too many 128-bit locals"), }; local_addr_map.push(*count); *count = count.checked_add(1).ok_or_else(|| crate::ParseError::Other(error.into()))?; diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs index 553f439..db1402d 100644 --- a/crates/parser/src/macros.rs +++ b/crates/parser/src/macros.rs @@ -141,7 +141,7 @@ pub(crate) mod visit { (@size Addr, $address:ident) => { $address }; (@size Field, $address:ident) => { $address }; - (@size $size:ident $(, $address:ident)?) => { OperandSize::$size }; + (@size $size:ident $(, $address:ident)?) => { ValueLane::$size }; } macro_rules! impl_visit_operator { diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs index 5c2d7d5..74a9fc0 100644 --- a/crates/parser/src/optimize.rs +++ b/crates/parser/src/optimize.rs @@ -93,7 +93,7 @@ fn rewrite( rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [GlobalGet(global)] => BinOpStackGlobal32(op, global)); + rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); if matches!(op, BinOp::IAdd) { rewrite!(instrs, i, [Const32(c)] => AddConst32(c)); rewrite!(instrs, i, [I32Add] => I32Add3); @@ -103,7 +103,7 @@ fn rewrite( let Some(op) = int_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [GlobalGet(global)] => BinOpStackGlobal32(op, global)); + rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); if matches!(op, BinOp::IShrS) { rewrite!(instrs, i, [BinOpLocalConst32(BinOp::IShl, local, 8), Const32(8)] => [LocalGet32(local), I32Extend8S]); rewrite!(instrs, i, [BinOpLocalConst32(BinOp::IShl, local, 16), Const32(16)] => [LocalGet32(local), I32Extend16S]); @@ -114,7 +114,7 @@ fn rewrite( rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); rewrite!(instrs, i, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [GlobalGet(global)] => BinOpStackGlobal64(op, global)); + rewrite!(instrs, i, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); if matches!(op, BinOp::IAdd) { rewrite!(instrs, i, [Const64(c)] => AddConst64(c)); rewrite!(instrs, i, [I64Add] => I64Add3); @@ -124,7 +124,7 @@ fn rewrite( let Some(op) = int_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [GlobalGet(global)] => BinOpStackGlobal64(op, global)); + rewrite!(instrs, i, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); if matches!(op, BinOp::IShrS) { rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 8), Const64(8)] => [LocalGet64(local), I64Extend8S]); rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 16), Const64(16)] => [LocalGet64(local), I64Extend16S]); diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index 4437242..46d1f9f 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -1,9 +1,13 @@ -use crate::{Result, conversion::convert_heap_type, macros::visit::*}; +use crate::{ + Result, + conversion::{convert_heap_type, value_lane}, + macros::visit::*, +}; use alloc::string::ToString; use alloc::vec::Vec; use tinywasm_types::{ - Global, Import, ImportKind, Instruction, MemoryArch, MemoryArg, MemoryType, StorageType, SubType, TableDefinition, - TypeSection, ValueCounts, WasmFunctionData, WasmType, + Global, Import, ImportKind, Instruction, MemoryArg, MemoryType, StorageType, SubType, TableDefinition, TypeSection, + ValueCounts, ValueLane, WasmFunctionData, }; use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator}; @@ -18,52 +22,6 @@ enum BlockKind { If, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum OperandSize { - S32, - S64, - S128, -} - -impl OperandSize { - fn choose(self, s32: T, s64: T, s128: T) -> T { - match self { - Self::S32 => s32, - Self::S64 => s64, - Self::S128 => s128, - } - } -} - -impl From for OperandSize { - fn from(ty: wasmparser::ValType) -> Self { - match ty { - wasmparser::ValType::I32 | wasmparser::ValType::F32 | wasmparser::ValType::Ref(_) => Self::S32, - wasmparser::ValType::I64 | wasmparser::ValType::F64 => Self::S64, - wasmparser::ValType::V128 => Self::S128, - } - } -} - -impl From<&WasmType> for OperandSize { - fn from(ty: &WasmType) -> Self { - match ty { - WasmType::I32 | WasmType::F32 | WasmType::Ref(_) => Self::S32, - WasmType::I64 | WasmType::F64 => Self::S64, - WasmType::V128 => Self::S128, - } - } -} - -impl From for OperandSize { - fn from(arch: MemoryArch) -> Self { - match arch { - MemoryArch::I32 => Self::S32, - MemoryArch::I64 => Self::S64, - } - } -} - struct ControlFrame { kind: BlockKind, has_else: bool, @@ -71,8 +29,8 @@ struct ControlFrame { branch_jumps: Vec, height: usize, base: ValueCounts, - params: Vec, - results: Vec, + params: Vec, + results: Vec, unreachable: bool, entry_unreachable: bool, end_reachable: bool, @@ -80,16 +38,16 @@ struct ControlFrame { #[derive(Clone)] pub(crate) struct Signature { - pub params: Vec, - results: Vec, + pub params: Vec, + results: Vec, } pub(crate) struct ModuleMetadata { signatures: Vec>, functions: Vec, - globals: Vec, - memories: Vec, - tables: Vec, + globals: Vec, + memories: Vec, + tables: Vec, types: Vec, } @@ -103,10 +61,10 @@ pub(crate) struct FunctionBuilder<'a> { instructions: Vec, data: FunctionDataBuilder, control_stack: Vec, - operand_stack: Vec, + operand_stack: Vec, lane_counts: ValueCounts, metadata: &'a ModuleMetadata, - local_types: Vec, + local_types: Vec, local_addr_map: Vec, } @@ -114,7 +72,7 @@ impl<'a> FunctionBuilder<'a> { pub(crate) fn new( metadata: &'a ModuleMetadata, signature: Signature, - local_types: Vec, + local_types: Vec, local_addr_map: Vec, body_size: usize, ) -> Self { @@ -149,7 +107,7 @@ impl<'a> FunctionBuilder<'a> { instruction: fn(u32, u32) -> Instruction, ) -> Result<()> { let size = ModuleMetadata::storage_size(self.metadata.struct_field(type_index, field_index)?.storage); - self.emit(&[OperandSize::S32], &[size], instruction(type_index, field_index)) + self.emit(&[ValueLane::S32], &[size], instruction(type_index, field_index)) } } @@ -161,6 +119,13 @@ struct ValidateThenVisit<'a, 'm> { } impl ModuleMetadata { + fn address_lane(arch: tinywasm_types::MemoryArch) -> ValueLane { + match arch { + tinywasm_types::MemoryArch::I32 => ValueLane::S32, + tinywasm_types::MemoryArch::I64 => ValueLane::S64, + } + } + pub(crate) fn new( types: &TypeSection, code_type_addrs: &[u32], @@ -177,24 +142,24 @@ impl ModuleMetadata { for import in imports { match &import.kind { ImportKind::Function(ty) => functions.push(*ty), - ImportKind::Global(ty) => global_sizes.push(OperandSize::from(&ty.ty)), - ImportKind::Memory(ty) => memory_sizes.push(OperandSize::from(ty.arch())), - ImportKind::Table(ty) => table_sizes.push(OperandSize::from(ty.arch())), + ImportKind::Global(ty) => global_sizes.push(ValueLane::from(&ty.ty)), + ImportKind::Memory(ty) => memory_sizes.push(Self::address_lane(ty.arch())), + ImportKind::Table(ty) => table_sizes.push(Self::address_lane(ty.arch())), } } functions.extend_from_slice(code_type_addrs); - global_sizes.extend(globals.iter().map(|global| OperandSize::from(&global.ty.ty))); - memory_sizes.extend(memories.iter().map(|ty| OperandSize::from(ty.arch()))); - table_sizes.extend(tables.iter().map(|table| OperandSize::from(table.ty.arch()))); + global_sizes.extend(globals.iter().map(|global| ValueLane::from(&global.ty.ty))); + memory_sizes.extend(memories.iter().map(|ty| Self::address_lane(ty.arch()))); + table_sizes.extend(tables.iter().map(|table| Self::address_lane(table.ty.arch()))); let signatures = types .types .iter() .map(|ty| { ty.as_func().map(|ty| Signature { - params: ty.params().iter().map(OperandSize::from).collect(), - results: ty.results().iter().map(OperandSize::from).collect(), + params: ty.params().iter().map(ValueLane::from).collect(), + results: ty.results().iter().map(ValueLane::from).collect(), }) }) .collect(); @@ -223,29 +188,29 @@ impl ModuleMetadata { self.signature(ty) } - fn global_size(&self, idx: u32) -> Result { + fn global_size(&self, idx: u32) -> Result { Self::indexed_size(&self.globals, "global", idx) } - fn memory_size(&self, idx: u32) -> Result { + fn memory_size(&self, idx: u32) -> Result { Self::indexed_size(&self.memories, "memory", idx) } - fn table_size(&self, idx: u32) -> Result { + fn table_size(&self, idx: u32) -> Result { Self::indexed_size(&self.tables, "table", idx) } - fn indexed_size(sizes: &[OperandSize], entity: &str, idx: u32) -> Result { + fn indexed_size(sizes: &[ValueLane], entity: &str, idx: u32) -> Result { sizes .get(idx as usize) .copied() .ok_or_else(|| crate::ParseError::Other(alloc::format!("{entity} index out of bounds: {idx}"))) } - fn storage_size(storage: StorageType) -> OperandSize { + fn storage_size(storage: StorageType) -> ValueLane { match storage { - StorageType::I8 | StorageType::I16 => OperandSize::S32, - StorageType::Value(ref ty) => OperandSize::from(ty), + StorageType::I8 | StorageType::I16 => ValueLane::S32, + StorageType::Value(ref ty) => ValueLane::from(ty), } } @@ -291,7 +256,7 @@ impl VisitSimdOperator<'_> for ValidateThenVisit<'_, '_> { pub(crate) fn process_operators( body: FunctionBody<'_>, - local_types: Vec, + local_types: Vec, local_addr_map: Vec, metadata: &ModuleMetadata, ty_idx: u32, @@ -327,7 +292,7 @@ pub(crate) fn process_operators( pub(crate) fn process_operators_and_validate( mut validator: FuncValidator, body: FunctionBody<'_>, - local_types: Vec, + local_types: Vec, local_addr_map: Vec, metadata: &ModuleMetadata, ty_idx: u32, @@ -470,7 +435,6 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { effect [S32] => [S32] { visit_f32_reinterpret_i32, visit_i32_reinterpret_f32 } effect [S64] => [S64] { visit_f64_reinterpret_i64, visit_i64_reinterpret_f64 } terminating [] => [] { visit_unreachable => Unreachable, visit_return => Return } - global [] => [Addr] { visit_global_get(global_index: u32) => GlobalGet } memory_index [] => [Addr] { visit_memory_size(memory: u32) => MemorySize } memory_index [Addr] => [Addr] { visit_memory_grow(memory: u32) => MemoryGrow } memory_index [Addr, S32, Addr] => [] { @@ -514,7 +478,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { .iter() .map(|field| ModuleMetadata::storage_size(field.storage)) .collect::>(); - self.emit(&inputs, &[OperandSize::S32], Instruction::StructNew(type_index)) + self.emit(&inputs, &[ValueLane::S32], Instruction::StructNew(type_index)) } fn visit_struct_get(&mut self, type_index: u32, field_index: u32) -> Self::Output { @@ -531,7 +495,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Self::Output { let size = ModuleMetadata::storage_size(self.metadata.struct_field(type_index, field_index)?.storage); - self.emit(&[OperandSize::S32, size], &[], Instruction::StructSet(type_index, field_index)) + self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(type_index, field_index)) } fn visit_array_new_fixed(&mut self, type_index: u32, array_size: u32) -> Self::Output { @@ -539,7 +503,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { for _ in 0..array_size { self.pop_expect(size)?; } - self.push_sizes(&[OperandSize::S32])?; + self.push_sizes(&[ValueLane::S32])?; self.instructions.push(Instruction::ArrayNewFixed(type_index, array_size)); Ok(()) } @@ -559,7 +523,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_call_ref(&mut self, type_index: u32) -> Self::Output { let signature = self.metadata.signature(type_index)?.clone(); let mut inputs = signature.params; - inputs.push(OperandSize::S32); + inputs.push(ValueLane::S32); self.emit(&inputs, &signature.results, Instruction::CallRef(type_index)) } @@ -584,7 +548,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_return_call_ref(&mut self, type_index: u32) -> Self::Output { let signature = self.metadata.signature(type_index)?.clone(); let mut inputs = signature.params; - inputs.push(OperandSize::S32); + inputs.push(ValueLane::S32); self.apply_effect(&inputs, &[])?; self.mark_unreachable(); self.instructions.push(Instruction::ReturnCallRef(type_index)); @@ -593,7 +557,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_global_set(&mut self, global_index: u32) -> Self::Output { let size = self.metadata.global_size(global_index)?; - let instruction = size.choose( + let instruction = size.select( Instruction::GlobalSet32(global_index), Instruction::GlobalSet64(global_index), Instruction::GlobalSet128(global_index), @@ -601,21 +565,31 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { self.emit(&[size], &[], instruction) } + fn visit_global_get(&mut self, global_index: u32) -> Self::Output { + let size = self.metadata.global_size(global_index)?; + let instruction = size.select( + Instruction::GlobalGet32(global_index), + Instruction::GlobalGet64(global_index), + Instruction::GlobalGet128(global_index), + ); + self.emit(&[], &[size], instruction) + } + fn visit_drop(&mut self) -> Self::Output { - let size = self.operand_stack.last().copied().unwrap_or(OperandSize::S32); - let instruction = size.choose(Instruction::Drop32, Instruction::Drop64, Instruction::Drop128); + let size = self.operand_stack.last().copied().unwrap_or(ValueLane::S32); + let instruction = size.select(Instruction::Drop32, Instruction::Drop64, Instruction::Drop128); self.emit(&[size], &[], instruction) } fn visit_select(&mut self) -> Self::Output { - let size = self.operand_stack.iter().rev().nth(1).copied().unwrap_or(OperandSize::S32); - let instruction = size.choose(Instruction::Select32, Instruction::Select64, Instruction::Select128); - self.emit(&[size, size, OperandSize::S32], &[size], instruction) + let size = self.operand_stack.iter().rev().nth(1).copied().unwrap_or(ValueLane::S32); + let instruction = size.select(Instruction::Select32, Instruction::Select64, Instruction::Select128); + self.emit(&[size, size, ValueLane::S32], &[size], instruction) } fn visit_local_get(&mut self, idx: u32) -> Self::Output { let (size, local_idx) = self.local(idx)?; - let instruction = size.choose( + let instruction = size.select( Instruction::LocalGet32(local_idx), Instruction::LocalGet64(local_idx), Instruction::LocalGet128(local_idx), @@ -625,7 +599,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_local_set(&mut self, idx: u32) -> Self::Output { let (size, local_idx) = self.local(idx)?; - let instruction = size.choose( + let instruction = size.select( Instruction::LocalSet32(local_idx), Instruction::LocalSet64(local_idx), Instruction::LocalSet128(local_idx), @@ -637,21 +611,21 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { let (size, local_idx) = self.local(idx)?; self.apply_effect(&[size], &[size])?; let src = match (size, self.instructions.last()) { - (OperandSize::S32, Some(Instruction::LocalGet32(src))) => Some(*src), - (OperandSize::S64, Some(Instruction::LocalGet64(src))) => Some(*src), - (OperandSize::S128, Some(Instruction::LocalGet128(src))) => Some(*src), + (ValueLane::S32, Some(Instruction::LocalGet32(src))) => Some(*src), + (ValueLane::S64, Some(Instruction::LocalGet64(src))) => Some(*src), + (ValueLane::S128, Some(Instruction::LocalGet128(src))) => Some(*src), _ => None, }; if let Some(src) = src { self.instructions.pop(); let instructions = match size { - OperandSize::S32 => [Instruction::LocalCopy32(src, local_idx), Instruction::LocalGet32(local_idx)], - OperandSize::S64 => [Instruction::LocalCopy64(src, local_idx), Instruction::LocalGet64(local_idx)], - OperandSize::S128 => [Instruction::LocalCopy128(src, local_idx), Instruction::LocalGet128(local_idx)], + ValueLane::S32 => [Instruction::LocalCopy32(src, local_idx), Instruction::LocalGet32(local_idx)], + ValueLane::S64 => [Instruction::LocalCopy64(src, local_idx), Instruction::LocalGet64(local_idx)], + ValueLane::S128 => [Instruction::LocalCopy128(src, local_idx), Instruction::LocalGet128(local_idx)], }; self.instructions.extend(instructions); } else { - self.instructions.push(size.choose( + self.instructions.push(size.select( Instruction::LocalTee32(local_idx), Instruction::LocalTee64(local_idx), Instruction::LocalTee128(local_idx), @@ -669,7 +643,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_if(&mut self, ty: wasmparser::BlockType) -> Self::Output { - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; self.instructions.push(Instruction::JumpIfZero32(0)); self.push_control(BlockKind::If, ty, Some(self.instructions.len() - 1)) } @@ -721,7 +695,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_br_if(&mut self, depth: u32) -> Self::Output { - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; let cond_jump_ip = self.instructions.len(); self.instructions.push(Instruction::JumpIfZero32(0)); @@ -745,7 +719,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_br_table(&mut self, targets: wasmparser::BrTable<'_>) -> Self::Output { let ts = targets.targets().collect::, wasmparser::Error>>()?; - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; let default_depth = targets.default(); let len = ts.len() as u32; @@ -819,24 +793,24 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_f32_const(&mut self, val: wasmparser::Ieee32) -> Self::Output { - self.emit(&[], &[OperandSize::S32], Instruction::Const32(val.bits() as i32)) + self.emit(&[], &[ValueLane::S32], Instruction::Const32(val.bits() as i32)) } fn visit_f64_const(&mut self, val: wasmparser::Ieee64) -> Self::Output { - self.emit(&[], &[OperandSize::S64], Instruction::Const64(val.bits() as i64)) + self.emit(&[], &[ValueLane::S64], Instruction::Const64(val.bits() as i64)) } fn visit_table_copy(&mut self, dst_table: u32, src_table: u32) -> Self::Output { let dst = self.metadata.table_size(dst_table)?; let src = self.metadata.table_size(src_table)?; - let len = if dst == OperandSize::S32 || src == OperandSize::S32 { OperandSize::S32 } else { OperandSize::S64 }; + let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; self.emit(&[dst, src, len], &[], Instruction::TableCopy { dst_table, src_table }) } fn visit_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Self::Output { let dst = self.metadata.memory_size(dst_mem)?; let src = self.metadata.memory_size(src_mem)?; - let len = if dst == OperandSize::S32 || src == OperandSize::S32 { OperandSize::S32 } else { OperandSize::S64 }; + let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; self.emit(&[dst, src, len], &[], Instruction::MemoryCopy { dst_mem, src_mem }) } @@ -859,41 +833,41 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_br_on_null(&mut self, relative_depth: u32) -> Self::Output { - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; let fallthrough_jump = self.instructions.len(); self.instructions.push(Instruction::JumpIfRefNonNull(0)); self.emit_dropkeep_to_label(relative_depth)?; self.emit_branch_jump_or_return(relative_depth)?; self.patch_jump(fallthrough_jump, self.instructions.len()); - self.push_sizes(&[OperandSize::S32]) + self.push_sizes(&[ValueLane::S32]) } fn visit_br_on_non_null(&mut self, relative_depth: u32) -> Self::Output { - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; let fallthrough_jump = self.instructions.len(); self.instructions.push(Instruction::JumpIfRefNull(0)); - self.push_sizes(&[OperandSize::S32])?; + self.push_sizes(&[ValueLane::S32])?; self.emit_dropkeep_to_label(relative_depth)?; - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; self.emit_branch_jump_or_return(relative_depth)?; self.patch_jump(fallthrough_jump, self.instructions.len()); Ok(()) } fn visit_typed_select_multi(&mut self, tys: Vec) -> Self::Output { - let sizes: Vec<_> = tys.into_iter().map(OperandSize::from).collect(); + let sizes: Vec<_> = tys.into_iter().map(value_lane).collect(); let counts = Self::value_counts(&sizes); self.emit( - &[sizes.as_slice(), sizes.as_slice(), &[OperandSize::S32]].concat(), + &[sizes.as_slice(), sizes.as_slice(), &[ValueLane::S32]].concat(), &sizes, Instruction::SelectMulti(counts), ) } fn visit_typed_select(&mut self, ty: wasmparser::ValType) -> Self::Output { - let size = OperandSize::from(ty); - let instruction = size.choose(Instruction::Select32, Instruction::Select64, Instruction::Select128); - self.emit(&[size, size, OperandSize::S32], &[size], instruction) + let size = value_lane(ty); + let instruction = size.select(Instruction::Select32, Instruction::Select64, Instruction::Select128); + self.emit(&[size, size, ValueLane::S32], &[size], instruction) } } @@ -1085,8 +1059,8 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { fn visit_i8x16_shuffle(&mut self, lanes: [u8; 16]) -> Self::Output { self.emit( - &[OperandSize::S128, OperandSize::S128], - &[OperandSize::S128], + &[ValueLane::S128, ValueLane::S128], + &[ValueLane::S128], Instruction::I8x16Shuffle(self.data.v128_constants.len() as u32), )?; self.data.v128_constants.push(lanes); @@ -1094,7 +1068,7 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { } fn visit_v128_const(&mut self, value: wasmparser::V128) -> Self::Output { - self.emit(&[], &[OperandSize::S128], Instruction::Const128(self.data.v128_constants.len() as u32))?; + self.emit(&[], &[ValueLane::S128], Instruction::Const128(self.data.v128_constants.len() as u32))?; self.data.v128_constants.push(*value.bytes()); Ok(()) } @@ -1107,11 +1081,11 @@ impl FunctionBuilder<'_> { target: wasmparser::RefType, branch_on_fail: bool, ) -> Result<()> { - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; let target = convert_heap_type(target.heap_type(), target.is_nullable())?; let conditional_ip = self.instructions.len(); self.instructions.push(Instruction::BrOnCast(0, target, branch_on_fail)); - self.push_sizes(&[OperandSize::S32])?; + self.push_sizes(&[ValueLane::S32])?; self.emit_dropkeep_to_label(relative_depth)?; self.emit_branch_jump_or_return(relative_depth)?; self.patch_jump(conditional_ip, self.instructions.len()); @@ -1129,7 +1103,7 @@ impl FunctionBuilder<'_> { .ok_or_else(|| crate::ParseError::Other(alloc::format!("branch depth out of bounds: {depth}"))) } - fn local(&self, idx: u32) -> Result<(OperandSize, u16)> { + fn local(&self, idx: u32) -> Result<(ValueLane, u16)> { let size = *self .local_types .get(idx as usize) @@ -1142,12 +1116,12 @@ impl FunctionBuilder<'_> { } /// Pushes logical operands while maintaining the lane counts used by `DropKeep`. - fn push_sizes(&mut self, sizes: &[OperandSize]) -> Result<()> { + fn push_sizes(&mut self, sizes: &[ValueLane]) -> Result<()> { for &size in sizes { let count = match size { - OperandSize::S32 => &mut self.lane_counts.c32, - OperandSize::S64 => &mut self.lane_counts.c64, - OperandSize::S128 => &mut self.lane_counts.c128, + ValueLane::S32 => &mut self.lane_counts.c32, + ValueLane::S64 => &mut self.lane_counts.c64, + ValueLane::S128 => &mut self.lane_counts.c128, }; *count = count .checked_add(1) @@ -1158,7 +1132,7 @@ impl FunctionBuilder<'_> { } /// Pops an operand, allowing a polymorphic value at an unreachable frame base. - fn pop_expect(&mut self, expected: OperandSize) -> Result<()> { + fn pop_expect(&mut self, expected: ValueLane) -> Result<()> { let frame_height = self.control_stack.last().map_or(0, |frame| frame.height); if self.operand_stack.len() == frame_height && self.is_unreachable() { return Ok(()); @@ -1171,22 +1145,22 @@ impl FunctionBuilder<'_> { return Err(crate::ParseError::Other("logical operand width mismatch".into())); } match actual { - OperandSize::S32 => self.lane_counts.c32 -= 1, - OperandSize::S64 => self.lane_counts.c64 -= 1, - OperandSize::S128 => self.lane_counts.c128 -= 1, + ValueLane::S32 => self.lane_counts.c32 -= 1, + ValueLane::S64 => self.lane_counts.c64 -= 1, + ValueLane::S128 => self.lane_counts.c128 -= 1, } Ok(()) } /// Applies a declared logical stack effect in WebAssembly operand order. - fn apply_effect(&mut self, inputs: &[OperandSize], outputs: &[OperandSize]) -> Result<()> { + fn apply_effect(&mut self, inputs: &[ValueLane], outputs: &[ValueLane]) -> Result<()> { inputs.iter().rev().try_for_each(|&size| self.pop_expect(size))?; self.push_sizes(outputs)?; Ok(()) } /// Applies an instruction's stack effect before adding it to the bytecode. - fn emit(&mut self, inputs: &[OperandSize], outputs: &[OperandSize], instruction: Instruction) -> Result<()> { + fn emit(&mut self, inputs: &[ValueLane], outputs: &[ValueLane], instruction: Instruction) -> Result<()> { self.apply_effect(inputs, outputs)?; self.instructions.push(instruction); Ok(()) @@ -1212,9 +1186,7 @@ impl FunctionBuilder<'_> { fn push_control(&mut self, kind: BlockKind, ty: wasmparser::BlockType, initial_jump: Option) -> Result<()> { let signature = match ty { wasmparser::BlockType::Empty => Signature { params: Vec::new(), results: Vec::new() }, - wasmparser::BlockType::Type(ty) => { - Signature { params: Vec::new(), results: alloc::vec![OperandSize::from(ty)] } - } + wasmparser::BlockType::Type(ty) => Signature { params: Vec::new(), results: alloc::vec![value_lane(ty)] }, wasmparser::BlockType::FuncType(idx) => self.metadata.signature(idx)?.clone(), }; for &size in signature.params.iter().rev() { @@ -1263,13 +1235,13 @@ impl FunctionBuilder<'_> { } } - fn value_counts(sizes: &[OperandSize]) -> ValueCounts { + fn value_counts(sizes: &[ValueLane]) -> ValueCounts { let mut counts = ValueCounts::default(); for size in sizes { match size { - OperandSize::S32 => counts.c32 += 1, - OperandSize::S64 => counts.c64 += 1, - OperandSize::S128 => counts.c128 += 1, + ValueLane::S32 => counts.c32 += 1, + ValueLane::S64 => counts.c64 += 1, + ValueLane::S128 => counts.c128 += 1, } } counts diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs index 3a7c06d..6a399ee 100644 --- a/crates/tinywasm/src/imports.rs +++ b/crates/tinywasm/src/imports.rs @@ -224,9 +224,18 @@ impl Imports { for import in &*module.imports { let (val, func_handle) = if let Some(defined) = self.take_defined(import) { match defined { - Extern::Global(global) => (ExternVal::Global(global.0.addr), None), - Extern::Table(table) => (ExternVal::Table(table.0.addr), None), - Extern::Memory(memory) => (ExternVal::Memory(memory.0.addr), None), + Extern::Global(global) => { + global.0.validate_store(store)?; + (ExternVal::Global(global.0.addr), None) + } + Extern::Table(table) => { + table.0.validate_store(store)?; + (ExternVal::Table(table.0.addr), None) + } + Extern::Memory(memory) => { + memory.0.validate_store(store)?; + (ExternVal::Memory(memory.0.addr), None) + } Extern::Function(func) => (ExternVal::Func(func.addr()), Some(func)), } } else { @@ -246,11 +255,11 @@ impl Imports { match (val, &import.kind) { (ExternVal::Global(global_addr), ImportKind::Global(ty)) => { - let global = store.state.get_global(global_addr); + let global_ty = store.state.globals.ty(global_addr); let expected = ty.with_ty(crate::store::canonicalize_value_type(ty.ty, type_addrs)); - let compatible = global.ty.mutable == ty.mutable - && store.state.value_type_is_subtype(global.ty.ty, expected.ty) - && (!ty.mutable || store.state.value_type_is_subtype(expected.ty, global.ty.ty)); + let compatible = global_ty.mutable == ty.mutable + && store.state.value_type_is_subtype(global_ty.ty, expected.ty) + && (!ty.mutable || store.state.value_type_is_subtype(expected.ty, global_ty.ty)); if !compatible { cold_path(); return Err(LinkingError::incompatible_import_type(import).into()); diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index fb8fdec..f864972 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -123,6 +123,16 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let val = <$ty>::stack_peek(&self.store.value_stack); <$ty>::local_set(&mut self.store.value_stack, &self.cf, *$local_index, val); }}; + (global_get $ty:ty, $global_index:expr) => {{ + let addr = self.module.resolve_global_addr(*$global_index); + let value = <$ty>::global_get(&self.store.state.globals, addr); + <$ty>::stack_push(&mut self.store.value_stack, value)?; + }}; + (global_set $ty:ty, $global_index:expr) => {{ + let addr = self.module.resolve_global_addr(*$global_index); + let value = <$ty>::stack_pop(&mut self.store.value_stack); + <$ty>::global_set(&mut self.store.state.globals, addr, value); + }}; } macro_rules! exec_binop { @@ -200,12 +210,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); self.store.value_stack.push(value)?; }}; - (stack_global $vt:ident, $width:tt, $op:ident, $global:ident) => {{ - let TinyWasmValue::$vt(global_val) = - self.store.state.get_global_val(self.module.resolve_global_addr(*$global)) - else { - unreachable!("expected global to be Value32") - }; + (stack_global $vt:ty, $width:tt, $op:ident, $global:ident) => {{ + let global_val = + <$vt>::global_get(&self.store.state.globals, self.module.resolve_global_addr(*$global)); let stack_val = <$vt>::stack_pop(&mut self.store.value_stack); self.store.value_stack.push(exec_binop!($width, *$op, stack_val, global_val))?; }}; @@ -339,10 +346,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { LocalTee32(local_index) => stack_op!(local_tee Value32, local_index), LocalTee64(local_index) => stack_op!(local_tee Value64, local_index), LocalTee128(local_index) => stack_op!(local_tee Value128, local_index), - GlobalGet(global_index) => self.exec_global_get(*global_index)?, - GlobalSet32(global_index) => self.exec_global_set_32(*global_index), - GlobalSet64(global_index) => self.exec_global_set::(*global_index), - GlobalSet128(global_index) => self.exec_global_set::(*global_index), + GlobalGet32(global_index) => stack_op!(global_get Value32, global_index), + GlobalGet64(global_index) => stack_op!(global_get Value64, global_index), + GlobalGet128(global_index) => stack_op!(global_get Value128, global_index), + GlobalSet32(global_index) => stack_op!(global_set Value32, global_index), + GlobalSet64(global_index) => stack_op!(global_set Value64, global_index), + GlobalSet128(global_index) => stack_op!(global_set Value128, global_index), Const32(val) => self.exec_const(*val)?, Const64(val) => self.exec_const(*val)?, I64Eqz => stack_op!(unary i64 => i32, |v| i32::from(v == 0)), @@ -1336,27 +1345,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_global_get(&mut self, global_index: u32) -> Result<(), Trap> { - self.store.value_stack.push_dyn(self.store.state.get_global_val(self.module.resolve_global_addr(global_index))) - } - - fn exec_global_set(&mut self, global_index: u32) { - let global_addr = self.module.resolve_global_addr(global_index); - let value = ::stack_pop(&mut self.store.value_stack).into(); - self.store.state.set_global_val(global_addr, value); - } - - fn exec_global_set_32(&mut self, global_index: u32) { - let global_addr = self.module.resolve_global_addr(global_index); - let raw = ::stack_pop(&mut self.store.value_stack); - let value = match self.store.state.get_global(global_addr).ty.ty { - WasmType::I32 | WasmType::F32 => TinyWasmValue::Value32(raw), - WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::from_raw(raw)), - WasmType::I64 | WasmType::F64 | WasmType::V128 => unreachable!("invalid global.set.32 target type"), - }; - self.store.state.set_global_val(global_addr, value); - } - fn exec_const(&mut self, val: T) -> Result<(), Trap> { self.store.value_stack.push(val) } diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index 378dc7f..3b5dfe2 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -8,6 +8,10 @@ use crate::interpreter::*; use crate::{Result, Trap}; #[cfg_attr(feature = "debug", derive(Debug))] +/// Physical value lanes used by the interpreter. +/// +/// Guest values should normally be accessed through +/// [`InternalValue`] so their stack and global representation stays consistent. pub(crate) struct ValueStack { pub(crate) stack_32: Stack, pub(crate) stack_64: Stack, diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs index f034906..fae7876 100644 --- a/crates/tinywasm/src/interpreter/values.rs +++ b/crates/tinywasm/src/interpreter/values.rs @@ -1,6 +1,7 @@ use super::stack::{CallFrame, ValueStack}; +use crate::store::Globals; use crate::{Result, interpreter::simd::Value128}; -use tinywasm_types::{AnyRef, ExnRef, ExternRef, FuncRef, LocalAddr, RefValue, WasmType, WasmValue}; +use tinywasm_types::{AnyRef, ExnRef, ExternRef, FuncRef, GlobalAddr, LocalAddr, RefValue, WasmType, WasmValue}; pub(crate) type Value32 = u32; pub(crate) type Value64 = u64; @@ -179,7 +180,8 @@ mod sealed { pub trait Sealed {} } -pub(crate) trait InternalValue: sealed::Sealed + Into + Copy + Default { +/// Typed access to values in their physical [`ValueStack`] and [`Globals`] lanes. +pub(crate) trait InternalValue: sealed::Sealed + Copy + Default { fn stack_push(stack: &mut ValueStack, value: Self) -> Result<(), crate::Trap>; fn stack_pop(stack: &mut ValueStack) -> Self; fn stack_peek(stack: &ValueStack) -> Self; @@ -188,12 +190,16 @@ pub(crate) trait InternalValue: sealed::Sealed + Into + Copy + De fn local_set(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, value: Self); fn local_update(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, f: impl FnOnce(Self) -> Self); fn local_copy(stack: &mut ValueStack, frame: &CallFrame, from: LocalAddr, to: LocalAddr); + /// Gets a value from its physical global lane. + fn global_get(globals: &Globals, addr: GlobalAddr) -> Self; + /// Sets a value in its physical global lane. + fn global_set(globals: &mut Globals, addr: GlobalAddr, value: Self); } macro_rules! impl_internalvalue { ( $( - $variant:ident, $stack:ident, $stack_base:ident, $outer:ty, + $variant:ident, $stack:ident, $stack_base:ident, $global_get:ident, $global_set:ident, $outer:ty, |$to_value_v:ident| $to_value:expr, |$to_stack_v:ident| $to_stack:expr, |$from_stack_v:ident| $from_stack:expr @@ -248,6 +254,18 @@ macro_rules! impl_internalvalue { stack.$stack.copy(base + from as usize, base + to as usize); } + #[inline(always)] + fn global_get(globals: &Globals, addr: GlobalAddr) -> Self { + let $from_stack_v = globals.$global_get(addr); + $from_stack + } + + #[inline(always)] + fn global_set(globals: &mut Globals, addr: GlobalAddr, value: Self) { + let $to_stack_v = value; + globals.$global_set(addr, $to_stack); + } + #[inline(always)] fn stack_pop(stack: &mut ValueStack) -> Self { let $from_stack_v = stack.$stack.pop(); @@ -278,12 +296,12 @@ macro_rules! impl_internalvalue { } impl_internalvalue! { - Value32, stack_32, s32, u32, |v| v, |v| v, |v| v - Value64, stack_64, s64, u64, |v| v, |v| v, |v| v - Value32, stack_32, s32, i32, |v| v as u32, |v| v as u32, |v| v as i32 - Value64, stack_64, s64, i64, |v| v as u64, |v| v as u64, |v| v as i64 - Value32, stack_32, s32, f32, |v| f32::to_bits(v), |v| f32::to_bits(v), |v| f32::from_bits(v) - Value64, stack_64, s64, f64, |v| f64::to_bits(v), |v| f64::to_bits(v), |v| f64::from_bits(v) - ValueRef, stack_32, s32, ValueRef, |v| v, |v| v.raw(), |v| ValueRef(v) - Value128, stack_128, s128, Value128, |v| v, |v| v, |v| v + Value32, stack_32, s32, get_32, set_32, u32, |v| v, |v| v, |v| v + Value64, stack_64, s64, get_64, set_64, u64, |v| v, |v| v, |v| v + Value32, stack_32, s32, get_32, set_32, i32, |v| v as u32, |v| v as u32, |v| v as i32 + Value64, stack_64, s64, get_64, set_64, i64, |v| v as u64, |v| v as u64, |v| v as i64 + Value32, stack_32, s32, get_32, set_32, f32, |v| f32::to_bits(v), |v| f32::to_bits(v), |v| f32::from_bits(v) + Value64, stack_64, s64, get_64, set_64, f64, |v| f64::to_bits(v), |v| f64::to_bits(v), |v| f64::from_bits(v) + ValueRef, stack_32, s32, get_32, set_32, ValueRef, |v| v, |v| v.raw(), |v| ValueRef(v) + Value128, stack_128, s128, get_128, set_128, Value128, |v| v, |v| v, |v| v } diff --git a/crates/tinywasm/src/reference.rs b/crates/tinywasm/src/reference.rs index d8f9669..ad9cfd9 100644 --- a/crates/tinywasm/src/reference.rs +++ b/crates/tinywasm/src/reference.rs @@ -6,9 +6,9 @@ use alloc::string::{String, ToString}; use alloc::vec::Vec; use crate::interpreter::TinyWasmValue; -use crate::store::{GlobalInstance, TableInstance}; +use crate::store::TableInstance; use crate::{Error, MemoryInstance, Result, Store, Trap}; -use tinywasm_types::{Addr, GlobalAddr, GlobalType, MemAddr, MemoryType, TableAddr, TableType, WasmType, WasmValue}; +use tinywasm_types::{Addr, GlobalType, MemAddr, MemoryType, TableAddr, TableType, WasmType, WasmValue}; #[derive(Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "debug", derive(Debug))] @@ -460,28 +460,20 @@ impl Global { cold_path(); return Err(Error::Other("invalid global value type".to_string())); } - let addr = store.state.globals.len() as GlobalAddr; - store.state.globals.push(GlobalInstance::new(ty, value.into())); + let addr = store.state.globals.push(ty, value.into()); Ok(Self(StoreItem::new(store.id(), addr))) } - #[inline] - fn instance<'a>(&self, store: &'a Store) -> Result<&'a GlobalInstance> { - self.0.validate_store(store)?; - Ok(store.state.get_global(self.0.addr)) - } - /// Get the type of the global. pub fn ty(&self, store: &Store) -> Result { - Ok(self.instance(store)?.ty) + self.0.validate_store(store)?; + Ok(store.state.globals.ty(self.0.addr)) } /// Get the current value of the global. pub fn get(&self, store: &Store) -> Result { - let global = self.instance(store)?; - let value = store.state.attach_value(global.value, global.ty.ty); - let value = - value.unwrap_or_else(|| unreachable!("Global value type does not match global type, this is a bug")); + self.0.validate_store(store)?; + let value = store.state.global_wasm_value(self.0.addr); if let WasmValue::Ref(value) = value { store.state.pin_host_ref(value); } @@ -491,16 +483,6 @@ impl Global { /// Set the current value of the global. pub fn set(&self, store: &mut Store, value: WasmValue) -> Result<()> { self.0.validate_store(store)?; - let global = store.state.get_global(self.0.addr); - if !global.ty.mutable { - cold_path(); - return Err(Error::Other("global is immutable".to_string())); - } - if !store.state.value_matches_type(value, global.ty.ty) { - cold_path(); - return Err(Error::Other("invalid global value type".to_string())); - } - store.state.get_global_mut(self.0.addr).value = value.into(); - Ok(()) + store.state.set_global_wasm_value(self.0.addr, value) } } diff --git a/crates/tinywasm/src/store/global.rs b/crates/tinywasm/src/store/global.rs index 9280494..c685d89 100644 --- a/crates/tinywasm/src/store/global.rs +++ b/crates/tinywasm/src/store/global.rs @@ -1,17 +1,162 @@ -use crate::interpreter::TinyWasmValue; +use alloc::vec::Vec; use tinywasm_types::*; -/// A WebAssembly Global Instance +use crate::interpreter::{TinyWasmValue, Value32, Value64, Value128, ValueRef}; + +struct GlobalLane { + values: Vec, + types: Vec, +} + +impl Default for GlobalLane { + fn default() -> Self { + Self { values: Vec::new(), types: Vec::new() } + } +} + +impl GlobalLane { + fn push(&mut self, ty: GlobalType, value: T) -> usize { + debug_assert_eq!(self.values.len(), self.types.len()); + let index = self.values.len(); + self.values.push(value); + self.types.push(ty); + index + } + + #[inline(always)] + fn get(&self, index: usize, addr: GlobalAddr) -> T { + *self.values.get(index).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) + } + + #[inline(always)] + fn set(&mut self, index: usize, addr: GlobalAddr, value: T) { + *self.values.get_mut(index).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) = value; + } + + fn ty(&self, index: usize, addr: GlobalAddr) -> GlobalType { + *self.types.get(index).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) + } +} + +/// Global instances split into their physical value lanes. /// -/// See -#[cfg_attr(feature = "debug", derive(Debug))] -pub(crate) struct GlobalInstance { - pub(crate) value: TinyWasmValue, - pub(crate) ty: GlobalType, +/// Guest values should normally be accessed through +/// [`InternalValue`](crate::interpreter::InternalValue). Dynamic access is +/// reserved for initialization and host boundaries. +#[derive(Default)] +pub(crate) struct Globals { + globals_32: GlobalLane, + globals_64: GlobalLane, + globals_128: GlobalLane, } -impl GlobalInstance { - pub(crate) fn new(ty: GlobalType, value: TinyWasmValue) -> Self { - Self { ty, value } +impl Globals { + const LANE_SHIFT: u32 = 30; + const INDEX_MASK: u32 = (1 << Self::LANE_SHIFT) - 1; + const LANE_32: u32 = 0; + const LANE_64: u32 = 1 << Self::LANE_SHIFT; + const LANE_128: u32 = 2 << Self::LANE_SHIFT; + + fn addr(lane: u32, index: usize) -> GlobalAddr { + assert!(index <= Self::INDEX_MASK as usize, "too many globals in one value lane"); + lane | index as u32 + } + + #[inline(always)] + fn index(addr: GlobalAddr, lane: u32) -> usize { + debug_assert_eq!(addr & !Self::INDEX_MASK, lane, "global address has the wrong value lane"); + (addr & Self::INDEX_MASK) as usize + } + + /// Returns a global's logical type and mutability. + pub(crate) fn ty(&self, addr: GlobalAddr) -> GlobalType { + match addr & !Self::INDEX_MASK { + Self::LANE_32 => self.globals_32.ty(Self::index(addr, Self::LANE_32), addr), + Self::LANE_64 => self.globals_64.ty(Self::index(addr, Self::LANE_64), addr), + Self::LANE_128 => self.globals_128.ty(Self::index(addr, Self::LANE_128), addr), + _ => unreachable!("invalid global address: {addr}"), + } + } + + /// Adds a global and returns its packed store address. + pub(crate) fn push(&mut self, ty: GlobalType, value: TinyWasmValue) -> GlobalAddr { + match (ty.ty, value) { + (WasmType::I32 | WasmType::F32, TinyWasmValue::Value32(value)) => { + Self::addr(Self::LANE_32, self.globals_32.push(ty, value)) + } + (WasmType::Ref(_), TinyWasmValue::ValueRef(value)) => { + Self::addr(Self::LANE_32, self.globals_32.push(ty, value.raw())) + } + (WasmType::I64 | WasmType::F64, TinyWasmValue::Value64(value)) => { + Self::addr(Self::LANE_64, self.globals_64.push(ty, value)) + } + (WasmType::V128, TinyWasmValue::Value128(value)) => { + Self::addr(Self::LANE_128, self.globals_128.push(ty, value)) + } + _ => unreachable!("global value does not match its declared type"), + } + } + + /// Returns a dynamically represented global value. + pub(crate) fn get(&self, addr: GlobalAddr) -> TinyWasmValue { + let ty = self.ty(addr); + match ty.ty { + WasmType::I32 | WasmType::F32 => TinyWasmValue::Value32(self.get_32(addr)), + WasmType::I64 | WasmType::F64 => TinyWasmValue::Value64(self.get_64(addr)), + WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::from_raw(self.get_32(addr))), + WasmType::V128 => TinyWasmValue::Value128(self.get_128(addr)), + } + } + + /// Sets a global from a dynamically represented value. + pub(crate) fn set(&mut self, addr: GlobalAddr, value: TinyWasmValue) { + match (self.ty(addr).ty, value) { + (WasmType::I32 | WasmType::F32, TinyWasmValue::Value32(value)) => self.set_32(addr, value), + (WasmType::Ref(_), TinyWasmValue::ValueRef(value)) => self.set_32(addr, value.raw()), + (WasmType::I64 | WasmType::F64, TinyWasmValue::Value64(value)) => self.set_64(addr, value), + (WasmType::V128, TinyWasmValue::Value128(value)) => self.set_128(addr, value), + _ => unreachable!("global value does not match its declared type"), + } + } + + /// Returns a raw value from the 32-bit lane. + #[inline(always)] + pub(crate) fn get_32(&self, addr: GlobalAddr) -> Value32 { + self.globals_32.get(Self::index(addr, Self::LANE_32), addr) + } + + /// Returns a raw value from the 64-bit lane. + #[inline(always)] + pub(crate) fn get_64(&self, addr: GlobalAddr) -> Value64 { + self.globals_64.get(Self::index(addr, Self::LANE_64), addr) + } + + /// Returns a raw value from the 128-bit lane. + #[inline(always)] + pub(crate) fn get_128(&self, addr: GlobalAddr) -> Value128 { + self.globals_128.get(Self::index(addr, Self::LANE_128), addr) + } + + /// Sets a raw value in the 32-bit lane. + #[inline(always)] + pub(crate) fn set_32(&mut self, addr: GlobalAddr, value: Value32) { + self.globals_32.set(Self::index(addr, Self::LANE_32), addr, value); + } + + /// Sets a raw value in the 64-bit lane. + #[inline(always)] + pub(crate) fn set_64(&mut self, addr: GlobalAddr, value: Value64) { + self.globals_64.set(Self::index(addr, Self::LANE_64), addr, value); + } + + /// Sets a raw value in the 128-bit lane. + #[inline(always)] + pub(crate) fn set_128(&mut self, addr: GlobalAddr, value: Value128) { + self.globals_128.set(Self::index(addr, Self::LANE_128), addr, value); + } + + /// Iterates over globals in the 32-bit lane for root tracing. + pub(crate) fn globals_32(&self) -> impl Iterator + '_ { + self.globals_32.values.iter().copied().zip(self.globals_32.types.iter().copied()) } } diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 84c4033..3c80e91 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -72,7 +72,8 @@ impl Store { /// Create a new store pub fn new(engine: Engine) -> Self { let id = STORE_ID.fetch_add(1, Ordering::Relaxed); - let state = State { gc: gc::GcHeap::new(engine.config().gc_collection_threshold), ..State::default() }; + let state = + State { gc: Box::new(gc::GcHeap::new(engine.config().gc_collection_threshold)), ..State::default() }; Self { id, module_instances: Vec::new(), @@ -138,16 +139,16 @@ impl Store { self.module_instances.push(instance); } - /// Get the global at the actual index in the store + /// Gets a global by its opaque store address. #[doc(hidden)] pub fn get_global_val(&self, addr: GlobalAddr) -> TinyWasmValue { - self.state.get_global_val(addr) + self.state.globals.get(addr) } - /// Set the global at the actual index in the store + /// Sets a global by its opaque store address. #[doc(hidden)] pub fn set_global_val(&mut self, addr: GlobalAddr, value: TinyWasmValue) { - self.state.set_global_val(addr, value); + self.state.globals.set(addr, value); } /// Returns whether a public value has the requested runtime type. @@ -232,9 +233,6 @@ impl Store { func_addrs: &[FuncAddr], type_addrs: &[TypeAddr], ) -> Result<()> { - let start = self.state.globals.len() as Addr; - out.extend(start..start + globals.len() as Addr); - for global in globals { let value = match self.eval_const(&global.init, out, func_addrs, type_addrs) { Ok(val) => val, @@ -244,7 +242,7 @@ impl Store { } }; let ty = global.ty.with_ty(canonicalize_value_type(global.ty.ty, type_addrs)); - self.state.globals.push(GlobalInstance::new(ty, value)); + out.push(self.state.globals.push(ty, value)); } Ok(()) @@ -439,7 +437,7 @@ impl Store { let addr = *module_global_addrs .get(index as usize) .ok_or_else(|| Error::Other(format!("global {index} not found")))?; - Ok(state.globals.get(addr as usize).ok_or_else(|| Error::Other(format!("global {addr} not found")))?.value) + Ok(state.globals.get(addr)) }; let func_ref = |index: u32| -> Result { let addr = *module_func_addrs diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index 125cc30..392035f 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -14,10 +14,10 @@ pub(crate) struct State { pub(crate) funcs: Vec, pub(crate) tables: Vec, pub(crate) memories: Vec, - pub(crate) globals: Vec, + pub(crate) globals: Globals, pub(crate) elements: Vec, pub(crate) data: Vec, - pub(crate) gc: gc::GcHeap, + pub(crate) gc: Box, } impl State { @@ -73,9 +73,9 @@ impl State { .map(ValueRef::from_raw) .chain( self.globals - .iter() - .filter(|global| Self::type_may_contain_gc_in(canonical_types, global.ty.ty)) - .filter_map(|global| global.value.as_ref()), + .globals_32() + .filter(|(_, ty)| Self::type_may_contain_gc_in(canonical_types, ty.ty)) + .map(|(value, _)| ValueRef::from_raw(value)), ) .chain( self.tables @@ -363,23 +363,45 @@ impl State { Self::get_mut(&mut self.elements, addr, "element") } - /// Get the global at the actual index in the store - pub(crate) fn get_global(&self, addr: GlobalAddr) -> &GlobalInstance { - Self::get(&self.globals, addr, "global") - } - - /// Get the global at the actual index in the store - pub(crate) fn get_global_mut(&mut self, addr: GlobalAddr) -> &mut GlobalInstance { - Self::get_mut(&mut self.globals, addr, "global") - } - - /// Get the global at the actual index in the store - pub(crate) fn get_global_val(&self, addr: GlobalAddr) -> TinyWasmValue { - self.get_global(addr).value + /// Converts a global directly to its public value representation. + pub(crate) fn global_wasm_value(&self, addr: GlobalAddr) -> WasmValue { + let ty = self.globals.ty(addr).ty; + match ty { + WasmType::I32 => WasmValue::I32(self.globals.get_32(addr) as i32), + WasmType::I64 => WasmValue::I64(self.globals.get_64(addr) as i64), + WasmType::F32 => WasmValue::F32(f32::from_bits(self.globals.get_32(addr))), + WasmType::F64 => WasmValue::F64(f64::from_bits(self.globals.get_64(addr))), + WasmType::Ref(_) => self + .attach_value(TinyWasmValue::ValueRef(ValueRef::from_raw(self.globals.get_32(addr))), ty) + .unwrap_or_else(|| unreachable!("global value does not match its type")), + WasmType::V128 => WasmValue::V128(self.globals.get_128(addr).to_le_bytes()), + } } - /// Set the global at the actual index in the store - pub(crate) fn set_global_val(&mut self, addr: GlobalAddr, value: TinyWasmValue) { - self.get_global_mut(addr).value = value; + /// Validates and sets a global from its public value representation. + pub(crate) fn set_global_wasm_value(&mut self, addr: GlobalAddr, value: WasmValue) -> Result<()> { + let ty = self.globals.ty(addr); + if !ty.mutable { + cold_path(); + return Err(Error::other("global is immutable")); + } + if !self.value_matches_type(value, ty.ty) { + cold_path(); + return Err(Error::other("invalid global value type")); + } + match value { + WasmValue::I32(value) => self.globals.set_32(addr, value as u32), + WasmValue::I64(value) => self.globals.set_64(addr, value as u64), + WasmValue::F32(value) => self.globals.set_32(addr, value.to_bits()), + WasmValue::F64(value) => self.globals.set_64(addr, value.to_bits()), + WasmValue::Ref(value) => { + let TinyWasmValue::ValueRef(value) = TinyWasmValue::from(WasmValue::Ref(value)) else { + unreachable!("reference value did not convert to an internal reference") + }; + self.globals.set_32(addr, value.raw()); + } + WasmValue::V128(value) => self.globals.set_128(addr, value.into()), + } + Ok(()) } } diff --git a/crates/tinywasm/tests/store_ownership.rs b/crates/tinywasm/tests/store_ownership.rs index 8577d73..6cae984 100644 --- a/crates/tinywasm/tests/store_ownership.rs +++ b/crates/tinywasm/tests/store_ownership.rs @@ -1,5 +1,6 @@ use eyre::Result; -use tinywasm::{ModuleInstance, Store}; +use tinywasm::types::{GlobalType, WasmType}; +use tinywasm::{Global, Imports, ModuleInstance, Store}; const MODULE_WAT: &str = r#" (module @@ -86,3 +87,18 @@ fn table_grow_rejects_wrong_store_with_invalid_store_error() -> Result<()> { Ok(()) } + +#[test] +fn global_import_rejects_wrong_store() -> Result<()> { + let wasm = wat::parse_str(r#"(module (import "env" "g" (global i32)))"#)?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut owner_store = Store::default(); + let global = Global::new(&mut owner_store, GlobalType::new(WasmType::I32, false), 1.into())?; + let mut imports = Imports::default(); + imports.define("env", "g", global); + + let mut other_store = Store::default(); + let err = ModuleInstance::instantiate(&mut other_store, &module, Some(imports)).unwrap_err(); + assert_eq!(err, tinywasm::Error::Trap(tinywasm::Trap::InvalidStore)); + Ok(()) +} diff --git a/crates/tinywasm/tests/typed_globals.rs b/crates/tinywasm/tests/typed_globals.rs new file mode 100644 index 0000000..80494e0 --- /dev/null +++ b/crates/tinywasm/tests/typed_globals.rs @@ -0,0 +1,93 @@ +use eyre::Result; +use tinywasm::types::{GlobalType, Instruction, RefValue, WasmType, WasmValue}; +use tinywasm::{Global, Imports, ModuleInstance, Store}; + +#[test] +fn globals_use_typed_instructions_and_roundtrip_values() -> Result<()> { + let wasm = wat::parse_str( + r#" + (module + (global (mut i32) (i32.const 1)) + (global (mut f32) (f32.const 2)) + (global (mut i64) (i64.const 3)) + (global (mut f64) (f64.const 4)) + (global (mut v128) (v128.const i32x4 1 2 3 4)) + (global (mut funcref) (ref.null func)) + + (func (export "i32") (param i32) (result i32) + local.get 0 global.set 0 global.get 0) + (func (export "f32") (param f32) (result f32) + local.get 0 global.set 1 global.get 1) + (func (export "i64") (param i64) (result i64) + local.get 0 global.set 2 global.get 2) + (func (export "f64") (param f64) (result f64) + local.get 0 global.set 3 global.get 3) + (func (export "v128") (param v128) (result v128) + local.get 0 global.set 4 global.get 4) + (func (export "ref") (param funcref) (result funcref) + local.get 0 global.set 5 global.get 5) + (func (export "add-i32") (param i32) (result i32) + local.get 0 global.get 0 i32.add) + (func (export "add-i64") (param i64) (result i64) + local.get 0 global.get 2 i64.add) + ) + "#, + )?; + + let module = tinywasm::parse_bytes(&wasm)?; + let instructions = module.funcs.iter().flat_map(|func| func.instructions.iter()); + let (mut get32, mut get64, mut get128, mut fused32, mut fused64) = (0, 0, 0, 0, 0); + for instruction in instructions { + match instruction { + Instruction::GlobalGet32(_) => get32 += 1, + Instruction::GlobalGet64(_) => get64 += 1, + Instruction::GlobalGet128(_) => get128 += 1, + Instruction::BinOpStackGlobal32(..) => fused32 += 1, + Instruction::BinOpStackGlobal64(..) => fused64 += 1, + _ => {} + } + } + assert_eq!((get32, get64, get128), (3, 2, 1)); + assert_eq!((fused32, fused64), (1, 1)); + + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let cases = [ + ("i32", WasmValue::I32(11)), + ("f32", WasmValue::F32(12.5)), + ("i64", WasmValue::I64(13)), + ("f64", WasmValue::F64(14.5)), + ("v128", WasmValue::V128([15; 16])), + ("ref", WasmValue::Ref(RefValue::Null)), + ]; + for (name, value) in cases { + assert_eq!(instance.func_untyped(&store, name)?.call(&mut store, &[value])?, vec![value]); + } + assert_eq!(instance.func::(&store, "add-i32")?.call(&mut store, 2)?, 13); + assert_eq!(instance.func::(&store, "add-i64")?.call(&mut store, 2)?, 15); + + Ok(()) +} + +#[test] +fn imported_global_keeps_its_typed_store_address() -> Result<()> { + let wasm = wat::parse_str( + r#" + (module + (import "env" "g" (global (mut i64))) + (func (export "roundtrip") (param i64) (result i64) + local.get 0 global.set 0 global.get 0) + ) + "#, + )?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut store = Store::default(); + let global = Global::new(&mut store, GlobalType::new(WasmType::I64, true), WasmValue::I64(1))?; + let mut imports = Imports::default(); + imports.define("env", "g", global); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + + assert_eq!(instance.func::(&store, "roundtrip")?.call(&mut store, 42)?, 42); + assert_eq!(global.get(&store)?, WasmValue::I64(42)); + Ok(()) +} diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index 1160fa5..b920ac7 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -239,10 +239,9 @@ pub enum Instruction { // > Variable Instructions // See - GlobalGet(GlobalAddr), - LocalGet32(LocalAddr), LocalSet32(LocalAddr), LocalTee32(LocalAddr), GlobalSet32(GlobalAddr), - LocalGet64(LocalAddr), LocalSet64(LocalAddr), LocalTee64(LocalAddr), GlobalSet64(GlobalAddr), - LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr), GlobalSet128(GlobalAddr), + GlobalGet32(GlobalAddr), LocalGet32(LocalAddr), LocalSet32(LocalAddr), LocalTee32(LocalAddr), GlobalSet32(GlobalAddr), + GlobalGet64(GlobalAddr), LocalGet64(LocalAddr), LocalSet64(LocalAddr), LocalTee64(LocalAddr), GlobalSet64(GlobalAddr), + GlobalGet128(GlobalAddr), LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr), GlobalSet128(GlobalAddr), // > Memory Instructions I32Load(MemoryArg), diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index c461296..0fd4e81 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -362,6 +362,39 @@ impl ExternVal { } } +/// The physical storage lane used by a [`WasmType`]. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub enum ValueLane { + /// A 32-bit value or reference. + S32, + /// A 64-bit value. + S64, + /// A 128-bit SIMD value. + S128, +} + +impl ValueLane { + /// Selects one of three values based on this lane. + pub fn select(self, s32: T, s64: T, s128: T) -> T { + match self { + Self::S32 => s32, + Self::S64 => s64, + Self::S128 => s128, + } + } +} + +impl From<&WasmType> for ValueLane { + fn from(ty: &WasmType) -> Self { + match ty { + WasmType::I32 | WasmType::F32 | WasmType::Ref(_) => Self::S32, + WasmType::I64 | WasmType::F64 => Self::S64, + WasmType::V128 => Self::S128, + } + } +} + #[derive(Default, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -384,10 +417,10 @@ impl<'a> FromIterator<&'a WasmType> for ValueCounts { let mut counts = Self::default(); for ty in iter { - match ty { - WasmType::I32 | WasmType::F32 | WasmType::Ref(_) => counts.c32 += 1, - WasmType::I64 | WasmType::F64 => counts.c64 += 1, - WasmType::V128 => counts.c128 += 1, + match ValueLane::from(ty) { + ValueLane::S32 => counts.c32 += 1, + ValueLane::S64 => counts.c64 += 1, + ValueLane::S128 => counts.c128 += 1, } } counts -- cgit v1.3.1 From e005e5afd144f5659e2ed19afa8ee94ff924be55 Mon Sep 17 00:00:00 2001 From: Henry Date: Sun, 9 Aug 2026 18:07:51 +0200 Subject: feat: initial exception support Signed-off-by: Henry --- CHANGELOG.md | 1 + README.md | 2 +- crates/cli/src/output.rs | 2 + crates/cli/src/wast_runner.rs | 179 ++++++++++++++++++------ crates/parser/src/conversion.rs | 11 +- crates/parser/src/lib.rs | 1 + crates/parser/src/macros.rs | 1 + crates/parser/src/module.rs | 36 +++++ crates/parser/src/optimize.rs | 42 ++++++ crates/parser/src/visit.rs | 127 ++++++++++++++++- crates/tinywasm/Cargo.toml | 2 - crates/tinywasm/src/error.rs | 7 +- crates/tinywasm/src/func/resume.rs | 20 ++- crates/tinywasm/src/imports.rs | 36 +++-- crates/tinywasm/src/instance.rs | 32 ++++- crates/tinywasm/src/interpreter/executor.rs | 158 ++++++++++++++++++--- crates/tinywasm/src/interpreter/mod.rs | 8 +- crates/tinywasm/src/interpreter/num_helpers.rs | 4 +- crates/tinywasm/src/reference.rs | 28 +++- crates/tinywasm/src/store/exception.rs | 10 ++ crates/tinywasm/src/store/mod.rs | 16 ++- crates/tinywasm/src/store/state.rs | 19 +++ crates/tinywasm/src/store/tag.rs | 7 + crates/tinywasm/tests/generated/wasm-3.csv | 2 +- crates/tinywasm/tests/generated/wasm-latest.csv | 2 +- crates/types/src/instructions.rs | 46 +++++- crates/types/src/lib.rs | 48 +++++++ 27 files changed, 744 insertions(+), 103 deletions(-) create mode 100644 crates/tinywasm/src/store/exception.rs create mode 100644 crates/tinywasm/src/store/tag.rs (limited to 'crates/parser/src/conversion.rs') diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ae416e..64366f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added support for the WebAssembly function-references proposal - Added basic support for the WebAssembly garbage-collection proposal +- Added support for the WebAssembly exception-handling proposal, including tags, `try_table`, `throw`, and `throw_ref` - Added `WasmValue::ty` and `WasmValue::matches_type` - Added `ValueLane` for mapping WebAssembly value types to their physical 32-bit, 64-bit, or 128-bit storage lane. - Added a `validate` feature to `tinywasm` and `tinywasm-parser` (enabled by default) to optionally skip wasmparser validation for faster parsing of trusted modules. diff --git a/README.md b/README.md index 484dbaf..305f61e 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ TinyWasm targets non-JavaScript core proposals through [phase 3](https://github. | [**Custom Page Sizes**](https://github.com/WebAssembly/custom-page-sizes) | 🟢 | 0.9.0 | | [**Typed Function References**](https://github.com/WebAssembly/function-references) | 🟢 | `next` | | [**Garbage Collection**](https://github.com/WebAssembly/gc) | 🟢 | `next` | -| [**Exception Handling**](https://github.com/WebAssembly/exception-handling) | 🌑 | - | +| [**Exception Handling**](https://github.com/WebAssembly/exception-handling) | 🟢 | `next` | | [**Stack Switching**](https://github.com/WebAssembly/stack-switching) | 🌑 | - | | [**Compact Import Section**](https://github.com/WebAssembly/compact-import-section) | 🌑 | - | | [**Threads**](https://github.com/WebAssembly/threads) | 🌑 | - | diff --git a/crates/cli/src/output.rs b/crates/cli/src/output.rs index 40a271e..a2bd287 100644 --- a/crates/cli/src/output.rs +++ b/crates/cli/src/output.rs @@ -77,6 +77,7 @@ pub fn format_export_type(ty: ExportType<'_>) -> String { ExportType::Memory(ty) => format_memory_type(ty), ExportType::Table(ty) => format_table_type(ty), ExportType::Global(ty) => format_global_type(ty), + ExportType::Tag(ty) => format!("tag {}", format_func_type(ty)), } } @@ -86,5 +87,6 @@ pub fn format_import_type(ty: ImportType<'_>) -> String { ImportType::Memory(ty) => format_memory_type(ty), ImportType::Table(ty) => format_table_type(ty), ImportType::Global(ty) => format_global_type(ty), + ImportType::Tag(ty) => format!("tag {}", format_func_type(ty)), } } diff --git a/crates/cli/src/wast_runner.rs b/crates/cli/src/wast_runner.rs index 2ca622d..24483b6 100644 --- a/crates/cli/src/wast_runner.rs +++ b/crates/cli/src/wast_runner.rs @@ -19,53 +19,63 @@ const TEST_MAX_SUSPENSIONS: u32 = 1000; #[derive(Default)] struct ModuleRegistry { - modules: HashMap, - named_modules: HashMap, - last_module: Option, + definitions: HashMap, + instances: HashMap, + registered: HashMap, + last_definition: Option, + last_instance: Option, } impl ModuleRegistry { - fn modules(&self) -> &HashMap { - &self.modules + fn registered(&self) -> &HashMap { + &self.registered } - fn update_last_module(&mut self, module: ModuleInstance, name: Option) { - self.last_module = Some(module.clone()); + fn define(&mut self, module: Module, name: Option) { + self.last_definition = Some(module.clone()); if let Some(name) = name { - self.named_modules.insert(name, module); + self.definitions.insert(name, module); } } - fn register(&mut self, name: String, module: ModuleInstance) { + fn definition(&self, id: Option>) -> Option { + match id { + Some(id) => self.definitions.get(id.name()).cloned(), + None => self.last_definition.clone(), + } + } + + fn update_last_instance(&mut self, instance: ModuleInstance, name: Option) { + self.last_instance = Some(instance.clone()); + if let Some(name) = name { + self.instances.insert(name, instance); + } + } + + fn register(&mut self, name: String, id: Option>) -> bool { + let Some(instance) = self.get(id) else { return false }; debug!("registering module: {name}"); - self.modules.insert(name.clone(), module.clone()); - self.last_module = Some(module.clone()); - self.named_modules.insert(name, module); + self.registered.insert(name, instance); + true } fn get_idx(&self, module_id: Option>) -> Option { match module_id { - Some(module) => self - .modules - .get(module.name()) - .or_else(|| self.named_modules.get(module.name())) - .map(ModuleInstance::id), - None => self.last_module.as_ref().map(ModuleInstance::id), + Some(module) => { + self.registered.get(module.name()).or_else(|| self.instances.get(module.name())).map(ModuleInstance::id) + } + None => self.last_instance.as_ref().map(ModuleInstance::id), } } fn get(&self, module_id: Option>) -> Option { match module_id { Some(module_id) => { - self.modules.get(module_id.name()).or_else(|| self.named_modules.get(module_id.name())).cloned() + self.registered.get(module_id.name()).or_else(|| self.instances.get(module_id.name())).cloned() } - None => self.last_module.clone(), + None => self.last_instance.clone(), } } - - fn last(&self) -> Option { - self.last_module.clone() - } } #[derive(Default)] @@ -200,6 +210,11 @@ impl WastRunner { Ok(imports) } + fn instantiate_module(store: &mut Store, registry: &ModuleRegistry, module: &Module) -> Result { + let imports = Self::imports(store, registry.registered())?; + Ok(ModuleInstance::instantiate(store, module, Some(&imports))?) + } + pub fn run_file(&mut self, file: TestFile<'_>) -> Result<()> { let test_group = self.test_group(file.name(), file.parent()); let wast_raw = file.raw(); @@ -213,51 +228,72 @@ impl WastRunner { for (i, directive) in directives.into_iter().enumerate() { let span = directive.span(); use wast::WastDirective::{ - AssertExhaustion, AssertInvalid, AssertMalformed, AssertReturn, AssertTrap, AssertUnlinkable, Invoke, - Module as Wat, ModuleDefinition, Register, + AssertException, AssertExhaustion, AssertInvalid, AssertMalformed, AssertReturn, AssertTrap, + AssertUnlinkable, Invoke, Module as Wat, ModuleDefinition, ModuleInstance as Instance, Register, }; match directive { - Register { span, name, .. } => { - let Some(last) = module_registry.last() else { + Register { span, name, module } => { + if !module_registry.register(name.to_string(), module) { test_group.add_result( &format!("Register({i})"), span.linecol_in(wast_raw), - Err(eyre!("no module to register")), + Err(eyre!("module instance to register was not found")), ); continue; - }; - module_registry.register(name.to_string(), last); + } test_group.add_result(&format!("Register({i})"), span.linecol_in(wast_raw), Ok(())); } Wat(module) => { let result = catch_unwind_silent(|| { - let (name, bytes) = encode_quote_wat(module); - let module = parse_module_bytes(&bytes).expect("failed to parse module bytes"); - let imports = Self::imports(&mut store, module_registry.modules()).unwrap(); - let module_instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports)) + let (name, module) = parse_quote_module(module).expect("failed to parse module bytes"); + let instance = Self::instantiate_module(&mut store, &module_registry, &module) .expect("failed to instantiate module"); - (name, module_instance) + (name, instance) }) .map_err(|e| eyre!("failed to parse wat module: {}", try_downcast_panic(e))); match &result { Err(err) => debug!("failed to parse module: {err:?}"), - Ok((name, module)) => module_registry.update_last_module(module.clone(), name.clone()), + Ok((name, instance)) => module_registry.update_last_instance(instance.clone(), name.clone()), }; test_group.add_result(&format!("Wat({i})"), span.linecol_in(wast_raw), result.map(|_| ())); } ModuleDefinition(module) => { + let result = + catch_unwind_silent(|| parse_quote_module(module).expect("failed to parse module definition")) + .map_err(|err| eyre!("failed to parse module definition: {}", try_downcast_panic(err))); + + if let Ok((name, module)) = &result { + module_registry.define(module.clone(), name.clone()); + } + + test_group.add_result( + &format!("ModuleDefinition({i})"), + span.linecol_in(wast_raw), + result.map(|_| ()), + ); + } + Instance { span, instance, module } => { + let name = instance.map(|id| id.name().to_string()); let result = catch_unwind_silent(|| { - let (_, bytes) = encode_quote_wat(module); - parse_module_bytes(&bytes) + let module = module_registry + .definition(module) + .ok_or_else(|| eyre!("module definition was not found"))?; + Self::instantiate_module(&mut store, &module_registry, &module) }) - .map_err(|err| eyre!("failed to parse module definition: {}", try_downcast_panic(err))) - .and_then(|result| result) - .map(|_| ()); + .map_err(|err| eyre!("failed to instantiate module definition: {}", try_downcast_panic(err))) + .and_then(|result| result); - test_group.add_result(&format!("ModuleDefinition({i})"), span.linecol_in(wast_raw), result); + if let Ok(instance) = &result { + module_registry.update_last_instance(instance.clone(), name); + } + test_group.add_result( + &format!("ModuleInstance({i})"), + span.linecol_in(wast_raw), + result.map(|_| ()), + ); } AssertMalformed { span, mut module, message } => { let Ok(encoded) = module.encode() else { @@ -330,7 +366,7 @@ impl WastRunner { wast::WastExecute::Wat(mut wat) => { let module = parse_module_bytes(&wat.encode().expect("failed to encode module")) .expect("failed to parse module"); - let imports = Self::imports(&mut store, module_registry.modules()).unwrap(); + let imports = Self::imports(&mut store, module_registry.registered()).unwrap(); ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; return Ok(()); } @@ -371,11 +407,37 @@ impl WastRunner { ), } } + AssertException { exec, span } => { + let res: Result, _> = catch_unwind_silent(|| { + let invoke = match exec { + wast::WastExecute::Wat(mut wat) => { + let module = parse_module_bytes(&wat.encode().expect("failed to encode module")) + .expect("failed to parse module"); + let imports = Self::imports(&mut store, module_registry.registered()).unwrap(); + ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + return Ok(()); + } + wast::WastExecute::Get { .. } => panic!("get not supported"), + wast::WastExecute::Invoke(invoke) => invoke, + }; + let module = module_registry.get_idx(invoke.module); + let args = + convert_wastargs(invoke.args).map_err(|err| tinywasm::Error::Other(err.to_string()))?; + exec_fn_instance(module, &mut store, invoke.name, &args).map(|_| ()) + }); + let result = match res { + Err(err) => Err(eyre!("test panicked: {}", try_downcast_panic(err))), + Ok(Err(tinywasm::Error::Exception(_))) => Ok(()), + Ok(Err(err)) => Err(eyre!("expected exception, got: {err:?}")), + Ok(Ok(())) => Err(eyre!("expected exception, got Ok")), + }; + test_group.add_result(&format!("AssertException({i})"), span.linecol_in(wast_raw), result); + } AssertUnlinkable { mut module, span, message } => { let res = catch_unwind_silent(|| { let module = parse_module_bytes(&module.encode().expect("failed to encode module")) .expect("failed to parse module"); - let imports = Self::imports(&mut store, module_registry.modules()).unwrap(); + let imports = Self::imports(&mut store, module_registry.registered()).unwrap(); ModuleInstance::instantiate(&mut store, &module, Some(&imports)) }); match res { @@ -729,6 +791,11 @@ fn parse_module_bytes(bytes: &[u8]) -> Result { Ok(tinywasm::parse_bytes(bytes)?) } +fn parse_quote_module(module: QuoteWat) -> Result<(Option, Module)> { + let (name, bytes) = encode_quote_wat(module); + Ok((name, parse_module_bytes(&bytes)?)) +} + fn convert_wastargs(args: Vec) -> Result> { args.into_iter().map(wastarg2tinywasmvalue).collect() } @@ -947,4 +1014,26 @@ mod tests { let mut runner = WastRunner::new(); runner.run_paths(&[path]).unwrap(); } + + #[test] + fn runs_module_definition_and_instance_directives() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("instance.wast"); + std::fs::write( + &path, + r#" + (module definition $M (global (export "g") i32 (i32.const 42))) + (module instance $I $M) + (register "I" $I) + (module + (import "I" "g" (global $g i32)) + (func (export "get") (result i32) global.get $g)) + (assert_return (invoke "get") (i32.const 42)) + "#, + ) + .unwrap(); + + let mut runner = WastRunner::new(); + runner.run_paths(&[path]).unwrap(); + } } diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 4073a8e..7b52363 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -76,9 +76,7 @@ pub(crate) fn convert_module_import(import: wasmparser::Import<'_>) -> Result { ImportKind::Global(GlobalType::new(convert_valtype(&ty.content_type)?, ty.mutable)) } - wasmparser::TypeRef::Tag(ty) => { - return Err(crate::ParseError::UnsupportedOperator(format!("Unsupported import kind: {ty:?}"))); - } + wasmparser::TypeRef::Tag(ty) => ImportKind::Tag(convert_tag_type(ty)), _ => { return Err(crate::ParseError::UnsupportedOperator(format!("Unsupported import kind: {:?}", import.ty))); } @@ -116,7 +114,8 @@ pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result ExternalKind::Table, wasmparser::ExternalKind::Memory => ExternalKind::Memory, wasmparser::ExternalKind::Global => ExternalKind::Global, - wasmparser::ExternalKind::Tag | wasmparser::ExternalKind::FuncExact => { + wasmparser::ExternalKind::Tag => ExternalKind::Tag, + wasmparser::ExternalKind::FuncExact => { return Err(crate::ParseError::UnsupportedOperator(format!("Unsupported export kind: {:?}", export.kind))); } }; @@ -124,6 +123,10 @@ pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result TagType { + TagType::new(ty.func_type_idx) +} + fn extend_local_types(local_types: &mut Vec, count: u32, ty: wasmparser::ValType) -> Result<()> { let size = value_lane(ty); let count = diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs index fe968d8..8b6cb39 100644 --- a/crates/parser/src/lib.rs +++ b/crates/parser/src/lib.rs @@ -189,6 +189,7 @@ impl Parser { | WasmFeatures::SIMD | WasmFeatures::MEMORY64 | WasmFeatures::CUSTOM_PAGE_SIZES + | WasmFeatures::EXCEPTIONS | WasmFeatures::WIDE_ARITHMETIC; self.options.validation().then(|| Validator::new_with_features(features)) } diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs index db1402d..98312ab 100644 --- a/crates/parser/src/macros.rs +++ b/crates/parser/src/macros.rs @@ -160,6 +160,7 @@ pub(crate) mod visit { (@@tail_call $($rest:tt)* ) => {}; (@@function_references $($rest:tt)* ) => {}; (@@gc $($rest:tt)* ) => {}; + (@@exceptions $($rest:tt)* ) => {}; (@@$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*)) => { fn $visit(&mut self $($(,_: $argty)*)?) -> Self::Output { diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index 237478c..bbe2cf8 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -57,6 +57,7 @@ pub(crate) struct ModuleReader<'a> { pub(crate) globals: Box<[Global]>, pub(crate) tables: Box<[TableDefinition]>, pub(crate) memory_types: Box<[MemoryType]>, + pub(crate) tags: Box<[TagType]>, pub(crate) imports: Box<[Import]>, pub(crate) data: Box<[Data]>, pub(crate) elements: Box<[Element]>, @@ -78,6 +79,7 @@ impl<'a> ModuleReader<'a> { &self.globals, &self.memory_types, &self.tables, + &self.tags, ))); } self.translation_metadata.as_deref().unwrap() @@ -182,6 +184,25 @@ impl<'a> ModuleReader<'a> { self.memory_types = reader.into_iter().map(|memory| Ok(convert_module_memory(memory?))).collect::>()?; } + Payload::TagSection(reader) => { + check_section("tag", !self.tags.is_empty())?; + #[cfg(feature = "validate")] + if let Some(validator) = validator.as_mut() { + validator.tag_section(&reader)?; + } + let mut tags = Vec::with_capacity(reader.count() as usize); + for tag in reader { + let tag = convert_tag_type(tag?); + let ty = self.types.get(tag.type_idx).and_then(SubType::as_func).ok_or_else(|| { + ParseError::Other(format!("tag type index does not reference a function: {}", tag.type_idx)) + })?; + if !ty.results().is_empty() { + return Err(ParseError::Other(format!("tag type must not have results: {}", tag.type_idx))); + } + tags.push(tag); + } + self.tags = tags.into_boxed_slice(); + } Payload::ElementSection(reader) => { debug!("Found element section"); #[cfg(feature = "validate")] @@ -249,6 +270,20 @@ impl<'a> ModuleReader<'a> { self.imported_func_count += 1; } ImportKind::Memory(_) => self.imported_memory_count += 1, + ImportKind::Tag(tag) => { + let ty = self.types.get(tag.type_idx).and_then(SubType::as_func).ok_or_else(|| { + ParseError::Other(format!( + "tag import type index does not reference a function: {}", + tag.type_idx + )) + })?; + if !ty.results().is_empty() { + return Err(ParseError::Other(format!( + "tag import type must not have results: {}", + tag.type_idx + ))); + } + } _ => {} } imports.push(import); @@ -553,6 +588,7 @@ impl<'a> ModuleReader<'a> { exports: self.exports, elements: self.elements, memory_types: self.memory_types, + tags: self.tags, local_memory_allocation, } .into()) diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs index 74a9fc0..be37e5e 100644 --- a/crates/parser/src/optimize.rs +++ b/crates/parser/src/optimize.rs @@ -910,11 +910,28 @@ fn is_unconditional_terminator(instr: Instruction) -> bool { | Instruction::ReturnCallSelf | Instruction::ReturnCallIndirect(..) | Instruction::ReturnCallRef(_) + | Instruction::Throw(_) + | Instruction::ThrowRef ) } fn target_boundaries(instructions: &[Instruction], function_data: &WasmFunctionData) -> Result> { let mut boundaries = alloc::vec![false; instructions.len() + 1]; + for handler in &function_data.exception_handlers { + for target in [handler.start_ip, handler.end_ip] { + let boundary = boundaries.get_mut(target as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("exception handler boundary out of bounds: {target}")) + })?; + *boundary = true; + } + for catch in &handler.catches { + let target = catch.landing_pad(); + let boundary = boundaries + .get_mut(target as usize) + .ok_or_else(|| ParseError::Other(alloc::format!("exception landing pad out of bounds: {target}")))?; + *boundary = true; + } + } for instr in instructions { if let Some(target) = instruction_target(instr) { let boundary = boundaries @@ -948,6 +965,31 @@ fn finalize( imported_memory_count: u32, ) -> Result { let len = instructions.len() as u32; + for handler in &mut function_data.exception_handlers { + if let Some(old_to_new) = old_to_new { + handler.start_ip = *old_to_new.get(handler.start_ip as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("exception handler boundary out of bounds: {}", handler.start_ip)) + })?; + handler.end_ip = *old_to_new.get(handler.end_ip as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("exception handler boundary out of bounds: {}", handler.end_ip)) + })?; + for catch in &mut handler.catches { + let landing_pad = match catch { + tinywasm_types::ExceptionCatch::Tag { landing_pad, .. } + | tinywasm_types::ExceptionCatch::All { landing_pad, .. } => landing_pad, + }; + *landing_pad = *old_to_new.get(*landing_pad as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("exception landing pad out of bounds: {landing_pad}")) + })?; + } + } + if handler.start_ip > handler.end_ip || handler.end_ip > len { + return Err(ParseError::Other("exception handler range out of bounds".into())); + } + if handler.catches.iter().any(|catch| catch.landing_pad() >= len) { + return Err(ParseError::Other("exception landing pad out of bounds".into())); + } + } for target in &mut function_data.branch_table_targets { if let Some(old_to_new) = old_to_new { *target = *old_to_new diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index 46d1f9f..c462d05 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -6,8 +6,8 @@ use crate::{ use alloc::string::ToString; use alloc::vec::Vec; use tinywasm_types::{ - Global, Import, ImportKind, Instruction, MemoryArg, MemoryType, StorageType, SubType, TableDefinition, TypeSection, - ValueCounts, ValueLane, WasmFunctionData, + Global, Import, ImportKind, Instruction, MemoryArg, MemoryType, StorageType, SubType, TableDefinition, TagType, + TypeSection, ValueCounts, ValueLane, WasmFunctionData, }; use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator}; @@ -20,6 +20,7 @@ enum BlockKind { Block, Loop, If, + TryTable(usize), } struct ControlFrame { @@ -48,6 +49,7 @@ pub(crate) struct ModuleMetadata { globals: Vec, memories: Vec, tables: Vec, + tags: Vec, types: Vec, } @@ -55,6 +57,7 @@ pub(crate) struct ModuleMetadata { struct FunctionDataBuilder { v128_constants: Vec<[u8; 16]>, branch_table_targets: Vec, + exception_handlers: Vec, } pub(crate) struct FunctionBuilder<'a> { @@ -133,11 +136,13 @@ impl ModuleMetadata { globals: &[Global], memories: &[MemoryType], tables: &[TableDefinition], + tags: &[TagType], ) -> Self { let mut functions = Vec::with_capacity(imports.len() + code_type_addrs.len()); let mut global_sizes = Vec::with_capacity(imports.len() + globals.len()); let mut memory_sizes = Vec::with_capacity(imports.len() + memories.len()); let mut table_sizes = Vec::with_capacity(imports.len() + tables.len()); + let mut tag_types = Vec::with_capacity(imports.len() + tags.len()); for import in imports { match &import.kind { @@ -145,6 +150,7 @@ impl ModuleMetadata { ImportKind::Global(ty) => global_sizes.push(ValueLane::from(&ty.ty)), ImportKind::Memory(ty) => memory_sizes.push(Self::address_lane(ty.arch())), ImportKind::Table(ty) => table_sizes.push(Self::address_lane(ty.arch())), + ImportKind::Tag(ty) => tag_types.push(ty.type_idx), } } @@ -152,6 +158,7 @@ impl ModuleMetadata { global_sizes.extend(globals.iter().map(|global| ValueLane::from(&global.ty.ty))); memory_sizes.extend(memories.iter().map(|ty| Self::address_lane(ty.arch()))); table_sizes.extend(tables.iter().map(|table| Self::address_lane(table.ty.arch()))); + tag_types.extend(tags.iter().map(|tag| tag.type_idx)); let signatures = types .types @@ -169,6 +176,7 @@ impl ModuleMetadata { globals: global_sizes, memories: memory_sizes, tables: table_sizes, + tags: tag_types, types: types.types.to_vec(), } } @@ -188,6 +196,14 @@ impl ModuleMetadata { self.signature(ty) } + fn tag_signature(&self, idx: u32) -> Result<&Signature> { + let ty = *self + .tags + .get(idx as usize) + .ok_or_else(|| crate::ParseError::Other(alloc::format!("tag index out of bounds: {idx}")))?; + self.signature(ty) + } + fn global_size(&self, idx: u32) -> Result { Self::indexed_size(&self.globals, "global", idx) } @@ -284,6 +300,7 @@ pub(crate) fn process_operators( let data = WasmFunctionData { v128_constants: builder.data.v128_constants.into_boxed_slice(), branch_table_targets: builder.data.branch_table_targets.into_boxed_slice(), + exception_handlers: builder.data.exception_handlers.into_boxed_slice(), }; Ok((builder.instructions, data, reader.into_allocations())) } @@ -320,6 +337,7 @@ pub(crate) fn process_operators_and_validate( let data = WasmFunctionData { v128_constants: builder.data.v128_constants.into_boxed_slice(), branch_table_targets: builder.data.branch_table_targets.into_boxed_slice(), + exception_handlers: builder.data.exception_handlers.into_boxed_slice(), }; Ok((builder.instructions, data, validator.into_allocations(), reader.into_allocations())) } @@ -648,6 +666,89 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { self.push_control(BlockKind::If, ty, Some(self.instructions.len() - 1)) } + fn visit_try_table(&mut self, try_table: wasmparser::TryTable) -> Self::Output { + let signature = self.block_signature(try_table.ty)?; + for &size in signature.params.iter().rev() { + self.pop_expect(size)?; + } + let height = self.operand_stack.len(); + let base = self.lane_counts; + let entry_unreachable = self.is_unreachable(); + + let body_jump = self.instructions.len(); + self.instructions.push(Instruction::Jump(0)); + let mut catches = Vec::with_capacity(try_table.catches.len()); + for catch in try_table.catches { + let (tag, depth, with_ref) = match catch { + wasmparser::Catch::One { tag, label } => (Some(tag), label, false), + wasmparser::Catch::OneRef { tag, label } => (Some(tag), label, true), + wasmparser::Catch::All { label } => (None, label, false), + wasmparser::Catch::AllRef { label } => (None, label, true), + }; + if let Some(tag) = tag { + self.metadata.tag_signature(tag)?; + } + let target_idx = self.get_ctx_idx(depth)?; + let target_base = self.control_stack[target_idx].base; + let landing_pad = u32::try_from(self.instructions.len()) + .map_err(|_| crate::ParseError::Other("function body is too large".into()))?; + match self.control_stack[target_idx].kind { + BlockKind::Function => self.instructions.push(Instruction::Return), + BlockKind::Loop => { + self.instructions.push(Instruction::Jump(self.control_stack[target_idx].start_ip as u32)); + } + BlockKind::Block | BlockKind::If | BlockKind::TryTable(_) => { + self.control_stack[target_idx].branch_jumps.push(self.instructions.len()); + self.control_stack[target_idx].end_reachable = true; + self.instructions.push(Instruction::Jump(0)); + } + } + catches.push(match tag { + Some(tag) => tinywasm_types::ExceptionCatch::Tag { tag, landing_pad, base: target_base, with_ref }, + None => tinywasm_types::ExceptionCatch::All { landing_pad, base: target_base, with_ref }, + }); + } + + let body_start = self.instructions.len(); + self.patch_jump(body_jump, body_start); + let handler_idx = self.data.exception_handlers.len(); + self.data.exception_handlers.push(tinywasm_types::ExceptionHandler { + start_ip: body_start as u32, + end_ip: 0, + catches: catches.into_boxed_slice(), + }); + self.push_sizes(&signature.params)?; + self.control_stack.push(ControlFrame { + kind: BlockKind::TryTable(handler_idx), + has_else: false, + start_ip: body_start, + branch_jumps: Vec::new(), + height, + base, + params: signature.params, + results: signature.results, + unreachable: entry_unreachable, + entry_unreachable, + end_reachable: false, + }); + Ok(()) + } + + fn visit_throw(&mut self, tag_index: u32) -> Self::Output { + let signature = self.metadata.tag_signature(tag_index)?.clone(); + self.apply_effect(&signature.params, &[])?; + self.instructions.push(Instruction::Throw(tag_index)); + self.mark_unreachable(); + Ok(()) + } + + fn visit_throw_ref(&mut self) -> Self::Output { + self.apply_effect(&[ValueLane::S32], &[])?; + self.instructions.push(Instruction::ThrowRef); + self.mark_unreachable(); + Ok(()) + } + fn visit_else(&mut self) -> Self::Output { let (cond_jump_ip, height, base, params, entry_unreachable) = { let ctx = self @@ -672,6 +773,9 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_end(&mut self) -> Self::Output { let ctx = self.control_stack.pop().ok_or_else(|| crate::ParseError::Other("end without control frame".into()))?; + if let BlockKind::TryTable(handler_idx) = ctx.kind { + self.data.exception_handlers[handler_idx].end_ip = self.instructions.len() as u32; + } if matches!(ctx.kind, BlockKind::Function) { self.instructions.push(Instruction::Return); } else { @@ -1184,11 +1288,24 @@ impl FunctionBuilder<'_> { /// Enters a control frame with its parameters restored above the saved base. fn push_control(&mut self, kind: BlockKind, ty: wasmparser::BlockType, initial_jump: Option) -> Result<()> { - let signature = match ty { + let signature = self.block_signature(ty)?; + self.push_control_signature(kind, signature, initial_jump) + } + + fn block_signature(&self, ty: wasmparser::BlockType) -> Result { + Ok(match ty { wasmparser::BlockType::Empty => Signature { params: Vec::new(), results: Vec::new() }, wasmparser::BlockType::Type(ty) => Signature { params: Vec::new(), results: alloc::vec![value_lane(ty)] }, wasmparser::BlockType::FuncType(idx) => self.metadata.signature(idx)?.clone(), - }; + }) + } + + fn push_control_signature( + &mut self, + kind: BlockKind, + signature: Signature, + initial_jump: Option, + ) -> Result<()> { for &size in signature.params.iter().rev() { self.pop_expect(size)?; } @@ -1264,7 +1381,7 @@ impl FunctionBuilder<'_> { match self.control_stack[ctx_idx].kind { BlockKind::Function => self.instructions.push(Instruction::Return), BlockKind::Loop => self.instructions.push(Instruction::Jump(self.control_stack[ctx_idx].start_ip as u32)), - BlockKind::Block | BlockKind::If => { + BlockKind::Block | BlockKind::If | BlockKind::TryTable(_) => { self.control_stack[ctx_idx].branch_jumps.push(self.instructions.len()); self.control_stack[ctx_idx].end_reachable = true; self.instructions.push(Instruction::Jump(0)); diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml index 6cf9b17..67d0742 100644 --- a/crates/tinywasm/Cargo.toml +++ b/crates/tinywasm/Cargo.toml @@ -34,7 +34,6 @@ name = "test-wasm-1" [[test]] harness = false name = "test-wasm-3" -test = false [[test]] harness = false @@ -43,7 +42,6 @@ name = "test-wasm-2" [[test]] harness = false name = "test-wasm-latest" -test = false [[test]] harness = false diff --git a/crates/tinywasm/src/error.rs b/crates/tinywasm/src/error.rs index ebd0470..0597847 100644 --- a/crates/tinywasm/src/error.rs +++ b/crates/tinywasm/src/error.rs @@ -2,8 +2,8 @@ use alloc::boxed::Box; use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::fmt::{Debug, Display}; -use tinywasm_types::FuncType; use tinywasm_types::archive::TwasmError; +use tinywasm_types::{ExnRef, FuncType}; #[cfg(feature = "parser")] pub use tinywasm_parser::ParseError; @@ -14,6 +14,9 @@ pub enum Error { /// A WebAssembly trap occurred Trap(Trap), + /// An uncaught WebAssembly exception occurred. + Exception(ExnRef), + /// A linking error occurred Linker(LinkingError), @@ -50,6 +53,7 @@ impl PartialEq for Error { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Trap(a), Self::Trap(b)) => a == b, + (Self::Exception(a), Self::Exception(b)) => a == b, (Self::Linker(a), Self::Linker(b)) => a == b, (Self::UnsupportedFeature(a), Self::UnsupportedFeature(b)) => a == b, (Self::Other(a), Self::Other(b)) => a == b, @@ -274,6 +278,7 @@ impl Display for Error { Self::Twasm(err) => write!(f, "serialization error: {err}"), Self::Trap(trap) => write!(f, "trap: {trap}"), + Self::Exception(_) => write!(f, "uncaught WebAssembly exception"), Self::Linker(err) => write!(f, "linking error: {err}"), Self::InvalidLabelType => write!(f, "invalid label type"), Self::Other(message) => write!(f, "unknown error: {message}"), diff --git a/crates/tinywasm/src/func/resume.rs b/crates/tinywasm/src/func/resume.rs index a71be32..892aa05 100644 --- a/crates/tinywasm/src/func/resume.rs +++ b/crates/tinywasm/src/func/resume.rs @@ -3,7 +3,7 @@ use tinywasm_types::{FuncAddr, TypeAddr, WasmValue}; use super::{FromWasmValues, Function, FunctionTyped, IntoWasmValues}; use crate::interpreter::stack::{CallFrame, StackBase}; -use crate::{Error, InterpreterRuntime, Result, Store, Trap}; +use crate::{Error, InterpreterRuntime, Result, Store}; #[derive(Clone, PartialEq, Eq)] /// Progress for fuel-limited function execution. @@ -93,7 +93,7 @@ impl Function { impl<'store> FuncExecution<'store> { fn resume_raw( &mut self, - run: impl FnOnce(&mut Store, CallFrame) -> Result, + run: impl FnOnce(&mut Store, CallFrame) -> Result, ) -> Result> { let (callframe, root_func_addr) = match &mut self.state { FuncExecutionState::Running { callframe, root_func_addr } => (*callframe, *root_func_addr), @@ -109,7 +109,17 @@ impl<'store> FuncExecution<'store> { let result = run(self.store, callframe); self.store.exit_execution(); - match result? { + let result = match result { + Ok(result) => result, + Err(error) => { + self.store.call_stack.clear(); + self.store.value_stack.clear(); + self.state = FuncExecutionState::Completed(None); + return Err(error); + } + }; + + match result { crate::interpreter::ExecState::Completed => { let func = self.store.state.get_func(root_func_addr); let result_ty = func.type_addr; @@ -129,7 +139,7 @@ impl<'store> FuncExecution<'store> { fn resume( &mut self, - run: impl FnOnce(&mut Store, CallFrame) -> Result, + run: impl FnOnce(&mut Store, CallFrame) -> Result, ) -> Result>> { match self.resume_raw(run)? { ExecProgress::Completed(CallResult::Stack { type_addr, pin_refs }) => { @@ -231,7 +241,7 @@ impl FunctionTyped { impl<'store, R: FromWasmValues> FuncExecutionTyped<'store, R> { fn resume( &mut self, - run: impl FnOnce(&mut Store, CallFrame) -> Result, + run: impl FnOnce(&mut Store, CallFrame) -> Result, ) -> Result> { match self.execution.resume_raw(run)? { ExecProgress::Completed(CallResult::Stack { type_addr, pin_refs }) => Ok(ExecProgress::Completed( diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs index a35cf2c..8232a90 100644 --- a/crates/tinywasm/src/imports.rs +++ b/crates/tinywasm/src/imports.rs @@ -3,7 +3,7 @@ use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::hint::cold_path; -use crate::{Function, Global, HostFunction, LinkingError, Memory, Result, Table}; +use crate::{Function, Global, HostFunction, LinkingError, Memory, Result, Table, Tag}; use tinywasm_types::*; #[derive(Clone)] @@ -21,6 +21,8 @@ pub enum Extern { Function(Function), /// A reusable host function definition. HostFunction(HostFunction), + /// A tag instance. + Tag(Tag), } macro_rules! impl_conv { @@ -41,6 +43,7 @@ impl_conv! { Memory => Memory, Function => Function, HostFunction => HostFunction, + Tag => Tag, } /// Imports for a module instance @@ -100,6 +103,7 @@ pub(crate) struct ResolvedImports { pub(crate) tables: Vec, pub(crate) memories: Vec, pub(crate) funcs: Vec, + pub(crate) tags: Vec, } impl Imports { @@ -127,7 +131,7 @@ impl Imports { /// Define an import value. /// - /// A [`Function`], [`Global`], [`Table`], or [`Memory`] handle belongs to + /// A [`Function`], [`Global`], [`Table`], [`Memory`], or [`Tag`] handle belongs to /// one store and can only be imported into that store. A [`HostFunction`] /// is a reusable definition and can be imported into multiple stores. /// @@ -225,12 +229,13 @@ impl Imports { module: &Module, type_addrs: &[TypeAddr], ) -> Result { - let (global_count, table_count, mem_count, func_count) = - module.imports.iter().fold((0, 0, 0, 0), |(g, t, m, f), import| match import.kind { - ImportKind::Global(_) => (g + 1, t, m, f), - ImportKind::Table(_) => (g, t + 1, m, f), - ImportKind::Memory(_) => (g, t, m + 1, f), - ImportKind::Function(_) => (g, t, m, f + 1), + let (global_count, table_count, mem_count, func_count, tag_count) = + module.imports.iter().fold((0, 0, 0, 0, 0), |(g, t, m, f, e), import| match import.kind { + ImportKind::Global(_) => (g + 1, t, m, f, e), + ImportKind::Table(_) => (g, t + 1, m, f, e), + ImportKind::Memory(_) => (g, t, m + 1, f, e), + ImportKind::Function(_) => (g, t, m, f + 1, e), + ImportKind::Tag(_) => (g, t, m, f, e + 1), }); let mut imports = ResolvedImports { @@ -238,6 +243,7 @@ impl Imports { tables: Vec::with_capacity(table_count + module.tables.len()), memories: Vec::with_capacity(mem_count + module.memory_types.len()), funcs: Vec::with_capacity(func_count + module.funcs.len()), + tags: Vec::with_capacity(tag_count + module.tags.len()), }; for import in &*module.imports { @@ -259,6 +265,10 @@ impl Imports { Extern::HostFunction(func) => { (ExternVal::Func(func.instantiate_for_import(store, type_addrs)?.addr()), None) } + Extern::Tag(tag) => { + tag.0.validate_store(store)?; + (ExternVal::Tag(tag.0.addr), None) + } } } else { let Some(instance) = self.modules.get(import.module.as_ref()) else { @@ -317,6 +327,16 @@ impl Imports { } imports.funcs.push(func_addr); } + (ExternVal::Tag(tag_addr), ImportKind::Tag(ty)) => { + let expected_type_addr = type_addrs + .get(ty.type_idx as usize) + .ok_or_else(|| LinkingError::incompatible_import_type(import))?; + if store.state.get_tag(tag_addr).type_addr != *expected_type_addr { + cold_path(); + return Err(LinkingError::incompatible_import_type(import).into()); + } + imports.tags.push(tag_addr); + } _ => unreachable!("import kind checked above"), } } diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index 52bb948..23bb298 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -4,7 +4,7 @@ use tinywasm_types::*; use crate::func::{FromWasmValues, IntoWasmValues, ToWasmTypes}; use crate::store::MemoryInstance; -use crate::{Error, Function, FunctionTyped, Global, Imports, Memory, Result, Store, StoreItem, Table, Trap}; +use crate::{Error, Function, FunctionTyped, Global, Imports, Memory, Result, Store, StoreItem, Table, Tag, Trap}; /// A typed view over an exported extern value. pub enum ExternItem { @@ -16,6 +16,8 @@ pub enum ExternItem { Table(Table), /// Exported global reference. Global(Global), + /// Exported tag reference. + Tag(Tag), } /// An instantiated WebAssembly module @@ -52,6 +54,7 @@ struct ModuleInstanceInner { table_addrs: Box<[TableAddr]>, mem_addrs: Box<[MemAddr]>, global_addrs: Box<[GlobalAddr]>, + tag_addrs: Box<[TagAddr]>, elem_addrs: Box<[ElemAddr]>, data_addrs: Box<[DataAddr]>, func_start: Option, @@ -100,6 +103,11 @@ impl ModuleInstance { *self.0.global_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) } + #[inline] + pub(crate) fn resolve_tag_addr(&self, addr: TagAddr) -> TagAddr { + *self.0.tag_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid tag address: {addr}")) + } + #[inline] pub(crate) fn validate_store(&self, store: &Store) -> Result<()> { if self.0.store_id != store.id() { @@ -157,6 +165,7 @@ impl ModuleInstance { let mut addrs = imports.unwrap_or(&default_imports).link(store, module, &type_addrs)?; let imported_funcs = addrs.funcs.len(); addrs.funcs.extend(store.init_funcs(&module.funcs, id, &module.func_type_idxs[imported_funcs..], &type_addrs)); + addrs.tags.extend(store.init_tags(&module.tags, &type_addrs)); match module.local_memory_allocation { LocalMemoryAllocation::Skip => { #[cfg(feature = "guest-debug")] @@ -185,6 +194,7 @@ impl ModuleInstance { table_addrs: addrs.tables.into_boxed_slice(), mem_addrs: addrs.memories.into_boxed_slice(), global_addrs: addrs.globals.into_boxed_slice(), + tag_addrs: addrs.tags.into_boxed_slice(), elem_addrs, data_addrs, func_start: module.start_func, @@ -209,6 +219,7 @@ impl ModuleInstance { ExternalKind::Table => self.0.table_addrs.get(export.index as usize)?, ExternalKind::Memory => self.0.mem_addrs.get(export.index as usize)?, ExternalKind::Global => self.0.global_addrs.get(export.index as usize)?, + ExternalKind::Tag => self.0.tag_addrs.get(export.index as usize)?, }; Some(ExternVal::new(export.kind, *addr)) } @@ -257,6 +268,9 @@ impl ModuleInstance { ExternalKind::Global => { ExternItem::Global(Global(StoreItem::new(self.0.store_id, self.resolve_global_addr(export.index)))) } + ExternalKind::Tag => { + ExternItem::Tag(Tag(StoreItem::new(self.0.store_id, self.resolve_tag_addr(export.index)))) + } }; (export.name.as_ref(), item) @@ -309,6 +323,7 @@ impl ModuleInstance { ExternVal::Memory(addr) => Ok(ExternItem::Memory(Memory(StoreItem::new(self.0.store_id, addr)))), ExternVal::Table(addr) => Ok(ExternItem::Table(Table(StoreItem::new(self.0.store_id, addr)))), ExternVal::Global(addr) => Ok(ExternItem::Global(Global(StoreItem::new(self.0.store_id, addr)))), + ExternVal::Tag(addr) => Ok(ExternItem::Tag(Tag(StoreItem::new(self.0.store_id, addr)))), } } @@ -487,6 +502,21 @@ impl ModuleInstance { Ok(Table(StoreItem::new(self.0.store_id, Self::index_addr(&self.0.table_addrs, table_index, "table")?))) } + /// Get a tag export by name. + pub fn tag(&self, name: &str) -> Result { + match self.require_export(name)? { + ExternVal::Tag(tag_addr) => Ok(Tag(StoreItem::new(self.0.store_id, tag_addr))), + _ => Err(Error::Other(format!("Export is not a tag: {name}"))), + } + } + + /// Get a tag by its module-local index. + #[cfg_attr(docsrs, doc(cfg(feature = "guest-debug")))] + #[cfg(feature = "guest-debug")] + pub fn tag_by_index(&self, tag_index: TagAddr) -> Result { + Ok(Tag(StoreItem::new(self.0.store_id, Self::index_addr(&self.0.tag_addrs, tag_index, "tag")?))) + } + /// Get the value of a global export by name. pub fn global_get(&self, store: &Store, name: &str) -> Result { self.global(name)?.get(store) diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index f5c9351..22c8441 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -65,7 +65,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } #[inline(always)] - fn exec(&mut self) -> Result, Trap> { + fn exec(&mut self) -> Result> { macro_rules! stack_op { (unary $ty:ty, |$v:ident| $expr:expr) => { stack_op!(unary $ty => $ty, |$v| $expr) @@ -223,7 +223,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { use tinywasm_types::Instruction::*; #[rustfmt::skip] match &self.func.instructions[self.cf.instr_ptr] { - Unreachable => { cold_path(); return Err(Trap::Unreachable) }, + Unreachable => { cold_path(); return Err(Trap::Unreachable.into()) }, Drop32 => { _ = Value32::stack_pop(&mut self.store.value_stack)}, Drop64 => { _ = Value64::stack_pop(&mut self.store.value_stack)}, Drop128 => { _ = Value128::stack_pop(&mut self.store.value_stack)}, @@ -239,6 +239,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { ReturnCallSelf => { self.exec_return_call_self()?; return Ok(None); } ReturnCallIndirect(ty, table) => { if self.exec_call_indirect::(*ty, *table)? { return Ok(Some(())); } return Ok(None); } ReturnCallRef(ty) => { if self.exec_call_ref::(*ty)? { return Ok(Some(())); } return Ok(None); } + Throw(tag) => { self.exec_throw(*tag)?; return Ok(None); } + ThrowRef => { self.exec_throw_ref()?; return Ok(None); } Jump(ip) => { self.cf.instr_ptr = *ip as usize; return Ok(None); } JumpIfZero32(ip) => if self.exec_jump_zero_32(*ip) { return Ok(None) }, JumpIfNonZero32(ip) => if self.exec_jump_non_zero_32(*ip) { return Ok(None) }, @@ -472,7 +474,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { RefCast(ty) => { if !self.exec_ref_matches(*ty) { cold_path(); - return Err(Trap::CastFailure); + return Err(Trap::CastFailure.into()); } } // GC objects @@ -992,6 +994,135 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.store.value_stack.truncate_keep_counts(base, drop_keep.keep); } + fn create_exception(&mut self, tag_index: TagAddr) -> Result { + let tag_addr = self.module.resolve_tag_addr(tag_index); + let type_addr = self.store.state.get_tag(tag_addr).type_addr; + let addr = u32::try_from(self.store.state.exceptions.len()).map_err(|_| Trap::OutOfMemory)?; + self.store.state.exceptions.try_reserve(1).map_err(|_| Trap::OutOfMemory)?; + let params = self.store.state.get_canonical_func_type(type_addr).params(); + let mut payload = Vec::new(); + payload.try_reserve_exact(params.len()).map_err(|_| Trap::OutOfMemory)?; + for &ty in params.iter().rev() { + payload.push(match ty { + WasmType::I32 | WasmType::F32 => { + TinyWasmValue::Value32(Value32::stack_pop(&mut self.store.value_stack)) + } + WasmType::I64 | WasmType::F64 => { + TinyWasmValue::Value64(Value64::stack_pop(&mut self.store.value_stack)) + } + WasmType::V128 => TinyWasmValue::Value128(Value128::stack_pop(&mut self.store.value_stack)), + WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::stack_pop(&mut self.store.value_stack)), + }); + } + payload.reverse(); + self.store + .state + .exceptions + .push(crate::store::ExceptionInstance { tag_addr, payload: payload.into_boxed_slice() }); + Ok(addr) + } + + fn exec_throw(&mut self, tag_index: TagAddr) -> Result<()> { + let exception = self.create_exception(tag_index)?; + let outcome = match self.dispatch_exception(exception) { + Ok(outcome) => outcome, + Err(trap) => { + _ = self.store.state.exceptions.pop(); + return Err(trap.into()); + } + }; + match outcome { + Some(catch) if !catch.with_ref() => { + debug_assert_eq!(self.store.state.exceptions.len() - 1, exception as usize); + _ = self.store.state.exceptions.pop(); + Ok(()) + } + Some(_) => Ok(()), + None => Err(Error::Exception(ExnRef::new(exception))), + } + } + + fn exec_throw_ref(&mut self) -> Result<()> { + let exception = ValueRef::stack_pop(&mut self.store.value_stack); + let exception = exception + .addr() + .filter(|addr| self.store.state.exceptions.get(*addr as usize).is_some()) + .ok_or(Trap::NullReference)?; + match self.dispatch_exception(exception)? { + Some(_) => Ok(()), + None => Err(Error::Exception(ExnRef::new(exception))), + } + } + + fn matching_catch(&self, protected_ip: usize, tag_addr: TagAddr) -> Option { + let handlers = &self.func.data.exception_handlers; + let end = handlers.partition_point(|handler| handler.start_ip as usize <= protected_ip); + handlers[..end] + .iter() + .rev() + .filter(|handler| protected_ip < handler.end_ip as usize) + .flat_map(|handler| handler.catches.iter().copied()) + .find(|catch| match catch { + ExceptionCatch::Tag { tag, .. } => self.module.resolve_tag_addr(*tag) == tag_addr, + ExceptionCatch::All { .. } => true, + }) + } + + fn switch_to_frame(&mut self, frame: CallFrame) { + let previous = core::mem::replace(&mut self.cf, frame); + if previous.func_addr == self.cf.func_addr { + return; + } + + let wasm_func = self.store.state.get_wasm_func(self.cf.func_addr); + self.func = wasm_func.func.clone(); + if wasm_func.owner != self.module.id() { + self.module = self + .store + .get_module_instance(wasm_func.owner) + .unwrap_or_else(|| unreachable!("invalid module instance")) + .clone(); + } + } + + fn dispatch_exception(&mut self, exception_addr: ExnAddr) -> Result, Trap> { + let tag_addr = self.store.state.exceptions[exception_addr as usize].tag_addr; + let mut protected_ip = self.cf.instr_ptr; + loop { + if let Some(catch) = self.matching_catch(protected_ip, tag_addr) { + let (landing_pad, base, with_ref, include_payload) = match catch { + ExceptionCatch::Tag { landing_pad, base, with_ref, .. } => (landing_pad, base, with_ref, true), + ExceptionCatch::All { landing_pad, base, with_ref } => (landing_pad, base, with_ref, false), + }; + let stack_base = self.cf.stack_base(); + let target = interpreter::stack::StackBase { + s32: stack_base.s32 + base.c32 as u32, + s64: stack_base.s64 + base.c64 as u32, + s128: stack_base.s128 + base.c128 as u32, + }; + self.store.value_stack.truncate_to_base(target); + if include_payload { + let Store { state, value_stack, .. } = self.store; + for value in state.exceptions[exception_addr as usize].payload.iter().copied() { + value_stack.push_dyn(value)?; + } + } + if with_ref { + self.store.value_stack.push(ValueRef::from_category_addr(exception_addr))?; + } + self.cf.instr_ptr = landing_pad as usize; + return Ok(Some(catch)); + } + + self.store.value_stack.truncate_to_base(self.cf.locals_base); + let Some(caller) = self.store.call_stack.pop_frame(self.call_stack_base) else { + return Ok(None); + }; + self.switch_to_frame(caller); + protected_ip = self.cf.instr_ptr.checked_sub(1).unwrap_or_else(|| unreachable!("invalid caller IP")); + } + } + fn exec_call(&mut self, wasm_func: WasmFunctionInstance, func_addr: FuncAddr) -> Result<(), Trap> { if !Arc::ptr_eq(&self.func, &wasm_func.func) { self.func = wasm_func.func.clone(); @@ -1207,20 +1338,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let Some(caller) = self.store.call_stack.pop_frame(self.call_stack_base) else { return true; }; - if caller.func_addr == self.cf.func_addr { - self.cf = caller; - return false; - } - let wasm_func = self.store.state.get_wasm_func(caller.func_addr); - self.func = wasm_func.func.clone(); - if wasm_func.owner != self.module.id() { - self.module = self - .store - .get_module_instance(wasm_func.owner) - .unwrap_or_else(|| unreachable!("invalid module instance")) - .clone(); - } - self.cf = caller; + self.switch_to_frame(caller); false } @@ -1922,7 +2040,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { impl<'store> Executor<'store, false> { #[inline(always)] - pub(crate) fn run_to_completion(&mut self) -> Result<(), Trap> { + pub(crate) fn run_to_completion(&mut self) -> Result<()> { // ideally we use `loop_match` / `become` once thats stabilized loop { if self.exec()?.is_some() { @@ -1933,7 +2051,7 @@ impl<'store> Executor<'store, false> { #[cfg(feature = "std")] #[inline(always)] - pub(crate) fn run_with_time_budget(&mut self, time_budget: core::time::Duration) -> Result { + pub(crate) fn run_with_time_budget(&mut self, time_budget: core::time::Duration) -> Result { use crate::std::time::Instant; let start = Instant::now(); if time_budget.is_zero() { @@ -1956,7 +2074,7 @@ impl<'store> Executor<'store, false> { impl<'store> Executor<'store, true> { #[inline(always)] - pub(crate) fn run_with_fuel(&mut self, fuel: u32) -> Result { + pub(crate) fn run_with_fuel(&mut self, fuel: u32) -> Result { self.store.execution_fuel = fuel; if self.store.execution_fuel == 0 { return Ok(ExecState::Suspended(self.cf)); diff --git a/crates/tinywasm/src/interpreter/mod.rs b/crates/tinywasm/src/interpreter/mod.rs index cece36a..6e6912c 100644 --- a/crates/tinywasm/src/interpreter/mod.rs +++ b/crates/tinywasm/src/interpreter/mod.rs @@ -7,7 +7,7 @@ pub(crate) mod values; #[cfg(not(feature = "std"))] mod no_std_floats; -use crate::{Result, Store, Trap, interpreter::stack::CallFrame}; +use crate::{Result, Store, interpreter::stack::CallFrame}; pub(crate) use simd::*; pub(crate) use values::*; @@ -26,11 +26,11 @@ pub(crate) enum ExecState { pub(crate) struct InterpreterRuntime; impl InterpreterRuntime { - pub(crate) fn exec(store: &mut Store, cf: CallFrame, call_stack_base: u32) -> Result<(), Trap> { + pub(crate) fn exec(store: &mut Store, cf: CallFrame, call_stack_base: u32) -> Result<()> { executor::Executor::::new(store, cf, call_stack_base).run_to_completion() } - pub(crate) fn exec_with_fuel(store: &mut Store, cf: CallFrame, fuel: u32) -> Result { + pub(crate) fn exec_with_fuel(store: &mut Store, cf: CallFrame, fuel: u32) -> Result { executor::Executor::::new(store, cf, 0).run_with_fuel(fuel) } @@ -39,7 +39,7 @@ impl InterpreterRuntime { store: &mut Store, cf: CallFrame, time_budget: core::time::Duration, - ) -> Result { + ) -> Result { executor::Executor::::new(store, cf, 0).run_with_time_budget(time_budget) } } diff --git a/crates/tinywasm/src/interpreter/num_helpers.rs b/crates/tinywasm/src/interpreter/num_helpers.rs index 7b3807e..783b10b 100644 --- a/crates/tinywasm/src/interpreter/num_helpers.rs +++ b/crates/tinywasm/src/interpreter/num_helpers.rs @@ -32,11 +32,11 @@ macro_rules! checked_conv_float { let (min, max) = float_min_max!($from, $intermediate); if v.is_nan() { core::hint::cold_path(); - return Err(crate::Trap::InvalidConversionToInt); + return Err(crate::Trap::InvalidConversionToInt.into()); } if v <= min || v >= max { core::hint::cold_path(); - return Err(crate::Trap::IntegerOverflow); + return Err(crate::Trap::IntegerOverflow.into()); } $self.store.value_stack.push::<$to>((v as $intermediate as $to).into())?; }}; diff --git a/crates/tinywasm/src/reference.rs b/crates/tinywasm/src/reference.rs index 6e904af..55f9e3b 100644 --- a/crates/tinywasm/src/reference.rs +++ b/crates/tinywasm/src/reference.rs @@ -8,7 +8,9 @@ use alloc::vec::Vec; use crate::interpreter::ValueRef; use crate::store::TableInstance; use crate::{Error, MemoryInstance, Result, Store, Trap}; -use tinywasm_types::{Addr, GlobalType, MemAddr, MemoryType, TableAddr, TableType, WasmType, WasmValue}; +use tinywasm_types::{ + Addr, FuncType, GlobalType, MemAddr, MemoryType, TableAddr, TableType, TagAddr, WasmType, WasmValue, +}; #[derive(Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "debug", derive(Debug))] @@ -66,6 +68,11 @@ pub struct Table(pub(crate) StoreItem); #[cfg_attr(feature = "debug", derive(Debug))] pub struct Global(pub(crate) StoreItem); +/// A tag instance in a store. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct Tag(pub(crate) StoreItem); + /// A cursor over a [`Memory`] instance. /// /// Available with the `std` feature enabled. @@ -471,3 +478,22 @@ impl Global { store.state.set_global_wasmvalue(self.0.addr, value) } } + +impl Tag { + /// Create a new exception tag in the given store. + pub fn new(store: &mut Store, ty: FuncType) -> Result { + if !ty.results().is_empty() { + return Err(Error::other("tag types must not have results")); + } + let type_addr = store.register_host_type(&ty); + let addr = store.state.tags.len() as TagAddr; + store.state.tags.push(crate::store::TagInstance { type_addr }); + Ok(Self(StoreItem::new(store.id(), addr))) + } + + /// Get the payload type of the tag. + pub fn ty<'a>(&self, store: &'a Store) -> Result<&'a FuncType> { + self.0.validate_store(store)?; + Ok(store.state.get_canonical_func_type(store.state.get_tag(self.0.addr).type_addr)) + } +} diff --git a/crates/tinywasm/src/store/exception.rs b/crates/tinywasm/src/store/exception.rs new file mode 100644 index 0000000..0725cda --- /dev/null +++ b/crates/tinywasm/src/store/exception.rs @@ -0,0 +1,10 @@ +use alloc::boxed::Box; +use tinywasm_types::TagAddr; + +use crate::interpreter::TinyWasmValue; + +#[cfg_attr(feature = "debug", derive(Debug))] +pub(crate) struct ExceptionInstance { + pub(crate) tag_addr: TagAddr, + pub(crate) payload: Box<[TinyWasmValue]>, +} diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 0cd5e5b..84a52b5 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -11,12 +11,14 @@ use crate::{Engine, Error, ModuleInstance, Result, Trap}; mod const_expr; mod data; mod element; +mod exception; mod function; mod gc; mod global; mod memory; mod state; mod table; +mod tag; mod types; use const_expr::eval_const; @@ -25,7 +27,7 @@ pub use memory::{LazyLinearMemory, LinearMemory, MemoryBackend, PagedMemory, Vec pub(crate) use memory::{MemValue, MemoryInstance}; pub(crate) use state::State; pub(crate) use types::{canonicalize_ref_type, canonicalize_value_type}; -pub(crate) use {data::*, element::*, function::*, global::*, table::*}; +pub(crate) use {data::*, element::*, exception::*, function::*, global::*, table::*, tag::*}; // global store id counter static STORE_ID: AtomicU32 = AtomicU32::new(0); @@ -227,6 +229,18 @@ impl Store { start..start + funcs.len() as FuncAddr } + /// Add tags to the store, returning their addresses in the store. + pub(crate) fn init_tags( + &mut self, + tags: &[TagType], + type_addrs: &[TypeAddr], + ) -> impl ExactSizeIterator { + let start = self.state.tags.len() as TagAddr; + self.state.tags.reserve_exact(tags.len()); + self.state.tags.extend(tags.iter().map(|tag| TagInstance { type_addr: type_addrs[tag.type_idx as usize] })); + start..start + tags.len() as TagAddr + } + /// Add tables to the store, returning their addresses in the store pub(crate) fn init_tables( &mut self, diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index 3371d4c..e6a213f 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -14,6 +14,8 @@ pub(crate) struct State { pub(crate) tables: Vec, pub(crate) memories: Vec, pub(crate) globals: Globals, + pub(crate) tags: Vec, + pub(crate) exceptions: Vec, pub(crate) elements: Vec, pub(crate) data: Vec, pub(crate) gc: Box, @@ -28,6 +30,8 @@ impl State { tables: Vec::new(), memories: Vec::new(), globals: Globals::default(), + tags: Vec::new(), + exceptions: Vec::new(), elements: Vec::new(), data: Vec::new(), gc: Box::new(gc::GcHeap::new(gc_collection_threshold)), @@ -104,6 +108,11 @@ impl State { .filter(|element| Self::type_may_contain_gc_in(canonical_types, &WasmType::Ref(element.ty))) .flat_map(|element| element.items.iter().flatten().copied()), ) + .chain( + self.exceptions + .iter() + .flat_map(|exception| exception.payload.iter().filter_map(|value| value.as_ref())), + ) .chain(values.iter().filter_map(|value| value.as_ref())); self.gc.collect(roots).map_err(|_| Trap::OutOfMemory)?; } @@ -261,6 +270,9 @@ impl State { let actual = RefType::new_concrete(false, func.type_addr).expect("canonical type fits"); return self.ref_type_is_subtype(actual, expected); } + if expected.is_exn() { + return value.addr().is_some_and(|addr| self.exceptions.get(addr as usize).is_some()); + } if value.is_i31() { let actual = RefType::new_abstract(false, AbstractHeapType::I31); return self.ref_type_is_subtype(actual, expected); @@ -304,6 +316,9 @@ impl State { { false } + (WasmValue::Ref(RefValue::Exn(value)), WasmType::Ref(expected)) if expected.is_exn() => { + self.exceptions.get(value.addr() as usize).is_some() + } (WasmValue::Ref(RefValue::Any(value)), WasmType::Ref(expected)) => { self.value_ref_matches(ValueRef::from_raw(value.raw()), expected) } @@ -332,6 +347,10 @@ impl State { Self::get(&self.funcs, addr, "function") } + pub(crate) fn get_tag(&self, addr: TagAddr) -> &TagInstance { + Self::get(&self.tags, addr, "tag") + } + /// Get a wasm function at the actual index in the store, panicking if it's a host function (which should be guaranteed by the validator) pub(crate) fn get_wasm_func(&self, addr: FuncAddr) -> &WasmFunctionInstance { match self.funcs.get(addr as usize).map(|func| &func.kind) { diff --git a/crates/tinywasm/src/store/tag.rs b/crates/tinywasm/src/store/tag.rs new file mode 100644 index 0000000..49c16d8 --- /dev/null +++ b/crates/tinywasm/src/store/tag.rs @@ -0,0 +1,7 @@ +use tinywasm_types::TypeAddr; + +#[derive(Clone, Copy)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub(crate) struct TagInstance { + pub(crate) type_addr: TypeAddr, +} diff --git a/crates/tinywasm/tests/generated/wasm-3.csv b/crates/tinywasm/tests/generated/wasm-3.csv index 7d3961c..fdc0e86 100644 --- a/crates/tinywasm/tests/generated/wasm-3.csv +++ b/crates/tinywasm/tests/generated/wasm-3.csv @@ -1,3 +1,3 @@ 0.9.0,20776,452,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":89,"failed":1},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":37,"failed":9},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] 0.10.0,20778,450,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":38,"failed":8},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] -0.11.0-pre.0,21151,77,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":12,"failed":0},{"name":"br_on_null.wast","passed":10,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":35,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":151,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":124,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":163,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":51,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":46,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":2,"failed":0},{"name":"type-equivalence.wast","passed":32,"failed":0},{"name":"type-rec.wast","passed":27,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":13,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] +0.11.0-pre.0,21228,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":12,"failed":0},{"name":"br_on_null.wast","passed":10,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":35,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":151,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":124,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":218,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":23,"failed":0},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":163,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":120,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":34,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":51,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":46,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":2,"failed":0},{"name":"type-equivalence.wast","passed":32,"failed":0},{"name":"type-rec.wast","passed":27,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":13,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] diff --git a/crates/tinywasm/tests/generated/wasm-latest.csv b/crates/tinywasm/tests/generated/wasm-latest.csv index 94a8b58..b25ec13 100644 --- a/crates/tinywasm/tests/generated/wasm-latest.csv +++ b/crates/tinywasm/tests/generated/wasm-latest.csv @@ -1,3 +1,3 @@ 0.9.0,20777,452,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":121,"failed":0},{"name":"memory.wast","passed":89,"failed":1},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":47,"failed":0},{"name":"return_call_indirect.wast","passed":79,"failed":0},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":37,"failed":9},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] 0.10.0,20697,536,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":1,"failed":11},{"name":"br_on_null.wast","passed":1,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":4,"failed":31},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":63,"failed":2},{"name":"elem.wast","passed":149,"failed":2},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":116,"failed":8},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":142,"failed":21},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":121,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":14,"failed":35},{"name":"return_call_indirect.wast","passed":30,"failed":51},{"name":"return_call_ref.wast","passed":11,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":38,"failed":8},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":0,"failed":2},{"name":"type-equivalence.wast","passed":12,"failed":20},{"name":"type-rec.wast","passed":10,"failed":17},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":11},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] -0.11.0-pre.0,21156,77,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":12,"failed":0},{"name":"br_on_null.wast","passed":10,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":35,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":151,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":124,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":198,"failed":20},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":0,"failed":23},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":163,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":121,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":0,"failed":34},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":49,"failed":0},{"name":"return_call_indirect.wast","passed":81,"failed":0},{"name":"return_call_ref.wast","passed":51,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":46,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":2,"failed":0},{"name":"type-equivalence.wast","passed":32,"failed":0},{"name":"type-rec.wast","passed":27,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":13,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] +0.11.0-pre.0,21233,0,[{"name":"address.wast","passed":260,"failed":0},{"name":"align.wast","passed":165,"failed":0},{"name":"annotations.wast","passed":74,"failed":0},{"name":"binary-leb128.wast","passed":91,"failed":0},{"name":"binary.wast","passed":127,"failed":0},{"name":"block.wast","passed":223,"failed":0},{"name":"br.wast","passed":97,"failed":0},{"name":"br_if.wast","passed":119,"failed":0},{"name":"br_on_non_null.wast","passed":12,"failed":0},{"name":"br_on_null.wast","passed":10,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call.wast","passed":91,"failed":0},{"name":"call_indirect.wast","passed":172,"failed":0},{"name":"call_ref.wast","passed":35,"failed":0},{"name":"comments.wast","passed":8,"failed":0},{"name":"const.wast","passed":778,"failed":0},{"name":"conversions.wast","passed":619,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":151,"failed":0},{"name":"endianness.wast","passed":69,"failed":0},{"name":"exports.wast","passed":97,"failed":0},{"name":"f32.wast","passed":2514,"failed":0},{"name":"f32_bitwise.wast","passed":364,"failed":0},{"name":"f32_cmp.wast","passed":2407,"failed":0},{"name":"f64.wast","passed":2514,"failed":0},{"name":"f64_bitwise.wast","passed":364,"failed":0},{"name":"f64_cmp.wast","passed":2407,"failed":0},{"name":"fac.wast","passed":8,"failed":0},{"name":"float_exprs.wast","passed":927,"failed":0},{"name":"float_literals.wast","passed":179,"failed":0},{"name":"float_memory.wast","passed":90,"failed":0},{"name":"float_misc.wast","passed":471,"failed":0},{"name":"forward.wast","passed":5,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"func_ptrs.wast","passed":36,"failed":0},{"name":"global.wast","passed":124,"failed":0},{"name":"i32.wast","passed":460,"failed":0},{"name":"i64.wast","passed":416,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"imports.wast","passed":218,"failed":0},{"name":"inline-module.wast","passed":1,"failed":0},{"name":"instance.wast","passed":23,"failed":0},{"name":"int_exprs.wast","passed":108,"failed":0},{"name":"int_literals.wast","passed":51,"failed":0},{"name":"labels.wast","passed":29,"failed":0},{"name":"left-to-right.wast","passed":96,"failed":0},{"name":"linking.wast","passed":163,"failed":0},{"name":"load.wast","passed":97,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"local_set.wast","passed":53,"failed":0},{"name":"local_tee.wast","passed":98,"failed":0},{"name":"loop.wast","passed":121,"failed":0},{"name":"memory.wast","passed":90,"failed":0},{"name":"memory_grow.wast","passed":106,"failed":0},{"name":"memory_redundancy.wast","passed":8,"failed":0},{"name":"memory_size.wast","passed":42,"failed":0},{"name":"memory_trap.wast","passed":182,"failed":0},{"name":"names.wast","passed":486,"failed":0},{"name":"nop.wast","passed":88,"failed":0},{"name":"obsolete-keywords.wast","passed":11,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":34,"failed":0},{"name":"return.wast","passed":84,"failed":0},{"name":"return_call.wast","passed":49,"failed":0},{"name":"return_call_indirect.wast","passed":81,"failed":0},{"name":"return_call_ref.wast","passed":51,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"skip-stack-guard-page.wast","passed":11,"failed":0},{"name":"stack.wast","passed":7,"failed":0},{"name":"start.wast","passed":20,"failed":0},{"name":"store.wast","passed":68,"failed":0},{"name":"switch.wast","passed":28,"failed":0},{"name":"table.wast","passed":46,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":58,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"token.wast","passed":61,"failed":0},{"name":"traps.wast","passed":36,"failed":0},{"name":"type-canon.wast","passed":2,"failed":0},{"name":"type-equivalence.wast","passed":32,"failed":0},{"name":"type-rec.wast","passed":27,"failed":0},{"name":"type.wast","passed":3,"failed":0},{"name":"unreachable.wast","passed":64,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":13,"failed":0},{"name":"unwind.wast","passed":50,"failed":0},{"name":"utf8-custom-section-id.wast","passed":176,"failed":0},{"name":"utf8-import-field.wast","passed":176,"failed":0},{"name":"utf8-import-module.wast","passed":176,"failed":0},{"name":"utf8-invalid-encoding.wast","passed":176,"failed":0}] diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index b920ac7..aff9e24 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -1,4 +1,6 @@ -use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TypeAddr, ValueCounts}; +use alloc::boxed::Box; + +use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TagAddr, TypeAddr, ValueCounts}; use crate::{ConstIdx, DataAddr, ElemAddr, MemAddr, RefType, RefValue}; /// Represents a memory immediate in a WebAssembly memory instruction. @@ -20,6 +22,46 @@ pub struct DropKeep { pub keep: ValueCounts, } +/// A catch clause attached to a lowered `try_table` instruction. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub enum ExceptionCatch { + /// Catch exceptions carrying the specified module-local tag. + Tag { tag: TagAddr, landing_pad: u32, base: ValueCounts, with_ref: bool }, + /// Catch any exception. + All { landing_pad: u32, base: ValueCounts, with_ref: bool }, +} + +impl ExceptionCatch { + /// Returns the catch landing pad instruction pointer. + pub const fn landing_pad(self) -> u32 { + match self { + Self::Tag { landing_pad, .. } | Self::All { landing_pad, .. } => landing_pad, + } + } + + /// Returns whether this clause exposes the caught exception reference. + pub const fn with_ref(self) -> bool { + match self { + Self::Tag { with_ref, .. } | Self::All { with_ref, .. } => with_ref, + } + } +} + +/// A statically lowered exception handler range. +#[derive(Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct ExceptionHandler { + /// First protected instruction, inclusive. + pub start_ip: u32, + /// End of the protected instruction range, exclusive. + pub end_ip: u32, + /// Catch clauses in source order. + pub catches: Box<[ExceptionCatch]>, +} + impl From<(ValueCounts, ValueCounts)> for DropKeep { fn from((base, keep): (ValueCounts, ValueCounts)) -> Self { Self { base, keep } @@ -229,6 +271,8 @@ pub enum Instruction { ReturnCallSelf, ReturnCallIndirect(TypeAddr, TableAddr), ReturnCallRef(TypeAddr), + Throw(TagAddr), + ThrowRef, // > Parametric Instructions // See diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index 0fd4e81..78a8d0d 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -111,6 +111,11 @@ pub struct ModuleInner { /// Corresponds to the `memory` section of the original WebAssembly module. pub memory_types: Box<[MemoryType]>, + /// Tag components of the WebAssembly module. + /// + /// Corresponds to the `tag` section of the original WebAssembly module. + pub tags: Box<[TagType]>, + /// Imports of the WebAssembly module. /// /// Corresponds to the `import` section of the original WebAssembly module. @@ -141,6 +146,7 @@ impl Module { ImportKind::Table(table_ty) => Some(ImportType::Table(table_ty)), ImportKind::Memory(memory_ty) => Some(ImportType::Memory(memory_ty)), ImportKind::Global(global_ty) => Some(ImportType::Global(global_ty)), + ImportKind::Tag(tag_ty) => Some(ImportType::Tag(self.0.types.get(tag_ty.type_idx)?.as_func()?)), }?; Some(ModuleImport { module: import.module.as_ref(), name: import.name.as_ref(), ty }) @@ -162,6 +168,7 @@ impl Module { | (ExternalKind::Table, ImportKind::Table(_)) | (ExternalKind::Memory, ImportKind::Memory(_)) | (ExternalKind::Global, ImportKind::Global(_)) + | (ExternalKind::Tag, ImportKind::Tag(_)) ) }) .count() @@ -175,6 +182,7 @@ impl Module { | (ExternalKind::Table, ImportKind::Table(_)) | (ExternalKind::Memory, ImportKind::Memory(_)) | (ExternalKind::Global, ImportKind::Global(_)) + | (ExternalKind::Tag, ImportKind::Tag(_)) ) }); let import = imports.nth(index)?; @@ -184,6 +192,7 @@ impl Module { ImportKind::Table(table_ty) => Some(ExportType::Table(table_ty)), ImportKind::Memory(memory_ty) => Some(ExportType::Memory(memory_ty)), ImportKind::Global(global_ty) => Some(ExportType::Global(global_ty)), + ImportKind::Tag(tag_ty) => Some(ExportType::Tag(module.types.get(tag_ty.type_idx)?.as_func()?)), } } @@ -223,6 +232,15 @@ impl Module { ExportType::Global(&self.0.globals.get(idx - imported_globals)?.ty) } } + ExternalKind::Tag => { + let imported_tags = imported_count(&self.0, ExternalKind::Tag); + if idx < imported_tags { + imported_type(&self.0, ExternalKind::Tag, idx)? + } else { + let tag_ty = self.0.tags.get(idx - imported_tags)?; + ExportType::Tag(self.0.types.get(tag_ty.type_idx)?.as_func()?) + } + } }; Some(ModuleExport { name: export.name.as_ref(), ty }) @@ -258,6 +276,8 @@ pub enum ImportType<'a> { Memory(&'a MemoryType), /// Imported global type. Global(&'a GlobalType), + /// Imported tag type. + Tag(&'a FuncType), } /// Exported entity type. @@ -270,6 +290,8 @@ pub enum ExportType<'a> { Memory(&'a MemoryType), /// Exported global type. Global(&'a GlobalType), + /// Exported tag type. + Tag(&'a FuncType), } /// How instantiation should prepare local memories declared by the module. @@ -301,6 +323,8 @@ pub enum ExternalKind { Memory, /// A WebAssembly Global. Global, + /// A WebAssembly Tag. + Tag, } /// A WebAssembly Address. @@ -315,6 +339,8 @@ pub type FuncAddr = Addr; pub type TableAddr = Addr; pub type MemAddr = Addr; pub type GlobalAddr = Addr; +pub type TagAddr = Addr; +pub type ExnAddr = Addr; pub type ElemAddr = Addr; pub type DataAddr = Addr; pub type ExternAddr = Addr; @@ -338,6 +364,7 @@ pub enum ExternVal { Table(TableAddr), Memory(MemAddr), Global(GlobalAddr), + Tag(TagAddr), } impl ExternVal { @@ -348,6 +375,7 @@ impl ExternVal { Self::Table(_) => ExternalKind::Table, Self::Memory(_) => ExternalKind::Memory, Self::Global(_) => ExternalKind::Global, + Self::Tag(_) => ExternalKind::Tag, } } @@ -358,6 +386,7 @@ impl ExternVal { ExternalKind::Table => Self::Table(addr), ExternalKind::Memory => Self::Memory(addr), ExternalKind::Global => Self::Global(addr), + ExternalKind::Tag => Self::Tag(addr), } } } @@ -444,6 +473,7 @@ pub struct WasmFunction { pub struct WasmFunctionData { pub v128_constants: Box<[[u8; 16]]>, pub branch_table_targets: Box<[u32]>, + pub exception_handlers: Box<[ExceptionHandler]>, } impl WasmFunctionData { @@ -638,6 +668,22 @@ pub enum MemoryArch { I64, } +/// A WebAssembly tag type. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct TagType { + /// The module-local function type index used by this tag. + pub type_idx: TypeAddr, +} + +impl TagType { + /// Creates a tag type from a module-local function type index. + pub const fn new(type_idx: TypeAddr) -> Self { + Self { type_idx } + } +} + #[derive(Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -655,6 +701,7 @@ pub enum ImportKind { Table(TableType), Memory(MemoryType), Global(GlobalType), + Tag(TagType), } impl From<&ImportKind> for ExternalKind { @@ -664,6 +711,7 @@ impl From<&ImportKind> for ExternalKind { ImportKind::Table(_) => Self::Table, ImportKind::Memory(_) => Self::Memory, ImportKind::Global(_) => Self::Global, + ImportKind::Tag(_) => Self::Tag, } } } -- cgit v1.3.1 From 666c7f59301acc9fcef10ac2da5beb464e57d665 Mon Sep 17 00:00:00 2001 From: Henry Date: Mon, 10 Aug 2026 15:22:56 +0200 Subject: chore: simplify runtime and clean up tests Signed-off-by: Henry --- crates/parser/src/conversion.rs | 48 ++++-- crates/parser/src/macros.rs | 2 +- crates/parser/src/module.rs | 17 +- crates/parser/src/visit.rs | 73 ++++++--- crates/tinywasm/Cargo.toml | 28 ---- crates/tinywasm/src/func/host.rs | 17 +- crates/tinywasm/src/imports.rs | 40 +++-- crates/tinywasm/src/interpreter/executor.rs | 5 +- crates/tinywasm/src/interpreter/simd/mod.rs | 2 - crates/tinywasm/src/interpreter/simd/tests.rs | 60 ------- .../tinywasm/src/interpreter/stack/value_stack.rs | 4 +- crates/tinywasm/src/interpreter/values.rs | 48 +----- crates/tinywasm/src/reference.rs | 2 +- crates/tinywasm/src/store/const_expr.rs | 120 +++++++++----- crates/tinywasm/src/store/gc/arena.rs | 15 ++ crates/tinywasm/src/store/gc/object.rs | 47 +++++- crates/tinywasm/src/store/global.rs | 28 +--- crates/tinywasm/src/store/memory/mod.rs | 182 --------------------- crates/tinywasm/src/store/memory/paged.rs | 45 ----- crates/tinywasm/src/store/mod.rs | 14 +- crates/tinywasm/src/store/state.rs | 25 +-- crates/tinywasm/src/store/table.rs | 55 +------ .../tinywasm/tests/generated/wasm-annotations.csv | 5 - .../tests/generated/wasm-extended-const.csv | 5 - .../tests/generated/wasm-function-references.csv | 3 - .../wasm-nontrapping-float-to-int-conversions.csv | 4 - .../tests/generated/wasm-reference-types.csv | 4 - .../tests/generated/wasm-sign-extension-ops.csv | 4 - crates/tinywasm/tests/generated/wasm-tail-call.csv | 4 - crates/tinywasm/tests/test-wasm-annotations.rs | 13 -- crates/tinywasm/tests/test-wasm-extended-const.rs | 13 -- .../tests/test-wasm-function-references.rs | 13 -- ...st-wasm-nontrapping-float-to-int-conversions.rs | 14 -- crates/tinywasm/tests/test-wasm-reference-types.rs | 13 -- .../tinywasm/tests/test-wasm-sign-extension-op.rs | 13 -- crates/tinywasm/tests/test-wasm-tail-call.rs | 14 -- .../tinywasm/tests/wasm-custom/table-basics.wast | 32 ++++ crates/types/src/instructions.rs | 5 +- 38 files changed, 329 insertions(+), 707 deletions(-) delete mode 100644 crates/tinywasm/src/interpreter/simd/tests.rs delete mode 100644 crates/tinywasm/tests/generated/wasm-annotations.csv delete mode 100644 crates/tinywasm/tests/generated/wasm-extended-const.csv delete mode 100644 crates/tinywasm/tests/generated/wasm-function-references.csv delete mode 100644 crates/tinywasm/tests/generated/wasm-nontrapping-float-to-int-conversions.csv delete mode 100644 crates/tinywasm/tests/generated/wasm-reference-types.csv delete mode 100644 crates/tinywasm/tests/generated/wasm-sign-extension-ops.csv delete mode 100644 crates/tinywasm/tests/generated/wasm-tail-call.csv delete mode 100644 crates/tinywasm/tests/test-wasm-annotations.rs delete mode 100644 crates/tinywasm/tests/test-wasm-extended-const.rs delete mode 100644 crates/tinywasm/tests/test-wasm-function-references.rs delete mode 100644 crates/tinywasm/tests/test-wasm-nontrapping-float-to-int-conversions.rs delete mode 100644 crates/tinywasm/tests/test-wasm-reference-types.rs delete mode 100644 crates/tinywasm/tests/test-wasm-sign-extension-op.rs delete mode 100644 crates/tinywasm/tests/test-wasm-tail-call.rs create mode 100644 crates/tinywasm/tests/wasm-custom/table-basics.wast (limited to 'crates/parser/src/conversion.rs') diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 7b52363..694c639 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -14,11 +14,14 @@ pub(crate) fn value_lane(ty: wasmparser::ValType) -> ValueLane { } } -pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result { +pub(crate) fn convert_module_element( + element: wasmparser::Element<'_>, + global_types: &[WasmType], +) -> Result { let kind = match element.kind { wasmparser::ElementKind::Active { table_index, offset_expr } => tinywasm_types::ElementKind::Active { table: table_index.unwrap_or(0), - offset: process_const_operators(offset_expr.get_operators_reader())?, + offset: process_const_operators(offset_expr.get_operators_reader(), global_types)?, }, wasmparser::ElementKind::Passive => tinywasm_types::ElementKind::Passive, wasmparser::ElementKind::Declared => tinywasm_types::ElementKind::Declared, @@ -38,7 +41,7 @@ pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result wasmparser::ElementItems::Expressions(ty, exprs) => { let items = exprs .into_iter() - .map(|expr| Ok(ElementItem::Expr(process_const_operators(expr?.get_operators_reader())?))) + .map(|expr| Ok(ElementItem::Expr(process_const_operators(expr?.get_operators_reader(), global_types)?))) .collect::>>()? .into_boxed_slice(); @@ -47,13 +50,16 @@ pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result } } -pub(crate) fn convert_module_data(data: wasmparser::Data<'_>) -> Result { +pub(crate) fn convert_module_data( + data: wasmparser::Data<'_>, + global_types: &[WasmType], +) -> Result { Ok(tinywasm_types::Data { data: data.data.to_vec().into_boxed_slice(), range: data.range, kind: match data.kind { wasmparser::DataKind::Active { memory_index, offset_expr } => { - let offset = process_const_operators(offset_expr.get_operators_reader())?; + let offset = process_const_operators(offset_expr.get_operators_reader(), global_types)?; tinywasm_types::DataKind::Active { mem: memory_index, offset } } wasmparser::DataKind::Passive => tinywasm_types::DataKind::Passive, @@ -96,16 +102,17 @@ pub(crate) fn convert_module_memory(memory: wasmparser::MemoryType) -> MemoryTyp pub(crate) fn convert_module_globals( globals: wasmparser::SectionLimited<'_, wasmparser::Global<'_>>, + global_types: &mut Vec, ) -> Result> { - globals - .into_iter() - .map(|global| { - let global = global?; - let ty = convert_valtype(&global.ty.content_type)?; - let ops = global.init_expr.get_operators_reader(); - Ok(Global { init: process_const_operators(ops)?, ty: GlobalType::new(ty, global.ty.mutable) }) - }) - .collect::>>() + let mut out = Vec::with_capacity(globals.count() as usize); + for global in globals { + let global = global?; + let ty = convert_valtype(&global.ty.content_type)?; + let init = process_const_operators(global.init_expr.get_operators_reader(), global_types)?; + global_types.push(ty); + out.push(Global { init, ty: GlobalType::new(ty, global.ty.mutable) }); + } + Ok(out.into_boxed_slice()) } pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result { @@ -313,7 +320,10 @@ fn convert_valtype_with_group(valtype: &wasmparser::ValType, group: Option<(u32, } } -pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result> { +pub(crate) fn process_const_operators( + ops: OperatorsReader<'_>, + global_types: &[WasmType], +) -> Result> { let mut out = Vec::new(); let mut operator_count = 0; let mut end_reached = false; @@ -353,7 +363,13 @@ pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result ConstInstruction::F32Const(f32::from_bits(value.bits())), wasmparser::Operator::F64Const { value } => ConstInstruction::F64Const(f64::from_bits(value.bits())), wasmparser::Operator::V128Const { value } => ConstInstruction::V128Const(*value.bytes()), - wasmparser::Operator::GlobalGet { global_index } => ConstInstruction::GlobalGet(global_index), + wasmparser::Operator::GlobalGet { global_index } => match global_types.get(global_index as usize) { + Some(WasmType::I32 | WasmType::F32) => ConstInstruction::GlobalGet32(global_index), + Some(WasmType::I64 | WasmType::F64) => ConstInstruction::GlobalGet64(global_index), + Some(WasmType::V128) => ConstInstruction::GlobalGet128(global_index), + Some(WasmType::Ref(_)) => ConstInstruction::GlobalGetRef(global_index), + None => return Err(crate::ParseError::Other(format!("global index out of bounds: {global_index}"))), + }, wasmparser::Operator::I32Add => ConstInstruction::I32Add, wasmparser::Operator::I32Sub => ConstInstruction::I32Sub, wasmparser::Operator::I32Mul => ConstInstruction::I32Mul, diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs index 98312ab..9fa7a01 100644 --- a/crates/parser/src/macros.rs +++ b/crates/parser/src/macros.rs @@ -89,7 +89,7 @@ pub(crate) mod visit { $visit:ident($type_index:ident: $type_ty:ty $(, $arg:ident: $arg_ty:ty)*) => $instr:ident ) => { fn $visit(&mut self, $type_index: $type_ty $(, $arg: $arg_ty)*) -> Self::Output { - let size = ModuleMetadata::storage_size(self.metadata.array_field($type_index)?.storage); + let size = self.metadata.array_field($type_index)?; lowering_ops!(@emit self address(size) [$($input),*] => [$($output),*] Instruction::$instr($type_index $(, $arg)*).into()) } diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index bbe2cf8..3d38ad6 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -64,6 +64,7 @@ pub(crate) struct ModuleReader<'a> { pub(crate) end_reached: bool, imported_func_count: usize, imported_memory_count: u32, + global_types: Vec, #[cfg(parallel_parser)] pending_functions: Option>>, @@ -148,7 +149,7 @@ impl<'a> ModuleReader<'a> { if let Some(validator) = validator.as_mut() { validator.global_section(&reader)?; } - self.globals = convert_module_globals(reader)?; + self.globals = convert_module_globals(reader, &mut self.global_types)?; } Payload::TableSection(reader) => { check_section("table", !self.tables.is_empty())?; @@ -168,7 +169,7 @@ impl<'a> ModuleReader<'a> { let init = match table.init { wasmparser::TableInit::RefNull => None, wasmparser::TableInit::Expr(expr) => { - Some(process_const_operators(expr.get_operators_reader())?) + Some(process_const_operators(expr.get_operators_reader(), &self.global_types)?) } }; tables.push(TableDefinition { ty, init }); @@ -209,8 +210,10 @@ impl<'a> ModuleReader<'a> { if let Some(validator) = validator.as_mut() { validator.element_section(&reader)?; } - self.elements = - reader.into_iter().map(|element| convert_module_element(element?)).collect::>()?; + self.elements = reader + .into_iter() + .map(|element| convert_module_element(element?, &self.global_types)) + .collect::>()?; } Payload::DataSection(reader) => { check_section("data", !self.data.is_empty())?; @@ -218,7 +221,10 @@ impl<'a> ModuleReader<'a> { if let Some(validator) = validator.as_mut() { validator.data_section(&reader)?; } - self.data = reader.into_iter().map(|data| convert_module_data(data?)).collect::>()?; + self.data = reader + .into_iter() + .map(|data| convert_module_data(data?, &self.global_types)) + .collect::>()?; } Payload::DataCountSection { count, range } => { debug!("Found data count section"); @@ -270,6 +276,7 @@ impl<'a> ModuleReader<'a> { self.imported_func_count += 1; } ImportKind::Memory(_) => self.imported_memory_count += 1, + ImportKind::Global(ty) => self.global_types.push(ty.ty), ImportKind::Tag(tag) => { let ty = self.types.get(tag.type_idx).and_then(SubType::as_func).ok_or_else(|| { ParseError::Other(format!( diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index c462d05..063bef4 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -3,11 +3,10 @@ use crate::{ conversion::{convert_heap_type, value_lane}, macros::visit::*, }; -use alloc::string::ToString; -use alloc::vec::Vec; +use alloc::{boxed::Box, string::ToString, vec::Vec}; use tinywasm_types::{ - Global, Import, ImportKind, Instruction, MemoryArg, MemoryType, StorageType, SubType, TableDefinition, TagType, - TypeSection, ValueCounts, ValueLane, WasmFunctionData, + Global, Import, ImportKind, Instruction, MemoryArg, MemoryType, StorageType, TableDefinition, TagType, TypeSection, + ValueCounts, ValueLane, WasmFunctionData, }; use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator}; @@ -50,7 +49,13 @@ pub(crate) struct ModuleMetadata { memories: Vec, tables: Vec, tags: Vec, - types: Vec, + aggregate_fields: Vec, +} + +enum AggregateFields { + Other, + Struct(Box<[ValueLane]>), + Array(ValueLane), } #[derive(Default)] @@ -109,7 +114,7 @@ impl<'a> FunctionBuilder<'a> { field_index: u32, instruction: fn(u32, u32) -> Instruction, ) -> Result<()> { - let size = ModuleMetadata::storage_size(self.metadata.struct_field(type_index, field_index)?.storage); + let size = self.metadata.struct_field(type_index, field_index)?; self.emit(&[ValueLane::S32], &[size], instruction(type_index, field_index)) } } @@ -170,6 +175,19 @@ impl ModuleMetadata { }) }) .collect(); + let aggregate_fields = types + .types + .iter() + .map(|ty| { + if let Some(ty) = ty.as_struct() { + AggregateFields::Struct(ty.fields.iter().map(|field| Self::storage_size(field.storage)).collect()) + } else if let Some(ty) = ty.as_array() { + AggregateFields::Array(Self::storage_size(ty.field.storage)) + } else { + AggregateFields::Other + } + }) + .collect(); Self { signatures, functions, @@ -177,7 +195,7 @@ impl ModuleMetadata { memories: memory_sizes, tables: table_sizes, tags: tag_types, - types: types.types.to_vec(), + aggregate_fields, } } @@ -230,26 +248,30 @@ impl ModuleMetadata { } } - fn struct_fields(&self, idx: u32) -> Result<&[tinywasm_types::FieldType]> { - self.types + fn struct_fields(&self, idx: u32) -> Result<&[ValueLane]> { + self.aggregate_fields .get(idx as usize) - .and_then(SubType::as_struct) - .map(|ty| ty.fields.as_ref()) + .and_then(|fields| match fields { + AggregateFields::Struct(fields) => Some(fields.as_ref()), + AggregateFields::Other | AggregateFields::Array(_) => None, + }) .ok_or_else(|| crate::ParseError::Other(alloc::format!("type index is not a struct type: {idx}"))) } - fn struct_field(&self, type_index: u32, field_index: u32) -> Result { + fn struct_field(&self, type_index: u32, field_index: u32) -> Result { self.struct_fields(type_index)? .get(field_index as usize) .copied() .ok_or_else(|| crate::ParseError::Other("struct field index out of bounds".into())) } - fn array_field(&self, idx: u32) -> Result { - self.types + fn array_field(&self, idx: u32) -> Result { + self.aggregate_fields .get(idx as usize) - .and_then(SubType::as_array) - .map(|ty| ty.field) + .and_then(|fields| match fields { + AggregateFields::Array(field) => Some(*field), + AggregateFields::Other | AggregateFields::Struct(_) => None, + }) .ok_or_else(|| crate::ParseError::Other(alloc::format!("type index is not an array type: {idx}"))) } } @@ -490,13 +512,14 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_struct_new(&mut self, type_index: u32) -> Self::Output { - let inputs = self - .metadata - .struct_fields(type_index)? - .iter() - .map(|field| ModuleMetadata::storage_size(field.storage)) - .collect::>(); - self.emit(&inputs, &[ValueLane::S32], Instruction::StructNew(type_index)) + let field_count = self.metadata.struct_fields(type_index)?.len(); + for field_index in (0..field_count).rev() { + let size = self.metadata.struct_field(type_index, field_index as u32)?; + self.pop_expect(size)?; + } + self.push_sizes(&[ValueLane::S32])?; + self.instructions.push(Instruction::StructNew(type_index)); + Ok(()) } fn visit_struct_get(&mut self, type_index: u32, field_index: u32) -> Self::Output { @@ -512,12 +535,12 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Self::Output { - let size = ModuleMetadata::storage_size(self.metadata.struct_field(type_index, field_index)?.storage); + let size = self.metadata.struct_field(type_index, field_index)?; self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(type_index, field_index)) } fn visit_array_new_fixed(&mut self, type_index: u32, array_size: u32) -> Self::Output { - let size = ModuleMetadata::storage_size(self.metadata.array_field(type_index)?.storage); + let size = self.metadata.array_field(type_index)?; for _ in 0..array_size { self.pop_expect(size)?; } diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml index 67d0742..65ef7f8 100644 --- a/crates/tinywasm/Cargo.toml +++ b/crates/tinywasm/Cargo.toml @@ -52,10 +52,6 @@ harness = false name = "test-wasm-threads" test = false -[[test]] -harness = false -name = "test-wasm-annotations" - [[test]] harness = false name = "test-wast" @@ -65,10 +61,6 @@ test = false harness = false name = "test-wasm-custom-page-sizes" -[[test]] -harness = false -name = "test-wasm-function-references" - [[test]] harness = false name = "test-wasm-custom" @@ -77,18 +69,10 @@ name = "test-wasm-custom" harness = false name = "test-wasm-gc" -[[test]] -harness = false -name = "test-wasm-tail-call" - [[test]] harness = false name = "test-wasm-memory64" -[[test]] -harness = false -name = "test-wasm-extended-const" - [[test]] harness = false name = "test-wasm-relaxed-simd" @@ -101,18 +85,6 @@ name = "test-wasm-simd" harness = false name = "test-wasm-wide-arithmetic" -[[test]] -harness = false -name = "test-wasm-sign-extension-op" - -[[test]] -harness = false -name = "test-wasm-nontrapping-float-to-int-conversions" - -[[test]] -harness = false -name = "test-wasm-reference-types" - [[bench]] harness = false name = "argon2id" diff --git a/crates/tinywasm/src/func/host.rs b/crates/tinywasm/src/func/host.rs index 83b17f9..5335444 100644 --- a/crates/tinywasm/src/func/host.rs +++ b/crates/tinywasm/src/func/host.rs @@ -9,8 +9,8 @@ use crate::{Function, FunctionInstance, Result, Store}; pub struct HostFunction(Arc); impl HostFunction { - fn instantiate_canonical(&self, store: &mut Store, ty: &FuncType) -> Function { - let type_addr = store.register_host_type(ty); + /// Instantiates the function with an already registered canonical type. + pub(crate) fn instantiate_registered(&self, store: &mut Store, type_addr: TypeAddr) -> Function { let addr = store.add_func(FunctionInstance { type_addr, gc: store.state.func_gc_metadata(type_addr), @@ -19,8 +19,12 @@ impl HostFunction { Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 } } - /// Instantiates this definition after resolving the importing module's types. - pub(crate) fn instantiate_for_import(&self, store: &mut Store, type_addrs: &[TypeAddr]) -> Result { + /// Resolves the importing module's types without allocating a function instance. + pub(crate) fn resolve_import_type(&self, type_addrs: &[TypeAddr]) -> Result { + let mut types = self.0.ty.params().iter().chain(self.0.ty.results()); + if types.all(|ty| !matches!(ty, WasmType::Ref(ty) if ty.is_concrete())) { + return Ok(self.0.ty.clone()); + } let resolve = |ty: WasmType| -> Result { let WasmType::Ref(ref_ty) = ty else { return Ok(ty) }; let Some(module_addr) = ref_ty.type_index() else { return Ok(ty) }; @@ -34,7 +38,7 @@ impl HostFunction { }; let params = self.0.ty.params().iter().copied().map(resolve).collect::>>()?; let results = self.0.ty.results().iter().copied().map(resolve).collect::>>()?; - Ok(self.instantiate_canonical(store, &FuncType::new(¶ms, &results))) + Ok(FuncType::new(¶ms, &results)) } /// Calls the host function through its untyped value interface. @@ -111,7 +115,8 @@ impl HostFunction { { return Err(crate::Error::other("host function signature contains a concrete type from another store")); } - Ok(self.instantiate_canonical(store, &self.0.ty)) + let type_addr = store.register_host_type(&self.0.ty); + Ok(self.instantiate_registered(store, type_addr)) } /// Create a new untyped host function. diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs index 8232a90..b8de4e0 100644 --- a/crates/tinywasm/src/imports.rs +++ b/crates/tinywasm/src/imports.rs @@ -168,8 +168,9 @@ impl Imports { self } - pub(crate) fn take_defined(&self, import: &Import) -> Option { - self.externs.get(import.module.as_ref())?.get(import.name.as_ref()).cloned() + /// Returns an explicitly defined import without cloning its handle. + pub(crate) fn defined(&self, import: &Import) -> Option<&Extern> { + self.externs.get(import.module.as_ref())?.get(import.name.as_ref()) } fn compare_types(import: &Import, actual: &T, expected: &T) -> Result<()> { @@ -247,27 +248,43 @@ impl Imports { }; for import in &*module.imports { - let (val, func_handle) = if let Some(defined) = self.take_defined(import) { + let val = if let Some(defined) = self.defined(import) { match defined { Extern::Global(global) => { global.0.validate_store(store)?; - (ExternVal::Global(global.0.addr), None) + ExternVal::Global(global.0.addr) } Extern::Table(table) => { table.0.validate_store(store)?; - (ExternVal::Table(table.0.addr), None) + ExternVal::Table(table.0.addr) } Extern::Memory(memory) => { memory.0.validate_store(store)?; - (ExternVal::Memory(memory.0.addr), None) + ExternVal::Memory(memory.0.addr) + } + Extern::Function(func) => { + func.item.validate_store(store)?; + ExternVal::Func(func.addr()) } - Extern::Function(func) => (ExternVal::Func(func.addr()), Some(func)), Extern::HostFunction(func) => { - (ExternVal::Func(func.instantiate_for_import(store, type_addrs)?.addr()), None) + let ImportKind::Function(type_idx) = import.kind else { + cold_path(); + return Err(LinkingError::incompatible_import_type(import).into()); + }; + let expected_type_addr = type_addrs + .get(type_idx as usize) + .ok_or_else(|| LinkingError::incompatible_import_type(import))?; + let actual_ty = func.resolve_import_type(type_addrs)?; + let actual_type_addr = store.register_host_type(&actual_ty); + if !store.state.type_addr_is_subtype(actual_type_addr, *expected_type_addr) { + cold_path(); + return Err(LinkingError::incompatible_import_type(import).into()); + } + ExternVal::Func(func.instantiate_registered(store, actual_type_addr).addr()) } Extern::Tag(tag) => { tag.0.validate_store(store)?; - (ExternVal::Tag(tag.0.addr), None) + ExternVal::Tag(tag.0.addr) } } } else { @@ -276,7 +293,7 @@ impl Imports { return Err(LinkingError::unknown_import(import).into()); }; instance.validate_store(store)?; - (instance.export_addr(&import.name).ok_or_else(|| LinkingError::unknown_import(import))?, None) + instance.export_addr(&import.name).ok_or_else(|| LinkingError::unknown_import(import))? }; if val.kind() != (&import.kind).into() { @@ -317,9 +334,6 @@ impl Imports { (ExternVal::Func(func_addr), ImportKind::Function(ty)) => { let expected_type_addr = type_addrs.get(*ty as usize).ok_or_else(|| LinkingError::incompatible_import_type(import))?; - if let Some(func) = &func_handle { - func.item.validate_store(store)?; - } if !store.state.type_addr_is_subtype(store.state.get_func(func_addr).type_addr, *expected_type_addr) { cold_path(); diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 22c8441..d9d00eb 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -1673,10 +1673,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.store.state.gc.copy_within(dst, src_index..src_end, dst_index).expect("live array range"); return Ok(()); } - let mut values = Vec::new(); - values.try_reserve_exact(len).map_err(|_| Trap::OutOfMemory)?; - values.extend_from_slice(&src_object.values[src_index..src_end]); - self.store.state.gc.set_slice(dst, dst_index, &values).expect("live array range"); + self.store.state.gc.copy_between(src, src_index..src_end, dst, dst_index).expect("live array ranges"); Ok(()) } diff --git a/crates/tinywasm/src/interpreter/simd/mod.rs b/crates/tinywasm/src/interpreter/simd/mod.rs index d54268f..406c0c7 100644 --- a/crates/tinywasm/src/interpreter/simd/mod.rs +++ b/crates/tinywasm/src/interpreter/simd/mod.rs @@ -3,8 +3,6 @@ #[macro_use] mod macros; mod instructions; -#[cfg(test)] -mod tests; mod utils; #[cfg(target_arch = "wasm32")] diff --git a/crates/tinywasm/src/interpreter/simd/tests.rs b/crates/tinywasm/src/interpreter/simd/tests.rs deleted file mode 100644 index 7400f6b..0000000 --- a/crates/tinywasm/src/interpreter/simd/tests.rs +++ /dev/null @@ -1,60 +0,0 @@ -use super::Value128; - -fn ref_swizzle(a: [u8; 16], idx: [u8; 16]) -> [u8; 16] { - let mut out = [0u8; 16]; - for i in 0..16 { - let j = idx[i]; - out[i] = if j < 16 { a[(j & 0x0f) as usize] } else { 0 }; - } - out -} - -fn ref_shuffle(a: [u8; 16], b: [u8; 16], idx: [u8; 16]) -> [u8; 16] { - let mut out = [0u8; 16]; - for i in 0..16 { - let j = idx[i] & 31; - out[i] = if j < 16 { a[j as usize] } else { b[(j & 0x0f) as usize] }; - } - out -} - -#[test] -fn swizzle_matches_reference() { - let a = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]; - - for seed in 0u32..512 { - let mut s = [0u8; 16]; - let mut x = seed.wrapping_mul(0x9e37_79b9).wrapping_add(0x7f4a_7c15); - for byte in &mut s { - x ^= x << 13; - x ^= x >> 17; - x ^= x << 5; - *byte = (x & 0xff) as u8; - } - - let got = Value128(a).i8x16_swizzle(Value128(s)); - let expected = ref_swizzle(a, s).into(); - assert_eq!(got, expected, "seed={seed}"); - } -} - -#[test] -fn shuffle_matches_reference() { - let a = [0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f]; - let b = [0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf]; - - for seed in 0u32..512 { - let mut idx = [0u8; 16]; - let mut x = seed.wrapping_mul(0x85eb_ca6b).wrapping_add(0xc2b2_ae35); - for byte in &mut idx { - x ^= x << 13; - x ^= x >> 17; - x ^= x << 5; - *byte = (x & 0xff) as u8; - } - - let got = Value128::i8x16_shuffle(Value128(a), Value128(b), Value128(idx)); - let expected = ref_shuffle(a, b, idx).into(); - assert_eq!(got, expected, "seed={seed}"); - } -} diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index 1824d20..ceea9eb 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -375,9 +375,7 @@ impl ValueStack { WasmValue::I64(v) => self.stack_64.push(v as u64)?, WasmValue::F32(v) => self.stack_32.push(v.to_bits())?, WasmValue::F64(v) => self.stack_64.push(v.to_bits())?, - WasmValue::Ref(v) => { - self.stack_32.push(TinyWasmValue::from(WasmValue::Ref(v)).as_ref().unwrap().raw())? - } + WasmValue::Ref(v) => self.stack_32.push(ValueRef::from(v).raw())?, WasmValue::V128(v) => self.stack_128.push(v.into())?, } } diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs index 6913605..b3382e8 100644 --- a/crates/tinywasm/src/interpreter/values.rs +++ b/crates/tinywasm/src/interpreter/values.rs @@ -87,55 +87,19 @@ impl From for ValueRef { } } -#[allow(private_interfaces)] #[derive(Debug, Clone, Copy, PartialEq, Eq)] -/// A untyped WebAssembly value -pub enum TinyWasmValue { - /// A 32-bit value +/// An untyped internal WebAssembly value. +pub(crate) enum TinyWasmValue { + /// A 32-bit value. Value32(Value32), - /// A 64-bit value + /// A 64-bit value. Value64(Value64), - /// A 128-bit value + /// A 128-bit value. Value128(Value128), - /// A reference value + /// A reference value. ValueRef(ValueRef), } -impl TinyWasmValue { - /// Converts the value to a 32-bit value (returns None if the value is not a 32-bit value) - pub fn as_32(self) -> Option { - match self { - Self::Value32(v) => Some(v), - _ => None, - } - } - - /// Converts the value to a 64-bit value (returns None if the value is not a 64-bit value) - pub fn as_64(self) -> Option { - match self { - Self::Value64(v) => Some(v), - _ => None, - } - } - - /// Converts the value to a 128-bit value (returns None if the value is not a 128-bit value) - pub fn as_128(self) -> Option { - match self { - Self::Value128(v) => Some(v), - _ => None, - } - } - - /// Converts the value to a reference value (returns None if the value is not a reference value) - #[allow(private_interfaces, dead_code)] - pub fn as_ref(self) -> Option { - match self { - Self::ValueRef(v) => Some(v), - _ => None, - } - } -} - impl From<&WasmValue> for TinyWasmValue { fn from(value: &WasmValue) -> Self { match value { diff --git a/crates/tinywasm/src/reference.rs b/crates/tinywasm/src/reference.rs index 55f9e3b..dd31efa 100644 --- a/crates/tinywasm/src/reference.rs +++ b/crates/tinywasm/src/reference.rs @@ -369,7 +369,7 @@ impl Table { } let init = table_value_to_element(&store.state, ty.element_type, init).map_err(Error::from)?; let addr = store.state.tables.len() as TableAddr; - store.state.tables.push(TableInstance::new_with_init(ty, init)?); + store.state.tables.push(TableInstance::new(ty, init)?); Ok(Self(StoreItem::new(store.id(), addr))) } diff --git a/crates/tinywasm/src/store/const_expr.rs b/crates/tinywasm/src/store/const_expr.rs index 201a1e1..c371763 100644 --- a/crates/tinywasm/src/store/const_expr.rs +++ b/crates/tinywasm/src/store/const_expr.rs @@ -6,6 +6,42 @@ use super::{State, default_value}; use crate::interpreter::{TinyWasmValue, ValueRef}; use crate::{Error, Result, Trap}; +fn resolve(items: &[T], index: u32, kind: &str) -> Result { + items.get(index as usize).copied().ok_or_else(|| Error::Other(format!("{kind} {index} not found"))) +} + +fn pop_value(stack: &mut Vec, storage: StorageType) -> Result { + let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; + match (storage, value) { + (StorageType::I8, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u8 as u32)), + (StorageType::I16, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u16 as u32)), + (StorageType::Value(WasmType::I32 | WasmType::F32), value @ TinyWasmValue::Value32(_)) + | (StorageType::Value(WasmType::I64 | WasmType::F64), value @ TinyWasmValue::Value64(_)) + | (StorageType::Value(WasmType::V128), value @ TinyWasmValue::Value128(_)) + | (StorageType::Value(WasmType::Ref(_)), value @ TinyWasmValue::ValueRef(_)) => Ok(value), + _ => Err(Error::other("type mismatch in GC constant")), + } +} + +fn value_ref(value: &TinyWasmValue) -> Option { + match value { + TinyWasmValue::ValueRef(value) => Some(*value), + _ => None, + } +} + +fn alloc_object( + state: &mut State, + stack: &mut Vec, + type_addr: TypeAddr, + values: Vec, +) -> Result<()> { + let roots = stack.iter().filter_map(value_ref).map(ValueRef::raw); + let reference = state.alloc_gc_object(type_addr, values, roots)?; + stack.push(TinyWasmValue::ValueRef(reference)); + Ok(()) +} + #[inline] pub(super) fn eval_const( state: &mut State, @@ -16,32 +52,6 @@ pub(super) fn eval_const( ) -> Result { use ConstInstruction::*; - let global_value = |state: &State, index: u32| -> Result { - let addr = - *global_addrs.get(index as usize).ok_or_else(|| Error::Other(format!("global {index} not found")))?; - Ok(state.globals.get(addr)) - }; - let func_ref = |index: u32| -> Result { - let addr = - *func_addrs.get(index as usize).ok_or_else(|| Error::Other(format!("function {index} not found")))?; - Ok(ValueRef::from_category_addr(addr)) - }; - let type_addr = |index: TypeAddr| -> Result { - type_addrs.get(index as usize).copied().ok_or_else(|| Error::other("GC constant type not found")) - }; - let pop_value = |stack: &mut Vec, storage: StorageType| -> Result { - let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; - match (storage, value) { - (StorageType::I8, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u8 as u32)), - (StorageType::I16, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u16 as u32)), - (StorageType::Value(WasmType::I32 | WasmType::F32), value @ TinyWasmValue::Value32(_)) - | (StorageType::Value(WasmType::I64 | WasmType::F64), value @ TinyWasmValue::Value64(_)) - | (StorageType::Value(WasmType::V128), value @ TinyWasmValue::Value128(_)) - | (StorageType::Value(WasmType::Ref(_)), value @ TinyWasmValue::ValueRef(_)) => Ok(value), - _ => Err(Error::other("type mismatch in GC constant")), - } - }; - if let [instruction] = instructions { match instruction { I32Const(value) => return Ok(TinyWasmValue::Value32(*value as u32)), @@ -49,9 +59,24 @@ pub(super) fn eval_const( F32Const(value) => return Ok(TinyWasmValue::Value32(value.to_bits())), F64Const(value) => return Ok(TinyWasmValue::Value64(value.to_bits())), V128Const(value) => return Ok(TinyWasmValue::Value128((*value).into())), - GlobalGet(index) => return global_value(state, *index), + GlobalGet32(index) => { + return Ok(TinyWasmValue::Value32(state.globals.get_32(resolve(global_addrs, *index, "global")?))); + } + GlobalGet64(index) => { + return Ok(TinyWasmValue::Value64(state.globals.get_64(resolve(global_addrs, *index, "global")?))); + } + GlobalGet128(index) => { + return Ok(TinyWasmValue::Value128(state.globals.get_128(resolve(global_addrs, *index, "global")?))); + } + GlobalGetRef(index) => { + let value = state.globals.get_32(resolve(global_addrs, *index, "global")?); + return Ok(TinyWasmValue::ValueRef(ValueRef::from_raw(value))); + } Ref(RefValue::Null) => return Ok(TinyWasmValue::ValueRef(ValueRef::NULL)), - Ref(RefValue::Func(func)) => return Ok(TinyWasmValue::ValueRef(func_ref(func.addr())?)), + Ref(RefValue::Func(func)) => { + let addr = resolve(func_addrs, func.addr(), "function")?; + return Ok(TinyWasmValue::ValueRef(ValueRef::from_category_addr(addr))); + } _ => {} } } @@ -64,9 +89,24 @@ pub(super) fn eval_const( F32Const(value) => stack.push(TinyWasmValue::Value32(value.to_bits())), F64Const(value) => stack.push(TinyWasmValue::Value64(value.to_bits())), V128Const(value) => stack.push(TinyWasmValue::Value128((*value).into())), - GlobalGet(index) => stack.push(global_value(state, *index)?), + GlobalGet32(index) => { + stack.push(TinyWasmValue::Value32(state.globals.get_32(resolve(global_addrs, *index, "global")?))); + } + GlobalGet64(index) => { + stack.push(TinyWasmValue::Value64(state.globals.get_64(resolve(global_addrs, *index, "global")?))); + } + GlobalGet128(index) => { + stack.push(TinyWasmValue::Value128(state.globals.get_128(resolve(global_addrs, *index, "global")?))); + } + GlobalGetRef(index) => { + let value = state.globals.get_32(resolve(global_addrs, *index, "global")?); + stack.push(TinyWasmValue::ValueRef(ValueRef::from_raw(value))); + } Ref(RefValue::Null) => stack.push(TinyWasmValue::ValueRef(ValueRef::NULL)), - Ref(RefValue::Func(func)) => stack.push(TinyWasmValue::ValueRef(func_ref(func.addr())?)), + Ref(RefValue::Func(func)) => { + let addr = resolve(func_addrs, func.addr(), "function")?; + stack.push(TinyWasmValue::ValueRef(ValueRef::from_category_addr(addr))); + } Ref(_) => { cold_path(); return Err(Error::other("unsupported reference constant")); @@ -86,13 +126,13 @@ pub(super) fn eval_const( stack.push(value); } StructNew(type_index) | StructNewDefault(type_index) => { - let type_addr = type_addr(*type_index)?; + let type_addr = resolve(type_addrs, *type_index, "type")?; let fields = state .get_type(type_addr) .as_struct() .ok_or_else(|| Error::other("GC constant type is not a struct"))? .fields - .clone(); + .as_ref(); let default = matches!(instruction, StructNewDefault(_)); let mut values = Vec::new(); values.try_reserve_exact(fields.len()).map_err(|_| Trap::OutOfMemory)?; @@ -104,12 +144,10 @@ pub(super) fn eval_const( } values.reverse(); } - let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw); - let reference = state.alloc_gc_object(type_addr, values, roots)?; - stack.push(TinyWasmValue::ValueRef(reference)); + alloc_object(state, &mut stack, type_addr, values)?; } ArrayNew(type_index) | ArrayNewDefault(type_index) => { - let type_addr = type_addr(*type_index)?; + let type_addr = resolve(type_addrs, *type_index, "type")?; let storage = state .get_type(type_addr) .as_array() @@ -127,12 +165,10 @@ pub(super) fn eval_const( let mut values = Vec::new(); values.try_reserve_exact(len as usize).map_err(|_| Trap::OutOfMemory)?; values.resize(len as usize, value); - let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw); - let reference = state.alloc_gc_object(type_addr, values, roots)?; - stack.push(TinyWasmValue::ValueRef(reference)); + alloc_object(state, &mut stack, type_addr, values)?; } ArrayNewFixed(type_index, len) => { - let type_addr = type_addr(*type_index)?; + let type_addr = resolve(type_addrs, *type_index, "type")?; let storage = state .get_type(type_addr) .as_array() @@ -145,9 +181,7 @@ pub(super) fn eval_const( values.push(pop_value(&mut stack, storage)?); } values.reverse(); - let roots = stack.iter().filter_map(|value| value.as_ref()).map(ValueRef::raw); - let reference = state.alloc_gc_object(type_addr, values, roots)?; - stack.push(TinyWasmValue::ValueRef(reference)); + alloc_object(state, &mut stack, type_addr, values)?; } I32Add | I32Sub | I32Mul => { let rhs = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; diff --git a/crates/tinywasm/src/store/gc/arena.rs b/crates/tinywasm/src/store/gc/arena.rs index b8f5961..6238466 100644 --- a/crates/tinywasm/src/store/gc/arena.rs +++ b/crates/tinywasm/src/store/gc/arena.rs @@ -139,6 +139,21 @@ impl Arena { } } + /// Returns exclusive references for two distinct live handles. + pub(crate) fn get_disjoint_mut(&mut self, first: Handle, second: Handle) -> Option<(&mut T, &mut T)> { + let [first_slot, second_slot] = + self.slots.get_disjoint_mut([first.index as usize, second.index as usize]).ok()?; + if first_slot.generation != first.generation || second_slot.generation != second.generation { + return None; + } + match (&mut first_slot.state, &mut second_slot.state) { + (SlotState::Occupied { value: first, .. }, SlotState::Occupied { value: second, .. }) => { + Some((first, second)) + } + _ => None, + } + } + /// Returns whether an allocation of this size should trigger collection. pub(crate) fn should_collect(&self, out_of_line_bytes: usize) -> bool { size_of::>() diff --git a/crates/tinywasm/src/store/gc/object.rs b/crates/tinywasm/src/store/gc/object.rs index a3c5440..4af64c9 100644 --- a/crates/tinywasm/src/store/gc/object.rs +++ b/crates/tinywasm/src/store/gc/object.rs @@ -94,7 +94,10 @@ impl GcHeap { } pub(crate) fn set(&mut self, object: ValueRef, index: usize, value: TinyWasmValue) -> Option<()> { - let reference = value.as_ref().and_then(|value| self.handle(value)); + let reference = match value { + TinyWasmValue::ValueRef(value) => self.handle(value), + _ => None, + }; let object = self.get_mut(object)?; *object.values.get_mut(index)? = value; if let Some(references) = &mut object.references { @@ -112,11 +115,14 @@ impl GcHeap { object.values.get_mut(index..end)?.copy_from_slice(values); if let Some(references) = &mut object.references { for (reference, value) in references[index..end].iter_mut().zip(values) { - *reference = value.as_ref().and_then(|value| { - let key = value.addr()?; - let index = directory.binary_search_by_key(&key, |entry| entry.0).ok()?; - Some(directory[index].1) - }); + *reference = match value { + TinyWasmValue::ValueRef(value) => { + let key = value.addr(); + key.and_then(|key| directory.binary_search_by_key(&key, |entry| entry.0).ok()) + .map(|index| directory[index].1) + } + _ => None, + }; } } Some(()) @@ -129,7 +135,10 @@ impl GcHeap { range: core::ops::Range, value: TinyWasmValue, ) -> Option<()> { - let reference = value.as_ref().and_then(|value| self.handle(value)); + let reference = match value { + TinyWasmValue::ValueRef(value) => self.handle(value), + _ => None, + }; let object = self.get_mut(object)?; object.values.get_mut(range.clone())?.fill(value); if let Some(references) = &mut object.references { @@ -176,6 +185,30 @@ impl GcHeap { } Some(()) } + + /// Copies values and tracing metadata between two distinct objects. + pub(crate) fn copy_between( + &mut self, + src: ValueRef, + src_range: core::ops::Range, + dst: ValueRef, + dst_index: usize, + ) -> Option<()> { + let src = self.handle(src)?; + let dst = self.handle(dst)?; + let (src, dst) = self.objects.get_disjoint_mut(src, dst)?; + let src_values = src.values.get(src_range.clone())?; + let dst_end = dst_index.checked_add(src_values.len())?; + dst.values.get_mut(dst_index..dst_end)?.copy_from_slice(src_values); + if let Some(dst_refs) = &mut dst.references { + if let Some(src_refs) = &src.references { + dst_refs[dst_index..dst_end].copy_from_slice(&src_refs[src_range]); + } else { + dst_refs[dst_index..dst_end].fill(None); + } + } + Some(()) + } } #[cfg(test)] diff --git a/crates/tinywasm/src/store/global.rs b/crates/tinywasm/src/store/global.rs index 638b01d..69e538f 100644 --- a/crates/tinywasm/src/store/global.rs +++ b/crates/tinywasm/src/store/global.rs @@ -1,7 +1,7 @@ use alloc::vec::Vec; use tinywasm_types::*; -use crate::interpreter::{TinyWasmValue, Value32, Value64, Value128, ValueRef}; +use crate::interpreter::{TinyWasmValue, Value32, Value64, Value128}; struct GlobalLane { values: Vec, @@ -116,28 +116,6 @@ impl Globals { } } - /// Returns a dynamically represented global value. - pub(crate) fn get(&self, addr: GlobalAddr) -> TinyWasmValue { - let ty = self.ty(addr); - match ty.ty { - WasmType::I32 | WasmType::F32 => TinyWasmValue::Value32(self.get_32(addr)), - WasmType::I64 | WasmType::F64 => TinyWasmValue::Value64(self.get_64(addr)), - WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::from_raw(self.get_32(addr))), - WasmType::V128 => TinyWasmValue::Value128(self.get_128(addr)), - } - } - - /// Sets a global from a dynamically represented value. - pub(crate) fn set(&mut self, addr: GlobalAddr, value: TinyWasmValue) { - match (self.ty(addr).ty, value) { - (WasmType::I32 | WasmType::F32, TinyWasmValue::Value32(value)) => self.set_32(addr, value), - (WasmType::Ref(_), TinyWasmValue::ValueRef(value)) => self.set_32(addr, value.raw()), - (WasmType::I64 | WasmType::F64, TinyWasmValue::Value64(value)) => self.set_64(addr, value), - (WasmType::V128, TinyWasmValue::Value128(value)) => self.set_128(addr, value), - _ => unreachable!("global value does not match its declared type"), - } - } - /// Returns a raw value from the 32-bit lane. #[inline(always)] pub(crate) fn get_32(&self, addr: GlobalAddr) -> Value32 { @@ -175,7 +153,7 @@ impl Globals { } /// Iterates over globals in the 32-bit lane for root tracing. - pub(crate) fn globals_32(&self) -> impl Iterator + '_ { - self.globals_32.values.iter().copied().zip(self.globals_32.types.iter().copied()) + pub(crate) fn globals_32(&self) -> impl Iterator { + self.globals_32.values.iter().zip(&self.globals_32.types) } } diff --git a/crates/tinywasm/src/store/memory/mod.rs b/crates/tinywasm/src/store/memory/mod.rs index 5805c86..f25d4ae 100644 --- a/crates/tinywasm/src/store/memory/mod.rs +++ b/crates/tinywasm/src/store/memory/mod.rs @@ -436,185 +436,3 @@ impl MemValue<16> for Value128 { const fn memory_oob(offset: usize, len: usize, max: usize) -> crate::Trap { crate::Trap::MemoryOutOfBounds { offset, len, max } } - -#[cfg(test)] -mod tests { - use super::*; - use tinywasm_types::MemoryArch; - - fn create_test_memory(kind: MemoryType, backend: MemoryBackend) -> MemoryInstance { - MemoryInstance::new(kind, &backend).unwrap() - } - - fn test_backends() -> [MemoryBackend; 2] { - [MemoryBackend::vec(), MemoryBackend::paged(4)] - } - - #[test] - fn effective_memory_addresses_handle_host_and_wasm_overflow() { - let memory = create_test_memory(MemoryType::new(MemoryArch::I32, 1, Some(1), None), MemoryBackend::vec()); - assert_eq!(memory.effective_addr_32::<1>(1, 2), Ok(3)); - assert_eq!(memory.effective_addr_64::<1>(1, 2), Ok(3)); - assert!(memory.effective_addr_64::<1>(u64::MAX, 1).is_err()); - - #[cfg(target_pointer_width = "64")] - assert_eq!( - memory.effective_addr_32::<1>(u32::MAX, u64::from(u32::MAX)), - Ok(usize::try_from(u64::from(u32::MAX) * 2).unwrap()) - ); - - #[cfg(target_pointer_width = "32")] - assert!(memory.effective_addr_32::<1>(u32::MAX, 1).is_err()); - } - - #[test] - fn memory_copy_from_slice_and_read_vec_work() { - for backend in test_backends() { - let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None); - let mut memory = create_test_memory(kind, backend); - let data = [1, 2, 3, 4]; - assert!(memory.inner.write_all(0, &data).is_some()); - assert_eq!(memory.inner.read_vec(0, data.len()).unwrap(), data); - } - } - - #[test] - fn memory_read_returns_partial_count() { - for backend in test_backends() { - let kind = MemoryType::new(MemoryArch::I32, 1, Some(1), Some(4)); - let memory = create_test_memory(kind, backend); - let mut dst = [9; 8]; - assert_eq!(memory.inner.read(2, &mut dst), 2); - assert_eq!(&dst[..2], &[0, 0]); - assert_eq!(&dst[2..], &[9; 6]); - } - } - - #[test] - fn memory_copy_from_slice_out_of_bounds_fails() { - for backend in test_backends() { - let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None); - let mut memory = create_test_memory(kind, backend); - let data = [1, 2, 3, 4]; - let len = memory.inner.len(); - assert!(memory.inner.write_all(len, &data).is_none()); - } - } - - #[test] - fn fixed_width_access_out_of_bounds_traps() { - for backend in test_backends() { - let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None); - let mut memory = create_test_memory(kind, backend); - let len = memory.inner.len(); - - assert!(memory.inner.read_8(len).is_err()); - assert!(memory.inner.read_32(len - 3).is_err()); - assert!(memory.inner.write_8(len, &[0]).is_err()); - assert!(memory.inner.write_32(len - 3, &[0; 4]).is_err()); - } - } - - #[test] - fn memory_fill_works() { - for backend in test_backends() { - let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None); - let mut memory = create_test_memory(kind, backend); - assert!(memory.inner.fill(0, 10, 42).is_some()); - assert_eq!(memory.inner.read_vec(0, 10).unwrap(), vec![42; 10]); - } - } - - #[test] - fn memory_fill_out_of_bounds_fails() { - for backend in test_backends() { - let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None); - let mut memory = create_test_memory(kind, backend); - let len = memory.inner.len(); - assert!(memory.inner.fill(len, 10, 42).is_none()); - } - } - - #[test] - fn memory_copy_within_works() { - for backend in test_backends() { - let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None); - let mut memory = create_test_memory(kind, backend); - memory.inner.fill(0, 10, 1).unwrap(); - assert!(memory.copy_within(10, 0, 10).is_ok()); - assert_eq!(memory.inner.read_vec(10, 10).unwrap(), vec![1; 10]); - } - } - - #[test] - fn memory_copy_within_out_of_bounds_fails() { - for backend in test_backends() { - let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None); - let mut memory = create_test_memory(kind, backend); - assert!(memory.copy_within(memory.inner.len(), 0, 10).is_err()); - } - } - - #[test] - fn memory_grow_works() { - for backend in test_backends() { - let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None); - let mut memory = create_test_memory(kind, backend); - let original_pages = memory.page_count; - assert_eq!(memory.grow(1, false).unwrap(), Some(original_pages as i64)); - assert_eq!(memory.page_count, original_pages + 1); - } - } - - #[test] - fn memory_grow_out_of_bounds_fails() { - for backend in test_backends() { - let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None); - let mut memory = create_test_memory(kind, backend); - assert_eq!(memory.grow(memory.kind.max_size() as i64 + 1, false).unwrap(), None); - } - } - - #[test] - fn memory_grow_respects_max_pages() { - for backend in test_backends() { - let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None); - let mut memory = create_test_memory(kind, backend); - assert_eq!(memory.grow(1, false).unwrap(), Some(1)); - assert_eq!(memory.grow(1, false).unwrap(), None); - } - } - - #[test] - fn memory_grow_negative_delta_fails() { - for backend in test_backends() { - let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), None); - let mut memory = create_test_memory(kind, backend); - let original_pages = memory.page_count; - assert_eq!(memory.grow(-1, false).unwrap(), None); - assert_eq!(memory.page_count, original_pages); - } - } - - #[test] - fn memory_custom_page_size_out_of_bounds_fails() { - for backend in test_backends() { - let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), Some(1)); - let mut memory = create_test_memory(kind, backend); - let data = [1, 2]; - assert!(memory.inner.write_all(0, &data).is_none()); - } - } - - #[test] - fn memory_custom_page_size_grow_works() { - for backend in test_backends() { - let kind = MemoryType::new(MemoryArch::I32, 1, Some(2), Some(1)); - let mut memory = create_test_memory(kind, backend); - assert_eq!(memory.grow(1, false).unwrap(), Some(1)); - let data = [1, 2]; - assert!(memory.inner.write_all(0, &data).is_some()); - assert_eq!(memory.inner.read_vec(0, data.len()).unwrap(), data); - } - } -} diff --git a/crates/tinywasm/src/store/memory/paged.rs b/crates/tinywasm/src/store/memory/paged.rs index 6ae65af..fc5947c 100644 --- a/crates/tinywasm/src/store/memory/paged.rs +++ b/crates/tinywasm/src/store/memory/paged.rs @@ -297,48 +297,3 @@ impl LinearMemory for PagedMemory { Ok(()) } } - -#[cfg(test)] -mod tests { - use super::{LinearMemory, PagedMemory}; - - #[test] - fn paged_memory_reads_zeroes_from_sparse_chunks() { - let memory = PagedMemory::try_new(16, 4).expect("test memory should be constructible"); - let mut dst = [1; 6]; - assert_eq!(memory.read(5, &mut dst), 3); - assert_eq!(&dst[..3], &[0; 3]); - assert_eq!(&dst[3..], &[1; 3]); - } - - #[test] - fn paged_memory_store_and_load_crosses_chunk_boundaries() { - let mut memory = PagedMemory::try_new(16, 4).expect("test memory should be constructible"); - memory.write_all(3, &[1, 2, 3, 4, 5, 6]).unwrap(); - - let mut dst = [0; 6]; - memory.read_exact(3, &mut dst).unwrap(); - assert_eq!(dst, [1, 2, 3, 4, 5, 6]); - } - - #[test] - fn paged_memory_copy_within_handles_overlap() { - let mut memory = PagedMemory::try_new(16, 4).expect("test memory should be constructible"); - memory.write_all(0, &[1, 2, 3, 4, 5, 6]).unwrap(); - memory.copy_within(2, 0, 6).unwrap(); - - let mut dst = [0; 8]; - memory.read_exact(0, &mut dst).unwrap(); - assert_eq!(dst, [1, 2, 1, 2, 3, 4, 5, 6]); - } - - #[test] - fn paged_memory_write_stops_at_chunk_boundary() { - let mut memory = PagedMemory::try_new(16, 4).expect("test memory should be constructible"); - assert_eq!(memory.write(3, &[1, 2, 3, 4]), 1); - - let mut dst = [0; 4]; - memory.read_exact(3, &mut dst).unwrap(); - assert_eq!(dst, [1, 0, 0, 0]); - } -} diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 84a52b5..1aabfb3 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -122,18 +122,6 @@ impl Store { self.module_instances.push(instance); } - /// Gets a global by its opaque store address. - #[doc(hidden)] - pub fn get_global_val(&self, addr: GlobalAddr) -> TinyWasmValue { - self.state.globals.get(addr) - } - - /// Sets a global by its opaque store address. - #[doc(hidden)] - pub fn set_global_val(&mut self, addr: GlobalAddr, value: TinyWasmValue) { - self.state.globals.set(addr, value); - } - /// Returns whether a public value has the requested runtime type. #[doc(hidden)] pub fn value_matches_type(&self, value: WasmValue, ty: WasmType) -> bool { @@ -264,7 +252,7 @@ impl Store { MemoryArch::I32 => TableType::new(element_type, table.ty.size_initial, table.ty.size_max), MemoryArch::I64 => TableType::new64(element_type, table.ty.size_initial, table.ty.size_max), }; - self.state.tables.push(TableInstance::new_with_init(ty, init)?); + self.state.tables.push(TableInstance::new(ty, init)?); } Ok(start..start + tables.len() as TableAddr) } diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index e6a213f..e12ef1a 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -92,7 +92,7 @@ impl State { self.globals .globals_32() .filter(|(_, ty)| Self::type_may_contain_gc_in(canonical_types, &ty.ty)) - .map(|(value, _)| ValueRef::from_raw(value)), + .map(|(value, _)| ValueRef::from_raw(*value)), ) .chain( self.tables @@ -108,12 +108,16 @@ impl State { .filter(|element| Self::type_may_contain_gc_in(canonical_types, &WasmType::Ref(element.ty))) .flat_map(|element| element.items.iter().flatten().copied()), ) - .chain( - self.exceptions - .iter() - .flat_map(|exception| exception.payload.iter().filter_map(|value| value.as_ref())), - ) - .chain(values.iter().filter_map(|value| value.as_ref())); + .chain(self.exceptions.iter().flat_map(|exception| { + exception.payload.iter().filter_map(|value| match value { + TinyWasmValue::ValueRef(value) => Some(*value), + _ => None, + }) + })) + .chain(values.iter().filter_map(|value| match value { + TinyWasmValue::ValueRef(value) => Some(*value), + _ => None, + })); self.gc.collect(roots).map_err(|_| Trap::OutOfMemory)?; } self.gc.alloc(type_addr, values, trace_references).map_err(|_| Trap::OutOfMemory) @@ -270,7 +274,7 @@ impl State { let actual = RefType::new_concrete(false, func.type_addr).expect("canonical type fits"); return self.ref_type_is_subtype(actual, expected); } - if expected.is_exn() { + if expected.abstract_heap_type() == Some(AbstractHeapType::Exn) { return value.addr().is_some_and(|addr| self.exceptions.get(addr as usize).is_some()); } if value.is_i31() { @@ -316,8 +320,9 @@ impl State { { false } - (WasmValue::Ref(RefValue::Exn(value)), WasmType::Ref(expected)) if expected.is_exn() => { - self.exceptions.get(value.addr() as usize).is_some() + (WasmValue::Ref(RefValue::Exn(value)), WasmType::Ref(expected)) => { + expected.abstract_heap_type() == Some(AbstractHeapType::Exn) + && self.exceptions.get(value.addr() as usize).is_some() } (WasmValue::Ref(RefValue::Any(value)), WasmType::Ref(expected)) => { self.value_ref_matches(ValueRef::from_raw(value.raw()), expected) diff --git a/crates/tinywasm/src/store/table.rs b/crates/tinywasm/src/store/table.rs index ece0001..5cbce74 100644 --- a/crates/tinywasm/src/store/table.rs +++ b/crates/tinywasm/src/store/table.rs @@ -15,12 +15,8 @@ pub(crate) struct TableInstance { } impl TableInstance { - #[cfg(test)] - pub(crate) fn new(kind: TableType) -> Result { - Self::new_with_init(kind, ValueRef::NULL) - } - - pub(crate) fn new_with_init(kind: TableType, init: ValueRef) -> Result { + /// Creates a table filled with the given initial reference. + pub(crate) fn new(kind: TableType, init: ValueRef) -> Result { let size = usize::try_from(kind.size_initial).map_err(|_| Trap::OutOfMemory)?; if size > MAX_TABLE_SIZE { return Err(Trap::OutOfMemory.into()); @@ -101,50 +97,3 @@ impl TableInstance { Ok(()) } } - -#[cfg(test)] -mod tests { - use super::*; - use alloc::vec; - - // Helper to create a dummy TableType - fn dummy_table_type() -> TableType { - TableType::new(RefType::FUNCREF, 10, Some(20)) - } - - #[test] - fn test_table_instance_creation() { - let kind = dummy_table_type(); - let table_instance = TableInstance::new(kind).unwrap(); - assert_eq!(table_instance.size() as u64, kind.size_initial, "Table instance creation failed: size mismatch"); - } - - #[test] - fn test_set_and_get() { - let kind = dummy_table_type(); - let mut table_instance = TableInstance::new(kind).unwrap(); - - let value = ValueRef::from_raw(2); - let result = table_instance.set(0, value); - assert!(result.is_ok(), "Setting table element failed"); - - let elem = table_instance.get(0); - assert!(elem.is_ok() && elem.unwrap() == &value, "Getting table element failed or returned incorrect value"); - } - - #[test] - fn test_table_init() { - let kind = dummy_table_type(); - let mut table_instance = TableInstance::new(kind).unwrap(); - - let init_elements = vec![ValueRef::from_raw(2); 5]; - let result = table_instance.init(0, &init_elements); - - assert!(result.is_ok(), "Initializing table with elements failed"); - - for i in 0..5 { - let elem = table_instance.get(i); - assert!(elem.is_ok() && !elem.unwrap().is_null(), "Element not initialized correctly at index {i}"); - } - } -} diff --git a/crates/tinywasm/tests/generated/wasm-annotations.csv b/crates/tinywasm/tests/generated/wasm-annotations.csv deleted file mode 100644 index f24ba50..0000000 --- a/crates/tinywasm/tests/generated/wasm-annotations.csv +++ /dev/null @@ -1,5 +0,0 @@ -0.8.0,142,0,[{"name":"annotations.wast","passed":74,"failed":0},{"name":"annotations/simd_lane.wast (skipped)","passed":0,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"token.wast","passed":61,"failed":0}] -0.9.0,617,0,[{"name":"annotations.wast","passed":74,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"simd_lane.wast","passed":475,"failed":0},{"name":"token.wast","passed":61,"failed":0}] -0.9.1,617,0,[{"name":"annotations.wast","passed":74,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"simd_lane.wast","passed":475,"failed":0},{"name":"token.wast","passed":61,"failed":0}] -0.10.0,617,0,[{"name":"annotations.wast","passed":74,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"simd_lane.wast","passed":475,"failed":0},{"name":"token.wast","passed":61,"failed":0}] -0.11.0-pre.0,617,0,[{"name":"annotations.wast","passed":74,"failed":0},{"name":"id.wast","passed":7,"failed":0},{"name":"simd_lane.wast","passed":475,"failed":0},{"name":"token.wast","passed":61,"failed":0}] diff --git a/crates/tinywasm/tests/generated/wasm-extended-const.csv b/crates/tinywasm/tests/generated/wasm-extended-const.csv deleted file mode 100644 index 1e4e851..0000000 --- a/crates/tinywasm/tests/generated/wasm-extended-const.csv +++ /dev/null @@ -1,5 +0,0 @@ -0.8.0,211,79,[{"name":"data.wast","passed":61,"failed":4},{"name":"elem.wast","passed":99,"failed":12},{"name":"global.wast","passed":51,"failed":63}] -0.9.0,290,0,[{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":111,"failed":0},{"name":"global.wast","passed":114,"failed":0}] -0.9.1,290,0,[{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":111,"failed":0},{"name":"global.wast","passed":114,"failed":0}] -0.10.0,290,0,[{"name":"data.wast","passed":65,"failed":0},{"name":"elem.wast","passed":111,"failed":0},{"name":"global.wast","passed":114,"failed":0}] -0.11.0-pre.0,284,0,[{"name":"data.wast","passed":63,"failed":0},{"name":"elem.wast","passed":109,"failed":0},{"name":"global.wast","passed":112,"failed":0}] diff --git a/crates/tinywasm/tests/generated/wasm-function-references.csv b/crates/tinywasm/tests/generated/wasm-function-references.csv deleted file mode 100644 index 9d6dd64..0000000 --- a/crates/tinywasm/tests/generated/wasm-function-references.csv +++ /dev/null @@ -1,3 +0,0 @@ -0.9.0,1536,331,[{"name":"binary.wast","passed":128,"failed":0},{"name":"br_on_non_null.wast","passed":0,"failed":9},{"name":"br_on_null.wast","passed":0,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call_ref.wast","passed":3,"failed":31},{"name":"data.wast","passed":59,"failed":0},{"name":"elem.wast","passed":138,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"global.wast","passed":108,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"linking.wast","passed":146,"failed":21},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":4},{"name":"return_call.wast","passed":45,"failed":0},{"name":"return_call_indirect.wast","passed":76,"failed":0},{"name":"return_call_ref.wast","passed":10,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"table-sub.wast","passed":2,"failed":1},{"name":"table.wast","passed":35,"failed":8},{"name":"type-equivalence.wast","passed":7,"failed":7},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":10}] -0.10.0,1536,331,[{"name":"binary.wast","passed":128,"failed":0},{"name":"br_on_non_null.wast","passed":0,"failed":9},{"name":"br_on_null.wast","passed":0,"failed":9},{"name":"br_table.wast","passed":24,"failed":162},{"name":"call_ref.wast","passed":3,"failed":31},{"name":"data.wast","passed":59,"failed":0},{"name":"elem.wast","passed":138,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"global.wast","passed":108,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"linking.wast","passed":146,"failed":21},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"ref.wast","passed":12,"failed":1},{"name":"ref_as_non_null.wast","passed":1,"failed":6},{"name":"ref_is_null.wast","passed":2,"failed":20},{"name":"ref_null.wast","passed":0,"failed":4},{"name":"return_call.wast","passed":45,"failed":0},{"name":"return_call_indirect.wast","passed":76,"failed":0},{"name":"return_call_ref.wast","passed":10,"failed":40},{"name":"select.wast","passed":155,"failed":2},{"name":"table-sub.wast","passed":2,"failed":1},{"name":"table.wast","passed":35,"failed":8},{"name":"type-equivalence.wast","passed":7,"failed":7},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":2,"failed":10}] -0.11.0-pre.0,1866,0,[{"name":"binary.wast","passed":128,"failed":0},{"name":"br_on_non_null.wast","passed":9,"failed":0},{"name":"br_on_null.wast","passed":9,"failed":0},{"name":"br_table.wast","passed":186,"failed":0},{"name":"call_ref.wast","passed":34,"failed":0},{"name":"data.wast","passed":59,"failed":0},{"name":"elem.wast","passed":138,"failed":0},{"name":"func.wast","passed":175,"failed":0},{"name":"global.wast","passed":108,"failed":0},{"name":"if.wast","passed":241,"failed":0},{"name":"linking.wast","passed":167,"failed":0},{"name":"local_get.wast","passed":36,"failed":0},{"name":"local_init.wast","passed":10,"failed":0},{"name":"ref.wast","passed":13,"failed":0},{"name":"ref_as_non_null.wast","passed":7,"failed":0},{"name":"ref_is_null.wast","passed":22,"failed":0},{"name":"ref_null.wast","passed":4,"failed":0},{"name":"return_call.wast","passed":45,"failed":0},{"name":"return_call_indirect.wast","passed":76,"failed":0},{"name":"return_call_ref.wast","passed":50,"failed":0},{"name":"select.wast","passed":157,"failed":0},{"name":"table-sub.wast","passed":3,"failed":0},{"name":"table.wast","passed":43,"failed":0},{"name":"type-equivalence.wast","passed":13,"failed":0},{"name":"unreached-invalid.wast","passed":121,"failed":0},{"name":"unreached-valid.wast","passed":12,"failed":0}] diff --git a/crates/tinywasm/tests/generated/wasm-nontrapping-float-to-int-conversions.csv b/crates/tinywasm/tests/generated/wasm-nontrapping-float-to-int-conversions.csv deleted file mode 100644 index 66d5329..0000000 --- a/crates/tinywasm/tests/generated/wasm-nontrapping-float-to-int-conversions.csv +++ /dev/null @@ -1,4 +0,0 @@ -0.9.0,615,0,[{"name":"conversions.wast","passed":615,"failed":0}] -0.9.1,615,0,[{"name":"conversions.wast","passed":615,"failed":0}] -0.10.0,615,0,[{"name":"conversions.wast","passed":615,"failed":0}] -0.11.0-pre.0,615,0,[{"name":"conversions.wast","passed":615,"failed":0}] diff --git a/crates/tinywasm/tests/generated/wasm-reference-types.csv b/crates/tinywasm/tests/generated/wasm-reference-types.csv deleted file mode 100644 index 92a4650..0000000 --- a/crates/tinywasm/tests/generated/wasm-reference-types.csv +++ /dev/null @@ -1,4 +0,0 @@ -0.9.0,9124,0,[{"name":"binary-leb128.wast","passed":77,"failed":0},{"name":"binary.wast","passed":134,"failed":0},{"name":"br_table.wast","passed":172,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call_indirect.wast","passed":169,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":45,"failed":0},{"name":"elem.wast","passed":60,"failed":0},{"name":"exports.wast","passed":84,"failed":0},{"name":"global.wast","passed":86,"failed":0},{"name":"imports.wast","passed":158,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":96,"failed":0},{"name":"memory_init.wast","passed":240,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":16,"failed":0},{"name":"ref_null.wast","passed":3,"failed":0},{"name":"select.wast","passed":141,"failed":0},{"name":"table-sub.wast","passed":2,"failed":0},{"name":"table.wast","passed":19,"failed":0},{"name":"table_copy.wast","passed":1728,"failed":0},{"name":"table_fill.wast","passed":45,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":50,"failed":0},{"name":"table_init.wast","passed":780,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"unreached-invalid.wast","passed":111,"failed":0}] -0.9.1,9124,0,[{"name":"binary-leb128.wast","passed":77,"failed":0},{"name":"binary.wast","passed":134,"failed":0},{"name":"br_table.wast","passed":172,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call_indirect.wast","passed":169,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":45,"failed":0},{"name":"elem.wast","passed":60,"failed":0},{"name":"exports.wast","passed":84,"failed":0},{"name":"global.wast","passed":86,"failed":0},{"name":"imports.wast","passed":158,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":96,"failed":0},{"name":"memory_init.wast","passed":240,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":16,"failed":0},{"name":"ref_null.wast","passed":3,"failed":0},{"name":"select.wast","passed":141,"failed":0},{"name":"table-sub.wast","passed":2,"failed":0},{"name":"table.wast","passed":19,"failed":0},{"name":"table_copy.wast","passed":1728,"failed":0},{"name":"table_fill.wast","passed":45,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":50,"failed":0},{"name":"table_init.wast","passed":780,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"unreached-invalid.wast","passed":111,"failed":0}] -0.10.0,9124,0,[{"name":"binary-leb128.wast","passed":77,"failed":0},{"name":"binary.wast","passed":134,"failed":0},{"name":"br_table.wast","passed":172,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call_indirect.wast","passed":169,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":45,"failed":0},{"name":"elem.wast","passed":60,"failed":0},{"name":"exports.wast","passed":84,"failed":0},{"name":"global.wast","passed":86,"failed":0},{"name":"imports.wast","passed":158,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":96,"failed":0},{"name":"memory_init.wast","passed":240,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":16,"failed":0},{"name":"ref_null.wast","passed":3,"failed":0},{"name":"select.wast","passed":141,"failed":0},{"name":"table-sub.wast","passed":2,"failed":0},{"name":"table.wast","passed":19,"failed":0},{"name":"table_copy.wast","passed":1728,"failed":0},{"name":"table_fill.wast","passed":45,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":50,"failed":0},{"name":"table_init.wast","passed":780,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"unreached-invalid.wast","passed":111,"failed":0}] -0.11.0-pre.0,9124,0,[{"name":"binary-leb128.wast","passed":77,"failed":0},{"name":"binary.wast","passed":134,"failed":0},{"name":"br_table.wast","passed":172,"failed":0},{"name":"bulk.wast","passed":117,"failed":0},{"name":"call_indirect.wast","passed":169,"failed":0},{"name":"custom.wast","passed":11,"failed":0},{"name":"data.wast","passed":45,"failed":0},{"name":"elem.wast","passed":60,"failed":0},{"name":"exports.wast","passed":84,"failed":0},{"name":"global.wast","passed":86,"failed":0},{"name":"imports.wast","passed":158,"failed":0},{"name":"linking.wast","passed":132,"failed":0},{"name":"memory_copy.wast","passed":4450,"failed":0},{"name":"memory_fill.wast","passed":100,"failed":0},{"name":"memory_grow.wast","passed":96,"failed":0},{"name":"memory_init.wast","passed":240,"failed":0},{"name":"ref_func.wast","passed":17,"failed":0},{"name":"ref_is_null.wast","passed":16,"failed":0},{"name":"ref_null.wast","passed":3,"failed":0},{"name":"select.wast","passed":141,"failed":0},{"name":"table-sub.wast","passed":2,"failed":0},{"name":"table.wast","passed":19,"failed":0},{"name":"table_copy.wast","passed":1728,"failed":0},{"name":"table_fill.wast","passed":45,"failed":0},{"name":"table_get.wast","passed":16,"failed":0},{"name":"table_grow.wast","passed":50,"failed":0},{"name":"table_init.wast","passed":780,"failed":0},{"name":"table_set.wast","passed":26,"failed":0},{"name":"table_size.wast","passed":39,"failed":0},{"name":"unreached-invalid.wast","passed":111,"failed":0}] diff --git a/crates/tinywasm/tests/generated/wasm-sign-extension-ops.csv b/crates/tinywasm/tests/generated/wasm-sign-extension-ops.csv deleted file mode 100644 index 4e7e2ee..0000000 --- a/crates/tinywasm/tests/generated/wasm-sign-extension-ops.csv +++ /dev/null @@ -1,4 +0,0 @@ -0.9.0,872,0,[{"name":"i32.wast","passed":458,"failed":0},{"name":"i64.wast","passed":414,"failed":0}] -0.9.1,872,0,[{"name":"i32.wast","passed":458,"failed":0},{"name":"i64.wast","passed":414,"failed":0}] -0.10.0,872,0,[{"name":"i32.wast","passed":458,"failed":0},{"name":"i64.wast","passed":414,"failed":0}] -0.11.0-pre.0,872,0,[{"name":"i32.wast","passed":458,"failed":0},{"name":"i64.wast","passed":414,"failed":0}] diff --git a/crates/tinywasm/tests/generated/wasm-tail-call.csv b/crates/tinywasm/tests/generated/wasm-tail-call.csv deleted file mode 100644 index 316895d..0000000 --- a/crates/tinywasm/tests/generated/wasm-tail-call.csv +++ /dev/null @@ -1,4 +0,0 @@ -0.9.0,119,0,[{"name":"return_call.wast","passed":44,"failed":0},{"name":"return_call_indirect.wast","passed":75,"failed":0}] -0.9.1,119,0,[{"name":"return_call.wast","passed":44,"failed":0},{"name":"return_call_indirect.wast","passed":75,"failed":0}] -0.10.0,119,0,[{"name":"return_call.wast","passed":44,"failed":0},{"name":"return_call_indirect.wast","passed":75,"failed":0}] -0.11.0-pre.0,119,0,[{"name":"return_call.wast","passed":44,"failed":0},{"name":"return_call_indirect.wast","passed":75,"failed":0}] diff --git a/crates/tinywasm/tests/test-wasm-annotations.rs b/crates/tinywasm/tests/test-wasm-annotations.rs deleted file mode 100644 index 8655d15..0000000 --- a/crates/tinywasm/tests/test-wasm-annotations.rs +++ /dev/null @@ -1,13 +0,0 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; -use wasm_testsuite::data::{Proposal, proposal}; - -fn main() -> Result<()> { - TestSuite::set_log_level(log::LevelFilter::Off); - - let mut test_suite = TestSuite::new(); - test_suite.run_files(proposal(&Proposal::Annotations))?; - test_suite.save_csv("./tests/generated/wasm-annotations.csv", env!("CARGO_PKG_VERSION"))?; - test_suite.report_status() -} diff --git a/crates/tinywasm/tests/test-wasm-extended-const.rs b/crates/tinywasm/tests/test-wasm-extended-const.rs deleted file mode 100644 index 888a49f..0000000 --- a/crates/tinywasm/tests/test-wasm-extended-const.rs +++ /dev/null @@ -1,13 +0,0 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; -use wasm_testsuite::data::{Proposal, proposal}; - -fn main() -> Result<()> { - TestSuite::set_log_level(log::LevelFilter::Off); - - let mut test_suite = TestSuite::new(); - test_suite.run_files(proposal(&Proposal::ExtendedConst))?; - test_suite.save_csv("./tests/generated/wasm-extended-const.csv", env!("CARGO_PKG_VERSION"))?; - test_suite.report_status() -} diff --git a/crates/tinywasm/tests/test-wasm-function-references.rs b/crates/tinywasm/tests/test-wasm-function-references.rs deleted file mode 100644 index d91ff82..0000000 --- a/crates/tinywasm/tests/test-wasm-function-references.rs +++ /dev/null @@ -1,13 +0,0 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; -use wasm_testsuite::data::{Proposal, proposal}; - -fn main() -> Result<()> { - TestSuite::set_log_level(log::LevelFilter::Off); - - let mut test_suite = TestSuite::new(); - test_suite.run_files(proposal(&Proposal::FunctionReferences))?; - test_suite.save_csv("./tests/generated/wasm-function-references.csv", env!("CARGO_PKG_VERSION"))?; - test_suite.report_status() -} diff --git a/crates/tinywasm/tests/test-wasm-nontrapping-float-to-int-conversions.rs b/crates/tinywasm/tests/test-wasm-nontrapping-float-to-int-conversions.rs deleted file mode 100644 index 0475fac..0000000 --- a/crates/tinywasm/tests/test-wasm-nontrapping-float-to-int-conversions.rs +++ /dev/null @@ -1,14 +0,0 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; -use wasm_testsuite::data::{Proposal, proposal}; - -fn main() -> Result<()> { - TestSuite::set_log_level(log::LevelFilter::Off); - let mut test_suite = TestSuite::new(); - - test_suite.run_files(proposal(&Proposal::NontrappingFloatToIntConversions))?; - test_suite - .save_csv("./tests/generated/wasm-nontrapping-float-to-int-conversions.csv", env!("CARGO_PKG_VERSION"))?; - test_suite.report_status() -} diff --git a/crates/tinywasm/tests/test-wasm-reference-types.rs b/crates/tinywasm/tests/test-wasm-reference-types.rs deleted file mode 100644 index b6f1155..0000000 --- a/crates/tinywasm/tests/test-wasm-reference-types.rs +++ /dev/null @@ -1,13 +0,0 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; -use wasm_testsuite::data::{Proposal, proposal}; - -fn main() -> Result<()> { - TestSuite::set_log_level(log::LevelFilter::Off); - let mut test_suite = TestSuite::new(); - - test_suite.run_files(proposal(&Proposal::ReferenceTypes))?; - test_suite.save_csv("./tests/generated/wasm-reference-types.csv", env!("CARGO_PKG_VERSION"))?; - test_suite.report_status() -} diff --git a/crates/tinywasm/tests/test-wasm-sign-extension-op.rs b/crates/tinywasm/tests/test-wasm-sign-extension-op.rs deleted file mode 100644 index c0ef143..0000000 --- a/crates/tinywasm/tests/test-wasm-sign-extension-op.rs +++ /dev/null @@ -1,13 +0,0 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; -use wasm_testsuite::data::{Proposal, proposal}; - -fn main() -> Result<()> { - TestSuite::set_log_level(log::LevelFilter::Off); - let mut test_suite = TestSuite::new(); - - test_suite.run_files(proposal(&Proposal::SignExtensionOps))?; - test_suite.save_csv("./tests/generated/wasm-sign-extension-ops.csv", env!("CARGO_PKG_VERSION"))?; - test_suite.report_status() -} diff --git a/crates/tinywasm/tests/test-wasm-tail-call.rs b/crates/tinywasm/tests/test-wasm-tail-call.rs deleted file mode 100644 index b6d8b2b..0000000 --- a/crates/tinywasm/tests/test-wasm-tail-call.rs +++ /dev/null @@ -1,14 +0,0 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; -use wasm_testsuite::data::{Proposal, proposal}; - -fn main() -> Result<()> { - TestSuite::set_log_level(log::LevelFilter::Off); - - let mut test_suite = TestSuite::new(); - test_suite.run_files(proposal(&Proposal::TailCall))?; - test_suite.print_errors(); - test_suite.save_csv("./tests/generated/wasm-tail-call.csv", env!("CARGO_PKG_VERSION"))?; - test_suite.report_status() -} diff --git a/crates/tinywasm/tests/wasm-custom/table-basics.wast b/crates/tinywasm/tests/wasm-custom/table-basics.wast new file mode 100644 index 0000000..64bda6c --- /dev/null +++ b/crates/tinywasm/tests/wasm-custom/table-basics.wast @@ -0,0 +1,32 @@ +(module + (type $result (func (result i32))) + (func $seven (type $result) (i32.const 7)) + (func $nine (type $result) (i32.const 9)) + + (table $table 3 5 funcref) + (elem (table $table) (i32.const 1) func $seven) + (elem $passive func $nine) + + (func (export "size") (result i32) + (table.size $table)) + (func (export "is-null") (param $index i32) (result i32) + (ref.is_null (table.get $table (local.get $index)))) + (func (export "call") (param $index i32) (result i32) + (call_indirect $table (type $result) (local.get $index))) + (func (export "set-nine") (param $index i32) + (table.set $table (local.get $index) (ref.func $nine))) + (func (export "init-nine") (param $index i32) + (table.init $table $passive (local.get $index) (i32.const 0) (i32.const 1))) +) + +(assert_return (invoke "size") (i32.const 3)) +(assert_return (invoke "is-null" (i32.const 0)) (i32.const 1)) +(assert_return (invoke "is-null" (i32.const 1)) (i32.const 0)) +(assert_return (invoke "call" (i32.const 1)) (i32.const 7)) +(assert_return (invoke "set-nine" (i32.const 0))) +(assert_return (invoke "is-null" (i32.const 0)) (i32.const 0)) +(assert_return (invoke "call" (i32.const 0)) (i32.const 9)) +(assert_return (invoke "is-null" (i32.const 2)) (i32.const 1)) +(assert_return (invoke "init-nine" (i32.const 2))) +(assert_return (invoke "is-null" (i32.const 2)) (i32.const 0)) +(assert_return (invoke "call" (i32.const 2)) (i32.const 9)) diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index aff9e24..5eb5491 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -94,7 +94,10 @@ pub enum ConstInstruction { F32Const(f32), F64Const(f64), V128Const([u8; 16]), - GlobalGet(GlobalAddr), + GlobalGet32(GlobalAddr), + GlobalGet64(GlobalAddr), + GlobalGet128(GlobalAddr), + GlobalGetRef(GlobalAddr), Ref(RefValue), RefI31, AnyConvertExtern, -- cgit v1.3.1 From 64cf33ced2db2135dd355a1c6e049bf51c93d956 Mon Sep 17 00:00:00 2001 From: Henry Date: Tue, 11 Aug 2026 17:25:32 +0200 Subject: chore: more superinstructions, cleanup Signed-off-by: Henry --- crates/parser/src/conversion.rs | 3 +- crates/parser/src/optimize.rs | 108 +- crates/tinywasm/src/func/host.rs | 5 +- crates/tinywasm/src/interpreter/executor.rs | 1304 ++++++++++---------- crates/tinywasm/src/store/state.rs | 21 +- crates/tinywasm/src/store/types.rs | 12 +- crates/tinywasm/tests/host_func_signature_check.rs | 2 +- crates/types/src/instructions.rs | 14 +- crates/types/src/reference.rs | 13 +- crates/types/src/value.rs | 2 +- examples/rust/Cargo.toml | 7 +- examples/rust/build.sh | 7 +- examples/rust/src/print.twasm | Bin 0 -> 154 bytes examples/rust/src/tinywasm_no_std.rs | 6 +- examples/rust/src/tinywasm_precompiled.rs | 30 + examples/wasm-rust.rs | 25 + 16 files changed, 827 insertions(+), 732 deletions(-) create mode 100644 examples/rust/src/print.twasm create mode 100644 examples/rust/src/tinywasm_precompiled.rs (limited to 'crates/parser/src/conversion.rs') diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 694c639..480a8d0 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -440,8 +440,7 @@ fn convert_heap_type_with_group( ))); } }; - RefType::new_concrete(nullable, index) - .ok_or_else(|| crate::ParseError::Other(format!("heap type index is too large: {index}"))) + Ok(RefType::new_concrete(nullable, index)) } wasmparser::HeapType::Abstract { shared: true, .. } | wasmparser::HeapType::Exact(_) => { Err(crate::ParseError::UnsupportedOperator(format!("Unsupported heap type: {heap:?}"))) diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs index 2b5e331..7081187 100644 --- a/crates/parser/src/optimize.rs +++ b/crates/parser/src/optimize.rs @@ -92,7 +92,9 @@ fn rewrite( let Some(op) = int_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); + rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); + rewrite!(instrs, i, [Const32(c), GlobalGet32(global)] => BinOpGlobalConst32(op, global, c)); rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); if matches!(op, BinOp::IAdd) { rewrite!(instrs, i, [Const32(c)] => AddConst32(c)); @@ -103,6 +105,7 @@ fn rewrite( let Some(op) = int_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); + rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); if matches!(op, BinOp::IShrS) { rewrite!(instrs, i, [BinOpLocalConst32(BinOp::IShl, local, 8), Const32(8)] => [LocalGet32(local), I32Extend8S]); @@ -113,7 +116,9 @@ fn rewrite( let Some(op) = int_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); + rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); rewrite!(instrs, i, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c)); + rewrite!(instrs, i, [Const64(c), GlobalGet64(global)] => BinOpGlobalConst64(op, global, c)); rewrite!(instrs, i, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); if matches!(op, BinOp::IAdd) { rewrite!(instrs, i, [Const64(c)] => AddConst64(c)); @@ -124,6 +129,7 @@ fn rewrite( let Some(op) = int_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); + rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); rewrite!(instrs, i, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); if matches!(op, BinOp::IShrS) { rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 8), Const64(8)] => [LocalGet64(local), I64Extend8S]); @@ -143,33 +149,42 @@ fn rewrite( let Some(op) = float_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); + rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); + rewrite!(instrs, i, [Const32(c), GlobalGet32(global)] => BinOpGlobalConst32(op, global, c)); } instr @ (F32Sub | F32Div | F32Copysign) => { let Some(op) = float_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); + rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); } instr @ (F64Add | F64Mul | F64Min | F64Max) => { let Some(op) = float_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); + rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); rewrite!(instrs, i, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c)); + rewrite!(instrs, i, [Const64(c), GlobalGet64(global)] => BinOpGlobalConst64(op, global, c)); } instr @ (F64Sub | F64Div | F64Copysign) => { let Some(op) = float_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); + rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); } instr @ (V128And | V128Or | V128Xor | I64x2Add | I64x2Mul) => { let Some(op) = bin_op_128(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet128(a), LocalGet128(b)] => BinOpLocalLocal128(op, a, b)); rewrite!(instrs, i, [LocalGet128(local), Const128(c)] => BinOpLocalConst128(op, local, c)); + rewrite!(instrs, i, [GlobalGet128(global), Const128(c)] => BinOpGlobalConst128(op, global, c)); rewrite!(instrs, i, [Const128(c), LocalGet128(local)] => BinOpLocalConst128(op, local, c)); + rewrite!(instrs, i, [Const128(c), GlobalGet128(global)] => BinOpGlobalConst128(op, global, c)); } V128AndNot => { rewrite!(instrs, i, [LocalGet128(a), LocalGet128(b)] => BinOpLocalLocal128(BinOp128::AndNot, a, b)); rewrite!(instrs, i, [LocalGet128(local), Const128(c)] => BinOpLocalConst128(BinOp128::AndNot, local, c)); + rewrite!(instrs, i, [GlobalGet128(global), Const128(c)] => BinOpGlobalConst128(BinOp128::AndNot, global, c)); } I32Store(memarg) | F32Store(memarg) => { rewrite!(instrs, i, @@ -277,6 +292,9 @@ fn rewrite( MemoryFill(mem) => { rewrite!(instrs, i, [Const32(val), Const32(size)] => MemoryFillImm(mem, val as u8, size)) } + GlobalGet32(dst) => rewrite!(instrs, i, [GlobalSet32(src)] if (src == dst) => GlobalTee32(src)), + GlobalGet64(dst) => rewrite!(instrs, i, [GlobalSet64(src)] if (src == dst) => GlobalTee64(src)), + GlobalGet128(dst) => rewrite!(instrs, i, [GlobalSet128(src)] if (src == dst) => GlobalTee128(src)), LocalGet32(dst) => rewrite!(instrs, i, [LocalSet32(src)] if (src == dst) => LocalTee32(src)), LocalGet64(dst) => rewrite!(instrs, i, [LocalSet64(src)] if (src == dst) => LocalTee64(src)), LocalGet128(dst) => rewrite!(instrs, i, [LocalSet128(src)] if (src == dst) => LocalTee128(src)), @@ -542,7 +560,6 @@ fn rewrite( replace!(instrs, i, 1 => JumpIfNonZero32(target)); continue; }); - rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalZero32 { target_ip: target, local }); rewrite!(instrs, i, [LocalGet64(local), I64Eqz] => { replace!(instrs, i, 2 => JumpIfLocalNonZero64 { target_ip: target, local }); continue; @@ -552,8 +569,30 @@ fn rewrite( continue; }); rewrite!(instrs, i, - [BinOpLocalConstTee32(BinOp::IAdd, local, delta, dst)] if (local == dst) => - IncLocalJump32 { target_ip: target, local, delta, on_zero: true } + [BinOpLocalConstTee32(op, local, imm, dst)] if (local == dst) => + match inc_delta(op, imm) { + Some(delta) => IncLocalJump32 { target_ip: target, local, delta, on_zero: true }, + None => BinOpLocalConstJump32 { target_ip: target, local, imm, op, on_zero: true }, + } + ); + rewrite!(instrs, i, + [AddConst32(imm), LocalTee32(local), LocalGet32(cond)] if (local == cond) => + IncStackTeeLocalJump32 { target_ip: target, local, delta: imm, on_zero: true } + ); + rewrite!(instrs, i, + [AndConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => + BinOpStackConstTeeLocalJump32 { target_ip: target, local, imm, op: BinOp::IAnd, on_zero: true } + ); + rewrite!(instrs, i, + [SubConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => + IncStackTeeLocalJump32 { target_ip: target, local, delta: imm.wrapping_neg(), on_zero: true } + ); + rewrite!(instrs, i, + [BinOpGlobalConst32(op, global, imm), GlobalTee32(dst)] if (global == dst) => + match inc_delta(op, imm) { + Some(delta) => IncGlobalJump32 { target_ip: target, global, delta, on_zero: true }, + None => BinOpGlobalConstJump32 { target_ip: target, global, imm, op, on_zero: true }, + } ); rewrite!(instrs, i, [CmpLocalLocal32(op, left, right)] => @@ -564,9 +603,12 @@ fn rewrite( JumpCmpLocalLocal64 { target_ip: target, left, right, op: inverse_cmp_op(op) } ); rewrite!(instrs, i, - [BinOpLocalConstTee32(BinOp::IAdd, local, delta, dst), LocalGet32(right), cmp] if - (local == dst && let Some(op) = cmp_op(cmp)) => - IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op: inverse_cmp_op(op) } + [BinOpLocalConstTee32(binop, local, imm, dst), LocalGet32(right), cmp] if + (local == dst && let Some(cmp) = cmp_op(cmp)) => + match inc_delta(binop, imm) { + Some(delta) => IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op: inverse_cmp_op(cmp) }, + None => BinOpLocalConstJumpCmpLocal32 { target_ip: target, local, imm, binop, right, cmp: inverse_cmp_op(cmp) }, + } ); rewrite!(instrs, i, [LocalGet32(local), cmp] if (let Some(op) = cmp_op(cmp)) => @@ -611,6 +653,8 @@ fn rewrite( (0, CmpOp::Ne) => JumpIfNonZero64(target), (imm, op) => JumpCmpStackConst64 { target_ip: target, imm, op }, }); + rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalZero32 { target_ip: target, local }); + rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalZero64 { target_ip: target, local }); canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1); } JumpIfNonZero32(ip) => { @@ -623,7 +667,6 @@ fn rewrite( replace!(instrs, i, 1 => JumpIfZero32(target)); continue; }); - rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalNonZero32 { target_ip: target, local }); rewrite!(instrs, i, [LocalGet64(local), I64Eqz] => { replace!(instrs, i, 2 => JumpIfLocalZero64 { target_ip: target, local }); continue; @@ -633,8 +676,30 @@ fn rewrite( continue; }); rewrite!(instrs, i, - [BinOpLocalConstTee32(BinOp::IAdd, local, delta, dst)] if (local == dst) => - IncLocalJump32 { target_ip: target, local, delta, on_zero: false } + [BinOpLocalConstTee32(op, local, imm, dst)] if (local == dst) => + match inc_delta(op, imm) { + Some(delta) => IncLocalJump32 { target_ip: target, local, delta, on_zero: false }, + None => BinOpLocalConstJump32 { target_ip: target, local, imm, op, on_zero: false }, + } + ); + rewrite!(instrs, i, + [AddConst32(imm), LocalTee32(local), LocalGet32(cond)] if (local == cond) => + IncStackTeeLocalJump32 { target_ip: target, local, delta: imm, on_zero: false } + ); + rewrite!(instrs, i, + [AndConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => + BinOpStackConstTeeLocalJump32 { target_ip: target, local, imm, op: BinOp::IAnd, on_zero: false } + ); + rewrite!(instrs, i, + [SubConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => + IncStackTeeLocalJump32 { target_ip: target, local, delta: imm.wrapping_neg(), on_zero: false } + ); + rewrite!(instrs, i, + [BinOpGlobalConst32(op, global, imm), GlobalTee32(dst)] if (global == dst) => + match inc_delta(op, imm) { + Some(delta) => IncGlobalJump32 { target_ip: target, global, delta, on_zero: false }, + None => BinOpGlobalConstJump32 { target_ip: target, global, imm, op, on_zero: false }, + } ); rewrite!(instrs, i, [CmpLocalLocal32(op, left, right)] => @@ -645,9 +710,12 @@ fn rewrite( JumpCmpLocalLocal64 { target_ip: target, left, right, op } ); rewrite!(instrs, i, - [BinOpLocalConstTee32(BinOp::IAdd, local, delta, dst), LocalGet32(right), cmp] if - (local == dst && let Some(op) = cmp_op(cmp)) => - IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op } + [BinOpLocalConstTee32(binop, local, imm, dst), LocalGet32(right), cmp] if + (local == dst && let Some(cmp) = cmp_op(cmp)) => + match inc_delta(binop, imm) { + Some(delta) => IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op: cmp }, + None => BinOpLocalConstJumpCmpLocal32 { target_ip: target, local, imm, binop, right, cmp }, + } ); rewrite!(instrs, i, [LocalGet32(local), cmp] if (let Some(op) = cmp_op(cmp)) => @@ -692,6 +760,8 @@ fn rewrite( (0, CmpOp::Ne) => JumpIfNonZero64(target), (imm, op) => JumpCmpStackConst64 { target_ip: target, imm, op }, }); + rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalNonZero32 { target_ip: target, local }); + rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalNonZero64 { target_ip: target, local }); canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1); } JumpIfZero64(ip) => { @@ -774,6 +844,14 @@ fn cmp_op(instr: Instruction) -> Option { }) } +fn inc_delta(op: BinOp, imm: i32) -> Option { + match op { + BinOp::IAdd => Some(imm), + BinOp::ISub => Some(imm.wrapping_neg()), + _ => None, + } +} + fn int_bin_op(instr: Instruction) -> Option { Some(match instr { Instruction::I32Add | Instruction::I64Add => BinOp::IAdd, @@ -921,7 +999,13 @@ fn instruction_target_mut(instr: &mut Instruction) -> Option<&mut u32> { | Instruction::JumpCmpStackConst64 { target_ip: ip, .. } | Instruction::JumpCmpStackLocal32 { target_ip: ip, .. } | Instruction::JumpCmpStackLocal64 { target_ip: ip, .. } + | Instruction::BinOpLocalConstJump32 { target_ip: ip, .. } + | Instruction::BinOpLocalConstJumpCmpLocal32 { target_ip: ip, .. } + | Instruction::BinOpStackConstTeeLocalJump32 { target_ip: ip, .. } + | Instruction::BinOpGlobalConstJump32 { target_ip: ip, .. } | Instruction::IncLocalJump32 { target_ip: ip, .. } + | Instruction::IncStackTeeLocalJump32 { target_ip: ip, .. } + | Instruction::IncGlobalJump32 { target_ip: ip, .. } | Instruction::IncLocalJumpCmpLocal32 { target_ip: ip, .. } | Instruction::JumpIfLocalZero32 { target_ip: ip, .. } | Instruction::JumpIfLocalNonZero32 { target_ip: ip, .. } diff --git a/crates/tinywasm/src/func/host.rs b/crates/tinywasm/src/func/host.rs index 5335444..27c5573 100644 --- a/crates/tinywasm/src/func/host.rs +++ b/crates/tinywasm/src/func/host.rs @@ -31,10 +31,7 @@ impl HostFunction { let canonical = *type_addrs .get(module_addr as usize) .ok_or_else(|| crate::Error::other("host function signature contains an invalid concrete type"))?; - Ok(WasmType::Ref( - tinywasm_types::RefType::new_concrete(ref_ty.is_nullable(), canonical) - .expect("canonical type addresses fit in references"), - )) + Ok(WasmType::Ref(tinywasm_types::RefType::new_concrete(ref_ty.is_nullable(), canonical))) }; let params = self.0.ty.params().iter().copied().map(resolve).collect::>>()?; let results = self.0.ty.results().iter().copied().map(resolve).collect::>>()?; diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 2d2a745..051b12f 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -66,14 +66,14 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec(&mut self, instr_ptr: usize) -> Result> { - macro_rules! stack_op { - (unary $ty:ty, |$v:ident| $expr:expr) => { - stack_op!(unary $ty => $ty, |$v| $expr) - }; - (binary $ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => { - stack_op!(binary $ty => $ty, |$lhs, $rhs| $expr) - }; - (binary try $ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ + macro_rules! exec_op { + (branch $target:expr, $condition:expr) => {{ + if $condition { + self.cf.instr_ptr = *$target as usize; + return Ok(None); + } + }}; + (binary_fallible $ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ let $rhs = <$ty>::stack_pop(&mut self.store.value_stack); let $lhs = <$ty>::stack_pop(&mut self.store.value_stack); <$ty>::stack_push(&mut self.store.value_stack, $expr?)?; @@ -87,28 +87,25 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let $lhs = <$from>::stack_pop(&mut self.store.value_stack); <$to>::stack_push(&mut self.store.value_stack, $expr)?; }}; - (binary_into2 $from:ty => $to:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ + (binary_two_results $from:ty => $to:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ let $rhs = <$from>::stack_pop(&mut self.store.value_stack); let $lhs = <$from>::stack_pop(&mut self.store.value_stack); let out = $expr; <$to>::stack_push(&mut self.store.value_stack, out.0)?; <$to>::stack_push(&mut self.store.value_stack, out.1)?; }}; - (binary $lhs_ty:ty, $rhs_ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => { - stack_op!(binary $lhs_ty, $rhs_ty => $rhs_ty, |$lhs, $rhs| $expr) - }; - (binary $lhs_ty:ty, $rhs_ty:ty => $res:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ + (binary_mixed $lhs_ty:ty, $rhs_ty:ty => $res:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ let $rhs = <$rhs_ty>::stack_pop(&mut self.store.value_stack); let $lhs = <$lhs_ty>::stack_pop(&mut self.store.value_stack); <$res>::stack_push(&mut self.store.value_stack, $expr)?; }}; - (ternary $ty:ty, |$a:ident, $b:ident, $c:ident| $expr:expr) => {{ - let $c = <$ty>::stack_pop(&mut self.store.value_stack); - let $b = <$ty>::stack_pop(&mut self.store.value_stack); - let $a = <$ty>::stack_pop(&mut self.store.value_stack); - <$ty>::stack_push(&mut self.store.value_stack, $expr)?; + (ternary $from:ty => $to:ty, |$a:ident, $b:ident, $c:ident| $expr:expr) => {{ + let $c = <$from>::stack_pop(&mut self.store.value_stack); + let $b = <$from>::stack_pop(&mut self.store.value_stack); + let $a = <$from>::stack_pop(&mut self.store.value_stack); + <$to>::stack_push(&mut self.store.value_stack, $expr)?; }}; - (quaternary_into2 $from:ty => $to:ty, |$a:ident, $b:ident, $c:ident, $d:ident| $expr:expr) => {{ + (quaternary_two_results $from:ty => $to:ty, |$a:ident, $b:ident, $c:ident, $d:ident| $expr:expr) => {{ let $d = <$from>::stack_pop(&mut self.store.value_stack); let $c = <$from>::stack_pop(&mut self.store.value_stack); let $b = <$from>::stack_pop(&mut self.store.value_stack); @@ -135,93 +132,64 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let value = <$ty>::stack_pop(&mut self.store.value_stack); <$ty>::global_set(&mut self.store.state.globals, addr, value); }}; - } - - macro_rules! exec_binop { - (32, $op:expr, $lhs:expr, $rhs:expr) => { - exec_binop!(@scalar i32, u32, f32, $op, $lhs, $rhs) - }; - (64, $op:expr, $lhs:expr, $rhs:expr) => { - exec_binop!(@scalar i64, u64, f64, $op, $lhs, $rhs) - }; - (@scalar $signed:ty, $unsigned:ty, $float:ty, $op:expr, $lhs:expr, $rhs:expr) => {{ - match $op { - BinOp::IAdd => $lhs.wrapping_add($rhs), - BinOp::ISub => $lhs.wrapping_sub($rhs), - BinOp::IMul => $lhs.wrapping_mul($rhs), - BinOp::IAnd => $lhs & $rhs, - BinOp::IOr => $lhs | $rhs, - BinOp::IXor => $lhs ^ $rhs, - BinOp::IShl => (($lhs as $signed).wrapping_shl($rhs as u32)) as $unsigned, - BinOp::IShrS => (($lhs as $signed).wrapping_shr($rhs as u32)) as $unsigned, - BinOp::IShrU => $lhs.wrapping_shr($rhs as u32), - BinOp::IRotl => (($lhs as $signed).rotate_left($rhs as u32)) as $unsigned, - BinOp::IRotr => (($lhs as $signed).rotate_right($rhs as u32)) as $unsigned, - BinOp::FAdd => (<$float>::from_bits($lhs) + <$float>::from_bits($rhs)).to_bits(), - BinOp::FSub => (<$float>::from_bits($lhs) - <$float>::from_bits($rhs)).to_bits(), - BinOp::FMul => (<$float>::from_bits($lhs) * <$float>::from_bits($rhs)).to_bits(), - BinOp::FDiv => (<$float>::from_bits($lhs) / <$float>::from_bits($rhs)).to_bits(), - BinOp::FMin => <$float>::from_bits($lhs).tw_minimum(<$float>::from_bits($rhs)).to_bits(), - BinOp::FMax => <$float>::from_bits($lhs).tw_maximum(<$float>::from_bits($rhs)).to_bits(), - BinOp::FCopysign => <$float>::from_bits($lhs).copysign(<$float>::from_bits($rhs)).to_bits(), - } - }}; - (128, $op:expr, $lhs:expr, $rhs:expr) => {{ - match $op { - BinOp128::And => $lhs.v128_and($rhs), - BinOp128::AndNot => $lhs.v128_andnot($rhs), - BinOp128::Or => $lhs.v128_or($rhs), - BinOp128::Xor => $lhs.v128_xor($rhs), - BinOp128::I64x2Add => $lhs.i64x2_add($rhs), - BinOp128::I64x2Mul => $lhs.i64x2_mul($rhs), - } + (global_tee $ty:ty, $global_index:expr) => {{ + let addr = self.module.resolve_global_addr(*$global_index); + let value = <$ty>::stack_peek(&self.store.value_stack); + <$ty>::global_set(&mut self.store.state.globals, addr, value); }}; - } - - macro_rules! binop { - (local_local $vt:ty, $width:tt, $op:ident, $a:ident, $b:ident) => {{ + (binop_local_local $vt:ty, $exec:ident, $op:ident, $a:ident, $b:ident) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); - self.store.value_stack.push(exec_binop!($width, *$op, lhs, rhs))?; + <$vt>::stack_push(&mut self.store.value_stack, $exec(*$op, lhs, rhs))?; }}; - (local_local_set $vt:ty, $width:tt, $op:ident, $a:ident, $b:ident, $dst:ident) => {{ + (binop_local_local_set $vt:ty, $exec:ident, $op:ident, $a:ident, $b:ident, $dst:ident) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); - let value = exec_binop!($width, *$op, lhs, rhs); + let value = $exec(*$op, lhs, rhs); <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); }}; - (local_local_tee $vt:ty, $width:tt, $op:ident, $a:ident, $b:ident, $dst:ident) => {{ + (binop_local_local_tee $vt:ty, $exec:ident, $op:ident, $a:ident, $b:ident, $dst:ident) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); - let value = exec_binop!($width, *$op, lhs, rhs); + let value = $exec(*$op, lhs, rhs); <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); - self.store.value_stack.push(value)?; + <$vt>::stack_push(&mut self.store.value_stack, value)?; }}; - (local_local_cmp $vt:ty, $cmp:ident, $op:ident, $a:ident, $b:ident) => {{ + (cmp_local_local $vt:ty, $cmp:ident, $op:ident, $a:ident, $b:ident) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); self.store.value_stack.push(i32::from($cmp(lhs, rhs, *$op)))?; }}; - (local_const $vt:ty, $width:tt, $op:ident, $local:ident, $rhs:expr) => {{ + (binop_local_const $vt:ty, $exec:ident, $op:ident, $local:ident, $rhs:expr) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - self.store.value_stack.push(exec_binop!($width, *$op, lhs, $rhs))?; + <$vt>::stack_push(&mut self.store.value_stack, $exec(*$op, lhs, $rhs))?; }}; - (local_const_set $vt:ty, $width:tt, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{ + (binop_local_const_set $vt:ty, $exec:ident, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - let value = exec_binop!($width, *$op, lhs, $rhs); + let value = $exec(*$op, lhs, $rhs); <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); }}; - (local_const_tee $vt:ty, $width:tt, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{ + (binop_local_const_tee $vt:ty, $exec:ident, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{ let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - let value = exec_binop!($width, *$op, lhs, $rhs); + let value = $exec(*$op, lhs, $rhs); <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); - self.store.value_stack.push(value)?; + <$vt>::stack_push(&mut self.store.value_stack, value)?; }}; - (stack_global $vt:ty, $width:tt, $op:ident, $global:ident) => {{ + (binop_global_const $vt:ty, $exec:ident, $op:ident, $global:ident, $rhs:expr) => {{ + let lhs = <$vt>::global_get(&self.store.state.globals, self.module.resolve_global_addr(*$global)); + self.store.value_stack.push($exec(*$op, lhs, $rhs))?; + }}; + (binop_stack_global $vt:ty, $exec:ident, $op:ident, $global:ident) => {{ let global_val = <$vt>::global_get(&self.store.state.globals, self.module.resolve_global_addr(*$global)); let stack_val = <$vt>::stack_pop(&mut self.store.value_stack); - self.store.value_stack.push(exec_binop!($width, *$op, stack_val, global_val))?; + self.store.value_stack.push($exec(*$op, stack_val, global_val))?; + }}; + (binop_acc_local $ty:ty, $acc:ident, $mul:expr, $add:expr) => {{ + let rhs = <$ty>::stack_pop(&mut self.store.value_stack); + let lhs = <$ty>::stack_pop(&mut self.store.value_stack); + let value = ($mul)(lhs, rhs); + <$ty>::local_update(&mut self.store.value_stack, &self.cf, *$acc, |acc| ($add)(value, acc)); }}; } @@ -247,27 +215,115 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Throw(tag) => { self.exec_throw(*tag)?; return Ok(None); } ThrowRef => { self.exec_throw_ref()?; return Ok(None); } Jump(ip) => { self.cf.instr_ptr = *ip as usize; return Ok(None); } - JumpIfZero32(ip) => if self.exec_jump_zero_32(*ip) { return Ok(None) }, - JumpIfNonZero32(ip) => if self.exec_jump_non_zero_32(*ip) { return Ok(None) }, - JumpIfZero64(ip) => if self.exec_jump_zero_64(*ip) { return Ok(None) }, - JumpIfNonZero64(ip) => if self.exec_jump_non_zero_64(*ip) { return Ok(None) }, - JumpIfRefNull(ip) => if self.exec_jump_ref_null(*ip) { return Ok(None) }, - JumpIfRefNonNull(ip) => if self.exec_jump_ref_non_null(*ip) { return Ok(None) }, + JumpIfZero32(ip) => exec_op!(branch ip, i32::stack_pop(&mut self.store.value_stack) == 0), + JumpIfNonZero32(ip) => exec_op!(branch ip, i32::stack_pop(&mut self.store.value_stack) != 0), + JumpIfZero64(ip) => exec_op!(branch ip, i64::stack_pop(&mut self.store.value_stack) == 0), + JumpIfNonZero64(ip) => exec_op!(branch ip, i64::stack_pop(&mut self.store.value_stack) != 0), + JumpIfRefNull(ip) => { + let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null(); + if is_null { + ValueRef::stack_pop(&mut self.store.value_stack); + } + exec_op!(branch ip, is_null); + }, + JumpIfRefNonNull(ip) => { + let is_non_null = !ValueRef::stack_peek(&self.store.value_stack).is_null(); + if !is_non_null { + ValueRef::stack_pop(&mut self.store.value_stack); + } + exec_op!(branch ip, is_non_null); + }, BrOnCast(ip, ty, on_fail) => if self.exec_ref_matches(*ty) == *on_fail { self.cf.instr_ptr = *ip as usize; return Ok(None); }, - JumpIfLocalZero32 { target_ip, local } => if self.exec_jump_local_zero_32(*target_ip, *local) { return Ok(None) }, - JumpIfLocalNonZero32 { target_ip, local } => if self.exec_jump_local_non_zero_32(*target_ip, *local) { return Ok(None) }, - JumpIfLocalZero64 { target_ip, local } => if self.exec_jump_local_zero_64(*target_ip, *local) { return Ok(None) }, - JumpIfLocalNonZero64 { target_ip, local } => if self.exec_jump_local_non_zero_64(*target_ip, *local) { return Ok(None) }, - JumpCmpStackConst32 { target_ip, imm, op } => if self.exec_jump_cmp_stack_const_32(*target_ip, *imm, *op) { return Ok(None) }, - JumpCmpStackConst64 { target_ip, imm, op } => if self.exec_jump_cmp_stack_const_64(*target_ip, *imm, *op) { return Ok(None) }, - JumpCmpStackLocal32 { target_ip, local, op } => if self.exec_jump_cmp_stack_local_32(*target_ip, *local, *op) { return Ok(None) }, - JumpCmpStackLocal64 { target_ip, local, op } => if self.exec_jump_cmp_stack_local_64(*target_ip, *local, *op) { return Ok(None) }, - IncLocalJump32 { target_ip, local, delta, on_zero } => if self.exec_inc_local_jump_32(*target_ip, *local, *delta, *on_zero) { return Ok(None) }, - IncLocalJumpCmpLocal32 { target_ip, local, delta, right, op } => if self.exec_inc_local_jump_cmp_local_32(*target_ip, *local, *delta, *right, *op) { return Ok(None) }, - JumpCmpLocalConst32 { target_ip, local, imm, op } => if self.exec_jump_cmp_local_const_32(*target_ip, *local, *imm, *op) { return Ok(None) }, - JumpCmpLocalConst64 { target_ip, local, imm, op } => if self.exec_jump_cmp_local_const_64(*target_ip, *local, *imm, *op) { return Ok(None) }, - JumpCmpLocalLocal32 { target_ip, left, right, op } => if self.exec_jump_cmp_local_local_32(*target_ip, *left, *right, *op) { return Ok(None) }, - JumpCmpLocalLocal64 { target_ip, left, right, op } => if self.exec_jump_cmp_local_local_64(*target_ip, *left, *right, *op) { return Ok(None) }, + JumpIfLocalZero32 { target_ip, local } => exec_op!(branch target_ip, Value32::local_get(&self.store.value_stack, &self.cf, *local) == 0), + JumpIfLocalNonZero32 { target_ip, local } => exec_op!(branch target_ip, Value32::local_get(&self.store.value_stack, &self.cf, *local) != 0), + JumpIfLocalZero64 { target_ip, local } => exec_op!(branch target_ip, Value64::local_get(&self.store.value_stack, &self.cf, *local) == 0), + JumpIfLocalNonZero64 { target_ip, local } => exec_op!(branch target_ip, Value64::local_get(&self.store.value_stack, &self.cf, *local) != 0), + JumpCmpStackConst32 { target_ip, imm, op } => { + let lhs = i32::stack_pop(&mut self.store.value_stack); + exec_op!(branch target_ip, cmp_i32(lhs, *imm, *op)); + }, + JumpCmpStackConst64 { target_ip, imm, op } => { + let lhs = i64::stack_pop(&mut self.store.value_stack); + exec_op!(branch target_ip, cmp_i64(lhs, *imm, *op)); + }, + JumpCmpStackLocal32 { target_ip, local, op } => { + let lhs = i32::stack_pop(&mut self.store.value_stack); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, *local); + exec_op!(branch target_ip, cmp_i32(lhs, rhs, *op)); + }, + JumpCmpStackLocal64 { target_ip, local, op } => { + let lhs = i64::stack_pop(&mut self.store.value_stack); + let rhs = i64::local_get(&self.store.value_stack, &self.cf, *local); + exec_op!(branch target_ip, cmp_i64(lhs, rhs, *op)); + }, + BinOpLocalConstJump32 { target_ip, local, imm, op, on_zero } => { + let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local); + let value = exec_binop_32(*op, lhs as u32, *imm as u32) as i32; + i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); + exec_op!(branch target_ip, (value == 0) == *on_zero); + }, + BinOpLocalConstJumpCmpLocal32 { target_ip, local, imm, binop, right, cmp } => { + let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local); + let lhs = exec_binop_32(*binop, lhs as u32, *imm as u32) as i32; + i32::local_set(&mut self.store.value_stack, &self.cf, *local, lhs); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, *right); + exec_op!(branch target_ip, cmp_i32(lhs, rhs, *cmp)); + }, + BinOpStackConstTeeLocalJump32 { target_ip, local, imm, op, on_zero } => { + let lhs = i32::stack_pop(&mut self.store.value_stack); + let value = exec_binop_32(*op, lhs as u32, *imm as u32) as i32; + i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); + i32::stack_push(&mut self.store.value_stack, value)?; + exec_op!(branch target_ip, (value == 0) == *on_zero); + }, + BinOpGlobalConstJump32 { target_ip, global, imm, op, on_zero } => { + let global = self.module.resolve_global_addr(*global); + let lhs = i32::global_get(&self.store.state.globals, global); + let value = exec_binop_32(*op, lhs as u32, *imm as u32) as i32; + i32::global_set(&mut self.store.state.globals, global, value); + exec_op!(branch target_ip, (value == 0) == *on_zero); + }, + IncLocalJump32 { target_ip, local, delta, on_zero } => { + let value = i32::local_get(&self.store.value_stack, &self.cf, *local).wrapping_add(*delta); + i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); + exec_op!(branch target_ip, (value == 0) == *on_zero); + }, + IncStackTeeLocalJump32 { target_ip, local, delta, on_zero } => { + let value = i32::stack_pop(&mut self.store.value_stack).wrapping_add(*delta); + i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); + i32::stack_push(&mut self.store.value_stack, value)?; + exec_op!(branch target_ip, (value == 0) == *on_zero); + }, + IncGlobalJump32 { target_ip, global, delta, on_zero } => { + let global = self.module.resolve_global_addr(*global); + let value = i32::global_get(&self.store.state.globals, global).wrapping_add(*delta); + i32::global_set(&mut self.store.state.globals, global, value); + exec_op!(branch target_ip, (value == 0) == *on_zero); + }, + IncLocalJumpCmpLocal32 { target_ip, local, delta, right, op } => { + let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local).wrapping_add(*delta); + i32::local_set(&mut self.store.value_stack, &self.cf, *local, lhs); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, *right); + exec_op!(branch target_ip, cmp_i32(lhs, rhs, *op)); + }, + JumpCmpLocalConst32 { target_ip, local, imm, op } => { + let lhs = i32::local_get(&self.store.value_stack, &self.cf, *local); + exec_op!(branch target_ip, cmp_i32(lhs, *imm, *op)); + }, + JumpCmpLocalConst64 { target_ip, local, imm, op } => { + let lhs = i64::local_get(&self.store.value_stack, &self.cf, *local); + exec_op!(branch target_ip, cmp_i64(lhs, i64::from(*imm), *op)); + }, + JumpCmpLocalLocal32 { target_ip, left, right, op } => { + let lhs = i32::local_get(&self.store.value_stack, &self.cf, *left); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, *right); + exec_op!(branch target_ip, cmp_i32(lhs, rhs, *op)); + }, + JumpCmpLocalLocal64 { target_ip, left, right, op } => { + let lhs = i64::local_get(&self.store.value_stack, &self.cf, *left); + let rhs = i64::local_get(&self.store.value_stack, &self.cf, *right); + exec_op!(branch target_ip, cmp_i64(lhs, rhs, *op)); + }, DropKeep(drop_keep) => self.exec_drop_keep(*drop_keep), BranchTable(default_ip, start, len) => { self.exec_branch_table(*default_ip, *start, *len); return Ok(None); } Return => { if self.exec_return() { return Ok(Some(())); } return Ok(None); } @@ -278,44 +334,47 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { LocalGet32(local_index) => self.store.value_stack.push(Value32::local_get(&self.store.value_stack, &self.cf, *local_index))?, LocalGet64(local_index) => self.store.value_stack.push(Value64::local_get(&self.store.value_stack, &self.cf, *local_index))?, LocalGet128(local_index) => self.store.value_stack.push(Value128::local_get(&self.store.value_stack, &self.cf, *local_index))?, - LocalSet32(local_index) => stack_op!(local_set_pop Value32, local_index), - LocalSet64(local_index) => stack_op!(local_set_pop Value64, local_index), - LocalSet128(local_index) => stack_op!(local_set_pop Value128, local_index), + LocalSet32(local_index) => exec_op!(local_set_pop Value32, local_index), + LocalSet64(local_index) => exec_op!(local_set_pop Value64, local_index), + LocalSet128(local_index) => exec_op!(local_set_pop Value128, local_index), LocalCopy32(from, to) => Value32::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), LocalCopy64(from, to) => Value64::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), LocalCopy128(from, to) => Value128::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), - AddConst32(c) => stack_op!(unary i32, |v| v.wrapping_add(*c)), - AddConst64(c) => stack_op!(unary i64, |v| v.wrapping_add(*c)), + AddConst32(c) => exec_op!(unary i32 => i32, |v| v.wrapping_add(*c)), + AddConst64(c) => exec_op!(unary i64 => i64, |v| v.wrapping_add(*c)), IncLocal32(local_index, delta) => i32::local_update(&mut self.store.value_stack, &self.cf, *local_index, |v| v.wrapping_add(*delta)), IncLocal64(local_index, delta) => i64::local_update(&mut self.store.value_stack, &self.cf, *local_index, |v| v.wrapping_add(*delta )), - I32Add3 => stack_op!(ternary i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)), - I64Add3 => stack_op!(ternary i64, |a, b, c| a.wrapping_add(b).wrapping_add(c)), - MulAccLocal32(acc) => self.exec_binop_acc_local::(*acc, |a, b| a.wrapping_mul(b), |a, b| a.wrapping_add(b)), - MulAccLocal64(acc) => self.exec_binop_acc_local::(*acc, |a, b| a.wrapping_mul(b), |a, b| a.wrapping_add(b)), - FMulAccLocal32(acc) => self.exec_binop_acc_local::(*acc, |a, b| a * b, |a, b| a + b), - FMulAccLocal64(acc) => self.exec_binop_acc_local::(*acc, |a, b| a * b, |a, b| a + b), - BinOpLocalLocal32(op, a, b) => binop!(local_local Value32, 32, op, a, b), - BinOpLocalLocal64(op, a, b) => binop!(local_local Value64, 64, op, a, b), - BinOpLocalLocal128(op, a, b) => binop!(local_local Value128, 128, op, a, b), - CmpLocalLocal32(op, a, b) => binop!(local_local_cmp i32, cmp_i32, op, a, b), - CmpLocalLocal64(op, a, b) => binop!(local_local_cmp i64, cmp_i64, op, a, b), - BinOpLocalLocalSet32(op, a, b, dst) => binop!(local_local_set Value32, 32, op, a, b, dst), - BinOpLocalLocalSet64(op, a, b, dst) => binop!(local_local_set Value64, 64, op, a, b, dst), - BinOpLocalLocalSet128(op, a, b, dst) => binop!(local_local_set Value128, 128, op, a, b, dst), - BinOpLocalLocalTee32(op, a, b, dst) => binop!(local_local_tee Value32, 32, op, a, b, dst), - BinOpLocalLocalTee64(op, a, b, dst) => binop!(local_local_tee Value64, 64, op, a, b, dst), - BinOpLocalLocalTee128(op, a, b, dst) => binop!(local_local_tee Value128, 128, op, a, b, dst), - BinOpLocalConst32(op, local_index, c) => binop!(local_const Value32, 32, op, local_index, *c as u32), - BinOpLocalConst64(op, local_index, c) => binop!(local_const Value64, 64, op, local_index, *c as u64), - BinOpLocalConst128(op, local_index, c) => binop!(local_const Value128, 128, op, local_index, Value128(self.func.data.v128_const(*c))), - BinOpLocalConstSet32(op, local_index, c, dst) => binop!(local_const_set Value32, 32, op, local_index, *c as u32, dst), - BinOpLocalConstSet64(op, local_index, c, dst) => binop!(local_const_set Value64, 64, op, local_index, *c as u64, dst), - BinOpLocalConstSet128(op, local_index, c, dst) => binop!(local_const_set Value128, 128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), - BinOpLocalConstTee32(op, local_index, c, dst) => binop!(local_const_tee Value32, 32, op, local_index, *c as u32, dst), - BinOpLocalConstTee64(op, local_index, c, dst) => binop!(local_const_tee Value64, 64, op, local_index, *c as u64, dst), - BinOpLocalConstTee128(op, local_index, c, dst) => binop!(local_const_tee Value128, 128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), - BinOpStackGlobal32(op, global_index) => binop!(stack_global Value32, 32, op, global_index), - BinOpStackGlobal64(op, global_index) => binop!(stack_global Value64, 64, op, global_index), + I32Add3 => exec_op!(ternary i32 => i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)), + I64Add3 => exec_op!(ternary i64 => i64, |a, b, c| a.wrapping_add(b).wrapping_add(c)), + MulAccLocal32(acc) => exec_op!(binop_acc_local i32, acc, |a: i32, b| a.wrapping_mul(b), |a: i32, b| a.wrapping_add(b)), + MulAccLocal64(acc) => exec_op!(binop_acc_local i64, acc, |a: i64, b| a.wrapping_mul(b), |a: i64, b| a.wrapping_add(b)), + FMulAccLocal32(acc) => exec_op!(binop_acc_local f32, acc, |a: f32, b| a * b, |a: f32, b| a + b), + FMulAccLocal64(acc) => exec_op!(binop_acc_local f64, acc, |a: f64, b| a * b, |a: f64, b| a + b), + BinOpLocalLocal32(op, a, b) => exec_op!(binop_local_local Value32, exec_binop_32, op, a, b), + BinOpLocalLocal64(op, a, b) => exec_op!(binop_local_local Value64, exec_binop_64, op, a, b), + BinOpLocalLocal128(op, a, b) => exec_op!(binop_local_local Value128, exec_binop_128, op, a, b), + CmpLocalLocal32(op, a, b) => exec_op!(cmp_local_local i32, cmp_i32, op, a, b), + CmpLocalLocal64(op, a, b) => exec_op!(cmp_local_local i64, cmp_i64, op, a, b), + BinOpLocalLocalSet32(op, a, b, dst) => exec_op!(binop_local_local_set Value32, exec_binop_32, op, a, b, dst), + BinOpLocalLocalSet64(op, a, b, dst) => exec_op!(binop_local_local_set Value64, exec_binop_64, op, a, b, dst), + BinOpLocalLocalSet128(op, a, b, dst) => exec_op!(binop_local_local_set Value128, exec_binop_128, op, a, b, dst), + BinOpLocalLocalTee32(op, a, b, dst) => exec_op!(binop_local_local_tee Value32, exec_binop_32, op, a, b, dst), + BinOpLocalLocalTee64(op, a, b, dst) => exec_op!(binop_local_local_tee Value64, exec_binop_64, op, a, b, dst), + BinOpLocalLocalTee128(op, a, b, dst) => exec_op!(binop_local_local_tee Value128, exec_binop_128, op, a, b, dst), + BinOpLocalConst32(op, local_index, c) => exec_op!(binop_local_const Value32, exec_binop_32, op, local_index, *c as u32), + BinOpLocalConst64(op, local_index, c) => exec_op!(binop_local_const Value64, exec_binop_64, op, local_index, *c as u64), + BinOpLocalConst128(op, local_index, c) => exec_op!(binop_local_const Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c))), + BinOpGlobalConst32(op, global_index, c) => exec_op!(binop_global_const Value32, exec_binop_32, op, global_index, *c as u32), + BinOpGlobalConst64(op, global_index, c) => exec_op!(binop_global_const Value64, exec_binop_64, op, global_index, *c as u64), + BinOpGlobalConst128(op, global_index, c) => exec_op!(binop_global_const Value128, exec_binop_128, op, global_index, Value128(self.func.data.v128_const(*c))), + BinOpLocalConstSet32(op, local_index, c, dst) => exec_op!(binop_local_const_set Value32, exec_binop_32, op, local_index, *c as u32, dst), + BinOpLocalConstSet64(op, local_index, c, dst) => exec_op!(binop_local_const_set Value64, exec_binop_64, op, local_index, *c as u64, dst), + BinOpLocalConstSet128(op, local_index, c, dst) => exec_op!(binop_local_const_set Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), + BinOpLocalConstTee32(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value32, exec_binop_32, op, local_index, *c as u32, dst), + BinOpLocalConstTee64(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value64, exec_binop_64, op, local_index, *c as u64, dst), + BinOpLocalConstTee128(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), + BinOpStackGlobal32(op, global_index) => exec_op!(binop_stack_global Value32, exec_binop_32, op, global_index), + BinOpStackGlobal64(op, global_index) => exec_op!(binop_stack_global Value64, exec_binop_64, op, global_index), SetLocalConst32(local_index, c) => i32::local_set(&mut self.store.value_stack, &self.cf, *local_index, *c), SetLocalConst64(local_index, c) => i64::local_set(&mut self.store.value_stack, &self.cf, *local_index, *c), SetLocalConst128(local_index, c) => Value128::local_set(&mut self.store.value_stack, &self.cf, *local_index, Value128(self.func.data.v128_const(*c))), @@ -342,129 +401,132 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { LoadLocalSet16U32(m, addr_local, dst_local) => self.exec_load_local_set::(*m, *addr_local, *dst_local, i32::from)?, LoadLocalTee128(m, addr_local, dst_local) => self.exec_load_local_tee::(*m, *addr_local, *dst_local, |v| v)?, LoadLocalSet128(m, addr_local, dst_local) => self.exec_load_local_set::(*m, *addr_local, *dst_local, |v| v)?, - AndConstTee32(c, local_index) => { stack_op!(unary i32, |v| v & *c); stack_op!(local_tee i32, local_index); } - SubConstTee32(c, local_index) => { stack_op!(unary i32, |v| v.wrapping_sub(*c)); stack_op!(local_tee i32, local_index); } - AndConstTee64(c, local_index) => { stack_op!(unary i64, |v| v & *c); stack_op!(local_tee i64, local_index); } - SubConstTee64(c, local_index) => { stack_op!(unary i64, |v| v.wrapping_sub(*c)); stack_op!(local_tee i64, local_index); } - LocalTee32(local_index) => stack_op!(local_tee Value32, local_index), - LocalTee64(local_index) => stack_op!(local_tee Value64, local_index), - LocalTee128(local_index) => stack_op!(local_tee Value128, local_index), - GlobalGet32(global_index) => stack_op!(global_get Value32, global_index), - GlobalGet64(global_index) => stack_op!(global_get Value64, global_index), - GlobalGet128(global_index) => stack_op!(global_get Value128, global_index), - GlobalSet32(global_index) => stack_op!(global_set Value32, global_index), - GlobalSet64(global_index) => stack_op!(global_set Value64, global_index), - GlobalSet128(global_index) => stack_op!(global_set Value128, global_index), - Const32(val) => self.exec_const(*val)?, - Const64(val) => self.exec_const(*val)?, - I64Eqz => stack_op!(unary i64 => i32, |v| i32::from(v == 0)), - I32Eqz => stack_op!(unary i32, |v| i32::from(v == 0)), - I32Eq => stack_op!(binary i32, |a, b| i32::from(a == b)), - I64Eq => stack_op!(binary i64 => i32, |a, b| i32::from(a == b)), - F32Eq => stack_op!(binary f32 => i32, |a, b| i32::from(a == b)), - F64Eq => stack_op!(binary f64 => i32, |a, b| i32::from(a == b)), - I32Ne => stack_op!(binary i32, |a, b| i32::from(a != b)), - I64Ne => stack_op!(binary i64 => i32, |a, b| i32::from(a != b)), - F32Ne => stack_op!(binary f32 => i32, |a, b| i32::from(a != b)), - F64Ne => stack_op!(binary f64 => i32, |a, b| i32::from(a != b)), - I32LtS => stack_op!(binary i32, |a, b| i32::from(a < b)), - I64LtS => stack_op!(binary i64 => i32, |a, b| i32::from(a < b)), - I32LtU => stack_op!(binary u32 => i32, |a, b| i32::from(a < b)), - I64LtU => stack_op!(binary u64 => i32, |a, b| i32::from(a < b)), - F32Lt => stack_op!(binary f32 => i32, |a, b| i32::from(a < b)), - F64Lt => stack_op!(binary f64 => i32, |a, b| i32::from(a < b)), - I32LeS => stack_op!(binary i32, |a, b| i32::from(a <= b)), - I64LeS => stack_op!(binary i64 => i32, |a, b| i32::from(a <= b)), - I32LeU => stack_op!(binary u32 => i32, |a, b| i32::from(a <= b)), - I64LeU => stack_op!(binary u64 => i32, |a, b| i32::from(a <= b)), - F32Le => stack_op!(binary f32 => i32, |a, b| i32::from(a <= b)), - F64Le => stack_op!(binary f64 => i32, |a, b| i32::from(a <= b)), - I32GeS => stack_op!(binary i32, |a, b| i32::from(a >= b)), - I64GeS => stack_op!(binary i64 => i32, |a, b| i32::from(a >= b)), - I32GeU => stack_op!(binary u32 => i32, |a, b| i32::from(a >= b)), - I64GeU => stack_op!(binary u64 => i32, |a, b| i32::from(a >= b)), - F32Ge => stack_op!(binary f32 => i32, |a, b| i32::from(a >= b)), - F64Ge => stack_op!(binary f64 => i32, |a, b| i32::from(a >= b)), - I32GtS => stack_op!(binary i32, |a, b| i32::from(a > b)), - I64GtS => stack_op!(binary i64 => i32, |a, b| i32::from(a > b)), - I32GtU => stack_op!(binary u32 => i32, |a, b| i32::from(a > b)), - I64GtU => stack_op!(binary u64 => i32, |a, b| i32::from(a > b)), - F32Gt => stack_op!(binary f32 => i32, |a, b| i32::from(a > b)), - F64Gt => stack_op!(binary f64 => i32, |a, b| i32::from(a > b)), - I32Add => stack_op!(binary i32, |a, b| a.wrapping_add(b)), - I64Add => stack_op!(binary i64, |a, b| a.wrapping_add(b)), - F32Add => stack_op!(binary f32, |a, b| a + b), - F64Add => stack_op!(binary f64, |a, b| a + b), - I32Sub => stack_op!(binary i32, |a, b| a.wrapping_sub(b)), - I64Sub => stack_op!(binary i64, |a, b| a.wrapping_sub(b)), - F32Sub => stack_op!(binary f32, |a, b| a - b), - F64Sub => stack_op!(binary f64, |a, b| a - b), - F32Div => stack_op!(binary f32, |a, b| a / b), - F64Div => stack_op!(binary f64, |a, b| a / b), - I32Mul => stack_op!(binary i32, |a, b| a.wrapping_mul(b)), - I64Mul => stack_op!(binary i64, |a, b| a.wrapping_mul(b)), - F32Mul => stack_op!(binary f32, |a, b| a * b), - F64Mul => stack_op!(binary f64, |a, b| a * b), - I32DivS => stack_op!(binary try i32, |a, b| a.tw_checked_div(b)), - I64DivS => stack_op!(binary try i64, |a, b| a.tw_checked_div(b)), - I32DivU => stack_op!(binary try u32, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)), - I64DivU => stack_op!(binary try u64, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)), - I32RemS => stack_op!(binary try i32, |a, b| a.tw_checked_wrapping_rem(b)), - I64RemS => stack_op!(binary try i64, |a, b| a.tw_checked_wrapping_rem(b)), - I32RemU => stack_op!(binary try u32, |a, b| a.tw_checked_wrapping_rem(b)), - I64RemU => stack_op!(binary try u64, |a, b| a.tw_checked_wrapping_rem(b)), - I32And => stack_op!(binary i32, |a, b| a & b), - I64And => stack_op!(binary i64, |a, b| a & b), - I32Or => stack_op!(binary i32, |a, b| a | b), - I64Or => stack_op!(binary i64, |a, b| a | b), - I32Xor => stack_op!(binary i32, |a, b| a ^ b), - I64Xor => stack_op!(binary i64, |a, b| a ^ b), - I32Shl => stack_op!(binary i32, |a, b| a.wrapping_shl(b as u32)), - I64Shl => stack_op!(binary i64, |a, b| a.wrapping_shl(b as u32)), - I32ShrS => stack_op!(binary i32, |a, b| a.wrapping_shr(b as u32)), - I64ShrS => stack_op!(binary i64, |a, b| a.wrapping_shr(b as u32)), - I32ShrU => stack_op!(binary u32, |a, b| a.wrapping_shr(b)), - I64ShrU => stack_op!(binary u64, |a, b| a.wrapping_shr(b as u32)), - I32Rotl => stack_op!(binary i32, |a, b| a.rotate_left(b as u32)), - I64Rotl => stack_op!(binary i64, |a, b| a.rotate_left(b as u32)), - I32Rotr => stack_op!(binary i32, |a, b| a.rotate_right(b as u32)), - I64Rotr => stack_op!(binary i64, |a, b| a.rotate_right(b as u32)), - I64Add128 => stack_op!(quaternary_into2 i64 => i64, |a_lo, a_hi, b_lo, b_hi| { + AndConstTee32(c, local_index) => { exec_op!(unary i32 => i32, |v| v & *c); exec_op!(local_tee i32, local_index); } + SubConstTee32(c, local_index) => { exec_op!(unary i32 => i32, |v| v.wrapping_sub(*c)); exec_op!(local_tee i32, local_index); } + AndConstTee64(c, local_index) => { exec_op!(unary i64 => i64, |v| v & *c); exec_op!(local_tee i64, local_index); } + SubConstTee64(c, local_index) => { exec_op!(unary i64 => i64, |v| v.wrapping_sub(*c)); exec_op!(local_tee i64, local_index); } + LocalTee32(local_index) => exec_op!(local_tee Value32, local_index), + LocalTee64(local_index) => exec_op!(local_tee Value64, local_index), + LocalTee128(local_index) => exec_op!(local_tee Value128, local_index), + GlobalGet32(global_index) => exec_op!(global_get Value32, global_index), + GlobalGet64(global_index) => exec_op!(global_get Value64, global_index), + GlobalGet128(global_index) => exec_op!(global_get Value128, global_index), + GlobalSet32(global_index) => exec_op!(global_set Value32, global_index), + GlobalSet64(global_index) => exec_op!(global_set Value64, global_index), + GlobalSet128(global_index) => exec_op!(global_set Value128, global_index), + GlobalTee32(global_index) => exec_op!(global_tee Value32, global_index), + GlobalTee64(global_index) => exec_op!(global_tee Value64, global_index), + GlobalTee128(global_index) => exec_op!(global_tee Value128, global_index), + Const32(val) => i32::stack_push(&mut self.store.value_stack, *val)?, + Const64(val) => i64::stack_push(&mut self.store.value_stack, *val)?, + I64Eqz => exec_op!(unary i64 => i32, |v| i32::from(v == 0)), + I32Eqz => exec_op!(unary i32 => i32, |v| i32::from(v == 0)), + I32Eq => exec_op!(binary i32 => i32, |a, b| i32::from(a == b)), + I64Eq => exec_op!(binary i64 => i32, |a, b| i32::from(a == b)), + F32Eq => exec_op!(binary f32 => i32, |a, b| i32::from(a == b)), + F64Eq => exec_op!(binary f64 => i32, |a, b| i32::from(a == b)), + I32Ne => exec_op!(binary i32 => i32, |a, b| i32::from(a != b)), + I64Ne => exec_op!(binary i64 => i32, |a, b| i32::from(a != b)), + F32Ne => exec_op!(binary f32 => i32, |a, b| i32::from(a != b)), + F64Ne => exec_op!(binary f64 => i32, |a, b| i32::from(a != b)), + I32LtS => exec_op!(binary i32 => i32, |a, b| i32::from(a < b)), + I64LtS => exec_op!(binary i64 => i32, |a, b| i32::from(a < b)), + I32LtU => exec_op!(binary u32 => i32, |a, b| i32::from(a < b)), + I64LtU => exec_op!(binary u64 => i32, |a, b| i32::from(a < b)), + F32Lt => exec_op!(binary f32 => i32, |a, b| i32::from(a < b)), + F64Lt => exec_op!(binary f64 => i32, |a, b| i32::from(a < b)), + I32LeS => exec_op!(binary i32 => i32, |a, b| i32::from(a <= b)), + I64LeS => exec_op!(binary i64 => i32, |a, b| i32::from(a <= b)), + I32LeU => exec_op!(binary u32 => i32, |a, b| i32::from(a <= b)), + I64LeU => exec_op!(binary u64 => i32, |a, b| i32::from(a <= b)), + F32Le => exec_op!(binary f32 => i32, |a, b| i32::from(a <= b)), + F64Le => exec_op!(binary f64 => i32, |a, b| i32::from(a <= b)), + I32GeS => exec_op!(binary i32 => i32, |a, b| i32::from(a >= b)), + I64GeS => exec_op!(binary i64 => i32, |a, b| i32::from(a >= b)), + I32GeU => exec_op!(binary u32 => i32, |a, b| i32::from(a >= b)), + I64GeU => exec_op!(binary u64 => i32, |a, b| i32::from(a >= b)), + F32Ge => exec_op!(binary f32 => i32, |a, b| i32::from(a >= b)), + F64Ge => exec_op!(binary f64 => i32, |a, b| i32::from(a >= b)), + I32GtS => exec_op!(binary i32 => i32, |a, b| i32::from(a > b)), + I64GtS => exec_op!(binary i64 => i32, |a, b| i32::from(a > b)), + I32GtU => exec_op!(binary u32 => i32, |a, b| i32::from(a > b)), + I64GtU => exec_op!(binary u64 => i32, |a, b| i32::from(a > b)), + F32Gt => exec_op!(binary f32 => i32, |a, b| i32::from(a > b)), + F64Gt => exec_op!(binary f64 => i32, |a, b| i32::from(a > b)), + I32Add => exec_op!(binary i32 => i32, |a, b| a.wrapping_add(b)), + I64Add => exec_op!(binary i64 => i64, |a, b| a.wrapping_add(b)), + F32Add => exec_op!(binary f32 => f32, |a, b| a + b), + F64Add => exec_op!(binary f64 => f64, |a, b| a + b), + I32Sub => exec_op!(binary i32 => i32, |a, b| a.wrapping_sub(b)), + I64Sub => exec_op!(binary i64 => i64, |a, b| a.wrapping_sub(b)), + F32Sub => exec_op!(binary f32 => f32, |a, b| a - b), + F64Sub => exec_op!(binary f64 => f64, |a, b| a - b), + F32Div => exec_op!(binary f32 => f32, |a, b| a / b), + F64Div => exec_op!(binary f64 => f64, |a, b| a / b), + I32Mul => exec_op!(binary i32 => i32, |a, b| a.wrapping_mul(b)), + I64Mul => exec_op!(binary i64 => i64, |a, b| a.wrapping_mul(b)), + F32Mul => exec_op!(binary f32 => f32, |a, b| a * b), + F64Mul => exec_op!(binary f64 => f64, |a, b| a * b), + I32DivS => exec_op!(binary_fallible i32, |a, b| a.tw_checked_div(b)), + I64DivS => exec_op!(binary_fallible i64, |a, b| a.tw_checked_div(b)), + I32DivU => exec_op!(binary_fallible u32, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)), + I64DivU => exec_op!(binary_fallible u64, |a, b| a.checked_div(b).ok_or(Trap::DivisionByZero)), + I32RemS => exec_op!(binary_fallible i32, |a, b| a.tw_checked_wrapping_rem(b)), + I64RemS => exec_op!(binary_fallible i64, |a, b| a.tw_checked_wrapping_rem(b)), + I32RemU => exec_op!(binary_fallible u32, |a, b| a.tw_checked_wrapping_rem(b)), + I64RemU => exec_op!(binary_fallible u64, |a, b| a.tw_checked_wrapping_rem(b)), + I32And => exec_op!(binary i32 => i32, |a, b| a & b), + I64And => exec_op!(binary i64 => i64, |a, b| a & b), + I32Or => exec_op!(binary i32 => i32, |a, b| a | b), + I64Or => exec_op!(binary i64 => i64, |a, b| a | b), + I32Xor => exec_op!(binary i32 => i32, |a, b| a ^ b), + I64Xor => exec_op!(binary i64 => i64, |a, b| a ^ b), + I32Shl => exec_op!(binary i32 => i32, |a, b| a.wrapping_shl(b as u32)), + I64Shl => exec_op!(binary i64 => i64, |a, b| a.wrapping_shl(b as u32)), + I32ShrS => exec_op!(binary i32 => i32, |a, b| a.wrapping_shr(b as u32)), + I64ShrS => exec_op!(binary i64 => i64, |a, b| a.wrapping_shr(b as u32)), + I32ShrU => exec_op!(binary u32 => u32, |a, b| a.wrapping_shr(b)), + I64ShrU => exec_op!(binary u64 => u64, |a, b| a.wrapping_shr(b as u32)), + I32Rotl => exec_op!(binary i32 => i32, |a, b| a.rotate_left(b as u32)), + I64Rotl => exec_op!(binary i64 => i64, |a, b| a.rotate_left(b as u32)), + I32Rotr => exec_op!(binary i32 => i32, |a, b| a.rotate_right(b as u32)), + I64Rotr => exec_op!(binary i64 => i64, |a, b| a.rotate_right(b as u32)), + I64Add128 => exec_op!(quaternary_two_results i64 => i64, |a_lo, a_hi, b_lo, b_hi| { let lo = a_lo.wrapping_add(b_lo); let carry = u64::from((lo as u64) < (a_lo as u64)); let hi = a_hi.wrapping_add(b_hi).wrapping_add(carry as i64); (lo, hi) }), - I64Sub128 => stack_op!(quaternary_into2 i64 => i64, |a_lo, a_hi, b_lo, b_hi| { + I64Sub128 => exec_op!(quaternary_two_results i64 => i64, |a_lo, a_hi, b_lo, b_hi| { let lo = a_lo.wrapping_sub(b_lo); let borrow = u64::from((a_lo as u64) < (b_lo as u64)); let hi = a_hi.wrapping_sub(b_hi).wrapping_sub(borrow as i64); (lo, hi) }), - I64MulWideS => stack_op!(binary_into2 i64 => i64, |a, b| { + I64MulWideS => exec_op!(binary_two_results i64 => i64, |a, b| { let product = (a as i128).wrapping_mul(b as i128); (product as i64, (product >> 64) as i64) }), - I64MulWideU => stack_op!(binary_into2 i64 => i64, |a, b| { + I64MulWideU => exec_op!(binary_two_results i64 => i64, |a, b| { let product = (a as u64 as u128).wrapping_mul(b as u64 as u128); (product as u64 as i64, (product >> 64) as u64 as i64) }), - I32Clz => stack_op!(unary i32, |v| v.leading_zeros() as i32), - I64Clz => stack_op!(unary i64, |v| i64::from(v.leading_zeros())), - I32Ctz => stack_op!(unary i32, |v| v.trailing_zeros() as i32), - I64Ctz => stack_op!(unary i64, |v| i64::from(v.trailing_zeros())), - I32Popcnt => stack_op!(unary i32, |v| v.count_ones() as i32), - I64Popcnt => stack_op!(unary i64, |v| i64::from(v.count_ones())), + I32Clz => exec_op!(unary i32 => i32, |v| v.leading_zeros() as i32), + I64Clz => exec_op!(unary i64 => i64, |v| i64::from(v.leading_zeros())), + I32Ctz => exec_op!(unary i32 => i32, |v| v.trailing_zeros() as i32), + I64Ctz => exec_op!(unary i64 => i64, |v| i64::from(v.trailing_zeros())), + I32Popcnt => exec_op!(unary i32 => i32, |v| v.count_ones() as i32), + I64Popcnt => exec_op!(unary i64 => i64, |v| i64::from(v.count_ones())), // Reference types - RefFunc(func_idx) => self.exec_const(ValueRef::from_category_addr(self.module.resolve_func_addr(*func_idx)))?, - RefNull(_) => self.exec_const(ValueRef::NULL)?, + RefFunc(func_idx) => ValueRef::stack_push(&mut self.store.value_stack, ValueRef::from_category_addr(self.module.resolve_func_addr(*func_idx)))?, + RefNull(_) => ValueRef::stack_push(&mut self.store.value_stack, ValueRef::NULL)?, RefIsNull => self.exec_ref_is_null()?, RefAsNonNull => self.exec_ref_as_non_null()?, - RefI31 => stack_op!(unary i32 => ValueRef, |v| ValueRef::from_i31(v)), + RefI31 => exec_op!(unary i32 => ValueRef, |v| ValueRef::from_i31(v)), I31GetS => self.exec_i31_get(true)?, I31GetU => self.exec_i31_get(false)?, - RefEq => stack_op!(binary ValueRef => i32, |a, b| i32::from(a == b)), + RefEq => exec_op!(binary ValueRef => i32, |a, b| i32::from(a == b)), RefTest(ty) => self.exec_ref_test(*ty)?, RefCast(ty) => self.exec_ref_cast(*ty)?, // GC objects @@ -536,46 +598,46 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I64Load32U(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, // Numeric conversion operations - F32ConvertI32S => stack_op!(unary i32 => f32, |v| v as f32), - F32ConvertI64S => stack_op!(unary i64 => f32, |v| v as f32), - F64ConvertI32S => stack_op!(unary i32 => f64, |v| f64::from(v)), - F64ConvertI64S => stack_op!(unary i64 => f64, |v| v as f64), - F32ConvertI32U => stack_op!(unary u32 => f32, |v| v as f32), - F32ConvertI64U => stack_op!(unary u64 => f32, |v| v as f32), - F64ConvertI32U => stack_op!(unary u32 => f64, |v| f64::from(v)), - F64ConvertI64U => stack_op!(unary u64 => f64, |v| v as f64), + F32ConvertI32S => exec_op!(unary i32 => f32, |v| v as f32), + F32ConvertI64S => exec_op!(unary i64 => f32, |v| v as f32), + F64ConvertI32S => exec_op!(unary i32 => f64, |v| f64::from(v)), + F64ConvertI64S => exec_op!(unary i64 => f64, |v| v as f64), + F32ConvertI32U => exec_op!(unary u32 => f32, |v| v as f32), + F32ConvertI64U => exec_op!(unary u64 => f32, |v| v as f32), + F64ConvertI32U => exec_op!(unary u32 => f64, |v| f64::from(v)), + F64ConvertI64U => exec_op!(unary u64 => f64, |v| v as f64), // Sign-extension operations - I32Extend8S => stack_op!(unary i32, |v| i32::from(v as i8)), - I32Extend16S => stack_op!(unary i32, |v| i32::from(v as i16)), - I64Extend8S => stack_op!(unary i64, |v| i64::from(v as i8)), - I64Extend16S => stack_op!(unary i64, |v| i64::from(v as i16)), - I64Extend32S => stack_op!(unary i64, |v| i64::from(v as i32)), - I64ExtendI32U => stack_op!(unary u32 => i64, |v| i64::from(v)), - I64ExtendI32S => stack_op!(unary i32 => i64, |v| i64::from(v)), - I32WrapI64 => stack_op!(unary i64 => i32, |v| v as i32), - F32DemoteF64 => stack_op!(unary f64 => f32, |v| v as f32), - F64PromoteF32 => stack_op!(unary f32 => f64, |v| f64::from(v)), - F32Abs => stack_op!(unary f32, |v| v.abs()), - F64Abs => stack_op!(unary f64, |v| v.abs()), - F32Neg => stack_op!(unary f32, |v| -v), - F64Neg => stack_op!(unary f64, |v| -v), - F32Ceil => stack_op!(unary f32, |v| v.ceil()), - F64Ceil => stack_op!(unary f64, |v| v.ceil()), - F32Floor => stack_op!(unary f32, |v| v.floor()), - F64Floor => stack_op!(unary f64, |v| v.floor()), - F32Trunc => stack_op!(unary f32, |v| v.trunc()), - F64Trunc => stack_op!(unary f64, |v| v.trunc()), - F32Nearest => stack_op!(unary f32, |v| v.tw_nearest()), - F64Nearest => stack_op!(unary f64, |v| v.tw_nearest()), - F32Sqrt => stack_op!(unary f32, |v| v.sqrt()), - F64Sqrt => stack_op!(unary f64, |v| v.sqrt()), - F32Min => stack_op!(binary f32, |a, b| a.tw_minimum(b)), - F64Min => stack_op!(binary f64, |a, b| a.tw_minimum(b)), - F32Max => stack_op!(binary f32, |a, b| a.tw_maximum(b)), - F64Max => stack_op!(binary f64, |a, b| a.tw_maximum(b)), - F32Copysign => stack_op!(binary f32, |a, b| a.copysign(b)), - F64Copysign => stack_op!(binary f64, |a, b| a.copysign(b)), + I32Extend8S => exec_op!(unary i32 => i32, |v| i32::from(v as i8)), + I32Extend16S => exec_op!(unary i32 => i32, |v| i32::from(v as i16)), + I64Extend8S => exec_op!(unary i64 => i64, |v| i64::from(v as i8)), + I64Extend16S => exec_op!(unary i64 => i64, |v| i64::from(v as i16)), + I64Extend32S => exec_op!(unary i64 => i64, |v| i64::from(v as i32)), + I64ExtendI32U => exec_op!(unary u32 => i64, |v| i64::from(v)), + I64ExtendI32S => exec_op!(unary i32 => i64, |v| i64::from(v)), + I32WrapI64 => exec_op!(unary i64 => i32, |v| v as i32), + F32DemoteF64 => exec_op!(unary f64 => f32, |v| v as f32), + F64PromoteF32 => exec_op!(unary f32 => f64, |v| f64::from(v)), + F32Abs => exec_op!(unary f32 => f32, |v| v.abs()), + F64Abs => exec_op!(unary f64 => f64, |v| v.abs()), + F32Neg => exec_op!(unary f32 => f32, |v| -v), + F64Neg => exec_op!(unary f64 => f64, |v| -v), + F32Ceil => exec_op!(unary f32 => f32, |v| v.ceil()), + F64Ceil => exec_op!(unary f64 => f64, |v| v.ceil()), + F32Floor => exec_op!(unary f32 => f32, |v| v.floor()), + F64Floor => exec_op!(unary f64 => f64, |v| v.floor()), + F32Trunc => exec_op!(unary f32 => f32, |v| v.trunc()), + F64Trunc => exec_op!(unary f64 => f64, |v| v.trunc()), + F32Nearest => exec_op!(unary f32 => f32, |v| v.tw_nearest()), + F64Nearest => exec_op!(unary f64 => f64, |v| v.tw_nearest()), + F32Sqrt => exec_op!(unary f32 => f32, |v| v.sqrt()), + F64Sqrt => exec_op!(unary f64 => f64, |v| v.sqrt()), + F32Min => exec_op!(binary f32 => f32, |a, b| a.tw_minimum(b)), + F64Min => exec_op!(binary f64 => f64, |a, b| a.tw_minimum(b)), + F32Max => exec_op!(binary f32 => f32, |a, b| a.tw_maximum(b)), + F64Max => exec_op!(binary f64 => f64, |a, b| a.tw_maximum(b)), + F32Copysign => exec_op!(binary f32 => f32, |a, b| a.copysign(b)), + F64Copysign => exec_op!(binary f64 => f64, |a, b| a.copysign(b)), I32TruncF32S => checked_conv_float!(f32, i32, self), I32TruncF64S => checked_conv_float!(f64, i32, self), I32TruncF32U => checked_conv_float!(f32, u32, i32, self), @@ -586,25 +648,25 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I64TruncF64U => checked_conv_float!(f64, u64, i64, self), // Non-trapping float-to-int conversions - I32TruncSatF32S => stack_op!(unary f32 => i32, |v| v.trunc() as i32), - I32TruncSatF32U => stack_op!(unary f32 => u32, |v| v.trunc() as u32), - I32TruncSatF64S => stack_op!(unary f64 => i32, |v| v.trunc() as i32), - I32TruncSatF64U => stack_op!(unary f64 => u32, |v| v.trunc() as u32), - I64TruncSatF32S => stack_op!(unary f32 => i64, |v| v.trunc() as i64), - I64TruncSatF32U => stack_op!(unary f32 => u64, |v| v.trunc() as u64), - I64TruncSatF64S => stack_op!(unary f64 => i64, |v| v.trunc() as i64), - I64TruncSatF64U => stack_op!(unary f64 => u64, |v| v.trunc() as u64), + I32TruncSatF32S => exec_op!(unary f32 => i32, |v| v.trunc() as i32), + I32TruncSatF32U => exec_op!(unary f32 => u32, |v| v.trunc() as u32), + I32TruncSatF64S => exec_op!(unary f64 => i32, |v| v.trunc() as i32), + I32TruncSatF64U => exec_op!(unary f64 => u32, |v| v.trunc() as u32), + I64TruncSatF32S => exec_op!(unary f32 => i64, |v| v.trunc() as i64), + I64TruncSatF32U => exec_op!(unary f32 => u64, |v| v.trunc() as u64), + I64TruncSatF64S => exec_op!(unary f64 => i64, |v| v.trunc() as i64), + I64TruncSatF64U => exec_op!(unary f64 => u64, |v| v.trunc() as u64), // SIMD extension - V128Not => stack_op!(unary Value128, |v| v.v128_not()), - V128And => stack_op!(binary Value128, |a, b| a.v128_and(b)), - V128AndNot => stack_op!(binary Value128, |a, b| a.v128_andnot(b)), - V128Or => stack_op!(binary Value128, |a, b| a.v128_or(b)), - V128Xor => stack_op!(binary Value128, |a, b| a.v128_xor(b)), - V128Bitselect => stack_op!(ternary Value128, |a, b, c| Value128::v128_bitselect(a, b, c)), - V128AnyTrue => stack_op!(unary Value128 => i32, |v| v.v128_any_true() as i32), - I8x16Swizzle => stack_op!(binary Value128, |a, s| a.i8x16_swizzle(s)), - I8x16RelaxedSwizzle => stack_op!(binary Value128, |a, s| a.i8x16_relaxed_swizzle(s)), + V128Not => exec_op!(unary Value128 => Value128, |v| v.v128_not()), + V128And => exec_op!(binary Value128 => Value128, |a, b| a.v128_and(b)), + V128AndNot => exec_op!(binary Value128 => Value128, |a, b| a.v128_andnot(b)), + V128Or => exec_op!(binary Value128 => Value128, |a, b| a.v128_or(b)), + V128Xor => exec_op!(binary Value128 => Value128, |a, b| a.v128_xor(b)), + V128Bitselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::v128_bitselect(a, b, c)), + V128AnyTrue => exec_op!(unary Value128 => i32, |v| v.v128_any_true() as i32), + I8x16Swizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_swizzle(s)), + I8x16RelaxedSwizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_relaxed_swizzle(s)), V128Load(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| v)?, V128Load8x8S(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load8x8_s(v.to_le_bytes()))?, V128Load8x8U(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load8x8_u(v.to_le_bytes()))?, @@ -623,235 +685,235 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { V128Store64Lane(arg, lane) => self.exec_mem_store_lane::(arg.mem_addr(), arg.offset(), *lane)?, V128Load32Zero(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::from_i32x4([v, 0, 0, 0]))?, V128Load64Zero(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::from_i64x2([v, 0]))?, - Const128(arg) => self.exec_const(Value128(self.func.data.v128_const(*arg)))?, - I8x16ExtractLaneS(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_i8(*lane) as i32), - I8x16ExtractLaneU(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_u8(*lane) as i32), - I16x8ExtractLaneS(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_i16(*lane) as i32), - I16x8ExtractLaneU(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_u16(*lane) as i32), - I32x4ExtractLane(lane) => stack_op!(unary Value128 => i32, |v| v.extract_lane_i32(*lane)), - I64x2ExtractLane(lane) => stack_op!(unary Value128 => i64, |v| v.extract_lane_i64(*lane)), - F32x4ExtractLane(lane) => stack_op!(unary Value128 => f32, |v| v.extract_lane_f32(*lane)), - F64x2ExtractLane(lane) => stack_op!(unary Value128 => f64, |v| v.extract_lane_f64(*lane)), + Const128(arg) => Value128::stack_push(&mut self.store.value_stack, Value128(self.func.data.v128_const(*arg)))?, + I8x16ExtractLaneS(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i8(*lane) as i32), + I8x16ExtractLaneU(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_u8(*lane) as i32), + I16x8ExtractLaneS(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i16(*lane) as i32), + I16x8ExtractLaneU(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_u16(*lane) as i32), + I32x4ExtractLane(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i32(*lane)), + I64x2ExtractLane(lane) => exec_op!(unary Value128 => i64, |v| v.extract_lane_i64(*lane)), + F32x4ExtractLane(lane) => exec_op!(unary Value128 => f32, |v| v.extract_lane_f32(*lane)), + F64x2ExtractLane(lane) => exec_op!(unary Value128 => f64, |v| v.extract_lane_f64(*lane)), V128Load8Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, V128Load16Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, V128Load32Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, V128Load64Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, - I8x16ReplaceLane(lane) => stack_op!(binary i32, Value128, |value, vec| vec.i8x16_replace_lane(*lane, value as i8)), - I16x8ReplaceLane(lane) => stack_op!(binary i32, Value128, |value, vec| vec.i16x8_replace_lane(*lane, value as i16)), - I32x4ReplaceLane(lane) => stack_op!(binary i32, Value128, |value, vec| vec.i32x4_replace_lane(*lane, value)), - I64x2ReplaceLane(lane) => stack_op!(binary i64, Value128, |value, vec| vec.i64x2_replace_lane(*lane, value)), - F32x4ReplaceLane(lane) => stack_op!(binary f32, Value128, |value, vec| vec.f32x4_replace_lane(*lane, value)), - F64x2ReplaceLane(lane) => stack_op!(binary f64, Value128, |value, vec| vec.f64x2_replace_lane(*lane, value)), - I8x16Splat => stack_op!(unary i32 => Value128, |v| Value128::splat_i8(v as i8)), - I16x8Splat => stack_op!(unary i32 => Value128, |v| Value128::splat_i16(v as i16)), - I32x4Splat => stack_op!(unary i32 => Value128, |v| Value128::splat_i32(v)), - I64x2Splat => stack_op!(unary i64 => Value128, |v| Value128::splat_i64(v)), - F32x4Splat => stack_op!(unary f32 => Value128, |v| Value128::splat_f32(v)), - F64x2Splat => stack_op!(unary f64 => Value128, |v| Value128::splat_f64(v)), - I8x16Eq => stack_op!(binary Value128, |a, b| a.i8x16_eq(b)), - I16x8Eq => stack_op!(binary Value128, |a, b| a.i16x8_eq(b)), - I32x4Eq => stack_op!(binary Value128, |a, b| a.i32x4_eq(b)), - I64x2Eq => stack_op!(binary Value128, |a, b| a.i64x2_eq(b)), - F32x4Eq => stack_op!(binary Value128, |a, b| a.f32x4_eq(b)), - F64x2Eq => stack_op!(binary Value128, |a, b| a.f64x2_eq(b)), - I8x16Ne => stack_op!(binary Value128, |a, b| a.i8x16_ne(b)), - I16x8Ne => stack_op!(binary Value128, |a, b| a.i16x8_ne(b)), - I32x4Ne => stack_op!(binary Value128, |a, b| a.i32x4_ne(b)), - I64x2Ne => stack_op!(binary Value128, |a, b| a.i64x2_ne(b)), - F32x4Ne => stack_op!(binary Value128, |a, b| a.f32x4_ne(b)), - F64x2Ne => stack_op!(binary Value128, |a, b| a.f64x2_ne(b)), - I8x16LtS => stack_op!(binary Value128, |a, b| a.i8x16_lt_s(b)), - I16x8LtS => stack_op!(binary Value128, |a, b| a.i16x8_lt_s(b)), - I32x4LtS => stack_op!(binary Value128, |a, b| a.i32x4_lt_s(b)), - I64x2LtS => stack_op!(binary Value128, |a, b| a.i64x2_lt_s(b)), - I8x16LtU => stack_op!(binary Value128, |a, b| a.i8x16_lt_u(b)), - I16x8LtU => stack_op!(binary Value128, |a, b| a.i16x8_lt_u(b)), - I32x4LtU => stack_op!(binary Value128, |a, b| a.i32x4_lt_u(b)), - F32x4Lt => stack_op!(binary Value128, |a, b| a.f32x4_lt(b)), - F64x2Lt => stack_op!(binary Value128, |a, b| a.f64x2_lt(b)), - F32x4Gt => stack_op!(binary Value128, |a, b| a.f32x4_gt(b)), - F64x2Gt => stack_op!(binary Value128, |a, b| a.f64x2_gt(b)), - I8x16GtS => stack_op!(binary Value128, |a, b| a.i8x16_gt_s(b)), - I16x8GtS => stack_op!(binary Value128, |a, b| a.i16x8_gt_s(b)), - I32x4GtS => stack_op!(binary Value128, |a, b| a.i32x4_gt_s(b)), - I64x2GtS => stack_op!(binary Value128, |a, b| a.i64x2_gt_s(b)), - I64x2LeS => stack_op!(binary Value128, |a, b| a.i64x2_le_s(b)), - F32x4Le => stack_op!(binary Value128, |a, b| a.f32x4_le(b)), - F64x2Le => stack_op!(binary Value128, |a, b| a.f64x2_le(b)), - I8x16GtU => stack_op!(binary Value128, |a, b| a.i8x16_gt_u(b)), - I16x8GtU => stack_op!(binary Value128, |a, b| a.i16x8_gt_u(b)), - I32x4GtU => stack_op!(binary Value128, |a, b| a.i32x4_gt_u(b)), - F32x4Ge => stack_op!(binary Value128, |a, b| a.f32x4_ge(b)), - F64x2Ge => stack_op!(binary Value128, |a, b| a.f64x2_ge(b)), - I8x16LeS => stack_op!(binary Value128, |a, b| a.i8x16_le_s(b)), - I16x8LeS => stack_op!(binary Value128, |a, b| a.i16x8_le_s(b)), - I32x4LeS => stack_op!(binary Value128, |a, b| a.i32x4_le_s(b)), - I8x16LeU => stack_op!(binary Value128, |a, b| a.i8x16_le_u(b)), - I16x8LeU => stack_op!(binary Value128, |a, b| a.i16x8_le_u(b)), - I32x4LeU => stack_op!(binary Value128, |a, b| a.i32x4_le_u(b)), - I8x16GeS => stack_op!(binary Value128, |a, b| a.i8x16_ge_s(b)), - I16x8GeS => stack_op!(binary Value128, |a, b| a.i16x8_ge_s(b)), - I32x4GeS => stack_op!(binary Value128, |a, b| a.i32x4_ge_s(b)), - I64x2GeS => stack_op!(binary Value128, |a, b| a.i64x2_ge_s(b)), - I8x16GeU => stack_op!(binary Value128, |a, b| a.i8x16_ge_u(b)), - I16x8GeU => stack_op!(binary Value128, |a, b| a.i16x8_ge_u(b)), - I32x4GeU => stack_op!(binary Value128, |a, b| a.i32x4_ge_u(b)), - I8x16Abs => stack_op!(unary Value128, |a| a.i8x16_abs()), - I16x8Abs => stack_op!(unary Value128, |a| a.i16x8_abs()), - I32x4Abs => stack_op!(unary Value128, |a| a.i32x4_abs()), - I64x2Abs => stack_op!(unary Value128, |a| a.i64x2_abs()), - I8x16Neg => stack_op!(unary Value128, |a| a.i8x16_neg()), - I16x8Neg => stack_op!(unary Value128, |a| a.i16x8_neg()), - I32x4Neg => stack_op!(unary Value128, |a| a.i32x4_neg()), - I64x2Neg => stack_op!(unary Value128, |a| a.i64x2_neg()), - I8x16AllTrue => stack_op!(unary Value128 => i32, |v| v.i8x16_all_true() as i32), - I16x8AllTrue => stack_op!(unary Value128 => i32, |v| v.i16x8_all_true() as i32), - I32x4AllTrue => stack_op!(unary Value128 => i32, |v| v.i32x4_all_true() as i32), - I64x2AllTrue => stack_op!(unary Value128 => i32, |v| v.i64x2_all_true() as i32), - I8x16Bitmask => stack_op!(unary Value128 => i32, |v| v.i8x16_bitmask() as i32), - I16x8Bitmask => stack_op!(unary Value128 => i32, |v| v.i16x8_bitmask() as i32), - I32x4Bitmask => stack_op!(unary Value128 => i32, |v| v.i32x4_bitmask() as i32), - I64x2Bitmask => stack_op!(unary Value128 => i32, |v| v.i64x2_bitmask() as i32), - I8x16Shl => stack_op!(binary i32, Value128, |a, b| b.i8x16_shl(a as u32)), - I16x8Shl => stack_op!(binary i32, Value128, |a, b| b.i16x8_shl(a as u32)), - I32x4Shl => stack_op!(binary i32, Value128, |a, b| b.i32x4_shl(a as u32)), - I64x2Shl => stack_op!(binary i32, Value128, |a, b| b.i64x2_shl(a as u32)), - I8x16ShrS => stack_op!(binary i32, Value128, |a, b| b.i8x16_shr_s(a as u32)), - I16x8ShrS => stack_op!(binary i32, Value128, |a, b| b.i16x8_shr_s(a as u32)), - I32x4ShrS => stack_op!(binary i32, Value128, |a, b| b.i32x4_shr_s(a as u32)), - I64x2ShrS => stack_op!(binary i32, Value128, |a, b| b.i64x2_shr_s(a as u32)), - I8x16ShrU => stack_op!(binary i32, Value128, |a, b| b.i8x16_shr_u(a as u32)), - I16x8ShrU => stack_op!(binary i32, Value128, |a, b| b.i16x8_shr_u(a as u32)), - I32x4ShrU => stack_op!(binary i32, Value128, |a, b| b.i32x4_shr_u(a as u32)), - I64x2ShrU => stack_op!(binary i32, Value128, |a, b| b.i64x2_shr_u(a as u32)), - I8x16Add => stack_op!(binary Value128, |a, b| a.i8x16_add(b)), - I16x8Add => stack_op!(binary Value128, |a, b| a.i16x8_add(b)), - I32x4Add => stack_op!(binary Value128, |a, b| a.i32x4_add(b)), - I64x2Add => stack_op!(binary Value128, |a, b| a.i64x2_add(b)), - I8x16Sub => stack_op!(binary Value128, |a, b| a.i8x16_sub(b)), - I16x8Sub => stack_op!(binary Value128, |a, b| a.i16x8_sub(b)), - I32x4Sub => stack_op!(binary Value128, |a, b| a.i32x4_sub(b)), - I64x2Sub => stack_op!(binary Value128, |a, b| a.i64x2_sub(b)), - I8x16MinS => stack_op!(binary Value128, |a, b| a.i8x16_min_s(b)), - I16x8MinS => stack_op!(binary Value128, |a, b| a.i16x8_min_s(b)), - I32x4MinS => stack_op!(binary Value128, |a, b| a.i32x4_min_s(b)), - I8x16MinU => stack_op!(binary Value128, |a, b| a.i8x16_min_u(b)), - I16x8MinU => stack_op!(binary Value128, |a, b| a.i16x8_min_u(b)), - I32x4MinU => stack_op!(binary Value128, |a, b| a.i32x4_min_u(b)), - I8x16MaxS => stack_op!(binary Value128, |a, b| a.i8x16_max_s(b)), - I16x8MaxS => stack_op!(binary Value128, |a, b| a.i16x8_max_s(b)), - I32x4MaxS => stack_op!(binary Value128, |a, b| a.i32x4_max_s(b)), - I8x16MaxU => stack_op!(binary Value128, |a, b| a.i8x16_max_u(b)), - I16x8MaxU => stack_op!(binary Value128, |a, b| a.i16x8_max_u(b)), - I32x4MaxU => stack_op!(binary Value128, |a, b| a.i32x4_max_u(b)), - I64x2Mul => stack_op!(binary Value128, |a, b| a.i64x2_mul(b)), - I16x8Mul => stack_op!(binary Value128, |a, b| a.i16x8_mul(b)), - I32x4Mul => stack_op!(binary Value128, |a, b| a.i32x4_mul(b)), - I8x16NarrowI16x8S => stack_op!(binary Value128, |a, b| Value128::i8x16_narrow_i16x8_s(a, b)), - I8x16NarrowI16x8U => stack_op!(binary Value128, |a, b| Value128::i8x16_narrow_i16x8_u(a, b)), - I16x8NarrowI32x4S => stack_op!(binary Value128, |a, b| Value128::i16x8_narrow_i32x4_s(a, b)), - I16x8NarrowI32x4U => stack_op!(binary Value128, |a, b| Value128::i16x8_narrow_i32x4_u(a, b)), - I8x16AddSatS => stack_op!(binary Value128, |a, b| a.i8x16_add_sat_s(b)), - I16x8AddSatS => stack_op!(binary Value128, |a, b| a.i16x8_add_sat_s(b)), - I8x16AddSatU => stack_op!(binary Value128, |a, b| a.i8x16_add_sat_u(b)), - I16x8AddSatU => stack_op!(binary Value128, |a, b| a.i16x8_add_sat_u(b)), - I8x16SubSatS => stack_op!(binary Value128, |a, b| a.i8x16_sub_sat_s(b)), - I16x8SubSatS => stack_op!(binary Value128, |a, b| a.i16x8_sub_sat_s(b)), - I8x16SubSatU => stack_op!(binary Value128, |a, b| a.i8x16_sub_sat_u(b)), - I16x8SubSatU => stack_op!(binary Value128, |a, b| a.i16x8_sub_sat_u(b)), - I8x16AvgrU => stack_op!(binary Value128, |a, b| a.i8x16_avgr_u(b)), - I16x8AvgrU => stack_op!(binary Value128, |a, b| a.i16x8_avgr_u(b)), - I16x8ExtAddPairwiseI8x16S => stack_op!(unary Value128, |a| a.i16x8_extadd_pairwise_i8x16_s()), - I16x8ExtAddPairwiseI8x16U => stack_op!(unary Value128, |a| a.i16x8_extadd_pairwise_i8x16_u()), - I32x4ExtAddPairwiseI16x8S => stack_op!(unary Value128, |a| a.i32x4_extadd_pairwise_i16x8_s()), - I32x4ExtAddPairwiseI16x8U => stack_op!(unary Value128, |a| a.i32x4_extadd_pairwise_i16x8_u()), - I16x8ExtMulLowI8x16S => stack_op!(binary Value128, |a, b| a.i16x8_extmul_low_i8x16_s(b)), - I16x8ExtMulLowI8x16U => stack_op!(binary Value128, |a, b| a.i16x8_extmul_low_i8x16_u(b)), - I16x8ExtMulHighI8x16S => stack_op!(binary Value128, |a, b| a.i16x8_extmul_high_i8x16_s(b)), - I16x8ExtMulHighI8x16U => stack_op!(binary Value128, |a, b| a.i16x8_extmul_high_i8x16_u(b)), - I32x4ExtMulLowI16x8S => stack_op!(binary Value128, |a, b| a.i32x4_extmul_low_i16x8_s(b)), - I32x4ExtMulLowI16x8U => stack_op!(binary Value128, |a, b| a.i32x4_extmul_low_i16x8_u(b)), - I32x4ExtMulHighI16x8S => stack_op!(binary Value128, |a, b| a.i32x4_extmul_high_i16x8_s(b)), - I32x4ExtMulHighI16x8U => stack_op!(binary Value128, |a, b| a.i32x4_extmul_high_i16x8_u(b)), - I64x2ExtMulLowI32x4S => stack_op!(binary Value128, |a, b| a.i64x2_extmul_low_i32x4_s(b)), - I64x2ExtMulLowI32x4U => stack_op!(binary Value128, |a, b| a.i64x2_extmul_low_i32x4_u(b)), - I64x2ExtMulHighI32x4S => stack_op!(binary Value128, |a, b| a.i64x2_extmul_high_i32x4_s(b)), - I64x2ExtMulHighI32x4U => stack_op!(binary Value128, |a, b| a.i64x2_extmul_high_i32x4_u(b)), - I16x8ExtendLowI8x16S => stack_op!(unary Value128, |a| a.i16x8_extend_low_i8x16_s()), - I16x8ExtendLowI8x16U => stack_op!(unary Value128, |a| a.i16x8_extend_low_i8x16_u()), - I16x8ExtendHighI8x16S => stack_op!(unary Value128, |a| a.i16x8_extend_high_i8x16_s()), - I16x8ExtendHighI8x16U => stack_op!(unary Value128, |a| a.i16x8_extend_high_i8x16_u()), - I32x4ExtendLowI16x8S => stack_op!(unary Value128, |a| a.i32x4_extend_low_i16x8_s()), - I32x4ExtendLowI16x8U => stack_op!(unary Value128, |a| a.i32x4_extend_low_i16x8_u()), - I32x4ExtendHighI16x8S => stack_op!(unary Value128, |a| a.i32x4_extend_high_i16x8_s()), - I32x4ExtendHighI16x8U => stack_op!(unary Value128, |a| a.i32x4_extend_high_i16x8_u()), - I64x2ExtendLowI32x4S => stack_op!(unary Value128, |a| a.i64x2_extend_low_i32x4_s()), - I64x2ExtendLowI32x4U => stack_op!(unary Value128, |a| a.i64x2_extend_low_i32x4_u()), - I64x2ExtendHighI32x4S => stack_op!(unary Value128, |a| a.i64x2_extend_high_i32x4_s()), - I64x2ExtendHighI32x4U => stack_op!(unary Value128, |a| a.i64x2_extend_high_i32x4_u()), - I8x16Popcnt => stack_op!(unary Value128, |v| v.i8x16_popcnt()), - I8x16Shuffle(idx) => stack_op!(binary Value128, |a, b| Value128::i8x16_shuffle(a, b, Value128(self.func.data.v128_const(*idx)))), - I16x8Q15MulrSatS => stack_op!(binary Value128, |a, b| a.i16x8_q15mulr_sat_s(b)), - I32x4DotI16x8S => stack_op!(binary Value128, |a, b| a.i32x4_dot_i16x8_s(b)), - I8x16RelaxedLaneselect => stack_op!(ternary Value128, |a, b, c| Value128::i8x16_relaxed_laneselect(a, b, c)), - I16x8RelaxedLaneselect => stack_op!(ternary Value128, |a, b, c| Value128::i16x8_relaxed_laneselect(a, b, c)), - I32x4RelaxedLaneselect => stack_op!(ternary Value128, |a, b, c| Value128::i32x4_relaxed_laneselect(a, b, c)), - I64x2RelaxedLaneselect => stack_op!(ternary Value128, |a, b, c| Value128::i64x2_relaxed_laneselect(a, b, c)), - I16x8RelaxedQ15mulrS => stack_op!(binary Value128, |a, b| a.i16x8_relaxed_q15mulr_s(b)), - I16x8RelaxedDotI8x16I7x16S => stack_op!(binary Value128, |a, b| a.i16x8_relaxed_dot_i8x16_i7x16_s(b)), - I32x4RelaxedDotI8x16I7x16AddS => stack_op!(ternary Value128, |a, b, c| a.i32x4_relaxed_dot_i8x16_i7x16_add_s(b, c)), - F32x4Ceil => stack_op!(unary Value128, |v| v.f32x4_ceil()), - F64x2Ceil => stack_op!(unary Value128, |v| v.f64x2_ceil()), - F32x4Floor => stack_op!(unary Value128, |v| v.f32x4_floor()), - F64x2Floor => stack_op!(unary Value128, |v| v.f64x2_floor()), - F32x4Trunc => stack_op!(unary Value128, |v| v.f32x4_trunc()), - F64x2Trunc => stack_op!(unary Value128, |v| v.f64x2_trunc()), - F32x4Nearest => stack_op!(unary Value128, |v| v.f32x4_nearest()), - F64x2Nearest => stack_op!(unary Value128, |v| v.f64x2_nearest()), - F32x4Abs => stack_op!(unary Value128, |v| v.f32x4_abs()), - F64x2Abs => stack_op!(unary Value128, |v| v.f64x2_abs()), - F32x4Neg => stack_op!(unary Value128, |v| v.f32x4_neg()), - F64x2Neg => stack_op!(unary Value128, |v| v.f64x2_neg()), - F32x4Sqrt => stack_op!(unary Value128, |v| v.f32x4_sqrt()), - F64x2Sqrt => stack_op!(unary Value128, |v| v.f64x2_sqrt()), - F32x4Add => stack_op!(binary Value128, |a, b| a.f32x4_add(b)), - F64x2Add => stack_op!(binary Value128, |a, b| a.f64x2_add(b)), - F32x4Sub => stack_op!(binary Value128, |a, b| a.f32x4_sub(b)), - F64x2Sub => stack_op!(binary Value128, |a, b| a.f64x2_sub(b)), - F32x4Mul => stack_op!(binary Value128, |a, b| a.f32x4_mul(b)), - F64x2Mul => stack_op!(binary Value128, |a, b| a.f64x2_mul(b)), - F32x4Div => stack_op!(binary Value128, |a, b| a.f32x4_div(b)), - F64x2Div => stack_op!(binary Value128, |a, b| a.f64x2_div(b)), - F32x4Min => stack_op!(binary Value128, |a, b| a.f32x4_min(b)), - F64x2Min => stack_op!(binary Value128, |a, b| a.f64x2_min(b)), - F32x4Max => stack_op!(binary Value128, |a, b| a.f32x4_max(b)), - F64x2Max => stack_op!(binary Value128, |a, b| a.f64x2_max(b)), - F32x4PMin => stack_op!(binary Value128, |a, b| a.f32x4_pmin(b)), - F32x4PMax => stack_op!(binary Value128, |a, b| a.f32x4_pmax(b)), - F64x2PMin => stack_op!(binary Value128, |a, b| a.f64x2_pmin(b)), - F64x2PMax => stack_op!(binary Value128, |a, b| a.f64x2_pmax(b)), - F32x4RelaxedMadd => stack_op!(ternary Value128, |a, b, c| a.f32x4_relaxed_madd(b, c)), - F32x4RelaxedNmadd => stack_op!(ternary Value128, |a, b, c| a.f32x4_relaxed_nmadd(b, c)), - F64x2RelaxedMadd => stack_op!(ternary Value128, |a, b, c| a.f64x2_relaxed_madd(b, c)), - F64x2RelaxedNmadd => stack_op!(ternary Value128, |a, b, c| a.f64x2_relaxed_nmadd(b, c)), - F32x4RelaxedMin => stack_op!(binary Value128, |a, b| a.f32x4_relaxed_min(b)), - F32x4RelaxedMax => stack_op!(binary Value128, |a, b| a.f32x4_relaxed_max(b)), - F64x2RelaxedMin => stack_op!(binary Value128, |a, b| a.f64x2_relaxed_min(b)), - F64x2RelaxedMax => stack_op!(binary Value128, |a, b| a.f64x2_relaxed_max(b)), - I32x4TruncSatF32x4S => stack_op!(unary Value128, |v| v.i32x4_trunc_sat_f32x4_s()), - I32x4TruncSatF32x4U => stack_op!(unary Value128, |v| v.i32x4_trunc_sat_f32x4_u()), - F32x4ConvertI32x4S => stack_op!(unary Value128, |v| v.f32x4_convert_i32x4_s()), - F32x4ConvertI32x4U => stack_op!(unary Value128, |v| v.f32x4_convert_i32x4_u()), - F64x2ConvertLowI32x4S => stack_op!(unary Value128, |v| v.f64x2_convert_low_i32x4_s()), - F64x2ConvertLowI32x4U => stack_op!(unary Value128, |v| v.f64x2_convert_low_i32x4_u()), - F32x4DemoteF64x2Zero => stack_op!(unary Value128, |v| v.f32x4_demote_f64x2_zero()), - F64x2PromoteLowF32x4 => stack_op!(unary Value128, |v| v.f64x2_promote_low_f32x4()), - I32x4TruncSatF64x2SZero => stack_op!(unary Value128, |v| v.i32x4_trunc_sat_f64x2_s_zero()), - I32x4TruncSatF64x2UZero => stack_op!(unary Value128, |v| v.i32x4_trunc_sat_f64x2_u_zero()), - I32x4RelaxedTruncF32x4S => stack_op!(unary Value128, |v| v.i32x4_relaxed_trunc_f32x4_s()), - I32x4RelaxedTruncF32x4U => stack_op!(unary Value128, |v| v.i32x4_relaxed_trunc_f32x4_u()), - I32x4RelaxedTruncF64x2SZero => stack_op!(unary Value128, |v| v.i32x4_relaxed_trunc_f64x2_s_zero()), - I32x4RelaxedTruncF64x2UZero => stack_op!(unary Value128, |v| v.i32x4_relaxed_trunc_f64x2_u_zero()), + I8x16ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i8x16_replace_lane(*lane, value as i8)), + I16x8ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i16x8_replace_lane(*lane, value as i16)), + I32x4ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i32x4_replace_lane(*lane, value)), + I64x2ReplaceLane(lane) => exec_op!(binary_mixed i64, Value128 => Value128, |value, vec| vec.i64x2_replace_lane(*lane, value)), + F32x4ReplaceLane(lane) => exec_op!(binary_mixed f32, Value128 => Value128, |value, vec| vec.f32x4_replace_lane(*lane, value)), + F64x2ReplaceLane(lane) => exec_op!(binary_mixed f64, Value128 => Value128, |value, vec| vec.f64x2_replace_lane(*lane, value)), + I8x16Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i8(v as i8)), + I16x8Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i16(v as i16)), + I32x4Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i32(v)), + I64x2Splat => exec_op!(unary i64 => Value128, |v| Value128::splat_i64(v)), + F32x4Splat => exec_op!(unary f32 => Value128, |v| Value128::splat_f32(v)), + F64x2Splat => exec_op!(unary f64 => Value128, |v| Value128::splat_f64(v)), + I8x16Eq => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_eq(b)), + I16x8Eq => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_eq(b)), + I32x4Eq => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_eq(b)), + I64x2Eq => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_eq(b)), + F32x4Eq => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_eq(b)), + F64x2Eq => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_eq(b)), + I8x16Ne => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_ne(b)), + I16x8Ne => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_ne(b)), + I32x4Ne => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_ne(b)), + I64x2Ne => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_ne(b)), + F32x4Ne => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_ne(b)), + F64x2Ne => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_ne(b)), + I8x16LtS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_lt_s(b)), + I16x8LtS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_lt_s(b)), + I32x4LtS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_lt_s(b)), + I64x2LtS => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_lt_s(b)), + I8x16LtU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_lt_u(b)), + I16x8LtU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_lt_u(b)), + I32x4LtU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_lt_u(b)), + F32x4Lt => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_lt(b)), + F64x2Lt => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_lt(b)), + F32x4Gt => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_gt(b)), + F64x2Gt => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_gt(b)), + I8x16GtS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_gt_s(b)), + I16x8GtS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_gt_s(b)), + I32x4GtS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_gt_s(b)), + I64x2GtS => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_gt_s(b)), + I64x2LeS => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_le_s(b)), + F32x4Le => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_le(b)), + F64x2Le => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_le(b)), + I8x16GtU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_gt_u(b)), + I16x8GtU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_gt_u(b)), + I32x4GtU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_gt_u(b)), + F32x4Ge => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_ge(b)), + F64x2Ge => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_ge(b)), + I8x16LeS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_le_s(b)), + I16x8LeS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_le_s(b)), + I32x4LeS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_le_s(b)), + I8x16LeU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_le_u(b)), + I16x8LeU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_le_u(b)), + I32x4LeU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_le_u(b)), + I8x16GeS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_ge_s(b)), + I16x8GeS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_ge_s(b)), + I32x4GeS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_ge_s(b)), + I64x2GeS => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_ge_s(b)), + I8x16GeU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_ge_u(b)), + I16x8GeU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_ge_u(b)), + I32x4GeU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_ge_u(b)), + I8x16Abs => exec_op!(unary Value128 => Value128, |a| a.i8x16_abs()), + I16x8Abs => exec_op!(unary Value128 => Value128, |a| a.i16x8_abs()), + I32x4Abs => exec_op!(unary Value128 => Value128, |a| a.i32x4_abs()), + I64x2Abs => exec_op!(unary Value128 => Value128, |a| a.i64x2_abs()), + I8x16Neg => exec_op!(unary Value128 => Value128, |a| a.i8x16_neg()), + I16x8Neg => exec_op!(unary Value128 => Value128, |a| a.i16x8_neg()), + I32x4Neg => exec_op!(unary Value128 => Value128, |a| a.i32x4_neg()), + I64x2Neg => exec_op!(unary Value128 => Value128, |a| a.i64x2_neg()), + I8x16AllTrue => exec_op!(unary Value128 => i32, |v| v.i8x16_all_true() as i32), + I16x8AllTrue => exec_op!(unary Value128 => i32, |v| v.i16x8_all_true() as i32), + I32x4AllTrue => exec_op!(unary Value128 => i32, |v| v.i32x4_all_true() as i32), + I64x2AllTrue => exec_op!(unary Value128 => i32, |v| v.i64x2_all_true() as i32), + I8x16Bitmask => exec_op!(unary Value128 => i32, |v| v.i8x16_bitmask() as i32), + I16x8Bitmask => exec_op!(unary Value128 => i32, |v| v.i16x8_bitmask() as i32), + I32x4Bitmask => exec_op!(unary Value128 => i32, |v| v.i32x4_bitmask() as i32), + I64x2Bitmask => exec_op!(unary Value128 => i32, |v| v.i64x2_bitmask() as i32), + I8x16Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i8x16_shl(a as u32)), + I16x8Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i16x8_shl(a as u32)), + I32x4Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i32x4_shl(a as u32)), + I64x2Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i64x2_shl(a as u32)), + I8x16ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i8x16_shr_s(a as u32)), + I16x8ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i16x8_shr_s(a as u32)), + I32x4ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i32x4_shr_s(a as u32)), + I64x2ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i64x2_shr_s(a as u32)), + I8x16ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i8x16_shr_u(a as u32)), + I16x8ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i16x8_shr_u(a as u32)), + I32x4ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i32x4_shr_u(a as u32)), + I64x2ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i64x2_shr_u(a as u32)), + I8x16Add => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_add(b)), + I16x8Add => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_add(b)), + I32x4Add => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_add(b)), + I64x2Add => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_add(b)), + I8x16Sub => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_sub(b)), + I16x8Sub => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_sub(b)), + I32x4Sub => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_sub(b)), + I64x2Sub => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_sub(b)), + I8x16MinS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_min_s(b)), + I16x8MinS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_min_s(b)), + I32x4MinS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_min_s(b)), + I8x16MinU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_min_u(b)), + I16x8MinU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_min_u(b)), + I32x4MinU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_min_u(b)), + I8x16MaxS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_max_s(b)), + I16x8MaxS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_max_s(b)), + I32x4MaxS => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_max_s(b)), + I8x16MaxU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_max_u(b)), + I16x8MaxU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_max_u(b)), + I32x4MaxU => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_max_u(b)), + I64x2Mul => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_mul(b)), + I16x8Mul => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_mul(b)), + I32x4Mul => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_mul(b)), + I8x16NarrowI16x8S => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_narrow_i16x8_s(a, b)), + I8x16NarrowI16x8U => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_narrow_i16x8_u(a, b)), + I16x8NarrowI32x4S => exec_op!(binary Value128 => Value128, |a, b| Value128::i16x8_narrow_i32x4_s(a, b)), + I16x8NarrowI32x4U => exec_op!(binary Value128 => Value128, |a, b| Value128::i16x8_narrow_i32x4_u(a, b)), + I8x16AddSatS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_add_sat_s(b)), + I16x8AddSatS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_add_sat_s(b)), + I8x16AddSatU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_add_sat_u(b)), + I16x8AddSatU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_add_sat_u(b)), + I8x16SubSatS => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_sub_sat_s(b)), + I16x8SubSatS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_sub_sat_s(b)), + I8x16SubSatU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_sub_sat_u(b)), + I16x8SubSatU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_sub_sat_u(b)), + I8x16AvgrU => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_avgr_u(b)), + I16x8AvgrU => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_avgr_u(b)), + I16x8ExtAddPairwiseI8x16S => exec_op!(unary Value128 => Value128, |a| a.i16x8_extadd_pairwise_i8x16_s()), + I16x8ExtAddPairwiseI8x16U => exec_op!(unary Value128 => Value128, |a| a.i16x8_extadd_pairwise_i8x16_u()), + I32x4ExtAddPairwiseI16x8S => exec_op!(unary Value128 => Value128, |a| a.i32x4_extadd_pairwise_i16x8_s()), + I32x4ExtAddPairwiseI16x8U => exec_op!(unary Value128 => Value128, |a| a.i32x4_extadd_pairwise_i16x8_u()), + I16x8ExtMulLowI8x16S => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_extmul_low_i8x16_s(b)), + I16x8ExtMulLowI8x16U => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_extmul_low_i8x16_u(b)), + I16x8ExtMulHighI8x16S => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_extmul_high_i8x16_s(b)), + I16x8ExtMulHighI8x16U => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_extmul_high_i8x16_u(b)), + I32x4ExtMulLowI16x8S => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_extmul_low_i16x8_s(b)), + I32x4ExtMulLowI16x8U => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_extmul_low_i16x8_u(b)), + I32x4ExtMulHighI16x8S => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_extmul_high_i16x8_s(b)), + I32x4ExtMulHighI16x8U => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_extmul_high_i16x8_u(b)), + I64x2ExtMulLowI32x4S => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_extmul_low_i32x4_s(b)), + I64x2ExtMulLowI32x4U => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_extmul_low_i32x4_u(b)), + I64x2ExtMulHighI32x4S => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_extmul_high_i32x4_s(b)), + I64x2ExtMulHighI32x4U => exec_op!(binary Value128 => Value128, |a, b| a.i64x2_extmul_high_i32x4_u(b)), + I16x8ExtendLowI8x16S => exec_op!(unary Value128 => Value128, |a| a.i16x8_extend_low_i8x16_s()), + I16x8ExtendLowI8x16U => exec_op!(unary Value128 => Value128, |a| a.i16x8_extend_low_i8x16_u()), + I16x8ExtendHighI8x16S => exec_op!(unary Value128 => Value128, |a| a.i16x8_extend_high_i8x16_s()), + I16x8ExtendHighI8x16U => exec_op!(unary Value128 => Value128, |a| a.i16x8_extend_high_i8x16_u()), + I32x4ExtendLowI16x8S => exec_op!(unary Value128 => Value128, |a| a.i32x4_extend_low_i16x8_s()), + I32x4ExtendLowI16x8U => exec_op!(unary Value128 => Value128, |a| a.i32x4_extend_low_i16x8_u()), + I32x4ExtendHighI16x8S => exec_op!(unary Value128 => Value128, |a| a.i32x4_extend_high_i16x8_s()), + I32x4ExtendHighI16x8U => exec_op!(unary Value128 => Value128, |a| a.i32x4_extend_high_i16x8_u()), + I64x2ExtendLowI32x4S => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_low_i32x4_s()), + I64x2ExtendLowI32x4U => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_low_i32x4_u()), + I64x2ExtendHighI32x4S => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_s()), + I64x2ExtendHighI32x4U => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_u()), + I8x16Popcnt => exec_op!(unary Value128 => Value128, |v| v.i8x16_popcnt()), + I8x16Shuffle(idx) => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_shuffle(a, b, Value128(self.func.data.v128_const(*idx)))), + I16x8Q15MulrSatS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_q15mulr_sat_s(b)), + I32x4DotI16x8S => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_dot_i16x8_s(b)), + I8x16RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i8x16_relaxed_laneselect(a, b, c)), + I16x8RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i16x8_relaxed_laneselect(a, b, c)), + I32x4RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i32x4_relaxed_laneselect(a, b, c)), + I64x2RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i64x2_relaxed_laneselect(a, b, c)), + I16x8RelaxedQ15mulrS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_relaxed_q15mulr_s(b)), + I16x8RelaxedDotI8x16I7x16S => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_relaxed_dot_i8x16_i7x16_s(b)), + I32x4RelaxedDotI8x16I7x16AddS => exec_op!(ternary Value128 => Value128, |a, b, c| a.i32x4_relaxed_dot_i8x16_i7x16_add_s(b, c)), + F32x4Ceil => exec_op!(unary Value128 => Value128, |v| v.f32x4_ceil()), + F64x2Ceil => exec_op!(unary Value128 => Value128, |v| v.f64x2_ceil()), + F32x4Floor => exec_op!(unary Value128 => Value128, |v| v.f32x4_floor()), + F64x2Floor => exec_op!(unary Value128 => Value128, |v| v.f64x2_floor()), + F32x4Trunc => exec_op!(unary Value128 => Value128, |v| v.f32x4_trunc()), + F64x2Trunc => exec_op!(unary Value128 => Value128, |v| v.f64x2_trunc()), + F32x4Nearest => exec_op!(unary Value128 => Value128, |v| v.f32x4_nearest()), + F64x2Nearest => exec_op!(unary Value128 => Value128, |v| v.f64x2_nearest()), + F32x4Abs => exec_op!(unary Value128 => Value128, |v| v.f32x4_abs()), + F64x2Abs => exec_op!(unary Value128 => Value128, |v| v.f64x2_abs()), + F32x4Neg => exec_op!(unary Value128 => Value128, |v| v.f32x4_neg()), + F64x2Neg => exec_op!(unary Value128 => Value128, |v| v.f64x2_neg()), + F32x4Sqrt => exec_op!(unary Value128 => Value128, |v| v.f32x4_sqrt()), + F64x2Sqrt => exec_op!(unary Value128 => Value128, |v| v.f64x2_sqrt()), + F32x4Add => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_add(b)), + F64x2Add => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_add(b)), + F32x4Sub => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_sub(b)), + F64x2Sub => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_sub(b)), + F32x4Mul => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_mul(b)), + F64x2Mul => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_mul(b)), + F32x4Div => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_div(b)), + F64x2Div => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_div(b)), + F32x4Min => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_min(b)), + F64x2Min => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_min(b)), + F32x4Max => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_max(b)), + F64x2Max => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_max(b)), + F32x4PMin => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_pmin(b)), + F32x4PMax => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_pmax(b)), + F64x2PMin => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_pmin(b)), + F64x2PMax => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_pmax(b)), + F32x4RelaxedMadd => exec_op!(ternary Value128 => Value128, |a, b, c| a.f32x4_relaxed_madd(b, c)), + F32x4RelaxedNmadd => exec_op!(ternary Value128 => Value128, |a, b, c| a.f32x4_relaxed_nmadd(b, c)), + F64x2RelaxedMadd => exec_op!(ternary Value128 => Value128, |a, b, c| a.f64x2_relaxed_madd(b, c)), + F64x2RelaxedNmadd => exec_op!(ternary Value128 => Value128, |a, b, c| a.f64x2_relaxed_nmadd(b, c)), + F32x4RelaxedMin => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_relaxed_min(b)), + F32x4RelaxedMax => exec_op!(binary Value128 => Value128, |a, b| a.f32x4_relaxed_max(b)), + F64x2RelaxedMin => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_relaxed_min(b)), + F64x2RelaxedMax => exec_op!(binary Value128 => Value128, |a, b| a.f64x2_relaxed_max(b)), + I32x4TruncSatF32x4S => exec_op!(unary Value128 => Value128, |v| v.i32x4_trunc_sat_f32x4_s()), + I32x4TruncSatF32x4U => exec_op!(unary Value128 => Value128, |v| v.i32x4_trunc_sat_f32x4_u()), + F32x4ConvertI32x4S => exec_op!(unary Value128 => Value128, |v| v.f32x4_convert_i32x4_s()), + F32x4ConvertI32x4U => exec_op!(unary Value128 => Value128, |v| v.f32x4_convert_i32x4_u()), + F64x2ConvertLowI32x4S => exec_op!(unary Value128 => Value128, |v| v.f64x2_convert_low_i32x4_s()), + F64x2ConvertLowI32x4U => exec_op!(unary Value128 => Value128, |v| v.f64x2_convert_low_i32x4_u()), + F32x4DemoteF64x2Zero => exec_op!(unary Value128 => Value128, |v| v.f32x4_demote_f64x2_zero()), + F64x2PromoteLowF32x4 => exec_op!(unary Value128 => Value128, |v| v.f64x2_promote_low_f32x4()), + I32x4TruncSatF64x2SZero => exec_op!(unary Value128 => Value128, |v| v.i32x4_trunc_sat_f64x2_s_zero()), + I32x4TruncSatF64x2UZero => exec_op!(unary Value128 => Value128, |v| v.i32x4_trunc_sat_f64x2_u_zero()), + I32x4RelaxedTruncF32x4S => exec_op!(unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f32x4_s()), + I32x4RelaxedTruncF32x4U => exec_op!(unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f32x4_u()), + I32x4RelaxedTruncF64x2SZero => exec_op!(unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f64x2_s_zero()), + I32x4RelaxedTruncF64x2UZero => exec_op!(unary Value128 => Value128, |v| v.i32x4_relaxed_trunc_f64x2_u_zero()), }; self.cf.instr_ptr = instr_ptr + 1; @@ -859,148 +921,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(None) } - #[inline(always)] - fn jump_if(&mut self, condition: bool, ip: u32) -> bool { - if condition { - self.cf.instr_ptr = ip as usize; - } - condition - } - - #[inline(always)] - fn exec_jump_zero_32(&mut self, target_ip: u32) -> bool { - let cond = ::stack_pop(&mut self.store.value_stack) == 0; - self.jump_if(cond, target_ip) - } - - #[inline(always)] - fn exec_jump_non_zero_32(&mut self, target_ip: u32) -> bool { - let cond = ::stack_pop(&mut self.store.value_stack) != 0; - self.jump_if(cond, target_ip) - } - - #[inline(always)] - fn exec_jump_zero_64(&mut self, target_ip: u32) -> bool { - let cond = ::stack_pop(&mut self.store.value_stack) == 0; - self.jump_if(cond, target_ip) - } - - #[inline(always)] - fn exec_jump_non_zero_64(&mut self, target_ip: u32) -> bool { - let cond = ::stack_pop(&mut self.store.value_stack) != 0; - self.jump_if(cond, target_ip) - } - - #[inline(always)] - fn exec_jump_ref_null(&mut self, target_ip: u32) -> bool { - let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null(); - if is_null { - ValueRef::stack_pop(&mut self.store.value_stack); - } - self.jump_if(is_null, target_ip) - } - - #[inline(always)] - fn exec_jump_ref_non_null(&mut self, target_ip: u32) -> bool { - let is_non_null = !ValueRef::stack_peek(&self.store.value_stack).is_null(); - if !is_non_null { - ValueRef::stack_pop(&mut self.store.value_stack); - } - self.jump_if(is_non_null, target_ip) - } - - #[inline(always)] - fn exec_jump_local_zero_32(&mut self, target_ip: u32, local: LocalAddr) -> bool { - self.jump_if(Value32::local_get(&self.store.value_stack, &self.cf, local) == 0, target_ip) - } - - #[inline(always)] - fn exec_jump_local_non_zero_32(&mut self, target_ip: u32, local: LocalAddr) -> bool { - self.jump_if(Value32::local_get(&self.store.value_stack, &self.cf, local) != 0, target_ip) - } - - #[inline(always)] - fn exec_jump_local_zero_64(&mut self, target_ip: u32, local: LocalAddr) -> bool { - self.jump_if(Value64::local_get(&self.store.value_stack, &self.cf, local) == 0, target_ip) - } - - #[inline(always)] - fn exec_jump_local_non_zero_64(&mut self, target_ip: u32, local: LocalAddr) -> bool { - self.jump_if(Value64::local_get(&self.store.value_stack, &self.cf, local) != 0, target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_stack_const_32(&mut self, target_ip: u32, imm: i32, op: CmpOp) -> bool { - let condition = cmp_i32(::stack_pop(&mut self.store.value_stack), imm, op); - self.jump_if(condition, target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_stack_const_64(&mut self, target_ip: u32, imm: i64, op: CmpOp) -> bool { - let condition = cmp_i64(::stack_pop(&mut self.store.value_stack), imm, op); - self.jump_if(condition, target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_stack_local_32(&mut self, target_ip: u32, local: LocalAddr, op: CmpOp) -> bool { - let lhs = ::stack_pop(&mut self.store.value_stack); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, local); - self.jump_if(cmp_i32(lhs, rhs, op), target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_stack_local_64(&mut self, target_ip: u32, local: LocalAddr, op: CmpOp) -> bool { - let lhs = ::stack_pop(&mut self.store.value_stack); - let rhs = i64::local_get(&self.store.value_stack, &self.cf, local); - self.jump_if(cmp_i64(lhs, rhs, op), target_ip) - } - - #[inline(always)] - fn exec_inc_local_jump_32(&mut self, target_ip: u32, local: LocalAddr, delta: i32, on_zero: bool) -> bool { - let value = i32::local_get(&self.store.value_stack, &self.cf, local).wrapping_add(delta); - i32::local_set(&mut self.store.value_stack, &self.cf, local, value); - self.jump_if((value == 0) == on_zero, target_ip) - } - - #[inline(always)] - fn exec_inc_local_jump_cmp_local_32( - &mut self, - target_ip: u32, - local: LocalAddr, - delta: i32, - right: LocalAddr, - op: CmpOp, - ) -> bool { - let lhs = i32::local_get(&self.store.value_stack, &self.cf, local).wrapping_add(delta); - i32::local_set(&mut self.store.value_stack, &self.cf, local, lhs); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, right); - self.jump_if(cmp_i32(lhs, rhs, op), target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_local_const_32(&mut self, target_ip: u32, local: LocalAddr, imm: i32, op: CmpOp) -> bool { - self.jump_if(cmp_i32(i32::local_get(&self.store.value_stack, &self.cf, local), imm, op), target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_local_const_64(&mut self, target_ip: u32, local: LocalAddr, imm: i32, op: CmpOp) -> bool { - self.jump_if(cmp_i64(i64::local_get(&self.store.value_stack, &self.cf, local), i64::from(imm), op), target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_local_local_32(&mut self, target_ip: u32, left: LocalAddr, right: LocalAddr, op: CmpOp) -> bool { - let lhs = i32::local_get(&self.store.value_stack, &self.cf, left); - let rhs = i32::local_get(&self.store.value_stack, &self.cf, right); - self.jump_if(cmp_i32(lhs, rhs, op), target_ip) - } - - #[inline(always)] - fn exec_jump_cmp_local_local_64(&mut self, target_ip: u32, left: LocalAddr, right: LocalAddr, op: CmpOp) -> bool { - let lhs = i64::local_get(&self.store.value_stack, &self.cf, left); - let rhs = i64::local_get(&self.store.value_stack, &self.cf, right); - self.jump_if(cmp_i64(lhs, rhs, op), target_ip) - } - fn exec_branch_table(&mut self, default_ip: u32, start: u32, len: u32) { let idx = ::stack_pop(&mut self.store.value_stack); let target_ip = if idx >= 0 && (idx as u32) < len { @@ -1453,18 +1373,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - #[inline(always)] - fn exec_binop_acc_local(&mut self, acc: LocalAddr, mul: M, add: A) - where - T: InternalValue, - M: Fn(T, T) -> T, - A: Fn(T, T) -> T, - { - let rhs = T::stack_pop(&mut self.store.value_stack); - let lhs = T::stack_pop(&mut self.store.value_stack); - T::local_update(&mut self.store.value_stack, &self.cf, acc, |v| add(mul(lhs, rhs), v)); - } - #[inline(always)] fn exec_load_local_value, const N: usize>( &self, @@ -1520,10 +1428,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_const(&mut self, val: T) -> Result<(), Trap> { - self.store.value_stack.push(val) - } - fn exec_ref_is_null(&mut self) -> Result<(), Trap> { let is_null = i32::from(::stack_pop(&mut self.store.value_stack).is_null()); self.store.value_stack.push::(is_null) @@ -1540,7 +1444,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn canonical_ref_type(&self, ty: RefType) -> RefType { let Some(type_index) = ty.type_index() else { return ty }; RefType::new_concrete(ty.is_nullable(), self.module.resolve_type_addr(type_index)) - .expect("canonical type address fits in a reference") } fn exec_ref_matches(&self, ty: RefType) -> bool { @@ -2171,3 +2074,60 @@ fn cmp_i64(lhs: i64, rhs: i64, op: CmpOp) -> bool { CmpOp::GeU => (lhs as u64) >= (rhs as u64), } } + +fn exec_binop_32(op: BinOp, lhs: u32, rhs: u32) -> u32 { + match op { + BinOp::IAdd => lhs.wrapping_add(rhs), + BinOp::ISub => lhs.wrapping_sub(rhs), + BinOp::IMul => lhs.wrapping_mul(rhs), + BinOp::IAnd => lhs & rhs, + BinOp::IOr => lhs | rhs, + BinOp::IXor => lhs ^ rhs, + BinOp::IShl => (lhs as i32).wrapping_shl(rhs) as u32, + BinOp::IShrS => (lhs as i32).wrapping_shr(rhs) as u32, + BinOp::IShrU => lhs.wrapping_shr(rhs), + BinOp::IRotl => (lhs as i32).rotate_left(rhs) as u32, + BinOp::IRotr => (lhs as i32).rotate_right(rhs) as u32, + BinOp::FAdd => (f32::from_bits(lhs) + f32::from_bits(rhs)).to_bits(), + BinOp::FSub => (f32::from_bits(lhs) - f32::from_bits(rhs)).to_bits(), + BinOp::FMul => (f32::from_bits(lhs) * f32::from_bits(rhs)).to_bits(), + BinOp::FDiv => (f32::from_bits(lhs) / f32::from_bits(rhs)).to_bits(), + BinOp::FMin => f32::from_bits(lhs).tw_minimum(f32::from_bits(rhs)).to_bits(), + BinOp::FMax => f32::from_bits(lhs).tw_maximum(f32::from_bits(rhs)).to_bits(), + BinOp::FCopysign => f32::from_bits(lhs).copysign(f32::from_bits(rhs)).to_bits(), + } +} + +fn exec_binop_64(op: BinOp, lhs: u64, rhs: u64) -> u64 { + match op { + BinOp::IAdd => lhs.wrapping_add(rhs), + BinOp::ISub => lhs.wrapping_sub(rhs), + BinOp::IMul => lhs.wrapping_mul(rhs), + BinOp::IAnd => lhs & rhs, + BinOp::IOr => lhs | rhs, + BinOp::IXor => lhs ^ rhs, + BinOp::IShl => (lhs as i64).wrapping_shl(rhs as u32) as u64, + BinOp::IShrS => (lhs as i64).wrapping_shr(rhs as u32) as u64, + BinOp::IShrU => lhs.wrapping_shr(rhs as u32), + BinOp::IRotl => (lhs as i64).rotate_left(rhs as u32) as u64, + BinOp::IRotr => (lhs as i64).rotate_right(rhs as u32) as u64, + BinOp::FAdd => (f64::from_bits(lhs) + f64::from_bits(rhs)).to_bits(), + BinOp::FSub => (f64::from_bits(lhs) - f64::from_bits(rhs)).to_bits(), + BinOp::FMul => (f64::from_bits(lhs) * f64::from_bits(rhs)).to_bits(), + BinOp::FDiv => (f64::from_bits(lhs) / f64::from_bits(rhs)).to_bits(), + BinOp::FMin => f64::from_bits(lhs).tw_minimum(f64::from_bits(rhs)).to_bits(), + BinOp::FMax => f64::from_bits(lhs).tw_maximum(f64::from_bits(rhs)).to_bits(), + BinOp::FCopysign => f64::from_bits(lhs).copysign(f64::from_bits(rhs)).to_bits(), + } +} + +fn exec_binop_128(op: BinOp128, lhs: Value128, rhs: Value128) -> Value128 { + match op { + BinOp128::And => lhs.v128_and(rhs), + BinOp128::AndNot => lhs.v128_andnot(rhs), + BinOp128::Or => lhs.v128_or(rhs), + BinOp128::Xor => lhs.v128_xor(rhs), + BinOp128::I64x2Add => lhs.i64x2_add(rhs), + BinOp128::I64x2Mul => lhs.i64x2_mul(rhs), + } +} diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index e12ef1a..6d13579 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -271,23 +271,20 @@ impl State { if expected_func { let Some(func_addr) = value.addr() else { return false }; let Some(func) = self.funcs.get(func_addr as usize) else { return false }; - let actual = RefType::new_concrete(false, func.type_addr).expect("canonical type fits"); - return self.ref_type_is_subtype(actual, expected); + return self.ref_type_is_subtype(RefType::new_concrete(false, func.type_addr), expected); } if expected.abstract_heap_type() == Some(AbstractHeapType::Exn) { return value.addr().is_some_and(|addr| self.exceptions.get(addr as usize).is_some()); } if value.is_i31() { - let actual = RefType::new_abstract(false, AbstractHeapType::I31); - return self.ref_type_is_subtype(actual, expected); + return self.ref_type_is_subtype(RefType::new_abstract(false, AbstractHeapType::I31), expected); } if value.is_host_any() { - let actual = RefType::new_abstract(false, AbstractHeapType::Any); - return self.ref_type_is_subtype(actual, expected); + return self.ref_type_is_subtype(RefType::new_abstract(false, AbstractHeapType::Any), expected); } let Some(object) = self.gc.get(value) else { return false }; - let actual = RefType::new_concrete(false, object.type_addr).expect("canonical type fits"); + let actual = RefType::new_concrete(false, object.type_addr); self.ref_type_is_subtype(actual, expected) } @@ -309,12 +306,10 @@ impl State { pub(crate) fn value_matches_type(&self, value: WasmValue, expected: WasmType) -> bool { match (value, expected) { (WasmValue::Ref(RefValue::Null), WasmType::Ref(expected)) => expected.is_nullable(), - (WasmValue::Ref(RefValue::Func(func)), WasmType::Ref(expected)) => { - self.funcs.get(func.addr() as usize).is_some_and(|func| { - let actual = RefType::new_concrete(false, func.type_addr).expect("canonical type fits"); - self.ref_type_is_subtype(actual, expected) - }) - } + (WasmValue::Ref(RefValue::Func(func)), WasmType::Ref(expected)) => self + .funcs + .get(func.addr() as usize) + .is_some_and(|func| self.ref_type_is_subtype(RefType::new_concrete(false, func.type_addr), expected)), (WasmValue::Ref(RefValue::Any(_)), WasmType::Ref(expected)) if expected.is_func() || expected.is_extern() || expected.is_exn() => { diff --git a/crates/tinywasm/src/store/types.rs b/crates/tinywasm/src/store/types.rs index 4954bba..e9fa6d1 100644 --- a/crates/tinywasm/src/store/types.rs +++ b/crates/tinywasm/src/store/types.rs @@ -6,7 +6,7 @@ use super::Store; pub(crate) fn canonicalize_ref_type(ty: RefType, type_addrs: &[TypeAddr]) -> RefType { let Some(type_addr) = ty.type_index() else { return ty }; let canonical = *type_addrs.get(type_addr as usize).expect("validated type address should exist"); - RefType::new_concrete(ty.is_nullable(), canonical).expect("canonical type addresses fit in references") + RefType::new_concrete(ty.is_nullable(), canonical) } pub(crate) fn canonicalize_value_type(ty: WasmType, type_addrs: &[TypeAddr]) -> WasmType { @@ -18,12 +18,10 @@ pub(crate) fn canonicalize_value_type(ty: WasmType, type_addrs: &[TypeAddr]) -> fn map_value_type(ty: WasmType, resolve: &mut impl FnMut(TypeAddr) -> TypeAddr) -> WasmType { match ty { - WasmType::Ref(ty) if ty.is_concrete() => { - let addr = resolve(ty.type_index().expect("concrete reference has a type index")); - WasmType::Ref( - RefType::new_concrete(ty.is_nullable(), addr).expect("canonical type addresses fit in references"), - ) - } + WasmType::Ref(ty) if ty.is_concrete() => WasmType::Ref(RefType::new_concrete( + ty.is_nullable(), + resolve(ty.type_index().expect("concrete reference has a type index")), + )), ty => ty, } } diff --git a/crates/tinywasm/tests/host_func_signature_check.rs b/crates/tinywasm/tests/host_func_signature_check.rs index 128f1ed..38a85ef 100644 --- a/crates/tinywasm/tests/host_func_signature_check.rs +++ b/crates/tinywasm/tests/host_func_signature_check.rs @@ -155,7 +155,7 @@ fn imported_host_functions_resolve_concrete_types() -> Result<(), Box Variable Instructions // See - GlobalGet32(GlobalAddr), LocalGet32(LocalAddr), LocalSet32(LocalAddr), LocalTee32(LocalAddr), GlobalSet32(GlobalAddr), - GlobalGet64(GlobalAddr), LocalGet64(LocalAddr), LocalSet64(LocalAddr), LocalTee64(LocalAddr), GlobalSet64(GlobalAddr), - GlobalGet128(GlobalAddr), LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr), GlobalSet128(GlobalAddr), + GlobalGet32(GlobalAddr), GlobalSet32(GlobalAddr), GlobalTee32(GlobalAddr), LocalGet32(LocalAddr), LocalSet32(LocalAddr), LocalTee32(LocalAddr), + GlobalGet64(GlobalAddr), GlobalSet64(GlobalAddr), GlobalTee64(GlobalAddr), LocalGet64(LocalAddr), LocalSet64(LocalAddr), LocalTee64(LocalAddr), + GlobalGet128(GlobalAddr), GlobalSet128(GlobalAddr), GlobalTee128(GlobalAddr), LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr), // > Memory Instructions I32Load(MemoryArg), diff --git a/crates/types/src/reference.rs b/crates/types/src/reference.rs index 884d330..9ed5df1 100644 --- a/crates/types/src/reference.rs +++ b/crates/types/src/reference.rs @@ -73,12 +73,9 @@ impl RefType { } #[inline] - pub const fn new_concrete(nullable: bool, type_index: u32) -> Option { - if type_index <= Self::PAYLOAD_MASK { - Some(Self(((nullable as u32) << 31) | Self::CONCRETE | type_index)) - } else { - None - } + pub const fn new_concrete(nullable: bool, type_index: u32) -> Self { + assert!(type_index <= Self::PAYLOAD_MASK, "type index is too large for a reference type"); + Self(((nullable as u32) << 31) | Self::CONCRETE | type_index) } #[inline] @@ -193,7 +190,7 @@ impl ExternRef { #[inline] pub const fn try_new(addr: u32) -> Option { match encode_host_ref(addr) { - Some(raw) => Some(Self(raw)), + Some(encoded) => Some(Self(encoded)), None => None, } } @@ -251,7 +248,7 @@ impl AnyRef { #[inline] pub const fn from_host(addr: u32) -> Option { match encode_host_ref(addr) { - Some(raw) => Some(Self(raw)), + Some(encoded) => Some(Self(encoded)), None => None, } } diff --git a/crates/types/src/value.rs b/crates/types/src/value.rs index f0a576b..5049ba2 100644 --- a/crates/types/src/value.rs +++ b/crates/types/src/value.rs @@ -81,7 +81,7 @@ mod tests { #[test] fn concrete_references_require_store_type_information() { - let concrete = WasmType::Ref(RefType::new_concrete(false, 0).unwrap()); + let concrete = WasmType::Ref(RefType::new_concrete(false, 0)); assert!(!WasmValue::from(FuncRef::new(0)).matches_type(concrete)); assert!(!WasmValue::from(AnyRef::from_host(0).unwrap()).matches_type(concrete)); diff --git a/examples/rust/Cargo.toml b/examples/rust/Cargo.toml index 0ae646c..b338bd2 100644 --- a/examples/rust/Cargo.toml +++ b/examples/rust/Cargo.toml @@ -22,6 +22,10 @@ path = "src/print.rs" name = "tinywasm" path = "src/tinywasm.rs" +[[bin]] +name = "tinywasm_precompiled" +path = "src/tinywasm_precompiled.rs" + [[bin]] name = "tinywasm_no_std" path = "src/tinywasm_no_std.rs" @@ -39,8 +43,7 @@ argon2 = { version = "0.5" } dlmalloc = { version = "0.2", features = ["global"] } tinywasm = { path = "../../crates/tinywasm", default-features = false, features = [ "archive", - "parser", - "validate" + "parser" ] } [features] diff --git a/examples/rust/build.sh b/examples/rust/build.sh index db4cb43..b2a6149 100755 --- a/examples/rust/build.sh +++ b/examples/rust/build.sh @@ -1,8 +1,8 @@ #!/usr/bin/env bash cd "$(dirname "$0")" || exit -bins=("host_fn" "hello" "fibonacci" "print" "tinywasm" "argon2id") -exclude_wat=("tinywasm") +bins=("host_fn" "hello" "fibonacci" "print" "tinywasm" "tinywasm_precompiled" "argon2id") +exclude_wat=("tinywasm" "tinywasm_precompiled") out_dir="./target/wasm32-unknown-unknown/wasm" dest_dir="out" @@ -13,8 +13,9 @@ wasmopt_features="--enable-simd --enable-relaxed-simd --enable-tail-call --enabl mkdir -p "$dest_dir" # build no_std -cargo build --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin tinywasm_no_std --no-default-features +RUSTFLAGS="-Zlocation-detail=none -Zfmt-debug=none -C target-feature=$rust_features -C panic=abort" cargo build -Z build-std=core,alloc,panic_abort -Z build-std-features="optimize_for_size" --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin tinywasm_no_std --no-default-features cp "$out_dir/tinywasm_no_std.wasm" "$dest_dir/" +wasm-opt "$dest_dir/tinywasm_no_std.wasm" -o "$dest_dir/tinywasm_no_std.opt.wasm" -O3 $wasmopt_features for bin in "${bins[@]}"; do RUSTFLAGS="-Zlocation-detail=none -Zfmt-debug=none -C target-feature=$rust_features -C panic=abort" cargo build -Z build-std=std,panic_abort -Z build-std-features="optimize_for_size" --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin "$bin" diff --git a/examples/rust/src/print.twasm b/examples/rust/src/print.twasm new file mode 100644 index 0000000..f0fa9a8 Binary files /dev/null and b/examples/rust/src/print.twasm differ diff --git a/examples/rust/src/tinywasm_no_std.rs b/examples/rust/src/tinywasm_no_std.rs index cbf10f4..a70abb9 100644 --- a/examples/rust/src/tinywasm_no_std.rs +++ b/examples/rust/src/tinywasm_no_std.rs @@ -1,7 +1,7 @@ #![no_main] #![no_std] use dlmalloc::GlobalDlmalloc; -use tinywasm::{FuncContext, HostFunction, ModuleInstance}; +use tinywasm::{FuncContext, HostFunction, Module, ModuleInstance}; extern crate alloc; @@ -28,9 +28,7 @@ fn run() -> tinywasm::Result<()> { let mut store = tinywasm::Store::default(); let mut imports = tinywasm::Imports::new(); - let res = tinywasm::parser::Parser::default().parse_module_bytes(include_bytes!("./print.wasm"))?; - let twasm = res.serialize_twasm()?; - let module = tinywasm::parse_bytes(&twasm)?; + let module = Module::try_from_twasm(include_bytes!("./print.twasm"))?; let printi32 = HostFunction::from(|_: FuncContext<'_>, v: i32| { unsafe { printi32(v) } diff --git a/examples/rust/src/tinywasm_precompiled.rs b/examples/rust/src/tinywasm_precompiled.rs new file mode 100644 index 0000000..bc0e0c1 --- /dev/null +++ b/examples/rust/src/tinywasm_precompiled.rs @@ -0,0 +1,30 @@ +#![no_main] +use tinywasm::{FuncContext, HostFunction, Module, ModuleInstance}; + +#[link(wasm_import_module = "env")] +unsafe extern "C" { + fn printi32(x: i32); +} + +#[unsafe(no_mangle)] +pub extern "C" fn hello() { + let _ = run(); +} + +fn run() -> tinywasm::Result<()> { + let module = Module::try_from_twasm(include_bytes!("./print.twasm"))?; + let mut store = tinywasm::Store::default(); + + let printi32 = HostFunction::from(|_: FuncContext<'_>, v: i32| { + unsafe { printi32(v) } + Ok(()) + }); + + let mut imports = tinywasm::Imports::new(); + imports.define("env", "printi32", printi32); + + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + let add_and_print = instance.func::<(i32, i32), ()>(&store, "add_and_print")?; + add_and_print.call(&mut store, (1, 2))?; + Ok(()) +} diff --git a/examples/wasm-rust.rs b/examples/wasm-rust.rs index 672b290..b3398f8 100644 --- a/examples/wasm-rust.rs +++ b/examples/wasm-rust.rs @@ -35,6 +35,8 @@ fn main() -> Result<()> { println!(" host_fn"); println!(" fibonacci - calculate fibonacci(30)"); println!(" tinywasm - run printi32 inside of tinywasm inside of itself"); + println!(" tinywasm_precompiled - run a precompiled module inside of tinywasm"); + println!(" tinywasm_no_std - run a precompiled module inside of no_std tinywasm"); println!(" argon2id - run argon2id(1000, 2, 1)"); return Ok(()); } @@ -44,6 +46,7 @@ fn main() -> Result<()> { "printi32" => printi32()?, "fibonacci" => fibonacci()?, "tinywasm" => tinywasm()?, + "tinywasm_precompiled" => tinywasm_precompiled()?, "tinywasm_no_std" => tinywasm_no_std()?, "argon2id" => argon2id()?, "host_fn" => host_fn()?, @@ -57,6 +60,8 @@ fn main() -> Result<()> { fibonacci()?; println!("\ntinywasm.wasm:"); tinywasm()?; + println!("\ntinywasm_precompiled.wasm:"); + tinywasm_precompiled()?; println!("\ntinywasm_no_std.wasm:"); tinywasm_no_std()?; println!("argon2id.wasm:"); @@ -100,6 +105,21 @@ fn tinywasm_no_std() -> Result<()> { Ok(()) } +fn tinywasm_precompiled() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/tinywasm_precompiled.opt.wasm")?; + let mut store = Store::default(); + + let mut imports = Imports::new(); + imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _x: i32| Ok(()))); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(black_box(&imports)))?; + + let hello = instance.func::<(), ()>(&store, "hello")?; + hello.call(&mut store, black_box(()))?; + hello.call(&mut store, black_box(()))?; + hello.call(&mut store, black_box(()))?; + Ok(()) +} + fn hello() -> Result<()> { let module = tinywasm::parse_file("./examples/rust/out/hello.opt.wasm")?; let mut store = Store::default(); @@ -211,6 +231,11 @@ mod tests { tinywasm().unwrap(); } + #[test] + fn test_tinywasm_precompiled() { + tinywasm_precompiled().unwrap(); + } + #[test] fn test_tinywasm_no_std() { tinywasm_no_std().unwrap(); -- cgit v1.3.1 From 358a183e5c12c32b8836acf9c71799f56e00b036 Mon Sep 17 00:00:00 2001 From: Henry Gressmann Date: Mon, 17 Aug 2026 20:07:51 +0200 Subject: chore: reduce instruction enum size (#52) this is a fairly big commit since I've been just playing around with this for a while now. the main goal is to reduce instruction size by moving some operands into two separate vecs. memory operations still seem like the biggest issue right now, so as a follow op I'll probably remove the public linear memory trait again but let's see how this goes first. performance wise this is about the same as before, but serialization/deserialization is about 20% faster now. Signed-off-by: Henry --------- Signed-off-by: Henry --- CHANGELOG.md | 1 + Cargo.lock | 8 +- crates/parser/src/conversion.rs | 33 +- crates/parser/src/lib.rs | 16 + crates/parser/src/macros.rs | 155 +-- crates/parser/src/module.rs | 42 +- crates/parser/src/optimize.rs | 1201 ----------------- crates/parser/src/optimize/mod.rs | 4 + crates/parser/src/optimize/rewrite.rs | 1397 ++++++++++++++++++++ crates/parser/src/optimize/targets.rs | 290 ++++ crates/parser/src/parallel.rs | 12 +- crates/parser/src/visit.rs | 281 +++- crates/tinywasm/src/interpreter/executor.rs | 543 ++++---- .../tinywasm/src/interpreter/stack/value_stack.rs | 11 + crates/tinywasm/src/interpreter/values.rs | 6 + .../tests/wasm-custom/conditional-rewrite.wast | 35 + .../tests/wasm-custom/sign-extension-rewrite.wast | 59 + .../tests/wasm-custom/simd-stack-local.wast | 53 + crates/types/src/archive.rs | 26 + crates/types/src/instructions.rs | 795 ++++++++--- crates/types/src/lib.rs | 13 +- crates/types/src/operands.rs | 177 +++ crates/types/src/reference.rs | 12 + 23 files changed, 3221 insertions(+), 1949 deletions(-) delete mode 100644 crates/parser/src/optimize.rs create mode 100644 crates/parser/src/optimize/mod.rs create mode 100644 crates/parser/src/optimize/rewrite.rs create mode 100644 crates/parser/src/optimize/targets.rs create mode 100644 crates/tinywasm/tests/wasm-custom/conditional-rewrite.wast create mode 100644 crates/tinywasm/tests/wasm-custom/sign-extension-rewrite.wast create mode 100644 crates/tinywasm/tests/wasm-custom/simd-stack-local.wast create mode 100644 crates/types/src/operands.rs (limited to 'crates/parser/src/conversion.rs') diff --git a/CHANGELOG.md b/CHANGELOG.md index 3427a80..701fc84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added `WasmValue::ty` and `WasmValue::matches_type` - Added `ValueLane` for mapping WebAssembly value types to their physical 32-bit, 64-bit, or 128-bit storage lane. - Added a `validate` feature to `tinywasm` and `tinywasm-parser` (enabled by default) to optionally skip wasmparser validation for faster parsing of trusted modules. +- Added optional parse-time operand deduplication to reduce precompiled module and `.twasm` archive size. ### Changed diff --git a/Cargo.lock b/Cargo.lock index b06f70f..3c13501 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -134,9 +134,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.4.2" +version = "1.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d262e149917187838d5b42777c8253bcb64500067342904e7d429499a6f277e" +checksum = "509591b7bcd67f4ef775afad7662703b4935daaa6ec0e5605cfb1090b32a2b6d" dependencies = [ "find-msvc-tools", "shlex", @@ -365,9 +365,9 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" [[package]] name = "find-msvc-tools" -version = "0.1.10" +version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b73573e6edcd2af0cdf47bd6cb58f0b3839491263c314eaad1ccf24430e1de" +checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890" [[package]] name = "float-cmp" diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 480a8d0..b94ebe6 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -1,7 +1,7 @@ use crate::validation::{FuncValidator, FuncValidatorAllocations, ValidatorResources}; #[cfg(feature = "validate")] use crate::visit::process_operators_and_validate; -use crate::{Result, module::FunctionCode, visit::process_operators}; +use crate::{ParserOptions, Result, module::FunctionCode, visit::process_operators}; use alloc::{boxed::Box, format, vec::Vec}; use tinywasm_types::*; use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations, UnpackedIndex}; @@ -149,6 +149,7 @@ pub(crate) fn convert_module_code( reader_allocs: OperatorsReaderAllocations, metadata: &crate::visit::ModuleMetadata, ty_idx: u32, + options: &ParserOptions, ) -> Result<(FunctionCode, Option, OperatorsReaderAllocations)> { let locals_reader = func.get_locals_reader()?; #[cfg(feature = "validate")] @@ -194,32 +195,40 @@ pub(crate) fn convert_module_code( let (body, data, validator_allocs, reader_allocs) = process_operators_and_validate( validator, func, - local_types, - local_addr_map, + (local_types, local_addr_map), metadata, ty_idx, reader_allocs, + options.deduplicate_operands(), )?; (body, data, Some(validator_allocs), reader_allocs) } None => { - let (body, data, reader_allocs) = - process_operators(func, local_types, local_addr_map, metadata, ty_idx, reader_allocs)?; + let (body, data, reader_allocs) = process_operators( + func, + (local_types, local_addr_map), + metadata, + ty_idx, + reader_allocs, + options.deduplicate_operands(), + )?; (body, data, None, reader_allocs) } }; #[cfg(not(feature = "validate"))] let (body, data, validator_allocs, reader_allocs) = { let _ = validator; - let (body, data, reader_allocs) = - process_operators(func, local_types, local_addr_map, metadata, ty_idx, reader_allocs)?; + let (body, data, reader_allocs) = process_operators( + func, + (local_types, local_addr_map), + metadata, + ty_idx, + reader_allocs, + options.deduplicate_operands(), + )?; (body, data, None, reader_allocs) }; - Ok(( - FunctionCode { instructions: body, data, locals: local_counts, uses_local_memory: false }, - validator_allocs, - reader_allocs, - )) + Ok((FunctionCode { instructions: body, data, locals: local_counts }, validator_allocs, reader_allocs)) } pub(crate) fn convert_rec_group(ty: wasmparser::RecGroup, group_start: u32, types: &mut Vec) -> Result { diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs index 8db7920..90e239b 100644 --- a/crates/parser/src/lib.rs +++ b/crates/parser/src/lib.rs @@ -65,6 +65,10 @@ pub struct ParserOptions { pub optimize_local_memory_allocation: bool, /// Whether to run the peephole rewrite optimizer. pub optimize_rewrite: bool, + /// Whether to deduplicate immutable function operands while parsing. + /// + /// This uses more parse CPU to reduce precompiled module and archive size. + pub deduplicate_operands: bool, #[cfg(parallel_parser)] /// Number of threads to use for parallel parsing. @@ -83,6 +87,7 @@ impl Default for ParserOptions { validation: cfg!(feature = "validate"), optimize_local_memory_allocation: true, optimize_rewrite: true, + deduplicate_operands: false, #[cfg(parallel_parser)] parser_threads: None, } @@ -134,6 +139,17 @@ impl ParserOptions { self.optimize_rewrite } + /// Enable or disable parse-time deduplication of immutable function operands. + pub const fn with_operand_deduplication(mut self, enabled: bool) -> Self { + self.deduplicate_operands = enabled; + self + } + + /// Returns whether immutable function operands are deduplicated while parsing. + pub const fn deduplicate_operands(&self) -> bool { + self.deduplicate_operands + } + #[cfg(parallel_parser)] /// Set the number of threads for parallel parsing. /// diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs index 9fa7a01..5e675e6 100644 --- a/crates/parser/src/macros.rs +++ b/crates/parser/src/macros.rs @@ -72,10 +72,17 @@ pub(crate) mod visit { ) => { fn $visit(&mut self, memarg: wasmparser::MemArg $(, $lane: $ty)?) -> Self::Output { let address = self.metadata.memory_size(memarg.memory)?; + let memory_arg_idx = self.push_operand(MemoryArg::new(memarg.offset, memarg.memory))?; lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*] - Instruction::$instr(MemoryArg::new(memarg.offset, memarg.memory) $(, $lane)?).into()) + lowering_ops!(@memory_instruction $instr memory_arg_idx $(, $lane)?)) } }; + (@memory_instruction $instr:ident $memory_arg_idx:ident) => { + Instruction::$instr($memory_arg_idx) + }; + (@memory_instruction $instr:ident $memory_arg_idx:ident, $lane:ident) => { + Instruction::$instr(tinywasm_types::MemoryLaneArg { memory_arg_idx: $memory_arg_idx, lane: $lane }) + }; (@global $inputs:tt => $outputs:tt $($operator:tt)*) => { lowering_ops!(@resolved global_size $inputs => $outputs $($operator)*); }; @@ -191,6 +198,20 @@ pub(crate) mod optimize { ($instructions:ident, $read:ident, $consumed:expr => $out:expr) => { replace!($instructions, $read, $consumed => [$out]); }; + ($instructions:ident, *$read:ident, $consumed:expr => [$($out:expr),+ $(,)?]) => {{ + const { + assert!($consumed >= 1 && $consumed <= 3); + assert!([$(stringify!($out)),+].len() <= $consumed + 1); + } + let replacements = [$($out),+]; + let start = *$read - $consumed; + $instructions[start..start + replacements.len()].copy_from_slice(&replacements); + $instructions.truncate(start + replacements.len()); + *$read = $instructions.len() - 1; + }}; + ($instructions:ident, *$read:ident, $consumed:expr => $out:expr) => { + replace!($instructions, *$read, $consumed => [$out]) + }; } macro_rules! rewrite { @@ -201,16 +222,13 @@ pub(crate) mod optimize { }; ($instructions:ident, $read:ident, [$($pattern:pat),+] $(if ($($guard:tt)+))? => $body:block $(,)?) => {{ const CONSUMED: usize = [$(stringify!($pattern)),+].len(); - if !$instructions.tail_rewritten - && $read < $instructions.len() - && $read >= $instructions.block_start + CONSUMED - { + if $read >= $instructions.block_start + CONSUMED { let previous: [Instruction; CONSUMED] = $instructions[$read - CONSUMED..$read].try_into().unwrap(); if let [$($pattern),+] = previous $( && $($guard)+ )? { - $instructions.tail_rewritten = true; $body + continue; } } }}; @@ -221,128 +239,5 @@ pub(crate) mod optimize { }; } - macro_rules! define_local_source_resolver { - ( - $name:ident, - get = $get:ident, - tee = $tee:ident, - set = $set:ident, - binop_local_local_tee = $lltee:ident, - binop_local_local_set = $llset:ident, - binop_local_const_tee = $lctee:ident, - binop_local_const_set = $lcset:ident - $(, load_local_tee = $loadtee:ident, load_local_set = $loadset:ident)? - ) => { - fn $name(instr: Instruction) -> Option<(Option, u16)> { - Some(match instr { - Instruction::$get(local) => (None, local), - Instruction::$tee(local) => (Some(Instruction::$set(local)), local), - Instruction::$lltee(op, a, b, local) => (Some(Instruction::$llset(op, a, b, local)), local), - Instruction::$lctee(op, src, c, local) => (Some(Instruction::$lcset(op, src, c, local)), local), - $(Instruction::$loadtee(memarg, addr, local) => (Some(Instruction::$loadset(memarg, addr, local)), local.into()),)? - _ => return None, - }) - } - }; - } - - macro_rules! fold_local_binop { - ( - $instrs:ident, $read:expr, $dst:expr, - source = $source:ident, - op = $op:ident, - const = $const:ident, - local_local = $local_local:ident, - local_const = $local_const:expr - ) => {{ - if !$instrs.tail_rewritten - && $read < $instrs.len() - && $read >= $instrs.block_start + 3 - && let [lhs_src, rhs_src, raw_op] = [$instrs[$read - 3], $instrs[$read - 2], $instrs[$read - 1]] - && let Some((lhs_instr, lhs)) = $source(lhs_src) - && let Some(op) = $op(raw_op) - { - if let Some((rhs_instr, rhs)) = $source(rhs_src) { - if rhs_instr.is_none() || rhs != lhs { - $instrs.tail_rewritten = true; - $instrs.truncate($read - 3); - $instrs.extend(lhs_instr); - $instrs.extend(rhs_instr); - $instrs.push(Instruction::$local_local(op, lhs, rhs, $dst)); - $read = $instrs.len() - 1; - } - } else if let Some(imm) = $const(rhs_src, raw_op) { - $instrs.tail_rewritten = true; - $instrs.truncate($read - 3); - $instrs.extend(lhs_instr); - $instrs.push($local_const($dst, lhs, op, imm)); - $read = $instrs.len() - 1; - } - } - }}; - } - - macro_rules! rewrite_local_set_direct { - ( - $instrs:ident, $read:ident, $dst:expr, - get = $get:ident, - copy = $copy:ident, - binop_local_local = $ll:ident, - binop_local_local_set = $llset:ident, - binop_local_const = $lc:ident, - binop_local_const_set = $lcset:expr - $(, const_instr = $const_instr:ident, set_local_const = $set_local_const:ident)? - ) => {{ - rewrite!($instrs, $read, [$get(src)] if (src != $dst) => Instruction::$copy(src, $dst)); - if !$instrs.tail_rewritten - && $read < $instrs.len() - && $read > $instrs.block_start - && let Instruction::$get(src) = $instrs[$read - 1] - && src == $dst - { - $instrs.tail_rewritten = true; - $instrs.truncate($read - 1); - $read = $instrs.len(); - } - $(rewrite!($instrs, $read, [$const_instr(c)] => Instruction::$set_local_const($dst, c));)? - rewrite!($instrs, $read, [$ll(op, a, b)] => Instruction::$llset(op, a, b, $dst)); - rewrite!($instrs, $read, [$lc(op, src, c)] => { replace!($instrs, $read, 1 => $lcset($dst, src, op, c)); }); - }}; - } - - macro_rules! rewrite_local_tee_direct { - ( - $instrs:ident, $read:ident, $dst:expr, - get = $get:ident, - binop_local_local = $ll:ident, - binop_local_local_tee = $lltee:ident, - binop_local_const = $lc:ident, - binop_local_const_tee = $lctee:ident - ) => {{ - rewrite!($instrs, $read, [$get(src)] if (src == $dst) => Instruction::$get(src)); - rewrite!($instrs, $read, [$ll(op, a, b)] => Instruction::$lltee(op, a, b, $dst)); - rewrite!($instrs, $read, [$lc(op, src, c)] => Instruction::$lctee(op, src, c, $dst)); - }}; - } - - macro_rules! rewrite_drop_tee_direct { - ( - $instrs:ident, $read:ident, - tee = $tee:ident, - set = $set:ident, - binop_local_local_tee = $lltee:ident, - binop_local_local_set = $llset:ident, - binop_local_const_tee = $lctee:ident, - binop_local_const_set = $lcset:ident - ) => {{ - rewrite!($instrs, $read, [$tee(local)] => Instruction::$set(local)); - rewrite!($instrs, $read, [$lltee(op, a, b, dst)] => Instruction::$llset(op, a, b, dst)); - rewrite!($instrs, $read, [$lctee(op, src, c, dst)] => Instruction::$lcset(op, src, c, dst)); - }}; - } - - pub(crate) use { - define_local_source_resolver, fold_local_binop, replace, rewrite, rewrite_drop_tee_direct, - rewrite_local_set_direct, rewrite_local_tee_direct, - }; + pub(crate) use {replace, rewrite}; } diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index 3d38ad6..8138666 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -10,6 +10,12 @@ use tinywasm_types::*; use wasmparser::{OperatorsReaderAllocations, Payload}; pub(crate) struct FunctionCode { + pub instructions: Vec, + pub data: crate::visit::FunctionDataBuilder, + pub locals: ValueCounts, +} + +pub(crate) struct OptimizedFunctionCode { pub instructions: Vec, pub data: WasmFunctionData, pub locals: ValueCounts, @@ -22,19 +28,15 @@ pub(crate) fn optimize_function_code( function_results: ValueCounts, self_func_addr: u32, imported_memory_count: u32, -) -> Result { - let optimized = optimize::optimize_instructions( - code.instructions, - &mut code.data, - options, - function_results, - self_func_addr, - imported_memory_count, - )?; - - code.instructions = optimized.instructions; - code.uses_local_memory = optimized.uses_local_memory; - Ok(code) +) -> Result { + let optimized = + optimize::optimize_instructions(code.instructions, &mut code.data, options, function_results, self_func_addr)?; + let data = code.data.finish(); + let uses_local_memory = optimized + .instructions + .iter() + .any(|instruction| instruction.memory_addr(&data).is_some_and(|memory| memory >= imported_memory_count)); + Ok(OptimizedFunctionCode { instructions: optimized.instructions, data, locals: code.locals, uses_local_memory }) } #[derive(Default)] @@ -53,7 +55,7 @@ pub(crate) struct ModuleReader<'a> { pub(crate) code_type_addrs: Box<[u32]>, code_results: Box<[ValueCounts]>, pub(crate) exports: Arc<[Export]>, - pub(crate) code: Vec, + pub(crate) code: Vec, pub(crate) globals: Box<[Global]>, pub(crate) tables: Box<[TableDefinition]>, pub(crate) memory_types: Box<[MemoryType]>, @@ -402,7 +404,7 @@ impl<'a> ModuleReader<'a> { let metadata = self.translation_metadata(); let (code, func_validator_allocs, operators_reader_allocs) = - convert_module_code(function, func_validator, operators_reader_allocs, metadata, ty_idx)?; + convert_module_code(function, func_validator, operators_reader_allocs, metadata, ty_idx, options)?; self.code.push(optimize_function_code( code, @@ -565,7 +567,7 @@ impl<'a> ModuleReader<'a> { .into_iter() .zip(self.code_type_addrs) .zip(self.code_results) - .map(|((code, ty_idx), results)| { + .map(|((code, ty_idx), results)| -> Result<_> { let ty = self.types.get(ty_idx).and_then(SubType::as_func).expect("function type was checked while parsing"); let params = ValueCounts::from_iter(ty.params()); @@ -573,15 +575,15 @@ impl<'a> ModuleReader<'a> { local_memory_allocation = LocalMemoryAllocation::Eager; } - Arc::new(WasmFunction { - instructions: code.instructions.into(), + Ok(Arc::new(WasmFunction { + instructions: code.instructions.into_boxed_slice(), data: code.data, locals: code.locals, params, results, - }) + })) }) - .collect(); + .collect::>()?; Ok(ModuleInner { funcs, diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs deleted file mode 100644 index 969d686..0000000 --- a/crates/parser/src/optimize.rs +++ /dev/null @@ -1,1201 +0,0 @@ -use crate::macros::optimize::*; -use crate::{ParseError, ParserOptions, Result}; -use alloc::vec::Vec; -use core::ops::{Deref, DerefMut}; -use tinywasm_types::{BinOp, BinOp128, CmpOp, ConstIdx, Instruction, ValueCounts, WasmFunctionData}; - -pub(crate) struct OptimizeResult { - pub(crate) instructions: Vec, - pub(crate) uses_local_memory: bool, -} - -struct CompactOutput { - instructions: Vec, - block_start: usize, - tail_rewritten: bool, -} - -impl Deref for CompactOutput { - type Target = Vec; - - fn deref(&self) -> &Self::Target { - &self.instructions - } -} - -impl DerefMut for CompactOutput { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.instructions - } -} - -pub(crate) fn optimize_instructions( - instructions: Vec, - function_data: &mut WasmFunctionData, - options: &ParserOptions, - function_results: ValueCounts, - self_func_addr: u32, - imported_memory_count: u32, -) -> Result { - let (mut instructions, old_to_new) = if options.optimize_rewrite() { - let boundaries = target_boundaries(&instructions, function_data)?; - let (instructions, old_to_new) = rewrite(instructions, &boundaries, function_results, self_func_addr); - (instructions, Some(old_to_new)) - } else { - (instructions, None) - }; - let uses_local_memory = finalize(&mut instructions, function_data, old_to_new.as_deref(), imported_memory_count)?; - Ok(OptimizeResult { instructions, uses_local_memory }) -} - -fn rewrite( - source: Vec, - boundaries: &[bool], - function_results: ValueCounts, - self_func_addr: u32, -) -> (Vec, Vec) { - use Instruction::*; - let mut instrs = - CompactOutput { instructions: Vec::with_capacity(source.len()), block_start: 0, tail_rewritten: false }; - let mut old_to_new = alloc::vec![0; source.len() + 1]; - let mut after_terminator = false; - let return_instr = match function_results { - ValueCounts { c32: 0, c64: 0, c128: 0 } => Some(ReturnVoid), - ValueCounts { c32: 1, c64: 0, c128: 0 } => Some(Return32), - ValueCounts { c32: 0, c64: 1, c128: 0 } => Some(Return64), - ValueCounts { c32: 0, c64: 0, c128: 1 } => Some(Return128), - _ => None, - }; - - for (old_idx, instr) in source.iter().copied().enumerate() { - if boundaries[old_idx] || after_terminator { - instrs.block_start = instrs.len(); - } - old_to_new[old_idx] = instrs.len() as u32; - instrs.tail_rewritten = false; - instrs.push(instr); - let mut i = instrs.len() - 1; - match instrs[i] { - LocalCopy32(a, b) if a == b => { - instrs.pop(); - } - LocalCopy64(a, b) if a == b => { - instrs.pop(); - } - LocalCopy128(a, b) if a == b => { - instrs.pop(); - } - Call(addr) if addr == self_func_addr => instrs[i] = CallSelf, - ReturnCall(addr) if addr == self_func_addr => instrs[i] = ReturnCallSelf, - Return if let Some(return_instr) = return_instr => instrs[i] = return_instr, - instr @ (I32Add | I32Mul | I32And | I32Or | I32Xor) => { - let Some(op) = int_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); - rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [Const32(c), GlobalGet32(global)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); - rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - if matches!(op, BinOp::IAdd) { - rewrite!(instrs, i, [Const32(c)] => AddConst32(c)); - rewrite!(instrs, i, [I32Add] => I32Add3); - rewrite!(instrs, i, - [BinOpStackLocal32(BinOp::IAdd, local)] => - [LocalGet32(local), I32Add3] - ); - } - } - instr @ (I32Sub | I32Shl | I32ShrS | I32ShrU | I32Rotl | I32Rotr) => { - let Some(op) = int_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); - rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); - rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - if matches!(op, BinOp::IShrS) { - rewrite!(instrs, i, [BinOpLocalConst32(BinOp::IShl, local, 8), Const32(8)] => [LocalGet32(local), I32Extend8S]); - rewrite!(instrs, i, [BinOpLocalConst32(BinOp::IShl, local, 16), Const32(16)] => [LocalGet32(local), I32Extend16S]); - } - } - instr @ (I64Add | I64Mul | I64And | I64Or | I64Xor) => { - let Some(op) = int_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); - rewrite!(instrs, i, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [Const64(c), GlobalGet64(global)] => BinOpGlobalConst64(op, global, c)); - rewrite!(instrs, i, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); - if matches!(op, BinOp::IAdd) { - rewrite!(instrs, i, [Const64(c)] => AddConst64(c)); - rewrite!(instrs, i, [I64Add] => I64Add3); - } - } - instr @ (I64Sub | I64Shl | I64ShrS | I64ShrU | I64Rotl | I64Rotr) => { - let Some(op) = int_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); - rewrite!(instrs, i, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); - if matches!(op, BinOp::IShrS) { - rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 8), Const64(8)] => [LocalGet64(local), I64Extend8S]); - rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 16), Const64(16)] => [LocalGet64(local), I64Extend16S]); - rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 32), Const64(32)] => [LocalGet64(local), I64Extend32S]); - } - } - instr @ (I32Eq | I32Ne | I32LtS | I32LtU | I32GtS | I32GtU | I32LeS | I32LeU | I32GeS | I32GeU) => { - let Some(op) = cmp_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet32(left), LocalGet32(right)] => CmpLocalLocal32(op, left, right)); - } - instr @ (I64Eq | I64Ne | I64LtS | I64LtU | I64GtS | I64GtU | I64LeS | I64LeU | I64GeS | I64GeU) => { - let Some(op) = cmp_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet64(left), LocalGet64(right)] => CmpLocalLocal64(op, left, right)); - } - instr @ (F32Add | F32Mul | F32Min | F32Max) => { - let Some(op) = float_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); - rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [Const32(c), GlobalGet32(global)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - } - instr @ (F32Sub | F32Div | F32Copysign) => { - let Some(op) = float_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); - rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - } - instr @ (F64Add | F64Mul | F64Min | F64Max) => { - let Some(op) = float_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); - rewrite!(instrs, i, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [Const64(c), GlobalGet64(global)] => BinOpGlobalConst64(op, global, c)); - } - instr @ (F64Sub | F64Div | F64Copysign) => { - let Some(op) = float_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); - } - instr @ (V128And | V128Or | V128Xor | I64x2Add | I64x2Mul) => { - let Some(op) = bin_op_128(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet128(a), LocalGet128(b)] => BinOpLocalLocal128(op, a, b)); - rewrite!(instrs, i, [LocalGet128(local), Const128(c)] => BinOpLocalConst128(op, local, c)); - rewrite!(instrs, i, [GlobalGet128(global), Const128(c)] => BinOpGlobalConst128(op, global, c)); - rewrite!(instrs, i, [Const128(c), LocalGet128(local)] => BinOpLocalConst128(op, local, c)); - rewrite!(instrs, i, [Const128(c), GlobalGet128(global)] => BinOpGlobalConst128(op, global, c)); - } - V128AndNot => { - rewrite!(instrs, i, [LocalGet128(a), LocalGet128(b)] => BinOpLocalLocal128(BinOp128::AndNot, a, b)); - rewrite!(instrs, i, [LocalGet128(local), Const128(c)] => BinOpLocalConst128(BinOp128::AndNot, local, c)); - rewrite!(instrs, i, [GlobalGet128(global), Const128(c)] => BinOpGlobalConst128(BinOp128::AndNot, global, c)); - } - I32Store(memarg) | F32Store(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr), LoadLocal32(load_memarg, load_addr), AddConst32(1)] if - (load_memarg == memarg && addr == u16::from(load_addr)) => - IncMemoryLocal32(memarg, load_addr) - ); - rewrite!(instrs, i, - [LocalGet64(addr), LoadLocal32(load_memarg, load_addr), AddConst32(1)] if - (load_memarg == memarg && addr == u16::from(load_addr)) => - IncMemoryLocal32(memarg, load_addr) - ); - rewrite!(instrs, i, [F32Mul, F32Add] => FMaStoreF32(memarg)); - rewrite!(instrs, i, - [BinOpStackLocal32(BinOp::FMul, local), F32Add] => - [LocalGet32(local), FMaStoreF32(memarg)] - ); - rewrite!(instrs, i, - [LocalGet32(addr_local), LocalGet32(value_local)] if - (let (Ok(addr_local), Ok(value_local)) = (u8::try_from(addr_local), u8::try_from(value_local))) => - StoreLocalLocal32(memarg, addr_local, value_local) - ); - } - I64Store(memarg) | F64Store(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr), LoadLocal64(load_memarg, load_addr), AddConst64(1)] if - (load_memarg == memarg && addr == u16::from(load_addr)) => - IncMemoryLocal64(memarg, load_addr) - ); - rewrite!(instrs, i, - [LocalGet64(addr), LoadLocal64(load_memarg, load_addr), AddConst64(1)] if - (load_memarg == memarg && addr == u16::from(load_addr)) => - IncMemoryLocal64(memarg, load_addr) - ); - rewrite!(instrs, i, [F64Mul, F64Add] => FMaStoreF64(memarg)); - rewrite!(instrs, i, - [LocalGet32(addr_local), LocalGet64(value_local)] if - (let (Ok(addr_local), Ok(value_local)) = (u8::try_from(addr_local), u8::try_from(value_local))) => - StoreLocalLocal64(memarg, addr_local, value_local) - ); - } - V128Store(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local), LocalGet128(value_local)] if - (let (Ok(addr_local), Ok(value_local)) = (u8::try_from(addr_local), u8::try_from(value_local))) => - StoreLocalLocal128(memarg, addr_local, value_local) - ); - } - I32Load(memarg) | F32Load(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal32(memarg, addr_local) - ); - rewrite!(instrs, i, - [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal32(memarg, addr_local) - ); - } - I64Load(memarg) | F64Load(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal64(memarg, addr_local) - ); - rewrite!(instrs, i, - [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal64(memarg, addr_local) - ); - } - I32Load8S(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal8S32(memarg, addr_local) - ); - rewrite!(instrs, i, - [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal8S32(memarg, addr_local) - ); - } - I32Load8U(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal8U32(memarg, addr_local) - ); - rewrite!(instrs, i, - [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal8U32(memarg, addr_local) - ); - } - I32Load16S(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal16S32(memarg, addr_local) - ); - rewrite!(instrs, i, - [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal16S32(memarg, addr_local) - ); - } - I32Load16U(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal16U32(memarg, addr_local) - ); - rewrite!(instrs, i, - [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal16U32(memarg, addr_local) - ); - } - MemoryFill(mem) => { - rewrite!(instrs, i, [Const32(val), Const32(size)] => MemoryFillImm(mem, val as u8, size)) - } - GlobalGet32(dst) => rewrite!(instrs, i, [GlobalSet32(src)] if (src == dst) => GlobalTee32(src)), - GlobalGet64(dst) => rewrite!(instrs, i, [GlobalSet64(src)] if (src == dst) => GlobalTee64(src)), - GlobalGet128(dst) => rewrite!(instrs, i, [GlobalSet128(src)] if (src == dst) => GlobalTee128(src)), - LocalGet32(dst) => rewrite!(instrs, i, [LocalSet32(src)] if (src == dst) => LocalTee32(src)), - LocalGet64(dst) => rewrite!(instrs, i, [LocalSet64(src)] if (src == dst) => LocalTee64(src)), - LocalGet128(dst) => rewrite!(instrs, i, [LocalSet128(src)] if (src == dst) => LocalTee128(src)), - LocalSet32(dst) => { - fold_local_binop!( - instrs, i, dst, - source = resolve_local_source_32, - op = scalar_bin_op, - const = scalar_const_32, - local_local = BinOpLocalLocalSet32, - local_const = |dst, lhs, op, imm| match (dst == lhs, op) { - (true, BinOp::IAdd) => Instruction::IncLocal32(dst, imm), - (true, BinOp::ISub) => Instruction::IncLocal32(dst, imm.wrapping_neg()), - _ => Instruction::BinOpLocalConstSet32(op, lhs, imm, dst), - } - ); - rewrite!(instrs, i, [I32Mul, LocalGet32(acc), I32Add] if (acc == dst) => MulAccLocal32(dst)); - rewrite!(instrs, i, [F32Mul, LocalGet32(acc), F32Add] if (acc == dst) => FMulAccLocal32(dst)); - rewrite!(instrs, i, - [I32Mul, BinOpStackLocal32(BinOp::IAdd, acc)] if (acc == dst) => - MulAccLocal32(dst) - ); - rewrite!(instrs, i, - [F32Mul, BinOpStackLocal32(BinOp::FAdd, acc)] if (acc == dst) => - FMulAccLocal32(dst) - ); - rewrite!(instrs, i, [BinOpStackLocal32(op, local)] => BinOpStackLocalSet32(op, local, dst)); - rewrite_local_set_direct!( - instrs, - i, - dst, - get = LocalGet32, - copy = LocalCopy32, - binop_local_local = BinOpLocalLocal32, - binop_local_local_set = BinOpLocalLocalSet32, - binop_local_const = BinOpLocalConst32, - binop_local_const_set = |dst, src, op, c| match (dst == src, op) { - (true, BinOp::IAdd) => IncLocal32(dst, c), - (true, BinOp::ISub) => IncLocal32(dst, c.wrapping_neg()), - _ => BinOpLocalConstSet32(op, src, c, dst), - }, - const_instr = Const32, - set_local_const = SetLocalConst32 - ); - rewrite!(instrs, i, [LoadLocal32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet32(memarg, addr, dst)); - rewrite!(instrs, i, [LoadLocal8S32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet8S32(memarg, addr, dst)); - rewrite!(instrs, i, [LoadLocal8U32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet8U32(memarg, addr, dst)); - rewrite!(instrs, i, [LoadLocal16S32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet16S32(memarg, addr, dst)); - rewrite!(instrs, i, [LoadLocal16U32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet16U32(memarg, addr, dst)); - rewrite!(instrs, i, - [LocalGet32(addr), I32Load(memarg)] if - (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) => - LoadLocalSet32(memarg, addr, dst) - ); - } - LocalSet64(dst) => { - fold_local_binop!( - instrs, i, dst, - source = resolve_local_source_64, - op = scalar_bin_op, - const = scalar_const_64, - local_local = BinOpLocalLocalSet64, - local_const = |dst, lhs, op, imm| match (dst == lhs, op) { - (true, BinOp::IAdd) => Instruction::IncLocal64(dst, imm), - (true, BinOp::ISub) => Instruction::IncLocal64(dst, imm.wrapping_neg()), - _ => Instruction::BinOpLocalConstSet64(op, lhs, imm, dst), - } - ); - rewrite!(instrs, i, [I64Mul, LocalGet64(acc), I64Add] if (acc == dst) => MulAccLocal64(dst)); - rewrite!(instrs, i, [F64Mul, LocalGet64(acc), F64Add] if (acc == dst) => FMulAccLocal64(dst)); - rewrite_local_set_direct!( - instrs, - i, - dst, - get = LocalGet64, - copy = LocalCopy64, - binop_local_local = BinOpLocalLocal64, - binop_local_local_set = BinOpLocalLocalSet64, - binop_local_const = BinOpLocalConst64, - binop_local_const_set = |dst, src, op, c| match (dst == src, op) { - (true, BinOp::IAdd) => IncLocal64(dst, c), - (true, BinOp::ISub) => IncLocal64(dst, c.wrapping_neg()), - _ => BinOpLocalConstSet64(op, src, c, dst), - }, - const_instr = Const64, - set_local_const = SetLocalConst64 - ); - } - LocalSet128(dst) => { - fold_local_binop!( - instrs, i, dst, - source = resolve_local_source_128, - op = bin_op_128, - const = const_128, - local_local = BinOpLocalLocalSet128, - local_const = |dst, lhs, op, imm| Instruction::BinOpLocalConstSet128(op, lhs, imm, dst) - ); - rewrite_local_set_direct!( - instrs, - i, - dst, - get = LocalGet128, - copy = LocalCopy128, - binop_local_local = BinOpLocalLocal128, - binop_local_local_set = BinOpLocalLocalSet128, - binop_local_const = BinOpLocalConst128, - binop_local_const_set = |dst, src, op, c| BinOpLocalConstSet128(op, src, c, dst), - const_instr = Const128, - set_local_const = SetLocalConst128 - ); - rewrite!(instrs, i, - [LocalGet32(addr), V128Load(memarg)] if - (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) => - LoadLocalSet128(memarg, addr, dst) - ); - } - LocalTee32(dst) => { - rewrite!(instrs, i, [BinOpStackLocal32(op, local)] => BinOpStackLocalTee32(op, local, dst)); - fold_local_binop!( - instrs, i, dst, - source = resolve_local_source_32, - op = scalar_bin_op, - const = scalar_const_32, - local_local = BinOpLocalLocalTee32, - local_const = |dst, lhs, op, imm| Instruction::BinOpLocalConstTee32(op, lhs, imm, dst) - ); - rewrite_local_tee_direct!( - instrs, - i, - dst, - get = LocalGet32, - binop_local_local = BinOpLocalLocal32, - binop_local_local_tee = BinOpLocalLocalTee32, - binop_local_const = BinOpLocalConst32, - binop_local_const_tee = BinOpLocalConstTee32 - ); - rewrite!(instrs, i, [Const32(c), I32And] => AndConstTee32(c, dst)); - rewrite!(instrs, i, [Const32(c), I32Sub] => SubConstTee32(c, dst)); - rewrite!(instrs, i, - [LocalGet32(addr), I32Load(memarg)] if - (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) => - LoadLocalTee32(memarg, addr, dst) - ); - rewrite!(instrs, i, - [LocalGet32(addr), F32Load(memarg)] if - (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) => - LoadLocalTee32(memarg, addr, dst) - ); - rewrite!(instrs, i, - [LoadLocal32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => - LoadLocalTee32(memarg, addr, dst) - ); - rewrite!(instrs, i, - [LoadLocal8S32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => - LoadLocalTee8S32(memarg, addr, dst) - ); - rewrite!(instrs, i, - [LoadLocal8U32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => - LoadLocalTee8U32(memarg, addr, dst) - ); - rewrite!(instrs, i, - [LoadLocal16S32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => - LoadLocalTee16S32(memarg, addr, dst) - ); - rewrite!(instrs, i, - [LoadLocal16U32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => - LoadLocalTee16U32(memarg, addr, dst) - ); - } - LocalTee64(dst) => { - fold_local_binop!( - instrs, i, dst, - source = resolve_local_source_64, - op = scalar_bin_op, - const = scalar_const_64, - local_local = BinOpLocalLocalTee64, - local_const = |dst, lhs, op, imm| Instruction::BinOpLocalConstTee64(op, lhs, imm, dst) - ); - rewrite_local_tee_direct!( - instrs, - i, - dst, - get = LocalGet64, - binop_local_local = BinOpLocalLocal64, - binop_local_local_tee = BinOpLocalLocalTee64, - binop_local_const = BinOpLocalConst64, - binop_local_const_tee = BinOpLocalConstTee64 - ); - rewrite!(instrs, i, [Const64(c), I64And] => AndConstTee64(c, dst)); - rewrite!(instrs, i, [Const64(c), I64Sub] => SubConstTee64(c, dst)); - } - LocalTee128(dst) => { - fold_local_binop!( - instrs, i, dst, - source = resolve_local_source_128, - op = bin_op_128, - const = const_128, - local_local = BinOpLocalLocalTee128, - local_const = |dst, lhs, op, imm| Instruction::BinOpLocalConstTee128(op, lhs, imm, dst) - ); - rewrite_local_tee_direct!( - instrs, - i, - dst, - get = LocalGet128, - binop_local_local = BinOpLocalLocal128, - binop_local_local_tee = BinOpLocalLocalTee128, - binop_local_const = BinOpLocalConst128, - binop_local_const_tee = BinOpLocalConstTee128 - ); - rewrite!(instrs, i, - [LocalGet32(addr), V128Load(memarg)] if - (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) => - LoadLocalTee128(memarg, addr, dst) - ); - } - Drop32 => { - rewrite!(instrs, i, - [BinOpStackLocalTee32(op, local, dst)] => - BinOpStackLocalSet32(op, local, dst) - ); - rewrite_drop_tee_direct!( - instrs, - i, - tee = LocalTee32, - set = LocalSet32, - binop_local_local_tee = BinOpLocalLocalTee32, - binop_local_local_set = BinOpLocalLocalSet32, - binop_local_const_tee = BinOpLocalConstTee32, - binop_local_const_set = BinOpLocalConstSet32 - ); - } - Drop64 => rewrite_drop_tee_direct!( - instrs, - i, - tee = LocalTee64, - set = LocalSet64, - binop_local_local_tee = BinOpLocalLocalTee64, - binop_local_local_set = BinOpLocalLocalSet64, - binop_local_const_tee = BinOpLocalConstTee64, - binop_local_const_set = BinOpLocalConstSet64 - ), - Drop128 => rewrite_drop_tee_direct!( - instrs, - i, - tee = LocalTee128, - set = LocalSet128, - binop_local_local_tee = BinOpLocalLocalTee128, - binop_local_local_set = BinOpLocalLocalSet128, - binop_local_const_tee = BinOpLocalConstTee128, - binop_local_const_set = BinOpLocalConstSet128 - ), - Jump(ip) => { - let target = resolve_jump_target(&source, ip); - let exit = old_idx as u32 + 1; - let body = target + 1; - - match source.get(target as usize).copied() { - Some(JumpCmpLocalLocal32 { target_ip, left, right, op }) - if resolve_jump_target(&source, target_ip) == exit && body > target => - { - instrs[i] = JumpCmpLocalLocal32 { target_ip: body, left, right, op: inverse_cmp_op(op) }; - } - Some(JumpCmpLocalLocal64 { target_ip, left, right, op }) - if resolve_jump_target(&source, target_ip) == exit && body > target => - { - instrs[i] = JumpCmpLocalLocal64 { target_ip: body, left, right, op: inverse_cmp_op(op) }; - } - _ => canonicalize_jump_like_with_target(&mut instrs, i, target, exit), - } - } - JumpIfZero32(ip) => { - let target = resolve_jump_target(&source, ip); - rewrite!(instrs, i, [LocalGet32(local), I32Eqz] => { - replace!(instrs, i, 2 => JumpIfLocalNonZero32 { target_ip: target, local }); - continue; - }); - rewrite!(instrs, i, [I32Eqz] => { - replace!(instrs, i, 1 => JumpIfNonZero32(target)); - continue; - }); - rewrite!(instrs, i, [LocalGet64(local), I64Eqz] => { - replace!(instrs, i, 2 => JumpIfLocalNonZero64 { target_ip: target, local }); - continue; - }); - rewrite!(instrs, i, [I64Eqz] => { - replace!(instrs, i, 1 => JumpIfNonZero64(target)); - continue; - }); - rewrite!(instrs, i, - [BinOpLocalConstTee32(op, local, imm, dst)] if (local == dst) => - match inc_delta(op, imm) { - Some(delta) => IncLocalJump32 { target_ip: target, local, delta, on_zero: true }, - None => BinOpLocalConstJump32 { target_ip: target, local, imm, op, on_zero: true }, - } - ); - rewrite!(instrs, i, - [AddConst32(imm), LocalTee32(local), LocalGet32(cond)] if (local == cond) => - IncStackTeeLocalJump32 { target_ip: target, local, delta: imm, on_zero: true } - ); - rewrite!(instrs, i, - [AndConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => - BinOpStackConstTeeLocalJump32 { target_ip: target, local, imm, op: BinOp::IAnd, on_zero: true } - ); - rewrite!(instrs, i, - [SubConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => - IncStackTeeLocalJump32 { target_ip: target, local, delta: imm.wrapping_neg(), on_zero: true } - ); - rewrite!(instrs, i, - [BinOpGlobalConst32(op, global, imm), GlobalTee32(dst)] if (global == dst) => - match inc_delta(op, imm) { - Some(delta) => IncGlobalJump32 { target_ip: target, global, delta, on_zero: true }, - None => BinOpGlobalConstJump32 { target_ip: target, global, imm, op, on_zero: true }, - } - ); - rewrite!(instrs, i, - [CmpLocalLocal32(op, left, right)] => - JumpCmpLocalLocal32 { target_ip: target, left, right, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, - [CmpLocalLocal64(op, left, right)] => - JumpCmpLocalLocal64 { target_ip: target, left, right, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, - [BinOpLocalConstTee32(binop, local, imm, dst), LocalGet32(right), cmp] if - (local == dst && let Some(cmp) = cmp_op(cmp)) => - match inc_delta(binop, imm) { - Some(delta) => IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op: inverse_cmp_op(cmp) }, - None => BinOpLocalConstJumpCmpLocal32 { target_ip: target, local, imm, binop, right, cmp: inverse_cmp_op(cmp) }, - } - ); - rewrite!(instrs, i, - [LocalGet32(local), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpStackLocal32 { target_ip: target, local, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, - [LocalGet64(local), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpStackLocal64 { target_ip: target, local, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, - [LocalGet32(local), Const32(imm), cmp] if (let Some(op) = cmp_op(cmp)) => - match (imm, inverse_cmp_op(op)) { - (0, CmpOp::Eq) => JumpIfLocalZero32 { target_ip: target, local }, - (0, CmpOp::Ne) => JumpIfLocalNonZero32 { target_ip: target, local }, - (imm, op) => JumpCmpLocalConst32 { target_ip: target, local, imm, op }, - } - ); - rewrite!(instrs, i, - [LocalGet64(local), Const64(imm), cmp] if - (let Some(op) = cmp_op(cmp) && let Ok(imm) = i32::try_from(imm)) => - match (imm, inverse_cmp_op(op)) { - (0, CmpOp::Eq) => JumpIfLocalZero64 { target_ip: target, local }, - (0, CmpOp::Ne) => JumpIfLocalNonZero64 { target_ip: target, local }, - (imm, op) => JumpCmpLocalConst64 { target_ip: target, local, imm, op }, - } - ); - rewrite!(instrs, i, - [LocalGet32(left), LocalGet32(right), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpLocalLocal32 { target_ip: target, left, right, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, - [LocalGet64(left), LocalGet64(right), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpLocalLocal64 { target_ip: target, left, right, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, [Const32(imm), cmp] if (let Some(op) = cmp_op(cmp)) => match (imm, inverse_cmp_op(op)) { - (0, CmpOp::Eq) => JumpIfZero32(target), - (0, CmpOp::Ne) => JumpIfNonZero32(target), - (imm, op) => JumpCmpStackConst32 { target_ip: target, imm, op }, - }); - rewrite!(instrs, i, [Const64(imm), cmp] if (let Some(op) = cmp_op(cmp)) => match (imm, inverse_cmp_op(op)) { - (0, CmpOp::Eq) => JumpIfZero64(target), - (0, CmpOp::Ne) => JumpIfNonZero64(target), - (imm, op) => JumpCmpStackConst64 { target_ip: target, imm, op }, - }); - rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalZero32 { target_ip: target, local }); - rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalZero64 { target_ip: target, local }); - canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1); - } - JumpIfNonZero32(ip) => { - let target = resolve_jump_target(&source, ip); - rewrite!(instrs, i, [LocalGet32(local), I32Eqz] => { - replace!(instrs, i, 2 => JumpIfLocalZero32 { target_ip: target, local }); - continue; - }); - rewrite!(instrs, i, [I32Eqz] => { - replace!(instrs, i, 1 => JumpIfZero32(target)); - continue; - }); - rewrite!(instrs, i, [LocalGet64(local), I64Eqz] => { - replace!(instrs, i, 2 => JumpIfLocalZero64 { target_ip: target, local }); - continue; - }); - rewrite!(instrs, i, [I64Eqz] => { - replace!(instrs, i, 1 => JumpIfZero64(target)); - continue; - }); - rewrite!(instrs, i, - [BinOpLocalConstTee32(op, local, imm, dst)] if (local == dst) => - match inc_delta(op, imm) { - Some(delta) => IncLocalJump32 { target_ip: target, local, delta, on_zero: false }, - None => BinOpLocalConstJump32 { target_ip: target, local, imm, op, on_zero: false }, - } - ); - rewrite!(instrs, i, - [AddConst32(imm), LocalTee32(local), LocalGet32(cond)] if (local == cond) => - IncStackTeeLocalJump32 { target_ip: target, local, delta: imm, on_zero: false } - ); - rewrite!(instrs, i, - [AndConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => - BinOpStackConstTeeLocalJump32 { target_ip: target, local, imm, op: BinOp::IAnd, on_zero: false } - ); - rewrite!(instrs, i, - [SubConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => - IncStackTeeLocalJump32 { target_ip: target, local, delta: imm.wrapping_neg(), on_zero: false } - ); - rewrite!(instrs, i, - [BinOpGlobalConst32(op, global, imm), GlobalTee32(dst)] if (global == dst) => - match inc_delta(op, imm) { - Some(delta) => IncGlobalJump32 { target_ip: target, global, delta, on_zero: false }, - None => BinOpGlobalConstJump32 { target_ip: target, global, imm, op, on_zero: false }, - } - ); - rewrite!(instrs, i, - [CmpLocalLocal32(op, left, right)] => - JumpCmpLocalLocal32 { target_ip: target, left, right, op } - ); - rewrite!(instrs, i, - [CmpLocalLocal64(op, left, right)] => - JumpCmpLocalLocal64 { target_ip: target, left, right, op } - ); - rewrite!(instrs, i, - [BinOpLocalConstTee32(binop, local, imm, dst), LocalGet32(right), cmp] if - (local == dst && let Some(cmp) = cmp_op(cmp)) => - match inc_delta(binop, imm) { - Some(delta) => IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op: cmp }, - None => BinOpLocalConstJumpCmpLocal32 { target_ip: target, local, imm, binop, right, cmp }, - } - ); - rewrite!(instrs, i, - [LocalGet32(local), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpStackLocal32 { target_ip: target, local, op } - ); - rewrite!(instrs, i, - [LocalGet64(local), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpStackLocal64 { target_ip: target, local, op } - ); - rewrite!(instrs, i, - [LocalGet32(local), Const32(imm), cmp] if (let Some(op) = cmp_op(cmp)) => - match (imm, op) { - (0, CmpOp::Eq) => JumpIfLocalZero32 { target_ip: target, local }, - (0, CmpOp::Ne) => JumpIfLocalNonZero32 { target_ip: target, local }, - (imm, op) => JumpCmpLocalConst32 { target_ip: target, local, imm, op }, - } - ); - rewrite!(instrs, i, - [LocalGet64(local), Const64(imm), cmp] if - (let Some(op) = cmp_op(cmp) && let Ok(imm) = i32::try_from(imm)) => - match (imm, op) { - (0, CmpOp::Eq) => JumpIfLocalZero64 { target_ip: target, local }, - (0, CmpOp::Ne) => JumpIfLocalNonZero64 { target_ip: target, local }, - (imm, op) => JumpCmpLocalConst64 { target_ip: target, local, imm, op }, - } - ); - rewrite!(instrs, i, - [LocalGet32(left), LocalGet32(right), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpLocalLocal32 { target_ip: target, left, right, op } - ); - rewrite!(instrs, i, - [LocalGet64(left), LocalGet64(right), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpLocalLocal64 { target_ip: target, left, right, op } - ); - rewrite!(instrs, i, [Const32(imm), cmp] if (let Some(op) = cmp_op(cmp)) => match (imm, op) { - (0, CmpOp::Eq) => JumpIfZero32(target), - (0, CmpOp::Ne) => JumpIfNonZero32(target), - (imm, op) => JumpCmpStackConst32 { target_ip: target, imm, op }, - }); - rewrite!(instrs, i, [Const64(imm), cmp] if (let Some(op) = cmp_op(cmp)) => match (imm, op) { - (0, CmpOp::Eq) => JumpIfZero64(target), - (0, CmpOp::Ne) => JumpIfNonZero64(target), - (imm, op) => JumpCmpStackConst64 { target_ip: target, imm, op }, - }); - rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalNonZero32 { target_ip: target, local }); - rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalNonZero64 { target_ip: target, local }); - canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1); - } - JumpIfZero64(ip) => { - let target = resolve_jump_target(&source, ip); - rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalZero64 { target_ip: target, local }); - canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1); - } - JumpIfNonZero64(ip) => { - let target = resolve_jump_target(&source, ip); - rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalNonZero64 { target_ip: target, local }); - canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1); - } - JumpCmpStackConst32 { target_ip, imm: 0, op } => { - match op { - CmpOp::Eq => instrs[i] = JumpIfZero32(target_ip), - CmpOp::Ne => instrs[i] = JumpIfNonZero32(target_ip), - _ => {} - } - canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1); - } - JumpCmpStackConst64 { target_ip, imm: 0, op } => { - match op { - CmpOp::Eq => instrs[i] = JumpIfZero64(target_ip), - CmpOp::Ne => instrs[i] = JumpIfNonZero64(target_ip), - _ => {} - } - canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1); - } - JumpCmpLocalConst32 { target_ip, local, imm: 0, op } => { - match op { - CmpOp::Eq => instrs[i] = JumpIfLocalZero32 { target_ip, local }, - CmpOp::Ne => instrs[i] = JumpIfLocalNonZero32 { target_ip, local }, - _ => {} - } - canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1); - } - JumpCmpLocalConst64 { target_ip, local, imm: 0, op } => { - match op { - CmpOp::Eq => instrs[i] = JumpIfLocalZero64 { target_ip, local }, - CmpOp::Ne => instrs[i] = JumpIfLocalNonZero64 { target_ip, local }, - _ => {} - } - canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1); - } - JumpCmpStackConst32 { .. } - | JumpCmpStackConst64 { .. } - | JumpCmpLocalConst32 { .. } - | JumpCmpLocalConst64 { .. } - | JumpCmpLocalLocal32 { .. } - | JumpCmpLocalLocal64 { .. } - | JumpIfLocalZero32 { .. } - | JumpIfLocalNonZero32 { .. } - | JumpIfLocalZero64 { .. } - | JumpIfLocalNonZero64 { .. } => { - canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1); - } - _ => {} - } - - after_terminator = is_unconditional_terminator(instr); - } - - old_to_new[source.len()] = instrs.len() as u32; - (instrs.instructions, old_to_new) -} - -fn cmp_op(instr: Instruction) -> Option { - Some(match instr { - Instruction::I32Eq | Instruction::I64Eq => CmpOp::Eq, - Instruction::I32Ne | Instruction::I64Ne => CmpOp::Ne, - Instruction::I32LtS | Instruction::I64LtS => CmpOp::LtS, - Instruction::I32LtU | Instruction::I64LtU => CmpOp::LtU, - Instruction::I32GtS | Instruction::I64GtS => CmpOp::GtS, - Instruction::I32GtU | Instruction::I64GtU => CmpOp::GtU, - Instruction::I32LeS | Instruction::I64LeS => CmpOp::LeS, - Instruction::I32LeU | Instruction::I64LeU => CmpOp::LeU, - Instruction::I32GeS | Instruction::I64GeS => CmpOp::GeS, - Instruction::I32GeU | Instruction::I64GeU => CmpOp::GeU, - _ => return None, - }) -} - -fn inc_delta(op: BinOp, imm: i32) -> Option { - match op { - BinOp::IAdd => Some(imm), - BinOp::ISub => Some(imm.wrapping_neg()), - _ => None, - } -} - -fn int_bin_op(instr: Instruction) -> Option { - Some(match instr { - Instruction::I32Add | Instruction::I64Add => BinOp::IAdd, - Instruction::I32Sub | Instruction::I64Sub => BinOp::ISub, - Instruction::I32Mul | Instruction::I64Mul => BinOp::IMul, - Instruction::I32And | Instruction::I64And => BinOp::IAnd, - Instruction::I32Or | Instruction::I64Or => BinOp::IOr, - Instruction::I32Xor | Instruction::I64Xor => BinOp::IXor, - Instruction::I32Shl | Instruction::I64Shl => BinOp::IShl, - Instruction::I32ShrS | Instruction::I64ShrS => BinOp::IShrS, - Instruction::I32ShrU | Instruction::I64ShrU => BinOp::IShrU, - Instruction::I32Rotl | Instruction::I64Rotl => BinOp::IRotl, - Instruction::I32Rotr | Instruction::I64Rotr => BinOp::IRotr, - _ => return None, - }) -} - -fn float_bin_op(instr: Instruction) -> Option { - Some(match instr { - Instruction::F32Add | Instruction::F64Add => BinOp::FAdd, - Instruction::F32Sub | Instruction::F64Sub => BinOp::FSub, - Instruction::F32Mul | Instruction::F64Mul => BinOp::FMul, - Instruction::F32Div | Instruction::F64Div => BinOp::FDiv, - Instruction::F32Min | Instruction::F64Min => BinOp::FMin, - Instruction::F32Max | Instruction::F64Max => BinOp::FMax, - Instruction::F32Copysign | Instruction::F64Copysign => BinOp::FCopysign, - _ => return None, - }) -} - -fn scalar_bin_op(instr: Instruction) -> Option { - int_bin_op(instr).or_else(|| float_bin_op(instr)) -} - -fn scalar_const_32(instr: Instruction, op_instr: Instruction) -> Option { - match instr { - Instruction::Const32(c) if scalar_bin_op(op_instr).is_some() => Some(c), - _ => None, - } -} - -fn scalar_const_64(instr: Instruction, op_instr: Instruction) -> Option { - match instr { - Instruction::Const64(c) if scalar_bin_op(op_instr).is_some() => Some(c), - _ => None, - } -} - -fn const_128(instr: Instruction, op_instr: Instruction) -> Option { - match instr { - Instruction::Const128(c) if bin_op_128(op_instr).is_some() => Some(c), - _ => None, - } -} - -define_local_source_resolver!( - resolve_local_source_32, - get = LocalGet32, - tee = LocalTee32, - set = LocalSet32, - binop_local_local_tee = BinOpLocalLocalTee32, - binop_local_local_set = BinOpLocalLocalSet32, - binop_local_const_tee = BinOpLocalConstTee32, - binop_local_const_set = BinOpLocalConstSet32, - load_local_tee = LoadLocalTee32, - load_local_set = LoadLocalSet32 -); - -define_local_source_resolver!( - resolve_local_source_64, - get = LocalGet64, - tee = LocalTee64, - set = LocalSet64, - binop_local_local_tee = BinOpLocalLocalTee64, - binop_local_local_set = BinOpLocalLocalSet64, - binop_local_const_tee = BinOpLocalConstTee64, - binop_local_const_set = BinOpLocalConstSet64 -); - -define_local_source_resolver!( - resolve_local_source_128, - get = LocalGet128, - tee = LocalTee128, - set = LocalSet128, - binop_local_local_tee = BinOpLocalLocalTee128, - binop_local_local_set = BinOpLocalLocalSet128, - binop_local_const_tee = BinOpLocalConstTee128, - binop_local_const_set = BinOpLocalConstSet128, - load_local_tee = LoadLocalTee128, - load_local_set = LoadLocalSet128 -); - -fn bin_op_128(instr: Instruction) -> Option { - Some(match instr { - Instruction::V128And => BinOp128::And, - Instruction::V128AndNot => BinOp128::AndNot, - Instruction::V128Or => BinOp128::Or, - Instruction::V128Xor => BinOp128::Xor, - Instruction::I64x2Add => BinOp128::I64x2Add, - Instruction::I64x2Mul => BinOp128::I64x2Mul, - _ => return None, - }) -} - -fn inverse_cmp_op(op: CmpOp) -> CmpOp { - match op { - CmpOp::Eq => CmpOp::Ne, - CmpOp::Ne => CmpOp::Eq, - CmpOp::LtS => CmpOp::GeS, - CmpOp::LtU => CmpOp::GeU, - CmpOp::GtS => CmpOp::LeS, - CmpOp::GtU => CmpOp::LeU, - CmpOp::LeS => CmpOp::GtS, - CmpOp::LeU => CmpOp::GtU, - CmpOp::GeS => CmpOp::LtS, - CmpOp::GeU => CmpOp::LtU, - } -} - -fn resolve_jump_target(instrs: &[Instruction], target: u32) -> u32 { - let mut idx = target as usize; - let mut steps = 0usize; - - while let Some(Instruction::Jump(next)) = instrs.get(idx) - && steps < instrs.len() - { - idx = *next as usize; - steps += 1; - } - - idx as u32 -} - -fn instruction_target_mut(instr: &mut Instruction) -> Option<&mut u32> { - Some(match instr { - Instruction::Jump(ip) - | Instruction::JumpIfZero32(ip) - | Instruction::JumpIfNonZero32(ip) - | Instruction::JumpIfZero64(ip) - | Instruction::JumpIfNonZero64(ip) - | Instruction::JumpIfRefNull(ip) - | Instruction::JumpIfRefNonNull(ip) - | Instruction::BrOnCast(ip, _, _) - | Instruction::JumpCmpStackConst32 { target_ip: ip, .. } - | Instruction::JumpCmpStackConst64 { target_ip: ip, .. } - | Instruction::JumpCmpStackLocal32 { target_ip: ip, .. } - | Instruction::JumpCmpStackLocal64 { target_ip: ip, .. } - | Instruction::BinOpLocalConstJump32 { target_ip: ip, .. } - | Instruction::BinOpLocalConstJumpCmpLocal32 { target_ip: ip, .. } - | Instruction::BinOpStackConstTeeLocalJump32 { target_ip: ip, .. } - | Instruction::BinOpGlobalConstJump32 { target_ip: ip, .. } - | Instruction::IncLocalJump32 { target_ip: ip, .. } - | Instruction::IncStackTeeLocalJump32 { target_ip: ip, .. } - | Instruction::IncGlobalJump32 { target_ip: ip, .. } - | Instruction::IncLocalJumpCmpLocal32 { target_ip: ip, .. } - | Instruction::JumpIfLocalZero32 { target_ip: ip, .. } - | Instruction::JumpIfLocalNonZero32 { target_ip: ip, .. } - | Instruction::JumpIfLocalZero64 { target_ip: ip, .. } - | Instruction::JumpIfLocalNonZero64 { target_ip: ip, .. } - | Instruction::JumpCmpLocalConst32 { target_ip: ip, .. } - | Instruction::JumpCmpLocalConst64 { target_ip: ip, .. } - | Instruction::JumpCmpLocalLocal32 { target_ip: ip, .. } - | Instruction::JumpCmpLocalLocal64 { target_ip: ip, .. } => ip, - Instruction::BranchTable(ip, _, _) => ip, - _ => return None, - }) -} - -fn instruction_target(instr: &Instruction) -> Option { - let mut instr = *instr; - instruction_target_mut(&mut instr).copied() -} - -fn canonicalize_jump_like(source: &[Instruction], instrs: &mut Vec, idx: usize, fallthrough: u32) { - let Some(target) = instruction_target(&instrs[idx]) else { - return; - }; - - canonicalize_jump_like_with_target(instrs, idx, resolve_jump_target(source, target), fallthrough); -} - -fn canonicalize_jump_like_with_target(instrs: &mut Vec, idx: usize, target: u32, fallthrough: u32) { - if matches!(instrs[idx], Instruction::Jump(_)) && target == fallthrough { - instrs.truncate(idx); - } else if let Some(ip) = instruction_target_mut(&mut instrs[idx]) { - *ip = target; - } -} - -fn is_unconditional_terminator(instr: Instruction) -> bool { - matches!( - instr, - Instruction::Unreachable - | Instruction::Jump(_) - | Instruction::BranchTable(..) - | Instruction::Return - | Instruction::ReturnVoid - | Instruction::Return32 - | Instruction::Return64 - | Instruction::Return128 - | Instruction::ReturnCall(_) - | Instruction::ReturnCallSelf - | Instruction::ReturnCallIndirect(..) - | Instruction::ReturnCallRef(_) - | Instruction::Throw(_) - | Instruction::ThrowRef - ) -} - -fn target_boundaries(instructions: &[Instruction], function_data: &WasmFunctionData) -> Result> { - let mut boundaries = alloc::vec![false; instructions.len() + 1]; - for handler in &function_data.exception_handlers { - for target in [handler.start_ip, handler.end_ip] { - let boundary = boundaries.get_mut(target as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("exception handler boundary out of bounds: {target}")) - })?; - *boundary = true; - } - for catch in &handler.catches { - let target = catch.landing_pad(); - let boundary = boundaries - .get_mut(target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("exception landing pad out of bounds: {target}")))?; - *boundary = true; - } - } - for instr in instructions { - if let Some(target) = instruction_target(instr) { - let boundary = boundaries - .get_mut(target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))?; - *boundary = true; - } - if let Instruction::BranchTable(_, start, count) = *instr { - let end = - start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; - let targets = function_data - .branch_table_targets - .get(start as usize..end as usize) - .ok_or_else(|| ParseError::Other("branch table range out of bounds".into()))?; - for &target in targets { - let boundary = boundaries - .get_mut(target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("branch table target out of bounds: {target}")))?; - *boundary = true; - } - } - } - Ok(boundaries) -} - -/// Remaps rewritten targets, then validates targets and ranges while detecting local memory use. -fn finalize( - instructions: &mut [Instruction], - function_data: &mut WasmFunctionData, - old_to_new: Option<&[u32]>, - imported_memory_count: u32, -) -> Result { - let len = instructions.len() as u32; - for handler in &mut function_data.exception_handlers { - if let Some(old_to_new) = old_to_new { - handler.start_ip = *old_to_new.get(handler.start_ip as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("exception handler boundary out of bounds: {}", handler.start_ip)) - })?; - handler.end_ip = *old_to_new.get(handler.end_ip as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("exception handler boundary out of bounds: {}", handler.end_ip)) - })?; - for catch in &mut handler.catches { - let landing_pad = match catch { - tinywasm_types::ExceptionCatch::Tag { landing_pad, .. } - | tinywasm_types::ExceptionCatch::All { landing_pad, .. } => landing_pad, - }; - *landing_pad = *old_to_new.get(*landing_pad as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("exception landing pad out of bounds: {landing_pad}")) - })?; - } - } - if handler.start_ip > handler.end_ip || handler.end_ip > len { - return Err(ParseError::Other("exception handler range out of bounds".into())); - } - if handler.catches.iter().any(|catch| catch.landing_pad() >= len) { - return Err(ParseError::Other("exception landing pad out of bounds".into())); - } - } - for target in &mut function_data.branch_table_targets { - if let Some(old_to_new) = old_to_new { - *target = *old_to_new - .get(*target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))?; - } - if *target >= len { - return Err(ParseError::Other(alloc::format!("branch table target out of bounds: {target}"))); - } - } - - let mut uses_local_memory = false; - for instr in instructions { - if let Some(target) = instruction_target_mut(instr) { - if let Some(old_to_new) = old_to_new { - *target = *old_to_new - .get(*target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))?; - } - if *target >= len { - return Err(ParseError::Other(alloc::format!("instruction target out of bounds: {target}"))); - } - } - if let Instruction::BranchTable(_, start, count) = *instr { - let end = - start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; - function_data - .branch_table_targets - .get(start as usize..end as usize) - .ok_or_else(|| ParseError::Other("branch table range out of bounds".into()))?; - } - uses_local_memory |= instr.memory_addr().is_some_and(|mem| mem >= imported_memory_count); - } - Ok(uses_local_memory) -} diff --git a/crates/parser/src/optimize/mod.rs b/crates/parser/src/optimize/mod.rs new file mode 100644 index 0000000..09501f9 --- /dev/null +++ b/crates/parser/src/optimize/mod.rs @@ -0,0 +1,4 @@ +mod rewrite; +mod targets; + +pub(crate) use rewrite::optimize_instructions; diff --git a/crates/parser/src/optimize/rewrite.rs b/crates/parser/src/optimize/rewrite.rs new file mode 100644 index 0000000..1146da7 --- /dev/null +++ b/crates/parser/src/optimize/rewrite.rs @@ -0,0 +1,1397 @@ +use super::targets::{finalize, resolve_jump_target, set_rewrite_target, target_boundaries}; +use crate::macros::optimize::{replace, rewrite}; +use crate::visit::FunctionDataBuilder as WasmFunctionData; +use crate::{ParserOptions, Result}; +use alloc::vec::Vec; +use core::ops::{Deref, DerefMut}; +use tinywasm_types::{ + BinOp, BinOp128, CmpOp, CompactMemoryArg, GlobalConst32, GlobalConst64, GlobalUpdate, GlobalV128, I32LocalArg, + I64Operand, Instruction, LocalConst64, LocalConstCmp, LocalConstSet32, LocalConstSet64, LocalConstSetV128, + LocalLocalCmp, LocalTripleArg, LocalU32, LocalUpdate, LocalUpdateCmp, LocalV128, MemoryArg, MemoryFillConstOp, + MemoryLocalArg, OperandIdx, PackedOp, StackConst32, StackConst64, TargetLocal, TargetLocalArg, V128Operand, + ValueCounts, +}; + +pub(crate) struct OptimizeResult { + pub(crate) instructions: Vec, +} + +struct CompactOutput { + instructions: Vec, + block_start: usize, +} + +macro_rules! operand { + ($data:expr, $value:expr) => { + $data.push_operand($value) + }; +} + +macro_rules! target_operand { + ($data:expr, $value:expr) => { + $data.push_target_operand($value) + }; +} + +impl Deref for CompactOutput { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.instructions + } +} + +impl DerefMut for CompactOutput { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.instructions + } +} + +pub(crate) fn optimize_instructions( + mut instructions: Vec, + function_data: &mut WasmFunctionData, + options: &ParserOptions, + function_results: ValueCounts, + self_func_addr: u32, +) -> Result { + let boundaries = target_boundaries(&instructions, function_data)?; + let (rewritten, old_to_new) = if options.optimize_rewrite() { + let (instructions, map) = rewrite(instructions, function_data, &boundaries, function_results, self_func_addr)?; + (instructions, Some(map)) + } else { + (instructions, None) + }; + instructions = rewritten; + finalize(&mut instructions, function_data, old_to_new.as_deref())?; + Ok(OptimizeResult { instructions }) +} + +fn rewrite( + source: Vec, + data: &mut WasmFunctionData, + boundaries: &[bool], + function_results: ValueCounts, + self_func_addr: u32, +) -> Result<(Vec, Vec)> { + #![allow(unused_assignments)] + use Instruction::*; + + let return_instruction = match function_results { + ValueCounts { c32: 0, c64: 0, c128: 0 } => Some(ReturnVoid), + ValueCounts { c32: 1, c64: 0, c128: 0 } => Some(Return32), + ValueCounts { c32: 0, c64: 1, c128: 0 } => Some(Return64), + ValueCounts { c32: 0, c64: 0, c128: 1 } => Some(Return128), + _ => None, + }; + let mut output = CompactOutput { instructions: Vec::with_capacity(source.len()), block_start: 0 }; + let mut old_to_new = alloc::vec![0; source.len() + 1]; + let mut after_terminator = false; + + for (old_index, instruction) in source.iter().copied().enumerate() { + if boundaries[old_index] || after_terminator { + output.block_start = output.len(); + } + after_terminator = is_unconditional_terminator(instruction); + old_to_new[old_index] = output.len() as u32; + output.push(instruction); + let mut read = output.len() - 1; + + match output[read] { + LocalCopy32(a, b) | LocalCopy64(a, b) | LocalCopy128(a, b) if a == b => { + output.pop(); + } + Call(address) if address == self_func_addr => output[read] = CallSelf, + ReturnCall(address) if address == self_func_addr => output[read] = ReturnCallSelf, + Return if let Some(specialized) = return_instruction => output[read] = specialized, + raw @ (I32Add | I32Mul | I32And | I32Or | I32Xor) => { + let op = int_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); + rewrite!(output, read, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); + rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); + if rewrite_scalar_const32(&mut output, &mut read, data, op, true)? { + continue; + } + if op == BinOp::IAdd { + rewrite!(output, read, [Const32(value)] => AddConst32(value)); + rewrite!(output, read, [I32Add] => I32Add3); + if read > output.block_start + && let BinOpStackLocal32(BinOp::IAdd, local) = output[read - 1] + { + output.truncate(read - 1); + output.extend([LocalGet32(local), I32Add3]); + read = output.len() - 1; + } + } + } + raw @ (I32Sub | I32Shl | I32ShrS | I32ShrU | I32Rotl | I32Rotr) => { + let op = int_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); + rewrite!(output, read, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); + rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); + if rewrite_scalar_const32(&mut output, &mut read, data, op, false)? { + continue; + } + rewrite_sign_extend32(&mut output, &mut read, data, op); + } + raw @ (I64Add | I64Mul | I64And | I64Or | I64Xor) => { + let op = int_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); + rewrite!(output, read, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); + if rewrite_scalar_const64(&mut output, &mut read, data, op, true)? { + continue; + } + if op == BinOp::IAdd { + rewrite!(output, read, [Const64(index)] => AddConst64(index)); + rewrite!(output, read, [I64Add] => I64Add3); + } + } + raw @ (I64Sub | I64Shl | I64ShrS | I64ShrU | I64Rotl | I64Rotr) => { + let op = int_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); + rewrite!(output, read, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); + if rewrite_scalar_const64(&mut output, &mut read, data, op, false)? { + continue; + } + rewrite_sign_extend64(&mut output, &mut read, data, op); + } + raw if cmp_op(raw).is_some() => { + let op = cmp_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => CmpLocalLocal32(op, a, b)); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => CmpLocalLocal64(op, a, b)); + } + raw @ (F32Add | F32Mul | F32Min | F32Max) => { + let op = float_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); + rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); + rewrite_scalar_const32(&mut output, &mut read, data, op, true)?; + } + raw @ (F32Sub | F32Div | F32Copysign) => { + let op = float_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); + rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); + rewrite_scalar_const32(&mut output, &mut read, data, op, false)?; + } + raw @ (F64Add | F64Mul | F64Min | F64Max) => { + let op = float_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); + rewrite_scalar_const64(&mut output, &mut read, data, op, true)?; + } + raw @ (F64Sub | F64Div | F64Copysign) => { + let op = float_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); + rewrite_scalar_const64(&mut output, &mut read, data, op, false)?; + } + raw @ (V128And | V128Or | V128Xor | I64x2Add | I64x2Mul | V128AndNot) => { + let op = bin_op_128(raw).unwrap(); + rewrite!(output, read, [LocalGet128(local)] => + BinOpStackLocal128(op, local) + ); + rewrite_vector_binop(&mut output, &mut read, data, op, raw != V128AndNot)?; + } + I32Store(index) | F32Store(index) => rewrite_store32(&mut output, &mut read, data, index)?, + I64Store(index) | F64Store(index) => rewrite_store64(&mut output, &mut read, data, index)?, + V128Store(index) => { + if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { + rewrite!(output, read, + [LocalGet32(addr), LocalGet128(value)] if + (let (Ok(addr), Ok(value)) = (u8::try_from(addr), u8::try_from(value))) => + StoreLocalLocal128(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value }) + ); + } + } + I32Load(index) | F32Load(index) => { + if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { + rewrite!(output, read, [LocalGet32(local) | LocalGet64(local)] if + (let Ok(local) = u8::try_from(local)) => + LoadLocal32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }) + ); + } + } + I64Load(index) | F64Load(index) => { + if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { + rewrite!(output, read, [LocalGet32(local) | LocalGet64(local)] if + (let Ok(local) = u8::try_from(local)) => + LoadLocal64(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }) + ); + } + } + raw @ (I32Load8S(index) | I32Load8U(index) | I32Load16S(index) | I32Load16U(index)) => { + if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { + rewrite!(output, read, [LocalGet32(local) | LocalGet64(local)] if + (let Ok(local) = u8::try_from(local)) => match raw { + I32Load8S(_) => LoadLocal8S32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), + I32Load8U(_) => LoadLocal8U32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), + I32Load16S(_) => LoadLocal16S32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), + I32Load16U(_) => LoadLocal16U32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), + _ => unreachable!(), + } + ); + } + } + MemoryFill(memory) => rewrite!(output, read, [Const32(value), Const32(size)] => { + let index = operand!(data, MemoryFillConstOp { memory, byte: value as u8, value: size })?; + replace!(output, read, 2 => MemoryFillConst(index)); + }), + GlobalGet32(dst) => rewrite!(output, read, [GlobalSet32(src)] if (src == dst) => GlobalTee32(src)), + GlobalGet64(dst) => rewrite!(output, read, [GlobalSet64(src)] if (src == dst) => GlobalTee64(src)), + GlobalGet128(dst) => rewrite!(output, read, [GlobalSet128(src)] if (src == dst) => GlobalTee128(src)), + LocalGet32(dst) => rewrite!(output, read, [LocalSet32(src)] if (src == dst) => LocalTee32(src)), + LocalGet64(dst) => rewrite!(output, read, [LocalSet64(src)] if (src == dst) => LocalTee64(src)), + LocalGet128(dst) => rewrite!(output, read, [LocalSet128(src)] if (src == dst) => LocalTee128(src)), + LocalSet32(dst) => rewrite_local_set32(&mut output, &mut read, data, dst)?, + LocalSet64(dst) => rewrite_local_set64(&mut output, &mut read, data, dst)?, + LocalSet128(dst) => rewrite_local_set128(&mut output, &mut read, data, dst)?, + LocalTee32(dst) => rewrite_local_tee32(&mut output, &mut read, data, dst)?, + LocalTee64(dst) => rewrite_local_tee64(&mut output, &mut read, data, dst)?, + LocalTee128(dst) => rewrite_local_tee128(&mut output, &mut read, data, dst)?, + Drop32 => { + rewrite!(output, read, [LocalTee32(local)] => LocalSet32(local)); + rewrite!(output, read, [BinOpStackLocalTee32(op, local, dst)] => BinOpStackLocalSet32(op, local, dst)); + rewrite!(output, read, [AddLocalLocalTee32(arg)] => AddLocalLocalSet32(arg)); + rewrite!(output, read, [BinOpLocalLocalTee32(packed)] => BinOpLocalLocalSet32(packed)); + rewrite!(output, read, [BinOpLocalConstTee32(packed)] => BinOpLocalConstSet32(packed)); + } + Drop64 => { + rewrite!(output, read, [LocalTee64(local)] => LocalSet64(local)); + rewrite!(output, read, [BinOpLocalLocalTee64(packed)] => BinOpLocalLocalSet64(packed)); + rewrite!(output, read, [BinOpLocalConstTee64(packed)] => BinOpLocalConstSet64(packed)); + } + Drop128 => { + rewrite!(output, read, [LocalTee128(local)] => LocalSet128(local)); + rewrite!(output, read, [BinOpLocalLocalTee128(packed)] => BinOpLocalLocalSet128(packed)); + rewrite!(output, read, [BinOpLocalConstTee128(packed)] => BinOpLocalConstSet128(packed)); + } + Jump(target) => rewrite_jump(&source, &mut output, read, data, old_index as u32, target)?, + JumpIfZero32(target) => rewrite_conditional(&source, &mut output, &mut read, data, target, true)?, + JumpIfNonZero32(target) => rewrite_conditional(&source, &mut output, &mut read, data, target, false)?, + JumpIfZero64(target) => { + rewrite!(output, read, [LocalGet64(local)] => + JumpIfLocalZero64(TargetLocalArg { target_ip: target, local }) + ); + } + JumpIfNonZero64(target) => { + rewrite!(output, read, [LocalGet64(local)] => + JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local }) + ); + } + JumpCmpStackConst32(_) + | JumpCmpStackConst64(_) + | JumpCmpLocalConst32(_) + | JumpCmpLocalConst64(_) + | JumpCmpLocalLocal32(_) + | JumpCmpLocalLocal64(_) + | JumpIfLocalZero32(_) + | JumpIfLocalNonZero32(_) + | JumpIfLocalZero64(_) + | JumpIfLocalNonZero64(_) => {} + _ => {} + } + } + for instruction in &mut output.instructions { + match *instruction { + Instruction::Const64(index) => { + let value = data.operand(index).value; + if value == i64::from(value as i32) { + *instruction = Instruction::Const64Imm(value as i32); + } + } + Instruction::Const128(index) => { + let value = u128::from_le_bytes(data.operand(index).value); + if let Ok(value) = u32::try_from(value) { + *instruction = Instruction::Const128Imm(value); + } + } + _ => {} + } + } + let end = old_to_new.len() - 1; + old_to_new[end] = output.len() as u32; + Ok((output.instructions, old_to_new)) +} + +fn local_const32(data: &WasmFunctionData, instruction: Instruction) -> Option<(BinOp, u16, i32)> { + match instruction { + Instruction::AddLocalConst32(arg) => Some((BinOp::IAdd, arg.local, arg.value)), + Instruction::SubLocalConst32(arg) => Some((BinOp::ISub, arg.local, arg.value)), + Instruction::MulLocalConst32(arg) => Some((BinOp::IMul, arg.local, arg.value)), + Instruction::BinOpLocalConst32(packed) => { + let value = data.operand(packed.index); + Some((packed.op, value.local, value.value as i32)) + } + _ => None, + } +} + +fn local_const64(data: &WasmFunctionData, instruction: Instruction) -> Option<(BinOp, u16, i64)> { + let Instruction::BinOpLocalConst64(packed) = instruction else { return None }; + let value = data.operand(packed.index); + Some((packed.op, value.local, value.value as i64)) +} + +fn local_const128( + data: &WasmFunctionData, + instruction: Instruction, +) -> Option<(BinOp128, u16, OperandIdx)> { + let Instruction::BinOpLocalConst128(packed) = instruction else { return None }; + let value = data.operand(packed.index); + Some((packed.op, value.local, value.value)) +} + +fn compact_memory_arg( + data: &mut WasmFunctionData, + index: OperandIdx, +) -> Result>> { + let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) else { return Ok(None) }; + Ok(Some(operand!(data, arg)?)) +} + +fn rewrite_scalar_const32( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + op: BinOp, + commutative: bool, +) -> Result { + if *read < output.block_start + 2 { + return Ok(false); + } + let previous = &output[*read - 2..*read]; + let replacement = match previous { + [Instruction::LocalGet32(local), Instruction::Const32(value)] => { + let arg = I32LocalArg { value: *value, local: *local }; + match op { + BinOp::IAdd => Instruction::AddLocalConst32(arg), + BinOp::ISub => Instruction::SubLocalConst32(arg), + BinOp::IMul => Instruction::MulLocalConst32(arg), + _ => Instruction::BinOpLocalConst32(PackedOp::new( + op, + operand!(data, LocalU32 { local: *local, value: *value as u32 })?, + )), + } + } + [Instruction::GlobalGet32(global), Instruction::Const32(value)] => Instruction::BinOpGlobalConst32( + PackedOp::new(op, operand!(data, GlobalConst32 { global: *global, value: *value as u32 })?), + ), + [Instruction::Const32(value), Instruction::LocalGet32(local)] if commutative => { + let arg = I32LocalArg { value: *value, local: *local }; + match op { + BinOp::IAdd => Instruction::AddLocalConst32(arg), + BinOp::IMul => Instruction::MulLocalConst32(arg), + _ => Instruction::BinOpLocalConst32(PackedOp::new( + op, + operand!(data, LocalU32 { local: *local, value: *value as u32 })?, + )), + } + } + [Instruction::Const32(value), Instruction::GlobalGet32(global)] if commutative => { + Instruction::BinOpGlobalConst32(PackedOp::new( + op, + operand!(data, GlobalConst32 { global: *global, value: *value as u32 })?, + )) + } + _ => return Ok(false), + }; + replace!(output, *read, 2 => replacement); + Ok(true) +} + +fn rewrite_scalar_const64( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + op: BinOp, + commutative: bool, +) -> Result { + if *read < output.block_start + 2 { + return Ok(false); + } + let previous = [output[*read - 2], output[*read - 1]]; + let replacement = match previous { + [Instruction::LocalGet64(local), Instruction::Const64(index)] => Instruction::BinOpLocalConst64(PackedOp::new( + op, + operand!(data, LocalConst64 { local, value: data.operand(index).value as u64 })?, + )), + [Instruction::GlobalGet64(global), Instruction::Const64(index)] => Instruction::BinOpGlobalConst64( + PackedOp::new(op, operand!(data, GlobalConst64 { global, value: data.operand(index).value as u64 })?), + ), + [Instruction::Const64(index), Instruction::LocalGet64(local)] if commutative => Instruction::BinOpLocalConst64( + PackedOp::new(op, operand!(data, LocalConst64 { local, value: data.operand(index).value as u64 })?), + ), + [Instruction::Const64(index), Instruction::GlobalGet64(global)] if commutative => { + Instruction::BinOpGlobalConst64(PackedOp::new( + op, + operand!(data, GlobalConst64 { global, value: data.operand(index).value as u64 })?, + )) + } + _ => return Ok(false), + }; + replace!(output, *read, 2 => replacement); + Ok(true) +} + +fn rewrite_sign_extend32(output: &mut CompactOutput, read: &mut usize, data: &WasmFunctionData, op: BinOp) -> bool { + if op != BinOp::IShrS || *read < output.block_start + 2 { + return false; + } + if let Some((BinOp::IShl, local, shift)) = local_const32(data, output[*read - 2]) + && let Instruction::Const32(right) = output[*read - 1] + && shift == right + && matches!(shift, 16 | 24) + { + output.truncate(*read - 2); + output.extend([ + Instruction::LocalGet32(local), + if shift == 24 { Instruction::I32Extend8S } else { Instruction::I32Extend16S }, + ]); + *read = output.len() - 1; + return true; + } + false +} + +fn rewrite_sign_extend64(output: &mut CompactOutput, read: &mut usize, data: &WasmFunctionData, op: BinOp) -> bool { + if op != BinOp::IShrS || *read < output.block_start + 2 { + return false; + } + if let Some((BinOp::IShl, local, shift)) = local_const64(data, output[*read - 2]) + && let Instruction::Const64(index) = output[*read - 1] + && shift == data.operand(index).value + { + let instruction = match shift { + 56 => Instruction::I64Extend8S, + 48 => Instruction::I64Extend16S, + 32 => Instruction::I64Extend32S, + _ => return false, + }; + output.truncate(*read - 2); + output.extend([Instruction::LocalGet64(local), instruction]); + *read = output.len() - 1; + return true; + } + false +} + +fn rewrite_vector_binop( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + op: BinOp128, + commutative: bool, +) -> Result<()> { + if *read >= output.block_start + 2 { + let previous = [output[*read - 2], output[*read - 1]]; + let replacement = match previous { + [Instruction::LocalGet128(a), Instruction::LocalGet128(b)] => Instruction::BinOpLocalLocal128(op, a, b), + [Instruction::LocalGet128(local), Instruction::Const128(value)] => { + Instruction::BinOpLocalConst128(PackedOp::new(op, operand!(data, LocalV128 { local, value })?)) + } + [Instruction::GlobalGet128(global), Instruction::Const128(value)] => { + Instruction::BinOpGlobalConst128(PackedOp::new(op, operand!(data, GlobalV128 { global, value })?)) + } + [Instruction::Const128(value), Instruction::LocalGet128(local)] if commutative => { + Instruction::BinOpLocalConst128(PackedOp::new(op, operand!(data, LocalV128 { local, value })?)) + } + [Instruction::Const128(value), Instruction::GlobalGet128(global)] if commutative => { + Instruction::BinOpGlobalConst128(PackedOp::new(op, operand!(data, GlobalV128 { global, value })?)) + } + _ => return Ok(()), + }; + replace!(output, *read, 2 => replacement); + } + Ok(()) +} + +fn rewrite_store32( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + index: OperandIdx, +) -> Result<()> { + let compact_arg = CompactMemoryArg::try_from(data.operand(index)).ok(); + if *read >= output.block_start + 3 { + let previous = [output[*read - 3], output[*read - 2], output[*read - 1]]; + if let [ + Instruction::LocalGet32(addr) | Instruction::LocalGet64(addr), + Instruction::LoadLocal32(arg), + Instruction::AddConst32(1), + ] = previous + && { compact_arg == Some(data.operand(arg.memory_arg_idx)) } + && addr == u16::from(arg.local1) + { + replace!(output, *read, 3 => Instruction::IncMemoryLocal32(arg)); + return Ok(()); + } + } + if *read >= output.block_start + 2 { + let previous = [output[*read - 2], output[*read - 1]]; + match previous { + [Instruction::F32Mul, Instruction::F32Add] + if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) => + { + replace!(output, *read, 2 => Instruction::FMaStoreF32(arg)); + } + [Instruction::BinOpStackLocal32(BinOp::FMul, local), Instruction::F32Add] + if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) => + { + replace!(output, *read, 2 => [Instruction::LocalGet32(local), Instruction::FMaStoreF32(arg)]); + } + [Instruction::LocalGet32(addr), Instruction::LocalGet32(value)] + if let (Ok(addr), Ok(value), Some(memory_arg)) = + (u8::try_from(addr), u8::try_from(value), compact_arg) => + { + let memory_arg_idx = operand!(data, memory_arg)?; + replace!(output, *read, 2 => Instruction::StoreLocalLocal32(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value })); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_store64( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + index: OperandIdx, +) -> Result<()> { + let compact_arg = CompactMemoryArg::try_from(data.operand(index)).ok(); + if *read >= output.block_start + 3 { + let previous = [output[*read - 3], output[*read - 2], output[*read - 1]]; + if let [ + Instruction::LocalGet32(addr) | Instruction::LocalGet64(addr), + Instruction::LoadLocal64(arg), + Instruction::Const64(one), + ] = previous + && { compact_arg == Some(data.operand(arg.memory_arg_idx)) } + && addr == u16::from(arg.local1) + && data.operand(one).value == 1 + { + replace!(output, *read, 3 => Instruction::IncMemoryLocal64(arg)); + return Ok(()); + } + } + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::F64Mul, Instruction::F64Add] + if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) => + { + replace!(output, *read, 2 => Instruction::FMaStoreF64(arg)); + } + [Instruction::LocalGet32(addr), Instruction::LocalGet64(value)] + if let (Ok(addr), Ok(value), Some(memory_arg)) = + (u8::try_from(addr), u8::try_from(value), compact_arg) => + { + let memory_arg_idx = operand!(data, memory_arg)?; + replace!(output, *read, 2 => Instruction::StoreLocalLocal64(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value })); + } + _ => {} + } + } + Ok(()) +} + +macro_rules! local_const_set { + ($data:expr, 32, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ + let index = operand!($data, LocalConstSet32 { local: $src, dst: $dst, value: $value as u32 })?; + if $tee { + Instruction::BinOpLocalConstTee32(PackedOp::new($op, index)) + } else { + Instruction::BinOpLocalConstSet32(PackedOp::new($op, index)) + } + }}; + ($data:expr, 64, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ + let index = operand!($data, LocalConstSet64 { local: $src, dst: $dst, value: $value as u64 })?; + if $tee { + Instruction::BinOpLocalConstTee64(PackedOp::new($op, index)) + } else { + Instruction::BinOpLocalConstSet64(PackedOp::new($op, index)) + } + }}; + ($data:expr, 128, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ + let index = operand!($data, LocalConstSetV128 { local: $src, dst: $dst, value: $value })?; + if $tee { + Instruction::BinOpLocalConstTee128(PackedOp::new($op, index)) + } else { + Instruction::BinOpLocalConstSet128(PackedOp::new($op, index)) + } + }}; +} + +fn rewrite_local_set32( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::I32Mul, Instruction::BinOpStackLocal32(BinOp::IAdd, acc)] if acc == dst => { + replace!(output, *read, 2 => Instruction::MulAccLocal32(dst)); + return Ok(()); + } + [Instruction::F32Mul, Instruction::BinOpStackLocal32(BinOp::FAdd, acc)] if acc == dst => { + replace!(output, *read, 2 => Instruction::FMulAccLocal32(dst)); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet32(src) if src == dst => { + output.truncate(*read - 1); + *read = output.len(); + return Ok(()); + } + Instruction::LocalGet32(src) => replace!(output, *read, 1 => Instruction::LocalCopy32(src, dst)), + Instruction::Const32(value) => { + replace!(output, *read, 1 => Instruction::SetLocalConst32(I32LocalArg { value, local: dst })) + } + Instruction::BinOpLocalLocal32(op, left, right) => { + let replacement = if op == BinOp::IAdd { + Instruction::AddLocalLocalSet32(LocalTripleArg { left, right, dst }) + } else { + Instruction::BinOpLocalLocalSet32(PackedOp::new( + op, + operand!(data, LocalTripleArg { left, right, dst })?, + )) + }; + replace!(output, *read, 1 => replacement); + } + instruction if let Some((op, src, value)) = local_const32(data, instruction) => { + if src == dst + && let Some(delta) = op.inc_delta(value) + { + replace!(output, *read, 1 => Instruction::IncLocal32(I32LocalArg { value: delta, local: dst })); + } else { + let replacement = local_const_set!(data, 32, op, src, dst, value, false); + replace!(output, *read, 1 => replacement); + } + } + Instruction::BinOpStackLocal32(op, local) => { + replace!(output, *read, 1 => Instruction::BinOpStackLocalSet32(op, local, dst)); + } + Instruction::LoadLocal32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet32(arg)); + } + Instruction::LoadLocal8S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet8S32(arg)); + } + Instruction::LoadLocal8U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet8U32(arg)); + } + Instruction::LoadLocal16S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet16S32(arg)); + } + Instruction::LoadLocal16U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet16U32(arg)); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_set64( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 3 { + match [output[*read - 3], output[*read - 2], output[*read - 1]] { + [Instruction::I64Mul, Instruction::LocalGet64(acc), Instruction::I64Add] if acc == dst => { + replace!(output, *read, 3 => Instruction::MulAccLocal64(dst)); + return Ok(()); + } + [Instruction::F64Mul, Instruction::LocalGet64(acc), Instruction::F64Add] if acc == dst => { + replace!(output, *read, 3 => Instruction::FMulAccLocal64(dst)); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet64(src) if src == dst => { + output.truncate(*read - 1); + *read = output.len(); + return Ok(()); + } + Instruction::LocalGet64(src) => replace!(output, *read, 1 => Instruction::LocalCopy64(src, dst)), + Instruction::Const64(index) => { + replace!(output, *read, 1 => Instruction::SetLocalConst64(PackedOp::new(dst, index))); + } + Instruction::BinOpLocalLocal64(op, left, right) => { + let index = operand!(data, LocalTripleArg { left, right, dst })?; + replace!(output, *read, 1 => Instruction::BinOpLocalLocalSet64(PackedOp::new(op, index))); + } + instruction if let Some((op, src, value)) = local_const64(data, instruction) => { + if src == dst && matches!(op, BinOp::IAdd | BinOp::ISub) { + let delta = if op == BinOp::IAdd { value } else { value.wrapping_neg() }; + let index = operand!(data, I64Operand { value: delta })?; + replace!(output, *read, 1 => Instruction::IncLocal64(PackedOp::new(dst, index))); + } else { + let replacement = local_const_set!(data, 64, op, src, dst, value, false); + replace!(output, *read, 1 => replacement); + } + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_set128( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 + && let [Instruction::LocalGet32(local), Instruction::V128Load(index)] = [output[*read - 2], output[*read - 1]] + && let (Ok(local), Ok(dst), Ok(memory_arg)) = + (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand(index))) + { + let memory_arg_idx = operand!(data, memory_arg)?; + replace!(output, *read, 2 => Instruction::LoadLocalSet128(MemoryLocalArg { + memory_arg_idx, + local1: local, + local2: dst, + })); + return Ok(()); + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet128(src) if src == dst => { + output.truncate(*read - 1); + *read = output.len(); + return Ok(()); + } + Instruction::LocalGet128(src) => replace!(output, *read, 1 => Instruction::LocalCopy128(src, dst)), + Instruction::Const128(value) => { + replace!(output, *read, 1 => Instruction::SetLocalConst128(PackedOp::new(dst, value))) + } + Instruction::BinOpLocalLocal128(op, left, right) => { + let index = operand!(data, LocalTripleArg { left, right, dst })?; + replace!(output, *read, 1 => Instruction::BinOpLocalLocalSet128(PackedOp::new(op, index))); + } + instruction if let Some((op, src, value)) = local_const128(data, instruction) => { + let replacement = local_const_set!(data, 128, op, src, dst, value, false); + replace!(output, *read, 1 => replacement); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_tee32( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::Const32(value), Instruction::I32And] => { + replace!(output, *read, 2 => Instruction::AndConstTee32(I32LocalArg { value, local: dst })); + return Ok(()); + } + [Instruction::Const32(value), Instruction::I32Sub] => { + replace!(output, *read, 2 => Instruction::SubConstTee32(I32LocalArg { value, local: dst })); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet32(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet32(src)), + Instruction::BinOpLocalLocal32(op, left, right) => { + let replacement = if op == BinOp::IAdd { + Instruction::AddLocalLocalTee32(LocalTripleArg { left, right, dst }) + } else { + Instruction::BinOpLocalLocalTee32(PackedOp::new( + op, + operand!(data, LocalTripleArg { left, right, dst })?, + )) + }; + replace!(output, *read, 1 => replacement); + } + instruction if let Some((op, src, value)) = local_const32(data, instruction) => { + let replacement = local_const_set!(data, 32, op, src, dst, value, true); + replace!(output, *read, 1 => replacement); + } + Instruction::BinOpStackLocal32(op, local) => { + replace!(output, *read, 1 => Instruction::BinOpStackLocalTee32(op, local, dst)); + } + Instruction::LoadLocal32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee32(arg)); + } + Instruction::LoadLocal8S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee8S32(arg)); + } + Instruction::LoadLocal8U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee8U32(arg)); + } + Instruction::LoadLocal16S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee16S32(arg)); + } + Instruction::LoadLocal16U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee16U32(arg)); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_tee64( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::Const64(value), Instruction::I64And] => { + replace!(output, *read, 2 => Instruction::AndConstTee64(PackedOp::new(dst, value))); + return Ok(()); + } + [Instruction::Const64(value), Instruction::I64Sub] => { + replace!(output, *read, 2 => Instruction::SubConstTee64(PackedOp::new(dst, value))); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet64(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet64(src)), + Instruction::BinOpLocalLocal64(op, left, right) => { + let index = operand!(data, LocalTripleArg { left, right, dst })?; + replace!(output, *read, 1 => Instruction::BinOpLocalLocalTee64(PackedOp::new(op, index))); + } + instruction if let Some((op, src, value)) = local_const64(data, instruction) => { + let replacement = local_const_set!(data, 64, op, src, dst, value, true); + replace!(output, *read, 1 => replacement); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_tee128( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 + && let [Instruction::LocalGet32(local), Instruction::V128Load(index)] = [output[*read - 2], output[*read - 1]] + && let (Ok(local), Ok(dst), Ok(memory_arg)) = + (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand(index))) + { + let memory_arg_idx = operand!(data, memory_arg)?; + replace!(output, *read, 2 => Instruction::LoadLocalTee128(MemoryLocalArg { + memory_arg_idx, + local1: local, + local2: dst, + })); + return Ok(()); + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet128(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet128(src)), + Instruction::BinOpLocalLocal128(op, left, right) => { + let index = operand!(data, LocalTripleArg { left, right, dst })?; + replace!(output, *read, 1 => Instruction::BinOpLocalLocalTee128(PackedOp::new(op, index))); + } + instruction if let Some((op, src, value)) = local_const128(data, instruction) => { + let replacement = local_const_set!(data, 128, op, src, dst, value, true); + replace!(output, *read, 1 => replacement); + } + _ => {} + } + } + Ok(()) +} + +fn int_bin_op(instruction: Instruction) -> Option { + Some(match instruction { + Instruction::I32Add | Instruction::I64Add => BinOp::IAdd, + Instruction::I32Sub | Instruction::I64Sub => BinOp::ISub, + Instruction::I32Mul | Instruction::I64Mul => BinOp::IMul, + Instruction::I32And | Instruction::I64And => BinOp::IAnd, + Instruction::I32Or | Instruction::I64Or => BinOp::IOr, + Instruction::I32Xor | Instruction::I64Xor => BinOp::IXor, + Instruction::I32Shl | Instruction::I64Shl => BinOp::IShl, + Instruction::I32ShrS | Instruction::I64ShrS => BinOp::IShrS, + Instruction::I32ShrU | Instruction::I64ShrU => BinOp::IShrU, + Instruction::I32Rotl | Instruction::I64Rotl => BinOp::IRotl, + Instruction::I32Rotr | Instruction::I64Rotr => BinOp::IRotr, + _ => return None, + }) +} + +fn float_bin_op(instruction: Instruction) -> Option { + Some(match instruction { + Instruction::F32Add | Instruction::F64Add => BinOp::FAdd, + Instruction::F32Sub | Instruction::F64Sub => BinOp::FSub, + Instruction::F32Mul | Instruction::F64Mul => BinOp::FMul, + Instruction::F32Div | Instruction::F64Div => BinOp::FDiv, + Instruction::F32Min | Instruction::F64Min => BinOp::FMin, + Instruction::F32Max | Instruction::F64Max => BinOp::FMax, + Instruction::F32Copysign | Instruction::F64Copysign => BinOp::FCopysign, + _ => return None, + }) +} + +fn cmp_op(instruction: Instruction) -> Option { + Some(match instruction { + Instruction::I32Eq | Instruction::I64Eq => CmpOp::Eq, + Instruction::I32Ne | Instruction::I64Ne => CmpOp::Ne, + Instruction::I32LtS | Instruction::I64LtS => CmpOp::LtS, + Instruction::I32LtU | Instruction::I64LtU => CmpOp::LtU, + Instruction::I32GtS | Instruction::I64GtS => CmpOp::GtS, + Instruction::I32GtU | Instruction::I64GtU => CmpOp::GtU, + Instruction::I32LeS | Instruction::I64LeS => CmpOp::LeS, + Instruction::I32LeU | Instruction::I64LeU => CmpOp::LeU, + Instruction::I32GeS | Instruction::I64GeS => CmpOp::GeS, + Instruction::I32GeU | Instruction::I64GeU => CmpOp::GeU, + _ => return None, + }) +} + +fn bin_op_128(instruction: Instruction) -> Option { + Some(match instruction { + Instruction::V128And => BinOp128::And, + Instruction::V128AndNot => BinOp128::AndNot, + Instruction::V128Or => BinOp128::Or, + Instruction::V128Xor => BinOp128::Xor, + Instruction::I64x2Add => BinOp128::I64x2Add, + Instruction::I64x2Mul => BinOp128::I64x2Mul, + _ => return None, + }) +} + +fn jump_cmp_local_local( + data: &mut WasmFunctionData, + target: u32, + left: u16, + right: u16, + op: CmpOp, + width64: bool, +) -> Result { + let index = target_operand!(data, LocalLocalCmp { target, left, right })?; + Ok(if width64 { + Instruction::JumpCmpLocalLocal64(PackedOp::new(op, index)) + } else { + Instruction::JumpCmpLocalLocal32(PackedOp::new(op, index)) + }) +} + +fn rewrite_jump( + source: &[Instruction], + output: &mut CompactOutput, + index: usize, + data: &mut WasmFunctionData, + old_index: u32, + target: u32, +) -> Result<()> { + let target = resolve_jump_target(source, data, target); + let exit = old_index + 1; + let body = target + 1; + if let Some(instruction) = source.get(target as usize).copied() { + match instruction { + Instruction::JumpCmpLocalLocal32(side) + if resolve_jump_target(source, data, data.operand(side.index).target) == exit && body > target => + { + let value = data.operand(side.index); + output[index] = jump_cmp_local_local(data, body, value.left, value.right, side.op.inverse(), false)?; + return Ok(()); + } + Instruction::JumpCmpLocalLocal64(side) + if resolve_jump_target(source, data, data.operand(side.index).target) == exit && body > target => + { + let value = data.operand(side.index); + output[index] = jump_cmp_local_local(data, body, value.left, value.right, side.op.inverse(), true)?; + return Ok(()); + } + _ => {} + } + } + if matches!(output[index], Instruction::Jump(_)) && target == exit { + output.truncate(index); + } else { + set_rewrite_target(&mut output[index], data, target)?; + } + Ok(()) +} + +fn jump_cmp_stack_local( + data: &mut WasmFunctionData, + target: u32, + local: u16, + op: CmpOp, + width64: bool, +) -> Result { + let index = target_operand!(data, TargetLocal { target, local })?; + Ok(if width64 { + Instruction::JumpCmpStackLocal64(PackedOp::new(op, index)) + } else { + Instruction::JumpCmpStackLocal32(PackedOp::new(op, index)) + }) +} + +fn jump_cmp_local_const32( + data: &mut WasmFunctionData, + target: u32, + local: u16, + value: i32, + op: CmpOp, +) -> Result { + if value == 0 { + return Ok(match op { + CmpOp::Eq => Instruction::JumpIfLocalZero32(TargetLocalArg { target_ip: target, local }), + CmpOp::Ne => Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }), + _ => Instruction::JumpCmpLocalConst32(PackedOp::new( + op, + target_operand!(data, LocalConstCmp { target, value, local })?, + )), + }); + } + Ok(Instruction::JumpCmpLocalConst32(PackedOp::new( + op, + target_operand!(data, LocalConstCmp { target, value, local })?, + ))) +} + +fn jump_cmp_local_const64( + data: &mut WasmFunctionData, + target: u32, + local: u16, + value: i32, + op: CmpOp, +) -> Result { + if value == 0 { + match op { + CmpOp::Eq => return Ok(Instruction::JumpIfLocalZero64(TargetLocalArg { target_ip: target, local })), + CmpOp::Ne => return Ok(Instruction::JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local })), + _ => {} + } + } + Ok(Instruction::JumpCmpLocalConst64(PackedOp::new( + op, + target_operand!(data, LocalConstCmp { target, value, local })?, + ))) +} + +fn jump_cmp_stack_const32(data: &mut WasmFunctionData, target: u32, value: i32, op: CmpOp) -> Result { + if value == 0 { + match op { + CmpOp::Eq => return Ok(Instruction::JumpIfZero32(target)), + CmpOp::Ne => return Ok(Instruction::JumpIfNonZero32(target)), + _ => {} + } + } + Ok(Instruction::JumpCmpStackConst32(PackedOp::new(op, target_operand!(data, StackConst32 { target, value })?))) +} + +fn jump_cmp_stack_const64(data: &mut WasmFunctionData, target: u32, value: i64, op: CmpOp) -> Result { + if value == 0 { + match op { + CmpOp::Eq => return Ok(Instruction::JumpIfZero64(target)), + CmpOp::Ne => return Ok(Instruction::JumpIfNonZero64(target)), + _ => {} + } + } + Ok(Instruction::JumpCmpStackConst64(PackedOp::new(op, target_operand!(data, StackConst64 { target, value })?))) +} + +fn update_jump( + data: &mut WasmFunctionData, + target: u32, + immediate: i32, + address: u32, + op: BinOp, + on_zero: bool, + global: bool, +) -> Result { + if let Some(delta) = op.inc_delta(immediate) { + Ok(if global { + Instruction::IncGlobalJump32(target_operand!( + data, + GlobalUpdate { target, value: delta, global: address, on_zero: u8::from(on_zero) } + )?) + } else { + Instruction::IncLocalJump32(target_operand!( + data, + LocalUpdate { target, value: delta, local: address as u16, on_zero: u8::from(on_zero) } + )?) + }) + } else { + Ok(if global { + Instruction::BinOpGlobalConstJump32(PackedOp::new( + op, + target_operand!( + data, + GlobalUpdate { target, value: immediate, global: address, on_zero: u8::from(on_zero) } + )?, + )) + } else { + Instruction::BinOpLocalConstJump32(PackedOp::new( + op, + target_operand!( + data, + LocalUpdate { target, value: immediate, local: address as u16, on_zero: u8::from(on_zero) } + )?, + )) + }) + } +} + +fn rewrite_conditional( + source: &[Instruction], + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + target: u32, + on_zero: bool, +) -> Result<()> { + let target = resolve_jump_target(source, data, target); + if *read > output.block_start + && let Instruction::BinOpLocalConstTee32(packed) = output[*read - 1] + { + let value = data.operand(packed.index); + if value.local == value.dst { + let replacement = + update_jump(data, target, value.value as i32, u32::from(value.local), packed.op, on_zero, false)?; + replace!(output, *read, 1 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 2 + && let [Instruction::BinOpGlobalConst32(packed), Instruction::GlobalTee32(dst)] = + [output[*read - 2], output[*read - 1]] + { + let value = data.operand(packed.index); + if value.global == dst { + let replacement = update_jump(data, target, value.value as i32, dst, packed.op, on_zero, true)?; + replace!(output, *read, 2 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 3 + && let [Instruction::AddConst32(value), Instruction::LocalTee32(local), Instruction::LocalGet32(cond)] = + [output[*read - 3], output[*read - 2], output[*read - 1]] + && local == cond + { + let replacement = Instruction::IncStackTeeLocalJump32(target_operand!( + data, + LocalUpdate { target, value, local, on_zero: u8::from(on_zero) } + )?); + replace!(output, *read, 3 => replacement); + return Ok(()); + } + if *read >= output.block_start + 2 { + let update = match [output[*read - 2], output[*read - 1]] { + [Instruction::AndConstTee32(arg), Instruction::LocalGet32(cond)] if arg.local == cond => { + Some((arg.local, arg.value, Some(BinOp::IAnd))) + } + [Instruction::SubConstTee32(arg), Instruction::LocalGet32(cond)] if arg.local == cond => { + Some((arg.local, arg.value.wrapping_neg(), None)) + } + _ => None, + }; + if let Some((local, value, op)) = update { + let replacement = if let Some(op) = op { + Instruction::BinOpStackConstTeeLocalJump32(PackedOp::new( + op, + target_operand!(data, LocalUpdate { target, value, local, on_zero: u8::from(on_zero) })?, + )) + } else { + Instruction::IncStackTeeLocalJump32(target_operand!( + data, + LocalUpdate { target, value, local, on_zero: u8::from(on_zero) } + )?) + }; + replace!(output, *read, 2 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 3 + && let [Instruction::BinOpLocalConstTee32(packed), Instruction::LocalGet32(right), raw_cmp] = + [output[*read - 3], output[*read - 2], output[*read - 1]] + && let Some(mut cmp) = cmp_op(raw_cmp) + { + let value = data.operand(packed.index); + if value.local == value.dst { + if on_zero { + cmp = cmp.inverse(); + } + let replacement = if let Some(delta) = packed.op.inc_delta(value.value as i32) { + Instruction::IncLocalJumpCmpLocal32(PackedOp::new( + cmp, + target_operand!(data, LocalUpdateCmp { target, value: delta, local: value.local, right })?, + )) + } else { + Instruction::BinOpLocalConstJumpCmpLocal32(PackedOp::new( + (packed.op, cmp), + target_operand!( + data, + LocalUpdateCmp { target, value: value.value as i32, local: value.local, right } + )?, + )) + }; + replace!(output, *read, 3 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::LocalGet32(local), Instruction::I32Eqz] => { + replace!(output, *read, 2 => + if on_zero { + Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }) + } else { + Instruction::JumpIfLocalZero32(TargetLocalArg { target_ip: target, local }) + } + ); + return Ok(()); + } + [Instruction::LocalGet64(local), Instruction::I64Eqz] => { + replace!(output, *read, 2 => + if on_zero { + Instruction::JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local }) + } else { + Instruction::JumpIfLocalZero64(TargetLocalArg { target_ip: target, local }) + } + ); + return Ok(()); + } + [Instruction::CmpLocalLocal32(op, left, right), Instruction::I32Eqz] => { + let op = if on_zero { op } else { op.inverse() }; + let replacement = jump_cmp_local_local(data, target, left, right, op, false)?; + replace!(output, *read, 2 => replacement); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + let previous = output[*read - 1]; + let replacement = match previous { + Instruction::I32Eqz => { + Some(if on_zero { Instruction::JumpIfNonZero32(target) } else { Instruction::JumpIfZero32(target) }) + } + Instruction::I64Eqz => { + Some(if on_zero { Instruction::JumpIfNonZero64(target) } else { Instruction::JumpIfZero64(target) }) + } + Instruction::CmpLocalLocal32(op, left, right) => { + Some(jump_cmp_local_local(data, target, left, right, if !on_zero { op } else { op.inverse() }, false)?) + } + Instruction::CmpLocalLocal64(op, left, right) => { + Some(jump_cmp_local_local(data, target, left, right, if !on_zero { op } else { op.inverse() }, true)?) + } + Instruction::LocalGet32(local) => Some(if on_zero { + Instruction::JumpIfLocalZero32(TargetLocalArg { target_ip: target, local }) + } else { + Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }) + }), + Instruction::LocalGet64(local) => Some(if on_zero { + Instruction::JumpIfLocalZero64(TargetLocalArg { target_ip: target, local }) + } else { + Instruction::JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local }) + }), + _ => None, + }; + if let Some(replacement) = replacement { + replace!(output, *read, 1 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 3 { + let raw_cmp = output[*read - 1]; + if let Some(mut op) = cmp_op(raw_cmp) { + if on_zero { + op = op.inverse(); + } + let replacement = match [output[*read - 3], output[*read - 2]] { + [Instruction::LocalGet32(local), Instruction::Const32(value)] => { + Some(jump_cmp_local_const32(data, target, local, value, op)?) + } + [Instruction::LocalGet64(local), Instruction::Const64(index)] + if let Ok(value) = i32::try_from(data.operand(index).value) => + { + Some(jump_cmp_local_const64(data, target, local, value, op)?) + } + [Instruction::LocalGet32(left), Instruction::LocalGet32(right)] => { + Some(jump_cmp_local_local(data, target, left, right, op, false)?) + } + [Instruction::LocalGet64(left), Instruction::LocalGet64(right)] => { + Some(jump_cmp_local_local(data, target, left, right, op, true)?) + } + _ => None, + }; + if let Some(replacement) = replacement { + replace!(output, *read, 3 => replacement); + return Ok(()); + } + } + } + if *read >= output.block_start + 2 { + let raw_cmp = output[*read - 1]; + if let Some(mut op) = cmp_op(raw_cmp) { + if on_zero { + op = op.inverse(); + } + let replacement = match output[*read - 2] { + Instruction::LocalGet32(local) => Some(jump_cmp_stack_local(data, target, local, op, false)?), + Instruction::LocalGet64(local) => Some(jump_cmp_stack_local(data, target, local, op, true)?), + Instruction::Const32(value) => Some(jump_cmp_stack_const32(data, target, value, op)?), + Instruction::Const64(index) => { + Some(jump_cmp_stack_const64(data, target, data.operand(index).value, op)?) + } + _ => None, + }; + if let Some(replacement) = replacement { + replace!(output, *read, 2 => replacement); + return Ok(()); + } + } + } + Ok(()) +} + +fn is_unconditional_terminator(instruction: Instruction) -> bool { + matches!( + instruction, + Instruction::Unreachable + | Instruction::Jump(_) + | Instruction::BranchTable(_) + | Instruction::Return + | Instruction::ReturnVoid + | Instruction::Return32 + | Instruction::Return64 + | Instruction::Return128 + | Instruction::ReturnCall(_) + | Instruction::ReturnCallSelf + | Instruction::ReturnCallIndirect(_) + | Instruction::ReturnCallRef(_) + | Instruction::Throw(_) + | Instruction::ThrowRef + ) +} diff --git a/crates/parser/src/optimize/targets.rs b/crates/parser/src/optimize/targets.rs new file mode 100644 index 0000000..36bdf2f --- /dev/null +++ b/crates/parser/src/optimize/targets.rs @@ -0,0 +1,290 @@ +use crate::visit::{BuilderRawOperand, FunctionDataBuilder}; +use crate::{ParseError, Result}; +use alloc::vec::Vec; +use tinywasm_types::{ + BranchTableArg, CastBranch, GlobalUpdate, Instruction, LocalConstCmp, LocalLocalCmp, LocalUpdate, LocalUpdateCmp, + OperandIdx, OperandType, PackedOp, StackConst32, StackConst64, TargetLocal, +}; + +pub(super) trait TargetOperand: OperandType { + fn set_target(&mut self, target: u32); +} + +macro_rules! target_operands { + ($($name:ty),+ $(,)?) => {$( + impl TargetOperand for $name { + fn set_target(&mut self, target: u32) { self.target = target; } + } + )+}; +} + +target_operands!( + TargetLocal, + CastBranch, + StackConst32, + StackConst64, + LocalUpdate, + GlobalUpdate, + LocalUpdateCmp, + LocalConstCmp, + LocalLocalCmp, + BranchTableArg, +); + +pub(super) fn resolve_jump_target(instructions: &[Instruction], data: &FunctionDataBuilder, target: u32) -> u32 { + let mut index = target as usize; + let mut steps = 0; + while let Some(instruction) = instructions.get(index) + && let Some(next) = instruction_target(data, *instruction) + && matches!(instruction, Instruction::Jump(_)) + && steps < instructions.len() + { + index = next as usize; + steps += 1; + } + index as u32 +} + +pub(super) fn set_rewrite_target( + instruction: &mut Instruction, + data: &mut FunctionDataBuilder, + target: u32, +) -> Result<()> { + use Instruction::*; + match instruction { + JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => { + *packed = push_packed_target_copy(data, *packed, target)? + } + BrOnCast(index) | BrOnCastFail(index) => *index = push_target_copy(data, *index, target)?, + JumpCmpStackConst32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + JumpCmpStackConst64(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => { + *packed = push_packed_target_copy(data, *packed, target)? + } + BinOpLocalConstJumpCmpLocal32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + BinOpGlobalConstJump32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + IncLocalJump32(index) | IncStackTeeLocalJump32(index) => *index = push_target_copy(data, *index, target)?, + IncGlobalJump32(index) => *index = push_target_copy(data, *index, target)?, + IncLocalJumpCmpLocal32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => { + *packed = push_packed_target_copy(data, *packed, target)? + } + JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => { + *packed = push_packed_target_copy(data, *packed, target)? + } + BranchTable(index) => *index = push_target_copy(data, *index, target)?, + _ => set_target(instruction, data, target), + } + Ok(()) +} + +fn push_target_copy( + data: &mut FunctionDataBuilder, + index: OperandIdx, + target: u32, +) -> Result> +where + T::Raw: BuilderRawOperand, +{ + let mut value = data.operand(index); + value.set_target(target); + data.push_target_operand(value) +} + +fn push_packed_target_copy( + data: &mut FunctionDataBuilder, + packed: PackedOp, + target: u32, +) -> Result> +where + T::Raw: BuilderRawOperand, +{ + let mut value = data.operand(packed.index); + value.set_target(target); + Ok(PackedOp::new(packed.op, data.push_target_operand(value)?)) +} + +fn instruction_target(data: &FunctionDataBuilder, instruction: Instruction) -> Option { + use Instruction::*; + Some(match instruction { + Jump(target) + | JumpIfZero32(target) + | JumpIfNonZero32(target) + | JumpIfZero64(target) + | JumpIfNonZero64(target) + | JumpIfRefNull(target) + | JumpIfRefNonNull(target) => target, + JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => { + arg.target_ip + } + JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => data.operand(packed.index).target, + BrOnCast(index) | BrOnCastFail(index) => data.operand(index).target, + JumpCmpStackConst32(packed) => data.operand(packed.index).target, + JumpCmpStackConst64(packed) => data.operand(packed.index).target, + BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => data.operand(packed.index).target, + BinOpLocalConstJumpCmpLocal32(packed) => data.operand(packed.index).target, + BinOpGlobalConstJump32(packed) => data.operand(packed.index).target, + IncLocalJump32(index) | IncStackTeeLocalJump32(index) => data.operand(index).target, + IncGlobalJump32(index) => data.operand(index).target, + IncLocalJumpCmpLocal32(packed) => data.operand(packed.index).target, + JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => data.operand(packed.index).target, + JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => data.operand(packed.index).target, + BranchTable(index) => data.operand(index).target, + _ => return None, + }) +} + +fn set_target(instruction: &mut Instruction, data: &mut FunctionDataBuilder, target: u32) { + use Instruction::*; + match instruction { + Jump(value) + | JumpIfZero32(value) + | JumpIfNonZero32(value) + | JumpIfZero64(value) + | JumpIfNonZero64(value) + | JumpIfRefNull(value) + | JumpIfRefNonNull(value) => *value = target, + JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => { + arg.target_ip = target + } + JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => set_packed_operand_target(data, *packed, target), + BrOnCast(index) | BrOnCastFail(index) => set_operand_target(data, *index, target), + JumpCmpStackConst32(packed) => set_packed_operand_target(data, *packed, target), + JumpCmpStackConst64(packed) => set_packed_operand_target(data, *packed, target), + BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => { + set_packed_operand_target(data, *packed, target) + } + BinOpLocalConstJumpCmpLocal32(packed) => set_packed_operand_target(data, *packed, target), + BinOpGlobalConstJump32(packed) => set_packed_operand_target(data, *packed, target), + IncLocalJump32(index) | IncStackTeeLocalJump32(index) => set_operand_target(data, *index, target), + IncGlobalJump32(index) => set_operand_target(data, *index, target), + IncLocalJumpCmpLocal32(packed) => set_packed_operand_target(data, *packed, target), + JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => set_packed_operand_target(data, *packed, target), + JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => set_packed_operand_target(data, *packed, target), + BranchTable(index) => set_operand_target(data, *index, target), + _ => {} + } +} + +fn set_operand_target(data: &mut FunctionDataBuilder, index: OperandIdx, target: u32) +where + T::Raw: BuilderRawOperand, +{ + let mut value = data.operand(index); + value.set_target(target); + data.set_operand(index, value); +} + +fn set_packed_operand_target( + data: &mut FunctionDataBuilder, + packed: PackedOp, + target: u32, +) where + T::Raw: BuilderRawOperand, +{ + let mut value = data.operand(packed.index); + value.set_target(target); + data.set_operand(packed.index, value); +} + +fn branch_table_range(data: &FunctionDataBuilder, instruction: Instruction) -> Option<(u32, u32)> { + let Instruction::BranchTable(index) = instruction else { return None }; + let operand = data.operand(index); + Some((operand.start, operand.len)) +} + +pub(super) fn target_boundaries(instructions: &[Instruction], data: &FunctionDataBuilder) -> Result> { + let mut boundaries = alloc::vec![false; instructions.len() + 1]; + for handler in &data.exception_handlers { + for target in [handler.start_ip, handler.end_ip] { + *boundaries.get_mut(target as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("exception handler boundary out of bounds: {target}")) + })? = true; + } + for catch in &handler.catches { + let target = catch.landing_pad(); + *boundaries + .get_mut(target as usize) + .ok_or_else(|| ParseError::Other(alloc::format!("exception landing pad out of bounds: {target}")))? = + true; + } + } + for &instruction in instructions { + if let Some(target) = instruction_target(data, instruction) { + *boundaries + .get_mut(target as usize) + .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))? = true; + } + if let Some((start, count)) = branch_table_range(data, instruction) { + let end = + start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; + let targets = data + .branch_table_targets + .get(start as usize..end as usize) + .ok_or_else(|| ParseError::Other("branch table range out of bounds".into()))?; + for &target in targets { + *boundaries.get_mut(target as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("branch table target out of bounds: {target}")) + })? = true; + } + } + } + Ok(boundaries) +} + +fn remap_target(target: u32, old_to_new: Option<&[u32]>, len: u32) -> Result { + let target = if let Some(map) = old_to_new { + *map.get(target as usize) + .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))? + } else { + target + }; + if target >= len { + return Err(ParseError::Other(alloc::format!("instruction target out of bounds: {target}"))); + } + Ok(target) +} + +pub(super) fn finalize( + instructions: &mut [Instruction], + data: &mut FunctionDataBuilder, + old_to_new: Option<&[u32]>, +) -> Result<()> { + let len = instructions.len() as u32; + for handler in &mut data.exception_handlers { + if let Some(map) = old_to_new { + handler.start_ip = *map + .get(handler.start_ip as usize) + .ok_or_else(|| ParseError::Other("exception handler boundary out of bounds".into()))?; + handler.end_ip = *map + .get(handler.end_ip as usize) + .ok_or_else(|| ParseError::Other("exception handler boundary out of bounds".into()))?; + for catch in &mut handler.catches { + let landing_pad = match catch { + tinywasm_types::ExceptionCatch::Tag { landing_pad, .. } + | tinywasm_types::ExceptionCatch::All { landing_pad, .. } => landing_pad, + }; + *landing_pad = remap_target(*landing_pad, Some(map), len)?; + } + } + if handler.start_ip > handler.end_ip || handler.end_ip > len { + return Err(ParseError::Other("exception handler range out of bounds".into())); + } + } + for target in &mut data.branch_table_targets { + *target = remap_target(*target, old_to_new, len)?; + } + for instruction in instructions { + if let Some(target) = instruction_target(data, *instruction) { + set_target(instruction, data, remap_target(target, old_to_new, len)?); + } + if let Some((start, count)) = branch_table_range(data, *instruction) { + let end = + start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; + data.branch_table_targets + .get(start as usize..end as usize) + .ok_or_else(|| ParseError::Other("branch table range out of bounds".into()))?; + } + } + Ok(()) +} diff --git a/crates/parser/src/parallel.rs b/crates/parser/src/parallel.rs index e0e3858..e29b38f 100644 --- a/crates/parser/src/parallel.rs +++ b/crates/parser/src/parallel.rs @@ -1,4 +1,4 @@ -use crate::module::{FunctionCode, optimize_function_code}; +use crate::module::{OptimizedFunctionCode, optimize_function_code}; use crate::validation::{FuncToValidate, FuncValidatorAllocations, ValidatorResources}; use crate::{ParseError, ParserOptions, Result, conversion}; use alloc::sync::Arc; @@ -64,7 +64,7 @@ fn process_function_job( imported_memory_count: u32, validator_allocs: Option, reader_allocs: OperatorsReaderAllocations, -) -> Result<(FunctionCode, Option, OperatorsReaderAllocations)> { +) -> Result<(OptimizedFunctionCode, Option, OperatorsReaderAllocations)> { #[cfg(feature = "validate")] let validator = job.func_to_validate.map(|func| func.into_validator(validator_allocs.unwrap_or_default())); #[cfg(not(feature = "validate"))] @@ -74,12 +74,12 @@ fn process_function_job( }; let (code, validator_allocs, reader_allocs) = match job.body { FunctionBodyInput::Borrowed(func) => { - conversion::convert_module_code(func, validator, reader_allocs, metadata, job.ty_idx)? + conversion::convert_module_code(func, validator, reader_allocs, metadata, job.ty_idx, options)? } FunctionBodyInput::Owned(body) => { let reader = wasmparser::BinaryReader::new(&body.section_bytes[body.body_range], body.body_offset); let func = wasmparser::FunctionBody::new(reader); - conversion::convert_module_code(func, validator, reader_allocs, metadata, job.ty_idx)? + conversion::convert_module_code(func, validator, reader_allocs, metadata, job.ty_idx, options)? } }; @@ -100,7 +100,7 @@ fn process_chunk<'a>( options: &ParserOptions, imported_func_count: usize, imported_memory_count: u32, -) -> Result> { +) -> Result> { let mut validator_allocs = None; let mut reader_allocs = OperatorsReaderAllocations::default(); let jobs = jobs.into_iter(); @@ -130,7 +130,7 @@ pub(crate) fn process_pending( options: &ParserOptions, imported_func_count: usize, imported_memory_count: u32, -) -> Result> { +) -> Result> { let num_workers = worker_count(options, pending.len()); if num_workers == 1 { return process_chunk(pending, metadata, options, imported_func_count, imported_memory_count); diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index cecbb8c..8315fb5 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -3,10 +3,11 @@ use crate::{ conversion::{convert_heap_type, value_lane}, macros::visit::*, }; -use alloc::{boxed::Box, string::ToString, vec::Vec}; +use alloc::{boxed::Box, collections::BTreeMap, string::ToString, vec::Vec}; use tinywasm_types::{ - Global, Import, ImportKind, Instruction, MemoryArg, MemoryType, StorageType, TableDefinition, TagType, TypeSection, - ValueCounts, ValueLane, WasmFunctionData, + BranchTableArg, CastBranch, ExceptionHandler, Global, I64Operand, Import, ImportKind, Instruction, MemoryArg, + MemoryType, Operand64, Operand128, OperandIdx, OperandType, StorageType, TableDefinition, TagType, TwoU32, + TypeSection, V128Operand, ValueCounts, ValueLane, WasmFunctionData, }; use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator}; @@ -52,19 +53,107 @@ pub(crate) struct ModuleMetadata { aggregate_fields: Vec, } +pub(crate) struct FunctionDataBuilder { + pub(crate) operands64: Vec, + pub(crate) operands128: Vec, + pub(crate) branch_table_targets: Vec, + pub(crate) exception_handlers: Vec, + deduplicate64: Option>, + deduplicate128: Option>, +} + +pub(crate) trait BuilderRawOperand: tinywasm_types::RawOperand + Ord { + fn push(builder: &mut FunctionDataBuilder, raw: Self, deduplicate: bool) -> Result; + fn get(builder: &FunctionDataBuilder, index: u32) -> Self; + fn set(builder: &mut FunctionDataBuilder, index: u32, raw: Self); +} + +macro_rules! builder_raw_operand { + ($raw:ty, $lane:ident, $map:ident) => { + impl BuilderRawOperand for $raw { + fn push(builder: &mut FunctionDataBuilder, raw: Self, deduplicate: bool) -> Result { + if deduplicate && let Some(index) = builder.$map.as_ref().and_then(|map| map.get(&raw)) { + return Ok(*index); + } + let index = u32::try_from(builder.$lane.len()) + .map_err(|_| crate::ParseError::Other("instruction operand index overflow".into()))?; + builder.$lane.push(raw); + if deduplicate && let Some(map) = &mut builder.$map { + map.insert(raw, index); + } + Ok(index) + } + + fn get(builder: &FunctionDataBuilder, index: u32) -> Self { + *builder.$lane.get(index as usize).unwrap_or_else(|| unreachable!("invalid operand index")) + } + + fn set(builder: &mut FunctionDataBuilder, index: u32, raw: Self) { + *builder.$lane.get_mut(index as usize).unwrap_or_else(|| unreachable!("invalid operand index")) = raw; + } + } + }; +} + +builder_raw_operand!(Operand64, operands64, deduplicate64); +builder_raw_operand!(Operand128, operands128, deduplicate128); + +impl FunctionDataBuilder { + pub(crate) fn new(deduplicate_operands: bool) -> Self { + Self { + operands64: Vec::new(), + operands128: Vec::new(), + branch_table_targets: Vec::new(), + exception_handlers: Vec::new(), + deduplicate64: deduplicate_operands.then(BTreeMap::new), + deduplicate128: deduplicate_operands.then(BTreeMap::new), + } + } + + pub(crate) fn push_operand(&mut self, operand: T) -> Result> + where + T::Raw: BuilderRawOperand, + { + ::push(self, operand.encode(), true).map(OperandIdx::new) + } + + pub(crate) fn push_target_operand(&mut self, operand: T) -> Result> + where + T::Raw: BuilderRawOperand, + { + ::push(self, operand.encode(), false).map(OperandIdx::new) + } + + pub(crate) fn operand(&self, index: OperandIdx) -> T + where + T::Raw: BuilderRawOperand, + { + T::decode(::get(self, index.index())) + } + + pub(crate) fn set_operand(&mut self, index: OperandIdx, operand: T) + where + T::Raw: BuilderRawOperand, + { + ::set(self, index.index(), operand.encode()) + } + + pub(crate) fn finish(self) -> WasmFunctionData { + WasmFunctionData { + operands64: self.operands64.into_boxed_slice(), + operands128: self.operands128.into_boxed_slice(), + branch_table_targets: self.branch_table_targets.into_boxed_slice(), + exception_handlers: self.exception_handlers.into_boxed_slice(), + } + } +} + enum AggregateFields { Other, Struct(Box<[ValueLane]>), Array(ValueLane), } -#[derive(Default)] -struct FunctionDataBuilder { - v128_constants: Vec<[u8; 16]>, - branch_table_targets: Vec, - exception_handlers: Vec, -} - pub(crate) struct FunctionBuilder<'a> { instructions: Vec, data: FunctionDataBuilder, @@ -83,13 +172,14 @@ impl<'a> FunctionBuilder<'a> { local_types: Vec, local_addr_map: Vec, body_size: usize, + deduplicate_operands: bool, ) -> Self { Self { local_types, local_addr_map, metadata, instructions: Vec::with_capacity(body_size.min(1024)), - data: FunctionDataBuilder::default(), + data: FunctionDataBuilder::new(deduplicate_operands), control_stack: alloc::vec![ControlFrame { kind: BlockKind::Function, has_else: false, @@ -112,10 +202,18 @@ impl<'a> FunctionBuilder<'a> { &mut self, type_index: u32, field_index: u32, - instruction: fn(u32, u32) -> Instruction, + instruction: fn(OperandIdx) -> Instruction, ) -> Result<()> { let size = self.metadata.struct_field(type_index, field_index)?; - self.emit(&[ValueLane::S32], &[size], instruction(type_index, field_index)) + let operand = self.push_operand(TwoU32 { first: type_index, second: field_index })?; + self.emit(&[ValueLane::S32], &[size], instruction(operand)) + } + + fn push_operand(&mut self, operand: T) -> Result> + where + T::Raw: BuilderRawOperand, + { + self.data.push_operand(operand) } } @@ -294,17 +392,19 @@ impl VisitSimdOperator<'_> for ValidateThenVisit<'_, '_> { pub(crate) fn process_operators( body: FunctionBody<'_>, - local_types: Vec, - local_addr_map: Vec, + locals: (Vec, Vec), metadata: &ModuleMetadata, ty_idx: u32, allocs: OperatorsReaderAllocations, -) -> Result<(Vec, WasmFunctionData, OperatorsReaderAllocations)> { + deduplicate_operands: bool, +) -> Result<(Vec, FunctionDataBuilder, OperatorsReaderAllocations)> { + let (local_types, local_addr_map) = locals; let body_size = body.as_bytes().len(); let reader = body.get_binary_reader_for_operators()?; let mut reader = OperatorsReader::new_with_allocs(reader, allocs); let signature = metadata.signature(ty_idx)?.clone(); - let mut builder = FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size); + let mut builder = + FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, deduplicate_operands); while !reader.eof() { let position = reader.original_position(); @@ -319,29 +419,26 @@ pub(crate) fn process_operators( } reader.finish()?; - let data = WasmFunctionData { - v128_constants: builder.data.v128_constants.into_boxed_slice(), - branch_table_targets: builder.data.branch_table_targets.into_boxed_slice(), - exception_handlers: builder.data.exception_handlers.into_boxed_slice(), - }; - Ok((builder.instructions, data, reader.into_allocations())) + Ok((builder.instructions, builder.data, reader.into_allocations())) } #[cfg(feature = "validate")] pub(crate) fn process_operators_and_validate( mut validator: FuncValidator, body: FunctionBody<'_>, - local_types: Vec, - local_addr_map: Vec, + locals: (Vec, Vec), metadata: &ModuleMetadata, ty_idx: u32, allocs: OperatorsReaderAllocations, -) -> Result<(Vec, WasmFunctionData, FuncValidatorAllocations, OperatorsReaderAllocations)> { + deduplicate_operands: bool, +) -> Result<(Vec, FunctionDataBuilder, FuncValidatorAllocations, OperatorsReaderAllocations)> { + let (local_types, local_addr_map) = locals; let body_size = body.as_bytes().len(); let reader = body.get_binary_reader_for_operators()?; let mut reader = OperatorsReader::new_with_allocs(reader, allocs); let signature = metadata.signature(ty_idx)?.clone(); - let mut builder = FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size); + let mut builder = + FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, deduplicate_operands); while !reader.eof() { let position = reader.original_position(); @@ -356,12 +453,7 @@ pub(crate) fn process_operators_and_validate( } reader.finish()?; - let data = WasmFunctionData { - v128_constants: builder.data.v128_constants.into_boxed_slice(), - branch_table_targets: builder.data.branch_table_targets.into_boxed_slice(), - exception_handlers: builder.data.exception_handlers.into_boxed_slice(), - }; - Ok((builder.instructions, data, validator.into_allocations(), reader.into_allocations())) + Ok((builder.instructions, builder.data, validator.into_allocations(), reader.into_allocations())) } impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { @@ -395,7 +487,6 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fixed [] => [] { visit_data_drop(segment: u32) => DataDrop, visit_elem_drop(segment: u32) => ElemDrop } fixed [] => [S32] { visit_i32_const(value: i32) => Const32, visit_ref_func(function: u32) => RefFunc } - fixed [] => [S64] { visit_i64_const(value: i64) => Const64 } heap false [] => [S32] { visit_ref_null => RefNull } heap false [S32] => [S32] { visit_ref_test_non_null => RefTest, visit_ref_cast_non_null => RefCast, @@ -483,22 +574,10 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { table [] => [Addr] { visit_table_size(table: u32) => TableSize } table [S32, Addr] => [Addr] { visit_table_grow(table: u32) => TableGrow } table [Addr, S32, Addr] => [] { visit_table_fill(table: u32) => TableFill } - table [Addr, S32, S32] => [] { visit_table_init(elem_index: u32, table: u32) => TableInit } fixed [] => [S32] { visit_struct_new_default(type_index: u32) => StructNewDefault } fixed [S32] => [S32] { visit_array_new_default(type_index: u32) => ArrayNewDefault, visit_array_len => ArrayLen, } - fixed [S32, S32] => [S32] { - visit_array_new_data(type_index: u32, data_index: u32) => ArrayNewData, - visit_array_new_elem(type_index: u32, elem_index: u32) => ArrayNewElem, - } - fixed [S32, S32, S32, S32] => [] { - visit_array_init_data(type_index: u32, data_index: u32) => ArrayInitData, - visit_array_init_elem(type_index: u32, elem_index: u32) => ArrayInitElem, - } - fixed [S32, S32, S32, S32, S32] => [] { - visit_array_copy(type_index_dst: u32, type_index_src: u32) => ArrayCopy, - } array_field [Field, S32] => [S32] { visit_array_new(type_index: u32) => ArrayNew } array_field [S32, S32] => [Field] { visit_array_get(type_index: u32) => ArrayGet, visit_array_get_s(type_index: u32) => ArrayGetS, @@ -533,7 +612,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Self::Output { let size = self.metadata.struct_field(type_index, field_index)?; - self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(type_index, field_index)) + let operand = self.push_operand(TwoU32 { first: type_index, second: field_index })?; + self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(operand)) } fn visit_array_new_fixed(&mut self, type_index: u32, array_size: u32) -> Self::Output { @@ -542,7 +622,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { self.pop_expect(size)?; } self.push_sizes(&[ValueLane::S32])?; - self.instructions.push(Instruction::ArrayNewFixed(type_index, array_size)); + let operand = self.push_operand(TwoU32 { first: type_index, second: array_size })?; + self.instructions.push(Instruction::ArrayNewFixed(operand)); Ok(()) } @@ -555,7 +636,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { let signature = self.metadata.signature(type_index)?.clone(); let mut inputs = signature.params; inputs.push(self.metadata.table_size(table_index)?); - self.emit(&inputs, &signature.results, Instruction::CallIndirect(type_index, table_index)) + let operand = self.push_operand(TwoU32 { first: type_index, second: table_index })?; + self.emit(&inputs, &signature.results, Instruction::CallIndirect(operand)) } fn visit_call_ref(&mut self, type_index: u32) -> Self::Output { @@ -579,7 +661,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { inputs.push(self.metadata.table_size(table_index)?); self.apply_effect(&inputs, &[])?; self.mark_unreachable(); - self.instructions.push(Instruction::ReturnCallIndirect(type_index, table_index)); + let operand = self.push_operand(TwoU32 { first: type_index, second: table_index })?; + self.instructions.push(Instruction::ReturnCallIndirect(operand)); Ok(()) } @@ -851,7 +934,9 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { let header_ip = self.instructions.len(); let branch_table_start = self.data.branch_table_targets.len() as u32; - self.instructions.push(Instruction::BranchTable(0, branch_table_start, len)); + let branch_operand = + self.data.push_target_operand(BranchTableArg { target: 0, start: branch_table_start, len })?; + self.instructions.push(Instruction::BranchTable(branch_operand)); struct PadInfo { depth: u32, @@ -894,8 +979,10 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { .iter() .find(|pad| pad.depth == default_depth) .ok_or_else(|| crate::ParseError::Other("missing default branch table target".into()))?; - if let Instruction::BranchTable(default_ip, _, _) = &mut self.instructions[header_ip] { - *default_ip = default_pad.pad_start as u32; + if let Instruction::BranchTable(index) = self.instructions[header_ip] { + let mut operand = self.data.operand(index); + operand.target = default_pad.pad_start as u32; + self.data.set_operand(index, operand); } for pad in &pads { @@ -921,26 +1008,66 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_f64_const(&mut self, val: wasmparser::Ieee64) -> Self::Output { - self.emit(&[], &[ValueLane::S64], Instruction::Const64(val.bits() as i64)) + let operand = self.push_operand(I64Operand { value: val.bits() as i64 })?; + self.emit(&[], &[ValueLane::S64], Instruction::Const64(operand)) + } + + fn visit_i64_const(&mut self, value: i64) -> Self::Output { + let operand = self.push_operand(I64Operand { value })?; + self.emit(&[], &[ValueLane::S64], Instruction::Const64(operand)) } fn visit_table_copy(&mut self, dst_table: u32, src_table: u32) -> Self::Output { let dst = self.metadata.table_size(dst_table)?; let src = self.metadata.table_size(src_table)?; let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; - self.emit(&[dst, src, len], &[], Instruction::TableCopy { dst_table, src_table }) + let operand = self.push_operand(TwoU32 { first: dst_table, second: src_table })?; + self.emit(&[dst, src, len], &[], Instruction::TableCopy(operand)) } fn visit_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Self::Output { let dst = self.metadata.memory_size(dst_mem)?; let src = self.metadata.memory_size(src_mem)?; let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; - self.emit(&[dst, src, len], &[], Instruction::MemoryCopy { dst_mem, src_mem }) + let operand = self.push_operand(TwoU32 { first: dst_mem, second: src_mem })?; + self.emit(&[dst, src, len], &[], Instruction::MemoryCopy(operand)) } fn visit_memory_init(&mut self, data_index: u32, memory: u32) -> Self::Output { let dst = self.metadata.memory_size(memory)?; - self.emit(&[dst, ValueLane::S32, ValueLane::S32], &[], Instruction::MemoryInit(data_index, memory)) + let operand = self.push_operand(TwoU32 { first: data_index, second: memory })?; + self.emit(&[dst, ValueLane::S32, ValueLane::S32], &[], Instruction::MemoryInit(operand)) + } + + fn visit_table_init(&mut self, elem_index: u32, table: u32) -> Self::Output { + let address = self.metadata.table_size(table)?; + let operand = self.push_operand(TwoU32 { first: elem_index, second: table })?; + self.emit(&[address, ValueLane::S32, ValueLane::S32], &[], Instruction::TableInit(operand)) + } + + fn visit_array_new_data(&mut self, type_index: u32, data_index: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index, second: data_index })?; + self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewData(operand)) + } + + fn visit_array_new_elem(&mut self, type_index: u32, elem_index: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index, second: elem_index })?; + self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewElem(operand)) + } + + fn visit_array_init_data(&mut self, type_index: u32, data_index: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index, second: data_index })?; + self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitData(operand)) + } + + fn visit_array_init_elem(&mut self, type_index: u32, elem_index: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index, second: elem_index })?; + self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitElem(operand)) + } + + fn visit_array_copy(&mut self, type_index_dst: u32, type_index_src: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index_dst, second: type_index_src })?; + self.emit(&[ValueLane::S32; 5], &[], Instruction::ArrayCopy(operand)) } fn visit_br_on_cast( @@ -1187,19 +1314,13 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { } fn visit_i8x16_shuffle(&mut self, lanes: [u8; 16]) -> Self::Output { - self.emit( - &[ValueLane::S128, ValueLane::S128], - &[ValueLane::S128], - Instruction::I8x16Shuffle(self.data.v128_constants.len() as u32), - )?; - self.data.v128_constants.push(lanes); - Ok(()) + let index = self.push_operand(V128Operand { value: lanes })?; + self.emit(&[ValueLane::S128, ValueLane::S128], &[ValueLane::S128], Instruction::I8x16Shuffle(index)) } fn visit_v128_const(&mut self, value: wasmparser::V128) -> Self::Output { - self.emit(&[], &[ValueLane::S128], Instruction::Const128(self.data.v128_constants.len() as u32))?; - self.data.v128_constants.push(*value.bytes()); - Ok(()) + let index = self.push_operand(V128Operand { value: *value.bytes() })?; + self.emit(&[], &[ValueLane::S128], Instruction::Const128(index)) } } @@ -1213,7 +1334,12 @@ impl FunctionBuilder<'_> { self.pop_expect(ValueLane::S32)?; let target = convert_heap_type(target.heap_type(), target.is_nullable())?; let conditional_ip = self.instructions.len(); - self.instructions.push(Instruction::BrOnCast(0, target, branch_on_fail)); + let operand = self.data.push_target_operand(CastBranch { target: 0, ref_type_bits: target.to_bits() })?; + self.instructions.push(if branch_on_fail { + Instruction::BrOnCastFail(operand) + } else { + Instruction::BrOnCast(operand) + }); self.push_sizes(&[ValueLane::S32])?; self.emit_dropkeep_to_label(relative_depth)?; self.emit_branch_jump_or_return(relative_depth)?; @@ -1357,10 +1483,15 @@ impl FunctionBuilder<'_> { /// Emits the stack-shaping instruction required by a branch. fn emit_dropkeep(&mut self, base: ValueCounts, keep: ValueCounts) { let target = ValueCounts { c32: base.c32 + keep.c32, c64: base.c64 + keep.c64, c128: base.c128 + keep.c128 }; - if self.lane_counts == target { - return; + if self.lane_counts.c32 != target.c32 { + self.instructions.push(Instruction::DropKeep32 { base: base.c32, keep: keep.c32 }); + } + if self.lane_counts.c64 != target.c64 { + self.instructions.push(Instruction::DropKeep64 { base: base.c64, keep: keep.c64 }); + } + if self.lane_counts.c128 != target.c128 { + self.instructions.push(Instruction::DropKeep128 { base: base.c128, keep: keep.c128 }); } - self.instructions.push(Instruction::DropKeep((base, keep).into())); } fn patch_jump(&mut self, jump_ip: usize, target: usize) { @@ -1369,10 +1500,14 @@ impl FunctionBuilder<'_> { | Instruction::JumpIfZero32(ip) | Instruction::JumpIfNonZero32(ip) | Instruction::JumpIfRefNull(ip) - | Instruction::JumpIfRefNonNull(ip) - | Instruction::BrOnCast(ip, _, _) => { + | Instruction::JumpIfRefNonNull(ip) => { *ip = target as u32; } + Instruction::BrOnCast(index) | Instruction::BrOnCastFail(index) => { + let mut operand = self.data.operand(*index); + operand.target = target as u32; + self.data.set_operand(*index, operand); + } _ => {} } } diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 0bdb474..9da4a7a 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -205,11 +205,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { SelectMulti(counts) => self.store.value_stack.select_multi(*counts), Call(v) => { self.exec_call_direct(*v)?; return Ok(None); } CallSelf => { self.exec_call_self()?; return Ok(None); } - CallIndirect(ty, table) => { self.exec_call_indirect::(*ty, *table)?; return Ok(None); } + CallIndirect(idx) => { self.exec_call_indirect::(*idx)?; return Ok(None); } CallRef(ty) => { self.exec_call_ref::(*ty)?; return Ok(None); } ReturnCall(v) => { if self.exec_return_call_direct(*v)? { return Ok(Some(())); } return Ok(None); } ReturnCallSelf => { self.exec_return_call_self()?; return Ok(None); } - ReturnCallIndirect(ty, table) => { if self.exec_call_indirect::(*ty, *table)? { return Ok(Some(())); } return Ok(None); } + ReturnCallIndirect(idx) => { if self.exec_call_indirect::(*idx)? { return Ok(Some(())); } return Ok(None); } ReturnCallRef(ty) => { if self.exec_call_ref::(*ty)? { return Ok(Some(())); } return Ok(None); } Throw(tag) => { self.exec_throw(*tag)?; return Ok(None); } ThrowRef => { self.exec_throw_ref()?; return Ok(None); } @@ -228,79 +228,56 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { if !is_non_null { ValueRef::stack_pop(&mut self.store.value_stack); } is_non_null }) { return Ok(None) }, - BrOnCast(ip, ty, on_fail) => if self.exec_ref_matches(*ty) == *on_fail { self.cf.instr_ptr = *ip as usize; return Ok(None); }, - JumpIfLocalZero32 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value32::local_get(&self.store.value_stack, cf, *local) == 0) { return Ok(None) }, - JumpIfLocalNonZero32 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value32::local_get(&self.store.value_stack, cf, *local) != 0) { return Ok(None) }, - JumpIfLocalZero64 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value64::local_get(&self.store.value_stack, cf, *local) == 0) { return Ok(None) }, - JumpIfLocalNonZero64 { target_ip, local } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| Value64::local_get(&self.store.value_stack, cf, *local) != 0) { return Ok(None) }, - JumpCmpStackConst32 { target_ip, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| cmp_i32(i32::stack_pop(&mut self.store.value_stack), *imm, *op)) { return Ok(None) }, - JumpCmpStackConst64 { target_ip, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| cmp_i64(i64::stack_pop(&mut self.store.value_stack), *imm, *op)) { return Ok(None) }, - JumpCmpStackLocal32 { target_ip, local, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { + BrOnCast(idx) => { let v = idx.get(&self.func.data); if !self.exec_ref_matches(v.ref_type()) { self.cf.instr_ptr = v.target as usize; return Ok(None); } }, + BrOnCastFail(idx) => { let v = idx.get(&self.func.data); if self.exec_ref_matches(v.ref_type()) { self.cf.instr_ptr = v.target as usize; return Ok(None); } }, + JumpIfLocalZero32(arg) => if Self::exec_jump_if(&mut self.cf, arg.target_ip, |cf| Value32::local_get(&self.store.value_stack, cf, arg.local) == 0) { return Ok(None) }, + JumpIfLocalNonZero32(arg) => if Self::exec_jump_if(&mut self.cf, arg.target_ip, |cf| Value32::local_get(&self.store.value_stack, cf, arg.local) != 0) { return Ok(None) }, + JumpIfLocalZero64(arg) => if Self::exec_jump_if(&mut self.cf, arg.target_ip, |cf| Value64::local_get(&self.store.value_stack, cf, arg.local) == 0) { return Ok(None) }, + JumpIfLocalNonZero64(arg) => if Self::exec_jump_if(&mut self.cf, arg.target_ip, |cf| Value64::local_get(&self.store.value_stack, cf, arg.local) != 0) { return Ok(None) }, + JumpCmpStackConst32(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&mut self.cf, v.target, |_| cmp_i32(i32::stack_pop(&mut self.store.value_stack), v.value, packed.op)) { return Ok(None) } }, + JumpCmpStackConst64(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&mut self.cf, v.target, |_| cmp_i64(i64::stack_pop(&mut self.store.value_stack), v.value, packed.op)) { return Ok(None) } }, + JumpCmpStackLocal32(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&mut self.cf, v.target, |cf| { let lhs = i32::stack_pop(&mut self.store.value_stack); - cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, *local), *op) - }) { return Ok(None) }, - JumpCmpStackLocal64 { target_ip, local, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { + cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, v.local), packed.op) + }) { return Ok(None) } }, + JumpCmpStackLocal64(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&mut self.cf, v.target, |cf| { let lhs = i64::stack_pop(&mut self.store.value_stack); - cmp_i64(lhs, i64::local_get(&self.store.value_stack, cf, *local), *op) - }) { return Ok(None) }, - BinOpLocalConstJump32 { target_ip, local, imm, op, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { - let value = exec_binop_32(*op, i32::local_get(&self.store.value_stack, cf, *local) as u32, *imm as u32) as i32; - i32::local_set(&mut self.store.value_stack, cf, *local, value); - (value == 0) == *on_zero - }) { return Ok(None) }, - BinOpLocalConstJumpCmpLocal32 { target_ip, local, imm, binop, right, cmp } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { - let lhs = exec_binop_32(*binop, i32::local_get(&self.store.value_stack, cf, *local) as u32, *imm as u32) as i32; - i32::local_set(&mut self.store.value_stack, cf, *local, lhs); - cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, *right), *cmp) - }) { return Ok(None) }, - BinOpStackConstTeeLocalJump32 { target_ip, local, imm, op, on_zero } => { - let value = exec_binop_32(*op, i32::stack_pop(&mut self.store.value_stack) as u32, *imm as u32) as i32; - i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); - i32::stack_push(&mut self.store.value_stack, value)?; - if Self::exec_jump_if(&mut self.cf, *target_ip, |_| (value == 0) == *on_zero) { return Ok(None) } - }, - BinOpGlobalConstJump32 { target_ip, global, imm, op, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| { - let global = self.module.resolve_global_addr(*global); - let value = exec_binop_32(*op, i32::global_get(&self.store.state.globals, global) as u32, *imm as u32) as i32; + cmp_i64(lhs, i64::local_get(&self.store.value_stack, cf, v.local), packed.op) + }) { return Ok(None) } }, + BinOpLocalConstJump32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| { let value = exec_binop_32(op, i32::local_get(&self.store.value_stack, cf, v.local) as u32, v.value as u32) as i32; i32::local_set(&mut self.store.value_stack, cf, v.local, value); (value == 0) == (v.on_zero != 0) }) { return Ok(None) } }, + BinOpLocalConstJumpCmpLocal32(packed) => { let v = packed.index.get(&self.func.data); let (binop, cmp) = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| { let lhs = exec_binop_32(binop, i32::local_get(&self.store.value_stack, cf, v.local) as u32, v.value as u32) as i32; i32::local_set(&mut self.store.value_stack, cf, v.local, lhs); cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, v.right), cmp) }) { return Ok(None) } }, + BinOpStackConstTeeLocalJump32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; let value = exec_binop_32(op, i32::stack_pop(&mut self.store.value_stack) as u32, v.value as u32) as i32; i32::local_set(&mut self.store.value_stack, &self.cf, v.local, value); i32::stack_push(&mut self.store.value_stack, value)?; if Self::exec_jump_if(&mut self.cf, v.target, |_| (value == 0) == (v.on_zero != 0)) { return Ok(None) } }, + BinOpGlobalConstJump32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |_| { + let global = self.module.resolve_global_addr(v.global); + let value = exec_binop_32(op, i32::global_get(&self.store.state.globals, global) as u32, v.value as u32) as i32; i32::global_set(&mut self.store.state.globals, global, value); - (value == 0) == *on_zero - }) { return Ok(None) }, - IncLocalJump32 { target_ip, local, delta, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { - let value = i32::local_get(&self.store.value_stack, cf, *local).wrapping_add(*delta); - i32::local_set(&mut self.store.value_stack, cf, *local, value); - (value == 0) == *on_zero - }) { return Ok(None) }, - IncStackTeeLocalJump32 { target_ip, local, delta, on_zero } => { - let value = i32::stack_pop(&mut self.store.value_stack).wrapping_add(*delta); - i32::local_set(&mut self.store.value_stack, &self.cf, *local, value); - i32::stack_push(&mut self.store.value_stack, value)?; - if Self::exec_jump_if(&mut self.cf, *target_ip, |_| (value == 0) == *on_zero) { return Ok(None) } - }, - IncGlobalJump32 { target_ip, global, delta, on_zero } => if Self::exec_jump_if(&mut self.cf, *target_ip, |_| { - let global = self.module.resolve_global_addr(*global); - let value = i32::global_get(&self.store.state.globals, global).wrapping_add(*delta); + (value == 0) == (v.on_zero != 0) + }) { return Ok(None) } }, + IncLocalJump32(idx) => { let v = idx.get(&self.func.data); if Self::exec_jump_if(&mut self.cf, v.target, |cf| { let value = i32::local_get(&self.store.value_stack, cf, v.local).wrapping_add(v.value); i32::local_set(&mut self.store.value_stack, cf, v.local, value); (value == 0) == (v.on_zero != 0) }) { return Ok(None) } }, + IncStackTeeLocalJump32(idx) => { let v = idx.get(&self.func.data); let value = i32::stack_pop(&mut self.store.value_stack).wrapping_add(v.value); i32::local_set(&mut self.store.value_stack, &self.cf, v.local, value); i32::stack_push(&mut self.store.value_stack, value)?; if Self::exec_jump_if(&mut self.cf, v.target, |_| (value == 0) == (v.on_zero != 0)) { return Ok(None) } }, + IncGlobalJump32(idx) => { let v = idx.get(&self.func.data); if Self::exec_jump_if(&mut self.cf, v.target, |_| { + let global = self.module.resolve_global_addr(v.global); + let value = i32::global_get(&self.store.state.globals, global).wrapping_add(v.value); i32::global_set(&mut self.store.state.globals, global, value); - (value == 0) == *on_zero - }) { return Ok(None) }, - IncLocalJumpCmpLocal32 { target_ip, local, delta, right, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| { - let lhs = i32::local_get(&self.store.value_stack, cf, *local).wrapping_add(*delta); - i32::local_set(&mut self.store.value_stack, cf, *local, lhs); - cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, *right), *op) - }) { return Ok(None) }, - JumpCmpLocalConst32 { target_ip, local, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, *local), *imm, *op)) { return Ok(None) }, - JumpCmpLocalConst64 { target_ip, local, imm, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, *local), i64::from(*imm), *op)) { return Ok(None) }, - JumpCmpLocalLocal32 { target_ip, left, right, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, *left), i32::local_get(&self.store.value_stack, cf, *right), *op)) { return Ok(None) }, - JumpCmpLocalLocal64 { target_ip, left, right, op } => if Self::exec_jump_if(&mut self.cf, *target_ip, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, *left), i64::local_get(&self.store.value_stack, cf, *right), *op)) { return Ok(None) }, - DropKeep(drop_keep) => self.exec_drop_keep(*drop_keep), - BranchTable(default_ip, start, len) => { self.exec_branch_table(*default_ip, *start, *len); return Ok(None); } + (value == 0) == (v.on_zero != 0) + }) { return Ok(None) } }, + IncLocalJumpCmpLocal32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| { let lhs = i32::local_get(&self.store.value_stack, cf, v.local).wrapping_add(v.value); i32::local_set(&mut self.store.value_stack, cf, v.local, lhs); cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, v.right), op) }) { return Ok(None) } }, + JumpCmpLocalConst32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, v.local), v.value, op)) { return Ok(None) } }, + JumpCmpLocalConst64(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, v.local), i64::from(v.value), op)) { return Ok(None) } }, + JumpCmpLocalLocal32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, v.left), i32::local_get(&self.store.value_stack, cf, v.right), op)) { return Ok(None) } }, + JumpCmpLocalLocal64(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&mut self.cf, v.target, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, v.left), i64::local_get(&self.store.value_stack, cf, v.right), op)) { return Ok(None) } }, + DropKeep32 { base, keep } => self.store.value_stack.stack_32.truncate_keep((self.cf.stack_base().s32 + u32::from(*base)) as usize, *keep as usize), + DropKeep64 { base, keep } => self.store.value_stack.stack_64.truncate_keep((self.cf.stack_base().s64 + u32::from(*base)) as usize, *keep as usize), + DropKeep128 { base, keep } => self.store.value_stack.stack_128.truncate_keep((self.cf.stack_base().s128 + u32::from(*base)) as usize, *keep as usize), + BranchTable(idx) => { self.exec_branch_table(*idx); return Ok(None); } Return => { if self.exec_return() { return Ok(Some(())); } return Ok(None); } ReturnVoid => { if self.exec_return_void() { return Ok(Some(())); } return Ok(None); } Return32 => { if self.exec_return_32() { return Ok(Some(())); } return Ok(None); } Return64 => { if self.exec_return_64() { return Ok(Some(())); } return Ok(None); } Return128 => { if self.exec_return_128() { return Ok(Some(())); } return Ok(None); } - LocalGet32(local_index) => self.store.value_stack.push(Value32::local_get(&self.store.value_stack, &self.cf, *local_index))?, - LocalGet64(local_index) => self.store.value_stack.push(Value64::local_get(&self.store.value_stack, &self.cf, *local_index))?, - LocalGet128(local_index) => self.store.value_stack.push(Value128::local_get(&self.store.value_stack, &self.cf, *local_index))?, + LocalGet32(local_index) => Value32::local_push(&mut self.store.value_stack, &self.cf, *local_index)?, + LocalGet64(local_index) => Value64::local_push(&mut self.store.value_stack, &self.cf, *local_index)?, + LocalGet128(local_index) => Value128::local_push(&mut self.store.value_stack, &self.cf, *local_index)?, LocalSet32(local_index) => exec_op!(local_set_pop Value32, local_index), LocalSet64(local_index) => exec_op!(local_set_pop Value64, local_index), LocalSet128(local_index) => exec_op!(local_set_pop Value128, local_index), @@ -308,9 +285,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { LocalCopy64(from, to) => Value64::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), LocalCopy128(from, to) => Value128::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), AddConst32(c) => exec_op!(unary i32 => i32, |v| v.wrapping_add(*c)), - AddConst64(c) => exec_op!(unary i64 => i64, |v| v.wrapping_add(*c)), - IncLocal32(local_index, delta) => i32::local_update(&mut self.store.value_stack, &self.cf, *local_index, |v| v.wrapping_add(*delta)), - IncLocal64(local_index, delta) => i64::local_update(&mut self.store.value_stack, &self.cf, *local_index, |v| v.wrapping_add(*delta )), + AddConst64(idx) => { let c = idx.get(&self.func.data).value; exec_op!(unary i64 => i64, |v| v.wrapping_add(c)); }, + IncLocal32(arg) => i32::local_update(&mut self.store.value_stack, &self.cf, arg.local, |v| v.wrapping_add(arg.value)), + IncLocal64(packed) => { let v = packed.index.get(&self.func.data).value; i64::local_update(&mut self.store.value_stack, &self.cf, packed.op, |n| n.wrapping_add(v)); }, I32Add3 => exec_op!(ternary i32 => i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)), I64Add3 => exec_op!(ternary i64 => i64, |a, b, c| a.wrapping_add(b).wrapping_add(c)), MulAccLocal32(acc) => exec_op!(binop_acc_local i32, acc, |a: i32, b| a.wrapping_mul(b), |a: i32, b| a.wrapping_add(b)), @@ -322,59 +299,65 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { BinOpLocalLocal128(op, a, b) => exec_op!(binop_local_local Value128, exec_binop_128, op, a, b), CmpLocalLocal32(op, a, b) => exec_op!(cmp_local_local i32, cmp_i32, op, a, b), CmpLocalLocal64(op, a, b) => exec_op!(cmp_local_local i64, cmp_i64, op, a, b), - BinOpLocalLocalSet32(op, a, b, dst) => exec_op!(binop_local_local_set Value32, exec_binop_32, op, a, b, dst), - BinOpLocalLocalSet64(op, a, b, dst) => exec_op!(binop_local_local_set Value64, exec_binop_64, op, a, b, dst), - BinOpLocalLocalSet128(op, a, b, dst) => exec_op!(binop_local_local_set Value128, exec_binop_128, op, a, b, dst), - BinOpLocalLocalTee32(op, a, b, dst) => exec_op!(binop_local_local_tee Value32, exec_binop_32, op, a, b, dst), - BinOpLocalLocalTee64(op, a, b, dst) => exec_op!(binop_local_local_tee Value64, exec_binop_64, op, a, b, dst), - BinOpLocalLocalTee128(op, a, b, dst) => exec_op!(binop_local_local_tee Value128, exec_binop_128, op, a, b, dst), - BinOpLocalConst32(op, local_index, c) => exec_op!(binop_local_const Value32, exec_binop_32, op, local_index, *c as u32), - BinOpLocalConst64(op, local_index, c) => exec_op!(binop_local_const Value64, exec_binop_64, op, local_index, *c as u64), - BinOpLocalConst128(op, local_index, c) => exec_op!(binop_local_const Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c))), - BinOpGlobalConst32(op, global_index, c) => exec_op!(binop_global_const Value32, exec_binop_32, op, global_index, *c as u32), - BinOpGlobalConst64(op, global_index, c) => exec_op!(binop_global_const Value64, exec_binop_64, op, global_index, *c as u64), - BinOpGlobalConst128(op, global_index, c) => exec_op!(binop_global_const Value128, exec_binop_128, op, global_index, Value128(self.func.data.v128_const(*c))), - BinOpLocalConstSet32(op, local_index, c, dst) => exec_op!(binop_local_const_set Value32, exec_binop_32, op, local_index, *c as u32, dst), - BinOpLocalConstSet64(op, local_index, c, dst) => exec_op!(binop_local_const_set Value64, exec_binop_64, op, local_index, *c as u64, dst), - BinOpLocalConstSet128(op, local_index, c, dst) => exec_op!(binop_local_const_set Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), - BinOpLocalConstTee32(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value32, exec_binop_32, op, local_index, *c as u32, dst), - BinOpLocalConstTee64(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value64, exec_binop_64, op, local_index, *c as u64, dst), - BinOpLocalConstTee128(op, local_index, c, dst) => exec_op!(binop_local_const_tee Value128, exec_binop_128, op, local_index, Value128(self.func.data.v128_const(*c)), dst), + AddLocalLocalSet32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.left).wrapping_add(i32::local_get(&self.store.value_stack, &self.cf, arg.right)); i32::local_set(&mut self.store.value_stack, &self.cf, arg.dst, value); }, + AddLocalLocalTee32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.left).wrapping_add(i32::local_get(&self.store.value_stack, &self.cf, arg.right)); i32::local_set(&mut self.store.value_stack, &self.cf, arg.dst, value); i32::stack_push(&mut self.store.value_stack, value)?; }, + BinOpLocalLocalSet32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.left), Value32::local_get(&self.store.value_stack, &self.cf, v.right)); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, + BinOpLocalLocalSet64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.left), Value64::local_get(&self.store.value_stack, &self.cf, v.right)); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, + BinOpLocalLocalSet128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.left), Value128::local_get(&self.store.value_stack, &self.cf, v.right)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, + BinOpLocalLocalTee32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.left), Value32::local_get(&self.store.value_stack, &self.cf, v.right)); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value32::stack_push(&mut self.store.value_stack, value)?; }, + BinOpLocalLocalTee64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.left), Value64::local_get(&self.store.value_stack, &self.cf, v.right)); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value64::stack_push(&mut self.store.value_stack, value)?; }, + BinOpLocalLocalTee128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.left), Value128::local_get(&self.store.value_stack, &self.cf, v.right)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value128::stack_push(&mut self.store.value_stack, value)?; }, + AddLocalConst32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.local).wrapping_add(arg.value); i32::stack_push(&mut self.store.value_stack, value)?; }, + SubLocalConst32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.local).wrapping_sub(arg.value); i32::stack_push(&mut self.store.value_stack, value)?; }, + MulLocalConst32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.local).wrapping_mul(arg.value); i32::stack_push(&mut self.store.value_stack, value)?; }, + BinOpLocalConst32(packed) => { let v = packed.index.get(&self.func.data); let lhs = Value32::local_get(&self.store.value_stack, &self.cf, v.local); Value32::stack_push(&mut self.store.value_stack, exec_binop_32(packed.op, lhs, v.value))?; }, + BinOpLocalConst64(packed) => { let v = packed.index.get(&self.func.data); let lhs = Value64::local_get(&self.store.value_stack, &self.cf, v.local); Value64::stack_push(&mut self.store.value_stack, exec_binop_64(packed.op, lhs, v.value))?; }, + BinOpLocalConst128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.local), Value128(v.value.get(&self.func.data).value)); Value128::stack_push(&mut self.store.value_stack, value)?; }, + BinOpGlobalConst32(packed) => { let v = packed.index.get(&self.func.data); Value32::stack_push(&mut self.store.value_stack, exec_binop_32(packed.op, Value32::global_get(&self.store.state.globals, self.module.resolve_global_addr(v.global)), v.value))?; }, + BinOpGlobalConst64(packed) => { let v = packed.index.get(&self.func.data); Value64::stack_push(&mut self.store.value_stack, exec_binop_64(packed.op, Value64::global_get(&self.store.state.globals, self.module.resolve_global_addr(v.global)), v.value))?; }, + BinOpGlobalConst128(packed) => { let v = packed.index.get(&self.func.data); Value128::stack_push(&mut self.store.value_stack, exec_binop_128(packed.op, Value128::global_get(&self.store.state.globals, self.module.resolve_global_addr(v.global)), Value128(v.value.get(&self.func.data).value)))?; }, + BinOpLocalConstSet32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, + BinOpLocalConstTee32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value32::stack_push(&mut self.store.value_stack, value)?; }, + BinOpLocalConstSet64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, + BinOpLocalConstTee64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value64::stack_push(&mut self.store.value_stack, value)?; }, + BinOpLocalConstSet128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.local), Value128(v.value.get(&self.func.data).value)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, + BinOpLocalConstTee128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.local), Value128(v.value.get(&self.func.data).value)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value128::stack_push(&mut self.store.value_stack, value)?; }, BinOpStackGlobal32(op, global_index) => exec_op!(binop_stack_global Value32, exec_binop_32, op, global_index), BinOpStackGlobal64(op, global_index) => exec_op!(binop_stack_global Value64, exec_binop_64, op, global_index), BinOpStackLocal32(op, local) => exec_op!(binop_stack_local Value32, exec_binop_32, op, local), BinOpStackLocalSet32(op, local, dst) => exec_op!(binop_stack_local_set Value32, exec_binop_32, op, local, dst), BinOpStackLocalTee32(op, local, dst) => exec_op!(binop_stack_local_tee Value32, exec_binop_32, op, local, dst), - SetLocalConst32(local_index, c) => i32::local_set(&mut self.store.value_stack, &self.cf, *local_index, *c), - SetLocalConst64(local_index, c) => i64::local_set(&mut self.store.value_stack, &self.cf, *local_index, *c), - SetLocalConst128(local_index, c) => Value128::local_set(&mut self.store.value_stack, &self.cf, *local_index, Value128(self.func.data.v128_const(*c))), - IncMemoryLocal32(m, addr_local) => self.exec_inc_memory_local::(*m, *addr_local, |v| v.wrapping_add(1))?, - IncMemoryLocal64(m, addr_local) => self.exec_inc_memory_local::(*m, *addr_local, |v| v.wrapping_add(1))?, - StoreLocalLocal32(m, addr_local, value_local) => self.exec_store_local_local::(*m, *addr_local, *value_local)?, - StoreLocalLocal64(m, addr_local, value_local) => self.exec_store_local_local::(*m, *addr_local, *value_local)?, - StoreLocalLocal128(m, addr_local, value_local) => self.exec_store_local_local::(*m, *addr_local, *value_local)?, - LoadLocal32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, |v| v)?, - LoadLocal64(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, |v| v)?, - LoadLocal8S32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, - LoadLocal8U32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, - LoadLocal16S32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, - LoadLocal16U32(m, addr_local) => self.exec_load_local::(*m, *addr_local, 0, i32::from)?, - LoadLocalTee32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, - LoadLocalSet32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, - LoadLocalTee8S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee8U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee16S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee16U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet8S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet8U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet16S32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalSet16U32(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, i32::from)?, - LoadLocalTee128(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, - LoadLocalSet128(m, addr_local, dst_local) => self.exec_load_local::(*m, *addr_local, *dst_local, |v| v)?, - AndConstTee32(c, local_index) => { exec_op!(unary i32 => i32, |v| v & *c); exec_op!(local_tee i32, local_index); } - SubConstTee32(c, local_index) => { exec_op!(unary i32 => i32, |v| v.wrapping_sub(*c)); exec_op!(local_tee i32, local_index); } - AndConstTee64(c, local_index) => { exec_op!(unary i64 => i64, |v| v & *c); exec_op!(local_tee i64, local_index); } - SubConstTee64(c, local_index) => { exec_op!(unary i64 => i64, |v| v.wrapping_sub(*c)); exec_op!(local_tee i64, local_index); } + BinOpStackLocal128(op, local) => exec_op!(binop_stack_local Value128, exec_binop_128, op, local), + SetLocalConst32(arg) => i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, arg.value), + SetLocalConst64(packed) => { let v = packed.index.get(&self.func.data).value; i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, v); }, + SetLocalConst128(packed) => Value128::local_set(&mut self.store.value_stack, &self.cf, packed.op, Value128(packed.index.get(&self.func.data).value)), + IncMemoryLocal32(arg) => self.exec_inc_memory_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, |v| v.wrapping_add(1))?, + IncMemoryLocal64(arg) => self.exec_inc_memory_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, |v| v.wrapping_add(1))?, + StoreLocalLocal32(arg) => self.exec_store_local_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2)?, + StoreLocalLocal64(arg) => self.exec_store_local_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2)?, + StoreLocalLocal128(arg) => self.exec_store_local_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2)?, + LoadLocal32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, |v| v)?, + LoadLocal64(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, |v| v)?, + LoadLocal8S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, + LoadLocal8U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, + LoadLocal16S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, + LoadLocal16U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, + LoadLocalTee32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, + LoadLocalSet32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, + LoadLocalTee8S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalTee8U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalTee16S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalTee16U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalSet8S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalSet8U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalSet16S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalSet16U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, + LoadLocalTee128(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, + LoadLocalSet128(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, + AndConstTee32(arg) => { exec_op!(unary i32 => i32, |v| v & arg.value); let value = i32::stack_peek(&self.store.value_stack); i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, value); }, + SubConstTee32(arg) => { exec_op!(unary i32 => i32, |v| v.wrapping_sub(arg.value)); let value = i32::stack_peek(&self.store.value_stack); i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, value); }, + AndConstTee64(packed) => { let v = packed.index.get(&self.func.data).value; exec_op!(unary i64 => i64, |n| n & v); let value = i64::stack_peek(&self.store.value_stack); i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, value); }, + SubConstTee64(packed) => { let v = packed.index.get(&self.func.data).value; exec_op!(unary i64 => i64, |n| n.wrapping_sub(v)); let value = i64::stack_peek(&self.store.value_stack); i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, value); }, LocalTee32(local_index) => exec_op!(local_tee Value32, local_index), LocalTee64(local_index) => exec_op!(local_tee Value64, local_index), LocalTee128(local_index) => exec_op!(local_tee Value128, local_index), @@ -388,7 +371,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { GlobalTee64(global_index) => exec_op!(global_tee Value64, global_index), GlobalTee128(global_index) => exec_op!(global_tee Value128, global_index), Const32(val) => i32::stack_push(&mut self.store.value_stack, *val)?, - Const64(val) => i64::stack_push(&mut self.store.value_stack, *val)?, + Const64Imm(val) => i64::stack_push(&mut self.store.value_stack, i64::from(*val))?, + Const64(idx) => i64::stack_push(&mut self.store.value_stack, idx.get(&self.func.data).value)?, + Const128Imm(val) => Value128::stack_push(&mut self.store.value_stack, Value128(u128::from(*val).to_le_bytes()))?, I64Eqz => exec_op!(unary i64 => i32, |v| i32::from(v == 0)), I32Eqz => exec_op!(unary i32 => i32, |v| i32::from(v == 0)), I32Eq => exec_op!(binary i32 => i32, |a, b| i32::from(a == b)), @@ -502,32 +487,32 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { // GC objects StructNew(ty) => self.exec_struct_new(*ty, false)?, StructNewDefault(ty) => self.exec_struct_new(*ty, true)?, - StructGet(ty, field) => self.exec_struct_get(*ty, *field, None)?, - StructGetS(ty, field) => self.exec_struct_get(*ty, *field, Some(true))?, - StructGetU(ty, field) => self.exec_struct_get(*ty, *field, Some(false))?, - StructSet(ty, field) => self.exec_struct_set(*ty, *field)?, + StructGet(idx) => self.exec_struct_get(*idx, None)?, + StructGetS(idx) => self.exec_struct_get(*idx, Some(true))?, + StructGetU(idx) => self.exec_struct_get(*idx, Some(false))?, + StructSet(idx) => self.exec_struct_set(*idx)?, ArrayNew(ty) => self.exec_array_new(*ty, false)?, ArrayNewDefault(ty) => self.exec_array_new(*ty, true)?, - ArrayNewFixed(ty, len) => self.exec_array_new_fixed(*ty, *len)?, - ArrayNewData(ty, data) => self.exec_array_new_data(*ty, *data)?, - ArrayNewElem(ty, elem) => self.exec_array_new_elem(*ty, *elem)?, + ArrayNewFixed(idx) => self.exec_array_new_fixed(*idx)?, + ArrayNewData(idx) => self.exec_array_new_data(*idx)?, + ArrayNewElem(idx) => self.exec_array_new_elem(*idx)?, ArrayGet(ty) => self.exec_array_get(*ty, None)?, ArrayGetS(ty) => self.exec_array_get(*ty, Some(true))?, ArrayGetU(ty) => self.exec_array_get(*ty, Some(false))?, ArraySet(ty) => self.exec_array_set(*ty)?, ArrayLen => self.exec_array_len()?, ArrayFill(ty) => self.exec_array_fill(*ty)?, - ArrayCopy(dst, src) => self.exec_array_copy(*dst, *src)?, - ArrayInitData(ty, data) => self.exec_array_init_data(*ty, *data)?, - ArrayInitElem(ty, elem) => self.exec_array_init_elem(*ty, *elem)?, + ArrayCopy(idx) => self.exec_array_copy(*idx)?, + ArrayInitData(idx) => self.exec_array_init_data(*idx)?, + ArrayInitElem(idx) => self.exec_array_init_elem(*idx)?, MemorySize(addr) => self.exec_memory_size(*addr)?, MemoryGrow(addr) => self.exec_memory_grow(*addr)?, // Bulk memory operations - MemoryCopy { dst_mem, src_mem } => self.exec_memory_copy(*dst_mem, *src_mem)?, + MemoryCopy(idx) => self.exec_memory_copy(*idx)?, MemoryFill(addr) => self.exec_memory_fill(*addr)?, - MemoryFillImm(addr, val, size) => self.exec_memory_fill_imm(*addr, *val, *size)?, - MemoryInit(data_idx, mem_idx) => self.exec_memory_init(*data_idx, *mem_idx)?, + MemoryFillConst(idx) => self.exec_memory_fill_const(*idx)?, + MemoryInit(idx) => self.exec_memory_init(*idx)?, DataDrop(data_index) => self.store.state.get_data_mut(self.module.resolve_data_addr(*data_index)).drop(), ElemDrop(elem_index) => self.store.state.get_elem_mut(self.module.resolve_elem_addr(*elem_index)).drop(), @@ -535,37 +520,37 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { TableGet(table_idx) => self.exec_table_get(*table_idx)?, TableSet(table_idx) => self.exec_table_set(*table_idx)?, TableSize(table_idx) => self.exec_table_size(*table_idx)?, - TableInit(elem_idx, table_idx) => self.exec_table_init(*elem_idx, *table_idx)?, + TableInit(idx) => self.exec_table_init(*idx)?, TableGrow(table_idx) => self.exec_table_grow(*table_idx)?, TableFill(table_idx) => self.exec_table_fill(*table_idx)?, - TableCopy { dst_table, src_table } => self.exec_table_copy(*dst_table, *src_table)?, + TableCopy(idx) => self.exec_table_copy(*idx)?, // Core memory load/store operations - I32Store(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v)?, - I64Store(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v)?, - F32Store(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v)?, - F64Store(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v)?, + I32Store(idx) => self.exec_mem_store::(*idx, |v| v)?, + I64Store(idx) => self.exec_mem_store::(*idx, |v| v)?, + F32Store(idx) => self.exec_mem_store::(*idx, |v| v)?, + F64Store(idx) => self.exec_mem_store::(*idx, |v| v)?, FMaStoreF32(m) => self.exec_fma_store::(*m)?, FMaStoreF64(m) => self.exec_fma_store::(*m)?, - I32Store8(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v as i8)?, - I32Store16(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v as i16)?, - I64Store8(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v as i8)?, - I64Store16(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v as i16)?, - I64Store32(m) => self.exec_mem_store::(m.mem_addr(), m.offset(), |v| v as i32)?, - I32Load(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), |v| v)?, - I64Load(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), |v| v)?, - F32Load(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), |v| v)?, - F64Load(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), |v| v)?, - I32Load8S(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i32::from)?, - I32Load8U(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i32::from)?, - I32Load16S(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i32::from)?, - I32Load16U(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i32::from)?, - I64Load8S(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, - I64Load8U(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, - I64Load16S(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, - I64Load16U(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, - I64Load32S(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, - I64Load32U(m) => self.exec_mem_load::(m.mem_addr(), m.offset(), i64::from)?, + I32Store8(idx) => self.exec_mem_store::(*idx, |v| v as i8)?, + I32Store16(idx) => self.exec_mem_store::(*idx, |v| v as i16)?, + I64Store8(idx) => self.exec_mem_store::(*idx, |v| v as i8)?, + I64Store16(idx) => self.exec_mem_store::(*idx, |v| v as i16)?, + I64Store32(idx) => self.exec_mem_store::(*idx, |v| v as i32)?, + I32Load(idx) => self.exec_mem_load::(*idx, |v| v)?, + I64Load(idx) => self.exec_mem_load::(*idx, |v| v)?, + F32Load(idx) => self.exec_mem_load::(*idx, |v| v)?, + F64Load(idx) => self.exec_mem_load::(*idx, |v| v)?, + I32Load8S(idx) => self.exec_mem_load::(*idx, i32::from)?, + I32Load8U(idx) => self.exec_mem_load::(*idx, i32::from)?, + I32Load16S(idx) => self.exec_mem_load::(*idx, i32::from)?, + I32Load16U(idx) => self.exec_mem_load::(*idx, i32::from)?, + I64Load8S(idx) => self.exec_mem_load::(*idx, i64::from)?, + I64Load8U(idx) => self.exec_mem_load::(*idx, i64::from)?, + I64Load16S(idx) => self.exec_mem_load::(*idx, i64::from)?, + I64Load16U(idx) => self.exec_mem_load::(*idx, i64::from)?, + I64Load32S(idx) => self.exec_mem_load::(*idx, i64::from)?, + I64Load32U(idx) => self.exec_mem_load::(*idx, i64::from)?, // Numeric conversion operations F32ConvertI32S => exec_op!(unary i32 => f32, |v| v as f32), @@ -637,25 +622,25 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { V128AnyTrue => exec_op!(unary Value128 => i32, |v| v.v128_any_true() as i32), I8x16Swizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_swizzle(s)), I8x16RelaxedSwizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_relaxed_swizzle(s)), - V128Load(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| v)?, - V128Load8x8S(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load8x8_s(v.to_le_bytes()))?, - V128Load8x8U(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load8x8_u(v.to_le_bytes()))?, - V128Load16x4S(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load16x4_s(v.to_le_bytes()))?, - V128Load16x4U(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load16x4_u(v.to_le_bytes()))?, - V128Load32x2S(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load32x2_s(v.to_le_bytes()))?, - V128Load32x2U(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::v128_load32x2_u(v.to_le_bytes()))?, - V128Load8Splat(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), Value128::splat_i8)?, - V128Load16Splat(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), Value128::splat_i16)?, - V128Load32Splat(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), Value128::splat_i32)?, - V128Load64Splat(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), Value128::splat_i64)?, - V128Store(arg) => self.exec_mem_store::(arg.mem_addr(), arg.offset(), |v| v)?, - V128Store8Lane(arg, lane) => self.exec_mem_store_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Store16Lane(arg, lane) => self.exec_mem_store_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Store32Lane(arg, lane) => self.exec_mem_store_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Store64Lane(arg, lane) => self.exec_mem_store_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Load32Zero(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::from_i32x4([v, 0, 0, 0]))?, - V128Load64Zero(arg) => self.exec_mem_load::(arg.mem_addr(), arg.offset(), |v| Value128::from_i64x2([v, 0]))?, - Const128(arg) => Value128::stack_push(&mut self.store.value_stack, Value128(self.func.data.v128_const(*arg)))?, + V128Load(idx) => self.exec_mem_load::(*idx, |v| v)?, + V128Load8x8S(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load8x8_s(v.to_le_bytes()))?, + V128Load8x8U(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load8x8_u(v.to_le_bytes()))?, + V128Load16x4S(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load16x4_s(v.to_le_bytes()))?, + V128Load16x4U(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load16x4_u(v.to_le_bytes()))?, + V128Load32x2S(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load32x2_s(v.to_le_bytes()))?, + V128Load32x2U(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load32x2_u(v.to_le_bytes()))?, + V128Load8Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i8)?, + V128Load16Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i16)?, + V128Load32Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i32)?, + V128Load64Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i64)?, + V128Store(idx) => self.exec_mem_store::(*idx, |v| v)?, + V128Store8Lane(arg) => self.exec_mem_store_lane::(*arg)?, + V128Store16Lane(arg) => self.exec_mem_store_lane::(*arg)?, + V128Store32Lane(arg) => self.exec_mem_store_lane::(*arg)?, + V128Store64Lane(arg) => self.exec_mem_store_lane::(*arg)?, + V128Load32Zero(idx) => self.exec_mem_load::(*idx, |v| Value128::from_i32x4([v, 0, 0, 0]))?, + V128Load64Zero(idx) => self.exec_mem_load::(*idx, |v| Value128::from_i64x2([v, 0]))?, + Const128(arg) => Value128::stack_push(&mut self.store.value_stack, Value128(arg.get(&self.func.data).value))?, I8x16ExtractLaneS(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i8(*lane) as i32), I8x16ExtractLaneU(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_u8(*lane) as i32), I16x8ExtractLaneS(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i16(*lane) as i32), @@ -664,10 +649,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I64x2ExtractLane(lane) => exec_op!(unary Value128 => i64, |v| v.extract_lane_i64(*lane)), F32x4ExtractLane(lane) => exec_op!(unary Value128 => f32, |v| v.extract_lane_f32(*lane)), F64x2ExtractLane(lane) => exec_op!(unary Value128 => f64, |v| v.extract_lane_f64(*lane)), - V128Load8Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Load16Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Load32Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, - V128Load64Lane(arg, lane) => self.exec_mem_load_lane::(arg.mem_addr(), arg.offset(), *lane)?, + V128Load8Lane(arg) => self.exec_mem_load_lane::(*arg)?, + V128Load16Lane(arg) => self.exec_mem_load_lane::(*arg)?, + V128Load32Lane(arg) => self.exec_mem_load_lane::(*arg)?, + V128Load64Lane(arg) => self.exec_mem_load_lane::(*arg)?, I8x16ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i8x16_replace_lane(*lane, value as i8)), I16x8ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i16x8_replace_lane(*lane, value as i16)), I32x4ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i32x4_replace_lane(*lane, value)), @@ -822,7 +807,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I64x2ExtendHighI32x4S => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_s()), I64x2ExtendHighI32x4U => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_u()), I8x16Popcnt => exec_op!(unary Value128 => Value128, |v| v.i8x16_popcnt()), - I8x16Shuffle(idx) => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_shuffle(a, b, Value128(self.func.data.v128_const(*idx)))), + I8x16Shuffle(idx) => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_shuffle(a, b, Value128(idx.get(&self.func.data).value))), I16x8Q15MulrSatS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_q15mulr_sat_s(b)), I32x4DotI16x8S => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_dot_i16x8_s(b)), I8x16RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i8x16_relaxed_laneselect(a, b, c)), @@ -900,25 +885,18 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { condition } - fn exec_branch_table(&mut self, default_ip: u32, start: u32, len: u32) { + fn exec_branch_table(&mut self, index: OperandIdx) { + let v = index.get(&self.func.data); let idx = ::stack_pop(&mut self.store.value_stack); - let target_ip = if idx >= 0 && (idx as u32) < len { - self.func.data.branch_table_targets.get((start + idx as u32) as usize).copied().unwrap_or(default_ip) + let target_ip = if idx >= 0 && (idx as u32) < v.len { + self.func.data.branch_table_targets.get((v.start + idx as u32) as usize).copied().unwrap_or(v.target) } else { - default_ip + v.target }; self.cf.instr_ptr = target_ip as usize; } - fn exec_drop_keep(&mut self, drop_keep: DropKeep) { - let mut base = self.cf.stack_base(); - base.s32 += drop_keep.base.c32 as u32; - base.s64 += drop_keep.base.c64 as u32; - base.s128 += drop_keep.base.c128 as u32; - self.store.value_stack.truncate_keep_counts(base, drop_keep.keep); - } - fn create_exception(&mut self, tag_index: TagAddr) -> Result { let tag_addr = self.module.resolve_tag_addr(tag_index); let type_addr = self.store.state.get_tag(tag_addr).type_addr; @@ -1043,22 +1021,26 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } } - fn exec_call(&mut self, wasm_func: WasmFunctionInstance, func_addr: FuncAddr) -> Result<(), Trap> { - if !Arc::ptr_eq(&self.func, &wasm_func.func) { - self.func = wasm_func.func.clone(); - } - - let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals) - else { + fn exec_call( + &mut self, + wasm_func: Arc, + owner: ModuleInstanceId, + func_addr: FuncAddr, + ) -> Result<(), Trap> { + let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.params, &wasm_func.locals) else { return cold!(Err(Trap::CallStackOverflow)); }; self.store.call_stack.push(self.cf)?; - self.cf = CallFrame::new(func_addr, locals_base, wasm_func.func.locals); - if wasm_func.owner != self.module.id() { + let locals = wasm_func.locals; + if !Arc::ptr_eq(&self.func, &wasm_func) { + self.func = wasm_func; + } + self.cf = CallFrame::new(func_addr, locals_base, locals); + if owner != self.module.id() { self.module = self .store - .get_module_instance(wasm_func.owner) + .get_module_instance(owner) .unwrap_or_else(|| unreachable!("invalid module instance")) .clone(); } @@ -1066,21 +1048,25 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_return_call(&mut self, wasm_func: WasmFunctionInstance, func_addr: FuncAddr) -> Result<(), Trap> { - if !Arc::ptr_eq(&self.func, &wasm_func.func) { - self.func = wasm_func.func.clone(); - } - - self.store.value_stack.truncate_keep_counts(self.cf.locals_base, wasm_func.func.params); - let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.func.params, &wasm_func.func.locals) - else { + fn exec_return_call( + &mut self, + wasm_func: Arc, + owner: ModuleInstanceId, + func_addr: FuncAddr, + ) -> Result<(), Trap> { + self.store.value_stack.truncate_keep_counts(self.cf.locals_base, wasm_func.params); + let Ok(locals_base) = self.store.value_stack.enter_locals(&wasm_func.params, &wasm_func.locals) else { return cold!(Err(Trap::CallStackOverflow)); }; - self.cf = CallFrame::new(func_addr, locals_base, wasm_func.func.locals); - if wasm_func.owner != self.module.id() { + let locals = wasm_func.locals; + if !Arc::ptr_eq(&self.func, &wasm_func) { + self.func = wasm_func; + } + self.cf = CallFrame::new(func_addr, locals_base, locals); + if owner != self.module.id() { self.module = self .store - .get_module_instance(wasm_func.owner) + .get_module_instance(owner) .unwrap_or_else(|| unreachable!("invalid module instance")) .clone(); } @@ -1132,11 +1118,13 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_call_direct(&mut self, v: u32) -> Result<(), Trap> { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); let addr = self.module.resolve_func_addr(v); - let func = self.store.state.get_func(addr).clone(); - match func.kind { - crate::store::FunctionKind::Wasm(wasm_func) => self.exec_call(wasm_func, addr), + let func = self.store.state.get_func(addr); + match &func.kind { + crate::store::FunctionKind::Wasm(wasm_func) => { + self.exec_call(wasm_func.func.clone(), wasm_func.owner, addr) + } crate::store::FunctionKind::Host(host_func) => { - self.exec_call_host::(host_func, func.type_addr, func.gc.params)?; + self.exec_call_host::(host_func.clone(), func.type_addr, func.gc.params)?; Ok(()) } } @@ -1145,14 +1133,14 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_return_call_direct(&mut self, v: u32) -> Result { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); let addr = self.module.resolve_func_addr(v); - let func = self.store.state.get_func(addr).clone(); - match func.kind { + let func = self.store.state.get_func(addr); + match &func.kind { crate::store::FunctionKind::Wasm(wasm_func) => { - self.exec_return_call(wasm_func, addr)?; + self.exec_return_call(wasm_func.func.clone(), wasm_func.owner, addr)?; Ok(false) } crate::store::FunctionKind::Host(host_func) => { - self.exec_call_host::(host_func, func.type_addr, func.gc.params) + self.exec_call_host::(host_func.clone(), func.type_addr, func.gc.params) } } } @@ -1179,11 +1167,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_call_indirect( - &mut self, - type_addr: u32, - table_addr: u32, - ) -> Result { + fn exec_call_indirect(&mut self, index: OperandIdx) -> Result { + let TwoU32 { first: type_addr, second: table_addr } = index.get(&self.func.data); self.charge_call_fuel(FUEL_COST_CALL_TOTAL); // verify that the table is of the right type, this should be validated by the parser already @@ -1207,20 +1192,20 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { func_addr: FuncAddr, expected_type_addr: TypeAddr, ) -> Result { - let func = self.store.state.get_func(func_addr).clone(); + let func = self.store.state.get_func(func_addr); if !self.store.state.type_addr_is_subtype(func.type_addr, expected_type_addr) { return cold!(Err(Trap::IndirectCallTypeMismatch { actual: Box::new(self.store.state.get_canonical_func_type(func.type_addr).clone()), expected: Box::new(self.store.state.get_canonical_func_type(expected_type_addr).clone()), })); } - match func.kind { + match &func.kind { crate::store::FunctionKind::Wasm(wasm_func) => match IS_RETURN_CALL { - true => self.exec_return_call(wasm_func, func_addr), - false => self.exec_call(wasm_func, func_addr), + true => self.exec_return_call(wasm_func.func.clone(), wasm_func.owner, func_addr), + false => self.exec_call(wasm_func.func.clone(), wasm_func.owner, func_addr), }, crate::store::FunctionKind::Host(host_func) => { - return self.exec_call_host::(host_func, func.type_addr, func.gc.params); + return self.exec_call_host::(host_func.clone(), func.type_addr, func.gc.params); } }?; Ok(false) @@ -1287,7 +1272,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec_store_local_local, const N: usize>( &mut self, - memarg: MemoryArg, + memarg: CompactMemoryArg, addr_local: u8, value_local: u8, ) -> Result<(), Trap> { @@ -1313,7 +1298,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec_inc_memory_local, const N: usize>( &mut self, - memarg: MemoryArg, + memarg: CompactMemoryArg, addr_local: u8, increment: impl FnOnce(T) -> T, ) -> Result<(), Trap> { @@ -1333,7 +1318,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { }; let mem = self.store.state.get_mem_mut(mem_addr); - let value = T::load_at(&*mem.inner, addr)?; + let value = cold_err!(T::load_at(&*mem.inner, addr))?; increment(value).store_at(&mut *mem.inner, addr) } @@ -1343,7 +1328,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { const N: usize, >( &mut self, - m: MemoryArg, + m: CompactMemoryArg, ) -> Result<(), Trap> { let rhs = T::stack_pop(&mut self.store.value_stack); let lhs = T::stack_pop(&mut self.store.value_stack); @@ -1361,7 +1346,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec_load_local_value, const N: usize>( &self, - memarg: MemoryArg, + memarg: CompactMemoryArg, addr_local: u8, ) -> Result { let mem = self.store.state.get_mem(self.module.resolve_mem_addr(memarg.mem_addr())); @@ -1377,7 +1362,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); mem.effective_addr::(base as usize, memarg.offset())? }; - T::load_at(&*mem.inner, addr) + cold_err!(T::load_at(&*mem.inner, addr)) } #[inline(always)] @@ -1389,7 +1374,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { const TEE: bool, >( &mut self, - memarg: MemoryArg, + memarg: CompactMemoryArg, addr_local: u8, dst_local: u8, cast: impl Fn(LOAD) -> TARGET, @@ -1474,7 +1459,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_struct_get(&mut self, type_index: TypeAddr, field_index: u32, signed: Option) -> Result<(), Trap> { + fn exec_struct_get(&mut self, index: OperandIdx, signed: Option) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: field_index } = index.get(&self.func.data); let reference = ValueRef::stack_pop(&mut self.store.value_stack); let type_addr = self.module.resolve_type_addr(type_index); let storage = self.store.state.get_type(type_addr).as_struct().expect("validated struct.get type").fields @@ -1485,7 +1471,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { push_value(&mut self.store.value_stack, value, storage, signed) } - fn exec_struct_set(&mut self, type_index: TypeAddr, field_index: u32) -> Result<(), Trap> { + fn exec_struct_set(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: field_index } = index.get(&self.func.data); let type_addr = self.module.resolve_type_addr(type_index); let storage = self.store.state.get_type(type_addr).as_struct().expect("validated struct.set type").fields [field_index as usize] @@ -1508,7 +1495,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_array_new_fixed(&mut self, type_index: TypeAddr, len: u32) -> Result<(), Trap> { + fn exec_array_new_fixed(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: len } = index.get(&self.func.data); let type_addr = self.module.resolve_type_addr(type_index); let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.new_fixed type").field.storage; @@ -1567,7 +1555,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_array_copy(&mut self, dst_type: TypeAddr, src_type: TypeAddr) -> Result<(), Trap> { + fn exec_array_copy(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: dst_type, second: src_type } = index.get(&self.func.data); let len = u32::stack_pop(&mut self.store.value_stack) as usize; let src_index = u32::stack_pop(&mut self.store.value_stack) as usize; let src = ValueRef::stack_pop(&mut self.store.value_stack); @@ -1588,7 +1577,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_array_new_data(&mut self, type_index: TypeAddr, data_index: DataAddr) -> Result<(), Trap> { + fn exec_array_new_data(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: data_index } = index.get(&self.func.data); let len = u32::stack_pop(&mut self.store.value_stack) as usize; let src = u32::stack_pop(&mut self.store.value_stack) as usize; let type_addr = self.module.resolve_type_addr(type_index); @@ -1599,7 +1589,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_array_new_elem(&mut self, type_index: TypeAddr, elem_index: ElemAddr) -> Result<(), Trap> { + fn exec_array_new_elem(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: elem_index } = index.get(&self.func.data); let len = u32::stack_pop(&mut self.store.value_stack) as usize; let src = u32::stack_pop(&mut self.store.value_stack) as usize; let elem_addr = self.module.resolve_elem_addr(elem_index); @@ -1611,7 +1602,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_array_init_data(&mut self, type_index: TypeAddr, data_index: DataAddr) -> Result<(), Trap> { + fn exec_array_init_data(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: data_index } = index.get(&self.func.data); let len = u32::stack_pop(&mut self.store.value_stack) as usize; let src = u32::stack_pop(&mut self.store.value_stack) as usize; let dst = u32::stack_pop(&mut self.store.value_stack) as usize; @@ -1627,7 +1619,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_array_init_elem(&mut self, type_index: TypeAddr, elem_index: ElemAddr) -> Result<(), Trap> { + fn exec_array_init_elem(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: type_index, second: elem_index } = index.get(&self.func.data); let len = u32::stack_pop(&mut self.store.value_stack) as usize; let src = u32::stack_pop(&mut self.store.value_stack) as usize; let dst = u32::stack_pop(&mut self.store.value_stack) as usize; @@ -1669,7 +1662,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Result<(), Trap> { + fn exec_memory_copy(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: dst_mem, second: src_mem } = index.get(&self.func.data); let dst_mem_addr = self.module.resolve_mem_addr(dst_mem); let src_mem_addr = self.module.resolve_mem_addr(src_mem); let dst_arch = self.store.state.get_mem(dst_mem_addr).kind.arch(); @@ -1701,7 +1695,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.exec_memory_fill_impl(mem_addr, dst, val as u8, size) } - fn exec_memory_fill_imm(&mut self, addr: u32, val: u8, size: i32) -> Result<(), Trap> { + fn exec_memory_fill_const(&mut self, index: OperandIdx) -> Result<(), Trap> { + let MemoryFillConstOp { memory: addr, byte: val, value: size } = index.get(&self.func.data); let mem_addr = self.module.resolve_mem_addr(addr); let arch = self.store.state.get_mem(mem_addr).kind.arch(); let dst = self.store.value_stack.pop_memory_operand(arch)?; @@ -1717,7 +1712,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_memory_init(&mut self, data_index: u32, mem_index: u32) -> Result<(), Trap> { + fn exec_memory_init(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: data_index, second: mem_index } = index.get(&self.func.data); let size = u32::stack_pop(&mut self.store.value_stack) as usize; let offset = u32::stack_pop(&mut self.store.value_stack) as usize; let mem_addr = self.module.resolve_mem_addr(mem_index); @@ -1749,7 +1745,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_table_copy(&mut self, dst_table: u32, src_table: u32) -> Result<(), Trap> { + fn exec_table_copy(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: dst_table, second: src_table } = index.get(&self.func.data); let dst_table_addr = self.module.resolve_table_addr(dst_table); let src_table_addr = self.module.resolve_table_addr(src_table); let dst_arch = self.store.state.get_table(dst_table_addr).kind.arch(); @@ -1772,15 +1769,14 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_mem_load_lane, const LOAD_SIZE: usize>( &mut self, - mem_addr: tinywasm_types::MemAddr, - offset: u64, - lane: u8, + arg: MemoryLaneArg, ) -> Result<(), Trap> { - let mem = self.store.state.get_mem(self.module.resolve_mem_addr(mem_addr)); + let m = arg.memory_arg_idx.get(&self.func.data); + let mem = self.store.state.get_mem(self.module.resolve_mem_addr(m.mem_addr())); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, offset)?; - let val = LOAD::load_at(&*mem.inner, addr)?; - let offset = lane as usize * LOAD_SIZE; + let addr = mem.effective_addr::(base, m.offset())?; + let val = cold_err!(LOAD::load_at(&*mem.inner, addr))?; + let offset = arg.lane as usize * LOAD_SIZE; let mut imm = ::stack_pop(&mut self.store.value_stack).to_mem_bytes(); imm[offset..offset + LOAD_SIZE].copy_from_slice(&val.to_mem_bytes()); self.store.value_stack.push(Value128(imm))?; @@ -1790,32 +1786,28 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec_mem_load, const LOAD_SIZE: usize, TARGET: InternalValue>( &mut self, - mem_addr: tinywasm_types::MemAddr, - offset: u64, + index: OperandIdx, cast: impl Fn(LOAD) -> TARGET, ) -> Result<(), Trap> { - let mem = self.store.state.get_mem(self.module.resolve_mem_addr(mem_addr)); + let m = index.get(&self.func.data); + let mem = self.store.state.get_mem(self.module.resolve_mem_addr(m.mem_addr())); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, offset)?; + let addr = mem.effective_addr::(base, m.offset())?; let value = cold_err!(LOAD::load_at(&*mem.inner, addr))?; self.store.value_stack.push(cast(value)) } - fn exec_mem_store_lane + Copy, const N: usize>( - &mut self, - mem_addr: tinywasm_types::MemAddr, - offset: u64, - lane: u8, - ) -> Result<(), Trap> { + fn exec_mem_store_lane + Copy, const N: usize>(&mut self, arg: MemoryLaneArg) -> Result<(), Trap> { let bytes = ::stack_pop(&mut self.store.value_stack).to_mem_bytes(); - let lane_offset = lane as usize * N; + let lane_offset = arg.lane as usize * N; let mut val_bytes = [0u8; N]; val_bytes.copy_from_slice(&bytes[lane_offset..lane_offset + N]); let val = U::from_mem_bytes(val_bytes); - let mem_addr = self.module.resolve_mem_addr(mem_addr); + let m = arg.memory_arg_idx.get(&self.func.data); + let mem_addr = self.module.resolve_mem_addr(m.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, offset)?; + let addr = mem.effective_addr::(base, m.offset())?; let mem = self.store.state.get_mem_mut(mem_addr); cold_err!(val.store_at(&mut *mem.inner, addr))?; Ok(()) @@ -1823,17 +1815,17 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_mem_store, const N: usize>( &mut self, - mem_addr: tinywasm_types::MemAddr, - offset: u64, + index: OperandIdx, cast: impl Fn(T) -> U, ) -> Result<(), Trap> { let val = ::stack_pop(&mut self.store.value_stack); let val = cast(val); - let mem_addr = self.module.resolve_mem_addr(mem_addr); + let m = index.get(&self.func.data); + let mem_addr = self.module.resolve_mem_addr(m.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, offset)?; + let addr = mem.effective_addr::(base, m.offset())?; let mem = self.store.state.get_mem_mut(mem_addr); cold_err!(val.store_at(&mut *mem.inner, addr))?; Ok(()) @@ -1862,7 +1854,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } } - fn exec_table_init(&mut self, elem_index: u32, table_index: u32) -> Result<(), Trap> { + fn exec_table_init(&mut self, index: OperandIdx) -> Result<(), Trap> { + let TwoU32 { first: elem_index, second: table_index } = index.get(&self.func.data); let size = self.pop_table_operand(MemoryArch::I32)?; // n let offset = self.pop_table_operand(MemoryArch::I32)?; // s let table_addr = self.module.resolve_table_addr(table_index); diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index 43c214a..f2c0c28 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -109,6 +109,17 @@ impl Stack { Ok(()) } + #[inline(always)] + pub(crate) fn push_copy(&mut self, index: usize) -> Result<(), Trap> { + if !self.ensure_capacity_for(self.data.len() + 1) { + return cold!(Err(Trap::ValueStackOverflow)); + } + + let value = self.data[index]; + self.data.push(value); + Ok(()) + } + #[inline(always)] pub(crate) fn pop(&mut self) -> T { self.data.pop().unwrap_or_else(|| unreachable!("ValueStack underflow, this is a bug")) diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs index e2cbef0..4fb81c9 100644 --- a/crates/tinywasm/src/interpreter/values.rs +++ b/crates/tinywasm/src/interpreter/values.rs @@ -137,6 +137,7 @@ pub(crate) trait InternalValue: sealed::Sealed + Copy + Default { fn stack_peek(stack: &ValueStack) -> Self; fn stack_select(stack: &mut ValueStack); fn local_get(stack: &ValueStack, frame: &CallFrame, index: LocalAddr) -> Self; + fn local_push(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr) -> Result<(), crate::Trap>; fn local_set(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, value: Self); fn local_update(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, f: impl FnOnce(Self) -> Self); fn local_copy(stack: &mut ValueStack, frame: &CallFrame, from: LocalAddr, to: LocalAddr); @@ -178,6 +179,11 @@ macro_rules! impl_internalvalue { $from_stack } + #[inline(always)] + fn local_push(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr) -> Result<(), crate::Trap> { + stack.$stack.push_copy(frame.locals_base.$stack_base as usize + index as usize) + } + #[inline(always)] fn local_set(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, value: Self) { let $to_stack_v = value; diff --git a/crates/tinywasm/tests/wasm-custom/conditional-rewrite.wast b/crates/tinywasm/tests/wasm-custom/conditional-rewrite.wast new file mode 100644 index 0000000..bc92b30 --- /dev/null +++ b/crates/tinywasm/tests/wasm-custom/conditional-rewrite.wast @@ -0,0 +1,35 @@ +(module + (func (export "retained-value-before-update-branch") (param i32 i32) (result i32) + (block (result i32) + local.get 0 + i32.eqz + local.get 1 + i32.const 1 + i32.add + local.tee 1 + br_if 0 + ) + drop + local.get 1 + ) + + (func (export "compare-eqz-br-if") (param i32 i32) (result i32) + block + i32.const 1 + local.get 0 + local.get 1 + i32.lt_u + i32.eqz + br_if 0 + drop + i32.const 2 + return + end + i32.const 3 + ) +) + +(assert_return (invoke "retained-value-before-update-branch" (i32.const 0) (i32.const 0)) (i32.const 1)) +(assert_return (invoke "retained-value-before-update-branch" (i32.const 1) (i32.const -1)) (i32.const 0)) +(assert_return (invoke "compare-eqz-br-if" (i32.const 1) (i32.const 2)) (i32.const 2)) +(assert_return (invoke "compare-eqz-br-if" (i32.const 2) (i32.const 1)) (i32.const 3)) diff --git a/crates/tinywasm/tests/wasm-custom/sign-extension-rewrite.wast b/crates/tinywasm/tests/wasm-custom/sign-extension-rewrite.wast new file mode 100644 index 0000000..147858a --- /dev/null +++ b/crates/tinywasm/tests/wasm-custom/sign-extension-rewrite.wast @@ -0,0 +1,59 @@ +(module + (func (export "i32-shift-8") (param i32) (result i32) + local.get 0 + i32.const 8 + i32.shl + i32.const 8 + i32.shr_s + ) + (func (export "i32-extend-8") (param i32) (result i32) + local.get 0 + i32.const 24 + i32.shl + i32.const 24 + i32.shr_s + ) + (func (export "i32-extend-16") (param i32) (result i32) + local.get 0 + i32.const 16 + i32.shl + i32.const 16 + i32.shr_s + ) + (func (export "i64-shift-16") (param i64) (result i64) + local.get 0 + i64.const 16 + i64.shl + i64.const 16 + i64.shr_s + ) + (func (export "i64-extend-8") (param i64) (result i64) + local.get 0 + i64.const 56 + i64.shl + i64.const 56 + i64.shr_s + ) + (func (export "i64-extend-16") (param i64) (result i64) + local.get 0 + i64.const 48 + i64.shl + i64.const 48 + i64.shr_s + ) + (func (export "i64-extend-32") (param i64) (result i64) + local.get 0 + i64.const 32 + i64.shl + i64.const 32 + i64.shr_s + ) +) + +(assert_return (invoke "i32-shift-8" (i32.const 0x80)) (i32.const 0x80)) +(assert_return (invoke "i32-extend-8" (i32.const 0x80)) (i32.const -128)) +(assert_return (invoke "i32-extend-16" (i32.const 0x8000)) (i32.const -32768)) +(assert_return (invoke "i64-shift-16" (i64.const 0x80)) (i64.const 0x80)) +(assert_return (invoke "i64-extend-8" (i64.const 0x80)) (i64.const -128)) +(assert_return (invoke "i64-extend-16" (i64.const 0x8000)) (i64.const -32768)) +(assert_return (invoke "i64-extend-32" (i64.const 0x80000000)) (i64.const -2147483648)) diff --git a/crates/tinywasm/tests/wasm-custom/simd-stack-local.wast b/crates/tinywasm/tests/wasm-custom/simd-stack-local.wast new file mode 100644 index 0000000..0dabf4e --- /dev/null +++ b/crates/tinywasm/tests/wasm-custom/simd-stack-local.wast @@ -0,0 +1,53 @@ +(module + (func (export "and") (param v128 v128) (result v128) + local.get 0 + local.get 1 + v128.and + ) + (func (export "or") (param v128 v128) (result v128) + local.get 0 + local.get 1 + v128.or + ) + (func (export "add") (param v128 v128) (result v128) + local.get 0 + local.get 1 + i64x2.add + ) + (func (export "mul") (param v128 v128) (result v128) + local.get 0 + local.get 1 + i64x2.mul + ) + (func (export "deep-xor") (param v128 v128 v128) (result v128 v128) + local.get 0 + local.get 1 + local.get 2 + v128.xor + ) +) + +(assert_return + (invoke "and" (v128.const i32x4 -1 0 -1 0) (v128.const i32x4 1 2 3 4)) + (v128.const i32x4 1 0 3 0) +) +(assert_return + (invoke "or" (v128.const i32x4 1 0 3 0) (v128.const i32x4 0 2 0 4)) + (v128.const i32x4 1 2 3 4) +) +(assert_return + (invoke "add" (v128.const i64x2 1 2) (v128.const i64x2 3 4)) + (v128.const i64x2 4 6) +) +(assert_return + (invoke "mul" (v128.const i64x2 2 3) (v128.const i64x2 4 5)) + (v128.const i64x2 8 15) +) +(assert_return + (invoke "deep-xor" + (v128.const i32x4 1 2 3 4) + (v128.const i32x4 8 4 2 1) + (v128.const i32x4 1 1 1 1)) + (v128.const i32x4 1 2 3 4) + (v128.const i32x4 9 5 3 0) +) diff --git a/crates/types/src/archive.rs b/crates/types/src/archive.rs index 9904a7d..db40263 100644 --- a/crates/types/src/archive.rs +++ b/crates/types/src/archive.rs @@ -64,6 +64,9 @@ impl Module { #[cfg(test)] mod tests { use super::*; + use crate::{Instruction, ModuleInner, V128Operand, WasmFunction}; + use crate::{OperandIdx, OperandType}; + use alloc::{boxed::Box, sync::Arc, vec}; #[test] fn test_invalid_magic() { @@ -80,4 +83,27 @@ mod tests { twasm[4] = 0; assert!(matches!(Module::try_from_twasm(&twasm), Err(TwasmError::InvalidVersion))); } + + #[test] + fn v128_operands_round_trip_archive() { + let bytes = [0x00, 0x01, 0x02, 0x03, 0x7f, 0x80, 0xfe, 0xff, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x90]; + let mut function = WasmFunction::default(); + let constant = OperandIdx::new(0); + function.data.operands128 = vec![V128Operand { value: bytes }.encode()].into_boxed_slice(); + function.instructions = vec![Instruction::Const128(constant), Instruction::I8x16Shuffle(constant)].into(); + let module = Module::from(ModuleInner { funcs: Box::new([Arc::new(function)]), ..ModuleInner::default() }); + + let archive = module.serialize_twasm().expect("serialize archive"); + assert_eq!(&archive[..6], b"TWAS05"); + let decoded = Module::try_from_twasm(&archive).expect("deserialize archive"); + let function = &decoded.funcs[0]; + + for instruction in function.instructions.iter() { + let index = match instruction { + Instruction::Const128(index) | Instruction::I8x16Shuffle(index) => *index, + _ => panic!("unexpected instruction"), + }; + assert_eq!(index.get(&function.data).value, bytes); + } + } } diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index 10ab028..797f703 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -1,7 +1,8 @@ use alloc::boxed::Box; use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TagAddr, TypeAddr, ValueCounts}; -use crate::{ConstIdx, DataAddr, ElemAddr, MemAddr, RefType, RefValue}; +use crate::operands::sealed; +use crate::{DataAddr, ElemAddr, MemAddr, Operand64, Operand128, OperandIdx, OperandType, RefType, RefValue}; /// Represents a memory immediate in a WebAssembly memory instruction. #[derive(Copy, Clone, PartialEq, Eq)] @@ -13,13 +14,275 @@ pub struct MemoryArg { mem_addr: MemAddr, } -/// Stack lanes discarded and retained when branching to a control frame. -#[derive(Clone, Copy, PartialEq, Eq)] +/// A compact memory immediate used by optimized instructions. +/// +/// Optimized instructions use this representation when the offset and +/// module-local memory index fit its narrower fields. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +#[repr(Rust, packed)] +pub struct CompactMemoryArg { + offset: u32, + mem_addr: u16, +} + +/// An indexed memory argument and up to two local operands. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +#[repr(Rust, packed)] +pub struct MemoryLocalArg { + pub memory_arg_idx: OperandIdx, + pub local1: u8, + pub local2: u8, +} + +/// An indexed memory argument and SIMD lane. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +#[repr(Rust, packed)] +pub struct MemoryLaneArg { + pub memory_arg_idx: OperandIdx, + pub lane: u8, +} + +/// A 32-bit immediate and local operand that fit in an instruction payload. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +#[repr(Rust, packed)] +pub struct I32LocalArg { + pub value: i32, + pub local: LocalAddr, +} + +/// Three local operands that fit in an instruction payload. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +pub struct LocalTripleArg { + pub left: LocalAddr, + pub right: LocalAddr, + pub dst: LocalAddr, +} + +impl sealed::Sealed for LocalTripleArg {} + +impl OperandType for LocalTripleArg { + type Raw = Operand64; + + #[inline(always)] + fn decode(raw: Self::Raw) -> Self { + Self { left: raw.u16::<0>(), right: raw.u16::<2>(), dst: raw.u16::<4>() } + } + + #[inline] + fn encode(self) -> Self::Raw { + Operand64::default().with_u16::<0>(self.left).with_u16::<2>(self.right).with_u16::<4>(self.dst) + } +} + +/// A branch target and local operand that fit in an instruction payload. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +#[repr(Rust, packed)] +pub struct TargetLocalArg { + pub target_ip: u32, + pub local: LocalAddr, +} + +macro_rules! operand_view { + ($name:ident, $lane:ident, $raw:ty, { $($field:ident : $ty:ty = $read:ident / $write:ident ($offset:expr)),+ $(,)? }) => { + #[derive(Copy, Clone, PartialEq, Eq)] + #[cfg_attr(feature = "debug", derive(Debug))] + pub struct $name { + $(pub $field: $ty),+ + } + + impl sealed::Sealed for $name {} + + impl OperandType for $name { + type Raw = $raw; + + #[inline(always)] + fn decode(raw: Self::Raw) -> Self { + Self { $($field: raw.$read::<$offset>() as $ty),+ } + } + + #[inline] + fn encode(self) -> Self::Raw { + <$raw>::default()$(.$write::<$offset>(self.$field as _))+ + } + } + }; +} + +operand_view!(I64Operand, operands64, Operand64, { value: i64 = u64 / with_u64(0) }); +operand_view!(TwoU32, operands64, Operand64, { + first: u32 = u32 / with_u32(0), second: u32 = u32 / with_u32(4) +}); +operand_view!(LocalU32, operands64, Operand64, { + local: u16 = u16 / with_u16(0), value: u32 = u32 / with_u32(2) +}); +operand_view!(TargetLocal, operands64, Operand64, { + target: u32 = u32 / with_u32(0), local: u16 = u16 / with_u16(4) +}); + +operand_view!(LocalConst64, operands128, Operand128, { + local: u16 = u16 / with_u16(0), value: u64 = u64 / with_u64(2) +}); +operand_view!(GlobalConst32, operands64, Operand64, { + global: u32 = u32 / with_u32(0), value: u32 = u32 / with_u32(4) +}); +operand_view!(GlobalConst64, operands128, Operand128, { + global: u32 = u32 / with_u32(0), value: u64 = u64 / with_u64(4) +}); +operand_view!(LocalConstSet32, operands64, Operand64, { + local: u16 = u16 / with_u16(0), dst: u16 = u16 / with_u16(2), value: u32 = u32 / with_u32(4) +}); +operand_view!(LocalConstSet64, operands128, Operand128, { + local: u16 = u16 / with_u16(0), dst: u16 = u16 / with_u16(2), value: u64 = u64 / with_u64(4) +}); +operand_view!(MemoryFillConstOp, operands128, Operand128, { + memory: u32 = u32 / with_u32(0), byte: u8 = u8 / with_u8(4), value: i32 = u32 / with_u32(5) +}); +operand_view!(CastBranch, operands64, Operand64, { + target: u32 = u32 / with_u32(0), ref_type_bits: u32 = u32 / with_u32(4) +}); +operand_view!(BranchTableArg, operands128, Operand128, { + target: u32 = u32 / with_u32(0), start: u32 = u32 / with_u32(4), len: u32 = u32 / with_u32(8) +}); +operand_view!(StackConst32, operands64, Operand64, { + target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4) +}); +operand_view!(StackConst64, operands128, Operand128, { + target: u32 = u32 / with_u32(0), value: i64 = u64 / with_u64(4) +}); +operand_view!(LocalConstCmp, operands128, Operand128, { + target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8) +}); +operand_view!(LocalLocalCmp, operands64, Operand64, { + target: u32 = u32 / with_u32(0), left: u16 = u16 / with_u16(4), right: u16 = u16 / with_u16(6) +}); +operand_view!(LocalUpdate, operands128, Operand128, { + target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8), on_zero: u8 = u8 / with_u8(10) +}); +operand_view!(GlobalUpdate, operands128, Operand128, { + target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), global: u32 = u32 / with_u32(8), on_zero: u8 = u8 / with_u8(12) +}); +operand_view!(LocalUpdateCmp, operands128, Operand128, { + target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8), right: u16 = u16 / with_u16(10) +}); + +/// An operation packed inline with an indexed operand. +#[derive(Copy, Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] -pub struct DropKeep { - pub base: ValueCounts, - pub keep: ValueCounts, +#[cfg_attr( + feature = "archive", + serde(bound(serialize = "Op: Copy + serde::Serialize", deserialize = "Op: Copy + serde::de::DeserializeOwned",)) +)] +#[repr(Rust, packed)] +pub struct PackedOp { + pub op: Op, + pub index: OperandIdx, +} + +impl PackedOp { + /// Creates a packed operation from an operator and operand index. + #[inline] + pub const fn new(op: Op, index: OperandIdx) -> Self { + Self { op, index } + } +} + +/// A SIMD value stored in the 128-bit operand lane. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct V128Operand { + pub value: [u8; 16], +} + +/// A local SIMD operation with an indexed constant. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct LocalV128 { + pub local: u16, + pub value: OperandIdx, +} + +/// A global SIMD operation with an indexed constant. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct GlobalV128 { + pub global: u32, + pub value: OperandIdx, +} + +/// A local SIMD operation, indexed constant, and destination local. +#[derive(Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct LocalConstSetV128 { + pub local: u16, + pub dst: u16, + pub value: OperandIdx, +} + +macro_rules! operand_raw_view { + ($name:ident, $raw:ty, $decode:expr, $encode:expr) => { + impl sealed::Sealed for $name {} + + impl OperandType for $name { + type Raw = $raw; + + #[inline(always)] + fn decode(raw: Self::Raw) -> Self { + $decode(raw) + } + + #[inline] + fn encode(self) -> Self::Raw { + $encode(self) + } + } + }; +} + +operand_raw_view!(V128Operand, Operand128, |raw: Operand128| Self { value: raw.to_le_bytes() }, |value: Self| { + Operand128::from_le_bytes(value.value) +}); +operand_raw_view!( + LocalV128, + Operand64, + |raw: Operand64| Self { local: raw.u16::<0>(), value: OperandIdx::new(raw.u32::<2>()) }, + |value: Self| { Operand64::default().with_u16::<0>(value.local).with_u32::<2>(value.value.index()) } +); +operand_raw_view!( + GlobalV128, + Operand64, + |raw: Operand64| Self { global: raw.u32::<0>(), value: OperandIdx::new(raw.u32::<4>()) }, + |value: Self| { Operand64::default().with_u32::<0>(value.global).with_u32::<4>(value.value.index()) } +); +operand_raw_view!( + LocalConstSetV128, + Operand64, + |raw: Operand64| Self { local: raw.u16::<0>(), dst: raw.u16::<2>(), value: OperandIdx::new(raw.u32::<4>()) }, + |value: Self| { + Operand64::default().with_u16::<0>(value.local).with_u16::<2>(value.dst).with_u32::<4>(value.value.index()) + } +); + +impl CastBranch { + #[inline] + pub const fn ref_type(self) -> RefType { + match RefType::from_bits(self.ref_type_bits) { + Some(value) => value, + None => unreachable!(), + } + } } /// A catch clause attached to a lowered `try_table` instruction. @@ -62,12 +325,6 @@ pub struct ExceptionHandler { pub catches: Box<[ExceptionCatch]>, } -impl From<(ValueCounts, ValueCounts)> for DropKeep { - fn from((base, keep): (ValueCounts, ValueCounts)) -> Self { - Self { base, keep } - } -} - impl MemoryArg { #[inline] pub const fn new(offset: u64, mem_addr: MemAddr) -> Self { @@ -85,6 +342,80 @@ impl MemoryArg { } } +impl sealed::Sealed for MemoryArg {} + +impl OperandType for MemoryArg { + type Raw = Operand128; + + #[inline(always)] + fn decode(raw: Self::Raw) -> Self { + Self::new(raw.u64::<0>(), raw.u32::<8>()) + } + + #[inline] + fn encode(self) -> Self::Raw { + Operand128::default().with_u64::<0>(self.offset).with_u32::<8>(self.mem_addr) + } +} + +impl CompactMemoryArg { + /// Returns the static byte offset. + #[inline] + pub const fn offset(self) -> u64 { + self.offset as u64 + } + + /// Returns the module-local memory index. + #[inline] + pub const fn mem_addr(self) -> MemAddr { + self.mem_addr as MemAddr + } +} + +impl sealed::Sealed for CompactMemoryArg {} + +impl OperandType for CompactMemoryArg { + type Raw = Operand64; + + #[inline(always)] + fn decode(raw: Self::Raw) -> Self { + Self { offset: raw.u32::<0>(), mem_addr: raw.u16::<4>() } + } + + #[inline] + fn encode(self) -> Self::Raw { + Operand64::default().with_u32::<0>(self.offset).with_u16::<4>(self.mem_addr) + } +} + +impl TryFrom for CompactMemoryArg { + type Error = (); + + #[inline] + fn try_from(arg: MemoryArg) -> Result { + Ok(Self { + offset: u32::try_from(arg.offset()).map_err(|_| ())?, + mem_addr: u16::try_from(arg.mem_addr()).map_err(|_| ())?, + }) + } +} + +impl From for MemoryArg { + #[inline] + fn from(arg: CompactMemoryArg) -> Self { + Self::new(arg.offset(), arg.mem_addr()) + } +} + +const _: () = { + assert!(core::mem::size_of::>() == 4); + assert!(core::mem::size_of::() == 8); + assert!(core::mem::size_of::() == 16); + assert!(core::mem::size_of::() == 6); + assert!(core::mem::size_of::() == 6); + assert!(core::mem::size_of::() == 6); +}; + #[derive(Clone, Copy, PartialEq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -132,6 +463,25 @@ pub enum CmpOp { GeU, } +impl CmpOp { + /// Returns the comparison that is true exactly when `self` is false. + #[inline] + pub const fn inverse(self) -> Self { + match self { + Self::Eq => Self::Ne, + Self::Ne => Self::Eq, + Self::LtS => Self::GeS, + Self::LtU => Self::GeU, + Self::GtS => Self::LeS, + Self::GtU => Self::LeU, + Self::LeS => Self::GtS, + Self::LeU => Self::GtU, + Self::GeS => Self::LtS, + Self::GeU => Self::LtU, + } + } +} + #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -156,6 +506,18 @@ pub enum BinOp { FCopysign, } +impl BinOp { + /// Returns the update delta for `local OP immediate`, when it is a simple increment. + #[inline] + pub const fn inc_delta(self, immediate: i32) -> Option { + match self { + Self::IAdd => Some(immediate), + Self::ISub => Some(immediate.wrapping_neg()), + _ => None, + } + } +} + #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -181,69 +543,47 @@ pub enum BinOp128 { #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub enum Instruction { LocalCopy32(LocalAddr, LocalAddr), LocalCopy64(LocalAddr, LocalAddr), LocalCopy128(LocalAddr, LocalAddr), - AddConst32(i32), AddConst64(i64), - IncLocal32(LocalAddr, i32), IncLocal64(LocalAddr, i64), + AddConst32(i32), AddConst64(OperandIdx), + IncLocal32(I32LocalArg), IncLocal64(PackedOp), // The 32/64 suffix describes the operand width. Future compare-style ops may still yield i32 results. BinOpLocalLocal32(BinOp, LocalAddr, LocalAddr), BinOpLocalLocal64(BinOp, LocalAddr, LocalAddr), BinOpLocalLocal128(BinOp128, LocalAddr, LocalAddr), CmpLocalLocal32(CmpOp, LocalAddr, LocalAddr), CmpLocalLocal64(CmpOp, LocalAddr, LocalAddr), - BinOpLocalLocalSet32(BinOp, LocalAddr, LocalAddr, LocalAddr), - BinOpLocalLocalSet64(BinOp, LocalAddr, LocalAddr, LocalAddr), - BinOpLocalLocalSet128(BinOp128, LocalAddr, LocalAddr, LocalAddr), - BinOpLocalLocalTee32(BinOp, LocalAddr, LocalAddr, LocalAddr), - BinOpLocalLocalTee64(BinOp, LocalAddr, LocalAddr, LocalAddr), - BinOpLocalLocalTee128(BinOp128, LocalAddr, LocalAddr, LocalAddr), - BinOpLocalConst32(BinOp, LocalAddr, i32), BinOpLocalConst64(BinOp, LocalAddr, i64), - BinOpGlobalConst32(BinOp, GlobalAddr, i32), BinOpGlobalConst64(BinOp, GlobalAddr, i64), - BinOpGlobalConst128(BinOp128, GlobalAddr, ConstIdx), - BinOpLocalConst128(BinOp128, LocalAddr, ConstIdx), - BinOpLocalConstSet32(BinOp, LocalAddr, i32, LocalAddr), - BinOpLocalConstSet64(BinOp, LocalAddr, i64, LocalAddr), - BinOpLocalConstSet128(BinOp128, LocalAddr, ConstIdx, LocalAddr), - BinOpLocalConstTee32(BinOp, LocalAddr, i32, LocalAddr), - BinOpLocalConstTee64(BinOp, LocalAddr, i64, LocalAddr), - BinOpLocalConstTee128(BinOp128, LocalAddr, ConstIdx, LocalAddr), + AddLocalLocalSet32(LocalTripleArg), AddLocalLocalTee32(LocalTripleArg), + BinOpLocalLocalSet32(PackedOp), BinOpLocalLocalSet64(PackedOp), BinOpLocalLocalSet128(PackedOp), + BinOpLocalLocalTee32(PackedOp), BinOpLocalLocalTee64(PackedOp), BinOpLocalLocalTee128(PackedOp), + AddLocalConst32(I32LocalArg), SubLocalConst32(I32LocalArg), MulLocalConst32(I32LocalArg), + BinOpLocalConst32(PackedOp), BinOpLocalConst64(PackedOp), + BinOpGlobalConst32(PackedOp), BinOpGlobalConst64(PackedOp), + BinOpGlobalConst128(PackedOp), BinOpLocalConst128(PackedOp), + BinOpLocalConstSet32(PackedOp), BinOpLocalConstSet64(PackedOp), BinOpLocalConstSet128(PackedOp), + BinOpLocalConstTee32(PackedOp), BinOpLocalConstTee64(PackedOp), BinOpLocalConstTee128(PackedOp), BinOpStackLocal32(BinOp, LocalAddr), BinOpStackLocalSet32(BinOp, LocalAddr, LocalAddr), BinOpStackLocalTee32(BinOp, LocalAddr, LocalAddr), + BinOpStackLocal128(BinOp128, LocalAddr), BinOpStackGlobal32(BinOp, u32), BinOpStackGlobal64(BinOp, u32), - SetLocalConst32(LocalAddr, i32), SetLocalConst64(LocalAddr, i64), SetLocalConst128(LocalAddr, ConstIdx), - IncMemoryLocal32(MemoryArg, u8), - IncMemoryLocal64(MemoryArg, u8), - StoreLocalLocal32(MemoryArg, u8, u8), - StoreLocalLocal64(MemoryArg, u8, u8), - StoreLocalLocal128(MemoryArg, u8, u8), - LoadLocal32(MemoryArg, u8), - LoadLocal64(MemoryArg, u8), - LoadLocal8S32(MemoryArg, u8), - LoadLocal8U32(MemoryArg, u8), - LoadLocal16S32(MemoryArg, u8), - LoadLocal16U32(MemoryArg, u8), - LoadLocalTee32(MemoryArg, u8, u8), - LoadLocalSet32(MemoryArg, u8, u8), - LoadLocalTee8S32(MemoryArg, u8, u8), - LoadLocalTee8U32(MemoryArg, u8, u8), - LoadLocalTee16S32(MemoryArg, u8, u8), - LoadLocalTee16U32(MemoryArg, u8, u8), - LoadLocalSet8S32(MemoryArg, u8, u8), - LoadLocalSet8U32(MemoryArg, u8, u8), - LoadLocalSet16S32(MemoryArg, u8, u8), - LoadLocalSet16U32(MemoryArg, u8, u8), - LoadLocalTee128(MemoryArg, u8, u8), - LoadLocalSet128(MemoryArg, u8, u8), - AndConstTee32(i32, LocalAddr), - SubConstTee32(i32, LocalAddr), - AndConstTee64(i64, LocalAddr), - SubConstTee64(i64, LocalAddr), - MulAccLocal32(LocalAddr), - MulAccLocal64(LocalAddr), - FMulAccLocal32(LocalAddr), - FMulAccLocal64(LocalAddr), + SetLocalConst32(I32LocalArg), SetLocalConst64(PackedOp), SetLocalConst128(PackedOp), + IncMemoryLocal32(MemoryLocalArg), IncMemoryLocal64(MemoryLocalArg), + StoreLocalLocal32(MemoryLocalArg), StoreLocalLocal64(MemoryLocalArg), StoreLocalLocal128(MemoryLocalArg), + LoadLocal32(MemoryLocalArg), LoadLocal64(MemoryLocalArg), + LoadLocal8S32(MemoryLocalArg), LoadLocal8U32(MemoryLocalArg), + LoadLocal16S32(MemoryLocalArg), LoadLocal16U32(MemoryLocalArg), + LoadLocalTee32(MemoryLocalArg), LoadLocalSet32(MemoryLocalArg), + LoadLocalTee8S32(MemoryLocalArg), LoadLocalTee8U32(MemoryLocalArg), + LoadLocalTee16S32(MemoryLocalArg), LoadLocalTee16U32(MemoryLocalArg), + LoadLocalSet8S32(MemoryLocalArg), LoadLocalSet8U32(MemoryLocalArg), + LoadLocalSet16S32(MemoryLocalArg), LoadLocalSet16U32(MemoryLocalArg), + LoadLocalTee128(MemoryLocalArg), LoadLocalSet128(MemoryLocalArg), + AndConstTee32(I32LocalArg), SubConstTee32(I32LocalArg), + AndConstTee64(PackedOp), SubConstTee64(PackedOp), + MulAccLocal32(LocalAddr), MulAccLocal64(LocalAddr), + FMulAccLocal32(LocalAddr), FMulAccLocal64(LocalAddr), I32Add3, I64Add3, - FMaStoreF32(MemoryArg), - FMaStoreF64(MemoryArg), + FMaStoreF32(CompactMemoryArg), + FMaStoreF64(CompactMemoryArg), // > Control Instructions (jump-oriented, lowered from structured control during parsing) // See @@ -255,28 +595,16 @@ pub enum Instruction { JumpIfNonZero64(u32), JumpIfRefNull(u32), JumpIfRefNonNull(u32), - JumpIfLocalZero32 { target_ip: u32, local: LocalAddr }, - JumpIfLocalNonZero32 { target_ip: u32, local: LocalAddr }, - JumpIfLocalZero64 { target_ip: u32, local: LocalAddr }, - JumpIfLocalNonZero64 { target_ip: u32, local: LocalAddr }, - JumpCmpStackConst32 { target_ip: u32, imm: i32, op: CmpOp }, - JumpCmpStackConst64 { target_ip: u32, imm: i64, op: CmpOp }, - JumpCmpStackLocal32 { target_ip: u32, local: LocalAddr, op: CmpOp }, - JumpCmpStackLocal64 { target_ip: u32, local: LocalAddr, op: CmpOp }, - BinOpLocalConstJump32 { target_ip: u32, local: LocalAddr, imm: i32, op: BinOp, on_zero: bool }, - BinOpLocalConstJumpCmpLocal32 { target_ip: u32, local: LocalAddr, imm: i32, binop: BinOp, right: LocalAddr, cmp: CmpOp }, - BinOpStackConstTeeLocalJump32 { target_ip: u32, local: LocalAddr, imm: i32, op: BinOp, on_zero: bool }, - BinOpGlobalConstJump32 { target_ip: u32, global: GlobalAddr, imm: i32, op: BinOp, on_zero: bool }, - IncLocalJump32 { target_ip: u32, local: LocalAddr, delta: i32, on_zero: bool }, - IncStackTeeLocalJump32 { target_ip: u32, local: LocalAddr, delta: i32, on_zero: bool }, - IncGlobalJump32 { target_ip: u32, global: GlobalAddr, delta: i32, on_zero: bool }, - IncLocalJumpCmpLocal32 { target_ip: u32, local: LocalAddr, delta: i32, right: LocalAddr, op: CmpOp }, - JumpCmpLocalConst32 { target_ip: u32, local: LocalAddr, imm: i32, op: CmpOp }, - JumpCmpLocalConst64 { target_ip: u32, local: LocalAddr, imm: i32, op: CmpOp }, - JumpCmpLocalLocal32 { target_ip: u32, left: LocalAddr, right: LocalAddr, op: CmpOp }, - JumpCmpLocalLocal64 { target_ip: u32, left: LocalAddr, right: LocalAddr, op: CmpOp }, - DropKeep(DropKeep), - BranchTable(u32, u32, u32), // (default_landing_pad_ip, branch_table_start, target_count) + JumpIfLocalZero32(TargetLocalArg), JumpIfLocalNonZero32(TargetLocalArg), + JumpIfLocalZero64(TargetLocalArg), JumpIfLocalNonZero64(TargetLocalArg), + JumpCmpStackConst32(PackedOp), JumpCmpStackConst64(PackedOp), + JumpCmpStackLocal32(PackedOp), JumpCmpStackLocal64(PackedOp), + BinOpLocalConstJump32(PackedOp), BinOpLocalConstJumpCmpLocal32(PackedOp<(BinOp, CmpOp), LocalUpdateCmp>), + BinOpStackConstTeeLocalJump32(PackedOp), BinOpGlobalConstJump32(PackedOp), + IncLocalJump32(OperandIdx), IncStackTeeLocalJump32(OperandIdx), IncGlobalJump32(OperandIdx), + IncLocalJumpCmpLocal32(PackedOp), JumpCmpLocalConst32(PackedOp), JumpCmpLocalConst64(PackedOp), + JumpCmpLocalLocal32(PackedOp), JumpCmpLocalLocal64(PackedOp), + DropKeep32 { base: u16, keep: u16 }, DropKeep64 { base: u16, keep: u16 }, DropKeep128 { base: u16, keep: u16 }, BranchTable(OperandIdx), Return, ReturnVoid, Return32, @@ -284,11 +612,11 @@ pub enum Instruction { Return128, Call(FuncAddr), CallSelf, - CallIndirect(TypeAddr, TableAddr), + CallIndirect(OperandIdx), CallRef(TypeAddr), ReturnCall(FuncAddr), ReturnCallSelf, - ReturnCallIndirect(TypeAddr, TableAddr), + ReturnCallIndirect(OperandIdx), ReturnCallRef(TypeAddr), Throw(TagAddr), ThrowRef, @@ -307,35 +635,18 @@ pub enum Instruction { GlobalGet128(GlobalAddr), GlobalSet128(GlobalAddr), GlobalTee128(GlobalAddr), LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr), // > Memory Instructions - I32Load(MemoryArg), - I64Load(MemoryArg), - F32Load(MemoryArg), - F64Load(MemoryArg), - I32Load8S(MemoryArg), - I32Load8U(MemoryArg), - I32Load16S(MemoryArg), - I32Load16U(MemoryArg), - I64Load8S(MemoryArg), - I64Load8U(MemoryArg), - I64Load16S(MemoryArg), - I64Load16U(MemoryArg), - I64Load32S(MemoryArg), - I64Load32U(MemoryArg), - I32Store(MemoryArg), - I64Store(MemoryArg), - F32Store(MemoryArg), - F64Store(MemoryArg), - I32Store8(MemoryArg), - I32Store16(MemoryArg), - I64Store8(MemoryArg), - I64Store16(MemoryArg), - I64Store32(MemoryArg), + I32Load(OperandIdx), I64Load(OperandIdx), F32Load(OperandIdx), F64Load(OperandIdx), + I32Load8S(OperandIdx), I32Load8U(OperandIdx), I32Load16S(OperandIdx), I32Load16U(OperandIdx), + I64Load8S(OperandIdx), I64Load8U(OperandIdx), I64Load16S(OperandIdx), I64Load16U(OperandIdx), I64Load32S(OperandIdx), I64Load32U(OperandIdx), + I32Store(OperandIdx), I64Store(OperandIdx), F32Store(OperandIdx), F64Store(OperandIdx), + I32Store8(OperandIdx), I32Store16(OperandIdx), I64Store8(OperandIdx), I64Store16(OperandIdx), I64Store32(OperandIdx), MemorySize(MemAddr), MemoryGrow(MemAddr), // > Constants Const32(i32), - Const64(i64), + Const64Imm(i32), + Const64(OperandIdx), // > Reference Types RefNull(RefType), @@ -348,29 +659,24 @@ pub enum Instruction { RefEq, RefTest(RefType), RefCast(RefType), - BrOnCast(u32, RefType, bool), + BrOnCast(OperandIdx), + BrOnCastFail(OperandIdx), // > GC Objects StructNew(TypeAddr), StructNewDefault(TypeAddr), - StructGet(TypeAddr, u32), - StructGetS(TypeAddr, u32), - StructGetU(TypeAddr, u32), - StructSet(TypeAddr, u32), + StructGet(OperandIdx), StructGetS(OperandIdx), StructGetU(OperandIdx), StructSet(OperandIdx), ArrayNew(TypeAddr), ArrayNewDefault(TypeAddr), - ArrayNewFixed(TypeAddr, u32), - ArrayNewData(TypeAddr, DataAddr), - ArrayNewElem(TypeAddr, ElemAddr), + ArrayNewFixed(OperandIdx), + ArrayNewData(OperandIdx), ArrayNewElem(OperandIdx), ArrayGet(TypeAddr), ArrayGetS(TypeAddr), ArrayGetU(TypeAddr), ArraySet(TypeAddr), ArrayLen, ArrayFill(TypeAddr), - ArrayCopy(TypeAddr, TypeAddr), - ArrayInitData(TypeAddr, DataAddr), - ArrayInitElem(TypeAddr, ElemAddr), + ArrayCopy(OperandIdx), ArrayInitData(OperandIdx), ArrayInitElem(OperandIdx), // > Numeric Instructions // See @@ -400,19 +706,18 @@ pub enum Instruction { I64TruncSatF32S, I64TruncSatF32U, I64TruncSatF64S, I64TruncSatF64U, // > Table Instructions - TableInit(ElemAddr, TableAddr), + TableInit(OperandIdx), TableGet(TableAddr), TableSet(TableAddr), - TableCopy { dst_table: TableAddr, src_table: TableAddr }, + TableCopy(OperandIdx), TableGrow(TableAddr), TableSize(TableAddr), TableFill(TableAddr), // > Bulk Memory Instructions - MemoryInit(DataAddr, MemAddr), - MemoryCopy { dst_mem: MemAddr, src_mem: MemAddr }, + MemoryInit(OperandIdx), MemoryCopy(OperandIdx), MemoryFill(MemAddr), - MemoryFillImm(MemAddr, u8, i32), + MemoryFillConst(OperandIdx), DataDrop(DataAddr), ElemDrop(ElemAddr), @@ -420,20 +725,18 @@ pub enum Instruction { I64Add128, I64Sub128, I64MulWideS, I64MulWideU, // > SIMD - V128Load(MemoryArg), - V128Load8x8S(MemoryArg), V128Load8x8U(MemoryArg), - V128Load16x4S(MemoryArg), V128Load16x4U(MemoryArg), - V128Load32x2S(MemoryArg), V128Load32x2U(MemoryArg), + V128Load(OperandIdx), V128Load8x8S(OperandIdx), V128Load8x8U(OperandIdx), + V128Load16x4S(OperandIdx), V128Load16x4U(OperandIdx), V128Load32x2S(OperandIdx), V128Load32x2U(OperandIdx), - V128Load8Splat(MemoryArg), V128Load16Splat(MemoryArg), V128Load32Splat(MemoryArg), V128Load64Splat(MemoryArg), - V128Load8Lane(MemoryArg, u8), V128Load16Lane(MemoryArg, u8), V128Load32Lane(MemoryArg, u8), V128Load64Lane(MemoryArg, u8), + V128Load8Splat(OperandIdx), V128Load16Splat(OperandIdx), V128Load32Splat(OperandIdx), V128Load64Splat(OperandIdx), + V128Load8Lane(MemoryLaneArg), V128Load16Lane(MemoryLaneArg), V128Load32Lane(MemoryLaneArg), V128Load64Lane(MemoryLaneArg), - V128Load32Zero(MemoryArg), V128Load64Zero(MemoryArg), + V128Load32Zero(OperandIdx), V128Load64Zero(OperandIdx), - V128Store(MemoryArg), V128Store8Lane(MemoryArg, u8), V128Store16Lane(MemoryArg, u8), V128Store32Lane(MemoryArg, u8), V128Store64Lane(MemoryArg, u8), + V128Store(OperandIdx), V128Store8Lane(MemoryLaneArg), V128Store16Lane(MemoryLaneArg), V128Store32Lane(MemoryLaneArg), V128Store64Lane(MemoryLaneArg), - I8x16Shuffle(ConstIdx), - Const128(ConstIdx), + I8x16Shuffle(OperandIdx), + Const128Imm(u32), Const128(OperandIdx), I8x16ExtractLaneS(u8), I8x16ExtractLaneU(u8), I8x16ReplaceLane(u8), I16x8ExtractLaneS(u8), I16x8ExtractLaneU(u8), I16x8ReplaceLane(u8), @@ -485,10 +788,8 @@ pub enum Instruction { I32x4RelaxedTruncF64x2SZero, I32x4RelaxedTruncF64x2UZero, F32x4RelaxedMadd, F32x4RelaxedNmadd, F64x2RelaxedMadd, F64x2RelaxedNmadd, - I8x16RelaxedLaneselect, - I16x8RelaxedLaneselect, - I32x4RelaxedLaneselect, - I64x2RelaxedLaneselect, + I8x16RelaxedLaneselect, I16x8RelaxedLaneselect, + I32x4RelaxedLaneselect, I64x2RelaxedLaneselect, F32x4RelaxedMin, F32x4RelaxedMax, F64x2RelaxedMin, F64x2RelaxedMax, I16x8RelaxedQ15mulrS, @@ -496,88 +797,144 @@ pub enum Instruction { I32x4RelaxedDotI8x16I7x16AddS, } -const _: () = assert!(core::mem::size_of::() <= 16); +const _: () = assert!(core::mem::size_of::() == 8); impl Instruction { + /// Returns the largest module-local memory index used by this instruction. #[inline] - pub const fn memory_addr(&self) -> Option { - match self { - Self::IncMemoryLocal32(arg, ..) - | Self::IncMemoryLocal64(arg, ..) - | Self::StoreLocalLocal32(arg, ..) - | Self::StoreLocalLocal64(arg, ..) - | Self::StoreLocalLocal128(arg, ..) - | Self::LoadLocal32(arg, ..) - | Self::LoadLocal64(arg, ..) - | Self::LoadLocal8S32(arg, ..) - | Self::LoadLocal8U32(arg, ..) - | Self::LoadLocal16S32(arg, ..) - | Self::LoadLocal16U32(arg, ..) - | Self::LoadLocalTee32(arg, ..) - | Self::LoadLocalSet32(arg, ..) - | Self::LoadLocalTee8S32(arg, ..) - | Self::LoadLocalTee8U32(arg, ..) - | Self::LoadLocalTee16S32(arg, ..) - | Self::LoadLocalTee16U32(arg, ..) - | Self::LoadLocalSet8S32(arg, ..) - | Self::LoadLocalSet8U32(arg, ..) - | Self::LoadLocalSet16S32(arg, ..) - | Self::LoadLocalSet16U32(arg, ..) - | Self::LoadLocalTee128(arg, ..) - | Self::LoadLocalSet128(arg, ..) - | Self::I32Load(arg) - | Self::I64Load(arg) - | Self::F32Load(arg) - | Self::F64Load(arg) - | Self::I32Load8S(arg) - | Self::I32Load8U(arg) - | Self::I32Load16S(arg) - | Self::I32Load16U(arg) - | Self::I64Load8S(arg) - | Self::I64Load8U(arg) - | Self::I64Load16S(arg) - | Self::I64Load16U(arg) - | Self::I64Load32S(arg) - | Self::I64Load32U(arg) - | Self::I32Store(arg) - | Self::I64Store(arg) - | Self::F32Store(arg) - | Self::F64Store(arg) - | Self::FMaStoreF32(arg) - | Self::FMaStoreF64(arg) - | Self::I32Store8(arg) - | Self::I32Store16(arg) - | Self::I64Store8(arg) - | Self::I64Store16(arg) - | Self::I64Store32(arg) - | Self::V128Load(arg) - | Self::V128Load8x8S(arg) - | Self::V128Load8x8U(arg) - | Self::V128Load16x4S(arg) - | Self::V128Load16x4U(arg) - | Self::V128Load32x2S(arg) - | Self::V128Load32x2U(arg) - | Self::V128Load8Splat(arg) - | Self::V128Load16Splat(arg) - | Self::V128Load32Splat(arg) - | Self::V128Load64Splat(arg) - | Self::V128Load8Lane(arg, ..) - | Self::V128Load16Lane(arg, ..) - | Self::V128Load32Lane(arg, ..) - | Self::V128Load64Lane(arg, ..) - | Self::V128Load32Zero(arg) - | Self::V128Load64Zero(arg) - | Self::V128Store(arg) - | Self::V128Store8Lane(arg, ..) - | Self::V128Store16Lane(arg, ..) - | Self::V128Store32Lane(arg, ..) - | Self::V128Store64Lane(arg, ..) => Some(arg.mem_addr()), - Self::MemorySize(mem) | Self::MemoryGrow(mem) | Self::MemoryFill(mem) | Self::MemoryFillImm(mem, ..) => { - Some(*mem) + pub fn memory_addr(&self, data: &super::WasmFunctionData) -> Option { + use Instruction::*; + match *self { + IncMemoryLocal32(arg) + | IncMemoryLocal64(arg) + | StoreLocalLocal32(arg) + | StoreLocalLocal64(arg) + | StoreLocalLocal128(arg) + | LoadLocal32(arg) + | LoadLocal64(arg) + | LoadLocal8S32(arg) + | LoadLocal8U32(arg) + | LoadLocal16S32(arg) + | LoadLocal16U32(arg) + | LoadLocalTee32(arg) + | LoadLocalSet32(arg) + | LoadLocalTee8S32(arg) + | LoadLocalTee8U32(arg) + | LoadLocalTee16S32(arg) + | LoadLocalTee16U32(arg) + | LoadLocalSet8S32(arg) + | LoadLocalSet8U32(arg) + | LoadLocalSet16S32(arg) + | LoadLocalSet16U32(arg) + | LoadLocalTee128(arg) + | LoadLocalSet128(arg) => Some(arg.memory_arg_idx.get(data).mem_addr()), + I32Load(index) + | I64Load(index) + | F32Load(index) + | F64Load(index) + | I32Load8S(index) + | I32Load8U(index) + | I32Load16S(index) + | I32Load16U(index) + | I64Load8S(index) + | I64Load8U(index) + | I64Load16S(index) + | I64Load16U(index) + | I64Load32S(index) + | I64Load32U(index) + | I32Store(index) + | I64Store(index) + | F32Store(index) + | F64Store(index) + | I32Store8(index) + | I32Store16(index) + | I64Store8(index) + | I64Store16(index) + | I64Store32(index) + | V128Load(index) + | V128Load8x8S(index) + | V128Load8x8U(index) + | V128Load16x4S(index) + | V128Load16x4U(index) + | V128Load32x2S(index) + | V128Load32x2U(index) + | V128Load8Splat(index) + | V128Load16Splat(index) + | V128Load32Splat(index) + | V128Load64Splat(index) + | V128Load32Zero(index) + | V128Load64Zero(index) + | V128Store(index) => Some(index.get(data).mem_addr()), + V128Load8Lane(arg) | V128Load16Lane(arg) | V128Load32Lane(arg) | V128Load64Lane(arg) + | V128Store8Lane(arg) | V128Store16Lane(arg) | V128Store32Lane(arg) | V128Store64Lane(arg) => { + Some(arg.memory_arg_idx.get(data).mem_addr()) + } + FMaStoreF32(arg) | FMaStoreF64(arg) => Some(arg.mem_addr()), + MemorySize(memory) | MemoryGrow(memory) | MemoryFill(memory) => Some(memory), + MemoryFillConst(index) => Some(index.get(data).memory), + MemoryInit(index) => Some(index.get(data).second), + MemoryCopy(index) => { + let value = index.get(data); + Some(value.first.max(value.second)) } - Self::MemoryInit(_, mem) => Some(*mem), - Self::MemoryCopy { dst_mem, src_mem } => Some(if *dst_mem >= *src_mem { *dst_mem } else { *src_mem }), _ => None, } } } + +#[cfg(test)] +mod tests { + use alloc::vec; + + use super::*; + + #[test] + fn compact_instruction_layout_is_exact() { + assert_eq!(core::mem::size_of::(), 8); + assert_eq!(core::mem::size_of::(), 6); + assert_eq!(core::mem::size_of::(), 6); + assert_eq!(core::mem::size_of::(), 6); + } + + #[test] + fn operand_lanes_round_trip_max_values() { + let memory = MemoryArg::new(u64::MAX, u32::MAX); + assert_eq!(MemoryArg::decode(memory.encode()), memory); + + let value = Operand128::default() + .with_u8::<0>(u8::MAX) + .with_u16::<1>(u16::MAX) + .with_u32::<3>(u32::MAX) + .with_u64::<7>(u64::MAX); + assert_eq!( + (value.u8::<0>(), value.u16::<1>(), value.u32::<3>(), value.u64::<7>()), + (u8::MAX, u16::MAX, u32::MAX, u64::MAX) + ); + + let bytes = [u8::MAX; 16]; + assert_eq!(Operand128::from_le_bytes(bytes).to_le_bytes(), bytes); + } + + #[test] + fn v128_operand_views_round_trip_max_bytes() { + let value = OperandIdx::::new(0); + let local = OperandIdx::::new(0); + let global = OperandIdx::::new(1); + let set = OperandIdx::::new(2); + let data = super::super::WasmFunctionData { + operands128: vec![V128Operand { value: [u8::MAX; 16] }.encode()].into_boxed_slice(), + operands64: vec![ + LocalV128 { local: u16::MAX, value }.encode(), + GlobalV128 { global: u32::MAX, value }.encode(), + LocalConstSetV128 { local: u16::MAX, dst: u16::MAX, value }.encode(), + ] + .into_boxed_slice(), + ..Default::default() + }; + + assert_eq!(value.get(&data).value, [u8::MAX; 16]); + assert_eq!(local.get(&data), LocalV128 { local: u16::MAX, value }); + assert_eq!(global.get(&data), GlobalV128 { global: u32::MAX, value }); + assert_eq!(set.get(&data), LocalConstSetV128 { local: u16::MAX, dst: u16::MAX, value }); + } +} diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index 9a7071c..bd92753 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -22,10 +22,12 @@ const fn max_page_count(arch: MemoryArch, page_size: u64) -> u64 { } mod instructions; +mod operands; mod reference; mod types; mod value; pub use instructions::*; +pub use operands::*; pub use reference::*; pub use types::*; pub use value::*; @@ -472,19 +474,12 @@ pub struct WasmFunction { #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub struct WasmFunctionData { - pub v128_constants: Box<[[u8; 16]]>, + pub operands64: Box<[Operand64]>, + pub operands128: Box<[Operand128]>, pub branch_table_targets: Box<[u32]>, pub exception_handlers: Box<[ExceptionHandler]>, } -impl WasmFunctionData { - /// Panics if `idx` is out of bounds. - #[inline(always)] - pub fn v128_const(&self, idx: ConstIdx) -> [u8; 16] { - *self.v128_constants.get(idx as usize).unwrap_or_else(|| unreachable!("invalid v128 constant index: {idx}")) - } -} - /// A WebAssembly Module Export #[derive(Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] diff --git a/crates/types/src/operands.rs b/crates/types/src/operands.rs new file mode 100644 index 0000000..3cc311c --- /dev/null +++ b/crates/types/src/operands.rs @@ -0,0 +1,177 @@ +use core::marker::PhantomData; + +use crate::WasmFunctionData; + +/// An index into the operand lane used by `T`. +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "archive", serde(transparent))] +#[repr(transparent)] +pub struct OperandIdx { + index: u32, + #[cfg_attr(feature = "archive", serde(skip))] + marker: PhantomData, +} + +impl OperandIdx { + #[inline] + #[doc(hidden)] + pub const fn new(index: u32) -> Self { + Self { index, marker: PhantomData } + } + + /// Returns the underlying lane index. + #[inline] + pub const fn index(self) -> u32 { + self.index + } +} + +impl OperandIdx { + /// Returns the typed operand at this index. + /// + /// Panics if the index is outside its statically selected operand lane. + #[inline(always)] + pub fn get(self, data: &WasmFunctionData) -> T { + T::decode(T::Raw::get(data, self.index)) + } +} + +impl Copy for OperandIdx {} + +impl Clone for OperandIdx { + fn clone(&self) -> Self { + *self + } +} + +impl PartialEq for OperandIdx { + fn eq(&self, other: &Self) -> bool { + self.index == other.index + } +} + +impl Eq for OperandIdx {} + +#[cfg(feature = "debug")] +impl core::fmt::Debug for OperandIdx { + fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + self.index.fmt(formatter) + } +} + +pub(crate) mod sealed { + pub trait Sealed {} +} + +/// A typed view stored in one of the per-function operand lanes. +pub trait OperandType: sealed::Sealed + Copy { + #[doc(hidden)] + type Raw: RawOperand; + + #[doc(hidden)] + fn decode(raw: Self::Raw) -> Self; + #[doc(hidden)] + fn encode(self) -> Self::Raw; +} + +#[doc(hidden)] +pub trait RawOperand: sealed::Sealed + Copy { + fn get(data: &WasmFunctionData, index: u32) -> Self; +} + +macro_rules! define_operand { + ($name:ident, $len:literal, $lane:ident) => { + #[doc = concat!("Raw fields stored in a per-function ", $len, "-byte operand lane.")] + #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default)] + #[cfg_attr(feature = "debug", derive(Debug))] + #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] + #[repr(transparent)] + pub struct $name([u8; $len]); + + impl sealed::Sealed for $name {} + + impl RawOperand for $name { + #[inline(always)] + fn get(data: &WasmFunctionData, index: u32) -> Self { + *data.$lane.get(index as usize).unwrap_or_else(|| unreachable!("invalid operand index")) + } + } + + impl $name { + /// Returns the byte at `OFFSET`. + #[inline] + pub fn u8(self) -> u8 { + const { assert!(OFFSET < $len) }; + self.0[OFFSET] + } + + /// Returns the little-endian `u16` at `OFFSET`. + #[inline] + pub fn u16(self) -> u16 { + const { assert!(OFFSET + 2 <= $len) }; + u16::from_le_bytes(self.0[OFFSET..OFFSET + 2].try_into().unwrap_or_else(|_| unreachable!())) + } + + /// Returns the little-endian `u32` at `OFFSET`. + #[inline] + pub fn u32(self) -> u32 { + const { assert!(OFFSET + 4 <= $len) }; + u32::from_le_bytes(self.0[OFFSET..OFFSET + 4].try_into().unwrap_or_else(|_| unreachable!())) + } + + /// Returns the little-endian `u64` at `OFFSET`. + #[inline] + pub fn u64(self) -> u64 { + const { assert!(OFFSET + 8 <= $len) }; + u64::from_le_bytes(self.0[OFFSET..OFFSET + 8].try_into().unwrap_or_else(|_| unreachable!())) + } + + /// Builds an operand from its raw little-endian bytes. + #[inline] + pub fn from_le_bytes(value: [u8; $len]) -> Self { + Self(value) + } + + /// Returns the raw little-endian bytes. + #[inline] + pub fn to_le_bytes(self) -> [u8; $len] { + self.0 + } + + /// Writes `value` at `OFFSET` and returns the updated operand. + #[inline] + pub fn with_u8(mut self, value: u8) -> Self { + const { assert!(OFFSET < $len) }; + self.0[OFFSET] = value; + self + } + + /// Writes `value` at `OFFSET` and returns the updated operand. + #[inline] + pub fn with_u16(mut self, value: u16) -> Self { + const { assert!(OFFSET + 2 <= $len) }; + self.0[OFFSET..OFFSET + 2].copy_from_slice(&value.to_le_bytes()); + self + } + + /// Writes `value` at `OFFSET` and returns the updated operand. + #[inline] + pub fn with_u32(mut self, value: u32) -> Self { + const { assert!(OFFSET + 4 <= $len) }; + self.0[OFFSET..OFFSET + 4].copy_from_slice(&value.to_le_bytes()); + self + } + + /// Writes `value` at `OFFSET` and returns the updated operand. + #[inline] + pub fn with_u64(mut self, value: u64) -> Self { + const { assert!(OFFSET + 8 <= $len) }; + self.0[OFFSET..OFFSET + 8].copy_from_slice(&value.to_le_bytes()); + self + } + } + }; +} + +define_operand!(Operand64, 8, operands64); +define_operand!(Operand128, 16, operands128); diff --git a/crates/types/src/reference.rs b/crates/types/src/reference.rs index 9ed5df1..ed59ae5 100644 --- a/crates/types/src/reference.rs +++ b/crates/types/src/reference.rs @@ -67,6 +67,18 @@ impl RefType { pub const EXTERNREF: Self = Self::new_abstract(true, AbstractHeapType::Extern); pub const EXNREF: Self = Self::new_abstract(true, AbstractHeapType::Exn); + #[inline] + #[doc(hidden)] + pub const fn to_bits(self) -> u32 { + self.0 + } + + #[inline] + pub(crate) const fn from_bits(bits: u32) -> Option { + let ty = Self(bits); + if ty.is_concrete() || ty.abstract_heap_type().is_some() { Some(ty) } else { None } + } + #[inline] pub const fn new_abstract(nullable: bool, heap_type: AbstractHeapType) -> Self { Self((nullable as u32) << 31 | heap_type as u32) -- cgit v1.3.1 From 951c8070169e8bd970940029156f305e741aecdb Mon Sep 17 00:00:00 2001 From: Henry Gressmann Date: Sun, 23 Aug 2026 13:40:38 +0200 Subject: chore: remove LinearMemory trait (#53) Signed-off-by: Henry --- ARCHITECTURE.md | 23 +- CHANGELOG.md | 10 +- Cargo.lock | 28 +- Cargo.toml | 12 +- README.md | 2 +- benches/memory_backends.rs | 151 ----------- crates/cli/src/engine_flags.rs | 36 +-- crates/parser/src/conversion.rs | 19 +- crates/parser/src/error.rs | 2 +- crates/parser/src/lib.rs | 39 +-- crates/parser/src/module.rs | 47 +--- crates/parser/src/parallel.rs | 31 +-- crates/parser/src/visit.rs | 2 +- crates/tinywasm/src/engine.rs | 58 ++-- crates/tinywasm/src/instance.rs | 27 +- crates/tinywasm/src/interpreter/executor.rs | 107 ++++---- crates/tinywasm/src/lib.rs | 7 +- crates/tinywasm/src/reference.rs | 50 ++-- crates/tinywasm/src/store/memory/instance.rs | 138 +++------- crates/tinywasm/src/store/memory/lazy.rs | 114 -------- crates/tinywasm/src/store/memory/mod.rs | 390 ++------------------------- crates/tinywasm/src/store/memory/paged.rs | 368 ------------------------- crates/tinywasm/src/store/memory/vec.rs | 185 +++++-------- crates/tinywasm/src/store/mod.rs | 80 +++++- crates/tinywasm/src/store/table.rs | 41 ++- crates/tinywasm/tests/internal_refs.rs | 2 +- crates/tinywasm/tests/memory.rs | 198 ++++++++++++++ crates/tinywasm/tests/memory_backends.rs | 307 --------------------- crates/types/src/instructions.rs | 83 ------ crates/types/src/lib.rs | 27 +- examples/rust/Cargo.toml | 14 +- examples/rust/build.sh | 4 +- examples/rust/src/hello.rs | 12 +- examples/rust/src/print.rs | 4 +- examples/rust/src/print.twasm | Bin 154 -> 154 bytes examples/rust/src/tinywasm_precompiled.rs | 30 --- examples/wasm-rust.rs | 24 -- 37 files changed, 663 insertions(+), 2009 deletions(-) delete mode 100644 benches/memory_backends.rs delete mode 100644 crates/tinywasm/src/store/memory/lazy.rs delete mode 100644 crates/tinywasm/src/store/memory/paged.rs create mode 100644 crates/tinywasm/tests/memory.rs delete mode 100644 crates/tinywasm/tests/memory_backends.rs delete mode 100644 examples/rust/src/tinywasm_precompiled.rs (limited to 'crates/parser/src/conversion.rs') diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 9405d38..62fa503 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -1,6 +1,6 @@ # TinyWasm Architecture -TinyWasm follows the general runtime model described in the [WebAssembly specification](https://webassembly.github.io/spec/core/exec/runtime.html). It is a stack-based interpreter with a compact internal bytecode, width-specific value stacks, and configurable linear-memory backends. +TinyWasm follows the general runtime model described in the [WebAssembly specification](https://webassembly.github.io/spec/core/exec/runtime.html). It is a stack-based interpreter with a compact internal bytecode, width-specific value stacks, and a contiguous `Vec`-backed linear memory. ## Execution Pipeline @@ -40,29 +40,20 @@ The default runtime remains safe Rust throughout rather than relying on unchecke SIMD instructions have a portable safe-Rust implementation built from fixed-size arrays and lane operations, relying on the compiler to auto-vectorize where possible. Generated code is inspected with `cargo asm`, and benchmarks determine where architecture-specific alternatives are worthwhile. WebAssembly targets use native SIMD intrinsics where available, while the optional `simd-x86` feature provides selected x86 implementations for operations where the generic code produces worse results. -## Memory Backends +## Linear Memory -Linear memory is implemented through the `LinearMemory` trait. The backend is selected with `engine::Config::with_memory_backend()`. +Linear memory is a contiguous `Vec` allocation owned by a `MemoryInstance`. The interpreter accesses it through the internal `MemoryStorage` type, a small concrete boundary that keeps the `Vec` representation out of the executor so an mmap-backed storage can be substituted later without touching load and store paths. -`LinearMemory` exposes separate fixed-width read and write methods for 8-, 16-, 32-, 64-, and 128-bit accesses. A const-generic method would not be callable through a `dyn LinearMemory` trait object, so each width is an explicit vtable entry that backends can optimize independently. +Fixed-width loads and stores use a single const-generic `read_fixed::` / `write_fixed::` pair rather than per-width vtable methods. Scalar operations reduce to an effective-address computation, a bounds check, a slice access, and a `from_le_bytes` / `to_le_bytes` conversion, with out-of-bounds construction kept on cold paths. Bulk operations such as `fill` and `copy_within` map directly to native slice methods. -This flexibility has a measurable cost: guest loads and stores cross the `dyn LinearMemory` boundary, adding an indirect call and generally preventing the backend operation from being inlined into the interpreter. The fixed-width methods keep the work behind that boundary as small and specialized as possible. +Memory growth keeps the Wasm page count and limits on `MemoryInstance`. Before memory or table backing storage is allocated or resized, the configured `ResourceLimiter` is consulted so a host can bound guest resource consumption. The limiter is shared across the stores created from one `Engine` and lives behind an `Arc`. -Available backends: - -- `VecMemory` - contiguous `Vec` backing and the default backend. -- `PagedMemory` - sparse chunk-based allocation, with untouched chunks left unallocated and growth avoiding relocation of one contiguous buffer. -- `LazyLinearMemory` - serves zero-filled reads without allocation and creates the configured backend on the first mutation or growth. -- Custom backends through `MemoryBackend::custom()`. - -`VecMemory` growth may reallocate, though operating-system allocators can often grow page-backed allocations without copying the full buffer. Applications on conventional operating systems should generally keep it unless sparse allocation or non-relocating growth is specifically needed. Bounded dynamic stacks and sparse paged memory trade some runtime overhead for a smaller initial footprint on embedded and other resource-constrained systems. +For conventional operating systems, a future mmap-backed storage could reserve virtual address space and use guard pages to move more bounds enforcement to the operating system, reducing explicit checks in linear-memory hot paths. This is the same broad approach described in [Wasmtime's linear-memory architecture](https://docs.wasmtime.dev/contributing-architecture.html#linear-memory), where virtual-memory reservations and guard regions eliminate or deduplicate explicit bounds checks. ## Future Experiments Future work may explore additional dispatch and code-generation strategies, including Rust's experimental `loop_match` state-machine work, a tail-call-based interpreter once Rust's explicit tail-call support matures, more aggressive superinstruction fusion, top-of-stack register allocation, or optional JIT compilation. -For conventional operating systems, a future `mmap`-based memory backend could reserve virtual address space and use guard pages to move more bounds enforcement to the operating system, reducing explicit checks in linear-memory hot paths. This is the same broad approach described in [Wasmtime's linear-memory architecture](https://docs.wasmtime.dev/contributing-architecture.html#linear-memory), where virtual-memory reservations and guard regions eliminate or deduplicate explicit bounds checks. - ## Important Modules - [visit.rs](./crates/parser/src/visit.rs) - function-body operator lowering @@ -71,4 +62,4 @@ For conventional operating systems, a future `mmap`-based memory backend could r - [instructions.rs](./crates/types/src/instructions.rs) - internal instruction set - [value_stack.rs](./crates/tinywasm/src/interpreter/stack/value_stack.rs) - width-specific stacks - [call_stack.rs](./crates/tinywasm/src/interpreter/stack/call_stack.rs) - call frame stack -- [memory/mod.rs](./crates/tinywasm/src/store/memory/mod.rs) - memory backend trait and implementations +- [memory/mod.rs](./crates/tinywasm/src/store/memory/mod.rs) - linear memory storage diff --git a/CHANGELOG.md b/CHANGELOG.md index 701fc84..c6c8ff7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added `ValueLane` for mapping WebAssembly value types to their physical 32-bit, 64-bit, or 128-bit storage lane. - Added a `validate` feature to `tinywasm` and `tinywasm-parser` (enabled by default) to optionally skip wasmparser validation for faster parsing of trusted modules. - Added optional parse-time operand deduplication to reduce precompiled module and `.twasm` archive size. +- Added a `ResourceLimiter` trait, configurable through `engine::Config::with_resource_limiter`, to bound guest memory and table allocation and growth. ### Changed @@ -25,14 +26,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Typed function tuples now support up to 20 parameters or results. `WasmTupleChain` is deprecated. Use untyped functions for larger signatures. - Module types now use one dense recursive type space, while function types are resolved through `Function::ty(&Store)`. - Globals are stored in separate 32-bit, 64-bit, and 128-bit value lanes, avoiding tagged value conversion during guest execution. -- `LinearMemory` mutation methods and custom memory-backend factories now return `Trap` errors so lazy backend failures can be propagated. +- Linear memory now uses a single contiguous `Vec`-backed storage with const-generic fixed-width loads and stores. +- Increased the minimum supported Rust version from 1.95 to 1.98. ### Fixed - Directly defined imports now reject handles from a different `Store`. - Tail calls to host functions now return directly to the caller frame. - Fixed Memory64 bulk-memory operations and optimized stores using the wrong value-stack lane. -- Fixed `memory.init` bounds checks, operand lowering, and local-memory allocation analysis. +- Fixed `memory.init` bounds checks and operand lowering. - Fixed Memory64 default limits and host-size handling, including 32-bit targets. ### Breaking Changes @@ -44,6 +46,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Renamed `ModuleInstanceAddr` to `ModuleInstanceId`. - Removed `HostFunction::ty` and `WasmFunction::ty`. Use `Function::ty(&Store)` for runtime function types. - Changed `TableType::element_type` and `Element::ty` from `WasmType` to `RefType`, and replaced module `table_types` with `TableDefinition { ty, init }`. +- Removed the pluggable memory backend system (`LinearMemory`, `MemoryBackend`, `VecMemory`, `PagedMemory`, `LazyLinearMemory`, and `Config::with_memory_backend`). Linear memory is always `Vec`-backed. To limit initial memory allocation and growth, configure a `ResourceLimiter` with `Config::with_resource_limiter`. +- Removed the local-memory allocation analysis (`LocalMemoryAllocation` and `ParserOptions::optimize_local_memory_allocation`). Local memories are always allocated eagerly. +- Removed `Config::with_trap_on_oom`. A `ResourceLimiter` can return a trap when rejecting a memory or table allocation or growth request. +- `Table::grow` now returns `Result>`, matching `Memory::grow`. Growth limits and allocation failures return `None`, while limiter-provided traps return an error. ## [0.10.0] - 2026-07-24 diff --git a/Cargo.lock b/Cargo.lock index 3c13501..ac0895a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -134,9 +134,9 @@ checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" [[package]] name = "cc" -version = "1.4.3" +version = "1.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "509591b7bcd67f4ef775afad7662703b4935daaa6ec0e5605cfb1090b32a2b6d" +checksum = "0ad534f4357a5264cce5019c989cf66a4f0dc4e0d1b1d15f8aacec0ff7360273" dependencies = [ "find-msvc-tools", "shlex", @@ -312,9 +312,9 @@ checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" [[package]] name = "either" -version = "1.17.0" +version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d" +checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" [[package]] name = "embedded-io" @@ -511,9 +511,9 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "log" -version = "0.4.33" +version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" [[package]] name = "memchr" @@ -962,9 +962,9 @@ dependencies = [ [[package]] name = "wasm-encoder" -version = "0.256.0" +version = "0.257.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec1492381bfd5ea51c2a99a919b676662559925cb8d7490547ec2e14c1ad3eb1" +checksum = "7d8ad9f0a39050867bda22e6486c316e2e52d20a42154d5bc433934bf738d085" dependencies = [ "leb128fmt", "wasmparser", @@ -982,9 +982,9 @@ dependencies = [ [[package]] name = "wasmparser" -version = "0.256.0" +version = "0.257.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60bd825ffedc6cba8a642924ba7ae424afbc47811cffbcb7b92031ec24e59b4c" +checksum = "d92fc335fb6d48f46bda1d8b26b69e28320c15ac3272208333833d6e217e2b4a" dependencies = [ "bitflags", "indexmap", @@ -993,9 +993,9 @@ dependencies = [ [[package]] name = "wast" -version = "256.0.0" +version = "257.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3ad42723fc9222da007f05812a3249c9a4ee7af79d497fc2a2079579ad7efe6" +checksum = "3c416ee8044cf88c5280e3d87c322b009525eb25142cf7428f0a90ea88febc3b" dependencies = [ "bumpalo", "leb128fmt", @@ -1006,9 +1006,9 @@ dependencies = [ [[package]] name = "wat" -version = "1.256.0" +version = "1.257.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37cc86c54d8011b3202e265bfebada440733ea3a788ffaf46d395f7d2fdeacfb" +checksum = "672e5495f00c5fc6c6b502205bae4708aa4dd13d969754438743afe0a8af0f1d" dependencies = [ "wast", ] diff --git a/Cargo.toml b/Cargo.toml index 7ea5181..764ae53 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ default-members = [".", "crates/parser", "crates/tinywasm", "crates/types"] [workspace.package] version = "0.11.0-pre.0" edition = "2024" -rust-version = "1.95" +rust-version = "1.98" repository = "https://github.com/explodingcamera/tinywasm" license = "MIT OR Apache-2.0" keywords = ["interpreter", "no-std", "tinywasm", "wasm", "webassembly"] @@ -31,9 +31,9 @@ pretty_env_logger = "0.5" serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0" } wasm-testsuite = { version = "0.7" } -wasmparser = { version = "0.256", default-features = false } -wast = "256" -wat = "1.256" +wasmparser = { version = "0.257", default-features = false } +wast = "257" +wat = "1.257" criterion = { version = "0.8", default-features = false, features = ["cargo_bench_support", "rayon"] } @@ -57,10 +57,6 @@ name = "tinywasm" harness = false name = "tinywasm_modes" -[[bench]] -harness = false -name = "memory_backends" - [dev-dependencies] anyhow.workspace = true criterion.workspace = true diff --git a/README.md b/README.md index 3d3bc4c..7f27ea4 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,7 @@ TinyWasm modules can be compiled to the internal `twasm` bytecode format, which With default features disabled, `tinywasm` depends only on `core`, `alloc`, and `libm`[^libm], making it usable in `no_std + alloc` environments. -Use `Engine` and `engine::Config` when you need non-default runtime settings such as fuel accounting, stack sizing, memory backend selection, the GC collection threshold, or trap-on-OOM behavior. +Use `Engine` and `engine::Config` when you need non-default runtime settings such as fuel accounting, stack sizing, or the GC collection threshold. A `ResourceLimiter` attached to the engine's config bounds guest memory and table allocation and growth and can trap rejected requests. [^libm]: [rust-lang/rust#137578](https://github.com/rust-lang/rust/issues/137578) — tracking issue for floating-point math support in `no_std`. diff --git a/benches/memory_backends.rs b/benches/memory_backends.rs deleted file mode 100644 index d7b8703..0000000 --- a/benches/memory_backends.rs +++ /dev/null @@ -1,151 +0,0 @@ -use criterion::measurement::WallTime; -use criterion::{BatchSize, BenchmarkGroup, BenchmarkId, Criterion, criterion_group, criterion_main}; -use std::hint::black_box; -use tinywasm::{LinearMemory, PagedMemory, VecMemory}; - -const PAGE_SIZE: usize = 64 * 1024; -const CHUNK_SIZE: usize = 4 * 1024; -const GROW_STEPS: usize = 32; -const BENCH_MEASUREMENT_TIME: std::time::Duration = std::time::Duration::from_secs(10); - -const MEMORY_LEN: usize = PAGE_SIZE * 4; -const CONTIGUOUS_OFFSET: usize = 1024; -const CONTIGUOUS_LEN: usize = 2048; -const CROSS_CHUNK_OFFSET: usize = CHUNK_SIZE - 512; -const CROSS_CHUNK_LEN: usize = CHUNK_SIZE * 2; - -fn bench_grow(group: &mut BenchmarkGroup<'_, WallTime>, backend: &str, make_memory: F) -where - M: LinearMemory, - F: Fn() -> M + Copy, -{ - group.bench_function(BenchmarkId::new("grow", backend), |b| { - b.iter_batched( - make_memory, - |mut memory| { - for page_count in 2..=GROW_STEPS + 1 { - memory.grow_to(page_count * PAGE_SIZE).unwrap(); - } - black_box(memory.len()) - }, - BatchSize::SmallInput, - ) - }); -} - -fn bench_write_all( - group: &mut BenchmarkGroup<'_, WallTime>, - backend: &str, - workload: &str, - mut memory: M, - offset: usize, - len: usize, -) { - let src = vec![0xA5; len]; - group.bench_function(BenchmarkId::new(format!("write_all/{workload}"), backend), |b| { - b.iter(|| { - memory.write_all(offset, black_box(&src)).unwrap(); - black_box(memory.len()) - }) - }); -} - -fn bench_read_exact( - group: &mut BenchmarkGroup<'_, WallTime>, - backend: &str, - workload: &str, - mut memory: M, - offset: usize, - len: usize, -) { - let src = vec![0x5A; len]; - memory.write_all(offset, &src).unwrap(); - - let mut dst = vec![0; len]; - group.bench_function(BenchmarkId::new(format!("read_exact/{workload}"), backend), |b| { - b.iter(|| { - memory.read_exact(offset, black_box(&mut dst)).unwrap(); - black_box(&dst); - }) - }); -} - -fn criterion_benchmark(c: &mut Criterion) { - let mut group = c.benchmark_group("memory_backends"); - group.measurement_time(BENCH_MEASUREMENT_TIME); - - bench_grow(&mut group, "vec", || VecMemory::try_new(PAGE_SIZE).expect("bench memory should be constructible")); - bench_grow(&mut group, "paged", || { - PagedMemory::try_new(PAGE_SIZE, CHUNK_SIZE).expect("bench memory should be constructible") - }); - bench_write_all( - &mut group, - "vec", - "contiguous", - VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"), - CONTIGUOUS_OFFSET, - CONTIGUOUS_LEN, - ); - bench_write_all( - &mut group, - "paged", - "contiguous", - PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"), - CONTIGUOUS_OFFSET, - CONTIGUOUS_LEN, - ); - bench_read_exact( - &mut group, - "vec", - "contiguous", - VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"), - CONTIGUOUS_OFFSET, - CONTIGUOUS_LEN, - ); - bench_read_exact( - &mut group, - "paged", - "contiguous", - PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"), - CONTIGUOUS_OFFSET, - CONTIGUOUS_LEN, - ); - - bench_write_all( - &mut group, - "vec", - "cross_chunk", - VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"), - CROSS_CHUNK_OFFSET, - CROSS_CHUNK_LEN, - ); - bench_write_all( - &mut group, - "paged", - "cross_chunk", - PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"), - CROSS_CHUNK_OFFSET, - CROSS_CHUNK_LEN, - ); - bench_read_exact( - &mut group, - "vec", - "cross_chunk", - VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"), - CROSS_CHUNK_OFFSET, - CROSS_CHUNK_LEN, - ); - bench_read_exact( - &mut group, - "paged", - "cross_chunk", - PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"), - CROSS_CHUNK_OFFSET, - CROSS_CHUNK_LEN, - ); - - group.finish(); -} - -criterion_group!(benches, criterion_benchmark); -criterion_main!(benches); diff --git a/crates/cli/src/engine_flags.rs b/crates/cli/src/engine_flags.rs index 3d90847..edc56aa 100644 --- a/crates/cli/src/engine_flags.rs +++ b/crates/cli/src/engine_flags.rs @@ -1,4 +1,4 @@ -use anyhow::{Result, bail}; +use anyhow::Result; use clap::{Args, ValueEnum}; use tinywasm::{Engine, StackConfig, engine::FuelPolicy}; @@ -8,18 +8,6 @@ pub struct EngineFlags { #[arg(long, value_enum)] pub fuel_policy: Option, - /// Trap immediately on memory or stack allocation failure - #[arg(long)] - pub trap_on_oom: bool, - - /// Memory backend to use for instantiated memories - #[arg(long, value_enum)] - pub memory_backend: Option, - - /// Chunk size in bytes for the paged memory backend - #[arg(long, default_value_t = 64 * 1024)] - pub memory_page_chunk_size: usize, - /// Fixed value stack size for all value lanes #[arg(long, conflicts_with = "value_stack_dynamic")] pub value_stack_size: Option, @@ -43,12 +31,6 @@ pub enum FuelPolicyArg { Weighted, } -#[derive(Clone, Copy, ValueEnum)] -pub enum MemoryBackendArg { - Vec, - Paged, -} - #[derive(Clone)] pub struct StackSpec { initial: usize, @@ -86,18 +68,6 @@ impl EngineFlags { }); } - if let Some(memory_backend) = self.memory_backend { - config = config.with_memory_backend(match memory_backend { - MemoryBackendArg::Vec => tinywasm::MemoryBackend::vec(), - MemoryBackendArg::Paged => { - if self.memory_page_chunk_size == 0 { - bail!("--memory-page-chunk-size must be greater than zero"); - } - tinywasm::MemoryBackend::paged(self.memory_page_chunk_size) - } - }); - } - if let Some(value_stack_size) = self.value_stack_size { config = config.with_value_stack(StackConfig::fixed(value_stack_size)); } @@ -114,10 +84,6 @@ impl EngineFlags { config = config.with_call_stack(call_stack_dynamic.into_stack_config()); } - if self.trap_on_oom { - config = config.with_trap_on_oom(true); - } - Ok(Engine::new(config)) } } diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index b94ebe6..364bae8 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -151,29 +151,26 @@ pub(crate) fn convert_module_code( ty_idx: u32, options: &ParserOptions, ) -> Result<(FunctionCode, Option, OperatorsReaderAllocations)> { - let locals_reader = func.get_locals_reader()?; - #[cfg(feature = "validate")] - let locals_position = locals_reader.original_position(); + let mut locals_reader = func.get_locals_reader()?; let signature = metadata.signature(ty_idx)?.clone(); let mut local_types = signature.params.clone(); #[cfg(feature = "validate")] let mut validator = validator; - #[cfg(feature = "validate")] - for (local_index, local) in locals_reader.into_iter().enumerate() { - let local = local?; + for _ in 0..locals_reader.get_count() { + #[cfg(feature = "validate")] + let position = locals_reader.original_position(); + let local = locals_reader.read()?; + #[cfg(feature = "validate")] if let Some(validator) = validator.as_mut() { - validator.define_locals(locals_position + local_index, local.0, local.1)?; + validator.define_locals(position, local.0, local.1)?; } extend_local_types(&mut local_types, local.0, local.1)?; } #[cfg(not(feature = "validate"))] - for local in locals_reader { - let local = local?; - extend_local_types(&mut local_types, local.0, local.1)?; - } + let _ = validator; // maps a local's address to the index in the type's locals array let mut local_addr_map = Vec::with_capacity(local_types.len()); diff --git a/crates/parser/src/error.rs b/crates/parser/src/error.rs index e4d8abd..892e27b 100644 --- a/crates/parser/src/error.rs +++ b/crates/parser/src/error.rs @@ -20,7 +20,7 @@ pub enum ParseError { /// The error message message: String, /// The offset in the module where the error occurred - offset: usize, + offset: u64, }, /// An invalid encoding was encountered InvalidEncoding(Encoding), diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs index 90e239b..262cc07 100644 --- a/crates/parser/src/lib.rs +++ b/crates/parser/src/lib.rs @@ -61,8 +61,6 @@ pub struct ParserOptions { /// Disable this only for trusted input. Parsing without validation may produce /// a module that violates runtime assumptions. pub validation: bool, - /// Whether to optimize local memory allocation by skipping allocation of unused local memories. - pub optimize_local_memory_allocation: bool, /// Whether to run the peephole rewrite optimizer. pub optimize_rewrite: bool, /// Whether to deduplicate immutable function operands while parsing. @@ -85,7 +83,6 @@ impl Default for ParserOptions { fn default() -> Self { Self { validation: cfg!(feature = "validate"), - optimize_local_memory_allocation: true, optimize_rewrite: true, deduplicate_operands: false, #[cfg(parallel_parser)] @@ -117,17 +114,6 @@ impl ParserOptions { self.validation } - /// Enable or disable the optimization that skips allocating unused local memories. - pub const fn with_local_memory_allocation_optimization(mut self, enabled: bool) -> Self { - self.optimize_local_memory_allocation = enabled; - self - } - - /// Returns whether unused local memory allocation optimization is enabled. - pub const fn optimize_local_memory_allocation(&self) -> bool { - self.optimize_local_memory_allocation - } - /// Enable or disable the peephole rewrite optimizer. pub const fn with_rewrite_optimization(mut self, enabled: bool) -> Self { self.optimize_rewrite = enabled; @@ -234,7 +220,7 @@ impl Parser { } reader.process_pending_functions(&self.options)?; - reader.into_module(&self.options) + reader.into_module() } #[cfg(feature = "std")] @@ -263,7 +249,7 @@ impl Parser { buffer.truncate(buffer.len() - buffer_offset); buffer_offset = 0; } - let read_bytes = Self::read_more(&mut stream, &mut buffer, hint as usize)?; + let read_bytes = Self::read_more(&mut stream, &mut buffer, hint)?; eof = read_bytes == 0; } wasmparser::Chunk::Parsed { consumed, payload } => { @@ -272,17 +258,12 @@ impl Parser { match payload { wasmparser::Payload::CodeSectionStart { count, range, size } => { - let defer = reader.begin_code_section( - count, - range.clone(), - size, - validator.as_mut(), - &self.options, - )?; + let defer = + reader.begin_code_section(count, range, size, validator.as_mut(), &self.options)?; #[cfg(parallel_parser)] if defer { - deferred_code_section = Some((count, range.end - size as usize, size as usize)); + deferred_code_section = Some((count, size as usize)); } #[cfg(not(parallel_parser))] @@ -298,21 +279,21 @@ impl Parser { buffer_offset += consumed; #[cfg(parallel_parser)] - if let Some((count, body_offset, section_size)) = deferred_code_section { + if let Some((count, section_size)) = deferred_code_section { while buffer.len() - buffer_offset < section_size { let remaining = section_size - (buffer.len() - buffer_offset); let read_bytes = Self::read_more(&mut stream, &mut buffer, remaining)?; if read_bytes == 0 { return Err(ParseError::ParseError { message: "unexpected end-of-file".into(), - offset: body_offset + buffer.len() - buffer_offset, + offset: parser.offset() + (buffer.len() - buffer_offset) as u64, }); } } let section_end = buffer_offset + section_size; let section_bytes = alloc::sync::Arc::<[u8]>::from(buffer[buffer_offset..section_end].to_vec()); - reader.queue_owned_code_section(count, body_offset, section_bytes, validator.as_mut())?; + reader.queue_owned_code_section(count, parser.offset(), section_bytes, validator.as_mut())?; parser.skip_section(); buffer_offset = section_end; continue; @@ -335,7 +316,7 @@ impl Parser { if reader.end_reached || eof { reader.process_pending_functions(&self.options)?; - return reader.into_module(&self.options); + return reader.into_module(); } } }; @@ -347,7 +328,7 @@ impl TryFrom> for Module { type Error = ParseError; fn try_from(reader: ModuleReader<'_>) -> Result { - reader.into_module(&ParserOptions::default()) + reader.into_module() } } diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index 8138666..c076035 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -19,7 +19,6 @@ pub(crate) struct OptimizedFunctionCode { pub instructions: Vec, pub data: WasmFunctionData, pub locals: ValueCounts, - pub uses_local_memory: bool, } pub(crate) fn optimize_function_code( @@ -27,16 +26,11 @@ pub(crate) fn optimize_function_code( options: &ParserOptions, function_results: ValueCounts, self_func_addr: u32, - imported_memory_count: u32, ) -> Result { let optimized = optimize::optimize_instructions(code.instructions, &mut code.data, options, function_results, self_func_addr)?; let data = code.data.finish(); - let uses_local_memory = optimized - .instructions - .iter() - .any(|instruction| instruction.memory_addr(&data).is_some_and(|memory| memory >= imported_memory_count)); - Ok(OptimizedFunctionCode { instructions: optimized.instructions, data, locals: code.locals, uses_local_memory }) + Ok(OptimizedFunctionCode { instructions: optimized.instructions, data, locals: code.locals }) } #[derive(Default)] @@ -65,7 +59,6 @@ pub(crate) struct ModuleReader<'a> { pub(crate) elements: Box<[Element]>, pub(crate) end_reached: bool, imported_func_count: usize, - imported_memory_count: u32, global_types: Vec, #[cfg(parallel_parser)] @@ -277,7 +270,6 @@ impl<'a> ModuleReader<'a> { } self.imported_func_count += 1; } - ImportKind::Memory(_) => self.imported_memory_count += 1, ImportKind::Global(ty) => self.global_types.push(ty.ty), ImportKind::Tag(tag) => { let ty = self.types.get(tag.type_idx).and_then(SubType::as_func).ok_or_else(|| { @@ -338,7 +330,7 @@ impl<'a> ModuleReader<'a> { pub(crate) fn begin_code_section( &mut self, count: u32, - range: Range, + range: Range, size: u32, validator: Option<&mut Validator>, options: &ParserOptions, @@ -411,7 +403,6 @@ impl<'a> ModuleReader<'a> { options, self.code_results[self.code.len()], (self.imported_func_count + self.code.len()) as u32, - self.imported_memory_count, )?); self.func_validator_allocations = func_validator_allocs; @@ -443,7 +434,7 @@ impl<'a> ModuleReader<'a> { pub(crate) fn queue_owned_code_section( &mut self, count: u32, - body_offset: usize, + body_offset: u64, section_bytes: Arc<[u8]>, validator: Option<&mut Validator>, ) -> Result<()> { @@ -455,6 +446,8 @@ impl<'a> ModuleReader<'a> { for _ in 0..count { let body_reader = reader.read_reader()?; let body_range = body_reader.range(); + let body_start = (body_range.start - body_offset) as usize; + let body_end = (body_range.end - body_offset) as usize; #[cfg(feature = "validate")] let func_to_validate = { let function = wasmparser::FunctionBody::new(body_reader); @@ -465,7 +458,7 @@ impl<'a> ModuleReader<'a> { self.queue_function( crate::parallel::FunctionBodyInput::Owned(crate::parallel::OwnedFunctionBody { section_bytes: section_bytes.clone(), - body_range: (body_range.start - body_offset)..(body_range.end - body_offset), + body_range: body_start..body_end, body_offset: body_range.start, }), func_to_validate, @@ -512,10 +505,8 @@ impl<'a> ModuleReader<'a> { }; let imported_func_count = self.imported_func_count; - let imported_memory_count = self.imported_memory_count; let metadata = self.translation_metadata(); - let code = - crate::parallel::process_pending(pending, metadata, options, imported_func_count, imported_memory_count)?; + let code = crate::parallel::process_pending(pending, metadata, options, imported_func_count)?; self.code.extend(code); Ok(()) } @@ -525,7 +516,7 @@ impl<'a> ModuleReader<'a> { Ok(()) } - pub(crate) fn into_module(self, options: &ParserOptions) -> Result { + pub(crate) fn into_module(self) -> Result { if !self.end_reached { return Err(ParseError::EndNotReached); } @@ -534,24 +525,6 @@ impl<'a> ModuleReader<'a> { return Err(ParseError::Other("Code and code type address count mismatch".to_string())); } - let import_mem_count = self.imported_memory_count; - let has_local_mem_export = - self.exports.iter().any(|export| export.kind == ExternalKind::Memory && export.index >= import_mem_count); - let has_active_data_segment_on_local_memory = self.data.iter().any(|data| match &data.kind { - DataKind::Active { mem, .. } => *mem >= import_mem_count, - DataKind::Passive => false, - }); - let optimize_local_memory_allocation = options.optimize_local_memory_allocation(); - let mut local_memory_allocation = if self.memory_types.is_empty() { - LocalMemoryAllocation::Skip - } else if !optimize_local_memory_allocation || has_active_data_segment_on_local_memory { - LocalMemoryAllocation::Eager - } else if has_local_mem_export { - LocalMemoryAllocation::Lazy - } else { - LocalMemoryAllocation::Skip - }; - let func_type_idxs = self .imports .iter() @@ -571,9 +544,6 @@ impl<'a> ModuleReader<'a> { let ty = self.types.get(ty_idx).and_then(SubType::as_func).expect("function type was checked while parsing"); let params = ValueCounts::from_iter(ty.params()); - if code.uses_local_memory { - local_memory_allocation = LocalMemoryAllocation::Eager; - } Ok(Arc::new(WasmFunction { instructions: code.instructions.into_boxed_slice(), @@ -598,7 +568,6 @@ impl<'a> ModuleReader<'a> { elements: self.elements, memory_types: self.memory_types, tags: self.tags, - local_memory_allocation, } .into()) } diff --git a/crates/parser/src/parallel.rs b/crates/parser/src/parallel.rs index e29b38f..9b96c7a 100644 --- a/crates/parser/src/parallel.rs +++ b/crates/parser/src/parallel.rs @@ -17,7 +17,7 @@ pub(crate) struct OwnedFunctionBody { // function jobs from that section. pub section_bytes: Arc<[u8]>, pub body_range: Range, - pub body_offset: usize, + pub body_offset: u64, } pub(crate) struct PendingFunction<'a> { @@ -61,7 +61,6 @@ fn process_function_job( metadata: &crate::visit::ModuleMetadata, options: &ParserOptions, imported_func_count: usize, - imported_memory_count: u32, validator_allocs: Option, reader_allocs: OperatorsReaderAllocations, ) -> Result<(OptimizedFunctionCode, Option, OperatorsReaderAllocations)> { @@ -83,13 +82,7 @@ fn process_function_job( } }; - let code = optimize_function_code( - code, - options, - job.results, - (imported_func_count + job.ordinal) as u32, - imported_memory_count, - )?; + let code = optimize_function_code(code, options, job.results, (imported_func_count + job.ordinal) as u32)?; Ok((code, validator_allocs, reader_allocs)) } @@ -99,7 +92,6 @@ fn process_chunk<'a>( metadata: &crate::visit::ModuleMetadata, options: &ParserOptions, imported_func_count: usize, - imported_memory_count: u32, ) -> Result> { let mut validator_allocs = None; let mut reader_allocs = OperatorsReaderAllocations::default(); @@ -107,15 +99,8 @@ fn process_chunk<'a>( let mut codes = Vec::with_capacity(jobs.size_hint().0); for job in jobs { - let (code, next_validator_allocs, next_reader_allocs) = process_function_job( - job, - metadata, - options, - imported_func_count, - imported_memory_count, - validator_allocs, - reader_allocs, - )?; + let (code, next_validator_allocs, next_reader_allocs) = + process_function_job(job, metadata, options, imported_func_count, validator_allocs, reader_allocs)?; codes.push(code); validator_allocs = next_validator_allocs; reader_allocs = next_reader_allocs; @@ -129,11 +114,10 @@ pub(crate) fn process_pending( metadata: &crate::visit::ModuleMetadata, options: &ParserOptions, imported_func_count: usize, - imported_memory_count: u32, ) -> Result> { let num_workers = worker_count(options, pending.len()); if num_workers == 1 { - return process_chunk(pending, metadata, options, imported_func_count, imported_memory_count); + return process_chunk(pending, metadata, options, imported_func_count); } let code_count = pending.len(); let chunk_size = pending.len().div_ceil(num_workers); @@ -151,10 +135,7 @@ pub(crate) fn process_pending( bytes += body_len(&job.body); chunk.push(job); } - handles - .push(scope.spawn(move || { - process_chunk(chunk, metadata, options, imported_func_count, imported_memory_count) - })); + handles.push(scope.spawn(move || process_chunk(chunk, metadata, options, imported_func_count))); } let mut codes = Vec::with_capacity(code_count); diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index 8315fb5..f48e1cf 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -221,7 +221,7 @@ impl<'a> FunctionBuilder<'a> { struct ValidateThenVisit<'a, 'm> { validator: &'a mut FuncValidator, builder: &'a mut FunctionBuilder<'m>, - position: usize, + position: u64, } impl ModuleMetadata { diff --git a/crates/tinywasm/src/engine.rs b/crates/tinywasm/src/engine.rs index 64ef6be..f1feae6 100644 --- a/crates/tinywasm/src/engine.rs +++ b/crates/tinywasm/src/engine.rs @@ -1,5 +1,6 @@ -/// Memory backend types and traits. -pub use crate::store::{LazyLinearMemory, LinearMemory, MemoryBackend, PagedMemory, VecMemory}; +use alloc::sync::Arc; + +use crate::ResourceLimiter; /// Global configuration for the WebAssembly interpreter /// @@ -88,21 +89,18 @@ impl StackConfig { /// /// ## Example /// ```rust -/// use tinywasm::engine::{Config, FuelPolicy, MemoryBackend, StackConfig}; +/// use tinywasm::engine::{Config, FuelPolicy, StackConfig}; /// /// let config = Config::new() /// .with_fuel_policy(FuelPolicy::Weighted) /// .with_value_stack_32(StackConfig::dynamic(1024, 36 * 1024)) /// .with_value_stack_64(StackConfig::dynamic(1024, 32 * 1024)) /// .with_value_stack_128(StackConfig::dynamic(256, 4 * 1024)) -/// .with_call_stack(StackConfig::dynamic(64, 1024)) -/// .with_memory_backend(MemoryBackend::paged(64 * 1024)) -/// .with_trap_on_oom(true); +/// .with_call_stack(StackConfig::dynamic(64, 1024)); /// /// assert!(matches!(config.fuel_policy(), FuelPolicy::Weighted)); /// ``` #[derive(Clone)] -#[cfg_attr(feature = "debug", derive(Debug))] #[non_exhaustive] pub struct Config { /// Configuration for the 32-bit value stack (i32, f32, ref values). @@ -118,11 +116,8 @@ pub struct Config { pub call_stack: StackConfig, /// Fuel accounting policy used by budgeted execution. Defaults to [`FuelPolicy::PerInstruction`]. pub fuel_policy: FuelPolicy, - /// Backend used for runtime memories. Defaults to [`MemoryBackend::vec`]. - pub memory_backend: MemoryBackend, - /// Whether memory and stack allocation failures should trap instead of degrading into normal operation failure modes. - /// Defaults to `false`. - pub trap_on_oom: bool, + /// Resource limiter shared across all stores created from this engine. Defaults to `None`. + pub resource_limiter: Option>, /// Initial number of GC heap bytes that triggers collection. /// Defaults to 1 MiB. pub gc_collection_threshold: usize, @@ -140,12 +135,6 @@ impl Config { self } - /// Set the backend used for runtime memories. - pub fn with_memory_backend(mut self, memory_backend: MemoryBackend) -> Self { - self.memory_backend = memory_backend; - self - } - /// Set the configuration used for the 32-bit value stack. pub fn with_value_stack_32(mut self, stack: StackConfig) -> Self { self.value_stack_32 = stack; @@ -178,9 +167,9 @@ impl Config { self } - /// Configure whether memory and stack allocation failures trap immediately. - pub fn with_trap_on_oom(mut self, trap_on_oom: bool) -> Self { - self.trap_on_oom = trap_on_oom; + /// Set the resource limiter shared across all stores created from this engine. + pub fn with_resource_limiter(mut self, limiter: Arc) -> Self { + self.resource_limiter = Some(limiter); self } @@ -194,15 +183,6 @@ impl Config { pub fn fuel_policy(&self) -> FuelPolicy { self.fuel_policy } - - /// Get the current memory backend - pub fn memory_backend(&self) -> &MemoryBackend { - &self.memory_backend - } - - pub(crate) const fn trap_on_oom(&self) -> bool { - self.trap_on_oom - } } impl Default for Config { @@ -213,9 +193,23 @@ impl Default for Config { value_stack_128: StackConfig::fixed(DEFAULT_VALUE_STACK_128_SIZE), call_stack: StackConfig::fixed(DEFAULT_MAX_CALL_STACK_SIZE), fuel_policy: FuelPolicy::default(), - memory_backend: MemoryBackend::default(), - trap_on_oom: false, + resource_limiter: None, gc_collection_threshold: 1024 * 1024, } } } + +#[cfg(feature = "debug")] +impl core::fmt::Debug for Config { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Config") + .field("value_stack_32", &self.value_stack_32) + .field("value_stack_64", &self.value_stack_64) + .field("value_stack_128", &self.value_stack_128) + .field("call_stack", &self.call_stack) + .field("fuel_policy", &self.fuel_policy) + .field("resource_limiter", &self.resource_limiter.is_some()) + .field("gc_collection_threshold", &self.gc_collection_threshold) + .finish() + } +} diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index f45b718..6700d53 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -85,6 +85,17 @@ impl ModuleInstance { *self.0.mem_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid memory address: {addr}")) } + /// The resolved store address of the module's first memory, or `MemAddr::MAX` when the module + /// has none. + /// + /// The sentinel is never used in practice: validation guarantees a memory instruction can only + /// reference index 0 when the module declares a memory, so any read of the sentinel would trip + /// an out-of-bounds panic in the store lookup and surface a bug. + #[inline] + pub(crate) fn mem0_addr(&self) -> MemAddr { + self.0.mem_addrs.first().copied().unwrap_or(MemAddr::MAX) + } + /// resolve a data address to the global store address #[inline] pub(crate) fn resolve_data_addr(&self, addr: DataAddr) -> DataAddr { @@ -165,18 +176,10 @@ impl ModuleInstance { let imported_funcs = addrs.funcs.len(); addrs.funcs.extend(store.init_funcs(&module.funcs, id, &module.func_type_idxs[imported_funcs..], &type_addrs)); addrs.tags.extend(store.init_tags(&module.tags, &type_addrs)); - match module.local_memory_allocation { - LocalMemoryAllocation::Skip => { - #[cfg(feature = "guest-debug")] - addrs.memories.extend(store.init_memories(&module.memory_types, MemoryInstance::new_lazy)?); - } - LocalMemoryAllocation::Lazy => { - addrs.memories.extend(store.init_memories(&module.memory_types, MemoryInstance::new_lazy)?) - } - LocalMemoryAllocation::Eager => { - addrs.memories.extend(store.init_memories(&module.memory_types, MemoryInstance::new)?) - } - } + let limiter = store.engine.config().resource_limiter.clone(); + addrs + .memories + .extend(store.init_memories(&module.memory_types, |ty| MemoryInstance::new(ty, limiter.as_deref()))?); store.init_globals(&mut addrs.globals, &module.globals, &addrs.funcs, &type_addrs)?; addrs.tables.extend(store.init_tables(&module.tables, &addrs.globals, &addrs.funcs, &type_addrs)?); diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 9da4a7a..b203980 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -27,6 +27,7 @@ pub(crate) struct Executor<'store, const BUDGETED: bool> { module: ModuleInstance, store: &'store mut Store, call_stack_base: u32, + mem0: MemAddr, } impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { @@ -36,7 +37,22 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { .get_module_instance(wasm_func.owner) .unwrap_or_else(|| unreachable!("invalid module instance")) .clone(); - Self { module, cf, func: wasm_func.func.clone(), store, call_stack_base } + let mem0 = module.mem0_addr(); + Self { module, cf, func: wasm_func.func.clone(), store, call_stack_base, mem0 } + } + + /// Resolves a module-local memory index to its store address, caching the common memory-0 case. + #[inline(always)] + fn mem_addr(&self, idx: MemAddr) -> MemAddr { + if idx == 0 { self.mem0 } else { self.module.resolve_mem_addr(idx) } + } + + /// Switches the executor to another module, keeping the cached memory-0 address in sync. + #[inline] + fn set_module(&mut self, owner: ModuleInstanceId) { + self.module = + self.store.get_module_instance(owner).unwrap_or_else(|| unreachable!("invalid module instance")).clone(); + self.mem0 = self.module.mem0_addr(); } #[inline(always)] @@ -975,11 +991,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let wasm_func = self.store.state.get_wasm_func(self.cf.func_addr); self.func = wasm_func.func.clone(); if wasm_func.owner != self.module.id() { - self.module = self - .store - .get_module_instance(wasm_func.owner) - .unwrap_or_else(|| unreachable!("invalid module instance")) - .clone(); + self.set_module(wasm_func.owner); } } @@ -1038,11 +1050,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } self.cf = CallFrame::new(func_addr, locals_base, locals); if owner != self.module.id() { - self.module = self - .store - .get_module_instance(owner) - .unwrap_or_else(|| unreachable!("invalid module instance")) - .clone(); + self.set_module(owner); } Ok(()) @@ -1064,11 +1072,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } self.cf = CallFrame::new(func_addr, locals_base, locals); if owner != self.module.id() { - self.module = self - .store - .get_module_instance(owner) - .unwrap_or_else(|| unreachable!("invalid module instance")) - .clone(); + self.set_module(owner); } Ok(()) @@ -1277,7 +1281,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { value_local: u8, ) -> Result<(), Trap> { let value = T::local_get(&self.store.value_stack, &self.cf, u16::from(value_local)); - let mem_addr = self.module.resolve_mem_addr(memarg.mem_addr()); + let mem_addr = self.mem_addr(memarg.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let addr = if mem.is_64bit() { let base = u64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); @@ -1292,7 +1296,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { mem.effective_addr::(base as usize, memarg.offset())? }; let mem = self.store.state.get_mem_mut(mem_addr); - value.store_at(&mut *mem.inner, addr) + value.store_at(&mut mem.inner, addr) } #[inline(always)] @@ -1302,7 +1306,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { addr_local: u8, increment: impl FnOnce(T) -> T, ) -> Result<(), Trap> { - let mem_addr = self.module.resolve_mem_addr(memarg.mem_addr()); + let mem_addr = self.mem_addr(memarg.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let addr = if mem.is_64bit() { let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64; @@ -1318,8 +1322,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { }; let mem = self.store.state.get_mem_mut(mem_addr); - let value = cold_err!(T::load_at(&*mem.inner, addr))?; - increment(value).store_at(&mut *mem.inner, addr) + let value = cold_err!(T::load_at(&mem.inner, addr))?; + increment(value).store_at(&mut mem.inner, addr) } #[inline(always)] @@ -1334,12 +1338,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let lhs = T::stack_pop(&mut self.store.value_stack); let acc = T::stack_pop(&mut self.store.value_stack); let fma = acc + lhs * rhs; - let mem_addr = self.module.resolve_mem_addr(m.mem_addr()); + let mem_addr = self.mem_addr(m.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; let addr = mem.effective_addr::(base, m.offset())?; let mem = self.store.state.get_mem_mut(mem_addr); - fma.store_at(&mut *mem.inner, addr)?; + fma.store_at(&mut mem.inner, addr)?; Ok(()) } @@ -1349,7 +1353,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { memarg: CompactMemoryArg, addr_local: u8, ) -> Result { - let mem = self.store.state.get_mem(self.module.resolve_mem_addr(memarg.mem_addr())); + let mem = self.store.state.get_mem(self.mem_addr(memarg.mem_addr())); let addr = if mem.is_64bit() { let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64; let base = cold_err!(usize::try_from(base).map_err(|_| Trap::MemoryOutOfBounds { @@ -1362,7 +1366,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); mem.effective_addr::(base as usize, memarg.offset())? }; - cold_err!(T::load_at(&*mem.inner, addr)) + cold_err!(T::load_at(&mem.inner, addr)) } #[inline(always)] @@ -1638,7 +1642,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } fn exec_memory_size(&mut self, addr: u32) -> Result<(), Trap> { - let mem = self.store.state.get_mem(self.module.resolve_mem_addr(addr)); + let mem = self.store.state.get_mem(self.mem_addr(addr)); match mem.is_64bit() { true => self.store.value_stack.push::(mem.page_count as i64), false => self.store.value_stack.push::(mem.page_count as i32), @@ -1646,14 +1650,16 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } fn exec_memory_grow(&mut self, addr: u32) -> Result<(), Trap> { - let mem = self.store.state.get_mem_mut(self.module.resolve_mem_addr(addr)); - let is_64bit = mem.is_64bit(); + let mem_addr = self.mem_addr(addr); + let is_64bit = self.store.state.get_mem(mem_addr).is_64bit(); let pages_delta = match is_64bit { true => ::stack_pop(&mut self.store.value_stack), false => i64::from(::stack_pop(&mut self.store.value_stack)), }; + let limiter = self.store.engine.config().resource_limiter.as_deref(); - let size = mem.grow(pages_delta, self.store.engine.config().trap_on_oom())?.unwrap_or(-1); + let mem = self.store.state.get_mem_mut(mem_addr); + let size = mem.grow(pages_delta, limiter)?.unwrap_or(-1); match is_64bit { true => self.store.value_stack.push::(size)?, false => self.store.value_stack.push::(size as i32)?, @@ -1664,8 +1670,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_memory_copy(&mut self, index: OperandIdx) -> Result<(), Trap> { let TwoU32 { first: dst_mem, second: src_mem } = index.get(&self.func.data); - let dst_mem_addr = self.module.resolve_mem_addr(dst_mem); - let src_mem_addr = self.module.resolve_mem_addr(src_mem); + let dst_mem_addr = self.mem_addr(dst_mem); + let src_mem_addr = self.mem_addr(src_mem); let dst_arch = self.store.state.get_mem(dst_mem_addr).kind.arch(); let src_arch = self.store.state.get_mem(src_mem_addr).kind.arch(); let len_arch = @@ -1687,7 +1693,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } fn exec_memory_fill(&mut self, addr: u32) -> Result<(), Trap> { - let mem_addr = self.module.resolve_mem_addr(addr); + let mem_addr = self.mem_addr(addr); let arch = self.store.state.get_mem(mem_addr).kind.arch(); let size = self.store.value_stack.pop_memory_operand(arch)?; let val = i32::stack_pop(&mut self.store.value_stack); @@ -1697,7 +1703,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_memory_fill_const(&mut self, index: OperandIdx) -> Result<(), Trap> { let MemoryFillConstOp { memory: addr, byte: val, value: size } = index.get(&self.func.data); - let mem_addr = self.module.resolve_mem_addr(addr); + let mem_addr = self.mem_addr(addr); let arch = self.store.state.get_mem(mem_addr).kind.arch(); let dst = self.store.value_stack.pop_memory_operand(arch)?; self.exec_memory_fill_impl(mem_addr, dst, val, size as u32 as usize) @@ -1706,7 +1712,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_memory_fill_impl(&mut self, mem_addr: MemAddr, dst: usize, val: u8, size: usize) -> Result<(), Trap> { let mem = self.store.state.get_mem_mut(mem_addr); let max = mem.inner.len(); - if mem.inner.fill(dst, size, val)?.is_none() { + if mem.inner.fill(dst, size, val).is_none() { return cold!(Err(Trap::MemoryOutOfBounds { offset: dst, len: size, max })); } Ok(()) @@ -1716,7 +1722,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let TwoU32 { first: data_index, second: mem_index } = index.get(&self.func.data); let size = u32::stack_pop(&mut self.store.value_stack) as usize; let offset = u32::stack_pop(&mut self.store.value_stack) as usize; - let mem_addr = self.module.resolve_mem_addr(mem_index); + let mem_addr = self.mem_addr(mem_index); let arch = self.store.state.get_mem(mem_addr).kind.arch(); let dst = self.store.value_stack.pop_memory_operand(arch)?; @@ -1739,7 +1745,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { return cold!(Err(Trap::MemoryOutOfBounds { offset: 0, len: 0, max: 0 })); }; - if mem.inner.write_all(dst, &data[offset..offset + size])?.is_none() { + if mem.inner.write_all(dst, &data[offset..offset + size]).is_none() { return cold!(Err(Trap::MemoryOutOfBounds { offset: dst, len: size, max: mem_len })); } Ok(()) @@ -1772,10 +1778,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { arg: MemoryLaneArg, ) -> Result<(), Trap> { let m = arg.memory_arg_idx.get(&self.func.data); - let mem = self.store.state.get_mem(self.module.resolve_mem_addr(m.mem_addr())); + let mem = self.store.state.get_mem(self.mem_addr(m.mem_addr())); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; let addr = mem.effective_addr::(base, m.offset())?; - let val = cold_err!(LOAD::load_at(&*mem.inner, addr))?; + let val = cold_err!(LOAD::load_at(&mem.inner, addr))?; let offset = arg.lane as usize * LOAD_SIZE; let mut imm = ::stack_pop(&mut self.store.value_stack).to_mem_bytes(); imm[offset..offset + LOAD_SIZE].copy_from_slice(&val.to_mem_bytes()); @@ -1790,10 +1796,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { cast: impl Fn(LOAD) -> TARGET, ) -> Result<(), Trap> { let m = index.get(&self.func.data); - let mem = self.store.state.get_mem(self.module.resolve_mem_addr(m.mem_addr())); + let mem = self.store.state.get_mem(self.mem_addr(m.mem_addr())); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; let addr = mem.effective_addr::(base, m.offset())?; - let value = cold_err!(LOAD::load_at(&*mem.inner, addr))?; + let value = cold_err!(LOAD::load_at(&mem.inner, addr))?; self.store.value_stack.push(cast(value)) } @@ -1804,12 +1810,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { val_bytes.copy_from_slice(&bytes[lane_offset..lane_offset + N]); let val = U::from_mem_bytes(val_bytes); let m = arg.memory_arg_idx.get(&self.func.data); - let mem_addr = self.module.resolve_mem_addr(m.mem_addr()); + let mem_addr = self.mem_addr(m.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; let addr = mem.effective_addr::(base, m.offset())?; let mem = self.store.state.get_mem_mut(mem_addr); - cold_err!(val.store_at(&mut *mem.inner, addr))?; + cold_err!(val.store_at(&mut mem.inner, addr))?; Ok(()) } @@ -1822,12 +1828,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let val = cast(val); let m = index.get(&self.func.data); - let mem_addr = self.module.resolve_mem_addr(m.mem_addr()); + let mem_addr = self.mem_addr(m.mem_addr()); let mem = self.store.state.get_mem(mem_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; let addr = mem.effective_addr::(base, m.offset())?; let mem = self.store.state.get_mem_mut(mem_addr); - cold_err!(val.store_at(&mut *mem.inner, addr))?; + cold_err!(val.store_at(&mut mem.inner, addr))?; Ok(()) } @@ -1874,14 +1880,15 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let arch = self.store.state.get_table(table_addr).kind.arch(); let n = self.pop_table_operand(arch)?; let val = ::stack_pop(&mut self.store.value_stack); + let limiter = self.store.engine.config().resource_limiter.as_deref(); let table = self.store.state.get_table_mut(table_addr); let sz = table.size(); - let result = table.grow(n, val); - match (arch, result) { - (MemoryArch::I32, Ok(())) => self.store.value_stack.push(sz as i32), - (MemoryArch::I32, Err(_)) => self.store.value_stack.push(-1_i32), - (MemoryArch::I64, Ok(())) => self.store.value_stack.push(sz as i64), - (MemoryArch::I64, Err(_)) => self.store.value_stack.push(-1_i64), + let grew = table.grow(n, val, limiter)?; + match (arch, grew) { + (MemoryArch::I32, true) => self.store.value_stack.push(sz as i32), + (MemoryArch::I32, false) => self.store.value_stack.push(-1_i32), + (MemoryArch::I64, true) => self.store.value_stack.push(sz as i64), + (MemoryArch::I64, false) => self.store.value_stack.push(-1_i64), } } diff --git a/crates/tinywasm/src/lib.rs b/crates/tinywasm/src/lib.rs index e941430..bd80ef1 100644 --- a/crates/tinywasm/src/lib.rs +++ b/crates/tinywasm/src/lib.rs @@ -54,8 +54,9 @@ //! ``` //! //! For non-default runtime behavior, construct a [`Store`] with a custom [`Engine`] -//! and [`engine::Config`] to control stack sizing, fuel accounting, memory backends, -//! and trap-on-OOM behavior. +//! and [`engine::Config`] to control stack sizing and fuel accounting. A [`ResourceLimiter`] can be +//! attached to the engine configuration to bound memory and table allocation and growth for stores +//! created from that engine and to trap rejected requests. //! //! For more examples, see the [`examples`](https://github.com/explodingcamera/tinywasm/tree/main/examples) directory. //! @@ -129,7 +130,7 @@ use interpreter::InterpreterRuntime; /// Global configuration for the WebAssembly interpreter pub mod engine; -pub use engine::{Engine, LazyLinearMemory, LinearMemory, MemoryBackend, PagedMemory, StackConfig, VecMemory}; +pub use engine::{Engine, StackConfig}; #[cfg(feature = "parser")] /// Re-export of [`tinywasm_parser`]. Requires `parser` feature. diff --git a/crates/tinywasm/src/reference.rs b/crates/tinywasm/src/reference.rs index f5d9c23..271e71c 100644 --- a/crates/tinywasm/src/reference.rs +++ b/crates/tinywasm/src/reference.rs @@ -122,7 +122,7 @@ impl crate::std::io::Read for MemoryCursor<'_> { impl crate::std::io::Write for MemoryCursor<'_> { fn write(&mut self, buf: &[u8]) -> crate::std::io::Result { let offset = self.offset()?; - let written = self.memory.inner.write(offset, buf).map_err(Error::from)?; + let written = self.memory.inner.write(offset, buf); self.advance(written)?; Ok(written) } @@ -163,7 +163,8 @@ impl Memory { /// Create a new memory in the given store. pub fn new(store: &mut Store, ty: MemoryType) -> Result { let addr = store.state.memories.len() as MemAddr; - store.state.memories.push(MemoryInstance::new(ty, &store.engine.config().memory_backend)?); + let limiter = store.engine.config().resource_limiter.clone(); + store.state.memories.push(MemoryInstance::new(ty, limiter.as_deref())?); Ok(Self(StoreItem::new(store.id(), addr))) } @@ -230,19 +231,18 @@ impl Memory { /// Reads up to `dst.len()` bytes from memory and returns the number of bytes read. /// - /// Depending on the configured backend, this may return fewer bytes than requested even when - /// more data is available. Use [`Self::read_exact`] or [`Self::read_vec`] when you need a full - /// range. + /// This returns fewer bytes than requested when the range extends past the end of memory. Use + /// [`Self::read_exact`] or [`Self::read_vec`] when you need a full range. pub fn read(&self, store: &Store, offset: usize, dst: &mut [u8]) -> Result { Ok(self.instance(store)?.inner.read(offset, dst)) } /// Writes up to `src.len()` bytes into memory and returns the number of bytes written. /// - /// Depending on the configured backend, this may return fewer bytes than requested even when - /// more space is available. Use [`Self::copy_from_slice`] when you need the full slice written. + /// This returns fewer bytes than requested when the range extends past the end of memory. Use + /// [`Self::copy_from_slice`] when you need the full slice written. pub fn write(&self, store: &mut Store, offset: usize, src: &[u8]) -> Result { - Ok(self.instance_mut(store)?.inner.write(offset, src)?) + Ok(self.instance_mut(store)?.inner.write(offset, src)) } /// Reads exactly `dst.len()` bytes from memory. @@ -263,9 +263,14 @@ impl Memory { }) } - /// Grow the memory by the given number of pages. + /// Grows the memory by the given number of pages. + /// + /// Returns the previous size, or `None` if growth fails or is rejected by the resource limiter. + /// A limiter-provided trap is returned as an error. pub fn grow(&self, store: &mut Store, delta_pages: i64) -> Result> { - self.instance_mut(store)?.grow(delta_pages, true).map_err(Into::into) + let limiter = store.engine.config().resource_limiter.clone(); + let mem = self.instance_mut(store)?; + mem.grow(delta_pages, limiter.as_deref()).map_err(Into::into) } /// Get the current size of the memory in pages. @@ -281,14 +286,14 @@ impl Memory { /// Fill a slice of memory with a value. pub fn fill(&self, store: &mut Store, offset: usize, len: usize, val: u8) -> Result<()> { - self.instance_mut(store)?.inner.fill(offset, len, val)?.ok_or_else(|| { + self.instance_mut(store)?.inner.fill(offset, len, val).ok_or_else(|| { Error::Trap(crate::Trap::MemoryOutOfBounds { offset, len, max: self.instance(store).unwrap().inner.len() }) }) } /// Copies a full slice into memory. pub fn copy_from_slice(&self, store: &mut Store, offset: usize, data: &[u8]) -> Result<()> { - self.instance_mut(store)?.inner.write_all(offset, data)?.ok_or_else(|| { + self.instance_mut(store)?.inner.write_all(offset, data).ok_or_else(|| { Error::Trap(crate::Trap::MemoryOutOfBounds { offset, len: data.len(), @@ -368,8 +373,9 @@ impl Table { return Err(Error::other("host tables cannot use module-relative concrete reference types")); } let init = table_value_to_element(&store.state, ty.element_type, init).map_err(Error::from)?; + let limiter = store.engine.config().resource_limiter.clone(); let addr = store.state.tables.len() as TableAddr; - store.state.tables.push(TableInstance::new(ty, init)?); + store.state.tables.push(TableInstance::new(ty, init, limiter.as_deref())?); Ok(Self(StoreItem::new(store.id(), addr))) } @@ -430,15 +436,23 @@ impl Table { store.state.get_table_mut(self.0.addr).copy_within(dst, src, len) } - /// Grow the table and return the previous size. - pub fn grow(&self, store: &mut Store, delta: i32, init: WasmValue) -> Result { + /// Grows the table and returns the previous size. + /// + /// Returns `None` if growth fails or is rejected by the resource limiter. A limiter-provided + /// trap is returned as an error. + pub fn grow(&self, store: &mut Store, delta: i32, init: WasmValue) -> Result> { self.0.validate_store(store)?; let table = store.state.get_table(self.0.addr); let old_size = table.size(); let init = table_value_to_element(&store.state, table.kind.element_type, init)?; - let delta = usize::try_from(delta).map_err(|_| Trap::TableOutOfBounds { offset: 0, len: 1, max: old_size })?; - store.state.get_table_mut(self.0.addr).grow(delta, init)?; - Ok(old_size) + let Ok(delta) = usize::try_from(delta) else { + return Ok(None); + }; + let limiter = store.engine.config().resource_limiter.clone(); + match store.state.get_table_mut(self.0.addr).grow(delta, init, limiter.as_deref())? { + true => Ok(Some(old_size)), + false => Ok(None), + } } } diff --git a/crates/tinywasm/src/store/memory/instance.rs b/crates/tinywasm/src/store/memory/instance.rs index 68a075b..a075d25 100644 --- a/crates/tinywasm/src/store/memory/instance.rs +++ b/crates/tinywasm/src/store/memory/instance.rs @@ -1,10 +1,8 @@ -use alloc::format; use tinywasm_types::{MemoryArch, MemoryType}; -use crate::{Error, MemoryBackend, Result, Trap}; +use crate::{Error, ResourceLimiter, Result, Trap}; use super::{MemoryStorage, memory_oob}; -use core::hint::cold_path; /// A WebAssembly Memory Instance /// @@ -23,25 +21,17 @@ impl core::fmt::Debug for MemoryInstance { } impl MemoryInstance { - const COPY_CHUNK_SIZE: usize = 4 * 1024; - + #[inline] fn host_size(kind: MemoryType, pages: u64) -> Result { - #[cfg(target_pointer_width = "64")] - { - pages - .checked_mul(kind.page_size()) - .map(|size| size as usize) - .ok_or(Error::UnsupportedFeature("memory size exceeds the host address space")) - } + let size = pages + .checked_mul(kind.page_size()) + .ok_or(Error::UnsupportedFeature("memory size exceeds the host address space"))?; + usize::try_from(size).map_err(|_| Error::UnsupportedFeature("memory size exceeds the host address space")) + } - #[cfg(not(target_pointer_width = "64"))] - { - let page_size = usize::try_from(kind.page_size()) - .map_err(|_| Error::UnsupportedFeature("memory page size exceeds the host address space"))?; - let pages = usize::try_from(pages) - .map_err(|_| Error::UnsupportedFeature("memory size exceeds the host address space"))?; - pages.checked_mul(page_size).ok_or(Error::UnsupportedFeature("memory size exceeds the host address space")) - } + #[inline] + fn maximum_size(kind: MemoryType) -> Option { + kind.page_count_max_declared().map(|pages| Self::host_size(kind, pages).unwrap_or(usize::MAX)) } #[inline(always)] @@ -67,7 +57,7 @@ impl MemoryInstance { } } - pub(crate) fn new(kind: MemoryType, backend: &MemoryBackend) -> Result { + pub(crate) fn new(kind: MemoryType, limiter: Option<&dyn ResourceLimiter>) -> Result { let initial_len = Self::host_size(kind, kind.page_count_initial())?; crate::log::debug!( @@ -76,27 +66,14 @@ impl MemoryInstance { kind.page_size() ); - let storage = backend.create(kind, initial_len)?; - if storage.len() != initial_len { - return Err(Error::Other(format!( - "memory backend returned {} bytes for a memory that requires {initial_len}", - storage.len() - ))); + if initial_len != 0 + && let Some(limiter) = limiter + && !limiter.memory_growing(0, initial_len, Self::maximum_size(kind))? + { + return cold!(Err(Trap::OutOfMemory.into())); } - Ok(Self { kind, inner: storage, page_count: kind.page_count_initial() as usize }) - } - - pub(crate) fn new_lazy(kind: MemoryType, backend: &MemoryBackend) -> Result { - let initial_len = Self::host_size(kind, kind.page_count_initial())?; - - crate::log::debug!( - "initializing lazy memory with {} pages of {} bytes", - kind.page_count_initial(), - kind.page_size() - ); - - let storage = backend.create_lazy(kind, initial_len)?; + let storage = MemoryStorage::try_new(initial_len)?; Ok(Self { kind, inner: storage, page_count: kind.page_count_initial() as usize }) } @@ -111,82 +88,49 @@ impl MemoryInstance { src: usize, len: usize, ) -> Result<(), Trap> { - fn check_range(mem: &MemoryStorage, addr: usize, len: usize) -> Result<(), crate::Trap> { - let Some(end) = addr.checked_add(len) else { - return cold!(Err(memory_oob(addr, len, mem.len()))); - }; - - if end > mem.len() || end < addr { - return cold!(Err(memory_oob(addr, len, mem.len()))); - } - Ok(()) - } - - check_range(&src_memory.inner, src, len)?; - check_range(&self.inner, dst, len)?; - - if len == 0 { - return Ok(()); - } - - let mut buf = [0u8; Self::COPY_CHUNK_SIZE]; - let mut copied = 0; - while copied < len { - let chunk_len = buf.len().min(len - copied); - src_memory.inner.read_exact(src + copied, &mut buf[..chunk_len]).ok_or_else(|| { - cold_path(); - memory_oob(src + copied, chunk_len, src_memory.inner.len()) - })?; - self.inner.write_all(dst + copied, &buf[..chunk_len])?.ok_or_else(|| { - cold_path(); - memory_oob(dst + copied, chunk_len, self.inner.len()) - })?; - copied += chunk_len; - } - + src_memory.inner.checked_range(src, len).ok_or_else(|| cold!(memory_oob(src, len, src_memory.inner.len())))?; + self.inner.checked_range(dst, len).ok_or_else(|| cold!(memory_oob(dst, len, self.inner.len())))?; + self.inner.copy_from(dst, &src_memory.inner, src, len); Ok(()) } pub(crate) fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> Result<(), Trap> { - self.inner.copy_within(dst, src, len)?.ok_or_else(|| { - cold_path(); - memory_oob(dst, len, self.inner.len()) - }) + self.inner.copy_within(dst, src, len).ok_or_else(|| cold!(memory_oob(dst, len, self.inner.len()))) } - pub(crate) fn grow(&mut self, pages_delta: i64, trap_on_oom: bool) -> Result, Trap> { - if pages_delta < 0 { - cold_path(); - crate::log::debug!("memory.grow failed: negative delta {}", pages_delta); - return Ok(None); - } - + pub(crate) fn grow( + &mut self, + pages_delta: i64, + limiter: Option<&dyn ResourceLimiter>, + ) -> Result, Trap> { let current_pages = self.page_count; - let Some(pages_delta) = usize::try_from(pages_delta).ok() else { - return Ok(None); - }; - let Some(new_pages) = current_pages.checked_add(pages_delta) else { - return Ok(None); + let Some(new_pages) = usize::try_from(pages_delta).ok().and_then(|delta| current_pages.checked_add(delta)) + else { + return cold!(Ok(None)); }; let max_pages = self.kind.page_count_max().try_into().unwrap_or(usize::MAX); if new_pages > max_pages { - cold_path(); - crate::log::debug!("memory.grow failed: new_pages={}, max_pages={}", new_pages, max_pages); - return Ok(None); + return cold!({ + crate::log::debug!("memory.grow failed: new_pages={}, max_pages={}", new_pages, max_pages); + Ok(None) + }); } let Ok(new_size) = Self::host_size(self.kind, new_pages as u64) else { - return Ok(None); + return cold!(Ok(None)); }; if new_size == self.inner.len() { return Ok(i64::try_from(current_pages).ok()); } - if let Err(err) = self.inner.grow_to(new_size) { - if trap_on_oom { - return Err(err); - } + if let Some(limiter) = limiter + && !limiter.memory_growing(self.inner.len(), new_size, Self::maximum_size(self.kind))? + { + return cold!(Ok(None)); + } + + if cold_err!(self.inner.grow_to(new_size)).is_err() { return Ok(None); } self.page_count = new_pages; diff --git a/crates/tinywasm/src/store/memory/lazy.rs b/crates/tinywasm/src/store/memory/lazy.rs deleted file mode 100644 index 780d5b5..0000000 --- a/crates/tinywasm/src/store/memory/lazy.rs +++ /dev/null @@ -1,114 +0,0 @@ -use alloc::boxed::Box; - -use tinywasm_types::MemoryType; - -use crate::{Error, MemoryBackend, Result}; - -use super::LinearMemory; - -/// A linear memory wrapper that allocates its backend on the first mutation. -/// -/// Before materialization, the memory is represented by its logical length and -/// reads return the zeroes required by WebAssembly semantics. -pub struct LazyLinearMemory { - ty: MemoryType, - initial_len: usize, - backend: MemoryBackend, - inner: Option>, -} - -impl LazyLinearMemory { - /// Creates a lazy memory for `ty` using `backend` for eventual storage. - pub fn try_new(ty: MemoryType, backend: MemoryBackend) -> Result { - let page_size = usize::try_from(ty.page_size()) - .map_err(|_| Error::UnsupportedFeature("memory page size exceeds the host address space"))?; - let pages = usize::try_from(ty.page_count_initial()) - .map_err(|_| Error::UnsupportedFeature("memory size exceeds the host address space"))?; - let initial_len = pages - .checked_mul(page_size) - .ok_or(Error::UnsupportedFeature("memory size exceeds the host address space"))?; - Ok(Self::new_with_initial_len(ty, initial_len, backend)) - } - - pub(crate) fn new_with_initial_len(ty: MemoryType, initial_len: usize, backend: MemoryBackend) -> Self { - Self { ty, initial_len, backend, inner: None } - } - - fn materialize(&mut self) -> core::result::Result<&mut dyn LinearMemory, crate::Trap> { - if self.inner.is_none() { - let storage = cold_err!(self.backend.create(self.ty, self.initial_len))?; - self.inner = Some(storage); - } - Ok(self.inner.as_deref_mut().expect("lazy memory should be materialized")) - } -} - -impl LinearMemory for LazyLinearMemory { - fn len(&self) -> usize { - self.inner.as_deref().map_or(self.initial_len, LinearMemory::len) - } - - fn grow_to(&mut self, new_len: usize) -> Result<(), crate::Trap> { - self.materialize()?.grow_to(new_len) - } - - fn read(&self, addr: usize, dst: &mut [u8]) -> usize { - if let Some(inner) = self.inner.as_deref() { - return inner.read(addr, dst); - } - if addr >= self.initial_len { - return 0; - } - let read_len = dst.len().min(self.initial_len - addr); - dst[..read_len].fill(0); - read_len - } - - fn write(&mut self, addr: usize, src: &[u8]) -> core::result::Result { - if src.is_empty() || addr >= self.len() { - return Ok(0); - } - self.materialize()?.write(addr, src) - } - - fn write_all(&mut self, addr: usize, src: &[u8]) -> core::result::Result, crate::Trap> { - let Some(end) = addr.checked_add(src.len()) else { return Ok(None) }; - if end > self.len() { - return Ok(None); - } - if src.is_empty() { - return Ok(Some(())); - } - self.materialize()?.write_all(addr, src) - } - - fn fill(&mut self, addr: usize, len: usize, val: u8) -> core::result::Result, crate::Trap> { - let Some(end) = addr.checked_add(len) else { return Ok(None) }; - if end > self.len() { - return Ok(None); - } - if len == 0 || val == 0 && self.inner.is_none() { - return Ok(Some(())); - } - self.materialize()?.fill(addr, len, val) - } - - fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> core::result::Result, crate::Trap> { - let Some(src_end) = src.checked_add(len) else { return Ok(None) }; - let Some(dst_end) = dst.checked_add(len) else { return Ok(None) }; - if src_end > self.len() || dst_end > self.len() { - return Ok(None); - } - if self.inner.is_none() || len == 0 || dst == src { - return Ok(Some(())); - } - self.materialize()?.copy_within(dst, src, len) - } -} - -#[cfg(feature = "debug")] -impl core::fmt::Debug for LazyLinearMemory { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.debug_struct("LazyLinearMemory").field("ty", &self.ty).field("materialized", &self.inner.is_some()).finish() - } -} diff --git a/crates/tinywasm/src/store/memory/mod.rs b/crates/tinywasm/src/store/memory/mod.rs index 70ffb20..24f295b 100644 --- a/crates/tinywasm/src/store/memory/mod.rs +++ b/crates/tinywasm/src/store/memory/mod.rs @@ -1,372 +1,32 @@ -use alloc::{boxed::Box, sync::Arc}; -use alloc::{vec, vec::Vec}; -use core::cmp::min; -use core::hint::cold_path; - -use tinywasm_types::MemoryType; - -use crate::Result; use crate::interpreter::Value128; mod instance; -mod lazy; - -mod paged; -#[path = "vec.rs"] -mod vec_memory; +mod vec; pub(crate) use instance::MemoryInstance; -pub use {lazy::LazyLinearMemory, paged::PagedMemory, vec_memory::VecMemory}; +pub(crate) use vec::VecMemory; -/// Backend storage for a linear memory +/// Internal storage for a linear memory. /// -/// This is a low-level trait that abstracts over the actual storage mechanism for linear memory. -/// This will probably change in the future to allow more efficient implementations. -/// See [`MemoryBackend`] for a higher-level interface to configuring memory storage. -/// The runtime passes slices of the exact indicated width to the fixed-width `write_*` methods. -pub trait LinearMemory { - /// Returns the current memory length in bytes. - fn len(&self) -> usize; - - /// Returns true if the memory is empty. - fn is_empty(&self) -> bool { - self.len() == 0 - } - - /// Grows the memory to `new_len` bytes. - /// - /// The runtime only calls this with lengths that are exact multiples of the Wasm page size for - /// the owning memory. - fn grow_to(&mut self, new_len: usize) -> core::result::Result<(), crate::Trap>; - - /// Reads up to `dst.len()` bytes starting at `addr` and returns the number of bytes read. - /// - /// Backends may return fewer bytes than requested even when more data is available. This lets - /// non-contiguous backends stop at a natural boundary such as the end of a chunk. - fn read(&self, addr: usize, dst: &mut [u8]) -> usize; - - /// Writes up to `src.len()` bytes starting at `addr` and returns the number of bytes written. - /// - /// Backends may return fewer bytes than requested even when more space is available. This lets - /// non-contiguous backends stop at a natural boundary such as the end of a chunk. Backend - /// failures are returned as traps. - fn write(&mut self, addr: usize, src: &[u8]) -> core::result::Result; - - /// Writes all bytes in `src`, returns `Ok(None)` for an invalid range, or returns a backend trap. - fn write_all(&mut self, addr: usize, src: &[u8]) -> core::result::Result, crate::Trap> { - let Some(end) = addr.checked_add(src.len()) else { - return cold!(Ok(None)); - }; - - if end > self.len() { - return cold!(Ok(None)); - } - - let mut offset = 0; - while offset < src.len() { - let written = self.write(addr + offset, &src[offset..])?; - if written == 0 { - return cold!(Ok(None)); - } - offset += written; - } - - Ok(Some(())) - } - - /// Fills the range `[addr, addr + len)` with `val`. - fn fill(&mut self, addr: usize, len: usize, val: u8) -> core::result::Result, crate::Trap> { - let Some(end) = addr.checked_add(len) else { return Ok(None) }; - if end > self.len() { - return Ok(None); - } - - let chunk = [val; 1024]; - let mut offset = 0; - while offset < len { - let chunk_len = min(len - offset, 1024); - if self.write_all(addr + offset, &chunk[..chunk_len])?.is_none() { - return Ok(None); - } - offset += chunk_len; - } - - Ok(Some(())) - } - - /// Copies `len` bytes from `src` to `dst` within the same memory. - fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> core::result::Result, crate::Trap> { - let Some(src_end) = src.checked_add(len) else { return Ok(None) }; - let Some(dst_end) = dst.checked_add(len) else { return Ok(None) }; - if src_end > self.len() || dst_end > self.len() { - return Ok(None); - } - - if len == 0 || dst == src { - return Ok(Some(())); - } - - let mut chunk = [0; 1024]; - - // If the source and destination ranges are disjoint, we can copy forward without a temporary buffer. - if dst < src || dst >= src_end { - let mut offset = 0; - while offset < len { - let chunk_len = min(len - offset, 1024); - if self.read_exact(src + offset, &mut chunk[..chunk_len]).is_none() - || self.write_all(dst + offset, &chunk[..chunk_len])?.is_none() - { - return Ok(None); - } - offset += chunk_len; - } - } else { - // Otherwise, we need to copy backward to avoid overwriting the source data before it's read. - let mut offset = len; - while offset > 0 { - let chunk_len = min(offset, 1024); - offset -= chunk_len; - if self.read_exact(src + offset, &mut chunk[..chunk_len]).is_none() - || self.write_all(dst + offset, &chunk[..chunk_len])?.is_none() - { - return Ok(None); - } - } - } - - Ok(Some(())) - } - - /// Reads exactly `dst.len()` bytes starting at `addr`. - fn read_exact(&self, addr: usize, dst: &mut [u8]) -> Option<()> { - let Some(end) = addr.checked_add(dst.len()) else { - return cold!(None); - }; - - if end > self.len() { - return cold!(None); - } - - let mut offset = 0; - while offset < dst.len() { - let read = self.read(addr + offset, &mut dst[offset..]); - if read == 0 { - return cold!(None); - } - offset += read; - } - - Some(()) - } - - /// Reads `len` bytes starting at `addr` into a newly allocated buffer. - fn read_vec(&self, addr: usize, len: usize) -> Option> { - let end = addr.checked_add(len)?; - if end > self.len() { - return None; - } - - let mut data = vec![0; len]; - self.read_exact(addr, &mut data)?; - Some(data) - } - - /// Reads exactly 1 byte at `addr`. - fn read_8(&self, addr: usize) -> core::result::Result<[u8; 1], crate::Trap> { - let mut bytes = [0; 1]; - self.read_exact(addr, &mut bytes).ok_or_else(|| { - cold_path(); - memory_oob(addr, 1, self.len()) - })?; - Ok(bytes) - } - - /// Reads exactly 2 bytes at `addr`. - fn read_16(&self, addr: usize) -> core::result::Result<[u8; 2], crate::Trap> { - let mut bytes = [0; 2]; - self.read_exact(addr, &mut bytes).ok_or_else(|| { - cold_path(); - memory_oob(addr, 2, self.len()) - })?; - Ok(bytes) - } - - /// Reads exactly 4 bytes at `addr`. - fn read_32(&self, addr: usize) -> core::result::Result<[u8; 4], crate::Trap> { - let mut bytes = [0; 4]; - self.read_exact(addr, &mut bytes).ok_or_else(|| { - cold_path(); - memory_oob(addr, 4, self.len()) - })?; - Ok(bytes) - } - - /// Reads exactly 8 bytes at `addr`. - fn read_64(&self, addr: usize) -> core::result::Result<[u8; 8], crate::Trap> { - let mut bytes = [0; 8]; - self.read_exact(addr, &mut bytes).ok_or_else(|| { - cold_path(); - memory_oob(addr, 8, self.len()) - })?; - Ok(bytes) - } - - /// Reads exactly 16 bytes at `addr`. - fn read_128(&self, addr: usize) -> core::result::Result<[u8; 16], crate::Trap> { - let mut bytes = [0; 16]; - self.read_exact(addr, &mut bytes).ok_or_else(|| { - cold_path(); - memory_oob(addr, 16, self.len()) - })?; - Ok(bytes) - } - - /// Writes exactly 1 byte at `addr`. - fn write_8(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_all(addr, bytes)?.ok_or_else(|| { - cold_path(); - memory_oob(addr, 1, self.len()) - }) - } - - /// Writes exactly 2 bytes at `addr`. - fn write_16(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_all(addr, bytes)?.ok_or_else(|| { - cold_path(); - memory_oob(addr, 2, self.len()) - }) - } - - /// Writes exactly 4 bytes at `addr`. - fn write_32(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_all(addr, bytes)?.ok_or_else(|| { - cold_path(); - memory_oob(addr, 4, self.len()) - }) - } - - /// Writes exactly 8 bytes at `addr`. - fn write_64(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_all(addr, bytes)?.ok_or_else(|| { - cold_path(); - memory_oob(addr, 8, self.len()) - }) - } - - /// Writes exactly 16 bytes at `addr`. - fn write_128(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_all(addr, bytes)?.ok_or_else(|| { - cold_path(); - memory_oob(addr, 16, self.len()) - }) - } -} - -type MemoryFactory = dyn Fn(MemoryType) -> core::result::Result, crate::Trap> + Send + Sync; - -/// Configures how runtime memory instances are created. -#[derive(Clone, Default)] -pub struct MemoryBackend(MemoryBackendInner); - -#[derive(Clone, Default)] -enum MemoryBackendInner { - #[default] - Vec, - Paged { - chunk_size: usize, - }, - Custom(Arc), -} - -impl MemoryBackend { - /// Uses a contiguous [`VecMemory`] for each memory instance. - /// - /// This is usually the fastest option for reads and writes, but large grows can be expensive - /// because they may reallocate and copy the entire buffer. - pub const fn vec() -> Self { - Self(MemoryBackendInner::Vec) - } - - /// Uses sparse chunked storage for each memory instance. - /// - /// `chunk_size` is the backend chunk size in bytes. It must be a non-zero power - /// of two and is independent from the Wasm page size. - /// - /// This generally makes growth cheaper than [`Self::vec`], but read and write operations do a - /// little more work and may be slightly slower. - pub fn paged(chunk_size: usize) -> Self { - assert!(chunk_size.is_power_of_two(), "chunk_size must be a non-zero power of two"); - Self(MemoryBackendInner::Paged { chunk_size }) - } - - /// Uses a custom factory to create memory instances. - /// - /// Factory traps are returned during eager creation or when a lazy memory first materializes. - pub fn custom(factory: F) -> Self - where - F: Fn(MemoryType) -> core::result::Result + Send + Sync + 'static, - M: LinearMemory + 'static, - { - Self(MemoryBackendInner::Custom(Arc::new(move |ty| { - let memory = factory(ty)?; - Ok(Box::new(memory) as Box) - }))) - } - - pub(crate) fn create( - &self, - ty: MemoryType, - initial_len: usize, - ) -> core::result::Result { - let storage = match &self.0 { - MemoryBackendInner::Vec => Box::new(VecMemory::try_new(initial_len)?) as Box, - MemoryBackendInner::Paged { chunk_size } => { - Box::new(PagedMemory::try_new(initial_len, *chunk_size)?) as Box - } - MemoryBackendInner::Custom(factory) => factory(ty)?, - }; - - if storage.len() < initial_len { - return Err(crate::Trap::Other("memory backend returned less storage than required")); - } - - Ok(storage) - } - - pub(crate) fn create_lazy(&self, ty: MemoryType, initial_len: usize) -> Result { - Ok(Box::new(LazyLinearMemory::new_with_initial_len(ty, initial_len, self.clone()))) - } -} - -#[cfg(feature = "debug")] -impl core::fmt::Debug for MemoryBackend { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match &self.0 { - MemoryBackendInner::Vec => f.debug_tuple("MemoryBackend::Vec").finish(), - MemoryBackendInner::Paged { chunk_size } => { - f.debug_struct("MemoryBackend::Paged").field("chunk_size", chunk_size).finish() - } - MemoryBackendInner::Custom(_) => f.debug_tuple("MemoryBackend::Custom").finish(), - } - } -} - -pub(crate) type MemoryStorage = Box; +/// This is the boundary between the interpreter and the backing representation. Keeping it a +/// concrete type selected at compile time means the executor's load and store paths stay the same +/// whether the memory is `Vec`-backed or, later, mmap-backed. +pub(crate) type MemoryStorage = VecMemory; -/// A trait for types that can be converted to and from static byte arrays +/// A trait for types that can be converted to and from static byte arrays. pub(crate) trait MemValue: Copy + Default { - /// Store a value in memory + /// Store a value in memory. fn to_mem_bytes(self) -> [u8; N]; fn from_mem_bytes(bytes: [u8; N]) -> Self; - fn load_at(mem: &dyn LinearMemory, addr: usize) -> core::result::Result; + fn load_at(mem: &MemoryStorage, addr: usize) -> core::result::Result; - fn store_at(self, mem: &mut dyn LinearMemory, addr: usize) -> core::result::Result<(), crate::Trap>; + fn store_at(self, mem: &mut MemoryStorage, addr: usize) -> core::result::Result<(), crate::Trap>; } macro_rules! impl_mem_traits { - ($($ty:ty, $size:expr, $read:ident, $write:ident),* $(,)?) => { + ($($ty:ty, $size:expr),* $(,)?) => { $( impl MemValue<$size> for $ty { #[inline(always)] @@ -380,28 +40,20 @@ macro_rules! impl_mem_traits { } #[inline(always)] - fn load_at(mem: &dyn LinearMemory, addr: usize) -> core::result::Result { - Ok(Self::from_le_bytes(cold_err!(mem.$read(addr))?)) + fn load_at(mem: &MemoryStorage, addr: usize) -> core::result::Result { + Ok(Self::from_le_bytes(cold_err!(mem.read_fixed::<$size>(addr))?)) } #[inline(always)] - fn store_at( - self, - mem: &mut dyn LinearMemory, - addr: usize, - ) -> core::result::Result<(), crate::Trap> { - mem.$write(addr, &self.to_mem_bytes()) + fn store_at(self, mem: &mut MemoryStorage, addr: usize) -> core::result::Result<(), crate::Trap> { + mem.write_fixed::<$size>(addr, &self.to_mem_bytes()) } } )* }; } -impl_mem_traits!( - u8, 1, read_8, write_8, i8, 1, read_8, write_8, u16, 2, read_16, write_16, i16, 2, read_16, write_16, u32, 4, - read_32, write_32, i32, 4, read_32, write_32, f32, 4, read_32, write_32, u64, 8, read_64, write_64, i64, 8, - read_64, write_64, f64, 8, read_64, write_64 -); +impl_mem_traits!(u8, 1, i8, 1, u16, 2, i16, 2, u32, 4, i32, 4, f32, 4, u64, 8, i64, 8, f64, 8); impl MemValue<16> for Value128 { #[inline(always)] @@ -415,13 +67,13 @@ impl MemValue<16> for Value128 { } #[inline(always)] - fn load_at(mem: &dyn LinearMemory, addr: usize) -> core::result::Result { - Ok(Self(cold_err!(mem.read_128(addr))?)) + fn load_at(mem: &MemoryStorage, addr: usize) -> core::result::Result { + Ok(Self(cold_err!(mem.read_fixed::<16>(addr))?)) } #[inline(always)] - fn store_at(self, mem: &mut dyn LinearMemory, addr: usize) -> core::result::Result<(), crate::Trap> { - mem.write_128(addr, &self.0) + fn store_at(self, mem: &mut MemoryStorage, addr: usize) -> core::result::Result<(), crate::Trap> { + mem.write_fixed::<16>(addr, &self.0) } } diff --git a/crates/tinywasm/src/store/memory/paged.rs b/crates/tinywasm/src/store/memory/paged.rs deleted file mode 100644 index 3e6e5ea..0000000 --- a/crates/tinywasm/src/store/memory/paged.rs +++ /dev/null @@ -1,368 +0,0 @@ -use alloc::boxed::Box; -use alloc::vec::Vec; -use core::cmp::min; -use core::hint::cold_path; - -use super::{LinearMemory, memory_oob}; - -/// A sparse chunked linear memory. -/// -/// This backend stores memory in fixed-size chunks, which makes growth cheaper because it avoids -/// resizing and copying one large contiguous buffer. -/// -/// The tradeoff is that reads and writes do a bit more bookkeeping and may need to cross chunk -/// boundaries, so they are usually slightly slower than [`super::VecMemory`]. -/// -/// In particular, [`LinearMemory::read`] and [`LinearMemory::write`] return at most the bytes up to -/// the end of the current chunk. Higher-level exact helpers loop over these short operations when -/// they need a full range. -pub struct PagedMemory { - len: usize, - chunk_size: usize, - chunk_shift: u32, - chunk_mask: usize, - chunks: Vec>>, -} - -impl PagedMemory { - /// Tries to create a new sparse memory with `len` addressable bytes and the given `chunk_size`. - /// - /// Prefer this backend when grow behavior matters more than absolute read and write speed. - pub fn try_new(len: usize, chunk_size: usize) -> Result { - assert!(chunk_size.is_power_of_two(), "chunk_size must be a power of two"); - - let mut memory = Self { - len: 0, - chunk_size, - chunk_shift: chunk_size.trailing_zeros(), - chunk_mask: chunk_size - 1, - chunks: Vec::new(), - }; - memory.grow_to(len)?; - Ok(memory) - } - - #[inline(always)] - fn allocate_chunk(&self) -> Result, crate::Trap> { - let mut chunk = Vec::new(); - cold_err!(chunk.try_reserve_exact(self.chunk_size)).map_err(|_| crate::Trap::OutOfMemory)?; - chunk.resize(self.chunk_size, 0); - Ok(chunk.into_boxed_slice()) - } - - #[inline(always)] - fn chunk_mut(&mut self, chunk_idx: usize) -> Result<&mut [u8], crate::Trap> { - if self.chunks[chunk_idx].is_none() { - self.chunks[chunk_idx] = Some(self.allocate_chunk()?); - } - - Ok(self.chunks[chunk_idx].as_deref_mut().unwrap_or_else(|| unreachable!())) - } - - #[inline(always)] - fn chunk_slice(&self, chunk_idx: usize) -> Option<&[u8]> { - self.chunks[chunk_idx].as_deref() - } - - #[inline(always)] - fn read_fixed(&self, addr: usize) -> Result<[u8; N], crate::Trap> { - let Some(end) = addr.checked_add(N).filter(|end| *end <= self.len) else { - return cold!(Err(memory_oob(addr, N, self.len))); - }; - let chunk_idx = addr >> self.chunk_shift; - let chunk_offset = addr & self.chunk_mask; - if end <= ((chunk_idx + 1) << self.chunk_shift) { - let mut bytes = [0; N]; - if let Some(chunk) = self.chunk_slice(chunk_idx) { - bytes.copy_from_slice(&chunk[chunk_offset..chunk_offset + N]); - } - return Ok(bytes); - } - cold_path(); - let mut bytes = [0; N]; - self.read_exact(addr, &mut bytes).ok_or_else(|| memory_oob(addr, N, self.len))?; - Ok(bytes) - } - - #[inline(always)] - fn write_fixed(&mut self, addr: usize, bytes: &[u8]) -> Result<(), crate::Trap> { - let Some(end) = addr.checked_add(N).filter(|end| *end <= self.len) else { - return cold!(Err(memory_oob(addr, N, self.len))); - }; - let chunk_idx = addr >> self.chunk_shift; - let chunk_offset = addr & self.chunk_mask; - if end <= ((chunk_idx + 1) << self.chunk_shift) { - self.chunk_mut(chunk_idx)?[chunk_offset..chunk_offset + N].copy_from_slice(bytes); - return Ok(()); - } - cold_path(); - self.write_all(addr, bytes)?.ok_or_else(|| memory_oob(addr, N, self.len)) - } - - #[inline(always)] - fn checked_end(&self, addr: usize, len: usize) -> Option { - let end = addr.checked_add(len)?; - if end > self.len { - return None; - } - Some(end) - } - - #[inline(always)] - fn copy_within_single_chunk(&mut self, dst: usize, src: usize, len: usize) -> bool { - if len == 0 { - return true; - } - - if self.checked_end(src, len).is_none() || self.checked_end(dst, len).is_none() { - return false; - } - - let src_chunk_idx = src >> self.chunk_shift; - let dst_chunk_idx = dst >> self.chunk_shift; - if src_chunk_idx != dst_chunk_idx { - return false; - } - - let src_offset = src & self.chunk_mask; - let dst_offset = dst & self.chunk_mask; - if src_offset + len > self.chunk_size || dst_offset + len > self.chunk_size { - return false; - } - - if let Some(Some(chunk)) = self.chunks.get_mut(src_chunk_idx) { - chunk.copy_within(src_offset..src_offset + len, dst_offset); - } - - true - } -} - -#[cfg(feature = "debug")] -impl core::fmt::Debug for PagedMemory { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - let allocated_chunks = self.chunks.iter().filter(|chunk| chunk.is_some()).count(); - f.debug_struct("PagedMemory") - .field("len", &self.len) - .field("chunk_size", &self.chunk_size) - .field("allocated_chunks", &allocated_chunks) - .finish() - } -} - -impl LinearMemory for PagedMemory { - #[inline(always)] - fn len(&self) -> usize { - self.len - } - - #[inline(always)] - fn grow_to(&mut self, new_len: usize) -> Result<(), crate::Trap> { - if new_len < self.len { - return Err(crate::Trap::MemoryOutOfBounds { offset: new_len, len: 0, max: self.len }); - } - - let new_chunk_count = if new_len == 0 { 0 } else { new_len.div_ceil(self.chunk_size) }; - if new_chunk_count > self.chunks.len() { - cold_err!(self.chunks.try_reserve_exact(new_chunk_count - self.chunks.len())) - .map_err(|_| crate::Trap::OutOfMemory)?; - self.chunks.resize_with(new_chunk_count, || None); - } else { - self.chunks.truncate(new_chunk_count); - } - - self.len = new_len; - Ok(()) - } - - #[inline(always)] - fn read(&self, addr: usize, dst: &mut [u8]) -> usize { - if addr >= self.len || dst.is_empty() { - return 0; - } - - let chunk_idx = addr >> self.chunk_shift; - let chunk_offset = addr & self.chunk_mask; - let chunk_end = min((chunk_idx + 1) << self.chunk_shift, self.len); - let read_len = min(chunk_end - addr, dst.len()); - if let Some(chunk) = self.chunk_slice(chunk_idx) { - dst[..read_len].copy_from_slice(&chunk[chunk_offset..chunk_offset + read_len]); - } else { - dst[..read_len].fill(0); - } - - read_len - } - - #[inline(always)] - fn write(&mut self, addr: usize, src: &[u8]) -> Result { - if addr >= self.len || src.is_empty() { - return Ok(0); - } - - let chunk_idx = addr >> self.chunk_shift; - let chunk_offset = addr & self.chunk_mask; - let write_len = min(min(self.chunk_size - chunk_offset, self.len - addr), src.len()); - - let chunk = self.chunk_mut(chunk_idx)?; - chunk[chunk_offset..chunk_offset + write_len].copy_from_slice(&src[..write_len]); - Ok(write_len) - } - - #[inline(always)] - fn write_all(&mut self, addr: usize, src: &[u8]) -> Result, crate::Trap> { - let Some(end) = self.checked_end(addr, src.len()) else { return Ok(None) }; - let mut pos = addr; - let mut src_offset = 0; - - while pos < end { - let chunk_idx = pos >> self.chunk_shift; - let chunk_offset = pos & self.chunk_mask; - let copy_len = min(self.chunk_size - chunk_offset, end - pos); - - let chunk = self.chunk_mut(chunk_idx)?; - chunk[chunk_offset..chunk_offset + copy_len].copy_from_slice(&src[src_offset..src_offset + copy_len]); - - pos += copy_len; - src_offset += copy_len; - } - - Ok(Some(())) - } - - #[inline(always)] - fn fill(&mut self, addr: usize, len: usize, val: u8) -> Result, crate::Trap> { - let Some(end) = self.checked_end(addr, len) else { return Ok(None) }; - let mut pos = addr; - - while pos < end { - let chunk_idx = pos >> self.chunk_shift; - let chunk_offset = pos & self.chunk_mask; - let chunk_start = chunk_idx << self.chunk_shift; - let chunk_full_len = min(self.chunk_size, self.len - chunk_start); - let chunk_end = min(chunk_start + self.chunk_size, end); - let fill_len = chunk_end - pos; - - if val == 0 { - if chunk_offset == 0 && fill_len == chunk_full_len { - self.chunks[chunk_idx] = None; - } else if let Some(Some(chunk)) = self.chunks.get_mut(chunk_idx) { - chunk[chunk_offset..chunk_offset + fill_len].fill(0); - } - } else { - self.chunk_mut(chunk_idx)?[chunk_offset..chunk_offset + fill_len].fill(val); - } - - pos = chunk_end; - } - - Ok(Some(())) - } - - #[inline(always)] - fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> Result, crate::Trap> { - if self.checked_end(src, len).is_none() || self.checked_end(dst, len).is_none() { - return Ok(None); - } - - if len == 0 || dst == src { - return Ok(Some(())); - } - - if self.copy_within_single_chunk(dst, src, len) { - return Ok(Some(())); - } - - let mut buf = [0u8; 256]; - - if dst < src || dst >= src + len { - let mut copied = 0; - while copied < len { - let chunk_len = min(buf.len(), len - copied); - if self.read_exact(src + copied, &mut buf[..chunk_len]).is_none() - || self.write_all(dst + copied, &buf[..chunk_len])?.is_none() - { - return Ok(None); - } - copied += chunk_len; - } - } else { - let mut remaining = len; - while remaining > 0 { - let chunk_len = min(buf.len(), remaining); - let chunk_start = remaining - chunk_len; - if self.read_exact(src + chunk_start, &mut buf[..chunk_len]).is_none() - || self.write_all(dst + chunk_start, &buf[..chunk_len])?.is_none() - { - return Ok(None); - } - remaining = chunk_start; - } - } - - Ok(Some(())) - } - - #[inline(always)] - fn read_8(&self, addr: usize) -> core::result::Result<[u8; 1], crate::Trap> { - if addr >= self.len { - cold_path(); - return Err(memory_oob(addr, 1, self.len)); - } - let chunk_idx = addr >> self.chunk_shift; - let chunk_offset = addr & self.chunk_mask; - Ok([self.chunk_slice(chunk_idx).map_or(0, |chunk| chunk[chunk_offset])]) - } - - #[inline(always)] - fn read_16(&self, addr: usize) -> core::result::Result<[u8; 2], crate::Trap> { - self.read_fixed::<2>(addr) - } - - #[inline(always)] - fn read_32(&self, addr: usize) -> core::result::Result<[u8; 4], crate::Trap> { - self.read_fixed::<4>(addr) - } - - #[inline(always)] - fn read_64(&self, addr: usize) -> core::result::Result<[u8; 8], crate::Trap> { - self.read_fixed::<8>(addr) - } - - #[inline(always)] - fn read_128(&self, addr: usize) -> core::result::Result<[u8; 16], crate::Trap> { - self.read_fixed::<16>(addr) - } - - #[inline(always)] - fn write_8(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - if addr >= self.len { - cold_path(); - return Err(memory_oob(addr, 1, self.len)); - } - let chunk_idx = addr >> self.chunk_shift; - let chunk_offset = addr & self.chunk_mask; - self.chunk_mut(chunk_idx)?[chunk_offset] = bytes[0]; - Ok(()) - } - - #[inline(always)] - fn write_16(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_fixed::<2>(addr, bytes) - } - - #[inline(always)] - fn write_32(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_fixed::<4>(addr, bytes) - } - - #[inline(always)] - fn write_64(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_fixed::<8>(addr, bytes) - } - - #[inline(always)] - fn write_128(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.write_fixed::<16>(addr, bytes) - } -} diff --git a/crates/tinywasm/src/store/memory/vec.rs b/crates/tinywasm/src/store/memory/vec.rs index be85e9b..98c24d6 100644 --- a/crates/tinywasm/src/store/memory/vec.rs +++ b/crates/tinywasm/src/store/memory/vec.rs @@ -1,24 +1,20 @@ use alloc::vec::Vec; +use core::ops::Range; -use super::{LinearMemory, memory_oob}; +use super::memory_oob; -/// A contiguous `Vec`-backed linear memory. +/// A contiguous `Vec`-backed linear memory storage. /// -/// This is the simplest backend and typically gives the best read and write throughput because -/// the whole memory lives in one contiguous allocation. -/// -/// The tradeoff is growth cost: large grows may need to reallocate and copy the full buffer, -/// which can get expensive for large memories. -#[cfg_attr(feature = "debug", derive(Debug))] -pub struct VecMemory { +/// This is the internal storage boundary for [`super::MemoryInstance`]. Keeping it a concrete type +/// rather than a `Vec` directly means the backing representation can later be swapped for an +/// mmap-backed implementation without touching the interpreter's load and store paths. +pub(crate) struct VecMemory { data: Vec, } impl VecMemory { /// Tries to create a new memory with `len` zero-initialized bytes. - /// - /// Prefer this backend when contiguous access is more important than grow performance. - pub fn try_new(len: usize) -> Result { + pub(crate) fn try_new(len: usize) -> Result { let mut data = Vec::new(); cold_err!(data.try_reserve_exact(len)).map_err(|_| crate::Trap::OutOfMemory)?; data.resize(len, 0); @@ -26,11 +22,24 @@ impl VecMemory { } #[inline(always)] - fn read_fixed(&self, addr: usize) -> Result<[u8; N], crate::Trap> { - self.check_fixed_addr::(addr)?; - let mut bytes = [0u8; N]; - bytes.copy_from_slice(&self.data[addr..addr + N]); - Ok(bytes) + pub(crate) fn len(&self) -> usize { + self.data.len() + } + + #[inline(always)] + pub(super) fn checked_range(&self, addr: usize, len: usize) -> Option> { + let end = addr.checked_add(len)?; + (end <= self.data.len()).then_some(addr..end) + } + + /// Grows the backing allocation to `new_len`. Only called after the Wasm limits and any user + /// limiter have accepted the grow. + #[inline(always)] + pub(crate) fn grow_to(&mut self, new_len: usize) -> Result<(), crate::Trap> { + debug_assert!(new_len >= self.data.len(), "memory only grows"); + cold_err!(self.data.try_reserve_exact(new_len - self.data.len())).map_err(|_| crate::Trap::OutOfMemory)?; + self.data.resize(new_len, 0); + Ok(()) } #[inline(always)] @@ -40,27 +49,27 @@ impl VecMemory { } Ok(()) } -} -impl LinearMemory for VecMemory { + /// Reads exactly `N` bytes at `addr` into a fixed-size array. #[inline(always)] - fn len(&self) -> usize { - self.data.len() + pub(crate) fn read_fixed(&self, addr: usize) -> Result<[u8; N], crate::Trap> { + self.check_fixed_addr::(addr)?; + let mut bytes = [0u8; N]; + bytes.copy_from_slice(&self.data[addr..addr + N]); + Ok(bytes) } + /// Writes exactly `N` bytes from `bytes` at `addr`. #[inline(always)] - fn grow_to(&mut self, new_len: usize) -> Result<(), crate::Trap> { - if new_len < self.data.len() { - return Err(crate::Trap::MemoryOutOfBounds { offset: new_len, len: 0, max: self.data.len() }); - } - cold_err!(self.data.try_reserve_exact(new_len.saturating_sub(self.data.len()))) - .map_err(|_| crate::Trap::OutOfMemory)?; - self.data.resize(new_len, 0); + pub(crate) fn write_fixed(&mut self, addr: usize, bytes: &[u8; N]) -> Result<(), crate::Trap> { + self.check_fixed_addr::(addr)?; + self.data[addr..addr + N].copy_from_slice(bytes); Ok(()) } + /// Reads up to `dst.len()` bytes starting at `addr` and returns the number of bytes read. #[inline(always)] - fn read(&self, addr: usize, dst: &mut [u8]) -> usize { + pub(crate) fn read(&self, addr: usize, dst: &mut [u8]) -> usize { if addr >= self.data.len() { return 0; } @@ -69,114 +78,60 @@ impl LinearMemory for VecMemory { read_len } + /// Writes up to `src.len()` bytes starting at `addr` and returns the number of bytes written. #[inline(always)] - fn read_exact(&self, addr: usize, dst: &mut [u8]) -> Option<()> { - dst.copy_from_slice(self.data.get(addr..addr.checked_add(dst.len())?)?); - Some(()) - } - - #[inline(always)] - fn read_vec(&self, addr: usize, len: usize) -> Option> { - Some(self.data.get(addr..addr.checked_add(len)?)?.to_vec()) - } - - #[inline(always)] - fn write(&mut self, addr: usize, src: &[u8]) -> Result { + pub(crate) fn write(&mut self, addr: usize, src: &[u8]) -> usize { if addr >= self.data.len() { - return Ok(0); + return 0; } - let write_len = src.len().min(self.data.len() - addr); self.data[addr..addr + write_len].copy_from_slice(&src[..write_len]); - Ok(write_len) + write_len } + /// Reads exactly `dst.len()` bytes starting at `addr`, returning `None` for an invalid range. #[inline(always)] - fn write_all(&mut self, addr: usize, src: &[u8]) -> Result, crate::Trap> { - let Some(end) = addr.checked_add(src.len()) else { return Ok(None) }; - let Some(dst) = self.data.get_mut(addr..end) else { return Ok(None) }; - dst.copy_from_slice(src); - Ok(Some(())) - } - - #[inline(always)] - fn fill(&mut self, addr: usize, len: usize, val: u8) -> Result, crate::Trap> { - let Some(end) = addr.checked_add(len) else { return Ok(None) }; - let Some(dst) = self.data.get_mut(addr..end) else { return Ok(None) }; - dst.fill(val); - Ok(Some(())) - } - - #[inline(always)] - fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> Result, crate::Trap> { - let Some(src_end) = src.checked_add(len) else { return Ok(None) }; - let Some(dst_end) = dst.checked_add(len) else { return Ok(None) }; - if src_end > self.data.len() || dst_end > self.data.len() { - return Ok(None); - } - - self.data.copy_within(src..src_end, dst); - Ok(Some(())) - } - - #[inline(always)] - fn read_8(&self, addr: usize) -> core::result::Result<[u8; 1], crate::Trap> { - self.check_fixed_addr::<1>(addr)?; - Ok([self.data[addr]]) - } - - #[inline(always)] - fn read_16(&self, addr: usize) -> core::result::Result<[u8; 2], crate::Trap> { - self.read_fixed::<2>(addr) - } - - #[inline(always)] - fn read_32(&self, addr: usize) -> core::result::Result<[u8; 4], crate::Trap> { - self.read_fixed::<4>(addr) - } - - #[inline(always)] - fn read_64(&self, addr: usize) -> core::result::Result<[u8; 8], crate::Trap> { - self.read_fixed::<8>(addr) - } - - #[inline(always)] - fn read_128(&self, addr: usize) -> core::result::Result<[u8; 16], crate::Trap> { - self.read_fixed::<16>(addr) + pub(crate) fn read_exact(&self, addr: usize, dst: &mut [u8]) -> Option<()> { + dst.copy_from_slice(&self.data[self.checked_range(addr, dst.len())?]); + Some(()) } + /// Reads `len` bytes starting at `addr` into a newly allocated buffer, returning `None` for an + /// invalid range. #[inline(always)] - fn write_8(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.check_fixed_addr::<1>(addr)?; - self.data[addr] = bytes[0]; - Ok(()) + pub(crate) fn read_vec(&self, addr: usize, len: usize) -> Option> { + Some(self.data[self.checked_range(addr, len)?].to_vec()) } + /// Writes all of `src` at `addr`, returning `None` for an invalid range. #[inline(always)] - fn write_16(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.check_fixed_addr::<2>(addr)?; - self.data[addr..addr + 2].copy_from_slice(bytes); - Ok(()) + pub(crate) fn write_all(&mut self, addr: usize, src: &[u8]) -> Option<()> { + let range = self.checked_range(addr, src.len())?; + self.data[range].copy_from_slice(src); + Some(()) } + /// Fills the range `[addr, addr + len)` with `val`, returning `None` for an invalid range. #[inline(always)] - fn write_32(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.check_fixed_addr::<4>(addr)?; - self.data[addr..addr + 4].copy_from_slice(bytes); - Ok(()) + pub(crate) fn fill(&mut self, addr: usize, len: usize, val: u8) -> Option<()> { + let range = self.checked_range(addr, len)?; + self.data[range].fill(val); + Some(()) } + /// Copies `len` bytes from `src` to `dst` within the memory, returning `None` for an invalid + /// range. #[inline(always)] - fn write_64(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.check_fixed_addr::<8>(addr)?; - self.data[addr..addr + 8].copy_from_slice(bytes); - Ok(()) + pub(crate) fn copy_within(&mut self, dst: usize, src: usize, len: usize) -> Option<()> { + let src = self.checked_range(src, len)?; + self.checked_range(dst, len)?; + self.data.copy_within(src, dst); + Some(()) } + /// Copies a previously checked range from another memory. #[inline(always)] - fn write_128(&mut self, addr: usize, bytes: &[u8]) -> core::result::Result<(), crate::Trap> { - self.check_fixed_addr::<16>(addr)?; - self.data[addr..addr + 16].copy_from_slice(bytes); - Ok(()) + pub(super) fn copy_from(&mut self, dst: usize, src_memory: &Self, src: usize, len: usize) { + self.data[dst..dst + len].copy_from_slice(&src_memory.data[src..src + len]); } } diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 33a549c..f0e426f 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -23,7 +23,6 @@ mod types; use const_expr::eval_const; pub(crate) use gc::{decode_data, default_value, pop_value, push_value}; -pub use memory::{LazyLinearMemory, LinearMemory, MemoryBackend, PagedMemory, VecMemory}; pub(crate) use memory::{MemValue, MemoryInstance}; pub(crate) use state::State; pub(crate) use types::{canonicalize_ref_type, canonicalize_value_type}; @@ -32,12 +31,72 @@ pub(crate) use {data::*, element::*, exception::*, function::*, global::*, table // global store id counter static STORE_ID: AtomicU32 = AtomicU32::new(0); -/// Global state that can be manipulated by WebAssembly programs +/// Controls resource usage by WebAssembly instances. /// -/// Managed WebAssembly GC objects are collected automatically. Other Store -/// instances, such as modules, functions, memories, and tables, live until the -/// Store is dropped. GC references exposed through the copyable host value API -/// are retained for the Store's lifetime. +/// Configure a limiter with +/// [`Config::with_resource_limiter`](crate::engine::Config::with_resource_limiter). It currently +/// controls guest linear-memory and table allocation and growth. It does not account for stacks, +/// GC storage, runtime metadata, or other host allocations. +/// +/// # Example +/// ```rust +/// use std::sync::Arc; +/// use tinywasm::engine::Config; +/// use tinywasm::types::{MemoryArch, MemoryType}; +/// use tinywasm::{Engine, Memory, ResourceLimiter, Store}; +/// +/// struct MemoryLimit(usize); +/// +/// impl ResourceLimiter for MemoryLimit { +/// fn memory_growing( +/// &self, +/// _current: usize, +/// desired: usize, +/// _maximum: Option, +/// ) -> Result { +/// Ok(desired <= self.0) +/// } +/// } +/// +/// let config = Config::new().with_resource_limiter(Arc::new(MemoryLimit(64 * 1024))); +/// let mut store = Store::new(Engine::new(config)); +/// let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?; +/// assert_eq!(memory.grow(&mut store, 1)?, None); +/// # Ok::<(), tinywasm::Error>(()) +/// ``` +pub trait ResourceLimiter: Send + Sync { + /// Returns whether a memory allocation or growth is allowed. + /// + /// Sizes are in bytes. `current` is zero for initial allocation, and `maximum` is `None` for an + /// unbounded memory. `Ok(false)` rejects the request, while `Err` traps. Rejected initial + /// allocations return [`Trap::OutOfMemory`], since they have no normal failure result. The + /// default implementation allows the request. + fn memory_growing( + &self, + _current: usize, + _desired: usize, + _maximum: Option, + ) -> core::result::Result { + Ok(true) + } + + /// Returns whether a table allocation or growth is allowed. + /// + /// Sizes are in elements. `current` is zero for initial allocation, and `maximum` is `None` for + /// an unbounded table. `Ok(false)` rejects the request, while `Err` traps. Rejected initial + /// allocations return [`Trap::OutOfMemory`], since they have no normal failure result. The + /// default implementation allows the request. + fn table_growing( + &self, + _current: usize, + _desired: usize, + _maximum: Option, + ) -> core::result::Result { + Ok(true) + } +} + +/// Runtime state used by WebAssembly instances and host functions. /// /// ## Example /// ```rust @@ -240,6 +299,7 @@ impl Store { type_addrs: &[TypeAddr], ) -> Result> { let start = self.state.tables.len() as TableAddr; + let limiter = self.engine.config().resource_limiter.clone(); self.state.tables.reserve_exact(tables.len()); for table in tables { let init = match &table.init { @@ -254,7 +314,7 @@ impl Store { MemoryArch::I32 => TableType::new(element_type, table.ty.size_initial, table.ty.size_max), MemoryArch::I64 => TableType::new64(element_type, table.ty.size_initial, table.ty.size_max), }; - self.state.tables.push(TableInstance::new(ty, init)?); + self.state.tables.push(TableInstance::new(ty, init, limiter.as_deref())?); } Ok(start..start + tables.len() as TableAddr) } @@ -263,12 +323,12 @@ impl Store { pub(crate) fn init_memories( &mut self, memories: &[MemoryType], - init: impl Fn(MemoryType, &MemoryBackend) -> Result, + init: impl Fn(MemoryType) -> Result, ) -> Result> { let start = self.state.memories.len() as MemAddr; self.state.memories.reserve_exact(memories.len()); for mem in memories { - self.state.memories.push(cold_err!(init(*mem, &self.engine.config().memory_backend))?); + self.state.memories.push(cold_err!(init(*mem))?); } Ok(start..start + memories.len() as MemAddr) } @@ -428,7 +488,7 @@ impl Store { }; let offset = usize::try_from(offset).unwrap_or(usize::MAX); - match mem.inner.write_all(offset, &data.data)? { + match mem.inner.write_all(offset, &data.data) { Some(()) => None, None => { return Ok(( diff --git a/crates/tinywasm/src/store/table.rs b/crates/tinywasm/src/store/table.rs index 8e6c055..da52660 100644 --- a/crates/tinywasm/src/store/table.rs +++ b/crates/tinywasm/src/store/table.rs @@ -1,4 +1,4 @@ -use crate::{Result, Trap, interpreter::ValueRef}; +use crate::{ResourceLimiter, Result, Trap, interpreter::ValueRef}; use alloc::vec::Vec; use core::ops::Range; use tinywasm_types::*; @@ -16,11 +16,17 @@ pub(crate) struct TableInstance { impl TableInstance { /// Creates a table filled with the given initial reference. - pub(crate) fn new(kind: TableType, init: ValueRef) -> Result { + pub(crate) fn new(kind: TableType, init: ValueRef, limiter: Option<&dyn ResourceLimiter>) -> Result { let size = cold_err!(usize::try_from(kind.size_initial)).map_err(|_| Trap::OutOfMemory)?; if size > MAX_TABLE_SIZE { return Err(Trap::OutOfMemory.into()); } + if size != 0 + && let Some(limiter) = limiter + && !limiter.table_growing(0, size, Self::maximum_size(kind))? + { + return Err(Trap::OutOfMemory.into()); + } let mut elements = Vec::new(); cold_err!(elements.try_reserve_exact(size)).map_err(|_| Trap::OutOfMemory)?; elements.resize(size, init); @@ -74,17 +80,38 @@ impl TableInstance { Ok(()) } - pub(crate) fn grow(&mut self, n: usize, init: ValueRef) -> Result<(), Trap> { - let len = n.checked_add(self.elements.len()).ok_or(Trap::OutOfMemory)?; + pub(crate) fn grow( + &mut self, + n: usize, + init: ValueRef, + limiter: Option<&dyn ResourceLimiter>, + ) -> Result { + let Some(len) = n.checked_add(self.elements.len()) else { + return Ok(false); + }; let declared_max = self.kind.size_max.and_then(|max| usize::try_from(max).ok()).unwrap_or(usize::MAX); let max = declared_max.min(MAX_TABLE_SIZE); if len > max { - return Err(crate::Trap::TableOutOfBounds { offset: len, len: 1, max: self.elements.len() }); + return Ok(false); + } + if len == self.elements.len() { + return Ok(true); + } + if let Some(limiter) = limiter + && !limiter.table_growing(self.elements.len(), len, Self::maximum_size(self.kind))? + { + return Ok(false); } - cold_err!(self.elements.try_reserve_exact(n)).map_err(|_| Trap::OutOfMemory)?; + if cold_err!(self.elements.try_reserve_exact(n)).is_err() { + return Ok(false); + } self.elements.resize(len, init); - Ok(()) + Ok(true) + } + + fn maximum_size(kind: TableType) -> Option { + kind.size_max.and_then(|maximum| usize::try_from(maximum).ok()) } pub(crate) fn size(&self) -> usize { diff --git a/crates/tinywasm/tests/internal_refs.rs b/crates/tinywasm/tests/internal_refs.rs index 07cbde2..1793e05 100644 --- a/crates/tinywasm/tests/internal_refs.rs +++ b/crates/tinywasm/tests/internal_refs.rs @@ -65,7 +65,7 @@ fn exported_tables_and_globals_have_handle_and_helper_apis() -> Result<(), Box = Result>; + +fn store_with_limiter(limiter: Arc) -> Store { + let engine = Engine::new(Config::new().with_resource_limiter(limiter)); + Store::new(engine) +} + +#[test] +fn memory_read_write_roundtrip() -> TestResult { + let mut store = Store::default(); + let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?; + + memory.copy_from_slice(&mut store, 0, &[1, 2, 3, 4, 5])?; + assert_eq!(memory.read_vec(&store, 0, 5)?, &[1, 2, 3, 4, 5]); + memory.fill(&mut store, 2, 2, 0)?; + assert_eq!(memory.read_vec(&store, 0, 5)?, &[1, 2, 0, 0, 5]); + Ok(()) +} + +#[test] +fn read_returns_short_count_at_end_of_memory() -> TestResult { + let mut store = Store::default(); + let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(1), Some(4)))?; + memory.copy_from_slice(&mut store, 0, &[1, 2, 3, 4])?; + + let mut dst = [9; 8]; + assert_eq!(memory.read(&store, 2, &mut dst)?, 2); + assert_eq!(&dst[..2], &[3, 4]); + assert_eq!(&dst[2..], &[9; 6]); + + Ok(()) +} + +#[test] +fn memory64_default_limit_is_not_memory32_limit() { + let ty = MemoryType::new(MemoryArch::I64, 65_537, None, None); + assert!(ty.page_count_max() > 65_536); +} + +struct DenyAll; + +impl ResourceLimiter for DenyAll { + fn memory_growing(&self, _current: usize, _desired: usize, _maximum: Option) -> Result { + Ok(false) + } + + fn table_growing(&self, _current: usize, _desired: usize, _maximum: Option) -> Result { + Ok(false) + } +} + +struct DenyGrowth; + +impl ResourceLimiter for DenyGrowth { + fn memory_growing(&self, current: usize, _desired: usize, _maximum: Option) -> Result { + Ok(current == 0) + } + + fn table_growing(&self, current: usize, _desired: usize, _maximum: Option) -> Result { + Ok(current == 0) + } +} + +struct TrapGrowth; + +impl ResourceLimiter for TrapGrowth { + fn memory_growing(&self, current: usize, _desired: usize, _maximum: Option) -> Result { + if current == 0 { Ok(true) } else { Err(Trap::Unreachable) } + } + + fn table_growing(&self, current: usize, _desired: usize, _maximum: Option) -> Result { + if current == 0 { Ok(true) } else { Err(Trap::Unreachable) } + } +} + +#[test] +fn resource_limiter_can_reject_growth() -> TestResult { + let mut store = store_with_limiter(Arc::new(DenyGrowth)); + let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?; + + assert_eq!(memory.grow(&mut store, 1)?, None); + assert_eq!(memory.page_count(&store)?, 1); + Ok(()) +} + +#[test] +fn resource_limiter_rejects_guest_memory_grow() -> TestResult { + let wasm = wat::parse_str( + r#" + (module + (memory 1) + (func (export "grow") (result i32) + i32.const 1 + memory.grow)) + "#, + )?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut store = store_with_limiter(Arc::new(DenyGrowth)); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + + let grow = instance.func::<(), i32>(&store, "grow")?; + assert_eq!(grow.call(&mut store, ())?, -1); + Ok(()) +} + +#[test] +fn resource_limiter_can_trap_guest_memory_grow() -> TestResult { + let wasm = wat::parse_str( + r#" + (module + (memory 1) + (func (export "grow") (result i32) + i32.const 1 + memory.grow)) + "#, + )?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut store = store_with_limiter(Arc::new(TrapGrowth)); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + + let grow = instance.func::<(), i32>(&store, "grow")?; + assert!(matches!(grow.call(&mut store, ()), Err(tinywasm::Error::Trap(Trap::Unreachable)))); + Ok(()) +} + +#[test] +fn resource_limiter_rejects_host_memory_initial_size() { + let mut store = store_with_limiter(Arc::new(DenyAll)); + let result = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None)); + + assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory)))); +} + +#[test] +fn resource_limiter_rejects_module_memory_initial_size() -> TestResult { + let wasm = wat::parse_str("(module (memory 1))")?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut store = store_with_limiter(Arc::new(DenyAll)); + let result = ModuleInstance::instantiate(&mut store, &module, None); + + assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory)))); + Ok(()) +} + +#[test] +fn resource_limiter_rejects_table_initial_size() { + let mut store = store_with_limiter(Arc::new(DenyAll)); + let result = Table::new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into()); + + assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory)))); +} + +#[test] +fn resource_limiter_can_reject_table_growth() -> TestResult { + let mut store = store_with_limiter(Arc::new(DenyGrowth)); + let table = Table::new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into())?; + + assert_eq!(table.grow(&mut store, 1, RefValue::Null.into())?, None); + assert_eq!(table.size(&store)?, 1); + Ok(()) +} + +#[test] +fn resource_limiter_can_trap_table_growth() -> TestResult { + let mut store = store_with_limiter(Arc::new(TrapGrowth)); + let table = Table::new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into())?; + + assert!(matches!(table.grow(&mut store, 1, RefValue::Null.into()), Err(tinywasm::Error::Trap(Trap::Unreachable)))); + Ok(()) +} + +#[test] +fn resource_limiter_allows_guest_memory_grow_by_default() -> TestResult { + let wasm = wat::parse_str( + r#" + (module + (memory 1) + (func (export "grow") (result i32) + i32.const 1 + memory.grow)) + "#, + )?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + + let grow = instance.func::<(), i32>(&store, "grow")?; + assert_eq!(grow.call(&mut store, ())?, 1); + Ok(()) +} diff --git a/crates/tinywasm/tests/memory_backends.rs b/crates/tinywasm/tests/memory_backends.rs deleted file mode 100644 index 73657df..0000000 --- a/crates/tinywasm/tests/memory_backends.rs +++ /dev/null @@ -1,307 +0,0 @@ -extern crate alloc; - -use alloc::sync::Arc; -use core::sync::atomic::{AtomicUsize, Ordering}; - -#[cfg(feature = "std")] -use std::io::{Read, Seek, SeekFrom, Write}; - -use tinywasm::engine::Config; -use tinywasm::types::{MemoryArch, MemoryType}; -use tinywasm::{Engine, Memory, MemoryBackend, Module, ModuleInstance, PagedMemory, Store}; -use tinywasm_parser::{Parser, ParserOptions}; - -type TestResult = Result>; - -fn initial_memory_size(ty: MemoryType) -> usize { - usize::try_from(ty.page_count_initial()) - .ok() - .and_then(|pages| pages.checked_mul(usize::try_from(ty.page_size()).ok()?)) - .expect("test memory size should fit usize") -} - -fn instantiate_module_with_counting_backend(module: Module) -> TestResult { - let created = Arc::new(AtomicUsize::new(0)); - let factory_calls = created.clone(); - let backend = MemoryBackend::custom(move |ty| { - factory_calls.fetch_add(1, Ordering::Relaxed); - PagedMemory::try_new(initial_memory_size(ty), 16) - }); - let engine = Engine::new(Config::new().with_memory_backend(backend)); - let mut store = Store::new(engine); - - let _ = ModuleInstance::instantiate(&mut store, &module, None)?; - - Ok(created.load(Ordering::Relaxed)) -} - -fn instantiate_with_counting_backend(wat: &str) -> TestResult { - let wasm = wat::parse_str(wat)?; - let module = tinywasm::parse_bytes(&wasm)?; - instantiate_module_with_counting_backend(module) -} - -fn instantiate_exported_memory_with_counting_backend( - wat: &str, -) -> TestResult<(Store, tinywasm::ModuleInstance, Arc)> { - let wasm = wat::parse_str(wat)?; - let module = tinywasm::parse_bytes(&wasm)?; - let created = Arc::new(AtomicUsize::new(0)); - let factory_calls = created.clone(); - let backend = MemoryBackend::custom(move |ty| { - factory_calls.fetch_add(1, Ordering::Relaxed); - PagedMemory::try_new(initial_memory_size(ty), 16) - }); - let engine = Engine::new(Config::new().with_memory_backend(backend)); - let mut store = Store::new(engine); - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - Ok((store, instance, created)) -} - -#[test] -fn paged_backend_works_for_module_memories() -> TestResult { - let wasm = wat::parse_str( - r#" - (module - (memory (export "memory") 1) - ) - "#, - )?; - - let module = tinywasm::parse_bytes(&wasm)?; - let config = Config::new().with_memory_backend(MemoryBackend::paged(8)); - let mut store = Store::new(Engine::new(config)); - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - let memory = instance.memory("memory")?; - - memory.copy_from_slice(&mut store, 6, &[1, 2, 3, 4, 5, 6, 7, 8])?; - assert_eq!(memory.read_vec(&store, 6, 8)?, &[1, 2, 3, 4, 5, 6, 7, 8]); - - Ok(()) -} - -#[test] -fn custom_backend_factory_is_used_for_host_memories() -> TestResult { - let created = Arc::new(AtomicUsize::new(0)); - let seen_page_size = Arc::new(AtomicUsize::new(0)); - let factory_calls = created.clone(); - let page_size_seen = seen_page_size.clone(); - - let backend = MemoryBackend::custom(move |ty| { - factory_calls.fetch_add(1, Ordering::Relaxed); - page_size_seen.store(ty.page_size() as usize, Ordering::Relaxed); - PagedMemory::try_new(initial_memory_size(ty), 16) - }); - - let engine = Engine::new(Config::new().with_memory_backend(backend)); - let mut store = Store::new(engine); - - let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(2), Some(32)))?; - assert_eq!(memory.ty(&store)?.page_size(), 32); - memory.copy_from_slice(&mut store, 12, &[9, 8, 7, 6, 5])?; - - assert_eq!(memory.read_vec(&store, 12, 5)?, &[9, 8, 7, 6, 5]); - assert_eq!(created.load(Ordering::Relaxed), 1); - assert_eq!(seen_page_size.load(Ordering::Relaxed), 32); - - Ok(()) -} - -#[test] -fn local_memory_without_observable_use_is_not_allocated() -> TestResult { - let created = instantiate_with_counting_backend( - r#" - (module - (memory 1) - (func (export "run")) - ) - "#, - )?; - - assert_eq!(created, 0); - Ok(()) -} - -#[test] -fn exported_local_memory_is_not_eagerly_allocated() -> TestResult { - let created = instantiate_with_counting_backend( - r#" - (module - (memory (export "memory") 1) - ) - "#, - )?; - - assert_eq!(created, 0); - Ok(()) -} - -#[test] -fn exported_local_memory_reads_zeroes_without_materializing() -> TestResult { - let (mut store, instance, created) = instantiate_exported_memory_with_counting_backend( - r#" - (module - (memory (export "memory") 1) - ) - "#, - )?; - - let memory = instance.memory("memory")?; - assert_eq!(created.load(Ordering::Relaxed), 0); - assert_eq!(memory.len(&store)?, 65536); - assert_eq!(memory.read_vec(&store, 65534, 2)?, &[0, 0]); - assert_eq!(created.load(Ordering::Relaxed), 0); - - memory.copy_from_slice(&mut store, 65534, &[1, 2])?; - assert_eq!(created.load(Ordering::Relaxed), 1); - assert_eq!(memory.read_vec(&store, 65534, 2)?, &[1, 2]); - Ok(()) -} - -#[test] -fn active_data_segment_on_local_memory_is_allocated() -> TestResult { - let created = instantiate_with_counting_backend( - r#" - (module - (memory 1) - (data (i32.const 0) "hi") - ) - "#, - )?; - - assert_eq!(created, 1); - Ok(()) -} - -#[test] -fn local_memory_instruction_is_allocated() -> TestResult { - let created = instantiate_with_counting_backend( - r#" - (module - (memory 1) - (func (export "run") (drop (memory.size))) - ) - "#, - )?; - - assert_eq!(created, 1); - Ok(()) -} - -#[test] -fn disabled_local_memory_allocation_optimization_keeps_old_behavior() -> TestResult { - let wasm = wat::parse_str( - r#" - (module - (memory 1) - (func (export "run")) - ) - "#, - )?; - let parser = Parser::new(ParserOptions::default().with_local_memory_allocation_optimization(false)); - let module = parser.parse_module_bytes(&wasm)?; - - let created = instantiate_module_with_counting_backend(module)?; - - assert_eq!(created, 1); - Ok(()) -} - -#[test] -fn read_returns_short_count_at_end_of_memory() -> TestResult { - let mut store = Store::default(); - let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(1), Some(4)))?; - memory.copy_from_slice(&mut store, 0, &[1, 2, 3, 4])?; - - let mut dst = [9; 8]; - assert_eq!(memory.read(&store, 2, &mut dst)?, 2); - assert_eq!(&dst[..2], &[3, 4]); - assert_eq!(&dst[2..], &[9; 6]); - - Ok(()) -} - -#[test] -fn paged_read_and_write_stop_at_chunk_boundaries() -> TestResult { - let engine = Engine::new(Config::new().with_memory_backend(MemoryBackend::paged(4))); - let mut store = Store::new(engine); - let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(1), Some(16)))?; - - memory.copy_from_slice(&mut store, 0, &[1, 2, 3, 4, 5, 6, 7, 8])?; - - let mut read_buf = [9; 6]; - assert_eq!(memory.read(&store, 2, &mut read_buf)?, 2); - assert_eq!(&read_buf[..2], &[3, 4]); - assert_eq!(&read_buf[2..], &[9; 4]); - - let mut exact_buf = [0; 6]; - memory.read_exact(&store, 2, &mut exact_buf)?; - assert_eq!(exact_buf, [3, 4, 5, 6, 7, 8]); - - assert_eq!(memory.write(&mut store, 6, &[10, 11, 12, 13])?, 2); - assert_eq!(memory.read_vec(&store, 6, 4)?, &[10, 11, 0, 0]); - - memory.copy_from_slice(&mut store, 6, &[20, 21, 22, 23])?; - assert_eq!(memory.read_vec(&store, 6, 4)?, &[20, 21, 22, 23]); - - Ok(()) -} - -#[test] -fn paged_fixed_width_accesses_cross_chunk_boundaries() -> TestResult { - use tinywasm::LinearMemory; - - let mut memory = PagedMemory::try_new(32, 4).map_err(tinywasm::Error::from)?; - memory.write_32(2, &0x1234_5678u32.to_le_bytes()).map_err(tinywasm::Error::from)?; - memory.write_64(6, &0x0123_4567_89ab_cdefu64.to_le_bytes()).map_err(tinywasm::Error::from)?; - memory.write_128(14, &u128::MAX.to_le_bytes()).map_err(tinywasm::Error::from)?; - - assert_eq!(u32::from_le_bytes(memory.read_32(2).map_err(tinywasm::Error::from)?), 0x1234_5678); - assert_eq!(u64::from_le_bytes(memory.read_64(6).map_err(tinywasm::Error::from)?), 0x0123_4567_89ab_cdef); - assert_eq!(u128::from_le_bytes(memory.read_128(14).map_err(tinywasm::Error::from)?), u128::MAX); - Ok(()) -} - -#[test] -fn lazy_custom_backend_creation_trap_is_propagated() -> TestResult { - let wasm = wat::parse_str(r#"(module (memory (export "memory") 1))"#)?; - let module = tinywasm::parse_bytes(&wasm)?; - let backend = MemoryBackend::custom(|_| Err::(tinywasm::Trap::Other("backend unavailable"))); - let mut store = Store::new(Engine::new(Config::new().with_memory_backend(backend))); - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - let memory = instance.memory("memory")?; - - assert_eq!( - memory.copy_from_slice(&mut store, 0, &[1]).unwrap_err(), - tinywasm::Error::from(tinywasm::Trap::Other("backend unavailable")) - ); - Ok(()) -} - -#[test] -fn memory64_default_limit_is_not_memory32_limit() { - let ty = MemoryType::new(MemoryArch::I64, 65_537, None, None); - assert!(ty.page_count_max() > 65_536); -} - -#[cfg(feature = "std")] -#[test] -fn memory_cursor_supports_read_write_and_seek() -> TestResult { - let mut store = Store::default(); - let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(1), Some(8)))?; - - let mut cursor = memory.cursor(&mut store)?; - cursor.seek(SeekFrom::Start(2))?; - cursor.write_all(b"abc")?; - cursor.seek(SeekFrom::Start(0))?; - - let mut buf = [0; 5]; - cursor.read_exact(&mut buf)?; - assert_eq!(buf, [0, 0, b'a', b'b', b'c']); - - cursor.seek(SeekFrom::End(-1))?; - cursor.write_all(b"z")?; - - assert_eq!(memory.read_vec(&store, 0, 8)?, &[0, 0, b'a', b'b', b'c', 0, 0, b'z']); - Ok(()) -} diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index 797f703..c9786d3 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -799,89 +799,6 @@ pub enum Instruction { const _: () = assert!(core::mem::size_of::() == 8); -impl Instruction { - /// Returns the largest module-local memory index used by this instruction. - #[inline] - pub fn memory_addr(&self, data: &super::WasmFunctionData) -> Option { - use Instruction::*; - match *self { - IncMemoryLocal32(arg) - | IncMemoryLocal64(arg) - | StoreLocalLocal32(arg) - | StoreLocalLocal64(arg) - | StoreLocalLocal128(arg) - | LoadLocal32(arg) - | LoadLocal64(arg) - | LoadLocal8S32(arg) - | LoadLocal8U32(arg) - | LoadLocal16S32(arg) - | LoadLocal16U32(arg) - | LoadLocalTee32(arg) - | LoadLocalSet32(arg) - | LoadLocalTee8S32(arg) - | LoadLocalTee8U32(arg) - | LoadLocalTee16S32(arg) - | LoadLocalTee16U32(arg) - | LoadLocalSet8S32(arg) - | LoadLocalSet8U32(arg) - | LoadLocalSet16S32(arg) - | LoadLocalSet16U32(arg) - | LoadLocalTee128(arg) - | LoadLocalSet128(arg) => Some(arg.memory_arg_idx.get(data).mem_addr()), - I32Load(index) - | I64Load(index) - | F32Load(index) - | F64Load(index) - | I32Load8S(index) - | I32Load8U(index) - | I32Load16S(index) - | I32Load16U(index) - | I64Load8S(index) - | I64Load8U(index) - | I64Load16S(index) - | I64Load16U(index) - | I64Load32S(index) - | I64Load32U(index) - | I32Store(index) - | I64Store(index) - | F32Store(index) - | F64Store(index) - | I32Store8(index) - | I32Store16(index) - | I64Store8(index) - | I64Store16(index) - | I64Store32(index) - | V128Load(index) - | V128Load8x8S(index) - | V128Load8x8U(index) - | V128Load16x4S(index) - | V128Load16x4U(index) - | V128Load32x2S(index) - | V128Load32x2U(index) - | V128Load8Splat(index) - | V128Load16Splat(index) - | V128Load32Splat(index) - | V128Load64Splat(index) - | V128Load32Zero(index) - | V128Load64Zero(index) - | V128Store(index) => Some(index.get(data).mem_addr()), - V128Load8Lane(arg) | V128Load16Lane(arg) | V128Load32Lane(arg) | V128Load64Lane(arg) - | V128Store8Lane(arg) | V128Store16Lane(arg) | V128Store32Lane(arg) | V128Store64Lane(arg) => { - Some(arg.memory_arg_idx.get(data).mem_addr()) - } - FMaStoreF32(arg) | FMaStoreF64(arg) => Some(arg.mem_addr()), - MemorySize(memory) | MemoryGrow(memory) | MemoryFill(memory) => Some(memory), - MemoryFillConst(index) => Some(index.get(data).memory), - MemoryInit(index) => Some(index.get(data).second), - MemoryCopy(index) => { - let value = index.get(data); - Some(value.first.max(value.second)) - } - _ => None, - } - } -} - #[cfg(test)] mod tests { use alloc::vec; diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index bd92753..d1f7453 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -133,9 +133,6 @@ pub struct ModuleInner { /// /// Corresponds to the `elem` section of the original WebAssembly module. pub elements: Box<[Element]>, - - /// How instantiation should prepare the module's local memories. - pub local_memory_allocation: LocalMemoryAllocation, } impl Module { @@ -297,20 +294,6 @@ pub enum ExportType<'a> { Tag(&'a FuncType), } -/// How instantiation should prepare local memories declared by the module. -#[derive(Clone, Copy, PartialEq, Eq, Default)] -#[cfg_attr(feature = "debug", derive(Debug))] -#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] -pub enum LocalMemoryAllocation { - /// The module's local memories are unobservable and can be skipped entirely. - #[default] - Skip, - /// The module's local memories may be observed through exports, but can be delayed until first use. - Lazy, - /// The module's local memories must be allocated during instantiation. - Eager, -} - /// A WebAssembly External Kind. /// /// See @@ -614,6 +597,12 @@ impl MemoryType { } } + /// The declared maximum page count, or `None` when the memory is unbounded. + #[inline] + pub const fn page_count_max_declared(&self) -> Option { + self.page_count_max + } + #[inline] pub const fn page_size(&self) -> u64 { if let Some(page_size) = self.page_size { page_size } else { MEM_PAGE_SIZE } @@ -711,7 +700,7 @@ impl From<&ImportKind> for ExternalKind { #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub struct Data { pub data: Box<[u8]>, - pub range: Range, + pub range: Range, pub kind: DataKind, } @@ -729,7 +718,7 @@ pub enum DataKind { pub struct Element { pub kind: ElementKind, pub items: Box<[ElementItem]>, - pub range: Range, + pub range: Range, pub ty: RefType, } diff --git a/examples/rust/Cargo.toml b/examples/rust/Cargo.toml index b338bd2..6701074 100644 --- a/examples/rust/Cargo.toml +++ b/examples/rust/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rust-wasm-examples" -edition = "2021" +edition = "2024" publish = false # treat this as an independent package @@ -22,10 +22,6 @@ path = "src/print.rs" name = "tinywasm" path = "src/tinywasm.rs" -[[bin]] -name = "tinywasm_precompiled" -path = "src/tinywasm_precompiled.rs" - [[bin]] name = "tinywasm_no_std" path = "src/tinywasm_no_std.rs" @@ -41,10 +37,10 @@ path = "src/argon2id.rs" [dependencies] argon2 = { version = "0.5" } dlmalloc = { version = "0.2", features = ["global"] } -tinywasm = { path = "../../crates/tinywasm", default-features = false, features = [ - "archive", - "parser" -] } +tinywasm = { path = "../../crates/tinywasm", default-features = false, features = ["archive", "parser"] } + +[lints.clippy] +missing_safety_doc = "allow" [features] default = ["std"] diff --git a/examples/rust/build.sh b/examples/rust/build.sh index b2a6149..cbd3b27 100755 --- a/examples/rust/build.sh +++ b/examples/rust/build.sh @@ -1,8 +1,8 @@ #!/usr/bin/env bash cd "$(dirname "$0")" || exit -bins=("host_fn" "hello" "fibonacci" "print" "tinywasm" "tinywasm_precompiled" "argon2id") -exclude_wat=("tinywasm" "tinywasm_precompiled") +bins=("host_fn" "hello" "fibonacci" "print" "tinywasm" "argon2id") +exclude_wat=("tinywasm") out_dir="./target/wasm32-unknown-unknown/wasm" dest_dir="out" diff --git a/examples/rust/src/hello.rs b/examples/rust/src/hello.rs index 3d9f400..06ef5c9 100644 --- a/examples/rust/src/hello.rs +++ b/examples/rust/src/hello.rs @@ -19,10 +19,12 @@ pub unsafe extern "C" fn arg_size() -> i32 { #[unsafe(no_mangle)] pub unsafe extern "C" fn hello(len: i32) { - let arg = core::str::from_utf8(&ARG[0..len as usize]).unwrap(); - let res = format!("Hello, {}!", arg).as_bytes().to_vec(); + unsafe { + let arg = core::str::from_utf8(&ARG[0..len as usize]).unwrap(); + let res = format!("Hello, {}!", arg).as_bytes().to_vec(); - let len = res.len() as i32; - let ptr = res.leak().as_ptr() as i64; - print_utf8(ptr, len); + let len = res.len() as i32; + let ptr = res.leak().as_ptr() as i64; + print_utf8(ptr, len); + } } diff --git a/examples/rust/src/print.rs b/examples/rust/src/print.rs index d2934f0..991ea4a 100644 --- a/examples/rust/src/print.rs +++ b/examples/rust/src/print.rs @@ -7,5 +7,7 @@ unsafe extern "C" { #[unsafe(no_mangle)] pub unsafe extern "C" fn add_and_print(lh: i32, rh: i32) { - printi32(lh + rh); + unsafe { + printi32(lh + rh); + } } diff --git a/examples/rust/src/print.twasm b/examples/rust/src/print.twasm index f0fa9a8..7841329 100644 Binary files a/examples/rust/src/print.twasm and b/examples/rust/src/print.twasm differ diff --git a/examples/rust/src/tinywasm_precompiled.rs b/examples/rust/src/tinywasm_precompiled.rs deleted file mode 100644 index bc0e0c1..0000000 --- a/examples/rust/src/tinywasm_precompiled.rs +++ /dev/null @@ -1,30 +0,0 @@ -#![no_main] -use tinywasm::{FuncContext, HostFunction, Module, ModuleInstance}; - -#[link(wasm_import_module = "env")] -unsafe extern "C" { - fn printi32(x: i32); -} - -#[unsafe(no_mangle)] -pub extern "C" fn hello() { - let _ = run(); -} - -fn run() -> tinywasm::Result<()> { - let module = Module::try_from_twasm(include_bytes!("./print.twasm"))?; - let mut store = tinywasm::Store::default(); - - let printi32 = HostFunction::from(|_: FuncContext<'_>, v: i32| { - unsafe { printi32(v) } - Ok(()) - }); - - let mut imports = tinywasm::Imports::new(); - imports.define("env", "printi32", printi32); - - let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; - let add_and_print = instance.func::<(i32, i32), ()>(&store, "add_and_print")?; - add_and_print.call(&mut store, (1, 2))?; - Ok(()) -} diff --git a/examples/wasm-rust.rs b/examples/wasm-rust.rs index b3398f8..0cfb0ce 100644 --- a/examples/wasm-rust.rs +++ b/examples/wasm-rust.rs @@ -35,7 +35,6 @@ fn main() -> Result<()> { println!(" host_fn"); println!(" fibonacci - calculate fibonacci(30)"); println!(" tinywasm - run printi32 inside of tinywasm inside of itself"); - println!(" tinywasm_precompiled - run a precompiled module inside of tinywasm"); println!(" tinywasm_no_std - run a precompiled module inside of no_std tinywasm"); println!(" argon2id - run argon2id(1000, 2, 1)"); return Ok(()); @@ -46,7 +45,6 @@ fn main() -> Result<()> { "printi32" => printi32()?, "fibonacci" => fibonacci()?, "tinywasm" => tinywasm()?, - "tinywasm_precompiled" => tinywasm_precompiled()?, "tinywasm_no_std" => tinywasm_no_std()?, "argon2id" => argon2id()?, "host_fn" => host_fn()?, @@ -60,8 +58,6 @@ fn main() -> Result<()> { fibonacci()?; println!("\ntinywasm.wasm:"); tinywasm()?; - println!("\ntinywasm_precompiled.wasm:"); - tinywasm_precompiled()?; println!("\ntinywasm_no_std.wasm:"); tinywasm_no_std()?; println!("argon2id.wasm:"); @@ -105,21 +101,6 @@ fn tinywasm_no_std() -> Result<()> { Ok(()) } -fn tinywasm_precompiled() -> Result<()> { - let module = tinywasm::parse_file("./examples/rust/out/tinywasm_precompiled.opt.wasm")?; - let mut store = Store::default(); - - let mut imports = Imports::new(); - imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _x: i32| Ok(()))); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(black_box(&imports)))?; - - let hello = instance.func::<(), ()>(&store, "hello")?; - hello.call(&mut store, black_box(()))?; - hello.call(&mut store, black_box(()))?; - hello.call(&mut store, black_box(()))?; - Ok(()) -} - fn hello() -> Result<()> { let module = tinywasm::parse_file("./examples/rust/out/hello.opt.wasm")?; let mut store = Store::default(); @@ -231,11 +212,6 @@ mod tests { tinywasm().unwrap(); } - #[test] - fn test_tinywasm_precompiled() { - tinywasm_precompiled().unwrap(); - } - #[test] fn test_tinywasm_no_std() { tinywasm_no_std().unwrap(); -- cgit v1.3.1 From de980a68647bafe7bc2c291163fdc044e0c50887 Mon Sep 17 00:00:00 2001 From: Henry Date: Sun, 23 Aug 2026 14:51:51 +0200 Subject: chore(parser): avoid cloning call signatures during lowering Signed-off-by: Henry --- crates/parser/src/conversion.rs | 3 +-- crates/parser/src/visit.rs | 44 +++++++++++++++++++--------------------- crates/tinywasm/tests/gc_refs.rs | 1 - 3 files changed, 22 insertions(+), 26 deletions(-) (limited to 'crates/parser/src/conversion.rs') diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 364bae8..8f39398 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -152,8 +152,7 @@ pub(crate) fn convert_module_code( options: &ParserOptions, ) -> Result<(FunctionCode, Option, OperatorsReaderAllocations)> { let mut locals_reader = func.get_locals_reader()?; - let signature = metadata.signature(ty_idx)?.clone(); - let mut local_types = signature.params.clone(); + let mut local_types = metadata.signature(ty_idx)?.params.clone(); #[cfg(feature = "validate")] let mut validator = validator; diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index f48e1cf..b65f77c 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -168,7 +168,7 @@ pub(crate) struct FunctionBuilder<'a> { impl<'a> FunctionBuilder<'a> { pub(crate) fn new( metadata: &'a ModuleMetadata, - signature: Signature, + signature: &Signature, local_types: Vec, local_addr_map: Vec, body_size: usize, @@ -188,7 +188,7 @@ impl<'a> FunctionBuilder<'a> { height: 0, base: ValueCounts::default(), params: Vec::new(), - results: signature.results, + results: signature.results.clone(), unreachable: false, entry_unreachable: false, end_reachable: false, @@ -402,7 +402,7 @@ pub(crate) fn process_operators( let body_size = body.as_bytes().len(); let reader = body.get_binary_reader_for_operators()?; let mut reader = OperatorsReader::new_with_allocs(reader, allocs); - let signature = metadata.signature(ty_idx)?.clone(); + let signature = metadata.signature(ty_idx)?; let mut builder = FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, deduplicate_operands); @@ -436,7 +436,7 @@ pub(crate) fn process_operators_and_validate( let body_size = body.as_bytes().len(); let reader = body.get_binary_reader_for_operators()?; let mut reader = OperatorsReader::new_with_allocs(reader, allocs); - let signature = metadata.signature(ty_idx)?.clone(); + let signature = metadata.signature(ty_idx)?; let mut builder = FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, deduplicate_operands); @@ -628,27 +628,26 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_call(&mut self, function_index: u32) -> Self::Output { - let signature = self.metadata.function_signature(function_index)?.clone(); + let signature = self.metadata.function_signature(function_index)?; self.emit(&signature.params, &signature.results, Instruction::Call(function_index)) } fn visit_call_indirect(&mut self, type_index: u32, table_index: u32) -> Self::Output { - let signature = self.metadata.signature(type_index)?.clone(); - let mut inputs = signature.params; - inputs.push(self.metadata.table_size(table_index)?); + let table_size = self.metadata.table_size(table_index)?; let operand = self.push_operand(TwoU32 { first: type_index, second: table_index })?; - self.emit(&inputs, &signature.results, Instruction::CallIndirect(operand)) + let signature = self.metadata.signature(type_index)?; + self.pop_expect(table_size)?; + self.emit(&signature.params, &signature.results, Instruction::CallIndirect(operand)) } fn visit_call_ref(&mut self, type_index: u32) -> Self::Output { - let signature = self.metadata.signature(type_index)?.clone(); - let mut inputs = signature.params; - inputs.push(ValueLane::S32); - self.emit(&inputs, &signature.results, Instruction::CallRef(type_index)) + let signature = self.metadata.signature(type_index)?; + self.pop_expect(ValueLane::S32)?; + self.emit(&signature.params, &signature.results, Instruction::CallRef(type_index)) } fn visit_return_call(&mut self, function_index: u32) -> Self::Output { - let signature = self.metadata.function_signature(function_index)?.clone(); + let signature = self.metadata.function_signature(function_index)?; self.apply_effect(&signature.params, &[])?; self.mark_unreachable(); self.instructions.push(Instruction::ReturnCall(function_index)); @@ -656,10 +655,10 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_return_call_indirect(&mut self, type_index: u32, table_index: u32) -> Self::Output { - let signature = self.metadata.signature(type_index)?.clone(); - let mut inputs = signature.params; - inputs.push(self.metadata.table_size(table_index)?); - self.apply_effect(&inputs, &[])?; + let table_size = self.metadata.table_size(table_index)?; + let signature = self.metadata.signature(type_index)?; + self.pop_expect(table_size)?; + self.apply_effect(&signature.params, &[])?; self.mark_unreachable(); let operand = self.push_operand(TwoU32 { first: type_index, second: table_index })?; self.instructions.push(Instruction::ReturnCallIndirect(operand)); @@ -667,10 +666,9 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_return_call_ref(&mut self, type_index: u32) -> Self::Output { - let signature = self.metadata.signature(type_index)?.clone(); - let mut inputs = signature.params; - inputs.push(ValueLane::S32); - self.apply_effect(&inputs, &[])?; + let signature = self.metadata.signature(type_index)?; + self.pop_expect(ValueLane::S32)?; + self.apply_effect(&signature.params, &[])?; self.mark_unreachable(); self.instructions.push(Instruction::ReturnCallRef(type_index)); Ok(()) @@ -838,7 +836,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_throw(&mut self, tag_index: u32) -> Self::Output { - let signature = self.metadata.tag_signature(tag_index)?.clone(); + let signature = self.metadata.tag_signature(tag_index)?; self.apply_effect(&signature.params, &[])?; self.instructions.push(Instruction::Throw(tag_index)); self.mark_unreachable(); diff --git a/crates/tinywasm/tests/gc_refs.rs b/crates/tinywasm/tests/gc_refs.rs index ce92300..d3f2994 100644 --- a/crates/tinywasm/tests/gc_refs.rs +++ b/crates/tinywasm/tests/gc_refs.rs @@ -1,4 +1,3 @@ - use tinywasm::types::{ExternRef, RefValue, WasmValue}; use tinywasm::{Engine, ExecProgress, ModuleInstance, Store, engine::Config}; -- cgit v1.3.1 From 7b9b3ec681e68280399d9c67e01433c2d3acb6c2 Mon Sep 17 00:00:00 2001 From: Henry Gressmann Date: Mon, 24 Aug 2026 15:47:05 +0200 Subject: feat: add host typed reference / gc APIs (#54) - add Store-aware handles for references, GC objects, and exceptions - simplify host value conversion, rooting, and exception propagation - update examples, tests, and documentation - Remove deprecated APIs Signed-off-by: Henry --- ARCHITECTURE.md | 65 -- CHANGELOG.md | 55 +- CONTRIBUTING.md | 4 +- Cargo.toml | 2 +- README.md | 48 +- crates/cli/Cargo.toml | 1 + crates/cli/src/cmd/run.rs | 5 +- crates/cli/src/testsuite.rs | 17 +- crates/cli/src/wast_runner.rs | 145 ++-- crates/parser/src/conversion.rs | 7 +- crates/tinywasm/src/error.rs | 25 +- crates/tinywasm/src/func/context.rs | 66 +- crates/tinywasm/src/func/host.rs | 108 +-- crates/tinywasm/src/func/mod.rs | 120 ++- crates/tinywasm/src/func/resume.rs | 108 ++- crates/tinywasm/src/func/values.rs | 97 +-- crates/tinywasm/src/imports.rs | 11 +- crates/tinywasm/src/instance.rs | 32 +- crates/tinywasm/src/interpreter/executor.rs | 208 ++--- .../tinywasm/src/interpreter/stack/value_stack.rs | 137 +-- crates/tinywasm/src/interpreter/values.rs | 57 +- crates/tinywasm/src/lib.rs | 48 +- crates/tinywasm/src/reference.rs | 513 ------------ crates/tinywasm/src/reference/managed.rs | 236 ++++++ crates/tinywasm/src/reference/mod.rs | 13 + crates/tinywasm/src/reference/store.rs | 915 +++++++++++++++++++++ crates/tinywasm/src/reference/value.rs | 232 ++++++ crates/tinywasm/src/store/const_expr.rs | 125 +-- crates/tinywasm/src/store/exception.rs | 10 - crates/tinywasm/src/store/function.rs | 8 - crates/tinywasm/src/store/gc/mod.rs | 74 +- crates/tinywasm/src/store/gc/object.rs | 148 ++-- crates/tinywasm/src/store/gc/roots.rs | 58 ++ crates/tinywasm/src/store/global.rs | 12 +- crates/tinywasm/src/store/mod.rs | 353 ++++++-- crates/tinywasm/src/store/state.rs | 228 ++--- crates/tinywasm/src/store/table.rs | 3 + crates/tinywasm/tests/gc_refs.rs | 61 +- crates/tinywasm/tests/host_func_signature_check.rs | 141 +++- crates/tinywasm/tests/imported_table_init.rs | 7 +- crates/tinywasm/tests/internal_refs.rs | 33 +- crates/tinywasm/tests/managed_exceptions.rs | 142 ++++ crates/tinywasm/tests/memory.rs | 22 +- crates/tinywasm/tests/reference_roots.rs | 104 +++ crates/tinywasm/tests/resume_execution.rs | 16 +- crates/tinywasm/tests/store_ownership.rs | 8 +- crates/tinywasm/tests/typed_gc_access.rs | 49 ++ crates/tinywasm/tests/typed_globals.rs | 8 +- crates/types/src/archive.rs | 42 +- crates/types/src/instructions.rs | 7 +- crates/types/src/lib.rs | 43 +- crates/types/src/reference.rs | 166 +--- crates/types/src/types.rs | 24 + crates/types/src/value.rs | 299 +------ examples/archive.rs | 8 +- examples/basic.rs | 26 + examples/exceptions.rs | 28 + examples/funcref_callbacks.rs | 123 --- examples/gc.rs | 33 + examples/linking.rs | 12 +- examples/reentrance.rs | 5 +- examples/references.rs | 34 + examples/resumable.rs | 2 + examples/rust.rs | 226 +++++ examples/rust/README.md | 4 +- examples/simple.rs | 22 - examples/simple2.rs | 21 - examples/wasm-rust.rs | 224 ----- 68 files changed, 3643 insertions(+), 2591 deletions(-) delete mode 100644 ARCHITECTURE.md delete mode 100644 crates/tinywasm/src/reference.rs create mode 100644 crates/tinywasm/src/reference/managed.rs create mode 100644 crates/tinywasm/src/reference/mod.rs create mode 100644 crates/tinywasm/src/reference/store.rs create mode 100644 crates/tinywasm/src/reference/value.rs delete mode 100644 crates/tinywasm/src/store/exception.rs create mode 100644 crates/tinywasm/src/store/gc/roots.rs create mode 100644 crates/tinywasm/tests/managed_exceptions.rs create mode 100644 crates/tinywasm/tests/reference_roots.rs create mode 100644 crates/tinywasm/tests/typed_gc_access.rs create mode 100644 examples/basic.rs create mode 100644 examples/exceptions.rs delete mode 100644 examples/funcref_callbacks.rs create mode 100644 examples/gc.rs create mode 100644 examples/references.rs create mode 100644 examples/rust.rs delete mode 100644 examples/simple.rs delete mode 100644 examples/simple2.rs delete mode 100644 examples/wasm-rust.rs (limited to 'crates/parser/src/conversion.rs') diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md deleted file mode 100644 index 62fa503..0000000 --- a/ARCHITECTURE.md +++ /dev/null @@ -1,65 +0,0 @@ -# TinyWasm Architecture - -TinyWasm follows the general runtime model described in the [WebAssembly specification](https://webassembly.github.io/spec/core/exec/runtime.html). It is a stack-based interpreter with a compact internal bytecode, width-specific value stacks, and a contiguous `Vec`-backed linear memory. - -## Execution Pipeline - -TinyWasm does not execute WebAssembly instructions directly. Parsing lowers them into an internal bytecode designed to make execution simpler and cheaper: - -- structured control flow (`block`, `loop`, `if`, and `br*`) becomes jump-oriented instructions such as `Jump`, `JumpIfZero`, `BranchTable*`, `DropKeep*`, and `Return` -- operand widths are encoded in instruction variants, and branch stack reshaping is explicit -- instructions retain compact module-local indexes, which each instance maps to Store-wide runtime addresses -- when enabled, the optimizer applies local rewrites, including superinstruction fusion, specialized calls and returns, and redundant-instruction removal -- modules can be serialized as `.twasm` archives containing this lowered representation -- execution uses a single iterative dispatch loop over the resulting instruction stream - -## Value Stacks - -WebAssembly combines an operand stack with function-scoped locals. TinyWasm stores both in the same width-specific physical stacks: - -- `stack_32` for `i32`, `f32`, and reference values, including GC and exception references -- `stack_64` for `i64` and `f64` -- `stack_128` for `v128` - -The interpreter does not maintain a runtime type stack or tag individual stack slots. Lowered instructions encode the physical lane they operate on, while WebAssembly validation guarantees type correctness. Splitting values by width lets each value use its natural storage size, reducing stack memory and the data moved by common operations. - -Locals are stored directly in these stacks. Each `CallFrame` records a base for every lane, and lowered local instructions index from those bases. The value stacks and call stack can use either a fixed capacity or dynamic initial and maximum sizes. Dynamic stacks keep the initial allocation small, grow when needed, and retain a hard limit. - -## Interpreter Optimization - -Instruction dispatch is one of the interpreter's main costs. TinyWasm reduces it through superinstructions and by shaping the large Rust dispatch match based on benchmarks and assembly inspection. Most simple arithmetic remains directly in the interpreter loop. Small, frequently used stack, value, and global operations use `#[inline]` or `#[inline(always)]` where measurements show a benefit, while unlikely error paths use `core::hint::cold_path()`. - -Superinstructions also reduce value-stack traffic. They can read locals, globals, and constants directly, perform an operation, and write `set` or `tee` destinations without materializing intermediate operand-stack values. Examples include: - -- fused binary operations such as `BinOpLocalLocal*`, `BinOpLocalConst*`, and `BinOpStackGlobal*` -- fused conditional branches such as `JumpCmpLocalConst*`, `JumpCmpLocalLocal*`, and `JumpCmpStackConst*` - -The default runtime remains safe Rust throughout rather than relying on unchecked operations. - -## SIMD - -SIMD instructions have a portable safe-Rust implementation built from fixed-size arrays and lane operations, relying on the compiler to auto-vectorize where possible. Generated code is inspected with `cargo asm`, and benchmarks determine where architecture-specific alternatives are worthwhile. WebAssembly targets use native SIMD intrinsics where available, while the optional `simd-x86` feature provides selected x86 implementations for operations where the generic code produces worse results. - -## Linear Memory - -Linear memory is a contiguous `Vec` allocation owned by a `MemoryInstance`. The interpreter accesses it through the internal `MemoryStorage` type, a small concrete boundary that keeps the `Vec` representation out of the executor so an mmap-backed storage can be substituted later without touching load and store paths. - -Fixed-width loads and stores use a single const-generic `read_fixed::` / `write_fixed::` pair rather than per-width vtable methods. Scalar operations reduce to an effective-address computation, a bounds check, a slice access, and a `from_le_bytes` / `to_le_bytes` conversion, with out-of-bounds construction kept on cold paths. Bulk operations such as `fill` and `copy_within` map directly to native slice methods. - -Memory growth keeps the Wasm page count and limits on `MemoryInstance`. Before memory or table backing storage is allocated or resized, the configured `ResourceLimiter` is consulted so a host can bound guest resource consumption. The limiter is shared across the stores created from one `Engine` and lives behind an `Arc`. - -For conventional operating systems, a future mmap-backed storage could reserve virtual address space and use guard pages to move more bounds enforcement to the operating system, reducing explicit checks in linear-memory hot paths. This is the same broad approach described in [Wasmtime's linear-memory architecture](https://docs.wasmtime.dev/contributing-architecture.html#linear-memory), where virtual-memory reservations and guard regions eliminate or deduplicate explicit bounds checks. - -## Future Experiments - -Future work may explore additional dispatch and code-generation strategies, including Rust's experimental `loop_match` state-machine work, a tail-call-based interpreter once Rust's explicit tail-call support matures, more aggressive superinstruction fusion, top-of-stack register allocation, or optional JIT compilation. - -## Important Modules - -- [visit.rs](./crates/parser/src/visit.rs) - function-body operator lowering -- [optimize.rs](./crates/parser/src/optimize.rs) - peephole optimizer and superinstruction fusion -- [parallel.rs](./crates/parser/src/parallel.rs) - parallel function parsing -- [instructions.rs](./crates/types/src/instructions.rs) - internal instruction set -- [value_stack.rs](./crates/tinywasm/src/interpreter/stack/value_stack.rs) - width-specific stacks -- [call_stack.rs](./crates/tinywasm/src/interpreter/stack/call_stack.rs) - call frame stack -- [memory/mod.rs](./crates/tinywasm/src/store/memory/mod.rs) - linear memory storage diff --git a/CHANGELOG.md b/CHANGELOG.md index 5473ebc..bad8caf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,47 +9,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Added support for the WebAssembly function-references proposal -- Added basic support for the WebAssembly garbage-collection proposal -- Added support for the WebAssembly exception-handling proposal, including tags, `try_table`, `throw`, and `throw_ref` -- Added support for the WebAssembly compact-imports proposal -- Added `WasmValue::ty` and `WasmValue::matches_type` -- Added `ValueLane` for mapping WebAssembly value types to their physical 32-bit, 64-bit, or 128-bit storage lane. -- Added a `validate` feature to `tinywasm` and `tinywasm-parser` (enabled by default) to optionally skip wasmparser validation for faster parsing of trusted modules. -- Added optional parse-time operand deduplication to reduce precompiled module and `.twasm` archive size. -- Added a `ResourceLimiter` trait, configurable through `engine::Config::with_resource_limiter`, to bound guest memory, table, and logical GC heap growth. +- Support for the typed function references, garbage collection, exception handling, and compact import section proposals. +- `ResourceLimiter` callbacks for memory and table allocation or growth +- A default `validate` Cargo feature & parser option to skip wasm validation +- Optional parse-time operand deduplication to reduce `.twasm` archive size ### Changed -- `HostFunction` is now a reusable definition, and module instantiation borrows `Imports` so host imports can be shared across stores. -- Host function callbacks now require `Send + Sync` so the same definition can be used safely with multiple stores. -- Typed function tuples now support up to 20 parameters or results. `WasmTupleChain` is deprecated. Use untyped functions for larger signatures. -- Module types now use one dense recursive type space, while function types are resolved through `Function::ty(&Store)`. -- Globals are stored in separate 32-bit, 64-bit, and 128-bit value lanes, avoiding tagged value conversion during guest execution. -- Linear memory now uses a single contiguous `Vec`-backed storage with const-generic fixed-width loads and stores. -- Increased the minimum supported Rust version from 1.95 to 1.98. +- Typed functions now support tuples up to arity 20 and `[u8; 16]` values for `v128`. +- Module types now use one recursive type space. Runtime function types are available through `Function::ty(&Store)`. +- Linear memory now uses contiguous `Vec`-backed storage. +- The minimum supported Rust version increased from 1.95 to 1.98. +- The internal instruction represetaions size was reduced from 16 to 8 bytes. ### Fixed -- Directly defined imports now reject handles from a different `Store`. +- Instantiation now rejects directly defined imports that contain handles from another `Store`. - Tail calls to host functions now return directly to the caller frame. -- Fixed Memory64 bulk-memory operations and optimized stores using the wrong value-stack lane. -- Fixed `memory.init` bounds checks and operand lowering. -- Fixed Memory64 default limits and host-size handling, including 32-bit targets. +- Memory64 bulk-memory operations and optimized stores now use the correct value-stack lanes. +- `memory.init` now performs correct bounds checks and operand lowering. +- Memory64 now uses the correct default limits and host-size conversions, including on 32-bit targets. ### Breaking Changes -- `HostFunction::from` and `HostFunction::from_untyped` no longer take a `Store` and now return reusable `HostFunction` definitions -- `ModuleInstance::instantiate` and `instantiate_no_start` now borrow `Imports`. -- `Store::id` now returns `u32` instead of `usize`. -- `Parser::new` now takes `ParserOptions`, use `Parser::default()` for default settings. `Parser::with_options` was removed. -- Renamed `ModuleInstanceAddr` to `ModuleInstanceId`. -- Removed `HostFunction::ty` and `WasmFunction::ty`. Use `Function::ty(&Store)` for runtime function types. -- Changed `TableType::element_type` and `Element::ty` from `WasmType` to `RefType`, and replaced module `table_types` with `TableDefinition { ty, init }`. -- Removed the pluggable memory backend system (`LinearMemory`, `MemoryBackend`, `VecMemory`, `PagedMemory`, `LazyLinearMemory`, and `Config::with_memory_backend`). Linear memory is always `Vec`-backed. To limit initial memory allocation and growth, configure a `ResourceLimiter` with `Config::with_resource_limiter`. -- Removed the local-memory allocation analysis (`LocalMemoryAllocation` and `ParserOptions::optimize_local_memory_allocation`). Local memories are always allocated eagerly. -- Removed `Config::with_trap_on_oom`. A `ResourceLimiter` can return a trap when rejecting a memory or table allocation or growth request. -- `Table::grow` now returns `Result>`, matching `Memory::grow`. Growth limits and allocation failures return `None`, while limiter-provided traps return an error. +- `Function::call` and `Function::call_resumable` now write to caller-provided result slices. Untyped host callbacks also receive a result slice and return `Result<()>`. +- Creating a `HostFunction` no longer requires a `Store`. Definitions require `Send + Sync` and can be reused across stores. Module instantiation now borrows `Imports` so the same imports can also be reused. +- `HostFunction::ty` and `WasmFunction::ty` were removed. Use `Function::ty(&Store)` for runtime types. +- Function and managed reference handles are tied to their originating `Store`. Managed references keep their referents live, so `WasmValue` is no longer `Copy`. Nullable typed references use `Option`, while bare typed references are non-null. +- The `Memory`, `Table`, `Global`, and `Tag` constructors were renamed from `new` to `try_new`. +- `Store::id` now returns `u32`, and `ModuleInstanceAddr` was renamed to `ModuleInstanceId`. +- Element types now use `RefType`, and module definitions use `TableDefinition { ty, init }`. `Table::grow` now returns `Result>`, matching `Memory::grow`. +- `Parser::new` now takes `ParserOptions`. Use `Parser::default()` for default settings. `Parser::with_options` was removed. +- Pluggable memory backends and `Config::with_trap_on_oom` were removed for performance reasons. Linear memory is always `Vec`-backed. Use `ResourceLimiter` to allow, reject, or trap memory allocation and growth requests. +- `WasmTupleChain` was removed. Use direct tuples up to arity 20 or untyped functions for larger signatures. +- The `.twasm` format changed. Regenerate archives created by earlier TinyWasm versions. ## [0.10.0] - 2026-07-24 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6cb7761..73186e7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -33,7 +33,7 @@ $ cargo test-wast ./wasm-testsuite/data/wasm-v1/{file}.wast $ cargo test-wasm-custom # Run a specific example (run without arguments to see available examples) -# The wasm test files required to run the `wasm-rust` examples are not +# The wasm test files required to run the `rust` example are not # included in the main repository. # To build these, you will need to install binaryen and wabt # and run `./examples/rust/build.sh`. @@ -48,7 +48,7 @@ Example usage: ```bash cargo install --locked samply -samply record -- cargo run --release --example wasm-rust -- tinywasm +samply record -- cargo run --release --example rust -- tinywasm ``` ## Commits diff --git a/Cargo.toml b/Cargo.toml index 764ae53..12fad7e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,7 +38,7 @@ wat = "1.257" criterion = { version = "0.8", default-features = false, features = ["cargo_bench_support", "rayon"] } [[example]] -name = "wasm-rust" +name = "rust" test = false [[bench]] diff --git a/README.md b/README.md index 5355249..70578dd 100644 --- a/README.md +++ b/README.md @@ -3,13 +3,17 @@ # `tinywasm` -[![docs.rs](https://img.shields.io/docsrs/tinywasm?logo=rust&style=flat-square)](https://docs.rs/tinywasm) [![Crates.io](https://img.shields.io/crates/v/tinywasm.svg?logo=rust&style=flat-square)](https://crates.io/crates/tinywasm) [![Crates.io](https://img.shields.io/crates/l/tinywasm.svg?style=flat-square)](./LICENSE-APACHE) +[![Documentation](https://img.shields.io/badge/docs-latest-blue?style=flat-square)](https://docs.rs/tinywasm/latest/tinywasm/) [![Build](https://img.shields.io/github/actions/workflow/status/explodingcamera/tinywasm/test.yaml?branch=next&style=flat-square&label=build)](https://github.com/explodingcamera/tinywasm/actions/workflows/test.yaml?query=branch%3Anext) [![Crates.io](https://img.shields.io/crates/v/tinywasm.svg?logo=rust&style=flat-square)](https://crates.io/crates/tinywasm) [![Crates.io](https://img.shields.io/crates/l/tinywasm.svg?style=flat-square)](./LICENSE-APACHE) ## Why `tinywasm`? -- **Tiny**: Small by design, while still passing the full WebAssembly 3.0 core testsuite. -- **Portable**: Runs anywhere Rust can target, supports `no_std`, has minimal dependencies, and can itself compile to WebAssembly. -- **Safe**: Written in safe Rust, with optional `unsafe` limited to the `simd-x86` feature. Its sandbox is designed to prevent untrusted Wasm from accessing host memory or escaping the runtime. +- **Tiny**: Small by design, while still passing the full WebAssembly 3.0 core test suite. +- **Portable**: Runs anywhere Rust can target, supports `no_std`, has minimal dependencies[^dependencies], and can itself compile to WebAssembly. +- **Safe by default**: Written entirely in safe Rust[^unsafe]. + +[^dependencies]: The two main external components are [`wasmparser`](https://crates.io/crates/wasmparser) for WebAssembly parsing and validation, and [`postcard`](https://crates.io/crates/postcard) for `.twasm` archives. + +[^unsafe]: The optional `simd-x86` feature is the only exception. It uses `unsafe` internally for selected x86 SIMD intrinsics. ## Installation @@ -42,38 +46,40 @@ assert_eq!(result, 3); See the [examples](./examples) directory and [documentation](https://docs.rs/tinywasm) for more information. -## Precompiled Modules - -TinyWasm modules can be compiled to the internal `twasm` bytecode format, which stores the optimized instruction representation for faster loading and reuse. - ## Cargo Features - **`std`:** Enables `std` and parsing from files and streams. Enabled by default. - **`log`:** Enables integration with the `log` crate. Enabled by default. - **`parser`:** Enables `tinywasm-parser` and top-level parse helpers. Enabled by default. -- **`validate`:** Enables WebAssembly validation while parsing. Enabled by default and configurable through `ParserOptions`. +- **`validate`:** Enables WebAssembly validation while parsing. Enabled by default and configurable through [`ParserOptions`](https://docs.rs/tinywasm/latest/tinywasm/parser/struct.ParserOptions.html). - **`archive`:** Enables serialization and deserialization of the internal `twasm` format. Enabled by default. -- **`canonicalize-nans`:** Canonicalizes NaN values. Enabled by default. +- **`canonicalize-nans`:** Uses a [canonical NaN](https://en.wikipedia.org/wiki/NaN#Canonical_NaN) for normalized NaN results. Enabled by default. - **`debug`:** Derives `Debug` for runtime types. Enabled by default. - **`parallel-parser`:** Parallelizes function parsing when `std` is enabled. Enabled by default. - **`guest-debug`:** Exposes module-internal by-index inspection APIs (`*_by_index`). - **`simd-x86`:** Enables x86-specific SIMD intrinsics and uses `unsafe` internally. -With default features disabled, `tinywasm` depends only on `core`, `alloc`, and `libm`[^libm], making it usable in `no_std + alloc` environments. +With default features disabled, `tinywasm` depends only on `core`, `alloc`, and `libm`, making it usable in `no_std + alloc` environments. + +Use [`Engine`](https://docs.rs/tinywasm/latest/tinywasm/engine/struct.Engine.html) and [`engine::Config`](https://docs.rs/tinywasm/latest/tinywasm/engine/struct.Config.html) for non-default fuel accounting, stack sizing, or GC collection thresholds. A configured `ResourceLimiter` can allow, reject, or trap memory and table allocation or growth requests, and GC object allocations. + +## Precompiled Modules + +TinyWasm can serialize a parsed module to its version-specific `.twasm` format. Loading an archive skips WebAssembly parsing, validation, and optimization. -Use `Engine` and `engine::Config` when you need non-default runtime settings such as fuel accounting, stack sizing, or the GC collection threshold. A `ResourceLimiter` attached to the engine's config bounds guest memory, table, and GC heap growth and can trap rejected requests. +Applications that only load `.twasm` can remove the parser and validator from their binary by only enabling the `archive` feature. Depending on the target and release profile, this can produce binaries smaller than 300 KB. -[^libm]: [rust-lang/rust#137578](https://github.com/rust-lang/rust/issues/137578) — tracking issue for floating-point math support in `no_std`. +## Untrusted Input -## Safety +WebAssembly [validation](https://webassembly.github.io/spec/core/valid/index.html) is enabled by default through the `validate` feature. Keep this feature enabled and leave `ParserOptions::validation` enabled for modules from untrusted sources. Without validation, parsing can produce modules that violate runtime assumptions and may panic during instantiation or execution. -TinyWasm only uses safe Rust by default. The optional `simd-x86` feature enables x86-specific SIMD intrinsics and uses `unsafe` internally. WebAssembly input is validated by default through the `validate` feature. Disabling validation should not let Wasm access host memory or escape the sandbox, but malformed input may panic or otherwise crash the process, so only disable it for trusted input. +Validation does not limit parsing or execution resources. Hosts that run untrusted code should also set input limits, configure stack and `ResourceLimiter` limits, and use fuel- or time-budgeted execution as needed. -The internal `twasm` bytecode format is not currently validated as an untrusted input format. Malformed `twasm` may panic, but should not compromise memory safety or allow sandbox escape. Only run trusted `twasm` bytecode, or generate it through TinyWasm from Wasm input. +Loading `.twasm` checks the archive header and encoding but does not run WebAssembly validation or verify TinyWasm's runtime invariants. Load archives only from trusted sources. For untrusted input, parse a WebAssembly binary with validation enabled. -## Supported Proposals +## WebAssembly Proposal Support -TinyWasm targets non-JavaScript core proposals through [phase 3](https://github.com/WebAssembly/proposals). JavaScript integrations and optional embedding or tooling APIs are not included here. +TinyWasm generally implements non-JavaScript core proposals at [phase 4](https://github.com/WebAssembly/proposals#phase-4---standardize-the-feature-wg) or later, with some proposals implemented earlier. The table shows current support and known exceptions. | Proposal | Status | `tinywasm` Version | | ---------------------------------------------------------------------------------------------------------------- | ------ | ------------------ | @@ -95,8 +101,8 @@ TinyWasm targets non-JavaScript core proposals through [phase 3](https://github. | [**Typed Function References**](https://github.com/WebAssembly/function-references) | 🟢 | `next` | | [**Garbage Collection**](https://github.com/WebAssembly/gc) | 🟢 | `next` | | [**Exception Handling**](https://github.com/WebAssembly/exception-handling) | 🟢 | `next` | +| [**Compact Import Section**](https://github.com/WebAssembly/compact-import-section) | 🟢 | `next` | | [**Stack Switching**](https://github.com/WebAssembly/stack-switching) | 🌑 | - | -| [**Compact Import Section**](https://github.com/WebAssembly/compact-import-section) | 🌑 | - | | [**Threads**](https://github.com/WebAssembly/threads) | 🌑 | - | **Legend**\ @@ -106,11 +112,13 @@ TinyWasm targets non-JavaScript core proposals through [phase 3](https://github. ## See Also -If you need a more mature, production-tested, or performance-focused WebAssembly runtime today, consider one of these projects: +If you're looking for a WebAssembly runtime with JIT compilation, better performance or other advanced features, check out these other runtimes: - [wasmi](https://github.com/wasmi-labs/wasmi) - efficient and versatile WebAssembly interpreter for embedded systems - [wasm3](https://github.com/wasm3/wasm3) - a fast WebAssembly interpreter written in C - [wazero](https://wazero.io/) - a zero-dependency WebAssembly interpreter written in Go +- [wasmer](https://wasmer.io/) - a fast and secure WebAssembly runtime written in Rust +- [wasmtime](https://wasmtime.dev/) - a fast and secure WebAssembly runtime written in Rust ## License diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 1aae437..069a4e2 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -35,6 +35,7 @@ tinywasm = { workspace = true, features = [ "archive", "canonicalize-nans", "debug", + "guest-debug", "log", "parallel-parser", "parser", diff --git a/crates/cli/src/cmd/run.rs b/crates/cli/src/cmd/run.rs index 3d25641..52cd273 100644 --- a/crates/cli/src/cmd/run.rs +++ b/crates/cli/src/cmd/run.rs @@ -29,7 +29,8 @@ pub fn run(args: RunArgs) -> Result<()> { .ok_or_else(|| anyhow::anyhow!("export is not a function: {export}"))?; let func = instance.func_untyped(&store, export)?; let params = parse_invocation_args(func_ty, &args.args)?; - let results = func.call(&mut store, ¶ms)?; + let mut results = vec![tinywasm::WasmValue::I32(0); func.ty(&store)?.results().len()]; + func.call(&mut store, ¶ms, &mut results)?; print_results(&results); Ok(()) } @@ -44,7 +45,7 @@ pub fn run(args: RunArgs) -> Result<()> { "module has no start function or `_start` export. Use `tinywasm inspect {module_path}` or `tinywasm run --invoke {module_path}`" ) })?; - start.call(&mut store, &[])?; + start.call(&mut store, &[], &mut [])?; Ok(()) } } diff --git a/crates/cli/src/testsuite.rs b/crates/cli/src/testsuite.rs index 032aa88..b23b2c8 100644 --- a/crates/cli/src/testsuite.rs +++ b/crates/cli/src/testsuite.rs @@ -7,9 +7,14 @@ use std::io::{BufRead, BufReader, Seek, SeekFrom}; /// Result type used by the WAST test utilities. pub type TestResult = core::result::Result>; -#[derive(Debug)] struct TestFailure(String); +impl core::fmt::Debug for TestFailure { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + Display::fmt(self, f) + } +} + impl Display for TestFailure { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.write_str(&self.0) @@ -89,13 +94,9 @@ impl TestSuite { } pub fn report_status(&self) -> TestResult<()> { - if self.runner.failed() { - println!(); - Err(TestFailure(format!("{}:\n{self}", "failed one or more tests".red().bold())).into()) - } else { - println!("{self}"); - Ok(()) - } + self.print_errors(); + println!("{self}"); + if self.runner.failed() { Err(TestFailure("failed one or more tests".into()).into()) } else { Ok(()) } } pub fn save_csv(&self, path: &str, version: &str) -> TestResult<()> { diff --git a/crates/cli/src/wast_runner.rs b/crates/cli/src/wast_runner.rs index 023c959..3f905d4 100644 --- a/crates/cli/src/wast_runner.rs +++ b/crates/cli/src/wast_runner.rs @@ -7,10 +7,7 @@ use std::time::Duration; use anyhow::{Context, Result, anyhow, bail}; use log::{debug, error}; -use tinywasm::types::{ - AbstractHeapType as TinyAbstractHeapType, AnyRef, ExternRef, FuncRef, MemoryType, RefType, RefValue, TableType, - WasmType, WasmValue, -}; +use tinywasm::types::{MemoryType, RefType, RefValue, TableType, WasmType, WasmValue}; use tinywasm::{ExecProgress, Global, HostFunction, Imports, Memory, Module, ModuleInstance, Store, Table}; use wast::{QuoteWat, core::AbstractHeapType}; @@ -171,17 +168,18 @@ impl WastRunner { fn imports(store: &mut Store, modules: &HashMap) -> Result { let mut imports = Imports::new(); - let table = Table::new(store, TableType::new(RefType::FUNCREF, 10, Some(20)), RefValue::Null.into())?; - let table64 = Table::new(store, TableType::new64(RefType::FUNCREF, 10, Some(20)), RefValue::Null.into())?; - let memory = Memory::new(store, MemoryType::default().with_page_count_initial(1).with_page_count_max(Some(2)))?; + let table = Table::try_new(store, TableType::new(RefType::FUNCREF, 10, Some(20)), RefValue::Null.into())?; + let table64 = Table::try_new(store, TableType::new64(RefType::FUNCREF, 10, Some(20)), RefValue::Null.into())?; + let memory = + Memory::try_new(store, MemoryType::default().with_page_count_initial(1).with_page_count_max(Some(2)))?; let global_i32 = - Global::new(store, tinywasm::types::GlobalType::new(WasmType::I32, false), WasmValue::I32(666))?; + Global::try_new(store, tinywasm::types::GlobalType::new(WasmType::I32, false), WasmValue::I32(666))?; let global_i64 = - Global::new(store, tinywasm::types::GlobalType::new(WasmType::I64, false), WasmValue::I64(666))?; + Global::try_new(store, tinywasm::types::GlobalType::new(WasmType::I64, false), WasmValue::I64(666))?; let global_f32 = - Global::new(store, tinywasm::types::GlobalType::new(WasmType::F32, false), WasmValue::F32(666.6))?; + Global::try_new(store, tinywasm::types::GlobalType::new(WasmType::F32, false), WasmValue::F32(666.6))?; let global_f64 = - Global::new(store, tinywasm::types::GlobalType::new(WasmType::F64, false), WasmValue::F64(666.6))?; + Global::try_new(store, tinywasm::types::GlobalType::new(WasmType::F64, false), WasmValue::F64(666.6))?; imports .define("spectest", "memory", memory) @@ -227,6 +225,7 @@ impl WastRunner { let mut store = Store::default(); let mut module_registry = ModuleRegistry::default(); + let mut call_results = Vec::new(); println!("running {} tests for group: {}", directives.len(), file.name()); for (i, directive) in directives.into_iter().enumerate() { @@ -333,9 +332,10 @@ impl WastRunner { } AssertExhaustion { call, message, span } => { let module = module_registry.get_idx(call.module); - let args = convert_wastargs(call.args)?; - let res = - catch_unwind_silent(|| exec_fn_instance(module, &mut store, call.name, &args).map(|_| ())); + let args = convert_wastargs(&mut store, call.args)?; + let res = catch_unwind_silent(|| { + exec_fn_instance(module, &mut store, call.name, &args, &mut call_results) + }); let Ok(Err(tinywasm::Error::Trap(trap))) = res else { test_group.add_result( &format!("AssertExhaustion({i})"), @@ -368,9 +368,9 @@ impl WastRunner { wast::WastExecute::Invoke(invoke) => invoke, }; let module = module_registry.get_idx(invoke.module); - let args = - convert_wastargs(invoke.args).map_err(|err| tinywasm::Error::Other(err.to_string()))?; - exec_fn_instance(module, &mut store, invoke.name, &args).map(|_| ()) + let args = convert_wastargs(&mut store, invoke.args) + .map_err(|err| tinywasm::Error::Other(err.to_string()))?; + exec_fn_instance(module, &mut store, invoke.name, &args, &mut call_results) }); match res { Err(err) => test_group.add_result( @@ -415,9 +415,9 @@ impl WastRunner { wast::WastExecute::Invoke(invoke) => invoke, }; let module = module_registry.get_idx(invoke.module); - let args = - convert_wastargs(invoke.args).map_err(|err| tinywasm::Error::Other(err.to_string()))?; - exec_fn_instance(module, &mut store, invoke.name, &args).map(|_| ()) + let args = convert_wastargs(&mut store, invoke.args) + .map_err(|err| tinywasm::Error::Other(err.to_string()))?; + exec_fn_instance(module, &mut store, invoke.name, &args, &mut call_results) }); let result = match res { Err(err) => Err(anyhow!("test panicked: {}", try_downcast_panic(err))), @@ -469,9 +469,9 @@ impl WastRunner { Invoke(invoke) => { let name = invoke.name; let res: Result, _> = catch_unwind_silent(|| { - let args = convert_wastargs(invoke.args)?; + let args = convert_wastargs(&mut store, invoke.args)?; let module = module_registry.get_idx(invoke.module); - exec_fn_instance(module, &mut store, invoke.name, &args).map_err(|e| { + exec_fn_instance(module, &mut store, invoke.name, &args, &mut call_results).map_err(|e| { error!("failed to execute function: {e:?}"); e })?; @@ -504,7 +504,7 @@ impl WastRunner { ); continue; }; - let module_global = match module.global_get(&store, global) { + let module_global = match module.global_get(&mut store, global) { Ok(value) => value, Err(err) => { test_group.add_result( @@ -518,7 +518,7 @@ impl WastRunner { let expected = expected_alternatives .iter() .filter_map(|alts| alts.first()) - .find(|exp| exp.matches(&module_global, &store)); + .find(|exp| exp.matches(&module_global, &store, &module)); if expected.is_none() { test_group.add_result( &format!("AssertReturn(unsupported-{i})"), @@ -552,25 +552,28 @@ impl WastRunner { let invoke_name = invoke.name; let res: Result, _> = catch_unwind_silent(|| { - let args = convert_wastargs(invoke.args)?; - let module = module_registry.get_idx(invoke.module); - let outcomes = exec_fn_instance(module, &mut store, invoke.name, &args).map_err(|e| { - error!("failed to execute function: {e:?}"); - e - })?; - if !expected_alternatives.iter().any(|expected| expected.len() == outcomes.len()) { + let args = convert_wastargs(&mut store, invoke.args)?; + let module = module_registry + .get(invoke.module) + .ok_or_else(|| anyhow!("module instance was not found"))?; + exec_fn_instance(Some(module.id()), &mut store, invoke.name, &args, &mut call_results) + .map_err(|e| { + error!("failed to execute function: {e:?}"); + e + })?; + if !expected_alternatives.iter().any(|expected| expected.len() == call_results.len()) { return Err(anyhow!( "expected {} results, got {}", expected_alternatives.first().map_or(0, |v| v.len()), - outcomes.len() + call_results.len() )); } if expected_alternatives.iter().any(|expected| { - expected.len() == outcomes.len() - && outcomes + expected.len() == call_results.len() + && call_results .iter() .zip(expected.iter()) - .all(|(outcome, exp)| exp.matches(outcome, &store)) + .all(|(outcome, exp)| exp.matches(outcome, &store, &module)) }) { Ok(()) } else { @@ -715,12 +718,12 @@ fn exec_with_budget( func: &tinywasm::Function, store: &mut Store, args: &[WasmValue], -) -> Result, tinywasm::Error> { - let mut exec = func.call_resumable(store, args)?; + results: &mut [WasmValue], +) -> Result<(), tinywasm::Error> { + let mut exec = func.call_resumable(store, args, results)?; for _ in 0..TEST_MAX_SUSPENSIONS { - match exec.resume_with_time_budget(TEST_TIME_SLICE)? { - ExecProgress::Completed(values) => return Ok(values), - ExecProgress::Suspended => {} + if let ExecProgress::Completed(()) = exec.resume_with_time_budget(TEST_TIME_SLICE)? { + return Ok(()); } } Err(tinywasm::Error::Other(format!( @@ -741,7 +744,8 @@ fn exec_fn_instance( store: &mut Store, name: &str, args: &[WasmValue], -) -> Result, tinywasm::Error> { + results: &mut Vec, +) -> Result<(), tinywasm::Error> { let Some(instance) = instance else { return Err(tinywasm::Error::Other("no instance found".to_string())); }; @@ -749,7 +753,9 @@ fn exec_fn_instance( return Err(tinywasm::Error::Other("no instance found".to_string())); }; let func = instance.func_untyped(store, name)?; - exec_with_budget(&func, store, args) + results.clear(); + results.resize(func.ty(store)?.results().len(), WasmValue::I32(0)); + exec_with_budget(&func, store, args, results) } fn catch_unwind_silent(f: impl FnOnce() -> R) -> std::thread::Result { @@ -790,8 +796,8 @@ fn parse_quote_module(module: QuoteWat) -> Result<(Option, Module)> { Ok((name, parse_module_bytes(&bytes)?)) } -fn convert_wastargs(args: Vec) -> Result> { - args.into_iter().map(wastarg2tinywasmvalue).collect() +fn convert_wastargs(store: &mut Store, args: Vec) -> Result> { + args.into_iter().map(|arg| wastarg2tinywasmvalue(store, arg)).collect() } fn convert_wastret<'a>(args: impl Iterator>) -> Result>> { @@ -802,7 +808,7 @@ fn convert_wastret<'a>(args: impl Iterator>) -> Result< for prefix in alternatives { for choice in &choices { let mut candidate = prefix.clone(); - candidate.push(*choice); + candidate.push(choice.clone()); next.push(candidate); } } @@ -811,7 +817,7 @@ fn convert_wastret<'a>(args: impl Iterator>) -> Result< Ok(alternatives) } -fn wastarg2tinywasmvalue(arg: wast::WastArg) -> Result { +fn wastarg2tinywasmvalue(store: &mut Store, arg: wast::WastArg) -> Result { let wast::WastArg::Core(arg) = arg else { bail!("unsupported arg type: Component"); }; @@ -822,7 +828,7 @@ fn wastarg2tinywasmvalue(arg: wast::WastArg) -> Result { I32(i) => WasmValue::I32(i), I64(i) => WasmValue::I64(i), V128(i) => WasmValue::V128(i.to_le_bytes()), - RefExtern(v) => ExternRef::try_new(v).ok_or_else(|| anyhow!("external reference address is too large"))?.into(), + RefExtern(v) => tinywasm::ExternRef::try_new(store, v)?.into(), RefNull(t) => match t { wast::core::HeapType::Abstract { shared: false, ty: AbstractHeapType::Func } => RefValue::Null.into(), wast::core::HeapType::Abstract { shared: false, ty: AbstractHeapType::Extern | AbstractHeapType::Any } => { @@ -832,10 +838,7 @@ fn wastarg2tinywasmvalue(arg: wast::WastArg) -> Result { bail!("unsupported arg type: refnull: {:?}", t); } }, - RefHost(value) => { - RefValue::Any(AnyRef::from_host(value).ok_or_else(|| anyhow!("host reference address is too large"))?) - .into() - } + RefHost(value) => RefValue::Any(tinywasm::ExternRef::try_new(store, value)?.to_any()).into(), }) } @@ -855,7 +858,7 @@ fn wast_v128_to_bytes(i: wast::core::V128Pattern) -> [u8; 16] { res.try_into().unwrap() } -#[derive(Clone, Copy)] +#[derive(Clone)] enum ExpectedValue { Exact(WasmValue), RefNull, @@ -866,24 +869,35 @@ enum ExpectedValue { RefI31, RefStruct, RefArray, + RefExternExact(u32), + RefFuncExact(u32), + RefHostExact(u32), } impl ExpectedValue { - fn matches(&self, value: &WasmValue, store: &Store) -> bool { + fn matches(&self, value: &WasmValue, store: &Store, module: &ModuleInstance) -> bool { match self { Self::Exact(expected) => value.eq_loose(expected), Self::RefNull => matches!(value, WasmValue::Ref(RefValue::Null)), Self::RefFunc => matches!(value, WasmValue::Ref(RefValue::Func(_))), Self::RefExtern => matches!(value, WasmValue::Ref(RefValue::Extern(_))), Self::RefAny => matches!(value, WasmValue::Ref(RefValue::Any(_))), - Self::RefEq => { - store.value_matches_type(*value, WasmType::Ref(RefType::new_abstract(false, TinyAbstractHeapType::Eq))) - } + Self::RefEq => matches!(value, WasmValue::Ref(RefValue::Any(value)) if value.as_eq().is_some()), Self::RefI31 => matches!(value, WasmValue::Ref(RefValue::Any(value)) if value.as_i31().is_some()), - Self::RefStruct => store - .value_matches_type(*value, WasmType::Ref(RefType::new_abstract(false, TinyAbstractHeapType::Struct))), - Self::RefArray => store - .value_matches_type(*value, WasmType::Ref(RefType::new_abstract(false, TinyAbstractHeapType::Array))), + Self::RefStruct => matches!(value, WasmValue::Ref(RefValue::Any(value)) if value.as_struct().is_some()), + Self::RefArray => matches!(value, WasmValue::Ref(RefValue::Any(value)) if value.as_array().is_some()), + Self::RefExternExact(expected) => match value { + WasmValue::Ref(RefValue::Extern(value)) => value.key(store) == Ok(*expected), + _ => false, + }, + Self::RefHostExact(expected) => match value { + WasmValue::Ref(RefValue::Any(value)) => value.to_extern().key(store) == Ok(*expected), + _ => false, + }, + Self::RefFuncExact(expected) => module + .func_by_index(store, *expected) + .and_then(|function| function.as_func_ref(store)) + .is_ok_and(|expected| matches!(value, WasmValue::Ref(RefValue::Func(value)) if *value == expected)), } } } @@ -912,11 +926,9 @@ fn wastretcore2tinywasmvalue(ret: wast::core::WastRetCore) -> Result ExpectedValue::Exact(WasmValue::I64(i)), V128(i) => ExpectedValue::Exact(WasmValue::V128(wast_v128_to_bytes(i))), RefNull(_) => ExpectedValue::RefNull, - RefExtern(Some(v)) => ExpectedValue::Exact( - ExternRef::try_new(v).ok_or_else(|| anyhow!("external reference address is too large"))?.into(), - ), + RefExtern(Some(v)) => ExpectedValue::RefExternExact(v), RefExtern(None) => ExpectedValue::RefExtern, - RefFunc(Some(wast::token::Index::Num(n, _))) => ExpectedValue::Exact(FuncRef::new(n).into()), + RefFunc(Some(wast::token::Index::Num(n, _))) => ExpectedValue::RefFuncExact(n), RefFunc(None) => ExpectedValue::RefFunc, RefFunc(v) => { bail!("unsupported arg type: reffunc: {:?}", v); @@ -926,10 +938,7 @@ fn wastretcore2tinywasmvalue(ret: wast::core::WastRetCore) -> Result ExpectedValue::RefI31, RefStruct => ExpectedValue::RefStruct, RefArray => ExpectedValue::RefArray, - RefHost(value) => ExpectedValue::Exact( - RefValue::Any(AnyRef::from_host(value).ok_or_else(|| anyhow!("host reference address is too large"))?) - .into(), - ), + RefHost(value) => ExpectedValue::RefHostExact(value), a => { bail!("unsupported arg type {:?}", a); } diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 8f39398..6857a19 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -342,12 +342,9 @@ pub(crate) fn process_const_operators( } let instr = match op { - wasmparser::Operator::RefNull { hty } => { - convert_heap_type(hty, false)?; - ConstInstruction::Ref(RefValue::Null) - } + wasmparser::Operator::RefNull { hty } => ConstInstruction::RefNull(convert_heap_type(hty, true)?), wasmparser::Operator::RefFunc { function_index } => { - ConstInstruction::Ref(RefValue::Func(FuncRef::new(function_index))) + ConstInstruction::RefFunc(ModuleFuncIdx::new(function_index)) } wasmparser::Operator::RefI31 => ConstInstruction::RefI31, wasmparser::Operator::AnyConvertExtern => ConstInstruction::AnyConvertExtern, diff --git a/crates/tinywasm/src/error.rs b/crates/tinywasm/src/error.rs index 05e36aa..77856af 100644 --- a/crates/tinywasm/src/error.rs +++ b/crates/tinywasm/src/error.rs @@ -2,8 +2,10 @@ use alloc::boxed::Box; use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::fmt::{Debug, Display}; +use tinywasm_types::FuncType; use tinywasm_types::archive::TwasmError; -use tinywasm_types::{ExnRef, FuncType}; + +use crate::{ExnRef, WasmValue}; #[cfg(feature = "parser")] pub use tinywasm_parser::ParseError; @@ -31,7 +33,7 @@ pub enum Error { /// The expected type expected: Box, /// The actual value - actual: Vec, + actual: Vec, }, /// An invalid label type was encountered @@ -105,9 +107,11 @@ impl Error { } } -/// A WebAssembly trap +/// An execution or runtime trap. +/// +/// This includes WebAssembly traps and TinyWasm runtime failures. /// -/// See +/// See #[non_exhaustive] #[cfg_attr(feature = "debug", derive(Debug))] pub enum Trap { @@ -123,7 +127,7 @@ pub enum Trap { offset: usize, /// The size of the access len: usize, - /// The maximum size of the memory + /// The current memory length in bytes. max: usize, }, @@ -133,7 +137,7 @@ pub enum Trap { offset: usize, /// The size of the access len: usize, - /// The maximum size of the memory + /// The current table length in elements. max: usize, }, @@ -146,9 +150,12 @@ pub enum Trap { /// Invalid Integer Conversion InvalidConversionToInt, - /// The store is not the one that the module instance was instantiated in + /// A Store-owned handle or reference was used with a different Store. InvalidStore, + /// A reference does not identify a live value of the expected kind. + InvalidReference, + /// Integer Overflow IntegerOverflow, @@ -158,7 +165,7 @@ pub enum Trap { /// Value stack overflow ValueStackOverflow, - /// The runtime could not allocate memory for a stack or linear memory operation. + /// An allocation or requested resource size could not be satisfied. OutOfMemory, /// An undefined element was encountered @@ -228,6 +235,7 @@ impl Trap { Self::IndirectCallTypeMismatch { .. } => "indirect call type mismatch", Self::HostFunction(_) => "host function trap", Self::InvalidStore => "invalid store", + Self::InvalidReference => "invalid reference", Self::Other(message) => message, } } @@ -337,6 +345,7 @@ impl Display for Trap { Self::NullI31Reference => write!(f, "null i31 reference"), Self::CastFailure => write!(f, "cast failure"), Self::InvalidStore => write!(f, "invalid store"), + Self::InvalidReference => write!(f, "invalid reference"), #[cfg(feature = "debug")] Self::IndirectCallTypeMismatch { expected, actual } => { write!(f, "indirect call type mismatch: expected={expected:?}, actual={actual:?}") diff --git a/crates/tinywasm/src/func/context.rs b/crates/tinywasm/src/func/context.rs index 95a2cec..7e289f6 100644 --- a/crates/tinywasm/src/func/context.rs +++ b/crates/tinywasm/src/func/context.rs @@ -1,7 +1,6 @@ -use alloc::vec::Vec; -use tinywasm_types::{ModuleInstanceId, WasmValue}; +use tinywasm_types::ModuleInstanceId; -use crate::{Error, FromWasmValues, Function, FunctionTyped, IntoWasmValues, Result}; +use crate::{Error, FromWasmValues, FuncRef, Function, FunctionTyped, IntoWasmValues, Result, WasmValue}; /// The context of a host-function call #[cfg_attr(feature = "debug", derive(core::fmt::Debug))] @@ -45,7 +44,7 @@ impl FuncContext<'_> { } /// Get the value of a global export. - pub fn global_get(&self, name: &str) -> Result { + pub fn global_get(&mut self, name: &str) -> Result { self.module().global_get(self.store, name) } @@ -84,17 +83,26 @@ impl FuncContext<'_> { /// Nested calls are currently blocking only. If the surrounding invocation /// is resumed with fuel or a time budget, this method does not suspend and /// later continue the host function in the middle of the nested call. - pub fn call_untyped(&mut self, func: &Function, args: &[WasmValue]) -> Result> { + pub fn call_untyped(&mut self, func: &Function, args: &[WasmValue], results: &mut [WasmValue]) -> Result<()> { if !self.store.execution_active { return Err(Error::other("FuncContext::call requires an active host-function invocation")); } - func.item.validate_store(self.store)?; - func.validate_params(self.store, args)?; + func.validate_call(self.store, args, results.len())?; let call_stack_base = self.store.call_stack.len(); let value_stack_base = self.store.value_stack.base(); - func.call_untyped(self.store, args, call_stack_base, value_stack_base) + func.call_untyped(self.store, args, results, call_stack_base, value_stack_base) + } + + /// Calls a Store-aware function reference in the current module context. + pub fn call_ref(&mut self, func: FuncRef, args: &[WasmValue], results: &mut [WasmValue]) -> Result<()> { + let addr = func.addr(self.store.store_id()).ok_or(crate::Trap::InvalidStore)?; + if self.store.state.funcs.get(addr as usize).is_none() { + return Err(crate::Trap::InvalidReference.into()); + } + let function = Function { item: crate::StoreItem::new(self.store.store_id(), addr), module_id: self.module_id }; + self.call_untyped(&function, args, results) } /// Call a typed function from within the current host-function invocation. @@ -112,20 +120,29 @@ impl FuncContext<'_> { func.func.item.validate_store(self.store)?; let func_instance = self.store.state.get_func(func.func.addr()).clone(); if matches!(&func_instance.kind, crate::store::FunctionKind::Host(host) if host.typed_callback().is_none()) { - let params = params.into_wasm_values().collect::>(); - let results = self.call_untyped(&func.func, ¶ms)?; - let mut values = results.into_iter(); - let result = R::from_wasm_values(&mut values)?; - return if values.next().is_none() { - Ok(result) - } else { - Err(Error::other("typed conversion did not consume all WebAssembly values")) - }; + let ty = self.store.state.get_canonical_func_type(func_instance.type_addr); + let (param_count, result_count) = (ty.params().len(), ty.results().len()); + self.store.with_scratch_values(param_count + result_count, |store, values| { + super::write_typed_params(&mut values[..param_count], params.into_wasm_values())?; + let (params, results) = values.split_at_mut(param_count); + func.func.validate_call(store, params, results.len())?; + let call_stack_base = store.call_stack.len(); + let value_stack_base = store.value_stack.base(); + func.func.call_untyped(store, params, results, call_stack_base, value_stack_base)?; + values.drain(..param_count); + R::from_wasm_values_exact(&mut values.drain(..)) + }) + } else { + let call_stack_base = self.store.call_stack.len(); + let value_stack_base = self.store.value_stack.base(); + func.func.call_typed( + self.store, + &func_instance, + params.into_wasm_values(), + call_stack_base, + value_stack_base, + ) } - - let call_stack_base = self.store.call_stack.len(); - let value_stack_base = self.store.value_stack.base(); - func.func.call_typed(self.store, &func_instance, params.into_wasm_values(), call_stack_base, value_stack_base) } } @@ -142,10 +159,3 @@ impl core::ops::DerefMut for FuncContext<'_> { self.store } } - -impl<'a> FuncContext<'a> { - /// Create a new host function context. - pub const fn new(store: &'a mut crate::Store, module_id: ModuleInstanceId) -> Self { - Self { store, module_id } - } -} diff --git a/crates/tinywasm/src/func/host.rs b/crates/tinywasm/src/func/host.rs index 27c5573..8f36761 100644 --- a/crates/tinywasm/src/func/host.rs +++ b/crates/tinywasm/src/func/host.rs @@ -1,8 +1,9 @@ use alloc::{boxed::Box, sync::Arc, vec::Vec}; -use tinywasm_types::{FuncType, ModuleInstanceId, TypeAddr, WasmType, WasmValue}; +use tinywasm_types::{FuncType, ModuleInstanceId, TypeAddr, WasmType}; use super::{FromWasmValues, FuncContext, IntoWasmValues, ToWasmTypes}; -use crate::{Function, FunctionInstance, Result, Store}; +use crate::store::FuncValueTypes; +use crate::{Function, FunctionInstance, Result, Store, WasmValue}; /// A reusable host function definition. #[derive(Clone)] @@ -11,12 +12,8 @@ pub struct HostFunction(Arc); impl HostFunction { /// Instantiates the function with an already registered canonical type. pub(crate) fn instantiate_registered(&self, store: &mut Store, type_addr: TypeAddr) -> Function { - let addr = store.add_func(FunctionInstance { - type_addr, - gc: store.state.func_gc_metadata(type_addr), - kind: crate::store::FunctionKind::Host(self.clone()), - }); - Function { item: crate::StoreItem::new(store.id(), addr), module_id: 0 } + let addr = store.add_func(FunctionInstance { type_addr, kind: crate::store::FunctionKind::Host(self.clone()) }); + Function { item: crate::StoreItem::new(store.store_id(), addr), module_id: 0 } } /// Resolves the importing module's types without allocating a function instance. @@ -45,19 +42,26 @@ impl HostFunction { module_id: ModuleInstanceId, type_addr: TypeAddr, args: &[WasmValue], - ) -> Result> { - let result = match &self.0.callback { - HostCallback::Untyped(func) => func(FuncContext { store, module_id }, args), - HostCallback::Typed(func) => func.call(FuncContext { store, module_id }, args), - }?; - let expected = store.state.get_canonical_func_type(type_addr); - if result.len() == expected.results().len() - && result.iter().zip(expected.results()).all(|(&value, &ty)| store.state.value_matches_type(value, ty)) - { - Ok(result) - } else { - Err(crate::Error::InvalidHostFnReturn { expected: Box::new(expected.clone()), actual: result }) + results: &mut [WasmValue], + ) -> Result<()> { + let expected = store.state.get_canonical_func_type(type_addr).clone(); + if results.len() != expected.results().len() { + return Err(crate::Error::other("host result buffer has the wrong length")); + } + for (result, ty) in results.iter_mut().zip(expected.results()) { + *result = match ty { + WasmType::I32 => WasmValue::I64(0), + _ => WasmValue::I32(0), + }; + } + match &self.0.callback { + HostCallback::Untyped(func) => func(FuncContext { store, module_id }, args, results)?, + HostCallback::Typed(func) => func.call(FuncContext { store, module_id }, args, results)?, } + if !results.iter().zip(expected.results()).all(|(value, &ty)| store.value_matches_type(value, ty)) { + return Err(crate::Error::InvalidHostFnReturn { expected: Box::new(expected), actual: results.to_vec() }); + } + Ok(()) } /// Returns the allocation-free typed callback when one is available. @@ -79,8 +83,9 @@ impl HostFunction { /// /// # Errors /// - /// Returns an error if the signature uses a store-specific reference type - /// that is not registered in `store`. + /// Returns an error if the signature contains a concrete reference type. + /// Define the function through [`crate::Imports`] when concrete types must + /// be resolved against an importing module. /// /// ## Example /// @@ -93,7 +98,9 @@ impl HostFunction { /// let add_one = HostFunction::from(|_ctx, value: i32| Ok(value + 1)); /// let function = add_one.instantiate(&mut store)?; /// - /// assert_eq!(function.call(&mut store, &[WasmValue::I32(41)])?, [WasmValue::I32(42)]); + /// let mut results = [WasmValue::I32(0)]; + /// function.call(&mut store, &[WasmValue::I32(41)], &mut results)?; + /// assert_eq!(results, [WasmValue::I32(42)]); /// # Ok(()) /// # } /// ``` @@ -104,13 +111,9 @@ impl HostFunction { .params() .iter() .chain(self.0.ty.results()) - .filter_map(|ty| match ty { - WasmType::Ref(ty) => ty.type_index(), - _ => None, - }) - .any(|type_addr| type_addr as usize >= store.state.canonical_types.len()) + .any(|ty| matches!(ty, WasmType::Ref(ty) if ty.is_concrete())) { - return Err(crate::Error::other("host function signature contains a concrete type from another store")); + return Err(crate::Error::other("standalone host functions cannot use concrete reference types")); } let type_addr = store.register_host_type(&self.0.ty); Ok(self.instantiate_registered(store, type_addr)) @@ -136,11 +139,12 @@ impl HostFunction { /// # let module = tinywasm::parse_bytes(&wasm)?; /// let mut store = Store::default(); /// let ty = FuncType::new(&[WasmType::I32], &[WasmType::I32]); - /// let add_one = HostFunction::from_untyped(&ty, |_ctx: FuncContext<'_>, args| { + /// let add_one = HostFunction::from_untyped(&ty, |_ctx: FuncContext<'_>, args, results| { /// let WasmValue::I32(value) = args[0] else { /// return Err(tinywasm::Error::Other("expected i32".into())); /// }; - /// Ok(vec![WasmValue::I32(value + 1)]) + /// results[0] = WasmValue::I32(value + 1); + /// Ok(()) /// }); /// /// let mut imports = Imports::new(); @@ -153,7 +157,7 @@ impl HostFunction { /// ``` pub fn from_untyped( ty: &FuncType, - func: impl Fn(FuncContext<'_>, &[WasmValue]) -> Result> + Send + Sync + 'static, + func: impl Fn(FuncContext<'_>, &[WasmValue], &mut [WasmValue]) -> Result<()> + Send + Sync + 'static, ) -> Self { Self(Arc::new(HostFunctionInner { ty: ty.clone(), callback: HostCallback::Untyped(Box::new(func)) })) } @@ -207,10 +211,10 @@ enum HostCallback { Typed(Box), } -type UntypedHostCallback = dyn Fn(FuncContext<'_>, &[WasmValue]) -> Result> + Send + Sync; +type UntypedHostCallback = dyn Fn(FuncContext<'_>, &[WasmValue], &mut [WasmValue]) -> Result<()> + Send + Sync; pub(crate) trait TypedHostCallback: Send + Sync { - fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue]) -> Result>; + fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue], results: &mut [WasmValue]) -> Result<()>; fn call_stack(&self, store: &mut Store, module_id: ModuleInstanceId, type_addr: TypeAddr) -> Result<()>; } @@ -225,30 +229,30 @@ where P: FromWasmValues, R: IntoWasmValues, { - fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue]) -> Result> { - let mut values = args.iter().copied(); - let params = P::from_wasm_values(&mut values)?; + fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue], results: &mut [WasmValue]) -> Result<()> { + let mut values = args.iter().cloned(); + let params = P::from_wasm_values_exact(&mut values)?; + let mut values = (self.func)(ctx, params)?.into_wasm_values(); + for result in results { + *result = values.next().ok_or_else(|| crate::Error::other("not enough typed function results"))?; + } if values.next().is_some() { - return Err(crate::Error::other("typed conversion did not consume all WebAssembly values")); + return Err(crate::Error::other("too many typed function results")); } - Ok((self.func)(ctx, params)?.into_wasm_values().collect()) + Ok(()) } fn call_stack(&self, store: &mut Store, module_id: ModuleInstanceId, type_addr: TypeAddr) -> Result<()> { - let params = store.state.get_canonical_func_type(type_addr).params(); - let base = store.value_stack.base_before(params.iter().collect()); - let mut values = store.value_stack.wasm_values(&store.state, params, base, true); - let params = P::from_wasm_values(&mut values).and_then(|params| { - if values.next().is_some() { - Err(crate::Error::other("typed conversion did not consume all WebAssembly values")) - } else { - Ok(params) - } - }); - drop(values); + let base = { + let params = store.state.get_canonical_func_type(type_addr).params(); + store.value_stack.base_before(params.iter().collect()) + }; + let params = { + let mut values = store.stack_value_iter(type_addr, FuncValueTypes::Params, base)?; + P::from_wasm_values_exact(&mut values) + }; store.value_stack.truncate_to_base(base); - let params = params?; - let result = (self.func)(FuncContext { store, module_id }, params)?; + let result = (self.func)(FuncContext { store, module_id }, params?)?; store.push_typed_values::(type_addr, result.into_wasm_values(), base) } } diff --git a/crates/tinywasm/src/func/mod.rs b/crates/tinywasm/src/func/mod.rs index 34a1938..c29b3db 100644 --- a/crates/tinywasm/src/func/mod.rs +++ b/crates/tinywasm/src/func/mod.rs @@ -1,9 +1,11 @@ use crate::interpreter::stack::{CallFrame, StackBase}; use crate::reference::StoreItem; use crate::{Error, FunctionInstance, InterpreterRuntime, Result, Store}; -use alloc::{format, vec::Vec}; +use alloc::format; use core::hint::cold_path; -use tinywasm_types::{FuncAddr, FuncType, ModuleInstanceId, WasmValue}; +use tinywasm_types::{FuncAddr, FuncType, ModuleInstanceId}; + +use crate::{FuncRef, WasmValue}; mod context; mod host; @@ -12,11 +14,21 @@ mod values; pub use context::FuncContext; pub use host::HostFunction; pub use resume::{ExecProgress, FuncExecution, FuncExecutionTyped}; -#[allow(deprecated)] -pub use values::WasmTupleChain; pub use values::{FromWasmValues, IntoWasmValues, ToWasmType, ToWasmTypes}; -/// A function handle +fn write_typed_params(params: &mut [WasmValue], mut values: impl Iterator) -> Result<()> { + for param in params { + *param = values.next().ok_or_else(|| Error::other("not enough typed function parameters"))?; + } + if values.next().is_some() { + return Err(Error::other("too many typed function parameters")); + } + Ok(()) +} + +/// A handle to a function instance in a store. +/// +/// See #[derive(Clone)] #[cfg_attr(feature = "debug", derive(core::fmt::Debug))] pub struct Function { @@ -25,6 +37,12 @@ pub struct Function { } impl Function { + /// Returns this function as a Store-aware WebAssembly function reference. + pub fn as_func_ref(&self, store: &Store) -> Result { + self.item.validate_store(store)?; + Ok(FuncRef::new(store.store_id(), self.addr())) + } + #[inline] /// Returns the function's address in its store. pub(crate) const fn addr(&self) -> FuncAddr { @@ -39,23 +57,24 @@ impl Function { Ok(store.state.get_func_type(self.addr())) } - /// Call a function (Invocation) + /// Calls the function and writes its results to `results`. /// - /// See + /// The initial result values are ignored. The result slice length must + /// match the function signature. #[inline] - pub fn call(&self, store: &mut Store, params: &[WasmValue]) -> Result> { - self.item.validate_store(store)?; - self.validate_params(store, params)?; + pub fn call(&self, store: &mut Store, params: &[WasmValue], results: &mut [WasmValue]) -> Result<()> { + self.validate_call(store, params, results.len())?; store.enter_execution()?; store.call_stack.clear(); store.value_stack.clear(); - let result = self.call_untyped(store, params, 0, StackBase::default()); + let result = self.call_untyped(store, params, results, 0, StackBase::default()); store.exit_execution(); result } - fn validate_params(&self, store: &Store, params: &[WasmValue]) -> Result<()> { + fn validate_call(&self, store: &Store, params: &[WasmValue], result_count: usize) -> Result<()> { + self.item.validate_store(store)?; let func_ty = store.state.get_func_type(self.addr()); if func_ty.params().len() != params.len() { cold_path(); @@ -66,17 +85,29 @@ impl Function { ))); } - if !func_ty.params().iter().zip(params).all(|(ty, param)| store.state.value_matches_type(*param, *ty)) { + for param in params { + if matches!(param, WasmValue::Ref(_)) { + param.to_runtime(store)?; + } + } + + if !func_ty.params().iter().zip(params).all(|(ty, param)| store.value_matches_type(param, *ty)) { cold_path(); #[cfg(feature = "debug")] return Err(Error::Other(format!( "param type mismatch: expected {:?}, got {:?}", func_ty.params(), - params.iter().map(|v| v.ty()).collect::>() + params.iter().map(|v| v.ty()).collect::>() ))); #[cfg(not(feature = "debug"))] return Err(Error::Other("param type mismatch".into())); } + if func_ty.results().len() != result_count { + return Err(Error::Other(format!( + "result count mismatch: expected {}, got {result_count}", + func_ty.results().len() + ))); + } Ok(()) } @@ -85,35 +116,36 @@ impl Function { &self, store: &mut Store, params: &[WasmValue], + results: &mut [WasmValue], call_stack_base: u32, value_stack_base: StackBase, - ) -> Result> { + ) -> Result<()> { let instance = store.state.get_func(self.addr()); let type_addr = instance.type_addr; - let results_may_gc = instance.gc.results; - let result = match &instance.kind { + match &instance.kind { crate::store::FunctionKind::Host(host) => { let host = host.clone(); - host.call_values(store, self.module_id, type_addr, params) + host.call_values(store, self.module_id, type_addr, params, results) } crate::store::FunctionKind::Wasm(wasm) => { let wasm_params = wasm.func.params; let wasm_locals = wasm.func.locals; - let locals_base = - store.value_stack.enter_wasm_call(params, wasm_params, wasm_locals, value_stack_base)?; + store + .push_wasm_values(params.iter().cloned()) + .inspect_err(|_| store.value_stack.truncate_to_base(value_stack_base))?; + let locals_base = store + .value_stack + .enter_locals(&wasm_params, &wasm_locals) + .inspect_err(|_| store.value_stack.truncate_to_base(value_stack_base))?; let callframe = CallFrame::new(self.addr(), locals_base, wasm_locals); InterpreterRuntime::exec(store, callframe, call_stack_base).inspect_err(|_| { store.call_stack.truncate_to(call_stack_base); store.value_stack.truncate_to_base(value_stack_base); })?; - let result_types = store.state.get_canonical_func_type(type_addr).results(); - Ok(store.value_stack.pop_wasmvalues(&store.state, result_types)) + let result_type = store.state.get_canonical_func_type(type_addr).clone(); + store.pop_stack_values(result_type.results(), results) } - }; - if results_may_gc && let Ok(values) = &result { - store.state.pin_host_values(values); } - result } fn prepare_typed( @@ -157,7 +189,7 @@ impl Function { store.value_stack.truncate_to_base(value_stack_base); })?; } - store.take_typed_results(instance.type_addr, value_stack_base, instance.gc.results) + store.take_typed_results(instance.type_addr, value_stack_base) } } @@ -178,24 +210,24 @@ impl FunctionTyped { self.func.item.validate_store(store)?; let func = store.state.get_func(self.func.addr()).clone(); if matches!(&func.kind, crate::store::FunctionKind::Host(host) if host.typed_callback().is_none()) { - let params = params.into_wasm_values().collect::>(); - let result = self.func.call(store, ¶ms)?; - let mut values = result.into_iter(); - let result = R::from_wasm_values(&mut values)?; - return if values.next().is_none() { - Ok(result) - } else { - Err(Error::other("typed conversion did not consume all WebAssembly values")) + let ty = store.state.get_canonical_func_type(func.type_addr); + let (param_count, result_count) = (ty.params().len(), ty.results().len()); + store.with_scratch_values(param_count + result_count, |store, values| { + write_typed_params(&mut values[..param_count], params.into_wasm_values())?; + let (params, results) = values.split_at_mut(param_count); + self.func.call(store, params, results)?; + values.drain(..param_count); + R::from_wasm_values_exact(&mut values.drain(..)) + }) + } else { + store.enter_execution()?; + let result: Result = { + store.call_stack.clear(); + store.value_stack.clear(); + self.func.call_typed(store, &func, params.into_wasm_values(), 0, StackBase::default()) }; + store.exit_execution(); + result } - - store.enter_execution()?; - let result: Result = { - store.call_stack.clear(); - store.value_stack.clear(); - self.func.call_typed(store, &func, params.into_wasm_values(), 0, StackBase::default()) - }; - store.exit_execution(); - result } } diff --git a/crates/tinywasm/src/func/resume.rs b/crates/tinywasm/src/func/resume.rs index 892aa05..6772eb8 100644 --- a/crates/tinywasm/src/func/resume.rs +++ b/crates/tinywasm/src/func/resume.rs @@ -1,9 +1,8 @@ -use alloc::vec::Vec; -use tinywasm_types::{FuncAddr, TypeAddr, WasmValue}; +use tinywasm_types::{FuncAddr, TypeAddr}; use super::{FromWasmValues, Function, FunctionTyped, IntoWasmValues}; use crate::interpreter::stack::{CallFrame, StackBase}; -use crate::{Error, InterpreterRuntime, Result, Store}; +use crate::{Error, InterpreterRuntime, Result, Store, WasmValue}; #[derive(Clone, PartialEq, Eq)] /// Progress for fuel-limited function execution. @@ -17,6 +16,12 @@ pub enum ExecProgress { /// Resumable execution for an untyped function call. #[cfg_attr(feature = "debug", derive(core::fmt::Debug))] pub struct FuncExecution<'store> { + execution: ExecutionCore<'store>, + results: &'store mut [WasmValue], +} + +#[cfg_attr(feature = "debug", derive(core::fmt::Debug))] +struct ExecutionCore<'store> { store: &'store mut Store, state: FuncExecutionState, } @@ -29,15 +34,15 @@ enum FuncExecutionState { #[cfg_attr(feature = "debug", derive(core::fmt::Debug))] enum CallResult { - Stack { type_addr: TypeAddr, pin_refs: bool }, - Values(Vec), + Stack { type_addr: TypeAddr }, + Written, } /// Resumable execution for a typed function call. #[cfg_attr(feature = "debug", derive(core::fmt::Debug))] pub struct FuncExecutionTyped<'store, R> { - execution: FuncExecution<'store>, - marker: core::marker::PhantomData, + execution: ExecutionCore<'store>, + result: Option, } impl Function { @@ -50,30 +55,24 @@ impl Function { &self, store: &'store mut Store, params: &[WasmValue], + results: &'store mut [WasmValue], ) -> Result> { - self.item.validate_store(store)?; - self.validate_params(store, params)?; - let results_may_gc = store.state.get_func(self.addr()).gc.results; + self.validate_call(store, params, results.len())?; store.enter_execution()?; let result: Result = (|| { let func_instance = store.state.get_func(self.addr()).clone(); match &func_instance.kind { crate::store::FunctionKind::Host(host_func) => { - let result = - host_func.clone().call_values(store, self.module_id, func_instance.type_addr, params)?; - Ok(FuncExecutionState::Completed(Some(CallResult::Values(result)))) + host_func.clone().call_values(store, self.module_id, func_instance.type_addr, params, results)?; + Ok(FuncExecutionState::Completed(Some(CallResult::Written))) } crate::store::FunctionKind::Wasm(wasm_func) => { store.call_stack.clear(); store.value_stack.clear(); let locals = wasm_func.func.locals; - let locals_base = store.value_stack.enter_wasm_call( - params, - wasm_func.func.params, - locals, - StackBase::default(), - )?; + store.push_wasm_values(params.iter().cloned())?; + let locals_base = store.value_stack.enter_locals(&wasm_func.func.params, &locals)?; let callframe = CallFrame::new(self.addr(), locals_base, locals); Ok(FuncExecutionState::Running { callframe, root_func_addr: self.addr() }) @@ -83,14 +82,11 @@ impl Function { store.exit_execution(); let state = result?; - if results_may_gc && let FuncExecutionState::Completed(Some(CallResult::Values(values))) = &state { - store.state.pin_host_values(values); - } - Ok(FuncExecution { store, state }) + Ok(FuncExecution { execution: ExecutionCore { store, state }, results }) } } -impl<'store> FuncExecution<'store> { +impl ExecutionCore<'_> { fn resume_raw( &mut self, run: impl FnOnce(&mut Store, CallFrame) -> Result, @@ -123,9 +119,8 @@ impl<'store> FuncExecution<'store> { crate::interpreter::ExecState::Completed => { let func = self.store.state.get_func(root_func_addr); let result_ty = func.type_addr; - let results_may_gc = func.gc.results; self.state = FuncExecutionState::Completed(None); - Ok(ExecProgress::Completed(CallResult::Stack { type_addr: result_ty, pin_refs: results_may_gc })) + Ok(ExecProgress::Completed(CallResult::Stack { type_addr: result_ty })) } crate::interpreter::ExecState::Suspended(callframe) => { let FuncExecutionState::Running { callframe: current, .. } = &mut self.state else { @@ -136,21 +131,20 @@ impl<'store> FuncExecution<'store> { } } } +} +impl FuncExecution<'_> { fn resume( &mut self, run: impl FnOnce(&mut Store, CallFrame) -> Result, - ) -> Result>> { - match self.resume_raw(run)? { - ExecProgress::Completed(CallResult::Stack { type_addr, pin_refs }) => { - let types = self.store.state.get_canonical_func_type(type_addr).results(); - let values = self.store.value_stack.pop_wasmvalues(&self.store.state, types); - if pin_refs { - self.store.state.pin_host_values(&values); - } - Ok(ExecProgress::Completed(values)) + ) -> Result> { + match self.execution.resume_raw(run)? { + ExecProgress::Completed(CallResult::Stack { type_addr }) => { + let ty = self.execution.store.state.get_canonical_func_type(type_addr).clone(); + self.execution.store.pop_stack_values(ty.results(), self.results)?; + Ok(ExecProgress::Completed(())) } - ExecProgress::Completed(CallResult::Values(values)) => Ok(ExecProgress::Completed(values)), + ExecProgress::Completed(CallResult::Written) => Ok(ExecProgress::Completed(())), ExecProgress::Suspended => Ok(ExecProgress::Suspended), } } @@ -161,13 +155,13 @@ impl<'store> FuncExecution<'store> { /// fuel before returning [`ExecProgress::Suspended`] (currently the chunk size is 128 instructions between fuel checks, but this may change in the future). /// /// Returns [`ExecProgress::Suspended`] when fuel is exhausted, or - /// [`ExecProgress::Completed`] with the final values once the invocation - /// returns. + /// [`ExecProgress::Completed`] after writing the final values to the result + /// slice supplied to [`Function::call_resumable`]. /// /// Reentrant calls made by host functions through [`crate::FuncContext::call`] are /// currently blocking. They do not suspend and later resume the host /// function in the middle of the nested call. - pub fn resume_with_fuel(&mut self, fuel: u32) -> Result>> { + pub fn resume_with_fuel(&mut self, fuel: u32) -> Result> { self.resume(|store, callframe| InterpreterRuntime::exec_with_fuel(store, callframe, fuel)) } @@ -180,10 +174,7 @@ impl<'store> FuncExecution<'store> { /// /// Reentrant calls made by host functions through [`crate::FuncContext::call`] /// are blocking and do not suspend in the middle of the host callback. - pub fn resume_with_time_budget( - &mut self, - time_budget: crate::std::time::Duration, - ) -> Result>> { + pub fn resume_with_time_budget(&mut self, time_budget: crate::std::time::Duration) -> Result> { self.resume(|store, callframe| InterpreterRuntime::exec_with_time_budget(store, callframe, time_budget)) } } @@ -215,9 +206,9 @@ impl FunctionTyped { self.func.item.validate_store(store)?; let func = store.state.get_func(self.func.addr()).clone(); if matches!(&func.kind, crate::store::FunctionKind::Host(host) if host.typed_callback().is_none()) { - let params = params.into_wasm_values().collect::>(); - let execution = self.func.call_resumable(store, ¶ms)?; - return Ok(FuncExecutionTyped { execution, marker: core::marker::PhantomData }); + let result = self.call(store, params)?; + let execution = ExecutionCore { store, state: FuncExecutionState::Completed(None) }; + return Ok(FuncExecutionTyped { execution, result: Some(result) }); } store.enter_execution()?; @@ -226,15 +217,12 @@ impl FunctionTyped { store.value_stack.clear(); match self.func.prepare_typed(store, &func, params.into_wasm_values(), StackBase::default())? { Some(callframe) => Ok(FuncExecutionState::Running { callframe, root_func_addr: self.func.addr() }), - None => Ok(FuncExecutionState::Completed(Some(CallResult::Stack { - type_addr: func.type_addr, - pin_refs: func.gc.results, - }))), + None => Ok(FuncExecutionState::Completed(Some(CallResult::Stack { type_addr: func.type_addr }))), } })(); store.exit_execution(); - let execution = FuncExecution { store, state: result? }; - Ok(FuncExecutionTyped { execution, marker: core::marker::PhantomData }) + let execution = ExecutionCore { store, state: result? }; + Ok(FuncExecutionTyped { execution, result: None }) } } @@ -243,18 +231,14 @@ impl<'store, R: FromWasmValues> FuncExecutionTyped<'store, R> { &mut self, run: impl FnOnce(&mut Store, CallFrame) -> Result, ) -> Result> { + if let Some(result) = self.result.take() { + return Ok(ExecProgress::Completed(result)); + } match self.execution.resume_raw(run)? { - ExecProgress::Completed(CallResult::Stack { type_addr, pin_refs }) => Ok(ExecProgress::Completed( - self.execution.store.take_typed_results(type_addr, StackBase::default(), pin_refs)?, - )), - ExecProgress::Completed(CallResult::Values(values)) => { - let mut values = values.into_iter(); - let result = R::from_wasm_values(&mut values)?; - if values.next().is_some() { - return Err(Error::other("typed conversion did not consume all WebAssembly values")); - } - Ok(ExecProgress::Completed(result)) + ExecProgress::Completed(CallResult::Stack { type_addr }) => { + Ok(ExecProgress::Completed(self.execution.store.take_typed_results(type_addr, StackBase::default())?)) } + ExecProgress::Completed(CallResult::Written) => unreachable!("untyped result in typed execution"), ExecProgress::Suspended => Ok(ExecProgress::Suspended), } } diff --git a/crates/tinywasm/src/func/values.rs b/crates/tinywasm/src/func/values.rs index 319b493..19d0673 100644 --- a/crates/tinywasm/src/func/values.rs +++ b/crates/tinywasm/src/func/values.rs @@ -1,6 +1,8 @@ use crate::{Error, Result}; -use alloc::{borrow::Cow, vec::Vec}; -use tinywasm_types::{ExternRef, FuncRef, WasmType, WasmValue}; +use alloc::borrow::Cow; +use tinywasm_types::WasmType; + +use crate::{AnyRef, ArrayRef, EqRef, ExnRef, ExternRef, FuncRef, I31Ref, StructRef, WasmValue}; /// Convert a Rust value or tuple into WebAssembly values. pub trait IntoWasmValues { @@ -12,6 +14,15 @@ pub trait IntoWasmValues { pub trait FromWasmValues: Sized { /// Read this value from a flattened WebAssembly value iterator. fn from_wasm_values(values: &mut impl Iterator) -> Result; + + /// Read one value and reject unconsumed iterator items. + fn from_wasm_values_exact(values: &mut impl Iterator) -> Result { + let result = Self::from_wasm_values(values)?; + if values.next().is_some() { + return Err(Error::other("typed conversion did not consume all WebAssembly values")); + } + Ok(result) + } } /// Describes the WebAssembly value types produced by a Rust value or tuple shape. @@ -117,70 +128,28 @@ impl_scalar_wasm_traits!( i64 => WasmType::I64, f32 => WasmType::F32, f64 => WasmType::F64, - FuncRef => WasmType::Ref(tinywasm_types::RefType::FUNCREF), - ExternRef => WasmType::Ref(tinywasm_types::RefType::EXTERNREF), + [u8; 16] => WasmType::V128, + FuncRef => WasmType::Ref(tinywasm_types::RefType::FUNCREF.with_nullability(false)), + AnyRef => WasmType::Ref(tinywasm_types::RefType::new_abstract(false, tinywasm_types::AbstractHeapType::Any)), + EqRef => WasmType::Ref(tinywasm_types::RefType::new_abstract(false, tinywasm_types::AbstractHeapType::Eq)), + I31Ref => WasmType::Ref(tinywasm_types::RefType::new_abstract(false, tinywasm_types::AbstractHeapType::I31)), + StructRef => WasmType::Ref(tinywasm_types::RefType::new_abstract(false, tinywasm_types::AbstractHeapType::Struct)), + ArrayRef => WasmType::Ref(tinywasm_types::RefType::new_abstract(false, tinywasm_types::AbstractHeapType::Array)), + ExternRef => WasmType::Ref(tinywasm_types::RefType::EXTERNREF.with_nullability(false)), + ExnRef => WasmType::Ref(tinywasm_types::RefType::EXNREF.with_nullability(false)), ); -impl_tuple_traits!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20); - -/// Concatenates two typed parameter or result groups. -/// -/// Direct tuple conversions are supported up to arity 20. Use untyped functions -/// for larger signatures. -#[deprecated(note = "direct tuples are supported up to arity 20, use untyped functions for larger signatures")] -#[derive(Default)] -pub struct WasmTupleChain(T1, T2); - -#[allow(deprecated)] -impl WasmTupleChain { - /// Create a new concatenated tuple wrapper. - pub const fn new(left: T1, right: T2) -> Self { - Self(left, right) - } - - /// Split the wrapper back into its two component values. - pub fn into_inner(self) -> (T1, T2) { - (self.0, self.1) - } -} - -#[allow(deprecated)] -impl From<(T1, T2)> for WasmTupleChain { - fn from((left, right): (T1, T2)) -> Self { - Self::new(left, right) - } -} - -#[allow(deprecated)] -impl ToWasmTypes for WasmTupleChain { - const WASM_TYPES: Option<&'static [WasmType]> = None; - - #[inline] - fn wasm_types() -> Cow<'static, [WasmType]> { - let mut types = Vec::new(); - types.extend_from_slice(&T1::wasm_types()); - types.extend_from_slice(&T2::wasm_types()); - Cow::Owned(types) - } -} -#[allow(deprecated)] -impl IntoWasmValues for WasmTupleChain { - #[inline] - fn into_wasm_values(self) -> impl Iterator { - let (left, right) = self.into_inner(); - left.into_wasm_values().chain(right.into_wasm_values()) - } -} - -#[allow(deprecated)] -impl FromWasmValues for WasmTupleChain { - #[inline] - fn from_wasm_values(values: &mut impl Iterator) -> Result { - let left = T1::from_wasm_values(values)?; - let right = T2::from_wasm_values(values)?; - Ok(Self::new(left, right)) - } -} +impl_scalar_wasm_traits!( + Option => WasmType::Ref(tinywasm_types::RefType::FUNCREF), + Option => WasmType::Ref(tinywasm_types::RefType::new_abstract(true, tinywasm_types::AbstractHeapType::Any)), + Option => WasmType::Ref(tinywasm_types::RefType::new_abstract(true, tinywasm_types::AbstractHeapType::Eq)), + Option => WasmType::Ref(tinywasm_types::RefType::new_abstract(true, tinywasm_types::AbstractHeapType::I31)), + Option => WasmType::Ref(tinywasm_types::RefType::new_abstract(true, tinywasm_types::AbstractHeapType::Struct)), + Option => WasmType::Ref(tinywasm_types::RefType::new_abstract(true, tinywasm_types::AbstractHeapType::Array)), + Option => WasmType::Ref(tinywasm_types::RefType::EXTERNREF), + Option => WasmType::Ref(tinywasm_types::RefType::EXNREF), +); +impl_tuple_traits!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20); impl ToWasmTypes for () { const WASM_TYPES: Option<&'static [WasmType]> = Some(&[]); diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs index eb2351b..6859bbf 100644 --- a/crates/tinywasm/src/imports.rs +++ b/crates/tinywasm/src/imports.rs @@ -66,17 +66,20 @@ impl_conv! { /// Ok(()) /// }); /// -/// let table = Table::new( +/// let table = Table::try_new( /// &mut store, /// TableType::new(tinywasm::types::RefType::FUNCREF, 10, Some(20)), /// tinywasm::types::RefValue::Null.into(), /// )?; -/// let memory = Memory::new( +/// let memory = Memory::try_new( /// &mut store, /// MemoryType::default().with_page_count_initial(1).with_page_count_max(Some(2)), /// )?; -/// let global_i32 = -/// Global::new(&mut store, GlobalType::default().with_ty(WasmType::I32), WasmValue::I32(666))?; +/// let global_i32 = Global::try_new( +/// &mut store, +/// GlobalType::default().with_ty(WasmType::I32), +/// WasmValue::I32(666), +/// )?; /// /// imports /// .define("my_module", "print_i32", print_i32) diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index 6700d53..4a92212 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -3,8 +3,11 @@ use core::hint::cold_path; use tinywasm_types::*; use crate::func::{FromWasmValues, IntoWasmValues, ToWasmTypes}; +use crate::reference::StoreId; use crate::store::MemoryInstance; -use crate::{Error, Function, FunctionTyped, Global, Imports, Memory, Result, Store, StoreItem, Table, Tag, Trap}; +use crate::{ + Error, Function, FunctionTyped, Global, Imports, Memory, Result, Store, StoreItem, Table, Tag, Trap, WasmValue, +}; /// A typed view over an exported extern value. pub enum ExternItem { @@ -47,7 +50,7 @@ pub struct ModuleInstance(Rc); #[cfg_attr(feature = "debug", derive(Debug))] struct ModuleInstanceInner { - store_id: u32, + store_id: StoreId, id: ModuleInstanceId, type_addrs: Box<[TypeAddr]>, func_addrs: Box<[FuncAddr]>, @@ -121,7 +124,7 @@ impl ModuleInstance { #[inline] pub(crate) fn validate_store(&self, store: &Store) -> Result<()> { - if self.0.store_id != store.id() { + if self.0.store_id != store.store_id() { return cold!(Err(Trap::InvalidStore.into())); } Ok(()) @@ -160,9 +163,9 @@ impl ModuleInstance { /// let mut store = Store::default(); /// let instance = ModuleInstance::instantiate_no_start(&mut store, &module, None)?; /// - /// assert_eq!(instance.global_get(&store, "g")?, 0.into()); + /// assert_eq!(instance.global_get(&mut store, "g")?, 0.into()); /// instance.start(&mut store)?; - /// assert_eq!(instance.global_get(&store, "g")?, 42.into()); + /// assert_eq!(instance.global_get(&mut store, "g")?, 42.into()); /// # Ok(()) /// # } /// ``` @@ -189,7 +192,7 @@ impl ModuleInstance { store.init_data(&addrs.memories, &addrs.globals, &addrs.funcs, &module.data, &type_addrs)?; let instance = ModuleInstanceInner { - store_id: store.id(), + store_id: store.store_id(), id, type_addrs, func_addrs: addrs.funcs.into_boxed_slice(), @@ -213,7 +216,7 @@ impl ModuleInstance { } /// Get a export by name - pub fn export_addr(&self, name: &str) -> Option { + pub(crate) fn export_addr(&self, name: &str) -> Option { let export = self.0.exports.iter().find(|e| *e.name == *name)?; let addr = match export.kind { ExternalKind::Func => self.0.func_addrs.get(export.index as usize)?, @@ -312,7 +315,7 @@ impl ModuleInstance { /// let ExternItem::Global(global) = instance.extern_item("answer")? else { /// panic!("expected global export"); /// }; - /// assert_eq!(global.get(&store)?, 42.into()); + /// assert_eq!(global.get(&mut store)?, 42.into()); /// # Ok(()) /// # } /// ``` @@ -346,8 +349,9 @@ impl ModuleInstance { /// # let mut store = Store::default(); /// let instance = ModuleInstance::instantiate(&mut store, &module, None)?; /// let add = instance.func_untyped(&store, "add")?; - /// let result = add.call(&mut store, &[WasmValue::I32(20), WasmValue::I32(22)])?; - /// assert_eq!(result, vec![WasmValue::I32(42)]); + /// let mut results = [WasmValue::I32(0)]; + /// add.call(&mut store, &[WasmValue::I32(20), WasmValue::I32(22)], &mut results)?; + /// assert_eq!(results, [WasmValue::I32(42)]); /// # Ok(()) /// # } /// ``` @@ -516,7 +520,7 @@ impl ModuleInstance { } /// Get the value of a global export by name. - pub fn global_get(&self, store: &Store, name: &str) -> Result { + pub fn global_get(&self, store: &mut Store, name: &str) -> Result { self.global(name)?.get(store) } @@ -601,9 +605,9 @@ impl ModuleInstance { /// let mut store = Store::default(); /// let instance = ModuleInstance::instantiate_no_start(&mut store, &module, None)?; /// - /// assert_eq!(instance.global_get(&store, "g")?, 0.into()); + /// assert_eq!(instance.global_get(&mut store, "g")?, 0.into()); /// assert_eq!(instance.start(&mut store)?, Some(())); - /// assert_eq!(instance.global_get(&store, "g")?, 7.into()); + /// assert_eq!(instance.global_get(&mut store, "g")?, 7.into()); /// # Ok(()) /// # } /// ``` @@ -611,7 +615,7 @@ impl ModuleInstance { /// See pub fn start(&self, store: &mut Store) -> Result> { match self.start_func(store)? { - Some(func) => func.call(store, &[]).map(|_| Some(())), + Some(func) => func.call(store, &[], &mut []).map(|_| Some(())), None => Ok(None), } } diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index a50c1fa..5f218fd 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -913,58 +913,46 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.cf.instr_ptr = target_ip as usize; } - fn create_exception(&mut self, tag_index: TagAddr) -> Result { + fn create_exception(&mut self, tag_index: TagAddr) -> Result { let tag_addr = self.module.resolve_tag_addr(tag_index); let type_addr = self.store.state.get_tag(tag_addr).type_addr; - let addr = cold_err!(u32::try_from(self.store.state.exceptions.len())).map_err(|_| Trap::OutOfMemory)?; - cold_err!(self.store.state.exceptions.try_reserve(1)).map_err(|_| Trap::OutOfMemory)?; - let params = self.store.state.get_canonical_func_type(type_addr).params(); + let payload_len = self.store.state.get_canonical_func_type(type_addr).params().len(); + self.store.state.gc.check_allocation(payload_len, true)?; let mut payload = Vec::new(); - cold_err!(payload.try_reserve_exact(params.len())).map_err(|_| Trap::OutOfMemory)?; + cold_err!(payload.try_reserve_exact(payload_len)).map_err(|_| Trap::OutOfMemory)?; let value_stack = &mut self.store.value_stack; - for &ty in params.iter().rev() { + for index in (0..payload_len).rev() { + let ty = self.store.state.get_canonical_func_type(type_addr).params()[index]; payload.push(match ty { - WasmType::I32 | WasmType::F32 => TinyWasmValue::Value32(Value32::stack_pop(value_stack)), - WasmType::I64 | WasmType::F64 => TinyWasmValue::Value64(Value64::stack_pop(value_stack)), - WasmType::V128 => TinyWasmValue::Value128(Value128::stack_pop(value_stack)), - WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::stack_pop(value_stack)), + WasmType::I32 | WasmType::F32 => RuntimeValue::Value32(Value32::stack_pop(value_stack)), + WasmType::I64 | WasmType::F64 => RuntimeValue::Value64(Value64::stack_pop(value_stack)), + WasmType::V128 => RuntimeValue::Value128(Value128::stack_pop(value_stack)), + WasmType::Ref(_) => RuntimeValue::ValueRef(ValueRef::stack_pop(value_stack)), }); } payload.reverse(); - let exception = crate::store::ExceptionInstance { tag_addr, payload: payload.into_boxed_slice() }; - self.store.state.exceptions.push(exception); - Ok(addr) + let roots = (&self.store.value_stack.stack_32).into_iter().copied().map(ValueRef::from_raw); + self.store.state.alloc_exception(tag_addr, payload, roots) } fn exec_throw(&mut self, tag_index: TagAddr) -> Result<()> { let exception = self.create_exception(tag_index)?; - let outcome = match self.dispatch_exception(exception) { - Ok(outcome) => outcome, - Err(trap) => { - _ = self.store.state.exceptions.pop(); - return Err(trap.into()); - } - }; - match outcome { - Some(catch) if !catch.with_ref() => { - debug_assert_eq!(self.store.state.exceptions.len() - 1, exception as usize); - _ = self.store.state.exceptions.pop(); - Ok(()) - } - Some(_) => Ok(()), - None => Err(Error::Exception(ExnRef::new(exception))), - } + self.throw_exception(exception) } fn exec_throw_ref(&mut self) -> Result<()> { let exception = ValueRef::stack_pop(&mut self.store.value_stack); - let exception = exception - .addr() - .filter(|addr| self.store.state.exceptions.get(*addr as usize).is_some()) - .ok_or(Trap::NullReference)?; - match self.dispatch_exception(exception)? { - Some(_) => Ok(()), - None => Err(Error::Exception(ExnRef::new(exception))), + if exception.is_null() { + return Err(Trap::NullReference.into()); + } + self.throw_exception(exception) + } + + fn throw_exception(&mut self, exception: ValueRef) -> Result<()> { + match self.dispatch_exception(exception) { + Ok(Some(_)) => Ok(()), + Ok(None) => self.store.root_exception(exception).and_then(|exception| Err(Error::Exception(exception))), + Err(trap) => Err(trap.into()), } } @@ -995,8 +983,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } } - fn dispatch_exception(&mut self, exception_addr: ExnAddr) -> Result, Trap> { - let tag_addr = self.store.state.exceptions[exception_addr as usize].tag_addr; + fn dispatch_exception(&mut self, exception: ValueRef) -> Result, Trap> { + let object = self.store.state.gc.get(exception).ok_or(Trap::InvalidReference)?; + let crate::store::GcObjectKind::Exception(tag_addr) = object.kind else { + return Err(Trap::InvalidReference); + }; let mut protected_ip = self.cf.instr_ptr; loop { if let Some(catch) = self.matching_catch(protected_ip, tag_addr) { @@ -1013,12 +1004,13 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.store.value_stack.truncate_to_base(target); if include_payload { let Store { state, value_stack, .. } = self.store; - for value in state.exceptions[exception_addr as usize].payload.iter().copied() { + let object = state.gc.get(exception).ok_or(Trap::InvalidReference)?; + for value in object.values.iter().copied() { value_stack.push_dyn(value)?; } } if with_ref { - self.store.value_stack.push(ValueRef::from_category_addr(exception_addr))?; + self.store.value_stack.push(exception)?; } self.cf.instr_ptr = landing_pad as usize; return Ok(Some(catch)); @@ -1078,12 +1070,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_call_host( - &mut self, - host_func: HostFunction, - type_addr: TypeAddr, - params_may_gc: bool, - ) -> Result { + fn exec_call_host(&mut self, host_func: HostFunction, type_addr: TypeAddr) -> Result { if let Some(host_func) = host_func.typed_callback() { cold_err!(host_func.call_stack(self.store, self.module.id(), type_addr)) .map_err(|error| Trap::HostFunction(Box::new(error)))?; @@ -1094,23 +1081,28 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { return Ok(false); } - let param_types = self.store.state.get_canonical_func_type(type_addr).params(); - let mut params = core::mem::take(&mut self.store.host_params); - debug_assert!(params.is_empty()); - cold_err!(params.try_reserve_exact(param_types.len())).map_err(|_| Trap::OutOfMemory)?; - for &ty in param_types.iter().rev() { - params.push(self.store.value_stack.pop_wasmvalue(&self.store.state, ty)); - } - params.reverse(); - if params_may_gc { - self.store.state.pin_host_values(¶ms); - } - let result = host_func.call_values(self.store, self.module.id(), type_addr, ¶ms); - params.clear(); - self.store.host_params = params; - let res = cold_err!(result).map_err(|error| Trap::HostFunction(Box::new(error)))?; - - self.store.value_stack.extend_wasmvalues(res.iter().copied())?; + let (param_count, result_count, base) = { + let ty = self.store.state.get_canonical_func_type(type_addr); + (ty.params().len(), ty.results().len(), self.store.value_stack.base_before(ty.params().iter().collect())) + }; + let module_id = self.module.id(); + self.store + .with_scratch_values(param_count + result_count, |store, values| { + let host_values = store.stack_value_iter(type_addr, crate::store::FuncValueTypes::Params, base)?; + for (slot, value) in values[..param_count].iter_mut().zip(host_values) { + *slot = value; + } + store.value_stack.truncate_to_base(base); + let (params, results) = values.split_at_mut(param_count); + host_func + .call_values(store, module_id, type_addr, params, results) + .map_err(|error| Error::Trap(Trap::HostFunction(Box::new(error))))?; + store.push_wasm_values(results.iter().cloned()) + }) + .map_err(|error| match error { + Error::Trap(trap) => trap, + other => Trap::HostFunction(Box::new(other)), + })?; if TAIL { Ok(self.exec_return()) } else { @@ -1128,7 +1120,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.exec_call(wasm_func.func.clone(), wasm_func.owner, addr) } crate::store::FunctionKind::Host(host_func) => { - self.exec_call_host::(host_func.clone(), func.type_addr, func.gc.params)?; + self.exec_call_host::(host_func.clone(), func.type_addr)?; Ok(()) } } @@ -1144,7 +1136,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(false) } crate::store::FunctionKind::Host(host_func) => { - self.exec_call_host::(host_func.clone(), func.type_addr, func.gc.params) + self.exec_call_host::(host_func.clone(), func.type_addr) } } } @@ -1174,7 +1166,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec_call_indirect(&mut self, index: OperandIdx) -> Result { let TwoU32 { first: type_addr, second: table_addr } = index.get(&self.func.data); self.charge_call_fuel(FUEL_COST_CALL_TOTAL); - // verify that the table is of the right type, this should be validated by the parser already let table_addr = self.module.resolve_table_addr(table_addr); let table_idx = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; @@ -1209,7 +1200,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { false => self.exec_call(wasm_func.func.clone(), wasm_func.owner, func_addr), }, crate::store::FunctionKind::Host(host_func) => { - return self.exec_call_host::(host_func.clone(), func.type_addr, func.gc.params); + return self.exec_call_host::(host_func.clone(), func.type_addr); } }?; Ok(false) @@ -1438,22 +1429,34 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.store.value_stack.push(value) } - fn push_gc_object(&mut self, type_addr: TypeAddr, values: Vec) -> Result<(), Trap> { - let roots = (&self.store.value_stack.stack_32).into_iter().copied(); + fn push_gc_object(&mut self, type_addr: TypeAddr, values: Vec) -> Result<(), Trap> { + let roots = (&self.store.value_stack.stack_32).into_iter().copied().map(ValueRef::from_raw); let reference = self.store.state.alloc_gc_object(type_addr, values, roots)?; self.store.value_stack.push(reference) } fn exec_struct_new(&mut self, type_index: TypeAddr, default: bool) -> Result<(), Trap> { let type_addr = self.module.resolve_type_addr(type_index); - let fields = &self.store.state.get_type(type_addr).as_struct().expect("validated struct.new type").fields; + let field_count = + self.store.state.get_type(type_addr).as_struct().expect("validated struct.new type").fields.len(); + self.store.state.check_gc_allocation(type_addr, field_count)?; let mut values = Vec::new(); - cold_err!(values.try_reserve_exact(fields.len())).map_err(|_| Trap::OutOfMemory)?; + cold_err!(values.try_reserve_exact(field_count)).map_err(|_| Trap::OutOfMemory)?; if default { - values.extend(fields.iter().map(|field| default_value(field.storage))); + values.extend( + self.store + .state + .get_type(type_addr) + .as_struct() + .expect("validated struct.new type") + .fields + .iter() + .map(|field| default_value(field.storage)), + ); } else { - for field in fields.iter().rev() { - values.push(pop_value(&mut self.store.value_stack, field.storage)); + for index in (0..field_count).rev() { + let storage = self.store.state.get_type(type_addr).as_struct().unwrap().fields[index].storage; + values.push(pop_value(&mut self.store.value_stack, storage)); } values.reverse(); } @@ -1468,6 +1471,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { [field_index as usize] .storage; let object = self.store.state.gc_object(reference, type_addr)?; + let object = self.store.state.gc.get_handle(object).ok_or(Trap::Other("invalid GC reference"))?; let value = *object.values.get(field_index as usize).expect("validated struct field index"); push_value(&mut self.store.value_stack, value, storage, signed) } @@ -1480,8 +1484,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { .storage; let value = pop_value(&mut self.store.value_stack, storage); let reference = ValueRef::stack_pop(&mut self.store.value_stack); - self.store.state.gc_object(reference, type_addr)?; - self.store.state.gc.set(reference, field_index as usize, value).expect("live struct field"); + let object = self.store.state.gc_object(reference, type_addr)?; + self.store.state.gc.set(object, field_index as usize, value).expect("live struct field"); Ok(()) } @@ -1489,6 +1493,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let type_addr = self.module.resolve_type_addr(type_index); let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.new type").field.storage; let len = u32::stack_pop(&mut self.store.value_stack) as usize; + self.store.state.check_gc_allocation(type_addr, len)?; let value = if default { default_value(storage) } else { pop_value(&mut self.store.value_stack, storage) }; let mut values = Vec::new(); cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; @@ -1502,6 +1507,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.new_fixed type").field.storage; let len = len as usize; + self.store.state.check_gc_allocation(type_addr, len)?; let mut values = Vec::new(); cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; for _ in 0..len { @@ -1517,6 +1523,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let type_addr = self.module.resolve_type_addr(type_index); let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.get type").field.storage; let object = self.store.state.gc_object(reference, type_addr)?; + let object = self.store.state.gc.get_handle(object).ok_or(Trap::Other("invalid GC reference"))?; let value = *object.values.get(index).ok_or(Trap::ArrayOutOfBounds)?; push_value(&mut self.store.value_stack, value, storage, signed) } @@ -1527,8 +1534,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let value = pop_value(&mut self.store.value_stack, storage); let index = u32::stack_pop(&mut self.store.value_stack) as usize; let reference = ValueRef::stack_pop(&mut self.store.value_stack); - self.store.state.gc_object(reference, type_addr)?; - self.store.state.gc.set(reference, index, value).ok_or(Trap::ArrayOutOfBounds) + let object = self.store.state.gc_object(reference, type_addr)?; + self.store.state.gc.set(object, index, value).ok_or(Trap::ArrayOutOfBounds) } fn exec_array_len(&mut self) -> Result<(), Trap> { @@ -1537,7 +1544,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { return Err(Trap::NullArrayReference); } let object = self.store.state.gc.get(reference).ok_or(Trap::Other("invalid GC reference"))?; - if self.store.state.get_type(object.type_addr).as_array().is_none() { + let crate::store::GcObjectKind::Composite(type_addr) = object.kind else { + return Err(Trap::Other("GC reference is not an array")); + }; + if self.store.state.get_type(type_addr).as_array().is_none() { return Err(Trap::Other("GC reference is not an array")); } self.store.value_stack.push(object.values.len() as i32) @@ -1551,8 +1561,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let index = u32::stack_pop(&mut self.store.value_stack) as usize; let reference = ValueRef::stack_pop(&mut self.store.value_stack); let object = self.store.state.gc_object(reference, type_addr)?; - let end = index.checked_add(len).filter(|end| *end <= object.values.len()).ok_or(Trap::ArrayOutOfBounds)?; - self.store.state.gc.fill(reference, index..end, value).expect("live array range"); + let object_ref = self.store.state.gc.get_handle(object).ok_or(Trap::Other("invalid GC reference"))?; + let end = index.checked_add(len).filter(|end| *end <= object_ref.values.len()).ok_or(Trap::ArrayOutOfBounds)?; + self.store.state.gc.fill(object, index..end, value).expect("live array range"); Ok(()) } @@ -1565,16 +1576,22 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let dst = ValueRef::stack_pop(&mut self.store.value_stack); let dst_type = self.module.resolve_type_addr(dst_type); let src_type = self.module.resolve_type_addr(src_type); - let dst_len = self.store.state.gc_object(dst, dst_type)?.values.len(); - let src_object = self.store.state.gc_object(src, src_type)?; + let dst_handle = self.store.state.gc_object(dst, dst_type)?; + let dst_len = self.store.state.gc.get_handle(dst_handle).expect("validated array").values.len(); + let src_handle = self.store.state.gc_object(src, src_type)?; + let src_object = self.store.state.gc.get_handle(src_handle).expect("validated array"); let src_end = src_index.checked_add(len).filter(|end| *end <= src_object.values.len()).ok_or(Trap::ArrayOutOfBounds)?; dst_index.checked_add(len).filter(|end| *end <= dst_len).ok_or(Trap::ArrayOutOfBounds)?; - if src == dst { - self.store.state.gc.copy_within(dst, src_index..src_end, dst_index).expect("live array range"); + if src_handle == dst_handle { + self.store.state.gc.copy_within(dst_handle, src_index..src_end, dst_index).expect("live array range"); return Ok(()); } - self.store.state.gc.copy_between(src, src_index..src_end, dst, dst_index).expect("live array ranges"); + self.store + .state + .gc + .copy_between(src_handle, src_index..src_end, dst_handle, dst_index) + .expect("live array ranges"); Ok(()) } @@ -1586,6 +1603,8 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let storage = self.store.state.get_type(type_addr).as_array().expect("validated array type").field.storage; let data_addr = self.module.resolve_data_addr(data_index); let data = self.store.state.data[data_addr as usize].data.as_deref().unwrap_or(&[]); + data_range(storage, data, src, len)?; + self.store.state.check_gc_allocation(type_addr, len)?; let values = decode_data(storage, data, src, len)?; self.push_gc_object(type_addr, values) } @@ -1594,12 +1613,13 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let TwoU32 { first: type_index, second: elem_index } = index.get(&self.func.data); let len = u32::stack_pop(&mut self.store.value_stack) as usize; let src = u32::stack_pop(&mut self.store.value_stack) as usize; + let type_addr = self.module.resolve_type_addr(type_index); let elem_addr = self.module.resolve_elem_addr(elem_index); let items = self.store.state.elements[elem_addr as usize].items_range(src, len)?; + self.store.state.check_gc_allocation(type_addr, len)?; let mut values = Vec::new(); cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; - values.extend(items.iter().copied().map(TinyWasmValue::ValueRef)); - let type_addr = self.module.resolve_type_addr(type_index); + values.extend(items.iter().copied().map(RuntimeValue::ValueRef)); self.push_gc_object(type_addr, values) } @@ -1611,12 +1631,13 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let reference = ValueRef::stack_pop(&mut self.store.value_stack); let type_addr = self.module.resolve_type_addr(type_index); let storage = self.store.state.get_type(type_addr).as_array().expect("validated array type").field.storage; - let object_len = self.store.state.gc_object(reference, type_addr)?.values.len(); + let object = self.store.state.gc_object(reference, type_addr)?; + let object_len = self.store.state.gc.get_handle(object).expect("validated array").values.len(); dst.checked_add(len).filter(|end| *end <= object_len).ok_or(Trap::ArrayOutOfBounds)?; let data = self.store.state.data[self.module.resolve_data_addr(data_index) as usize].data.as_deref().unwrap_or(&[]); let values = decode_data(storage, data, src, len)?; - self.store.state.gc.set_slice(reference, dst, &values).expect("live array range"); + self.store.state.gc.set_slice(object, dst, &values).expect("live array range"); Ok(()) } @@ -1627,14 +1648,15 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let dst = u32::stack_pop(&mut self.store.value_stack) as usize; let reference = ValueRef::stack_pop(&mut self.store.value_stack); let type_addr = self.module.resolve_type_addr(type_index); - let object_len = self.store.state.gc_object(reference, type_addr)?.values.len(); + let object = self.store.state.gc_object(reference, type_addr)?; + let object_len = self.store.state.gc.get_handle(object).expect("validated array").values.len(); dst.checked_add(len).filter(|end| *end <= object_len).ok_or(Trap::ArrayOutOfBounds)?; let items = self.store.state.elements[self.module.resolve_elem_addr(elem_index) as usize].items_range(src, len)?; let mut values = Vec::new(); cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; - values.extend(items.iter().copied().map(TinyWasmValue::ValueRef)); - self.store.state.gc.set_slice(reference, dst, &values).expect("live array range"); + values.extend(items.iter().copied().map(RuntimeValue::ValueRef)); + self.store.state.gc.set_slice(object, dst, &values).expect("live array range"); Ok(()) } diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index 62a9480..e123a41 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -1,6 +1,6 @@ -use alloc::{vec, vec::Vec}; +use alloc::vec::Vec; use core::hint::cold_path; -use tinywasm_types::{MemoryArch, ValueCounts, WasmType, WasmValue}; +use tinywasm_types::{MemoryArch, ValueCounts}; use super::StackBase; use crate::engine::{Config, StackConfig}; @@ -18,66 +18,6 @@ pub(crate) struct ValueStack { pub(crate) stack_128: Stack, } -struct WasmValues<'a> { - stack: &'a ValueStack, - state: &'a crate::store::State, - types: core::slice::Iter<'a, WasmType>, - index: StackBase, - pin_refs: bool, -} - -impl Iterator for WasmValues<'_> { - type Item = WasmValue; - - fn next(&mut self) -> Option { - let value = match *self.types.next()? { - WasmType::I32 => { - let value = *self.stack.stack_32.get(self.index.s32 as usize) as i32; - self.index.s32 += 1; - WasmValue::I32(value) - } - WasmType::I64 => { - let value = *self.stack.stack_64.get(self.index.s64 as usize) as i64; - self.index.s64 += 1; - WasmValue::I64(value) - } - WasmType::F32 => { - let value = f32::from_bits(*self.stack.stack_32.get(self.index.s32 as usize)); - self.index.s32 += 1; - WasmValue::F32(value) - } - WasmType::F64 => { - let value = f64::from_bits(*self.stack.stack_64.get(self.index.s64 as usize)); - self.index.s64 += 1; - WasmValue::F64(value) - } - WasmType::Ref(ty) => { - let value = - self.state.to_ref_value(ValueRef::from_raw(*self.stack.stack_32.get(self.index.s32 as usize)), ty); - self.index.s32 += 1; - WasmValue::Ref(value) - } - WasmType::V128 => { - let value = self.stack.stack_128.get(self.index.s128 as usize).0; - self.index.s128 += 1; - WasmValue::V128(value) - } - }; - if self.pin_refs - && let WasmValue::Ref(value) = value - { - self.state.pin_host_ref(value); - } - Some(value) - } - - fn size_hint(&self) -> (usize, Option) { - self.types.size_hint() - } -} - -impl ExactSizeIterator for WasmValues<'_> {} - #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) struct Stack { data: Vec, @@ -281,11 +221,6 @@ impl ValueStack { } } - #[inline(always)] - pub(crate) fn len(&self) -> usize { - self.stack_32.len() + self.stack_64.len() + self.stack_128.len() - } - #[inline(always)] pub(crate) fn push(&mut self, value: T) -> Result<(), Trap> { T::stack_push(self, value) @@ -325,19 +260,6 @@ impl ValueStack { Ok(StackBase { s32: locals_base32, s64: locals_base64, s128: locals_base128 }) } - #[inline] - /// Pushes call arguments and allocates the function's local lanes. - pub(crate) fn enter_wasm_call( - &mut self, - values: &[WasmValue], - params: ValueCounts, - locals: ValueCounts, - base: StackBase, - ) -> Result { - self.extend_wasmvalues(values.iter().copied()).inspect_err(|_| self.truncate_to_base(base))?; - self.enter_locals(¶ms, &locals).inspect_err(|_| self.truncate_to_base(base)) - } - #[inline(always)] pub(crate) fn truncate_keep_counts(&mut self, base: StackBase, keep: ValueCounts) { self.stack_32.truncate_keep(base.s32 as usize, keep.c32 as usize); @@ -352,57 +274,12 @@ impl ValueStack { self.stack_128.truncate_to(base.s128 as usize); } - pub(crate) fn push_dyn(&mut self, value: TinyWasmValue) -> Result<(), Trap> { + pub(crate) fn push_dyn(&mut self, value: RuntimeValue) -> Result<(), Trap> { match value { - TinyWasmValue::Value32(v) => self.stack_32.push(v), - TinyWasmValue::Value64(v) => self.stack_64.push(v), - TinyWasmValue::Value128(v) => self.stack_128.push(v), - TinyWasmValue::ValueRef(v) => self.stack_32.push(v.raw()), - } - } - - pub(crate) fn pop_wasmvalue(&mut self, state: &crate::store::State, val_type: WasmType) -> WasmValue { - match val_type { - WasmType::I32 => WasmValue::I32(self.stack_32.pop() as i32), - WasmType::I64 => WasmValue::I64(self.stack_64.pop() as i64), - WasmType::F32 => WasmValue::F32(f32::from_bits(self.stack_32.pop())), - WasmType::F64 => WasmValue::F64(f64::from_bits(self.stack_64.pop())), - WasmType::Ref(ty) => WasmValue::Ref(state.to_ref_value(ValueRef::from_raw(self.stack_32.pop()), ty)), - WasmType::V128 => WasmValue::V128(self.stack_128.pop().0), - } - } - - /// Pops values in their logical WebAssembly order. - pub(crate) fn pop_wasmvalues(&mut self, state: &crate::store::State, types: &[WasmType]) -> Vec { - debug_assert!(self.len() >= types.len()); - let mut values = vec![WasmValue::I32(0); types.len()]; - for (index, &ty) in types.iter().enumerate().rev() { - values[index] = self.pop_wasmvalue(state, ty); + RuntimeValue::Value32(v) => self.stack_32.push(v), + RuntimeValue::Value64(v) => self.stack_64.push(v), + RuntimeValue::Value128(v) => self.stack_128.push(v), + RuntimeValue::ValueRef(v) => self.stack_32.push(v.raw()), } - values - } - - pub(crate) fn wasm_values<'a>( - &'a self, - state: &'a crate::store::State, - types: &'a [WasmType], - index: StackBase, - pin_refs: bool, - ) -> impl ExactSizeIterator + 'a { - WasmValues { stack: self, state, types: types.iter(), index, pin_refs } - } - - pub(crate) fn extend_wasmvalues(&mut self, values: impl Iterator) -> Result<(), Trap> { - for value in values { - match value { - WasmValue::I32(v) => self.stack_32.push(v as u32)?, - WasmValue::I64(v) => self.stack_64.push(v as u64)?, - WasmValue::F32(v) => self.stack_32.push(v.to_bits())?, - WasmValue::F64(v) => self.stack_64.push(v.to_bits())?, - WasmValue::Ref(v) => self.stack_32.push(ValueRef::from(v).raw())?, - WasmValue::V128(v) => self.stack_128.push(Value128(v))?, - } - } - Ok(()) } } diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs index 2e0793b..22f20b7 100644 --- a/crates/tinywasm/src/interpreter/values.rs +++ b/crates/tinywasm/src/interpreter/values.rs @@ -1,7 +1,7 @@ use super::stack::{CallFrame, ValueStack}; use crate::store::Globals; -use crate::{Result, interpreter::simd::Value128}; -use tinywasm_types::{GlobalAddr, LocalAddr, RefValue, WasmValue}; +use crate::{Error, Result, Store, WasmValue, interpreter::simd::Value128}; +use tinywasm_types::{GlobalAddr, LocalAddr, WasmType}; pub(crate) type Value32 = u32; pub(crate) type Value64 = u64; @@ -34,6 +34,14 @@ impl ValueRef { Self(((value as u32) << 1) | 1) } + #[inline] + pub(crate) const fn try_from_host_any(addr: u32) -> Option { + if addr >= Self::HOST_ANY_TAG - 1 { + return None; + } + Some(Self::from_category_addr(addr | Self::HOST_ANY_TAG)) + } + pub(crate) const fn is_host_any(self) -> bool { matches!(self.addr(), Some(addr) if addr & Self::HOST_ANY_TAG != 0) } @@ -69,21 +77,9 @@ impl ValueRef { } } -impl From for ValueRef { - fn from(value: RefValue) -> Self { - match value { - RefValue::Null => Self::NULL, - RefValue::Func(value) => Self::from_category_addr(value.addr()), - RefValue::Extern(value) => Self::from_raw(value.raw()), - RefValue::Exn(value) => Self::from_category_addr(value.addr()), - RefValue::Any(value) => Self::from_raw(value.raw()), - } - } -} - #[derive(Debug, Clone, Copy, PartialEq, Eq)] /// An untyped internal WebAssembly value. -pub(crate) enum TinyWasmValue { +pub(crate) enum RuntimeValue { /// A 32-bit value. Value32(Value32), /// A 64-bit value. @@ -94,16 +90,17 @@ pub(crate) enum TinyWasmValue { ValueRef(ValueRef), } -impl From for TinyWasmValue { - fn from(value: WasmValue) -> Self { - match value { - WasmValue::I32(v) => Self::Value32(v as u32), - WasmValue::I64(v) => Self::Value64(v as u64), - WasmValue::F32(v) => Self::Value32(v.to_bits()), - WasmValue::F64(v) => Self::Value64(v.to_bits()), - WasmValue::Ref(value) => Self::ValueRef(value.into()), - WasmValue::V128(v) => Self::Value128(Value128(v)), - } +impl RuntimeValue { + pub(crate) fn into_wasm(self, store: &mut Store, ty: WasmType) -> Result { + Ok(match (self, ty) { + (Self::Value32(value), WasmType::I32) => WasmValue::I32(value as i32), + (Self::Value32(value), WasmType::F32) => WasmValue::F32(f32::from_bits(value)), + (Self::Value64(value), WasmType::I64) => WasmValue::I64(value as i64), + (Self::Value64(value), WasmType::F64) => WasmValue::F64(f64::from_bits(value)), + (Self::Value128(value), WasmType::V128) => WasmValue::V128(value.0), + (Self::ValueRef(value), WasmType::Ref(ty)) => WasmValue::Ref(store.decode_ref(value, ty)?), + _ => return Err(Error::other("internal value does not match its WebAssembly type")), + }) } } @@ -234,3 +231,13 @@ impl_internalvalue! { stack_32, s32, get_32, set_32, ValueRef, |v| v.raw(), |v| ValueRef(v) stack_128, s128, get_128, set_128, Value128, |v| v, |v| v } + +#[cfg(test)] +mod tests { + use super::ValueRef; + + #[test] + fn value_ref_remains_four_bytes() { + assert_eq!(core::mem::size_of::(), 4); + } +} diff --git a/crates/tinywasm/src/lib.rs b/crates/tinywasm/src/lib.rs index bd80ef1..15ccd0e 100644 --- a/crates/tinywasm/src/lib.rs +++ b/crates/tinywasm/src/lib.rs @@ -18,47 +18,48 @@ //! //! ## Getting started //! -//! The easiest way to get started is to use the `parse_bytes` function to load a -//! WebAssembly module from bytes. This will parse the module and validate it, returning -//! a [`Module`] that can be used to instantiate the module. +//! Use [`parse_bytes`] to parse and validate a WebAssembly module, then instantiate it +//! in a [`Store`]. A module can be reused, while each store owns its runtime state. //! //! ```rust //! # #[cfg(feature = "parser")] //! # fn main() -> tinywasm::Result<()> { //! use tinywasm::{ModuleInstance, Store}; //! -//! // Load a module from bytes //! let wasm = include_bytes!("../../../examples/wasm/add.wasm"); //! let module = tinywasm::parse_bytes(wasm)?; //! -//! // # Create a new store -//! // Stores are used to allocate objects like functions and globals //! let mut store = Store::default(); -//! -//! // # Instantiate the module -//! // This will allocate the module and its globals into the store -//! // and execute the module's start function. //! let instance = ModuleInstance::instantiate(&mut store, &module, None)?; //! -//! // # Get a typed handle to the exported "add" function -//! // Alternatively, you can use `instance.func_untyped` to get an untyped handle -//! // that takes and returns [`types::WasmValue`]s -//! let func = instance.func::<(i32, i32), i32>(&store, "add")?; -//! let res = func.call(&mut store, (1, 2))?; +//! let add = instance.func::<(i32, i32), i32>(&store, "add")?; +//! let result = add.call(&mut store, (1, 2))?; //! -//! assert_eq!(res, 3); +//! assert_eq!(result, 3); //! # Ok(()) //! # } //! # #[cfg(not(feature = "parser"))] //! # fn main() {} //! ``` //! -//! For non-default runtime behavior, construct a [`Store`] with a custom [`Engine`] -//! and [`engine::Config`] to control stack sizing and fuel accounting. A [`ResourceLimiter`] can be -//! attached to the engine configuration to bound memory and table allocation and growth for stores -//! created from that engine and to trap rejected requests. +//! Typed functions convert Rust values directly. Use [`ModuleInstance::func_untyped`] +//! and [`WasmValue`] when types are selected at runtime. References such as [`StructRef`] +//! and [`ExternRef`] are owned handles tied to their store. Cloning a managed reference +//! keeps its referent live. +//! +//! Construct a store with a custom [`Engine`] and [`engine::Config`] to configure +//! stack limits, fuel, and GC collection. A [`ResourceLimiter`] can bound guest memory, +//! table, and GC heap growth. +//! +//! ## References and GC +//! +//! Runtime references belong to a [`Store`]. Passing a reference to another store +//! returns [`Trap::InvalidStore`]. Managed references are cloneable owned handles, and +//! their referents become collectible after the last handle is dropped. Nullable typed +//! parameters and results use `Option`. Use [`RefValue`] for dynamic reference values +//! and [`Store::gc`] to request collection explicitly. //! -//! For more examples, see the [`examples`](https://github.com/explodingcamera/tinywasm/tree/main/examples) directory. +//! For more examples, see the [`examples`](https://github.com/explodingcamera/tinywasm/tree/next/examples) directory. //! //! ## Cargo features //! @@ -67,7 +68,7 @@ //! - **`parser`:** Enables `tinywasm-parser` and top-level parse helpers. Enabled by default. //! - **`validate`:** Enables WebAssembly validation while parsing. Enabled by default and configurable through `ParserOptions`. //! - **`archive`:** Enables serialization and deserialization of the internal `twasm` format. Enabled by default. -//! - **`canonicalize-nans`:** Canonicalizes NaN values. Enabled by default. +//! - **`canonicalize-nans`:** Uses a [canonical NaN](https://en.wikipedia.org/wiki/NaN#Canonical_NaN) for normalized NaN results. Enabled by default. //! - **`debug`:** Derives `Debug` for runtime types. Enabled by default. //! - **`parallel-parser`:** Parallelizes function parsing when `std` is enabled. Enabled by default. //! - **`guest-debug`:** Exposes module-internal by-index inspection APIs (`*_by_index`). @@ -108,8 +109,6 @@ pub(crate) mod log { mod error; pub use error::*; -#[allow(deprecated)] -pub use func::WasmTupleChain; pub use func::{ ExecProgress, FromWasmValues, FuncContext, FuncExecution, FuncExecutionTyped, Function, FunctionTyped, HostFunction, IntoWasmValues, ToWasmType, ToWasmTypes, @@ -145,6 +144,7 @@ pub use parser::{parse_file, parse_stream}; /// Re-export of [`tinywasm_types`]. pub mod types { + pub use crate::{AnyRef, ArrayRef, EqRef, ExnRef, ExternRef, FuncRef, I31Ref, RefValue, StructRef, WasmValue}; pub use tinywasm_types::*; } diff --git a/crates/tinywasm/src/reference.rs b/crates/tinywasm/src/reference.rs deleted file mode 100644 index 271e71c..0000000 --- a/crates/tinywasm/src/reference.rs +++ /dev/null @@ -1,513 +0,0 @@ -use core::hint::cold_path; - -use alloc::ffi::CString; -use alloc::format; -use alloc::string::{String, ToString}; -use alloc::vec::Vec; - -use crate::interpreter::ValueRef; -use crate::store::TableInstance; -use crate::{Error, MemoryInstance, Result, Store, Trap}; -use tinywasm_types::{ - Addr, FuncType, GlobalType, MemAddr, MemoryType, TableAddr, TableType, TagAddr, WasmType, WasmValue, -}; - -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub(crate) struct StoreItem { - pub(crate) store_id: u32, - pub(crate) addr: Addr, -} - -impl StoreItem { - #[inline] - /// Creates a handle for an address owned by a store. - pub(crate) const fn new(store_id: u32, addr: Addr) -> Self { - Self { store_id, addr } - } - - #[inline] - pub(crate) fn validate_store(&self, store: &Store) -> Result<(), Trap> { - if self.store_id != store.id() { - return Err(Trap::InvalidStore); - } - Ok(()) - } -} - -/// A memory instance in a store. -/// -/// ## Example -/// ```rust -/// # fn main() -> tinywasm::Result<()> { -/// use tinywasm::types::MemoryType; -/// use tinywasm::{Memory, Store}; -/// -/// let mut store = Store::default(); -/// let memory = Memory::new(&mut store, MemoryType::default().with_page_count_initial(1))?; -/// -/// memory.copy_from_slice(&mut store, 0, b"hi")?; -/// assert_eq!(memory.read_vec(&store, 0, 2)?, b"hi"); -/// assert_eq!(memory.page_count(&store)?, 1); -/// memory.grow(&mut store, 1)?; -/// assert_eq!(memory.page_count(&store)?, 2); -/// # Ok(()) -/// # } -/// ``` -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub struct Memory(pub(crate) StoreItem); - -/// A table instance in a store. -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub struct Table(pub(crate) StoreItem); - -/// A global instance in a store. -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub struct Global(pub(crate) StoreItem); - -/// A tag instance in a store. -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub struct Tag(pub(crate) StoreItem); - -/// A cursor over a [`Memory`] instance. -/// -/// Available with the `std` feature enabled. -#[cfg(feature = "std")] -pub struct MemoryCursor<'a> { - memory: &'a mut MemoryInstance, - position: u64, -} - -#[cfg(feature = "std")] -impl MemoryCursor<'_> { - fn offset(&self) -> crate::std::io::Result { - usize::try_from(self.position).map_err(|_| { - crate::std::io::Error::new(crate::std::io::ErrorKind::InvalidInput, "cursor position exceeds usize") - }) - } - - fn advance(&mut self, amount: usize) -> crate::std::io::Result<()> { - self.position = self.position.checked_add(amount as u64).ok_or_else(|| { - crate::std::io::Error::new(crate::std::io::ErrorKind::InvalidInput, "cursor position overflow") - })?; - Ok(()) - } - - /// Returns the current cursor position. - pub const fn position(&self) -> u64 { - self.position - } - - /// Sets the current cursor position. - pub fn set_position(&mut self, position: u64) { - self.position = position; - } -} - -#[cfg(feature = "std")] -impl crate::std::io::Read for MemoryCursor<'_> { - fn read(&mut self, buf: &mut [u8]) -> crate::std::io::Result { - let offset = self.offset()?; - let read = self.memory.inner.read(offset, buf); - self.advance(read)?; - Ok(read) - } -} - -#[cfg(feature = "std")] -impl crate::std::io::Write for MemoryCursor<'_> { - fn write(&mut self, buf: &[u8]) -> crate::std::io::Result { - let offset = self.offset()?; - let written = self.memory.inner.write(offset, buf); - self.advance(written)?; - Ok(written) - } - - fn flush(&mut self) -> crate::std::io::Result<()> { - Ok(()) - } -} - -#[cfg(feature = "std")] -impl crate::std::io::Seek for MemoryCursor<'_> { - fn seek(&mut self, pos: crate::std::io::SeekFrom) -> crate::std::io::Result { - let len = self.memory.inner.len() as i128; - let current = i128::from(self.position); - - let next = match pos { - crate::std::io::SeekFrom::Start(offset) => i128::from(offset), - crate::std::io::SeekFrom::End(offset) => len + i128::from(offset), - crate::std::io::SeekFrom::Current(offset) => current + i128::from(offset), - }; - - if next < 0 { - return Err(crate::std::io::Error::new( - crate::std::io::ErrorKind::InvalidInput, - "invalid seek before start", - )); - } - - let next = u64::try_from(next).map_err(|_| { - crate::std::io::Error::new(crate::std::io::ErrorKind::InvalidInput, "invalid seek position") - })?; - self.position = next; - Ok(next) - } -} - -impl Memory { - /// Create a new memory in the given store. - pub fn new(store: &mut Store, ty: MemoryType) -> Result { - let addr = store.state.memories.len() as MemAddr; - let limiter = store.engine.config().resource_limiter.clone(); - store.state.memories.push(MemoryInstance::new(ty, limiter.as_deref())?); - Ok(Self(StoreItem::new(store.id(), addr))) - } - - /// Creates a cursor positioned at the start of this memory. - /// - /// Available with the `std` feature enabled. - /// - /// ## Example - /// - /// ```rust - /// # fn main() -> Result<(), Box> { - /// use std::io::{Read, Seek, SeekFrom, Write}; - /// use tinywasm::types::MemoryType; - /// use tinywasm::{Memory, Store}; - /// - /// let mut store = Store::default(); - /// let memory = Memory::new(&mut store, MemoryType::default().with_page_count_initial(1))?; - /// let mut cursor = memory.cursor(&mut store)?; - /// - /// cursor.seek(SeekFrom::Start(2))?; - /// cursor.write_all(b"abc")?; - /// cursor.seek(SeekFrom::Start(0))?; - /// - /// let mut bytes = [0; 5]; - /// cursor.read_exact(&mut bytes)?; - /// assert_eq!(bytes, [0, 0, b'a', b'b', b'c']); - /// # Ok(()) - /// # } - /// ``` - #[cfg(feature = "std")] - pub fn cursor<'a>(&self, store: &'a mut Store) -> Result> { - self.cursor_at(store, 0) - } - - /// Creates a cursor positioned at `position` bytes from the start of this memory. - /// - /// Available with the `std` feature enabled. - #[cfg(feature = "std")] - pub fn cursor_at<'a>(&self, store: &'a mut Store, position: u64) -> Result> { - Ok(MemoryCursor { memory: self.instance_mut(store)?, position }) - } - - #[inline] - fn instance<'a>(&self, store: &'a Store) -> Result<&'a MemoryInstance> { - self.0.validate_store(store)?; - Ok(store.state.get_mem(self.0.addr)) - } - - #[inline] - fn instance_mut<'a>(&self, store: &'a mut Store) -> Result<&'a mut MemoryInstance> { - self.0.validate_store(store)?; - Ok(store.state.get_mem_mut(self.0.addr)) - } - - /// Returns the raw memory byte length. - pub fn len(&self, store: &Store) -> Result { - Ok(self.instance(store)?.inner.len()) - } - - /// Returns the memory type, including page size and limits. - pub fn ty(&self, store: &Store) -> Result { - Ok(self.instance(store)?.kind) - } - - /// Reads up to `dst.len()` bytes from memory and returns the number of bytes read. - /// - /// This returns fewer bytes than requested when the range extends past the end of memory. Use - /// [`Self::read_exact`] or [`Self::read_vec`] when you need a full range. - pub fn read(&self, store: &Store, offset: usize, dst: &mut [u8]) -> Result { - Ok(self.instance(store)?.inner.read(offset, dst)) - } - - /// Writes up to `src.len()` bytes into memory and returns the number of bytes written. - /// - /// This returns fewer bytes than requested when the range extends past the end of memory. Use - /// [`Self::copy_from_slice`] when you need the full slice written. - pub fn write(&self, store: &mut Store, offset: usize, src: &[u8]) -> Result { - Ok(self.instance_mut(store)?.inner.write(offset, src)) - } - - /// Reads exactly `dst.len()` bytes from memory. - pub fn read_exact(&self, store: &Store, offset: usize, dst: &mut [u8]) -> Result<()> { - self.instance(store)?.inner.read_exact(offset, dst).ok_or_else(|| { - Error::Trap(crate::Trap::MemoryOutOfBounds { - offset, - len: dst.len(), - max: self.instance(store).unwrap().inner.len(), - }) - }) - } - - /// Reads `len` bytes from memory into a newly allocated buffer. - pub fn read_vec(&self, store: &Store, offset: usize, len: usize) -> Result> { - self.instance(store)?.inner.read_vec(offset, len).ok_or_else(|| { - Error::Trap(crate::Trap::MemoryOutOfBounds { offset, len, max: self.instance(store).unwrap().inner.len() }) - }) - } - - /// Grows the memory by the given number of pages. - /// - /// Returns the previous size, or `None` if growth fails or is rejected by the resource limiter. - /// A limiter-provided trap is returned as an error. - pub fn grow(&self, store: &mut Store, delta_pages: i64) -> Result> { - let limiter = store.engine.config().resource_limiter.clone(); - let mem = self.instance_mut(store)?; - mem.grow(delta_pages, limiter.as_deref()).map_err(Into::into) - } - - /// Get the current size of the memory in pages. - pub fn page_count(&self, store: &Store) -> Result { - Ok(self.instance(store)?.page_count) - } - - /// Copy a slice of memory to another place in memory. - pub fn copy_within(&self, store: &mut Store, src: usize, dst: usize, len: usize) -> Result<()> { - self.instance_mut(store)?.copy_within(dst, src, len)?; - Ok(()) - } - - /// Fill a slice of memory with a value. - pub fn fill(&self, store: &mut Store, offset: usize, len: usize, val: u8) -> Result<()> { - self.instance_mut(store)?.inner.fill(offset, len, val).ok_or_else(|| { - Error::Trap(crate::Trap::MemoryOutOfBounds { offset, len, max: self.instance(store).unwrap().inner.len() }) - }) - } - - /// Copies a full slice into memory. - pub fn copy_from_slice(&self, store: &mut Store, offset: usize, data: &[u8]) -> Result<()> { - self.instance_mut(store)?.inner.write_all(offset, data).ok_or_else(|| { - Error::Trap(crate::Trap::MemoryOutOfBounds { - offset, - len: data.len(), - max: self.instance(store).unwrap().inner.len(), - }) - }) - } - - /// Copies a nul-terminated C string into memory. - pub fn write_cstring(&self, store: &mut Store, offset: usize, string: &CString) -> Result<()> { - self.copy_from_slice(store, offset, string.as_bytes_with_nul()) - } - - /// Copies a UTF-8 string into memory and appends a trailing nul byte. - pub fn write_cstring_bytes(&self, store: &mut Store, offset: usize, string: &str) -> Result<()> { - let mut bytes = Vec::with_capacity(string.len() + 1); - bytes.extend_from_slice(string.as_bytes()); - bytes.push(0); - self.copy_from_slice(store, offset, &bytes) - } - - /// Reads a C-style string from memory. - pub fn read_cstring(&self, store: &Store, offset: usize, len: usize) -> Result { - CString::from_vec_with_nul(self.read_vec(store, offset, len)?) - .map_err(|e| crate::Error::Other(format!("Invalid C-style string: {e}"))) - } - - /// Reads a C-style string from memory, stopping at the first null byte. - pub fn read_cstring_until_null(&self, store: &Store, offset: usize, max_len: usize) -> Result { - let bytes = self.read_vec(store, offset, max_len)?; - let Some(null) = bytes.iter().position(|byte| *byte == 0) else { - return Err(crate::Error::Other("Invalid C-style string: missing null terminator".to_string())); - }; - - CString::from_vec_with_nul(bytes[..=null].to_vec()) - .map_err(|e| crate::Error::Other(format!("Invalid C-style string: {e}"))) - } - - /// Reads a UTF-8 string from memory. - pub fn read_string(&self, store: &Store, offset: usize, len: usize) -> Result { - String::from_utf8(self.read_vec(store, offset, len)?) - .map_err(|e| crate::Error::Other(format!("Invalid UTF-8 string: {e}"))) - } - - /// Reads a JavaScript-style utf-16 string from memory. - pub fn read_js_string(&self, store: &Store, offset: usize, len: usize) -> Result { - let bytes = self.read_vec(store, offset, len)?; - let mut string = String::new(); - for i in 0..(len / 2) { - let c = u16::from_le_bytes([bytes[i * 2], bytes[i * 2 + 1]]); - string.push( - char::from_u32(u32::from(c)).ok_or_else(|| crate::Error::Other("Invalid UTF-16 string".to_string()))?, - ); - } - Ok(string) - } -} - -fn table_value_to_element( - state: &crate::store::State, - element_type: tinywasm_types::RefType, - value: WasmValue, -) -> Result { - let WasmValue::Ref(value) = value else { - return Err(Trap::Other("invalid table value type")); - }; - if !state.value_matches_type(WasmValue::Ref(value), WasmType::Ref(element_type)) { - return Err(Trap::Other("invalid table value type")); - } - Ok(value.into()) -} - -impl Table { - /// Create a new table in the given store. - pub fn new(store: &mut Store, ty: TableType, init: WasmValue) -> Result { - if ty.element_type.is_concrete() { - return Err(Error::other("host tables cannot use module-relative concrete reference types")); - } - let init = table_value_to_element(&store.state, ty.element_type, init).map_err(Error::from)?; - let limiter = store.engine.config().resource_limiter.clone(); - let addr = store.state.tables.len() as TableAddr; - store.state.tables.push(TableInstance::new(ty, init, limiter.as_deref())?); - Ok(Self(StoreItem::new(store.id(), addr))) - } - - #[inline] - fn instance<'a>(&self, store: &'a Store) -> Result<&'a TableInstance> { - self.0.validate_store(store)?; - Ok(store.state.get_table(self.0.addr)) - } - - /// Get the type of the table. - pub fn ty(&self, store: &Store) -> Result { - Ok(self.instance(store)?.kind) - } - - /// Get the current number of elements in the table. - pub fn size(&self, store: &Store) -> Result { - Ok(self.instance(store)?.size()) - } - - /// Get a table element as a wasm reference value. - pub fn get(&self, store: &Store, index: TableAddr) -> Result { - let table = self.instance(store)?; - let value = store.state.to_ref_value(*table.get(index as usize)?, table.kind.element_type); - store.state.pin_host_ref(value); - Ok(WasmValue::Ref(value)) - } - - /// Load a range of table elements and iterate over wasm reference values. - pub fn load<'a>( - &self, - store: &'a Store, - offset: usize, - len: usize, - ) -> Result + 'a> { - let table = self.instance(store)?; - let element_type = table.kind.element_type; - let elements = table.load(offset, len)?; - let may_contain_gc = store.state.type_may_contain_gc(&WasmType::Ref(element_type)); - Ok(elements.iter().copied().map(move |value| { - if may_contain_gc { - store.state.gc.pin(value); - } - WasmValue::Ref(store.state.to_ref_value(value, element_type)) - })) - } - - /// Set a table element. - pub fn set(&self, store: &mut Store, index: TableAddr, value: WasmValue) -> Result<(), Trap> { - self.0.validate_store(store)?; - let element_type = store.state.get_table(self.0.addr).kind.element_type; - let value = table_value_to_element(&store.state, element_type, value)?; - store.state.get_table_mut(self.0.addr).set(index as usize, value) - } - - /// Copy elements within the same table. - pub fn copy_within(&self, store: &mut Store, src: usize, dst: usize, len: usize) -> Result<(), Trap> { - self.0.validate_store(store)?; - store.state.get_table_mut(self.0.addr).copy_within(dst, src, len) - } - - /// Grows the table and returns the previous size. - /// - /// Returns `None` if growth fails or is rejected by the resource limiter. A limiter-provided - /// trap is returned as an error. - pub fn grow(&self, store: &mut Store, delta: i32, init: WasmValue) -> Result> { - self.0.validate_store(store)?; - let table = store.state.get_table(self.0.addr); - let old_size = table.size(); - let init = table_value_to_element(&store.state, table.kind.element_type, init)?; - let Ok(delta) = usize::try_from(delta) else { - return Ok(None); - }; - let limiter = store.engine.config().resource_limiter.clone(); - match store.state.get_table_mut(self.0.addr).grow(delta, init, limiter.as_deref())? { - true => Ok(Some(old_size)), - false => Ok(None), - } - } -} - -impl Global { - /// Create a new global in the given store. - pub fn new(store: &mut Store, ty: GlobalType, value: WasmValue) -> Result { - if matches!(ty.ty, WasmType::Ref(ty) if ty.is_concrete()) { - return Err(Error::other("host globals cannot use module-relative concrete reference types")); - } - if !store.state.value_matches_type(value, ty.ty) { - cold_path(); - return Err(Error::Other("invalid global value type".to_string())); - } - let addr = store.state.globals.push(ty, value.into()); - Ok(Self(StoreItem::new(store.id(), addr))) - } - - /// Get the type of the global. - pub fn ty(&self, store: &Store) -> Result { - self.0.validate_store(store)?; - Ok(store.state.globals.ty(self.0.addr)) - } - - /// Get the current value of the global. - pub fn get(&self, store: &Store) -> Result { - self.0.validate_store(store)?; - let value = store.state.get_global_wasmvalue(self.0.addr); - if let WasmValue::Ref(value) = value { - store.state.pin_host_ref(value); - } - Ok(value) - } - - /// Set the current value of the global. - pub fn set(&self, store: &mut Store, value: WasmValue) -> Result<()> { - self.0.validate_store(store)?; - store.state.set_global_wasmvalue(self.0.addr, value) - } -} - -impl Tag { - /// Create a new exception tag in the given store. - pub fn new(store: &mut Store, ty: FuncType) -> Result { - if !ty.results().is_empty() { - return Err(Error::other("tag types must not have results")); - } - let type_addr = store.register_host_type(&ty); - let addr = store.state.tags.len() as TagAddr; - store.state.tags.push(crate::store::TagInstance { type_addr }); - Ok(Self(StoreItem::new(store.id(), addr))) - } - - /// Get the payload type of the tag. - pub fn ty<'a>(&self, store: &'a Store) -> Result<&'a FuncType> { - self.0.validate_store(store)?; - Ok(store.state.get_canonical_func_type(store.state.get_tag(self.0.addr).type_addr)) - } -} diff --git a/crates/tinywasm/src/reference/managed.rs b/crates/tinywasm/src/reference/managed.rs new file mode 100644 index 0000000..1e5f38a --- /dev/null +++ b/crates/tinywasm/src/reference/managed.rs @@ -0,0 +1,236 @@ +use alloc::sync::Arc; +use core::sync::atomic::{AtomicU32, Ordering}; + +use crate::interpreter::ValueRef; +use crate::{Result, Store, Trap}; + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub(crate) struct StoreId(u32); + +impl StoreId { + pub(crate) fn fresh() -> Self { + static NEXT: AtomicU32 = AtomicU32::new(0); + next_store_id(&NEXT) + } + + pub(crate) const fn get(self) -> u32 { + self.0 + } +} + +fn next_store_id(counter: &AtomicU32) -> StoreId { + let id = counter + .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1)) + .expect("Store identity space exhausted"); + StoreId(id) +} + +#[cfg(feature = "debug")] +impl core::fmt::Debug for StoreId { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("StoreId(..)") + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub(crate) enum ReferentKind { + I31, + HostExtern, + Struct, + Array, + Exception, +} + +#[derive(Clone)] +pub(crate) struct RootedItem { + pub(crate) store: StoreId, + pub(crate) value: ValueRef, + pub(crate) kind: ReferentKind, + pub(crate) _token: Option>, +} + +impl PartialEq for RootedItem { + fn eq(&self, other: &Self) -> bool { + self.kind == other.kind + && self.value == other.value + && (self.kind == ReferentKind::I31 || self.store == other.store) + } +} + +impl Eq for RootedItem {} + +#[cfg(feature = "debug")] +impl core::fmt::Debug for RootedItem { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Reference").field("kind", &self.kind).finish_non_exhaustive() + } +} + +pub(crate) trait StoredRef: Clone + Sized { + fn from_rooted_item(item: RootedItem) -> Self; + fn rooted_item(&self) -> &RootedItem; +} + +macro_rules! reference_types { + ($($(#[$meta:meta])* $name:ident),* $(,)?) => {$($( + #[$meta] + )* + #[derive(Clone, PartialEq, Eq)] + #[cfg_attr(feature = "debug", derive(Debug))] + pub struct $name(RootedItem); + + impl StoredRef for $name { + fn from_rooted_item(item: RootedItem) -> Self { Self(item) } + fn rooted_item(&self) -> &RootedItem { &self.0 } + } + )*}; +} + +reference_types! { + /// An owned WebAssembly `anyref`. + AnyRef, + /// An owned WebAssembly `eqref`. + EqRef, + /// An owned WebAssembly `i31ref`. + I31Ref, + /// An owned WebAssembly `structref`. + StructRef, + /// An owned WebAssembly `arrayref`. + ArrayRef, + /// An owned WebAssembly `externref`. + ExternRef, + /// An owned WebAssembly `exnref`. + ExnRef, +} + +impl AnyRef { + /// Returns this reference as an `eqref` when its referent is comparable. + pub fn as_eq(&self) -> Option { + matches!(self.0.kind, ReferentKind::I31 | ReferentKind::Struct | ReferentKind::Array) + .then(|| EqRef(self.0.clone())) + } + + /// Returns this reference as an `i31ref` when it contains an i31. + pub fn as_i31(&self) -> Option { + (self.0.kind == ReferentKind::I31).then(|| I31Ref(self.0.clone())) + } + + /// Returns this reference as a `structref` when it refers to a struct. + pub fn as_struct(&self) -> Option { + (self.0.kind == ReferentKind::Struct).then(|| StructRef(self.0.clone())) + } + + /// Returns this reference as an `arrayref` when it refers to an array. + pub fn as_array(&self) -> Option { + (self.0.kind == ReferentKind::Array).then(|| ArrayRef(self.0.clone())) + } + + /// Returns this reference with the `externref` view. + pub fn to_extern(&self) -> ExternRef { + ExternRef(self.0.clone()) + } +} + +macro_rules! impl_to_any { + ($($ty:ty),* $(,)?) => {$( + impl $ty { + /// Returns this reference with the `anyref` view. + pub fn to_any(&self) -> AnyRef { AnyRef(self.0.clone()) } + } + )*}; +} + +impl_to_any!(EqRef, I31Ref, StructRef, ArrayRef, ExternRef); + +/// A Store-aware WebAssembly function reference. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct FuncRef { + store: StoreId, + addr: u32, +} + +impl FuncRef { + pub(crate) const fn new(store: StoreId, addr: u32) -> Self { + Self { store, addr } + } + + pub(crate) fn addr(self, store: StoreId) -> Option { + (self.store == store).then_some(self.addr) + } +} + +#[cfg(feature = "debug")] +impl core::fmt::Debug for FuncRef { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.write_str("FuncRef(..)") + } +} + +/// A host-facing WebAssembly reference value. +#[derive(Clone, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub enum RefValue { + /// A null reference. + Null, + /// A function reference. + Func(FuncRef), + /// An external reference. + Extern(ExternRef), + /// A reference in the `any` hierarchy. + Any(AnyRef), + /// An exception reference. + Exn(ExnRef), +} + +impl ExternRef { + /// Creates an external reference containing a host-defined key. + /// + /// Keys must be in `0..=(1 << 30) - 2`. + pub fn try_new(store: &mut Store, key: u32) -> Result { + let value = ValueRef::try_from_host_any(key).ok_or(Trap::InvalidReference)?; + store.root_reference(value, ReferentKind::HostExtern) + } + + /// Returns the host-defined key stored in this external reference. + /// + /// Returns an error for a reference produced by `extern.convert_any` from a + /// guest GC object or when `store` does not own the reference. + pub fn key(&self, store: &Store) -> Result { + let value = store.resolve_ref(self)?; + let addr = value.addr().filter(|_| value.is_host_any()).ok_or(Trap::InvalidReference)?; + Ok(addr & !(1 << 30)) + } +} + +impl I31Ref { + /// Creates a signed WebAssembly i31 reference. + /// + /// Values must be in `-2^30..=2^30 - 1`. + pub fn try_new(store: &mut Store, value: i32) -> Result { + if !(-(1 << 30)..(1 << 30)).contains(&value) { + return Err(Trap::InvalidReference.into()); + } + store.root_reference(ValueRef::from_i31(value), ReferentKind::I31) + } +} + +#[cfg(test)] +mod tests { + extern crate std; + use super::*; + + #[test] + fn exhausted_store_identity_counter_never_wraps() { + let counter = AtomicU32::new(u32::MAX - 1); + assert_eq!(next_store_id(&counter).get(), u32::MAX - 1); + assert!(std::panic::catch_unwind(|| next_store_id(&counter)).is_err()); + assert!(std::panic::catch_unwind(|| next_store_id(&counter)).is_err()); + } + + #[test] + fn host_reference_key_fits_internal_encoding() { + assert!(ValueRef::try_from_host_any((1 << 30) - 2).is_some()); + assert!(ValueRef::try_from_host_any((1 << 30) - 1).is_none()); + } +} diff --git a/crates/tinywasm/src/reference/mod.rs b/crates/tinywasm/src/reference/mod.rs new file mode 100644 index 0000000..7bc61e5 --- /dev/null +++ b/crates/tinywasm/src/reference/mod.rs @@ -0,0 +1,13 @@ +mod managed; +mod store; +mod value; + +pub use managed::{AnyRef, ArrayRef, EqRef, ExnRef, ExternRef, FuncRef, I31Ref, RefValue, StructRef}; +pub(crate) use managed::{ReferentKind, RootedItem, StoreId, StoredRef}; +#[cfg(feature = "std")] +pub use store::MemoryCursor; +pub(crate) use store::StoreItem; +pub use store::{ + GcFieldType, GcHeapType, GcRefType, GcStorageType, GcType, GcTypeKind, GcValueType, Global, Memory, Table, Tag, +}; +pub use value::WasmValue; diff --git a/crates/tinywasm/src/reference/store.rs b/crates/tinywasm/src/reference/store.rs new file mode 100644 index 0000000..d0eba6b --- /dev/null +++ b/crates/tinywasm/src/reference/store.rs @@ -0,0 +1,915 @@ +use core::hint::cold_path; + +use alloc::ffi::CString; +use alloc::format; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; + +use super::managed::{ReferentKind, StoreId, StoredRef}; +use crate::interpreter::ValueRef; +use crate::store::TableInstance; +use crate::{ArrayRef, Error, ExnRef, I31Ref, MemoryInstance, Result, Store, StructRef, Trap, WasmValue}; +use tinywasm_types::{ + AbstractHeapType, Addr, CompositeType, FieldType, FuncType, GlobalType, MemAddr, MemoryType, StorageType, + TableAddr, TableType, TagAddr, TypeAddr, WasmType, +}; + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub(crate) struct StoreItem { + pub(crate) store_id: StoreId, + pub(crate) addr: Addr, +} + +impl StoreItem { + #[inline] + /// Creates a handle for an address owned by a store. + pub(crate) const fn new(store_id: StoreId, addr: Addr) -> Self { + Self { store_id, addr } + } + + #[inline] + pub(crate) fn validate_store(&self, store: &Store) -> Result<(), Trap> { + if self.store_id != store.store_id() { + return Err(Trap::InvalidStore); + } + Ok(()) + } +} + +/// A memory instance in a store. +/// +/// See +/// +/// ## Example +/// ```rust +/// # fn main() -> tinywasm::Result<()> { +/// use tinywasm::types::MemoryType; +/// use tinywasm::{Memory, Store}; +/// +/// let mut store = Store::default(); +/// let memory = Memory::try_new(&mut store, MemoryType::default().with_page_count_initial(1))?; +/// +/// memory.copy_from_slice(&mut store, 0, b"hi")?; +/// assert_eq!(memory.read_vec(&store, 0, 2)?, b"hi"); +/// assert_eq!(memory.page_count(&store)?, 1); +/// memory.grow(&mut store, 1)?; +/// assert_eq!(memory.page_count(&store)?, 2); +/// # Ok(()) +/// # } +/// ``` +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct Memory(pub(crate) StoreItem); + +/// A table instance in a store. +/// +/// See +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct Table(pub(crate) StoreItem); + +/// A global instance in a store. +/// +/// See +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct Global(pub(crate) StoreItem); + +/// A tag instance in a store. +/// +/// See +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct Tag(pub(crate) StoreItem); + +/// An opaque canonical function, struct, or array type owned by a Store. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct GcType(StoreItem); + +/// The composite kind of a [`GcType`]. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub enum GcTypeKind { + /// A function type. + Function, + /// A struct type. + Struct, + /// An array type. + Array, +} + +/// Metadata for a struct field or array element. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct GcFieldType { + storage: GcStorageType, + mutable: bool, +} + +impl GcFieldType { + /// Returns the field's storage type. + pub const fn storage(self) -> GcStorageType { + self.storage + } + + /// Returns whether the field can be changed. + pub const fn is_mutable(self) -> bool { + self.mutable + } +} + +/// Host-visible storage metadata for a GC field or array element. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub enum GcStorageType { + /// A packed 8-bit integer. + I8, + /// A packed 16-bit integer. + I16, + /// An unpacked WebAssembly value. + Value(GcValueType), +} + +/// Host-visible value metadata that does not expose concrete reference encodings. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub enum GcValueType { + /// A 32-bit integer. + I32, + /// A 64-bit integer. + I64, + /// A 32-bit float. + F32, + /// A 64-bit float. + F64, + /// A 128-bit vector. + V128, + /// A reference type. + Ref(GcRefType), +} + +/// Host-visible reference metadata with opaque concrete types. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub struct GcRefType { + nullable: bool, + heap_type: GcHeapType, +} + +impl GcRefType { + /// Returns whether the reference type accepts null. + pub const fn is_nullable(self) -> bool { + self.nullable + } + + /// Returns the abstract or opaque concrete heap type. + pub const fn heap_type(self) -> GcHeapType { + self.heap_type + } +} + +/// Host-visible heap type metadata. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub enum GcHeapType { + /// An abstract WebAssembly heap type. + Abstract(AbstractHeapType), + /// An opaque canonical type owned by the Store. + Concrete(GcType), +} + +impl GcType { + fn subtype(self, store: &Store) -> Result<&tinywasm_types::SubType> { + self.0.validate_store(store)?; + store.state.canonical_types.get(self.0.addr as usize).ok_or_else(|| Trap::InvalidReference.into()) + } + + /// Returns this type's composite kind. + pub fn kind(self, store: &Store) -> Result { + Ok(match &self.subtype(store)?.composite { + CompositeType::Func(_) => GcTypeKind::Function, + CompositeType::Struct(_) => GcTypeKind::Struct, + CompositeType::Array(_) => GcTypeKind::Array, + }) + } + + /// Returns whether this type is a nominal subtype of `other`. + pub fn is_subtype_of(self, store: &Store, other: Self) -> Result { + self.subtype(store)?; + other.subtype(store)?; + Ok(store.state.type_addr_is_subtype(self.0.addr, other.0.addr)) + } + + /// Returns the number of struct fields. + pub fn field_count(self, store: &Store) -> Result { + self.subtype(store)? + .as_struct() + .map(|ty| ty.fields.len()) + .ok_or_else(|| Error::other("GC type is not a struct")) + } + + /// Returns metadata for one struct field. + pub fn field(self, store: &Store, index: usize) -> Result { + let field = self + .subtype(store)? + .as_struct() + .ok_or_else(|| Error::other("GC type is not a struct"))? + .fields + .get(index) + .copied() + .ok_or_else(|| Error::other("struct field out of bounds"))?; + Ok(gc_field_type(store, field)) + } + + /// Returns metadata for an array element. + pub fn array_element(self, store: &Store) -> Result { + let field = self.subtype(store)?.as_array().ok_or_else(|| Error::other("GC type is not an array"))?.field; + Ok(gc_field_type(store, field)) + } +} + +fn gc_field_type(store: &Store, field: FieldType) -> GcFieldType { + let storage = match field.storage { + StorageType::I8 => GcStorageType::I8, + StorageType::I16 => GcStorageType::I16, + StorageType::Value(ty) => GcStorageType::Value(match ty { + WasmType::I32 => GcValueType::I32, + WasmType::I64 => GcValueType::I64, + WasmType::F32 => GcValueType::F32, + WasmType::F64 => GcValueType::F64, + WasmType::V128 => GcValueType::V128, + WasmType::Ref(ty) => GcValueType::Ref(GcRefType { + nullable: ty.is_nullable(), + heap_type: match ty.type_index() { + Some(addr) => GcHeapType::Concrete(GcType(StoreItem::new(store.store_id(), addr))), + None => GcHeapType::Abstract(ty.abstract_heap_type().expect("abstract reference type")), + }, + }), + }), + }; + GcFieldType { storage, mutable: field.mutable } +} + +fn rooted_object(store: &Store, root: &T, kind: ReferentKind) -> Result<(ValueRef, TypeAddr)> { + let value = store.resolve_ref(root)?; + if root.rooted_item().kind != kind { + return Err(Trap::InvalidReference.into()); + } + let object = store.state.gc.get(value).ok_or(Trap::InvalidReference)?; + let crate::store::GcObjectKind::Composite(type_addr) = object.kind else { + return Err(Trap::InvalidReference.into()); + }; + Ok((value, type_addr)) +} + +/// A cursor over a [`Memory`] instance. +/// +/// Available with the `std` feature enabled. +#[cfg(feature = "std")] +pub struct MemoryCursor<'a> { + memory: &'a mut MemoryInstance, + position: u64, +} + +#[cfg(feature = "std")] +impl MemoryCursor<'_> { + fn offset(&self) -> crate::std::io::Result { + usize::try_from(self.position).map_err(|_| { + crate::std::io::Error::new(crate::std::io::ErrorKind::InvalidInput, "cursor position exceeds usize") + }) + } + + fn advance(&mut self, amount: usize) -> crate::std::io::Result<()> { + self.position = self.position.checked_add(amount as u64).ok_or_else(|| { + crate::std::io::Error::new(crate::std::io::ErrorKind::InvalidInput, "cursor position overflow") + })?; + Ok(()) + } + + /// Returns the current cursor position. + pub const fn position(&self) -> u64 { + self.position + } + + /// Sets the current cursor position. + pub fn set_position(&mut self, position: u64) { + self.position = position; + } +} + +#[cfg(feature = "std")] +impl crate::std::io::Read for MemoryCursor<'_> { + fn read(&mut self, buf: &mut [u8]) -> crate::std::io::Result { + let offset = self.offset()?; + let read = self.memory.inner.read(offset, buf); + self.advance(read)?; + Ok(read) + } +} + +#[cfg(feature = "std")] +impl crate::std::io::Write for MemoryCursor<'_> { + fn write(&mut self, buf: &[u8]) -> crate::std::io::Result { + let offset = self.offset()?; + let written = self.memory.inner.write(offset, buf); + self.advance(written)?; + Ok(written) + } + + fn flush(&mut self) -> crate::std::io::Result<()> { + Ok(()) + } +} + +#[cfg(feature = "std")] +impl crate::std::io::Seek for MemoryCursor<'_> { + fn seek(&mut self, pos: crate::std::io::SeekFrom) -> crate::std::io::Result { + let len = self.memory.inner.len() as i128; + let current = i128::from(self.position); + + let next = match pos { + crate::std::io::SeekFrom::Start(offset) => i128::from(offset), + crate::std::io::SeekFrom::End(offset) => len + i128::from(offset), + crate::std::io::SeekFrom::Current(offset) => current + i128::from(offset), + }; + + if next < 0 { + return Err(crate::std::io::Error::new( + crate::std::io::ErrorKind::InvalidInput, + "invalid seek before start", + )); + } + + let next = u64::try_from(next).map_err(|_| { + crate::std::io::Error::new(crate::std::io::ErrorKind::InvalidInput, "invalid seek position") + })?; + self.position = next; + Ok(next) + } +} + +impl Memory { + /// Create a new memory in the given store. + pub fn try_new(store: &mut Store, ty: MemoryType) -> Result { + let addr = store.state.memories.len() as MemAddr; + let limiter = store.engine.config().resource_limiter.clone(); + store.state.memories.push(MemoryInstance::new(ty, limiter.as_deref())?); + Ok(Self(StoreItem::new(store.store_id(), addr))) + } + + /// Creates a cursor positioned at the start of this memory. + /// + /// Available with the `std` feature enabled. + /// + /// ## Example + /// + /// ```rust + /// # fn main() -> Result<(), Box> { + /// use std::io::{Read, Seek, SeekFrom, Write}; + /// use tinywasm::types::MemoryType; + /// use tinywasm::{Memory, Store}; + /// + /// let mut store = Store::default(); + /// let memory = Memory::try_new(&mut store, MemoryType::default().with_page_count_initial(1))?; + /// let mut cursor = memory.cursor(&mut store)?; + /// + /// cursor.seek(SeekFrom::Start(2))?; + /// cursor.write_all(b"abc")?; + /// cursor.seek(SeekFrom::Start(0))?; + /// + /// let mut bytes = [0; 5]; + /// cursor.read_exact(&mut bytes)?; + /// assert_eq!(bytes, [0, 0, b'a', b'b', b'c']); + /// # Ok(()) + /// # } + /// ``` + #[cfg(feature = "std")] + pub fn cursor<'a>(&self, store: &'a mut Store) -> Result> { + self.cursor_at(store, 0) + } + + /// Creates a cursor positioned at `position` bytes from the start of this memory. + /// + /// Available with the `std` feature enabled. + #[cfg(feature = "std")] + pub fn cursor_at<'a>(&self, store: &'a mut Store, position: u64) -> Result> { + Ok(MemoryCursor { memory: self.instance_mut(store)?, position }) + } + + #[inline] + fn instance<'a>(&self, store: &'a Store) -> Result<&'a MemoryInstance> { + self.0.validate_store(store)?; + Ok(store.state.get_mem(self.0.addr)) + } + + #[inline] + fn instance_mut<'a>(&self, store: &'a mut Store) -> Result<&'a mut MemoryInstance> { + self.0.validate_store(store)?; + Ok(store.state.get_mem_mut(self.0.addr)) + } + + /// Returns the raw memory byte length. + pub fn len(&self, store: &Store) -> Result { + Ok(self.instance(store)?.inner.len()) + } + + /// Returns the memory type, including page size and limits. + pub fn ty(&self, store: &Store) -> Result { + Ok(self.instance(store)?.kind) + } + + /// Reads up to `dst.len()` bytes from memory and returns the number of bytes read. + /// + /// This returns fewer bytes than requested when the range extends past the end of memory. Use + /// [`Self::read_exact`] or [`Self::read_vec`] when you need a full range. + pub fn read(&self, store: &Store, offset: usize, dst: &mut [u8]) -> Result { + Ok(self.instance(store)?.inner.read(offset, dst)) + } + + /// Writes up to `src.len()` bytes into memory and returns the number of bytes written. + /// + /// This returns fewer bytes than requested when the range extends past the end of memory. Use + /// [`Self::copy_from_slice`] when you need the full slice written. + pub fn write(&self, store: &mut Store, offset: usize, src: &[u8]) -> Result { + Ok(self.instance_mut(store)?.inner.write(offset, src)) + } + + /// Reads exactly `dst.len()` bytes from memory. + pub fn read_exact(&self, store: &Store, offset: usize, dst: &mut [u8]) -> Result<()> { + self.instance(store)?.inner.read_exact(offset, dst).ok_or_else(|| { + Error::Trap(crate::Trap::MemoryOutOfBounds { + offset, + len: dst.len(), + max: self.instance(store).unwrap().inner.len(), + }) + }) + } + + /// Reads `len` bytes from memory into a newly allocated buffer. + pub fn read_vec(&self, store: &Store, offset: usize, len: usize) -> Result> { + self.instance(store)?.inner.read_vec(offset, len).ok_or_else(|| { + Error::Trap(crate::Trap::MemoryOutOfBounds { offset, len, max: self.instance(store).unwrap().inner.len() }) + }) + } + + /// Grows the memory by the given number of pages. + /// + /// Returns the previous size, or `None` if growth fails or is rejected by the resource limiter. + /// A limiter-provided trap is returned as an error. + pub fn grow(&self, store: &mut Store, delta_pages: i64) -> Result> { + let limiter = store.engine.config().resource_limiter.clone(); + let mem = self.instance_mut(store)?; + mem.grow(delta_pages, limiter.as_deref()).map_err(Into::into) + } + + /// Get the current size of the memory in pages. + pub fn page_count(&self, store: &Store) -> Result { + Ok(self.instance(store)?.page_count) + } + + /// Copy a slice of memory to another place in memory. + pub fn copy_within(&self, store: &mut Store, src: usize, dst: usize, len: usize) -> Result<()> { + self.instance_mut(store)?.copy_within(dst, src, len)?; + Ok(()) + } + + /// Fill a slice of memory with a value. + pub fn fill(&self, store: &mut Store, offset: usize, len: usize, val: u8) -> Result<()> { + self.instance_mut(store)?.inner.fill(offset, len, val).ok_or_else(|| { + Error::Trap(crate::Trap::MemoryOutOfBounds { offset, len, max: self.instance(store).unwrap().inner.len() }) + }) + } + + /// Copies a full slice into memory. + pub fn copy_from_slice(&self, store: &mut Store, offset: usize, data: &[u8]) -> Result<()> { + self.instance_mut(store)?.inner.write_all(offset, data).ok_or_else(|| { + Error::Trap(crate::Trap::MemoryOutOfBounds { + offset, + len: data.len(), + max: self.instance(store).unwrap().inner.len(), + }) + }) + } + + /// Copies a nul-terminated C string into memory. + pub fn write_cstring(&self, store: &mut Store, offset: usize, string: &CString) -> Result<()> { + self.copy_from_slice(store, offset, string.as_bytes_with_nul()) + } + + /// Copies a UTF-8 string into memory and appends a trailing nul byte. + pub fn write_cstring_bytes(&self, store: &mut Store, offset: usize, string: &str) -> Result<()> { + let mut bytes = Vec::with_capacity(string.len() + 1); + bytes.extend_from_slice(string.as_bytes()); + bytes.push(0); + self.copy_from_slice(store, offset, &bytes) + } + + /// Reads a C-style string from memory. + pub fn read_cstring(&self, store: &Store, offset: usize, len: usize) -> Result { + CString::from_vec_with_nul(self.read_vec(store, offset, len)?) + .map_err(|e| crate::Error::Other(format!("Invalid C-style string: {e}"))) + } + + /// Reads a C-style string from memory, stopping at the first null byte. + pub fn read_cstring_until_null(&self, store: &Store, offset: usize, max_len: usize) -> Result { + let bytes = self.read_vec(store, offset, max_len)?; + let Some(null) = bytes.iter().position(|byte| *byte == 0) else { + return Err(crate::Error::Other("Invalid C-style string: missing null terminator".to_string())); + }; + + CString::from_vec_with_nul(bytes[..=null].to_vec()) + .map_err(|e| crate::Error::Other(format!("Invalid C-style string: {e}"))) + } + + /// Reads a UTF-8 string from memory. + pub fn read_string(&self, store: &Store, offset: usize, len: usize) -> Result { + String::from_utf8(self.read_vec(store, offset, len)?) + .map_err(|e| crate::Error::Other(format!("Invalid UTF-8 string: {e}"))) + } + + /// Reads a JavaScript-style utf-16 string from memory. + pub fn read_js_string(&self, store: &Store, offset: usize, len: usize) -> Result { + let bytes = self.read_vec(store, offset, len)?; + let mut string = String::new(); + for i in 0..(len / 2) { + let c = u16::from_le_bytes([bytes[i * 2], bytes[i * 2 + 1]]); + string.push( + char::from_u32(u32::from(c)).ok_or_else(|| crate::Error::Other("Invalid UTF-16 string".to_string()))?, + ); + } + Ok(string) + } +} + +fn table_value_to_element( + store: &Store, + element_type: tinywasm_types::RefType, + value: WasmValue, +) -> Result { + let WasmValue::Ref(reference) = &value else { + return Err(Trap::Other("invalid table value type")); + }; + if !store.value_matches_type(&value, WasmType::Ref(element_type)) { + return Err(Trap::Other("invalid table value type")); + } + store.encode_ref(reference).map_err(|error| match error { + Error::Trap(trap) => trap, + _ => Trap::Other("invalid table value type"), + }) +} + +impl I31Ref { + /// Returns the signed i31 value. + pub fn value(&self, store: &Store) -> Result { + if self.rooted_item().kind != ReferentKind::I31 { + return Err(Trap::InvalidReference.into()); + } + store.resolve_ref(self)?.i31_s().ok_or_else(|| Trap::InvalidReference.into()) + } +} + +impl StructRef { + /// Returns this struct's canonical type. + pub fn ty(&self, store: &Store) -> Result { + let (_, type_addr) = rooted_object(store, self, ReferentKind::Struct)?; + Ok(GcType(StoreItem::new(store.store_id(), type_addr))) + } + + /// Reads one field. + /// + /// Packed integer fields are returned as zero-extended `i32` values. Mutable + /// Store access is required to register owned reference results. + pub fn field(&self, store: &mut Store, index: usize) -> Result { + let (reference, type_addr) = rooted_object(store, self, ReferentKind::Struct)?; + let storage = store + .state + .get_type(type_addr) + .as_struct() + .unwrap() + .fields + .get(index) + .ok_or_else(|| Error::other("struct field out of bounds"))? + .storage; + let value = *store.state.gc.get(reference).unwrap().values.get(index).unwrap(); + value.into_wasm(store, storage.unpacked()) + } + + /// Reads all fields in declaration order. + /// + /// Mutable Store access is required because reference results are registered with the Store. + pub fn fields(&self, store: &mut Store) -> Result> { + let (reference, type_addr) = rooted_object(store, self, ReferentKind::Struct)?; + let field_count = store.state.get_type(type_addr).as_struct().unwrap().fields.len(); + let mut values = Vec::new(); + values.try_reserve_exact(field_count).map_err(|_| Trap::OutOfMemory)?; + for index in 0..field_count { + let storage = store.state.get_type(type_addr).as_struct().unwrap().fields[index].storage; + let value = store.state.gc.get(reference).unwrap().values[index]; + values.push(value.into_wasm(store, storage.unpacked())?); + } + Ok(values) + } + + /// Writes one mutable field after validating its canonical value type. + /// + /// Writes to packed integer fields truncate the input to the field width. + pub fn set_field(&self, store: &mut Store, index: usize, value: WasmValue) -> Result<()> { + let (reference, type_addr) = rooted_object(store, self, ReferentKind::Struct)?; + let field = *store + .state + .get_type(type_addr) + .as_struct() + .unwrap() + .fields + .get(index) + .ok_or_else(|| Error::other("struct field out of bounds"))?; + set_gc_value(store, reference, index, field, value, "struct field") + } +} + +impl ArrayRef { + /// Returns this array's canonical type. + pub fn ty(&self, store: &Store) -> Result { + let (_, type_addr) = rooted_object(store, self, ReferentKind::Array)?; + Ok(GcType(StoreItem::new(store.store_id(), type_addr))) + } + + /// Returns the number of array elements. + pub fn len(&self, store: &Store) -> Result { + let (reference, _) = rooted_object(store, self, ReferentKind::Array)?; + Ok(store.state.gc.get(reference).unwrap().values.len()) + } + + /// Returns whether the array contains no elements. + pub fn is_empty(&self, store: &Store) -> Result { + Ok(self.len(store)? == 0) + } + + /// Reads one array element. + /// + /// Packed integer elements are returned as zero-extended `i32` values. Mutable + /// Store access is required to register owned reference results. + pub fn get(&self, store: &mut Store, index: usize) -> Result { + let (reference, type_addr) = rooted_object(store, self, ReferentKind::Array)?; + let storage = store.state.get_type(type_addr).as_array().unwrap().field.storage; + let value = *store.state.gc.get(reference).unwrap().values.get(index).ok_or(Trap::ArrayOutOfBounds)?; + value.into_wasm(store, storage.unpacked()) + } + + /// Writes one mutable array element after validating its canonical value type. + /// + /// Writes to packed integer elements truncate the input to the element width. + pub fn set(&self, store: &mut Store, index: usize, value: WasmValue) -> Result<()> { + let (reference, type_addr) = rooted_object(store, self, ReferentKind::Array)?; + let field = store.state.get_type(type_addr).as_array().unwrap().field; + if index >= store.state.gc.get(reference).unwrap().values.len() { + return Err(Trap::ArrayOutOfBounds.into()); + } + set_gc_value(store, reference, index, field, value, "array element") + } +} + +fn set_gc_value( + store: &mut Store, + reference: ValueRef, + index: usize, + field: FieldType, + value: WasmValue, + field_name: &'static str, +) -> Result<()> { + if !field.mutable { + return Err(Error::other(format!("{field_name} is immutable"))); + } + let expected = field.storage.unpacked(); + if !store.value_matches_type(&value, expected) { + return Err(Error::other(format!("invalid {field_name} value type"))); + } + let value = match (field.storage, value.to_runtime(store)?) { + (StorageType::I8, crate::interpreter::RuntimeValue::Value32(value)) => { + crate::interpreter::RuntimeValue::Value32(value as u8 as u32) + } + (StorageType::I16, crate::interpreter::RuntimeValue::Value32(value)) => { + crate::interpreter::RuntimeValue::Value32(value as u16 as u32) + } + (_, value) => value, + }; + let handle = store.state.gc.handle(reference).ok_or(Trap::InvalidReference)?; + store.state.gc.set(handle, index, value).ok_or_else(|| Trap::InvalidReference.into()) +} + +impl ExnRef { + /// Returns the exception's tag. + pub fn tag(&self, store: &Store) -> Result { + let (_, tag_addr) = exception_object(store, self)?; + Ok(Tag(StoreItem::new(store.store_id(), tag_addr))) + } + + /// Reads one exception payload field. + /// + /// Mutable Store access is required because reference results are registered with the Store. + pub fn field(&self, store: &mut Store, index: usize) -> Result { + let (reference, tag_addr) = exception_object(store, self)?; + let type_addr = store.state.get_tag(tag_addr).type_addr; + let ty = *store + .state + .get_canonical_func_type(type_addr) + .params() + .get(index) + .ok_or_else(|| Error::other("exception payload field out of bounds"))?; + let value = *store + .state + .gc + .get(reference) + .unwrap() + .values + .get(index) + .ok_or_else(|| Error::other("exception payload field out of bounds"))?; + value.into_wasm(store, ty) + } + + /// Reads all exception payload fields. + /// + /// Mutable Store access is required because reference results are registered with the Store. + pub fn fields(&self, store: &mut Store) -> Result> { + let (reference, tag_addr) = exception_object(store, self)?; + let type_addr = store.state.get_tag(tag_addr).type_addr; + let field_count = store.state.gc.get(reference).unwrap().values.len(); + let mut fields = Vec::new(); + fields.try_reserve_exact(field_count).map_err(|_| Trap::OutOfMemory)?; + for index in 0..field_count { + let ty = store.state.get_canonical_func_type(type_addr).params()[index]; + let value = store.state.gc.get(reference).unwrap().values[index]; + fields.push(value.into_wasm(store, ty)?); + } + Ok(fields) + } +} + +fn exception_object(store: &Store, root: &ExnRef) -> Result<(ValueRef, TagAddr)> { + let reference = store.resolve_ref(root)?; + if root.rooted_item().kind != ReferentKind::Exception { + return Err(Trap::InvalidReference.into()); + } + let object = store.state.gc.get(reference).ok_or(Trap::InvalidReference)?; + let crate::store::GcObjectKind::Exception(tag_addr) = object.kind else { + return Err(Trap::InvalidReference.into()); + }; + Ok((reference, tag_addr)) +} + +impl Table { + /// Create a new table in the given store. + pub fn try_new(store: &mut Store, ty: TableType, init: WasmValue) -> Result { + if ty.element_type.is_concrete() { + return Err(Error::other("host tables cannot use module-relative concrete reference types")); + } + let init = table_value_to_element(store, ty.element_type, init).map_err(Error::from)?; + let limiter = store.engine.config().resource_limiter.clone(); + let addr = store.state.tables.len() as TableAddr; + store.state.tables.push(TableInstance::new(ty, init, limiter.as_deref())?); + Ok(Self(StoreItem::new(store.store_id(), addr))) + } + + #[inline] + fn instance<'a>(&self, store: &'a Store) -> Result<&'a TableInstance> { + self.0.validate_store(store)?; + Ok(store.state.get_table(self.0.addr)) + } + + /// Get the type of the table. + pub fn ty(&self, store: &Store) -> Result { + Ok(self.instance(store)?.kind) + } + + /// Get the current number of elements in the table. + pub fn size(&self, store: &Store) -> Result { + Ok(self.instance(store)?.size()) + } + + /// Get a table element as a wasm reference value. + /// + /// Mutable Store access is required because managed results are registered with the Store. + pub fn get(&self, store: &mut Store, index: TableAddr) -> Result { + self.0.validate_store(store)?; + let table = store.state.get_table(self.0.addr); + let value = *table.get(index as usize)?; + let element_type = table.kind.element_type; + Ok(WasmValue::Ref(store.decode_ref(value, element_type)?)) + } + + /// Load a range of table elements and iterate over wasm reference values. + /// + /// Mutable Store access is required because managed results are registered with the Store. + pub fn load(&self, store: &mut Store, offset: usize, len: usize) -> Result> { + self.0.validate_store(store)?; + let table = store.state.get_table(self.0.addr); + let element_type = table.kind.element_type; + let elements = table.load(offset, len)?.to_vec(); + let mut values = Vec::new(); + values.try_reserve_exact(elements.len()).map_err(|_| Trap::OutOfMemory)?; + for value in elements { + values.push(WasmValue::Ref(store.decode_ref(value, element_type)?)); + } + Ok(values.into_iter()) + } + + /// Set a table element. + pub fn set(&self, store: &mut Store, index: TableAddr, value: WasmValue) -> Result<(), Trap> { + self.0.validate_store(store)?; + let element_type = store.state.get_table(self.0.addr).kind.element_type; + let value = table_value_to_element(store, element_type, value)?; + store.state.get_table_mut(self.0.addr).set(index as usize, value) + } + + /// Copy elements within the same table. + pub fn copy_within(&self, store: &mut Store, src: usize, dst: usize, len: usize) -> Result<(), Trap> { + self.0.validate_store(store)?; + store.state.get_table_mut(self.0.addr).copy_within(dst, src, len) + } + + /// Grows the table and returns the previous size. + /// + /// Returns `None` if growth fails or is rejected by the resource limiter. A limiter-provided + /// trap is returned as an error. + pub fn grow(&self, store: &mut Store, delta: i32, init: WasmValue) -> Result> { + self.0.validate_store(store)?; + let table = store.state.get_table(self.0.addr); + let old_size = table.size(); + let init = table_value_to_element(store, table.kind.element_type, init)?; + let Ok(delta) = usize::try_from(delta) else { + return Ok(None); + }; + let limiter = store.engine.config().resource_limiter.clone(); + match store.state.get_table_mut(self.0.addr).grow(delta, init, limiter.as_deref())? { + true => Ok(Some(old_size)), + false => Ok(None), + } + } +} + +impl Global { + /// Create a new global in the given store. + pub fn try_new(store: &mut Store, ty: GlobalType, value: WasmValue) -> Result { + if matches!(ty.ty, WasmType::Ref(ty) if ty.is_concrete()) { + return Err(Error::other("host globals cannot use module-relative concrete reference types")); + } + if !store.value_matches_type(&value, ty.ty) { + cold_path(); + return Err(Error::Other("invalid global value type".to_string())); + } + let value = value.to_runtime(store)?; + let addr = store.state.globals.push(ty, value); + Ok(Self(StoreItem::new(store.store_id(), addr))) + } + + /// Get the type of the global. + pub fn ty(&self, store: &Store) -> Result { + self.0.validate_store(store)?; + Ok(store.state.globals.ty(self.0.addr)) + } + + /// Get the current value of the global. + /// + /// Mutable Store access is required because an owned reference result is registered with the Store. + pub fn get(&self, store: &mut Store) -> Result { + self.0.validate_store(store)?; + let ty = store.state.globals.ty(self.0.addr).ty; + let value = store.state.global_value(self.0.addr); + value.into_wasm(store, ty) + } + + /// Set the current value of the global. + pub fn set(&self, store: &mut Store, value: WasmValue) -> Result<()> { + self.0.validate_store(store)?; + let ty = store.state.globals.ty(self.0.addr).ty; + if !store.value_matches_type(&value, ty) { + return Err(Error::other("invalid global value type")); + } + let value = value.to_runtime(store)?; + store.state.set_global_value(self.0.addr, value) + } +} + +impl Tag { + /// Create a new exception tag in the given store. + pub fn try_new(store: &mut Store, ty: FuncType) -> Result { + if !ty.results().is_empty() { + return Err(Error::other("tag types must not have results")); + } + if ty.params().iter().any(|ty| matches!(ty, WasmType::Ref(ty) if ty.is_concrete())) { + return Err(Error::other("host tags cannot use concrete reference types")); + } + let type_addr = store.register_host_type(&ty); + let addr = store.state.tags.len() as TagAddr; + store.state.tags.push(crate::store::TagInstance { type_addr }); + Ok(Self(StoreItem::new(store.store_id(), addr))) + } + + /// Get the payload type of the tag. + pub fn ty<'a>(&self, store: &'a Store) -> Result<&'a FuncType> { + self.0.validate_store(store)?; + Ok(store.state.get_canonical_func_type(store.state.get_tag(self.0.addr).type_addr)) + } +} diff --git a/crates/tinywasm/src/reference/value.rs b/crates/tinywasm/src/reference/value.rs new file mode 100644 index 0000000..7ef3dea --- /dev/null +++ b/crates/tinywasm/src/reference/value.rs @@ -0,0 +1,232 @@ +use core::fmt::Debug; + +use tinywasm_types::{AbstractHeapType, RefType, WasmType}; + +use crate::interpreter::{RuntimeValue, Value128}; +use crate::{AnyRef, ArrayRef, EqRef, ExnRef, ExternRef, FuncRef, I31Ref, RefValue, Result, Store, StructRef}; + +/// A host-facing WebAssembly value. +/// +/// See +#[derive(Clone, PartialEq)] +pub enum WasmValue { + /// A 32-bit integer. + I32(i32), + /// A 64-bit integer. + I64(i64), + /// A 32-bit float. + F32(f32), + /// A 64-bit float. + F64(f64), + /// A 128-bit vector. + V128([u8; 16]), + /// A reference. + Ref(RefValue), +} + +impl WasmValue { + pub(crate) fn to_runtime(&self, store: &Store) -> Result { + Ok(match self { + Self::I32(value) => RuntimeValue::Value32(*value as u32), + Self::I64(value) => RuntimeValue::Value64(*value as u64), + Self::F32(value) => RuntimeValue::Value32(value.to_bits()), + Self::F64(value) => RuntimeValue::Value64(value.to_bits()), + Self::V128(value) => RuntimeValue::Value128(Value128(*value)), + Self::Ref(value) => RuntimeValue::ValueRef(store.encode_ref(value)?), + }) + } + + /// Returns this value's broad WebAssembly type, or `None` for null. + pub fn ty(&self) -> Option { + match self { + Self::I32(_) => Some(WasmType::I32), + Self::I64(_) => Some(WasmType::I64), + Self::F32(_) => Some(WasmType::F32), + Self::F64(_) => Some(WasmType::F64), + Self::V128(_) => Some(WasmType::V128), + Self::Ref(RefValue::Null) => None, + Self::Ref(RefValue::Func(_)) => Some(WasmType::Ref(RefType::FUNCREF)), + Self::Ref(RefValue::Extern(_)) => Some(WasmType::Ref(RefType::EXTERNREF)), + Self::Ref(RefValue::Exn(_)) => Some(WasmType::Ref(RefType::EXNREF)), + Self::Ref(RefValue::Any(_)) => Some(WasmType::Ref(RefType::new_abstract(true, AbstractHeapType::Any))), + } + } + + /// Returns whether this value matches a broad or abstract type. + /// + /// A non-null value does not match a concrete reference type because + /// concrete types require Store-specific subtype information. + pub fn matches_type(&self, ty: WasmType) -> bool { + match (self, ty) { + (Self::I32(_), WasmType::I32) + | (Self::I64(_), WasmType::I64) + | (Self::F32(_), WasmType::F32) + | (Self::F64(_), WasmType::F64) + | (Self::V128(_), WasmType::V128) => true, + (Self::Ref(RefValue::Null), WasmType::Ref(ty)) => ty.is_nullable(), + (Self::Ref(RefValue::Func(_)), WasmType::Ref(ty)) => { + ty.abstract_heap_type() == Some(AbstractHeapType::Func) + } + (Self::Ref(RefValue::Extern(_)), WasmType::Ref(ty)) => { + ty.abstract_heap_type() == Some(AbstractHeapType::Extern) + } + (Self::Ref(RefValue::Exn(_)), WasmType::Ref(ty)) => ty.abstract_heap_type() == Some(AbstractHeapType::Exn), + (Self::Ref(RefValue::Any(value)), WasmType::Ref(ty)) => match ty.abstract_heap_type() { + Some(AbstractHeapType::Any) => true, + Some(AbstractHeapType::Eq) => value.as_eq().is_some(), + Some(AbstractHeapType::I31) => value.as_i31().is_some(), + Some(AbstractHeapType::Struct) => value.as_struct().is_some(), + Some(AbstractHeapType::Array) => value.as_array().is_some(), + _ => false, + }, + _ => false, + } + } + + /// Returns the default value for `ty`, or `None` for a non-null reference type. + pub fn default_for(ty: WasmType) -> Option { + match ty { + WasmType::I32 => Some(Self::I32(0)), + WasmType::I64 => Some(Self::I64(0)), + WasmType::F32 => Some(Self::F32(0.0)), + WasmType::F64 => Some(Self::F64(0.0)), + WasmType::V128 => Some(Self::V128([0; 16])), + WasmType::Ref(ty) if ty.is_nullable() => Some(Self::Ref(RefValue::Null)), + WasmType::Ref(_) => None, + } + } + + /// Compares values while treating NaN values with different payloads as equal. + pub fn eq_loose(&self, other: &Self) -> bool { + match (self, other) { + (Self::F32(a), Self::F32(b)) => a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits(), + (Self::F64(a), Self::F64(b)) => a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits(), + (Self::V128(a), Self::V128(b)) => a == b || vector_nan_eq(*a, *b), + _ => self == other, + } + } +} + +fn vector_nan_eq(a: [u8; 16], b: [u8; 16]) -> bool { + let f32_equal = a.as_chunks::<4>().0.iter().zip(b.as_chunks::<4>().0).all(|(a, b)| { + let a = f32::from_le_bytes(*a); + let b = f32::from_le_bytes(*b); + a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits() + }); + if f32_equal && a.as_chunks::<4>().0.iter().any(|v| f32::from_le_bytes(*v).is_nan()) { + return true; + } + a.as_chunks::<8>().0.iter().zip(b.as_chunks::<8>().0).all(|(a, b)| { + let a = f64::from_le_bytes(*a); + let b = f64::from_le_bytes(*b); + a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits() + }) && a.as_chunks::<8>().0.iter().any(|v| f64::from_le_bytes(*v).is_nan()) +} + +impl Debug for WasmValue { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::I32(value) => write!(f, "i32({value})"), + Self::I64(value) => write!(f, "i64({value})"), + Self::F32(value) => write!(f, "f32({value})"), + Self::F64(value) => write!(f, "f64({value})"), + Self::V128(value) => write!(f, "v128({value:?})"), + #[cfg(feature = "debug")] + Self::Ref(value) => write!(f, "ref({value:?})"), + #[cfg(not(feature = "debug"))] + Self::Ref(_) => f.write_str("ref(..)"), + } + } +} + +macro_rules! value_conversions { + ($($ty:ty => $variant:ident, $method:ident);* $(;)?) => {$( + impl WasmValue { + #[doc = concat!("Returns the contained `", stringify!($ty), "` value.")] + pub fn $method(&self) -> Option<$ty> { + if let Self::$variant(value) = self { Some(value.clone()) } else { None } + } + } + impl From<$ty> for WasmValue { fn from(value: $ty) -> Self { Self::$variant(value) } } + impl TryFrom for $ty { + type Error = (); + fn try_from(value: WasmValue) -> Result { + if let WasmValue::$variant(value) = value { Ok(value) } else { Err(()) } + } + } + )*}; +} + +value_conversions! { + i32 => I32, as_i32; + i64 => I64, as_i64; + f32 => F32, as_f32; + f64 => F64, as_f64; + [u8; 16] => V128, as_v128; +} + +impl WasmValue { + /// Returns the contained reference value. + pub const fn as_ref(&self) -> Option<&RefValue> { + if let Self::Ref(value) = self { Some(value) } else { None } + } +} + +impl From for WasmValue { + fn from(value: RefValue) -> Self { + Self::Ref(value) + } +} + +impl TryFrom for RefValue { + type Error = (); + + fn try_from(value: WasmValue) -> Result { + if let WasmValue::Ref(value) = value { Ok(value) } else { Err(()) } + } +} + +macro_rules! ref_conversions { + ($($ty:ty => $variant:ident),* $(,)?) => {$( + impl From<$ty> for WasmValue { fn from(value: $ty) -> Self { Self::Ref(RefValue::$variant(value)) } } + impl TryFrom for $ty { + type Error = (); + fn try_from(value: WasmValue) -> Result { + if let WasmValue::Ref(RefValue::$variant(value)) = value { Ok(value) } else { Err(()) } + } + } + )*}; +} + +ref_conversions!(FuncRef => Func, ExternRef => Extern, AnyRef => Any, ExnRef => Exn); + +macro_rules! any_ref_conversions { + ($($ty:ty => $cast:ident),* $(,)?) => {$( + impl From<$ty> for WasmValue { fn from(value: $ty) -> Self { Self::Ref(RefValue::Any(value.to_any())) } } + impl TryFrom for $ty { + type Error = (); + fn try_from(value: WasmValue) -> Result { + let WasmValue::Ref(RefValue::Any(value)) = value else { return Err(()) }; + value.$cast().ok_or(()) + } + } + )*}; +} + +any_ref_conversions!(EqRef => as_eq, I31Ref => as_i31, StructRef => as_struct, ArrayRef => as_array); + +macro_rules! nullable_conversions { + ($($ty:ty),* $(,)?) => {$( + impl From> for WasmValue { + fn from(value: Option<$ty>) -> Self { value.map(Into::into).unwrap_or(Self::Ref(RefValue::Null)) } + } + impl TryFrom for Option<$ty> { + type Error = (); + fn try_from(value: WasmValue) -> Result { + if matches!(value, WasmValue::Ref(RefValue::Null)) { Ok(None) } else { <$ty>::try_from(value).map(Some) } + } + } + )*}; +} + +nullable_conversions!(FuncRef, AnyRef, EqRef, I31Ref, StructRef, ArrayRef, ExternRef, ExnRef); diff --git a/crates/tinywasm/src/store/const_expr.rs b/crates/tinywasm/src/store/const_expr.rs index 356304b..cd01648 100644 --- a/crates/tinywasm/src/store/const_expr.rs +++ b/crates/tinywasm/src/store/const_expr.rs @@ -2,42 +2,42 @@ use alloc::{format, vec::Vec}; use tinywasm_types::*; use super::{State, default_value}; -use crate::interpreter::{TinyWasmValue, Value128, ValueRef}; +use crate::interpreter::{RuntimeValue, Value128, ValueRef}; use crate::{Error, Result, Trap}; fn resolve(items: &[T], index: u32, kind: &str) -> Result { items.get(index as usize).copied().ok_or_else(|| Error::Other(format!("{kind} {index} not found"))) } -fn pop_value(stack: &mut Vec, storage: StorageType) -> Result { +fn pop_value(stack: &mut Vec, storage: StorageType) -> Result { let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; match (storage, value) { - (StorageType::I8, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u8 as u32)), - (StorageType::I16, TinyWasmValue::Value32(value)) => Ok(TinyWasmValue::Value32(value as u16 as u32)), - (StorageType::Value(WasmType::I32 | WasmType::F32), value @ TinyWasmValue::Value32(_)) - | (StorageType::Value(WasmType::I64 | WasmType::F64), value @ TinyWasmValue::Value64(_)) - | (StorageType::Value(WasmType::V128), value @ TinyWasmValue::Value128(_)) - | (StorageType::Value(WasmType::Ref(_)), value @ TinyWasmValue::ValueRef(_)) => Ok(value), + (StorageType::I8, RuntimeValue::Value32(value)) => Ok(RuntimeValue::Value32(value as u8 as u32)), + (StorageType::I16, RuntimeValue::Value32(value)) => Ok(RuntimeValue::Value32(value as u16 as u32)), + (StorageType::Value(WasmType::I32 | WasmType::F32), value @ RuntimeValue::Value32(_)) + | (StorageType::Value(WasmType::I64 | WasmType::F64), value @ RuntimeValue::Value64(_)) + | (StorageType::Value(WasmType::V128), value @ RuntimeValue::Value128(_)) + | (StorageType::Value(WasmType::Ref(_)), value @ RuntimeValue::ValueRef(_)) => Ok(value), _ => Err(Error::other("type mismatch in GC constant")), } } -fn value_ref(value: &TinyWasmValue) -> Option { +fn value_ref(value: &RuntimeValue) -> Option { match value { - TinyWasmValue::ValueRef(value) => Some(*value), + RuntimeValue::ValueRef(value) => Some(*value), _ => None, } } fn alloc_object( state: &mut State, - stack: &mut Vec, + stack: &mut Vec, type_addr: TypeAddr, - values: Vec, + values: Vec, ) -> Result<()> { - let roots = stack.iter().filter_map(value_ref).map(ValueRef::raw); + let roots = stack.iter().filter_map(value_ref); let reference = state.alloc_gc_object(type_addr, values, roots)?; - stack.push(TinyWasmValue::ValueRef(reference)); + stack.push(RuntimeValue::ValueRef(reference)); Ok(()) } @@ -48,33 +48,33 @@ pub(super) fn eval_const( global_addrs: &[GlobalAddr], func_addrs: &[FuncAddr], type_addrs: &[TypeAddr], -) -> Result { +) -> Result { use ConstInstruction::*; if let [instruction] = instructions { match instruction { - I32Const(value) => return Ok(TinyWasmValue::Value32(*value as u32)), - I64Const(value) => return Ok(TinyWasmValue::Value64(*value as u64)), - F32Const(value) => return Ok(TinyWasmValue::Value32(value.to_bits())), - F64Const(value) => return Ok(TinyWasmValue::Value64(value.to_bits())), - V128Const(value) => return Ok(TinyWasmValue::Value128(Value128(*value))), + I32Const(value) => return Ok(RuntimeValue::Value32(*value as u32)), + I64Const(value) => return Ok(RuntimeValue::Value64(*value as u64)), + F32Const(value) => return Ok(RuntimeValue::Value32(value.to_bits())), + F64Const(value) => return Ok(RuntimeValue::Value64(value.to_bits())), + V128Const(value) => return Ok(RuntimeValue::Value128(Value128(*value))), GlobalGet32(index) => { - return Ok(TinyWasmValue::Value32(state.globals.get_32(resolve(global_addrs, *index, "global")?))); + return Ok(RuntimeValue::Value32(state.globals.get_32(resolve(global_addrs, *index, "global")?))); } GlobalGet64(index) => { - return Ok(TinyWasmValue::Value64(state.globals.get_64(resolve(global_addrs, *index, "global")?))); + return Ok(RuntimeValue::Value64(state.globals.get_64(resolve(global_addrs, *index, "global")?))); } GlobalGet128(index) => { - return Ok(TinyWasmValue::Value128(state.globals.get_128(resolve(global_addrs, *index, "global")?))); + return Ok(RuntimeValue::Value128(state.globals.get_128(resolve(global_addrs, *index, "global")?))); } GlobalGetRef(index) => { let value = state.globals.get_32(resolve(global_addrs, *index, "global")?); - return Ok(TinyWasmValue::ValueRef(ValueRef::from_raw(value))); + return Ok(RuntimeValue::ValueRef(ValueRef::from_raw(value))); } - Ref(RefValue::Null) => return Ok(TinyWasmValue::ValueRef(ValueRef::NULL)), - Ref(RefValue::Func(func)) => { - let addr = resolve(func_addrs, func.addr(), "function")?; - return Ok(TinyWasmValue::ValueRef(ValueRef::from_category_addr(addr))); + RefNull(_) => return Ok(RuntimeValue::ValueRef(ValueRef::NULL)), + RefFunc(func) => { + let addr = resolve(func_addrs, func.index(), "function")?; + return Ok(RuntimeValue::ValueRef(ValueRef::from_category_addr(addr))); } _ => {} } @@ -83,62 +83,69 @@ pub(super) fn eval_const( let mut stack = Vec::new(); for instruction in instructions { match instruction { - I32Const(value) => stack.push(TinyWasmValue::Value32(*value as u32)), - I64Const(value) => stack.push(TinyWasmValue::Value64(*value as u64)), - F32Const(value) => stack.push(TinyWasmValue::Value32(value.to_bits())), - F64Const(value) => stack.push(TinyWasmValue::Value64(value.to_bits())), - V128Const(value) => stack.push(TinyWasmValue::Value128(Value128(*value))), + I32Const(value) => stack.push(RuntimeValue::Value32(*value as u32)), + I64Const(value) => stack.push(RuntimeValue::Value64(*value as u64)), + F32Const(value) => stack.push(RuntimeValue::Value32(value.to_bits())), + F64Const(value) => stack.push(RuntimeValue::Value64(value.to_bits())), + V128Const(value) => stack.push(RuntimeValue::Value128(Value128(*value))), GlobalGet32(index) => { - stack.push(TinyWasmValue::Value32(state.globals.get_32(resolve(global_addrs, *index, "global")?))); + stack.push(RuntimeValue::Value32(state.globals.get_32(resolve(global_addrs, *index, "global")?))); } GlobalGet64(index) => { - stack.push(TinyWasmValue::Value64(state.globals.get_64(resolve(global_addrs, *index, "global")?))); + stack.push(RuntimeValue::Value64(state.globals.get_64(resolve(global_addrs, *index, "global")?))); } GlobalGet128(index) => { - stack.push(TinyWasmValue::Value128(state.globals.get_128(resolve(global_addrs, *index, "global")?))); + stack.push(RuntimeValue::Value128(state.globals.get_128(resolve(global_addrs, *index, "global")?))); } GlobalGetRef(index) => { let value = state.globals.get_32(resolve(global_addrs, *index, "global")?); - stack.push(TinyWasmValue::ValueRef(ValueRef::from_raw(value))); + stack.push(RuntimeValue::ValueRef(ValueRef::from_raw(value))); } - Ref(RefValue::Null) => stack.push(TinyWasmValue::ValueRef(ValueRef::NULL)), - Ref(RefValue::Func(func)) => { - let addr = resolve(func_addrs, func.addr(), "function")?; - stack.push(TinyWasmValue::ValueRef(ValueRef::from_category_addr(addr))); - } - Ref(_) => { - return cold!(Err(Error::other("unsupported reference constant"))); + RefNull(_) => stack.push(RuntimeValue::ValueRef(ValueRef::NULL)), + RefFunc(func) => { + let addr = resolve(func_addrs, func.index(), "function")?; + stack.push(RuntimeValue::ValueRef(ValueRef::from_category_addr(addr))); } RefI31 => { let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; - let TinyWasmValue::Value32(value) = value else { + let RuntimeValue::Value32(value) = value else { return Err(Error::other("type mismatch in const ref.i31")); }; - stack.push(TinyWasmValue::ValueRef(ValueRef::from_i31(value as i32))); + stack.push(RuntimeValue::ValueRef(ValueRef::from_i31(value as i32))); } AnyConvertExtern | ExternConvertAny => { let value = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; - if !matches!(value, TinyWasmValue::ValueRef(_)) { + if !matches!(value, RuntimeValue::ValueRef(_)) { return Err(Error::other("type mismatch in const reference conversion")); } stack.push(value); } StructNew(type_index) | StructNewDefault(type_index) => { let type_addr = resolve(type_addrs, *type_index, "type")?; - let fields = state + let field_count = state .get_type(type_addr) .as_struct() .ok_or_else(|| Error::other("GC constant type is not a struct"))? .fields - .as_ref(); + .len(); let default = matches!(instruction, StructNewDefault(_)); + state.check_gc_allocation(type_addr, field_count)?; let mut values = Vec::new(); - cold_err!(values.try_reserve_exact(fields.len())).map_err(|_| Trap::OutOfMemory)?; + cold_err!(values.try_reserve_exact(field_count)).map_err(|_| Trap::OutOfMemory)?; if default { - values.extend(fields.iter().map(|field| default_value(field.storage))); + values.extend( + state + .get_type(type_addr) + .as_struct() + .unwrap() + .fields + .iter() + .map(|field| default_value(field.storage)), + ); } else { - for field in fields.iter().rev() { - values.push(pop_value(&mut stack, field.storage)?); + for index in (0..field_count).rev() { + let storage = state.get_type(type_addr).as_struct().unwrap().fields[index].storage; + values.push(pop_value(&mut stack, storage)?); } values.reverse(); } @@ -152,9 +159,10 @@ pub(super) fn eval_const( .ok_or_else(|| Error::other("GC constant type is not an array"))? .field .storage; - let Some(TinyWasmValue::Value32(len)) = stack.pop() else { + let Some(RuntimeValue::Value32(len)) = stack.pop() else { return Err(Error::other("type mismatch in const array length")); }; + state.check_gc_allocation(type_addr, len as usize)?; let value = if matches!(instruction, ArrayNewDefault(_)) { default_value(storage) } else { @@ -173,6 +181,7 @@ pub(super) fn eval_const( .ok_or_else(|| Error::other("GC constant type is not an array"))? .field .storage; + state.check_gc_allocation(type_addr, *len as usize)?; let mut values = Vec::new(); cold_err!(values.try_reserve_exact(*len as usize)).map_err(|_| Trap::OutOfMemory)?; for _ in 0..*len { @@ -184,7 +193,7 @@ pub(super) fn eval_const( I32Add | I32Sub | I32Mul => { let rhs = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; let lhs = stack.pop().ok_or_else(|| Error::other("const stack underflow"))?; - let (TinyWasmValue::Value32(lhs), TinyWasmValue::Value32(rhs)) = (lhs, rhs) else { + let (RuntimeValue::Value32(lhs), RuntimeValue::Value32(rhs)) = (lhs, rhs) else { return cold!(Err(Error::other("type mismatch in const i32 op"))); }; let out = match instruction { @@ -193,12 +202,12 @@ pub(super) fn eval_const( I32Mul => (lhs as i32).wrapping_mul(rhs as i32), _ => unreachable!(), }; - stack.push(TinyWasmValue::Value32(out as u32)); + stack.push(RuntimeValue::Value32(out as u32)); } I64Add | I64Sub | I64Mul => { let rhs = stack.pop(); let lhs = stack.pop(); - let (Some(TinyWasmValue::Value64(lhs)), Some(TinyWasmValue::Value64(rhs))) = (lhs, rhs) else { + let (Some(RuntimeValue::Value64(lhs)), Some(RuntimeValue::Value64(rhs))) = (lhs, rhs) else { return cold!(Err(Error::other("type mismatch in const i64 op"))); }; let out = match instruction { @@ -207,7 +216,7 @@ pub(super) fn eval_const( I64Mul => (lhs as i64).wrapping_mul(rhs as i64), _ => unreachable!(), }; - stack.push(TinyWasmValue::Value64(out as u64)); + stack.push(RuntimeValue::Value64(out as u64)); } } } diff --git a/crates/tinywasm/src/store/exception.rs b/crates/tinywasm/src/store/exception.rs deleted file mode 100644 index 0725cda..0000000 --- a/crates/tinywasm/src/store/exception.rs +++ /dev/null @@ -1,10 +0,0 @@ -use alloc::boxed::Box; -use tinywasm_types::TagAddr; - -use crate::interpreter::TinyWasmValue; - -#[cfg_attr(feature = "debug", derive(Debug))] -pub(crate) struct ExceptionInstance { - pub(crate) tag_addr: TagAddr, - pub(crate) payload: Box<[TinyWasmValue]>, -} diff --git a/crates/tinywasm/src/store/function.rs b/crates/tinywasm/src/store/function.rs index 3580e9d..3c716a7 100644 --- a/crates/tinywasm/src/store/function.rs +++ b/crates/tinywasm/src/store/function.rs @@ -10,17 +10,9 @@ use crate::func::HostFunction; #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) struct FunctionInstance { pub(crate) type_addr: TypeAddr, - pub(crate) gc: FunctionGcMetadata, pub(crate) kind: FunctionKind, } -#[derive(Clone, Copy)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub(crate) struct FunctionGcMetadata { - pub(crate) params: bool, - pub(crate) results: bool, -} - #[derive(Clone)] #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) enum FunctionKind { diff --git a/crates/tinywasm/src/store/gc/mod.rs b/crates/tinywasm/src/store/gc/mod.rs index 6379357..152d651 100644 --- a/crates/tinywasm/src/store/gc/mod.rs +++ b/crates/tinywasm/src/store/gc/mod.rs @@ -1,58 +1,57 @@ mod arena; mod object; +mod roots; use alloc::vec::Vec; +use core::ops::Range; use tinywasm_types::{StorageType, WasmType}; use crate::Trap; use crate::interpreter::stack::ValueStack; -use crate::interpreter::{InternalValue, TinyWasmValue, Value128, ValueRef}; +use crate::interpreter::{InternalValue, RuntimeValue, Value128, ValueRef}; pub(crate) use arena::{AllocError, Arena, Handle, Trace}; -pub(crate) use object::{GcHeap, GcObject}; +pub(crate) use object::{GcHeap, GcObjectKind}; +pub(crate) use roots::Roots; /// Returns the zero value for a GC field or array element. -pub(crate) fn default_value(storage: StorageType) -> TinyWasmValue { +pub(crate) fn default_value(storage: StorageType) -> RuntimeValue { match storage { StorageType::I8 | StorageType::I16 | StorageType::Value(WasmType::I32 | WasmType::F32) => { - TinyWasmValue::Value32(0) + RuntimeValue::Value32(0) } - StorageType::Value(WasmType::I64 | WasmType::F64) => TinyWasmValue::Value64(0), - StorageType::Value(WasmType::V128) => TinyWasmValue::Value128(Value128([0; 16])), - StorageType::Value(WasmType::Ref(_)) => TinyWasmValue::ValueRef(ValueRef::NULL), + StorageType::Value(WasmType::I64 | WasmType::F64) => RuntimeValue::Value64(0), + StorageType::Value(WasmType::V128) => RuntimeValue::Value128(Value128([0; 16])), + StorageType::Value(WasmType::Ref(_)) => RuntimeValue::ValueRef(ValueRef::NULL), } } /// Pops and packs a GC field or array element from the operand stack. -pub(crate) fn pop_value(stack: &mut ValueStack, storage: StorageType) -> TinyWasmValue { +pub(crate) fn pop_value(stack: &mut ValueStack, storage: StorageType) -> RuntimeValue { match storage { - StorageType::I8 => TinyWasmValue::Value32(i32::stack_pop(stack) as u8 as u32), - StorageType::I16 => TinyWasmValue::Value32(i32::stack_pop(stack) as u16 as u32), - StorageType::Value(WasmType::I32 | WasmType::F32) => TinyWasmValue::Value32(u32::stack_pop(stack)), - StorageType::Value(WasmType::I64 | WasmType::F64) => TinyWasmValue::Value64(u64::stack_pop(stack)), - StorageType::Value(WasmType::V128) => TinyWasmValue::Value128(Value128::stack_pop(stack)), - StorageType::Value(WasmType::Ref(_)) => TinyWasmValue::ValueRef(ValueRef::stack_pop(stack)), + StorageType::I8 => RuntimeValue::Value32(i32::stack_pop(stack) as u8 as u32), + StorageType::I16 => RuntimeValue::Value32(i32::stack_pop(stack) as u16 as u32), + StorageType::Value(WasmType::I32 | WasmType::F32) => RuntimeValue::Value32(u32::stack_pop(stack)), + StorageType::Value(WasmType::I64 | WasmType::F64) => RuntimeValue::Value64(u64::stack_pop(stack)), + StorageType::Value(WasmType::V128) => RuntimeValue::Value128(Value128::stack_pop(stack)), + StorageType::Value(WasmType::Ref(_)) => RuntimeValue::ValueRef(ValueRef::stack_pop(stack)), } } /// Extends a packed value and pushes it onto the operand stack. pub(crate) fn push_value( stack: &mut ValueStack, - value: TinyWasmValue, + value: RuntimeValue, storage: StorageType, signed: Option, ) -> Result<(), Trap> { let value = match (value, storage, signed) { - (TinyWasmValue::Value32(value), StorageType::I8, Some(true)) => { - TinyWasmValue::Value32(value as i8 as i32 as u32) - } - (TinyWasmValue::Value32(value), StorageType::I16, Some(true)) => { - TinyWasmValue::Value32(value as i16 as i32 as u32) - } - (TinyWasmValue::Value32(value), StorageType::I8, Some(false)) => TinyWasmValue::Value32(value & u8::MAX as u32), - (TinyWasmValue::Value32(value), StorageType::I16, Some(false)) => { - TinyWasmValue::Value32(value & u16::MAX as u32) + (RuntimeValue::Value32(value), StorageType::I8, Some(true)) => RuntimeValue::Value32(value as i8 as i32 as u32), + (RuntimeValue::Value32(value), StorageType::I16, Some(true)) => { + RuntimeValue::Value32(value as i16 as i32 as u32) } + (RuntimeValue::Value32(value), StorageType::I8, Some(false)) => RuntimeValue::Value32(value & u8::MAX as u32), + (RuntimeValue::Value32(value), StorageType::I16, Some(false)) => RuntimeValue::Value32(value & u16::MAX as u32), (value, _, None) => value, _ => unreachable!("validated packed field access"), }; @@ -60,12 +59,12 @@ pub(crate) fn push_value( } /// Decodes numeric array elements from a data segment. -pub(crate) fn decode_data( +pub(crate) fn data_range( storage: StorageType, data: &[u8], src: usize, len: usize, -) -> Result, Trap> { +) -> Result<(Range, usize), Trap> { let width = match storage { StorageType::I8 => 1, StorageType::I16 => 2, @@ -78,14 +77,25 @@ pub(crate) fn decode_data( else { return Err(Trap::MemoryOutOfBounds { offset: src, len: len.saturating_mul(width), max: data.len() }); }; + Ok((src..end, width)) +} + +/// Decodes numeric array elements from a data segment. +pub(crate) fn decode_data( + storage: StorageType, + data: &[u8], + src: usize, + len: usize, +) -> Result, Trap> { + let (range, width) = data_range(storage, data, src, len)?; let mut values = Vec::new(); cold_err!(values.try_reserve_exact(len)).map_err(|_| Trap::OutOfMemory)?; - values.extend(data[src..end].chunks_exact(width).map(|bytes| match width { - 1 => TinyWasmValue::Value32(u32::from(bytes[0])), - 2 => TinyWasmValue::Value32(u32::from(u16::from_le_bytes(bytes.try_into().unwrap()))), - 4 => TinyWasmValue::Value32(u32::from_le_bytes(bytes.try_into().unwrap())), - 8 => TinyWasmValue::Value64(u64::from_le_bytes(bytes.try_into().unwrap())), - 16 => TinyWasmValue::Value128(Value128(<[u8; 16]>::try_from(bytes).unwrap())), + values.extend(data[range].chunks_exact(width).map(|bytes| match width { + 1 => RuntimeValue::Value32(u32::from(bytes[0])), + 2 => RuntimeValue::Value32(u32::from(u16::from_le_bytes(bytes.try_into().unwrap()))), + 4 => RuntimeValue::Value32(u32::from_le_bytes(bytes.try_into().unwrap())), + 8 => RuntimeValue::Value64(u64::from_le_bytes(bytes.try_into().unwrap())), + 16 => RuntimeValue::Value128(Value128(<[u8; 16]>::try_from(bytes).unwrap())), _ => unreachable!(), })); Ok(values) diff --git a/crates/tinywasm/src/store/gc/object.rs b/crates/tinywasm/src/store/gc/object.rs index ca22338..cf27cd5 100644 --- a/crates/tinywasm/src/store/gc/object.rs +++ b/crates/tinywasm/src/store/gc/object.rs @@ -1,12 +1,11 @@ use alloc::{boxed::Box, sync::Arc, vec::Vec}; -use core::cell::RefCell; use core::mem::size_of; use core::sync::atomic::{AtomicU32, Ordering}; -use tinywasm_types::TypeAddr; +use tinywasm_types::{TagAddr, TypeAddr}; use crate::engine::Config; -use crate::interpreter::{TinyWasmValue, ValueRef}; +use crate::interpreter::{RuntimeValue, ValueRef}; use crate::{ResourceLimiter, Trap}; use super::{AllocError, Arena, Handle, Trace}; @@ -14,11 +13,17 @@ use super::{AllocError, Arena, Handle, Trace}; static NEXT_GC_REF: AtomicU32 = AtomicU32::new(0); pub(crate) struct GcObject { - pub(crate) type_addr: TypeAddr, - pub(crate) values: Box<[TinyWasmValue]>, + pub(crate) kind: GcObjectKind, + pub(crate) values: Box<[RuntimeValue]>, references: Option]>>, } +#[derive(Clone, Copy)] +pub(crate) enum GcObjectKind { + Composite(TypeAddr), + Exception(TagAddr), +} + impl Trace for GcObject { fn trace(&self, mark: &mut impl FnMut(Handle)) { if let Some(references) = &self.references { @@ -30,7 +35,6 @@ impl Trace for GcObject { pub(crate) struct GcHeap { objects: Arena, directory: Vec<(u32, Handle)>, - pinned: RefCell>, resource_limiter: Option>, } @@ -46,7 +50,6 @@ impl GcHeap { Self { objects: Arena::new(config.gc_collection_threshold), directory: Vec::new(), - pinned: RefCell::new(Vec::new()), resource_limiter: config.resource_limiter.clone(), } } @@ -65,19 +68,13 @@ impl GcHeap { } #[inline] - pub(crate) fn get_mut(&mut self, value: ValueRef) -> Option<&mut GcObject> { - self.objects.get_mut(self.handle(value)?) + pub(crate) fn get_handle(&self, handle: Handle) -> Option<&GcObject> { + self.objects.get(handle) } - /// Allocates an object and returns its compact runtime reference. - pub(crate) fn alloc( - &mut self, - type_addr: TypeAddr, - values: Vec, - trace_references: bool, - ) -> Result { - let element_size = size_of::() + if trace_references { size_of::>() } else { 0 }; - let out_of_line_bytes = values.len().checked_mul(element_size).ok_or(Trap::OutOfMemory)?; + pub(crate) fn check_allocation(&self, value_count: usize, trace_references: bool) -> Result<(), Trap> { + let element_size = size_of::() + if trace_references { size_of::>() } else { 0 }; + let out_of_line_bytes = value_count.checked_mul(element_size).ok_or(Trap::OutOfMemory)?; let allocation_size = Arena::::allocation_size(out_of_line_bytes).ok_or(Trap::OutOfMemory)?; let desired = self.objects.allocated_bytes.checked_add(allocation_size).ok_or(Trap::OutOfMemory)?; if let Some(limiter) = &self.resource_limiter @@ -85,7 +82,38 @@ impl GcHeap { { return Err(Trap::OutOfMemory); } + Ok(()) + } + + /// Allocates an object and returns its compact runtime reference. + pub(crate) fn alloc( + &mut self, + type_addr: TypeAddr, + values: Vec, + trace_references: bool, + ) -> Result { + self.alloc_kind(GcObjectKind::Composite(type_addr), values, trace_references, None) + } + + /// Allocates an exception and traces references in its payload. + pub(crate) fn alloc_exception( + &mut self, + tag_addr: TagAddr, + payload: Vec, + trace_fields: &[bool], + ) -> Result { + self.alloc_kind(GcObjectKind::Exception(tag_addr), payload, true, Some(trace_fields)) + } + fn alloc_kind( + &mut self, + kind: GcObjectKind, + values: Vec, + trace_references: bool, + trace_fields: Option<&[bool]>, + ) -> Result { + let element_size = size_of::() + if trace_references { size_of::>() } else { 0 }; + let out_of_line_bytes = values.len().checked_mul(element_size).ok_or(Trap::OutOfMemory)?; let key = NEXT_GC_REF.try_update(Ordering::Relaxed, Ordering::Relaxed, |key| (key < (1 << 30)).then_some(key + 1)); let Ok(key) = key else { @@ -94,27 +122,27 @@ impl GcHeap { let references = if trace_references { let mut references = Vec::new(); references.try_reserve_exact(values.len()).map_err(|_| Trap::OutOfMemory)?; - references.extend(values.iter().map(|value| match value { - TinyWasmValue::ValueRef(value) => self.handle(*value), + references.extend(values.iter().enumerate().map(|(index, value)| match value { + RuntimeValue::ValueRef(value) if trace_fields.is_none_or(|fields| fields[index]) => self.handle(*value), _ => None, })); Some(references.into_boxed_slice()) } else { None }; - let object = GcObject { type_addr, values: values.into_boxed_slice(), references }; + let object = GcObject { kind, values: values.into_boxed_slice(), references }; self.directory.try_reserve(1).map_err(|_| Trap::OutOfMemory)?; let handle = self.objects.alloc(object, out_of_line_bytes).map_err(|_| Trap::OutOfMemory)?; self.directory.push((key, handle)); Ok(ValueRef::from_category_addr(key)) } - pub(crate) fn set(&mut self, object: ValueRef, index: usize, value: TinyWasmValue) -> Option<()> { + pub(crate) fn set(&mut self, object: Handle, index: usize, value: RuntimeValue) -> Option<()> { let reference = match value { - TinyWasmValue::ValueRef(value) => self.handle(value), + RuntimeValue::ValueRef(value) => self.handle(value), _ => None, }; - let object = self.get_mut(object)?; + let object = self.objects.get_mut(object)?; *object.values.get_mut(index)? = value; if let Some(references) = &mut object.references { references[index] = reference; @@ -123,20 +151,17 @@ impl GcHeap { } /// Replaces a contiguous range and updates its traced references. - pub(crate) fn set_slice(&mut self, object: ValueRef, index: usize, values: &[TinyWasmValue]) -> Option<()> { - let object_handle = self.handle(object)?; + pub(crate) fn set_slice(&mut self, object: Handle, index: usize, values: &[RuntimeValue]) -> Option<()> { let end = index.checked_add(values.len())?; let directory = &self.directory; - let object = self.objects.get_mut(object_handle)?; + let object = self.objects.get_mut(object)?; object.values.get_mut(index..end)?.copy_from_slice(values); if let Some(references) = &mut object.references { for (reference, value) in references[index..end].iter_mut().zip(values) { *reference = match value { - TinyWasmValue::ValueRef(value) => { - let key = value.addr(); - key.and_then(|key| directory.binary_search_by_key(&key, |entry| entry.0).ok()) - .map(|index| directory[index].1) - } + RuntimeValue::ValueRef(value) => value.addr().and_then(|key| { + directory.binary_search_by_key(&key, |entry| entry.0).ok().map(|index| directory[index].1) + }), _ => None, }; } @@ -145,17 +170,12 @@ impl GcHeap { } /// Fills a contiguous range and updates its traced references. - pub(crate) fn fill( - &mut self, - object: ValueRef, - range: core::ops::Range, - value: TinyWasmValue, - ) -> Option<()> { + pub(crate) fn fill(&mut self, object: Handle, range: core::ops::Range, value: RuntimeValue) -> Option<()> { let reference = match value { - TinyWasmValue::ValueRef(value) => self.handle(value), + RuntimeValue::ValueRef(value) => self.handle(value), _ => None, }; - let object = self.get_mut(object)?; + let object = self.objects.get_mut(object)?; object.values.get_mut(range.clone())?.fill(value); if let Some(references) = &mut object.references { references[range].fill(reference); @@ -164,36 +184,24 @@ impl GcHeap { } pub(crate) fn should_collect(&self, value_count: usize, trace_references: bool) -> bool { - let element_size = size_of::() + if trace_references { size_of::>() } else { 0 }; + let element_size = size_of::() + if trace_references { size_of::>() } else { 0 }; self.objects.should_collect(value_count.saturating_mul(element_size)) } - /// Reclaims objects unreachable from runtime and permanent host roots. + /// Reclaims objects unreachable from runtime roots. pub(crate) fn collect(&mut self, roots: impl IntoIterator) -> Result<(), AllocError> { - let pinned = self.pinned.borrow(); let directory = &self.directory; let root_handles = roots.into_iter().filter_map(|value| { let key = value.addr()?; Some(directory.get(directory.binary_search_by_key(&key, |entry| entry.0).ok()?)?.1) }); - self.objects.collect(pinned.iter().copied().chain(root_handles))?; - drop(pinned); + self.objects.collect(root_handles)?; self.directory.retain(|(_, handle)| self.objects.get(*handle).is_some()); Ok(()) } - /// Permanently roots a managed reference exposed through the copyable host API. - pub(crate) fn pin(&self, value: ValueRef) { - if let Some(handle) = self.handle(value) { - let mut pinned = self.pinned.borrow_mut(); - if let Err(index) = pinned.binary_search(&handle) { - pinned.insert(index, handle); - } - } - } - - pub(crate) fn copy_within(&mut self, object: ValueRef, src: core::ops::Range, dst: usize) -> Option<()> { - let object = self.get_mut(object)?; + pub(crate) fn copy_within(&mut self, object: Handle, src: core::ops::Range, dst: usize) -> Option<()> { + let object = self.objects.get_mut(object)?; object.values.copy_within(src.clone(), dst); if let Some(references) = &mut object.references { references.copy_within(src, dst); @@ -204,13 +212,11 @@ impl GcHeap { /// Copies values and tracing metadata between two distinct objects. pub(crate) fn copy_between( &mut self, - src: ValueRef, + src: Handle, src_range: core::ops::Range, - dst: ValueRef, + dst: Handle, dst_index: usize, ) -> Option<()> { - let src = self.handle(src)?; - let dst = self.handle(dst)?; let (src, dst) = self.objects.get_disjoint_mut(src, dst)?; let src_values = src.values.get(src_range.clone())?; let dst_end = dst_index.checked_add(src_values.len())?; @@ -254,13 +260,27 @@ mod tests { #[test] fn collection_reclaims_object_cycles() { let mut heap = GcHeap::default(); - let first = heap.alloc(0, alloc::vec![TinyWasmValue::ValueRef(ValueRef::NULL)], true).unwrap(); - let second = heap.alloc(0, alloc::vec![TinyWasmValue::ValueRef(first)], true).unwrap(); - heap.set(first, 0, TinyWasmValue::ValueRef(second)).unwrap(); + let first = heap.alloc(0, alloc::vec![RuntimeValue::ValueRef(ValueRef::NULL)], true).unwrap(); + let second = heap.alloc(0, alloc::vec![RuntimeValue::ValueRef(first)], true).unwrap(); + heap.set(heap.handle(first).unwrap(), 0, RuntimeValue::ValueRef(second)).unwrap(); heap.collect([]).unwrap(); assert!(heap.get(first).is_none()); assert!(heap.get(second).is_none()); } + + #[test] + fn exception_payload_traces_managed_objects() { + let mut heap = GcHeap::default(); + let payload = heap.alloc(0, Vec::new(), false).unwrap(); + let exception = heap.alloc_exception(0, alloc::vec![RuntimeValue::ValueRef(payload)], &[true]).unwrap(); + + heap.collect([exception]).unwrap(); + assert!(heap.get(payload).is_some()); + + heap.collect([]).unwrap(); + assert!(heap.get(exception).is_none()); + assert!(heap.get(payload).is_none()); + } } diff --git a/crates/tinywasm/src/store/gc/roots.rs b/crates/tinywasm/src/store/gc/roots.rs new file mode 100644 index 0000000..7107295 --- /dev/null +++ b/crates/tinywasm/src/store/gc/roots.rs @@ -0,0 +1,58 @@ +use alloc::{sync::Arc, sync::Weak, vec::Vec}; + +use crate::Trap; +use crate::interpreter::ValueRef; + +pub(crate) struct Roots { + entries: Vec>, + free: Vec, +} + +struct Root { + value: ValueRef, + token: Weak<()>, +} + +impl Roots { + pub(crate) const fn new() -> Self { + Self { entries: Vec::new(), free: Vec::new() } + } + + pub(crate) fn reserve(&mut self, additional: usize) -> Result<(), Trap> { + self.remove_dead(); + let needed = additional.saturating_sub(self.free.len()); + self.entries.try_reserve(needed).map_err(|_| Trap::OutOfMemory) + } + + pub(crate) fn insert(&mut self, value: ValueRef) -> Result, Trap> { + if self.free.is_empty() && self.entries.len() == self.entries.capacity() { + self.remove_dead(); + } + let index = if let Some(index) = self.free.pop() { + index + } else { + let index = u32::try_from(self.entries.len()).map_err(|_| Trap::OutOfMemory)?; + self.entries.try_reserve(1).map_err(|_| Trap::OutOfMemory)?; + self.entries.push(None); + index + }; + + let token = Arc::new(()); + self.entries[index as usize] = Some(Root { value, token: Arc::downgrade(&token) }); + Ok(token) + } + + pub(crate) fn values(&mut self) -> impl Iterator + '_ { + self.remove_dead(); + self.entries.iter().flatten().map(|root| root.value) + } + + fn remove_dead(&mut self) { + for (index, root) in self.entries.iter_mut().enumerate() { + if root.as_ref().is_some_and(|root| root.token.strong_count() == 0) { + *root = None; + self.free.push(index as u32); + } + } + } +} diff --git a/crates/tinywasm/src/store/global.rs b/crates/tinywasm/src/store/global.rs index 69e538f..4052eb8 100644 --- a/crates/tinywasm/src/store/global.rs +++ b/crates/tinywasm/src/store/global.rs @@ -1,7 +1,7 @@ use alloc::vec::Vec; use tinywasm_types::*; -use crate::interpreter::{TinyWasmValue, Value32, Value64, Value128}; +use crate::interpreter::{RuntimeValue, Value32, Value64, Value128}; struct GlobalLane { values: Vec, @@ -98,18 +98,18 @@ impl Globals { } /// Adds a global and returns its packed store address. - pub(crate) fn push(&mut self, ty: GlobalType, value: TinyWasmValue) -> GlobalAddr { + pub(crate) fn push(&mut self, ty: GlobalType, value: RuntimeValue) -> GlobalAddr { match (ty.ty, value) { - (WasmType::I32 | WasmType::F32, TinyWasmValue::Value32(value)) => { + (WasmType::I32 | WasmType::F32, RuntimeValue::Value32(value)) => { Self::addr(Self::LANE_32, self.globals_32.push(ty, value)) } - (WasmType::Ref(_), TinyWasmValue::ValueRef(value)) => { + (WasmType::Ref(_), RuntimeValue::ValueRef(value)) => { Self::addr(Self::LANE_32, self.globals_32.push(ty, value.raw())) } - (WasmType::I64 | WasmType::F64, TinyWasmValue::Value64(value)) => { + (WasmType::I64 | WasmType::F64, RuntimeValue::Value64(value)) => { Self::addr(Self::LANE_64, self.globals_64.push(ty, value)) } - (WasmType::V128, TinyWasmValue::Value128(value)) => { + (WasmType::V128, RuntimeValue::Value128(value)) => { Self::addr(Self::LANE_128, self.globals_128.push(ty, value)) } _ => unreachable!("global value does not match its declared type"), diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 2ddd43c..91895b4 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -1,17 +1,16 @@ use alloc::{boxed::Box, format, vec::Vec}; use core::hint::cold_path; -use core::sync::atomic::{AtomicU32, Ordering}; use tinywasm_types::*; use crate::func::FromWasmValues; use crate::interpreter::stack::{CallStack, StackBase, ValueStack}; -use crate::interpreter::{TinyWasmValue, ValueRef}; -use crate::{Engine, Error, ModuleInstance, Result, Trap}; +use crate::interpreter::{RuntimeValue, ValueRef}; +use crate::reference::{ReferentKind, RootedItem, StoreId, StoredRef}; +use crate::{Engine, Error, ExnRef, FuncRef, ModuleInstance, RefValue, Result, Trap, WasmValue}; mod const_expr; mod data; mod element; -mod exception; mod function; mod gc; mod global; @@ -22,22 +21,24 @@ mod tag; mod types; use const_expr::eval_const; -pub(crate) use gc::{decode_data, default_value, pop_value, push_value}; +pub(crate) use gc::{GcObjectKind, data_range, decode_data, default_value, pop_value, push_value}; pub(crate) use memory::{MemValue, MemoryInstance}; pub(crate) use state::State; pub(crate) use types::{canonicalize_ref_type, canonicalize_value_type}; -pub(crate) use {data::*, element::*, exception::*, function::*, global::*, table::*, tag::*}; +pub(crate) use {data::*, element::*, function::*, global::*, table::*, tag::*}; -// global store id counter -static STORE_ID: AtomicU32 = AtomicU32::new(0); - -/// Controls resource usage by WebAssembly instances. +/// Controls selected allocation requests from WebAssembly instances. /// /// Configure a limiter with -/// [`Config::with_resource_limiter`](crate::engine::Config::with_resource_limiter). It currently -/// controls guest linear-memory, table, and GC heap growth. It does not account for stacks, runtime +/// [`Config::with_resource_limiter`](crate::engine::Config::with_resource_limiter). The callbacks +/// cover linear memory, tables, and the logical GC heap. They do not account for stacks, runtime /// metadata, temporary buffers, backing-capacity overhead, or other host allocations. /// +/// `Ok(true)` allows an allocation attempt, `Ok(false)` rejects it, and `Err` returns the supplied +/// trap. Allowing a request does not guarantee that the backing allocation will succeed. Rejected +/// growth uses the operation's normal failed-growth result. Rejected initial allocation and GC +/// allocation produce [`Trap::OutOfMemory`]. +/// /// # Example /// ```rust /// use std::sync::Arc; @@ -60,17 +61,17 @@ static STORE_ID: AtomicU32 = AtomicU32::new(0); /// /// let config = Config::new().with_resource_limiter(Arc::new(MemoryLimit(64 * 1024))); /// let mut store = Store::new(Engine::new(config)); -/// let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?; +/// let memory = Memory::try_new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?; /// assert_eq!(memory.grow(&mut store, 1)?, None); /// # Ok::<(), tinywasm::Error>(()) /// ``` pub trait ResourceLimiter: Send + Sync { - /// Returns whether a memory allocation or growth is allowed. + /// Checks a nonzero memory allocation or growth request. /// - /// Sizes are in bytes. `current` is zero for initial allocation, and `maximum` is `None` for an - /// unbounded memory. `Ok(false)` rejects the request, while `Err` traps. Rejected initial - /// allocations return [`Trap::OutOfMemory`], since they have no normal failure result. The - /// default implementation allows the request. + /// Sizes are in bytes. `current` is zero for initial allocation. `maximum` is the declared + /// maximum in bytes, saturated to `usize::MAX` if needed, or `None` if no maximum was declared. + /// Growth limits are checked before this callback. The default implementation allows the + /// request. fn memory_growing( &self, _current: usize, @@ -80,12 +81,11 @@ pub trait ResourceLimiter: Send + Sync { Ok(true) } - /// Returns whether a table allocation or growth is allowed. + /// Checks a nonzero table allocation or growth request. /// - /// Sizes are in elements. `current` is zero for initial allocation, and `maximum` is `None` for - /// an unbounded table. `Ok(false)` rejects the request, while `Err` traps. Rejected initial - /// allocations return [`Trap::OutOfMemory`], since they have no normal failure result. The - /// default implementation allows the request. + /// Sizes are in elements. `current` is zero for initial allocation. `maximum` is the declared + /// maximum element count when it fits `usize`, or `None` otherwise. Table limits are checked + /// before this callback. The default implementation allows the request. fn table_growing( &self, _current: usize, @@ -95,11 +95,12 @@ pub trait ResourceLimiter: Send + Sync { Ok(true) } - /// Returns whether a GC object allocation is allowed. + /// Checks a GC object allocation request. /// - /// Sizes are the logical bytes retained by live GC objects after collection. `maximum` is - /// currently always `None`. `Ok(false)` rejects the allocation with [`Trap::OutOfMemory`], while - /// `Err` returns the provided trap. The default implementation allows the request. + /// Sizes are the current TinyWasm-accounted heap bytes and that count plus the requested + /// allocation. They include unreachable objects until collection but not all allocator + /// overhead. `maximum` is currently always `None`. This callback runs before threshold-triggered + /// collection. fn gc_growing( &self, _current: usize, @@ -122,9 +123,9 @@ pub trait ResourceLimiter: Send + Sync { /// # _ = store; /// ``` /// -/// See +/// See pub struct Store { - id: u32, + id: StoreId, pub(crate) module_instances: Vec, pub(crate) engine: Engine, @@ -133,9 +134,74 @@ pub struct Store { pub(crate) state: State, pub(crate) call_stack: CallStack, pub(crate) value_stack: ValueStack, - pub(crate) host_params: Vec, + value_scratch: ValueScratch, +} + +#[derive(Default)] +struct ValueScratch(Vec); + +impl ValueScratch { + fn take_resized(&mut self, len: usize) -> Result> { + self.0.clear(); + self.0.try_reserve(len).map_err(|_| Trap::OutOfMemory)?; + self.0.resize(len, WasmValue::I32(0)); + Ok(core::mem::take(&mut self.0)) + } + + fn restore(&mut self, mut values: Vec) { + values.clear(); + if values.capacity() > self.0.capacity() { + self.0 = values; + } + } +} + +#[derive(Clone, Copy)] +pub(crate) enum FuncValueTypes { + Params, + Results, +} + +pub(crate) struct StackValueIter<'a> { + store: &'a mut Store, + type_addr: TypeAddr, + types: FuncValueTypes, + index: StackBase, + position: usize, + len: usize, } +impl Iterator for StackValueIter<'_> { + type Item = WasmValue; + + fn next(&mut self) -> Option { + if self.position == self.len { + return None; + } + let ty = { + let func_ty = self.store.state.get_canonical_func_type(self.type_addr); + match self.types { + FuncValueTypes::Params => func_ty.params()[self.position], + FuncValueTypes::Results => func_ty.results()[self.position], + } + }; + self.position += 1; + let value = self.store.stack_value(ty, &mut self.index); + Some( + value + .into_wasm(self.store, ty) + .unwrap_or_else(|_| unreachable!("invalid internal value at a typed host boundary")), + ) + } + + fn size_hint(&self) -> (usize, Option) { + let remaining = self.len - self.position; + (remaining, Some(remaining)) + } +} + +impl ExactSizeIterator for StackValueIter<'_> {} + #[cfg(feature = "debug")] impl core::fmt::Debug for Store { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { @@ -162,8 +228,7 @@ impl Default for Store { impl Store { /// Create a new store pub fn new(engine: Engine) -> Self { - let id = - STORE_ID.try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1)).expect("too many stores"); + let id = StoreId::fresh(); let state = State::new(engine.config()); Self { id, @@ -171,7 +236,7 @@ impl Store { state, call_stack: CallStack::new(engine.config()), value_stack: ValueStack::new(engine.config()), - host_params: Vec::new(), + value_scratch: ValueScratch::default(), engine, execution_fuel: 0, execution_active: false, @@ -180,9 +245,166 @@ impl Store { /// Get the store's ID (unique per process) pub fn id(&self) -> u32 { + self.id.get() + } + + pub(crate) const fn store_id(&self) -> StoreId { self.id } + pub(crate) fn with_scratch_values( + &mut self, + len: usize, + use_values: impl FnOnce(&mut Self, &mut Vec) -> Result, + ) -> Result { + let mut values = self.value_scratch.take_resized(len)?; + let result = use_values(self, &mut values); + self.value_scratch.restore(values); + result + } + + pub(crate) fn root_reference(&mut self, value: ValueRef, kind: ReferentKind) -> Result { + let token = match kind { + ReferentKind::Struct | ReferentKind::Array | ReferentKind::Exception => { + Some(self.state.roots.insert(value)?) + } + ReferentKind::I31 | ReferentKind::HostExtern => None, + }; + Ok(T::from_rooted_item(RootedItem { store: self.id, value, kind, _token: token })) + } + + pub(crate) fn root_exception(&mut self, value: ValueRef) -> Result { + if !matches!(self.state.gc.get(value).map(|object| object.kind), Some(gc::GcObjectKind::Exception(_))) { + return Err(Trap::InvalidReference.into()); + } + self.root_reference(value, ReferentKind::Exception) + } + + pub(crate) fn resolve_ref(&self, reference: &T) -> Result { + let item = reference.rooted_item(); + if item.store != self.id { + return Err(Trap::InvalidStore); + } + Ok(item.value) + } + + pub(crate) fn encode_ref(&self, value: &RefValue) -> Result { + Ok(match value { + RefValue::Null => ValueRef::NULL, + RefValue::Func(value) => ValueRef::from_category_addr(value.addr(self.id).ok_or(Trap::InvalidStore)?), + RefValue::Any(value) => self.resolve_ref(value)?, + RefValue::Extern(value) => self.resolve_ref(value)?, + RefValue::Exn(value) => self.resolve_ref(value)?, + }) + } + + pub(crate) fn decode_ref(&mut self, value: ValueRef, ty: RefType) -> Result { + if value.is_null() { + return Ok(RefValue::Null); + } + if ty.type_index().is_some_and(|addr| self.state.get_type(addr).as_func().is_some()) || ty.is_func() { + return Ok(RefValue::Func(FuncRef::new(self.id, value.addr().ok_or(Trap::InvalidReference)?))); + } + if ty.is_exn() { + return self.root_exception(value).map(RefValue::Exn); + } + let kind = if value.is_i31() { + ReferentKind::I31 + } else if value.is_host_any() { + ReferentKind::HostExtern + } else { + match self.state.gc.get(value).map(|object| object.kind) { + Some(gc::GcObjectKind::Composite(type_addr)) => match &self.state.get_type(type_addr).composite { + CompositeType::Struct(_) => ReferentKind::Struct, + CompositeType::Array(_) => ReferentKind::Array, + CompositeType::Func(_) => return Err(Trap::InvalidReference.into()), + }, + _ => return Err(Trap::InvalidReference.into()), + } + }; + if ty.is_extern() { + Ok(RefValue::Extern(self.root_reference(value, kind)?)) + } else { + Ok(RefValue::Any(self.root_reference(value, kind)?)) + } + } + + fn stack_value(&self, ty: WasmType, index: &mut StackBase) -> RuntimeValue { + match ty { + WasmType::I32 | WasmType::F32 | WasmType::Ref(_) => { + let value = *self.value_stack.stack_32.get(index.s32 as usize); + index.s32 += 1; + if matches!(ty, WasmType::Ref(_)) { + RuntimeValue::ValueRef(ValueRef::from_raw(value)) + } else { + RuntimeValue::Value32(value) + } + } + WasmType::I64 | WasmType::F64 => { + let value = *self.value_stack.stack_64.get(index.s64 as usize); + index.s64 += 1; + RuntimeValue::Value64(value) + } + WasmType::V128 => { + let value = *self.value_stack.stack_128.get(index.s128 as usize); + index.s128 += 1; + RuntimeValue::Value128(value) + } + } + } + + pub(crate) fn stack_value_iter( + &mut self, + type_addr: TypeAddr, + types: FuncValueTypes, + index: StackBase, + ) -> Result, Trap> { + let canonical = self.state.get_canonical_func_type(type_addr); + let canonical = match types { + FuncValueTypes::Params => canonical.params(), + FuncValueTypes::Results => canonical.results(), + }; + let len = canonical.len(); + let reference_count = canonical.iter().filter(|ty| matches!(ty, WasmType::Ref(_))).count(); + self.state.roots.reserve(reference_count)?; + Ok(StackValueIter { store: self, type_addr, types, index, position: 0, len }) + } + + pub(crate) fn push_wasm_values(&mut self, values: impl IntoIterator) -> Result<()> { + for value in values { + let value = value.to_runtime(self)?; + self.value_stack.push_dyn(value)?; + } + Ok(()) + } + + pub(crate) fn pop_stack_values(&mut self, types: &[WasmType], results: &mut [WasmValue]) -> Result<()> { + if types.len() != results.len() { + return Err(Error::other("result buffer has the wrong length")); + } + let base = self.value_stack.base_before(types.iter().collect()); + let result = (|| { + let mut index = base; + for (&ty, result) in types.iter().zip(results) { + let value = self.stack_value(ty, &mut index); + *result = value.into_wasm(self, ty)?; + } + Ok(()) + })(); + self.value_stack.truncate_to_base(base); + result + } + + /// Reclaims unreachable managed objects. + /// + /// Globals, tables, operand stacks, and owned host references are traced as + /// roots. Objects also become eligible for automatic threshold collection + /// after the last owned handle is dropped. + pub fn gc(&mut self) -> Result<()> { + let stack_roots = self.value_stack.stack_32.into_iter().copied().map(ValueRef::from_raw).collect::>(); + self.state.collect_gc(stack_roots).map_err(|_| Trap::OutOfMemory.into()) + } + /// Get a module instance by the internal id pub fn get_module_instance(&self, id: ModuleInstanceId) -> Option<&ModuleInstance> { self.module_instances.get(id as usize) @@ -197,10 +419,27 @@ impl Store { self.module_instances.push(instance); } - /// Returns whether a public value has the requested runtime type. - #[doc(hidden)] - pub fn value_matches_type(&self, value: WasmValue, ty: WasmType) -> bool { - self.state.value_matches_type(value, ty) + pub(crate) fn value_matches_type(&self, value: &WasmValue, ty: WasmType) -> bool { + let (WasmValue::Ref(value), WasmType::Ref(expected)) = (value, ty) else { + return value.matches_type(ty); + }; + let category_matches = match value { + RefValue::Null => return expected.is_nullable(), + RefValue::Func(_) => { + expected.is_func() + || expected.type_index().is_some_and(|addr| self.state.get_type(addr).as_func().is_some()) + } + RefValue::Extern(_) => expected.is_extern(), + RefValue::Exn(_) => expected.is_exn(), + RefValue::Any(_) => !expected.is_func() && !expected.is_extern() && !expected.is_exn(), + }; + if !category_matches { + return false; + } + match self.encode_ref(value) { + Ok(value) => self.state.value_ref_matches(value, expected), + _ => false, + } } /// Marks the store as executing and rejects nested root calls. @@ -233,10 +472,11 @@ impl Store { let mut values = values; for &ty in expected { let value = values.next().ok_or_else(|| Error::other("not enough typed function values"))?; - if !self.state.value_matches_type(value, ty) { + let internal = value.to_runtime(self)?; + if !self.value_matches_type(&value, ty) { return Err(Error::other("typed function value does not match its signature")); } - self.value_stack.extend_wasmvalues(core::iter::once(value))?; + self.value_stack.push_dyn(internal)?; } if values.next().is_some() { return Err(Error::other("too many typed function values")); @@ -254,18 +494,11 @@ impl Store { &mut self, type_addr: TypeAddr, stack_base: StackBase, - pin_refs: bool, ) -> Result { - let types = self.state.get_canonical_func_type(type_addr).results(); - let mut values = self.value_stack.wasm_values(&self.state, types, stack_base, pin_refs); - let result = R::from_wasm_values(&mut values).and_then(|result| { - if values.next().is_some() { - Err(Error::other("typed conversion did not consume all WebAssembly values")) - } else { - Ok(result) - } - }); - drop(values); + let result = { + let mut values = self.stack_value_iter(type_addr, FuncValueTypes::Results, stack_base)?; + R::from_wasm_values_exact(&mut values) + }; self.value_stack.truncate_to_base(stack_base); result } @@ -283,11 +516,9 @@ impl Store { self.state.funcs.reserve_exact(funcs.len()); for (func, &type_idx) in funcs.iter().cloned().zip(module_type_idxs) { let type_addr = type_addrs[type_idx as usize]; - self.state.funcs.push(FunctionInstance { - type_addr, - gc: self.state.func_gc_metadata(type_addr), - kind: FunctionKind::Wasm(WasmFunctionInstance { func, owner }), - }); + self.state + .funcs + .push(FunctionInstance { type_addr, kind: FunctionKind::Wasm(WasmFunctionInstance { func, owner }) }); } start..start + funcs.len() as FuncAddr } @@ -318,7 +549,7 @@ impl Store { for table in tables { let init = match &table.init { Some(expr) => match eval_const(&mut self.state, expr, global_addrs, func_addrs, type_addrs)? { - TinyWasmValue::ValueRef(value) => value, + RuntimeValue::ValueRef(value) => value, _ => return Err(Error::other("table initializer is not a reference value")), }, None => ValueRef::NULL, @@ -374,7 +605,7 @@ impl Store { ) -> Result { match item { ElementItem::Expr(expr) => match eval_const(&mut self.state, expr, globals, funcs, type_addrs)? { - TinyWasmValue::ValueRef(value) => Ok(value), + RuntimeValue::ValueRef(value) => Ok(value), other => { cold_path(); Err(Error::Other(format!("expected ref type, got {other:?}"))) @@ -426,8 +657,8 @@ impl Store { // this one is active, so we need to initialize it (essentially a `table.init` instruction) ElementKind::Active { offset, table } => { let offset = match eval_const(&mut self.state, offset, global_addrs, func_addrs, type_addrs)? { - TinyWasmValue::Value32(value) => u64::from(value), - TinyWasmValue::Value64(value) => value, + RuntimeValue::Value32(value) => u64::from(value), + RuntimeValue::Value64(value) => value, other => return Err(Error::Other(format!("expected i32 or i64, got {other:?}"))), }; let table_addr = table_addrs @@ -493,8 +724,8 @@ impl Store { }; let offset = match eval_const(&mut self.state, offset, global_addrs, func_addrs, type_addrs)? { - TinyWasmValue::Value32(value) => u64::from(value), - TinyWasmValue::Value64(value) => value, + RuntimeValue::Value32(value) => u64::from(value), + RuntimeValue::Value64(value) => value, other => return Err(Error::Other(format!("expected i32 or i64, got {other:?}"))), }; let Some(mem) = self.state.memories.get_mut(*mem_addr as usize) else { diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index 90d1fb0..11ea70d 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -2,7 +2,6 @@ use alloc::vec::Vec; use super::*; use crate::engine::Config; -use crate::interpreter::Value128; /// Global state that can be manipulated by WebAssembly programs /// @@ -17,10 +16,10 @@ pub(crate) struct State { pub(crate) memories: Vec, pub(crate) globals: Globals, pub(crate) tags: Vec, - pub(crate) exceptions: Vec, pub(crate) elements: Vec, pub(crate) data: Vec, pub(crate) gc: gc::GcHeap, + pub(crate) roots: gc::Roots, } impl State { @@ -33,16 +32,37 @@ impl State { memories: Vec::new(), globals: Globals::default(), tags: Vec::new(), - exceptions: Vec::new(), elements: Vec::new(), data: Vec::new(), gc: gc::GcHeap::new(config), + roots: gc::Roots::new(), } } - /// Returns whether values of this type can contain a managed GC object. - pub(crate) fn type_may_contain_gc(&self, ty: &WasmType) -> bool { - Self::type_may_contain_gc_in(&self.canonical_types, ty) + pub(crate) fn collect_gc(&mut self, additional: impl IntoIterator) -> Result<(), gc::AllocError> { + let canonical_types = &self.canonical_types; + let store_roots = self + .globals + .globals_32() + .filter(|(_, ty)| Self::type_may_contain_gc_in(canonical_types, &ty.ty)) + .map(|(value, _)| ValueRef::from_raw(*value)) + .chain( + self.tables + .iter() + .filter(|table| { + Self::type_may_contain_gc_in(canonical_types, &WasmType::Ref(table.kind.element_type)) + }) + .flat_map(|table| table.elements.iter().copied()), + ) + .chain( + self.elements + .iter() + .filter(|element| Self::type_may_contain_gc_in(canonical_types, &WasmType::Ref(element.ty))) + .flat_map(|element| element.items.iter().flatten().copied()), + ) + .chain(additional); + let roots = self.roots.values().chain(store_roots); + self.gc.collect(roots) } fn type_may_contain_gc_in(types: &[SubType], ty: &WasmType) -> bool { @@ -58,25 +78,28 @@ impl State { | AbstractHeapType::Struct | AbstractHeapType::Array | AbstractHeapType::Extern + | AbstractHeapType::Exn ) ) } - /// Precomputes whether a canonical function signature can carry GC objects. - pub(crate) fn func_gc_metadata(&self, type_addr: TypeAddr) -> FunctionGcMetadata { - let ty = self.get_canonical_func_type(type_addr); - FunctionGcMetadata { - params: ty.params().iter().any(|ty| self.type_may_contain_gc(ty)), - results: ty.results().iter().any(|ty| self.type_may_contain_gc(ty)), - } + pub(crate) fn check_gc_allocation(&self, type_addr: TypeAddr, value_count: usize) -> Result<(), Trap> { + let trace_references = match &self.get_type(type_addr).composite { + CompositeType::Struct(ty) => { + ty.fields.iter().any(|field| matches!(field.storage, StorageType::Value(WasmType::Ref(_)))) + } + CompositeType::Array(ty) => matches!(ty.field.storage, StorageType::Value(WasmType::Ref(_))), + CompositeType::Func(_) => unreachable!("GC object type is not a function"), + }; + self.gc.check_allocation(value_count, trace_references) } /// Allocates an object, collecting from all runtime roots when needed. pub(crate) fn alloc_gc_object( &mut self, type_addr: TypeAddr, - values: Vec, - stack_32: impl IntoIterator, + values: Vec, + additional_roots: impl IntoIterator, ) -> Result { let trace_references = match &self.get_type(type_addr).composite { CompositeType::Struct(ty) => { @@ -86,66 +109,43 @@ impl State { CompositeType::Func(_) => unreachable!("GC object type is not a function"), }; if self.gc.should_collect(values.len(), trace_references) { - let canonical_types = &self.canonical_types; - let roots = stack_32 - .into_iter() - .map(ValueRef::from_raw) - .chain( - self.globals - .globals_32() - .filter(|(_, ty)| Self::type_may_contain_gc_in(canonical_types, &ty.ty)) - .map(|(value, _)| ValueRef::from_raw(*value)), - ) - .chain( - self.tables - .iter() - .filter(|table| { - Self::type_may_contain_gc_in(canonical_types, &WasmType::Ref(table.kind.element_type)) - }) - .flat_map(|table| table.elements.iter().copied()), - ) - .chain( - self.elements - .iter() - .filter(|element| Self::type_may_contain_gc_in(canonical_types, &WasmType::Ref(element.ty))) - .flat_map(|element| element.items.iter().flatten().copied()), - ) - .chain(self.exceptions.iter().flat_map(|exception| { - exception.payload.iter().filter_map(|value| match value { - TinyWasmValue::ValueRef(value) => Some(*value), - _ => None, - }) - })) - .chain(values.iter().filter_map(|value| match value { - TinyWasmValue::ValueRef(value) => Some(*value), - _ => None, - })); - cold_err!(self.gc.collect(roots)).map_err(|_| Trap::OutOfMemory)?; + let roots = additional_roots.into_iter().chain(values.iter().filter_map(|value| match value { + RuntimeValue::ValueRef(value) => Some(*value), + _ => None, + })); + cold_err!(self.collect_gc(roots)).map_err(|_| Trap::OutOfMemory)?; } self.gc.alloc(type_addr, values, trace_references) } - /// Pins a host-visible reference when it resolves to a managed GC object. - pub(crate) fn pin_host_ref(&self, value: RefValue) { - let raw = match value { - RefValue::Any(value) => value.raw(), - RefValue::Extern(value) => value.raw(), - RefValue::Null | RefValue::Func(_) | RefValue::Exn(_) => return, - }; - self.gc.pin(ValueRef::from_raw(raw)); - } - - /// Pins GC references that have crossed into host-visible values. - pub(crate) fn pin_host_values(&self, values: &[WasmValue]) { - for &value in values { - if let WasmValue::Ref(value) = value { - self.pin_host_ref(value); - } + /// Allocates a traced exception object, collecting with its payload as temporary roots. + pub(crate) fn alloc_exception( + &mut self, + tag_addr: TagAddr, + payload: Vec, + additional_roots: impl IntoIterator, + ) -> Result { + let type_addr = self.get_tag(tag_addr).type_addr; + let mut trace_fields = Vec::new(); + trace_fields.try_reserve_exact(payload.len()).map_err(|_| Trap::OutOfMemory)?; + trace_fields.extend( + self.get_canonical_func_type(type_addr) + .params() + .iter() + .map(|ty| Self::type_may_contain_gc_in(&self.canonical_types, ty)), + ); + if self.gc.should_collect(payload.len(), true) { + let roots = additional_roots.into_iter().chain(payload.iter().filter_map(|value| match value { + RuntimeValue::ValueRef(value) => Some(*value), + _ => None, + })); + cold_err!(self.collect_gc(roots)).map_err(|_| Trap::OutOfMemory)?; } + self.gc.alloc_exception(tag_addr, payload, &trace_fields) } /// Resolves a non-null object of the expected canonical type. - pub(crate) fn gc_object(&self, reference: ValueRef, expected_type: TypeAddr) -> Result<&gc::GcObject, Trap> { + pub(crate) fn gc_object(&self, reference: ValueRef, expected_type: TypeAddr) -> Result { if reference.is_null() { return Err(if self.get_type(expected_type).as_array().is_some() { Trap::NullArrayReference @@ -154,36 +154,13 @@ impl State { }); } let object = self.gc.get(reference).ok_or(Trap::Other("invalid GC reference"))?; - if !self.type_addr_is_subtype(object.type_addr, expected_type) { + let gc::GcObjectKind::Composite(type_addr) = object.kind else { + return Err(Trap::Other("GC reference is not a struct or array")); + }; + if !self.type_addr_is_subtype(type_addr, expected_type) { return Err(Trap::Other("GC reference type mismatch")); } - Ok(object) - } - - /// Converts an internal reference using canonical heap type information. - pub(crate) fn to_ref_value(&self, value: ValueRef, ty: RefType) -> RefValue { - if value.is_null() { - return RefValue::Null; - } - - if let Some(type_addr) = ty.type_index() { - return match &self.get_type(type_addr).composite { - CompositeType::Func(_) => { - RefValue::Func(FuncRef::new(value.addr().expect("non-null reference has an address"))) - } - CompositeType::Struct(_) | CompositeType::Array(_) => RefValue::Any(AnyRef::from_raw(value.raw())), - }; - } - if ty.is_func() { - return RefValue::Func(FuncRef::new(value.addr().expect("non-null reference has an address"))); - } - if ty.is_extern() { - return RefValue::Extern(ExternRef::from_raw(value.raw())); - } - if ty.is_exn() { - return RefValue::Exn(ExnRef::new(value.addr().expect("non-null reference has an address"))); - } - RefValue::Any(AnyRef::from_raw(value.raw())) + self.gc.handle(reference).ok_or(Trap::Other("invalid GC reference")) } /// Returns whether one canonical type is a subtype of another. @@ -276,7 +253,7 @@ impl State { return self.ref_type_is_subtype(RefType::new_concrete(false, func.type_addr), expected); } if expected.abstract_heap_type() == Some(AbstractHeapType::Exn) { - return value.addr().is_some_and(|addr| self.exceptions.get(addr as usize).is_some()); + return matches!(self.gc.get(value).map(|object| object.kind), Some(gc::GcObjectKind::Exception(_))); } if value.is_i31() { return self.ref_type_is_subtype(RefType::new_abstract(false, AbstractHeapType::I31), expected); @@ -286,7 +263,8 @@ impl State { } let Some(object) = self.gc.get(value) else { return false }; - let actual = RefType::new_concrete(false, object.type_addr); + let gc::GcObjectKind::Composite(type_addr) = object.kind else { return false }; + let actual = RefType::new_concrete(false, type_addr); self.ref_type_is_subtype(actual, expected) } @@ -305,30 +283,6 @@ impl State { self.get_type(addr).as_func().expect("validated function address references a function type") } - pub(crate) fn value_matches_type(&self, value: WasmValue, expected: WasmType) -> bool { - match (value, expected) { - (WasmValue::Ref(RefValue::Null), WasmType::Ref(expected)) => expected.is_nullable(), - (WasmValue::Ref(RefValue::Func(func)), WasmType::Ref(expected)) => self - .funcs - .get(func.addr() as usize) - .is_some_and(|func| self.ref_type_is_subtype(RefType::new_concrete(false, func.type_addr), expected)), - (WasmValue::Ref(RefValue::Any(_)), WasmType::Ref(expected)) - if expected.is_func() || expected.is_extern() || expected.is_exn() => - { - false - } - (WasmValue::Ref(RefValue::Exn(value)), WasmType::Ref(expected)) => { - expected.abstract_heap_type() == Some(AbstractHeapType::Exn) - && self.exceptions.get(value.addr() as usize).is_some() - } - (WasmValue::Ref(RefValue::Any(value)), WasmType::Ref(expected)) => { - self.value_ref_matches(ValueRef::from_raw(value.raw()), expected) - } - (_, WasmType::Ref(expected)) if expected.is_concrete() => false, - _ => value.matches_type(expected), - } - } - pub(super) fn get<'a, T>(items: &'a [T], addr: Addr, kind: &str) -> &'a T { items.get(addr as usize).unwrap_or_else(|| unreachable!("invalid {kind} address: {addr}")) } @@ -405,37 +359,29 @@ impl State { Self::get_mut(&mut self.elements, addr, "element") } - /// Converts a global directly to its public value representation. - pub(crate) fn get_global_wasmvalue(&self, addr: GlobalAddr) -> WasmValue { + /// Returns a global in its internal value representation. + pub(crate) fn global_value(&self, addr: GlobalAddr) -> RuntimeValue { let ty = self.globals.ty(addr).ty; match ty { - WasmType::I32 => WasmValue::I32(self.globals.get_32(addr) as i32), - WasmType::I64 => WasmValue::I64(self.globals.get_64(addr) as i64), - WasmType::F32 => WasmValue::F32(f32::from_bits(self.globals.get_32(addr))), - WasmType::F64 => WasmValue::F64(f64::from_bits(self.globals.get_64(addr))), - WasmType::Ref(ty) => WasmValue::Ref(self.to_ref_value(ValueRef::from_raw(self.globals.get_32(addr)), ty)), - WasmType::V128 => WasmValue::V128(self.globals.get_128(addr).0), + WasmType::I32 | WasmType::F32 => RuntimeValue::Value32(self.globals.get_32(addr)), + WasmType::I64 | WasmType::F64 => RuntimeValue::Value64(self.globals.get_64(addr)), + WasmType::Ref(_) => RuntimeValue::ValueRef(ValueRef::from_raw(self.globals.get_32(addr))), + WasmType::V128 => RuntimeValue::Value128(self.globals.get_128(addr)), } } - /// Validates and sets a global from its public value representation. - pub(crate) fn set_global_wasmvalue(&mut self, addr: GlobalAddr, value: WasmValue) -> Result<()> { + /// Sets a global from its internal value representation. + pub(crate) fn set_global_value(&mut self, addr: GlobalAddr, value: RuntimeValue) -> Result<()> { let ty = self.globals.ty(addr); if !ty.mutable { cold_path(); return Err(Error::other("global is immutable")); } - if !self.value_matches_type(value, ty.ty) { - cold_path(); - return Err(Error::other("invalid global value type")); - } match value { - WasmValue::I32(value) => self.globals.set_32(addr, value as u32), - WasmValue::I64(value) => self.globals.set_64(addr, value as u64), - WasmValue::F32(value) => self.globals.set_32(addr, value.to_bits()), - WasmValue::F64(value) => self.globals.set_64(addr, value.to_bits()), - WasmValue::Ref(value) => self.globals.set_32(addr, ValueRef::from(value).raw()), - WasmValue::V128(value) => self.globals.set_128(addr, Value128(value)), + RuntimeValue::Value32(value) => self.globals.set_32(addr, value), + RuntimeValue::Value64(value) => self.globals.set_64(addr, value), + RuntimeValue::ValueRef(value) => self.globals.set_32(addr, value.raw()), + RuntimeValue::Value128(value) => self.globals.set_128(addr, value), } Ok(()) } diff --git a/crates/tinywasm/src/store/table.rs b/crates/tinywasm/src/store/table.rs index da52660..cb8ded0 100644 --- a/crates/tinywasm/src/store/table.rs +++ b/crates/tinywasm/src/store/table.rs @@ -17,6 +17,9 @@ pub(crate) struct TableInstance { impl TableInstance { /// Creates a table filled with the given initial reference. pub(crate) fn new(kind: TableType, init: ValueRef, limiter: Option<&dyn ResourceLimiter>) -> Result { + if kind.size_max.is_some_and(|maximum| maximum < kind.size_initial) { + return Err(Trap::OutOfMemory.into()); + } let size = cold_err!(usize::try_from(kind.size_initial)).map_err(|_| Trap::OutOfMemory)?; if size > MAX_TABLE_SIZE { return Err(Trap::OutOfMemory.into()); diff --git a/crates/tinywasm/tests/gc_refs.rs b/crates/tinywasm/tests/gc_refs.rs index d3f2994..9662bee 100644 --- a/crates/tinywasm/tests/gc_refs.rs +++ b/crates/tinywasm/tests/gc_refs.rs @@ -1,4 +1,4 @@ -use tinywasm::types::{ExternRef, RefValue, WasmValue}; +use tinywasm::types::{RefValue, WasmValue}; use tinywasm::{Engine, ExecProgress, ModuleInstance, Store, engine::Config}; const MODULE: &str = r#" @@ -28,7 +28,7 @@ fn store() -> Store { } #[test] -fn host_result_is_pinned_and_rejected_by_another_store() { +fn host_result_is_rooted_and_rejected_by_another_store() { let module = tinywasm::parse_bytes(&wat::parse_str(MODULE).unwrap()).unwrap(); let mut first_store = store(); let first = ModuleInstance::instantiate(&mut first_store, &module, None).unwrap(); @@ -36,19 +36,23 @@ fn host_result_is_pinned_and_rejected_by_another_store() { let read = first.func_untyped(&first_store, "read").unwrap(); let churn = first.func_untyped(&first_store, "churn").unwrap(); - let value = new.call(&mut first_store, &[]).unwrap().pop().unwrap(); + let mut results = [WasmValue::Ref(RefValue::Null)]; + new.call(&mut first_store, &[], &mut results).unwrap(); + let [value] = results; assert!(matches!(value, WasmValue::Ref(RefValue::Any(_)))); - churn.call(&mut first_store, &[]).unwrap(); - assert_eq!(read.call(&mut first_store, &[value]).unwrap(), [WasmValue::I32(42)]); + churn.call(&mut first_store, &[], &mut []).unwrap(); + let mut results = [WasmValue::I32(0)]; + read.call(&mut first_store, std::slice::from_ref(&value), &mut results).unwrap(); + assert_eq!(results, [WasmValue::I32(42)]); let mut second_store = store(); let second = ModuleInstance::instantiate(&mut second_store, &module, None).unwrap(); let other_read = second.func_untyped(&second_store, "read").unwrap(); - assert!(other_read.call(&mut second_store, &[value]).is_err()); + assert!(other_read.call(&mut second_store, &[value], &mut [WasmValue::I32(0)]).is_err()); } #[test] -fn externalized_gc_result_is_pinned() { +fn externalized_gc_result_is_rooted() { let module = tinywasm::parse_bytes(&wat::parse_str(MODULE).unwrap()).unwrap(); let mut store = store(); let instance = ModuleInstance::instantiate(&mut store, &module, None).unwrap(); @@ -56,10 +60,14 @@ fn externalized_gc_result_is_pinned() { let read = instance.func_untyped(&store, "read-extern").unwrap(); let churn = instance.func_untyped(&store, "churn").unwrap(); - let value = new.call(&mut store, &[]).unwrap().pop().unwrap(); + let mut results = [WasmValue::Ref(RefValue::Null)]; + new.call(&mut store, &[], &mut results).unwrap(); + let [value] = results; assert!(matches!(value, WasmValue::Ref(RefValue::Extern(_)))); - churn.call(&mut store, &[]).unwrap(); - assert_eq!(read.call(&mut store, &[value]).unwrap(), [WasmValue::I32(42)]); + churn.call(&mut store, &[], &mut []).unwrap(); + let mut results = [WasmValue::I32(0)]; + read.call(&mut store, &[value], &mut results).unwrap(); + assert_eq!(results, [WasmValue::I32(42)]); } #[test] @@ -70,13 +78,13 @@ fn host_externref_does_not_alias_a_gc_object() { let new = instance.func_untyped(&store, "new").unwrap(); let read = instance.func_untyped(&store, "read-extern").unwrap(); - new.call(&mut store, &[]).unwrap(); - let host_ref = WasmValue::Ref(RefValue::Extern(ExternRef::new(0))); - assert!(read.call(&mut store, &[host_ref]).is_err()); + new.call(&mut store, &[], &mut [WasmValue::Ref(RefValue::Null)]).unwrap(); + let host_ref = tinywasm::ExternRef::try_new(&mut store, 0).unwrap().into(); + assert!(read.call(&mut store, &[host_ref], &mut [WasmValue::I32(0)]).is_err()); } #[test] -fn resumable_gc_result_is_pinned() { +fn resumable_gc_result_is_rooted() { let module = tinywasm::parse_bytes(&wat::parse_str(MODULE).unwrap()).unwrap(); let mut store = store(); let instance = ModuleInstance::instantiate(&mut store, &module, None).unwrap(); @@ -84,15 +92,20 @@ fn resumable_gc_result_is_pinned() { let read = instance.func_untyped(&store, "read").unwrap(); let churn = instance.func_untyped(&store, "churn").unwrap(); - let mut execution = new.call_resumable(&mut store, &[]).unwrap(); - let value = match execution.resume_with_fuel(1000).unwrap() { - ExecProgress::Completed(mut values) => values.pop().unwrap(), - ExecProgress::Suspended => panic!("constructor unexpectedly suspended"), - }; - drop(execution); + let mut results = [WasmValue::Ref(RefValue::Null)]; + { + let mut execution = new.call_resumable(&mut store, &[], &mut results).unwrap(); + match execution.resume_with_fuel(1000).unwrap() { + ExecProgress::Completed(()) => {} + ExecProgress::Suspended => panic!("constructor unexpectedly suspended"), + } + } + let [value] = results; - churn.call(&mut store, &[]).unwrap(); - assert_eq!(read.call(&mut store, &[value]).unwrap(), [WasmValue::I32(42)]); + churn.call(&mut store, &[], &mut []).unwrap(); + let mut results = [WasmValue::I32(0)]; + read.call(&mut store, &[value], &mut results).unwrap(); + assert_eq!(results, [WasmValue::I32(42)]); } #[test] @@ -116,5 +129,7 @@ fn element_initializers_root_previous_gc_values() { let mut store = store(); let instance = ModuleInstance::instantiate(&mut store, &module, None).unwrap(); - assert_eq!(instance.func_untyped(&store, "first").unwrap().call(&mut store, &[]).unwrap(), [WasmValue::I32(1)]); + let mut results = [WasmValue::I32(0)]; + instance.func_untyped(&store, "first").unwrap().call(&mut store, &[], &mut results).unwrap(); + assert_eq!(results, [WasmValue::I32(1)]); } diff --git a/crates/tinywasm/tests/host_func_signature_check.rs b/crates/tinywasm/tests/host_func_signature_check.rs index 38a85ef..484b3cc 100644 --- a/crates/tinywasm/tests/host_func_signature_check.rs +++ b/crates/tinywasm/tests/host_func_signature_check.rs @@ -1,6 +1,30 @@ use std::fmt::Write; -use tinywasm::types::{ExternRef, FuncType, RefType, RefValue, WasmType, WasmValue}; -use tinywasm::{FuncContext, HostFunction, Imports, Module, ModuleInstance, Store}; +use tinywasm::types::{FuncType, RefType, RefValue, WasmType, WasmValue}; +use tinywasm::{FuncContext, HostFunction, Imports, IntoWasmValues, Module, ModuleInstance, Store, ToWasmTypes}; + +struct TooFewParams; + +impl ToWasmTypes for TooFewParams { + const WASM_TYPES: Option<&'static [WasmType]> = Some(&[WasmType::I32, WasmType::I32]); +} + +impl IntoWasmValues for TooFewParams { + fn into_wasm_values(self) -> impl Iterator { + [WasmValue::I32(1)].into_iter() + } +} + +struct TooManyParams; + +impl ToWasmTypes for TooManyParams { + const WASM_TYPES: Option<&'static [WasmType]> = Some(&[WasmType::I32, WasmType::I32]); +} + +impl IntoWasmValues for TooManyParams { + fn into_wasm_values(self) -> impl Iterator { + [WasmValue::I32(1), WasmValue::I32(2), WasmValue::I32(3)].into_iter() + } +} const VAL_LISTS: &[&[WasmValue]] = &[ &[], @@ -8,7 +32,6 @@ const VAL_LISTS: &[&[WasmValue]] = &[ &[WasmValue::I32(0), WasmValue::I32(0)], &[WasmValue::I32(0), WasmValue::I32(0), WasmValue::F64(0.0)], &[WasmValue::I32(0), WasmValue::F64(0.0), WasmValue::I32(0)], - &[WasmValue::Ref(RefValue::Extern(ExternRef::new(0))), WasmValue::F64(0.0), WasmValue::I32(0)], ]; fn module_cases() -> Vec<(Module, FuncType, Vec)> { @@ -32,7 +55,13 @@ fn test_return_invalid_type() -> Result<(), Box> { for returned_values in VAL_LISTS { let mut store = Store::default(); let mut imports = Imports::new(); - let hfn = HostFunction::from_untyped(&ty, |_: FuncContext<'_>, _| Ok(returned_values.to_vec())); + let hfn = HostFunction::from_untyped(&ty, move |_: FuncContext<'_>, _, results| { + if results.len() != returned_values.len() { + return Err(tinywasm::Error::Other("invalid fixture result count".into())); + } + results.clone_from_slice(returned_values); + Ok(()) + }); imports.define("host", "hfn", hfn); let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports)).unwrap(); @@ -40,7 +69,8 @@ fn test_return_invalid_type() -> Result<(), Box> { // Return-type mismatch is only observable at call time. let should_succeed = returned_values.len() == ty.results().len() && returned_values.iter().zip(ty.results()).all(|(value, ty)| value.matches_type(*ty)); - let call_res = caller.call(&mut store, &args); + let mut results = vec![WasmValue::I32(0); ty.results().len()]; + let call_res = caller.call(&mut store, &args, &mut results); assert_eq!(call_res.is_ok(), should_succeed); } } @@ -54,7 +84,8 @@ fn test_linking_invalid_untyped_func() -> Result<(), Box for (module, expected_func_ty, _) in &cases { for (_, ty, _) in &cases { let mut store = Store::default(); - let tried_fn = HostFunction::from_untyped(ty, |_: FuncContext<'_>, _| panic!("not intended to be called")); + let tried_fn = + HostFunction::from_untyped(ty, |_: FuncContext<'_>, _, _| panic!("not intended to be called")); let mut imports = Imports::new(); imports.define("host", "hfn", tried_fn); @@ -105,7 +136,79 @@ fn test_linking_invalid_typed_func() -> Result<(), Box> } #[test] -fn concrete_host_references_use_canonical_types() -> Result<(), Box> { +fn typed_v128_values_roundtrip() -> Result<(), Box> { + let module = tinywasm::parse_bytes(&wat::parse_str( + r#" + (module + (import "host" "identity" (func $identity (param v128) (result v128))) + (func (export "identity") (param v128) (result v128) + local.get 0 + call $identity)) + "#, + )?)?; + let mut store = Store::default(); + let mut imports = Imports::new(); + imports.define("host", "identity", HostFunction::from(|_, value: [u8; 16]| Ok(value))); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + let identity = instance.func::<[u8; 16], [u8; 16]>(&store, "identity")?; + let value = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; + + assert_eq!(identity.call(&mut store, value)?, value); + Ok(()) +} + +#[test] +fn untyped_host_callbacks_must_write_all_results() -> Result<(), Box> { + let ty = FuncType::new(&[], &[WasmType::I32]); + let host = HostFunction::from_untyped(&ty, |_, _, _| Ok(())); + let mut store = Store::default(); + let function = host.clone().instantiate(&mut store)?; + let mut results = [WasmValue::I32(7)]; + + assert!(function.call(&mut store, &[], &mut results).is_err()); + assert!(function.call_resumable(&mut store, &[], &mut results).is_err()); + + let module = tinywasm::parse_bytes(&wat::parse_str( + r#" + (module + (import "host" "value" (func $value (result i32))) + (func (export "value") (result i32) call $value)) + "#, + )?)?; + let mut imports = Imports::new(); + imports.define("host", "value", host); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + let function = instance.func_untyped(&store, "value")?; + + assert!(function.call(&mut store, &[], &mut results).is_err()); + Ok(()) +} + +#[test] +fn typed_untyped_bridge_rejects_inexact_parameter_iterators() -> Result<(), Box> { + let module = tinywasm::parse_bytes(&wat::parse_str( + r#" + (module + (import "host" "take" (func $take (param i32 i32))) + (export "take" (func $take))) + "#, + )?)?; + let mut store = Store::default(); + let mut imports = Imports::new(); + imports.define( + "host", + "take", + HostFunction::from_untyped(&FuncType::new(&[WasmType::I32, WasmType::I32], &[]), |_, _, _| Ok(())), + ); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + + assert!(instance.func::(&store, "take")?.call(&mut store, TooFewParams).is_err()); + assert!(instance.func::(&store, "take")?.call(&mut store, TooManyParams).is_err()); + Ok(()) +} + +#[test] +fn standalone_host_functions_reject_concrete_types() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -125,19 +228,11 @@ fn concrete_host_references_use_canonical_types() -> Result<(), Box Result<(), Box Result<(), Box Result<(), Box> { let mut store = Store::default(); let ty = FuncType::new(&[WasmType::Ref(tinywasm::types::RefType::FUNCREF)], &[]); - let host = HostFunction::from_untyped(&ty, |_, _| Ok(Vec::new())).instantiate(&mut store)?; - let invalid = WasmValue::Ref(RefValue::Func(tinywasm::types::FuncRef::new(u32::MAX))); + let host = HostFunction::from_untyped(&ty, |_, _, _| Ok(())).instantiate(&mut store)?; + let mut other_store = Store::default(); + let other = HostFunction::from_untyped(&FuncType::new(&[], &[]), |_, _, _| Ok(())).instantiate(&mut other_store)?; + let invalid = WasmValue::Ref(RefValue::Func(other.as_func_ref(&other_store)?)); - assert!(host.call(&mut store, &[invalid]).is_err()); + assert!(host.call(&mut store, &[invalid], &mut []).is_err()); Ok(()) } diff --git a/crates/tinywasm/tests/imported_table_init.rs b/crates/tinywasm/tests/imported_table_init.rs index aaa781b..aa27b85 100644 --- a/crates/tinywasm/tests/imported_table_init.rs +++ b/crates/tinywasm/tests/imported_table_init.rs @@ -1,4 +1,4 @@ -use tinywasm::types::{FuncRef, RefType, TableType}; +use tinywasm::types::{RefType, TableType}; use tinywasm::{HostFunction, Imports, ModuleInstance, Store, Table}; #[test] @@ -18,8 +18,9 @@ fn imported_table_uses_provided_init_value() -> Result<(), Box Result<(), Box Result<(), Box Result<(), Box Result<() let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; let ExternItem::Func(func) = instance.extern_item("f")? else { panic!("expected function export") }; - assert_eq!(func.call(&mut store, &[])?, vec![]); + func.call(&mut store, &[], &mut [])?; Ok(()) } @@ -196,7 +199,7 @@ fn start_resolves_module_func_index_to_store_addr() -> Result<(), Box ModuleInstance { + let wasm = wat::parse_str(MODULE).unwrap(); + let module = tinywasm::parse_bytes(&wasm).unwrap(); + ModuleInstance::instantiate(store, &module, None).unwrap() +} + +fn exception(error: Error) -> ExnRef { + let Error::Exception(exception) = error else { panic!("expected exception") }; + exception +} + +#[test] +fn exception_accessors_validate_store_and_expose_payload() { + let mut store = Store::default(); + let instance = instantiate(&mut store); + let throw = instance.func_untyped(&store, "throw-scalar").unwrap(); + let exception = exception(throw.call(&mut store, &[WasmValue::I32(17)], &mut []).unwrap_err()); + + assert_eq!(exception.tag(&store).unwrap(), instance.tag("scalar-tag").unwrap()); + assert_eq!(exception.field(&mut store, 0).unwrap(), WasmValue::I32(17)); + assert_eq!(exception.fields(&mut store).unwrap(), [WasmValue::I32(17)]); + assert!(exception.field(&mut store, 1).is_err()); + + let other = Store::default(); + assert_eq!(exception.tag(&other).unwrap_err(), Error::Trap(Trap::InvalidStore)); +} + +#[test] +fn exception_roots_keep_payload_graphs_live() { + let mut store = Store::new(Engine::new(Config::new().with_gc_collection_threshold(1))); + let instance = instantiate(&mut store); + let throw = instance.func_untyped(&store, "throw-graph").unwrap(); + let read = instance.func_untyped(&store, "read-node").unwrap(); + let exception = exception(throw.call(&mut store, &[], &mut []).unwrap_err()); + + store.gc().unwrap(); + let payload = exception.field(&mut store, 0).unwrap(); + assert!(matches!(payload, WasmValue::Ref(RefValue::Any(_)))); + let mut results = [WasmValue::I32(0)]; + read.call(&mut store, &[payload], &mut results).unwrap(); + assert_eq!(results, [WasmValue::I32(42)]); +} + +#[test] +fn owned_exception_references_survive_collection_and_reject_another_store() { + let mut store = Store::default(); + let instance = instantiate(&mut store); + let throw = instance.func_untyped(&store, "throw-scalar").unwrap(); + let first = exception(throw.call(&mut store, &[WasmValue::I32(1)], &mut []).unwrap_err()); + + store.gc().unwrap(); + let current = exception(throw.call(&mut store, &[WasmValue::I32(2)], &mut []).unwrap_err()); + assert_eq!(current.field(&mut store, 0).unwrap(), WasmValue::I32(2)); + assert_eq!(first.field(&mut store, 0).unwrap(), WasmValue::I32(1)); + let rethrow = instance.func_untyped(&store, "rethrow").unwrap(); + let rethrown = exception(rethrow.call(&mut store, &[WasmValue::Ref(RefValue::Exn(first))], &mut []).unwrap_err()); + assert_eq!(rethrown.field(&mut store, 0).unwrap(), WasmValue::I32(1)); + + let mut other = Store::default(); + let other_instance = instantiate(&mut other); + let other_rethrow = other_instance.func_untyped(&other, "rethrow").unwrap(); + assert_eq!( + other_rethrow.call(&mut other, &[WasmValue::Ref(RefValue::Exn(current))], &mut []).unwrap_err(), + Error::Trap(Trap::InvalidStore) + ); +} + +#[test] +fn host_tags_reject_unbranded_concrete_types() { + let mut store = Store::default(); + let ty = FuncType::new(&[WasmType::Ref(RefType::new_concrete(true, 0))], &[]); + + assert!(Tag::try_new(&mut store, ty).is_err()); +} + +struct GcUsage(Arc>>); + +impl ResourceLimiter for GcUsage { + fn gc_growing(&self, current: usize, desired: usize, _maximum: Option) -> Result { + self.0.lock().unwrap().push((current, desired)); + Ok(true) + } +} + +#[test] +fn dropped_exception_roots_release_counted_gc_bytes() { + let usage = Arc::new(Mutex::new(Vec::new())); + let config = + Config::new().with_gc_collection_threshold(usize::MAX).with_resource_limiter(Arc::new(GcUsage(usage.clone()))); + let mut store = Store::new(Engine::new(config)); + let instance = instantiate(&mut store); + let catch = instance.func_untyped(&store, "catch-scalar").unwrap(); + + for value in 0..32 { + catch.call(&mut store, &[WasmValue::I32(value)], &mut []).unwrap(); + } + store.gc().unwrap(); + usage.lock().unwrap().clear(); + + catch.call(&mut store, &[WasmValue::I32(33)], &mut []).unwrap(); + assert_eq!(usage.lock().unwrap()[0].0, 0); +} diff --git a/crates/tinywasm/tests/memory.rs b/crates/tinywasm/tests/memory.rs index 213a15f..819fe85 100644 --- a/crates/tinywasm/tests/memory.rs +++ b/crates/tinywasm/tests/memory.rs @@ -16,7 +16,7 @@ fn store_with_limiter(limiter: Arc) -> Store { #[test] fn memory_read_write_roundtrip() -> TestResult { let mut store = Store::default(); - let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?; + let memory = Memory::try_new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?; memory.copy_from_slice(&mut store, 0, &[1, 2, 3, 4, 5])?; assert_eq!(memory.read_vec(&store, 0, 5)?, &[1, 2, 3, 4, 5]); @@ -28,7 +28,7 @@ fn memory_read_write_roundtrip() -> TestResult { #[test] fn read_returns_short_count_at_end_of_memory() -> TestResult { let mut store = Store::default(); - let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(1), Some(4)))?; + let memory = Memory::try_new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(1), Some(4)))?; memory.copy_from_slice(&mut store, 0, &[1, 2, 3, 4])?; let mut dst = [9; 8]; @@ -84,7 +84,7 @@ impl ResourceLimiter for TrapGrowth { #[test] fn resource_limiter_can_reject_growth() -> TestResult { let mut store = store_with_limiter(Arc::new(DenyGrowth)); - let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?; + let memory = Memory::try_new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None))?; assert_eq!(memory.grow(&mut store, 1)?, None); assert_eq!(memory.page_count(&store)?, 1); @@ -134,7 +134,7 @@ fn resource_limiter_can_trap_guest_memory_grow() -> TestResult { #[test] fn resource_limiter_rejects_host_memory_initial_size() { let mut store = store_with_limiter(Arc::new(DenyAll)); - let result = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None)); + let result = Memory::try_new(&mut store, MemoryType::new(MemoryArch::I32, 1, None, None)); assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory)))); } @@ -153,7 +153,15 @@ fn resource_limiter_rejects_module_memory_initial_size() -> TestResult { #[test] fn resource_limiter_rejects_table_initial_size() { let mut store = store_with_limiter(Arc::new(DenyAll)); - let result = Table::new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into()); + let result = Table::try_new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into()); + + assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory)))); +} + +#[test] +fn table_rejects_initial_size_above_maximum() { + let mut store = Store::default(); + let result = Table::try_new(&mut store, TableType::new(RefType::FUNCREF, 2, Some(1)), RefValue::Null.into()); assert!(matches!(result, Err(tinywasm::Error::Trap(Trap::OutOfMemory)))); } @@ -161,7 +169,7 @@ fn resource_limiter_rejects_table_initial_size() { #[test] fn resource_limiter_can_reject_table_growth() -> TestResult { let mut store = store_with_limiter(Arc::new(DenyGrowth)); - let table = Table::new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into())?; + let table = Table::try_new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into())?; assert_eq!(table.grow(&mut store, 1, RefValue::Null.into())?, None); assert_eq!(table.size(&store)?, 1); @@ -171,7 +179,7 @@ fn resource_limiter_can_reject_table_growth() -> TestResult { #[test] fn resource_limiter_can_trap_table_growth() -> TestResult { let mut store = store_with_limiter(Arc::new(TrapGrowth)); - let table = Table::new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into())?; + let table = Table::try_new(&mut store, TableType::new(RefType::FUNCREF, 1, None), RefValue::Null.into())?; assert!(matches!(table.grow(&mut store, 1, RefValue::Null.into()), Err(tinywasm::Error::Trap(Trap::Unreachable)))); Ok(()) diff --git a/crates/tinywasm/tests/reference_roots.rs b/crates/tinywasm/tests/reference_roots.rs new file mode 100644 index 0000000..775047e --- /dev/null +++ b/crates/tinywasm/tests/reference_roots.rs @@ -0,0 +1,104 @@ +use std::sync::{Arc, Mutex}; +use tinywasm::types::{ExternRef, FuncType, RefType, RefValue, WasmType, WasmValue}; +use tinywasm::{HostFunction, Imports, ModuleInstance, Store, Trap}; + +#[test] +fn direct_references_stay_live_until_the_last_clone_is_dropped() { + let mut store = Store::default(); + let reference = ExternRef::try_new(&mut store, 7).unwrap(); + let clone = reference.clone(); + drop(reference); + store.gc().unwrap(); + + assert_eq!(clone.key(&store), Ok(7)); +} + +#[test] +fn roots_and_function_references_reject_another_store() { + let mut first = Store::default(); + let mut second = Store::default(); + let root = ExternRef::try_new(&mut first, 1).unwrap(); + let function = HostFunction::from(|_, ()| -> tinywasm::Result<()> { Ok(()) }).instantiate(&mut first).unwrap(); + let func_ref = function.as_func_ref(&first).unwrap(); + let accepts_func_ref = + HostFunction::from(|_, _: Option| -> tinywasm::Result<()> { Ok(()) }) + .instantiate(&mut second) + .unwrap(); + + assert!(matches!(root.key(&second), Err(tinywasm::Error::Trap(Trap::InvalidStore)))); + assert!(matches!( + accepts_func_ref.call(&mut second, &[WasmValue::Ref(RefValue::Func(func_ref))], &mut []), + Err(tinywasm::Error::Trap(Trap::InvalidStore)) + )); +} + +#[test] +fn callback_results_and_captured_clones_remain_valid() { + let mut store = Store::default(); + let captured = Arc::new(Mutex::new(None)); + let callback_root = captured.clone(); + let ty = FuncType::new(&[], &[WasmType::Ref(RefType::EXTERNREF)]); + let function = HostFunction::from_untyped(&ty, move |mut context, _, results| { + let root = ExternRef::try_new(context.store_mut(), 17)?; + *callback_root.lock().unwrap() = Some(root.clone()); + results[0] = root.into(); + Ok(()) + }) + .instantiate(&mut store) + .unwrap(); + + let mut results = [WasmValue::Ref(RefValue::Null)]; + function.call(&mut store, &[], &mut results).unwrap(); + let [result] = results; + let WasmValue::Ref(RefValue::Extern(result)) = result else { panic!("expected externref") }; + assert_eq!(result.key(&store), Ok(17)); + assert_eq!(captured.lock().unwrap().as_ref().unwrap().key(&store), Ok(17)); +} + +#[test] +fn guest_callback_arguments_are_rooted_before_entering_untyped_host_code() { + let wasm = wat::parse_str( + r#" + (module + (import "host" "make" (func $make (result (ref extern)))) + (import "host" "check" (func $check (param externref))) + (func (export "call") + call $make + call $check)) + "#, + ) + .unwrap(); + let module = tinywasm::parse_bytes(&wasm).unwrap(); + let mut store = Store::default(); + let mut imports = Imports::new(); + imports.define("host", "make", HostFunction::from(|mut context, ()| ExternRef::try_new(context.store_mut(), 23))); + imports.define( + "host", + "check", + HostFunction::from_untyped( + &FuncType::new(&[WasmType::Ref(RefType::EXTERNREF)], &[]), + |context, args, _results| { + let WasmValue::Ref(RefValue::Extern(value)) = &args[0] else { panic!("expected externref") }; + assert_eq!(value.key(context.store()), Ok(23)); + Ok(()) + }, + ), + ); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports)).unwrap(); + + instance.func::<(), ()>(&store, "call").unwrap().call(&mut store, ()).unwrap(); +} + +#[test] +fn typed_option_reference_signatures_are_nullable() { + let mut store = Store::default(); + let function = + HostFunction::from(|_context, value: Option| -> tinywasm::Result> { Ok(value) }) + .instantiate(&mut store) + .unwrap(); + + assert_eq!(function.ty(&store).unwrap().params(), &[WasmType::Ref(RefType::EXTERNREF)]); + let mut results = [WasmValue::Ref(RefValue::Null)]; + function.call(&mut store, &[WasmValue::Ref(RefValue::Null)], &mut results).unwrap(); + assert_eq!(results, [WasmValue::Ref(RefValue::Null)]); +} diff --git a/crates/tinywasm/tests/resume_execution.rs b/crates/tinywasm/tests/resume_execution.rs index 2798e7b..f7dff4f 100644 --- a/crates/tinywasm/tests/resume_execution.rs +++ b/crates/tinywasm/tests/resume_execution.rs @@ -42,15 +42,17 @@ fn untyped_resume_supports_zero_fuel() -> Result<()> { let instance = ModuleInstance::instantiate(&mut store, &module, None)?; let func = instance.func_untyped(&store, "add")?; - let mut exec = func.call_resumable(&mut store, &[WasmValue::I32(20), WasmValue::I32(22)])?; - assert!(matches!(exec.resume_with_fuel(0)?, ExecProgress::Suspended)); - - match exec.resume_with_fuel(16)? { - ExecProgress::Completed(values) => { - assert_eq!(values, vec![WasmValue::I32(42)]) + let mut results = [WasmValue::I32(0)]; + { + let mut exec = func.call_resumable(&mut store, &[WasmValue::I32(20), WasmValue::I32(22)], &mut results)?; + assert!(matches!(exec.resume_with_fuel(0)?, ExecProgress::Suspended)); + + match exec.resume_with_fuel(16)? { + ExecProgress::Completed(()) => {} + ExecProgress::Suspended => panic!("expected completion"), } - ExecProgress::Suspended => panic!("expected completion"), } + assert_eq!(results, [WasmValue::I32(42)]); Ok(()) } diff --git a/crates/tinywasm/tests/store_ownership.rs b/crates/tinywasm/tests/store_ownership.rs index a508817..72c9478 100644 --- a/crates/tinywasm/tests/store_ownership.rs +++ b/crates/tinywasm/tests/store_ownership.rs @@ -21,7 +21,7 @@ fn func_handle_rejects_wrong_store() -> Result<(), Box> let func = instance.func_untyped(&owner_store, "add")?; let mut other_store = Store::default(); - let err = func.call(&mut other_store, &[1.into(), 2.into()]).unwrap_err(); + let err = func.call(&mut other_store, &[1.into(), 2.into()], &mut [0.into()]).unwrap_err(); assert!(err.to_string().contains("invalid store")); Ok(()) @@ -58,8 +58,8 @@ fn global_access_rejects_wrong_store() -> Result<(), Box let instance = ModuleInstance::instantiate(&mut owner_store, &module, None)?; let global = instance.global("g")?; - let other_store = Store::default(); - let err = global.get(&other_store).unwrap_err(); + let mut other_store = Store::default(); + let err = global.get(&mut other_store).unwrap_err(); assert_eq!(err, tinywasm::Error::Trap(tinywasm::Trap::InvalidStore)); Ok(()) @@ -92,7 +92,7 @@ fn global_import_rejects_wrong_store() -> Result<(), Box let wasm = wat::parse_str(r#"(module (import "env" "g" (global i32)))"#)?; let module = tinywasm::parse_bytes(&wasm)?; let mut owner_store = Store::default(); - let global = Global::new(&mut owner_store, GlobalType::new(WasmType::I32, false), 1.into())?; + let global = Global::try_new(&mut owner_store, GlobalType::new(WasmType::I32, false), 1.into())?; let mut imports = Imports::default(); imports.define("env", "g", global); diff --git a/crates/tinywasm/tests/typed_gc_access.rs b/crates/tinywasm/tests/typed_gc_access.rs new file mode 100644 index 0000000..26b2362 --- /dev/null +++ b/crates/tinywasm/tests/typed_gc_access.rs @@ -0,0 +1,49 @@ +use tinywasm::types::{ArrayRef, RefValue, StructRef, WasmValue}; +use tinywasm::{GcStorageType, ModuleInstance, Store}; + +#[test] +fn typed_struct_and_array_access() -> tinywasm::Result<()> { + let wasm = wat::parse_str( + r#"(module + (type $s (struct (field (mut i32)) (field i8))) + (type $refs (struct (field (ref $s)) (field (ref null $s)))) + (type $a (array (mut i16))) + (func $make-struct (result (ref $s)) + i32.const 7 + i32.const 258 + struct.new $s) + (func (export "struct") (result (ref struct)) + call $make-struct) + (func (export "refs") (result (ref struct)) + call $make-struct + ref.null $s + struct.new $refs) + (func (export "array") (result (ref array)) + i32.const 65537 + i32.const 2 + array.new $a))"#, + ) + .expect("valid WAT"); + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &tinywasm::parse_bytes(&wasm)?, None)?; + + let structure: StructRef = instance.func::<(), StructRef>(&store, "struct")?.call(&mut store, ())?; + assert_eq!(structure.fields(&mut store)?, [WasmValue::I32(7), WasmValue::I32(2)]); + structure.set_field(&mut store, 0, WasmValue::I32(9))?; + assert_eq!(structure.field(&mut store, 0)?, WasmValue::I32(9)); + assert_eq!(structure.ty(&store)?.field(&store, 1)?.storage(), GcStorageType::I8); + + let references: StructRef = instance.func::<(), StructRef>(&store, "refs")?.call(&mut store, ())?; + let fields = references.fields(&mut store)?; + let WasmValue::Ref(RefValue::Any(nested)) = &fields[0] else { panic!("expected struct reference") }; + assert_eq!(fields[1], WasmValue::Ref(RefValue::Null)); + store.gc()?; + assert_eq!(nested.as_struct().unwrap().field(&mut store, 0)?, WasmValue::I32(7)); + + let array: ArrayRef = instance.func::<(), ArrayRef>(&store, "array")?.call(&mut store, ())?; + assert_eq!(array.len(&store)?, 2); + assert_eq!(array.get(&mut store, 0)?, WasmValue::I32(1)); + array.set(&mut store, 1, WasmValue::I32(3))?; + assert_eq!(array.get(&mut store, 1)?, WasmValue::I32(3)); + Ok(()) +} diff --git a/crates/tinywasm/tests/typed_globals.rs b/crates/tinywasm/tests/typed_globals.rs index e57309f..34f402d 100644 --- a/crates/tinywasm/tests/typed_globals.rs +++ b/crates/tinywasm/tests/typed_globals.rs @@ -60,7 +60,9 @@ fn globals_use_typed_instructions_and_roundtrip_values() -> Result<(), Box(&store, "add-i32")?.call(&mut store, 2)?, 13); assert_eq!(instance.func::(&store, "add-i64")?.call(&mut store, 2)?, 15); @@ -81,12 +83,12 @@ fn imported_global_keeps_its_typed_store_address() -> Result<(), Box(&store, "roundtrip")?.call(&mut store, 42)?, 42); - assert_eq!(global.get(&store)?, WasmValue::I64(42)); + assert_eq!(global.get(&mut store)?, WasmValue::I64(42)); Ok(()) } diff --git a/crates/types/src/archive.rs b/crates/types/src/archive.rs index db40263..b568155 100644 --- a/crates/types/src/archive.rs +++ b/crates/types/src/archive.rs @@ -7,7 +7,7 @@ use crate::Module; #[rustfmt::skip] const TWASM_MAGIC: [u8; 16] = [ TWASM_MAGIC_PREFIX[0], TWASM_MAGIC_PREFIX[1], TWASM_MAGIC_PREFIX[2], TWASM_MAGIC_PREFIX[3], TWASM_VERSION[0], TWASM_VERSION[1], 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; const TWASM_MAGIC_PREFIX: &[u8; 4] = b"TWAS"; -const TWASM_VERSION: &[u8; 2] = b"05"; +const TWASM_VERSION: &[u8; 2] = b"06"; fn validate_magic(wasm: &[u8]) -> Result { if wasm.len() < TWASM_MAGIC.len() || &wasm[..TWASM_MAGIC_PREFIX.len()] != TWASM_MAGIC_PREFIX { @@ -64,7 +64,10 @@ impl Module { #[cfg(test)] mod tests { use super::*; - use crate::{Instruction, ModuleInner, V128Operand, WasmFunction}; + use crate::{ + AbstractHeapType, ConstInstruction, Global, GlobalType, Instruction, ModuleFuncIdx, ModuleInner, RefType, + V128Operand, WasmFunction, WasmType, + }; use crate::{OperandIdx, OperandType}; use alloc::{boxed::Box, sync::Arc, vec}; @@ -94,7 +97,7 @@ mod tests { let module = Module::from(ModuleInner { funcs: Box::new([Arc::new(function)]), ..ModuleInner::default() }); let archive = module.serialize_twasm().expect("serialize archive"); - assert_eq!(&archive[..6], b"TWAS05"); + assert_eq!(&archive[..6], b"TWAS06"); let decoded = Module::try_from_twasm(&archive).expect("deserialize archive"); let function = &decoded.funcs[0]; @@ -106,4 +109,37 @@ mod tests { assert_eq!(index.get(&function.data).value, bytes); } } + + #[test] + fn const_reference_expressions_round_trip_archive() { + let null_type = RefType::new_abstract(true, AbstractHeapType::Extern); + let module = Module::from(ModuleInner { + globals: vec![ + Global { + ty: GlobalType::new(WasmType::Ref(null_type), false), + init: vec![ConstInstruction::RefNull(null_type)].into_boxed_slice(), + }, + Global { + ty: GlobalType::new(WasmType::Ref(RefType::FUNCREF), false), + init: vec![ConstInstruction::RefFunc(ModuleFuncIdx::new(7))].into_boxed_slice(), + }, + Global { + ty: GlobalType::new(WasmType::Ref(RefType::new_abstract(false, AbstractHeapType::I31)), false), + init: vec![ConstInstruction::I32Const(42), ConstInstruction::RefI31].into_boxed_slice(), + }, + ] + .into_boxed_slice(), + ..ModuleInner::default() + }); + + let archive = module.serialize_twasm().expect("serialize archive"); + let decoded = Module::try_from_twasm(&archive).expect("deserialize archive"); + + assert!(matches!(decoded.globals[0].init.as_ref(), [ConstInstruction::RefNull(ty)] if *ty == null_type)); + assert!(matches!( + decoded.globals[1].init.as_ref(), + [ConstInstruction::RefFunc(index)] if index.index() == 7 + )); + assert!(matches!(decoded.globals[2].init.as_ref(), [ConstInstruction::I32Const(42), ConstInstruction::RefI31])); + } } diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index c9786d3..7e0cd28 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -2,7 +2,7 @@ use alloc::boxed::Box; use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TagAddr, TypeAddr, ValueCounts}; use crate::operands::sealed; -use crate::{DataAddr, ElemAddr, MemAddr, Operand64, Operand128, OperandIdx, OperandType, RefType, RefValue}; +use crate::{DataAddr, ElemAddr, MemAddr, ModuleFuncIdx, Operand64, Operand128, OperandIdx, OperandType, RefType}; /// Represents a memory immediate in a WebAssembly memory instruction. #[derive(Copy, Clone, PartialEq, Eq)] @@ -429,7 +429,8 @@ pub enum ConstInstruction { GlobalGet64(GlobalAddr), GlobalGet128(GlobalAddr), GlobalGetRef(GlobalAddr), - Ref(RefValue), + RefNull(RefType), + RefFunc(ModuleFuncIdx), RefI31, AnyConvertExtern, ExternConvertAny, @@ -535,8 +536,6 @@ pub enum BinOp128 { /// These instructions are an internal, version-specific representation and do not /// map one-to-one to WebAssembly instructions. Their variants and serialized form /// may change between TinyWasm releases. -/// -/// See #[rustfmt::skip] #[derive(Clone, Copy, PartialEq)] #[cfg_attr(feature = "debug", derive(Debug))] diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index d1f7453..686433d 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -47,11 +47,12 @@ pub mod archive { impl core::error::Error for TwasmError {} } -/// A `TinyWasm` WebAssembly Module +/// TinyWasm's parsed and lowered representation of a WebAssembly module. /// -/// This is the internal representation of a WebAssembly module in `TinyWasm`. /// Modules produced by the parser are validated by default, but validation can be /// disabled for trusted input. Do not trust modules or archives from third parties. +/// +/// See #[derive(Clone, Default, PartialEq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -326,13 +327,35 @@ pub type TableAddr = Addr; pub type MemAddr = Addr; pub type GlobalAddr = Addr; pub type TagAddr = Addr; -pub type ExnAddr = Addr; pub type ElemAddr = Addr; pub type DataAddr = Addr; pub type ExternAddr = Addr; pub type ConstIdx = Addr; // additional internal addresses +/// A function index in a WebAssembly module's function index space. +/// +/// This remains module-local until instantiation resolves it to a [`FuncAddr`]. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "debug", derive(Debug))] +#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] +#[cfg_attr(feature = "archive", serde(transparent))] +pub struct ModuleFuncIdx(u32); + +impl ModuleFuncIdx { + /// Creates a module-local function index. + #[inline] + pub const fn new(index: u32) -> Self { + Self(index) + } + + /// Returns the module-local function index. + #[inline] + pub const fn index(self) -> u32 { + self.0 + } +} + /// An address in the current type space. /// /// Parsed modules use module-local addresses; instantiated types use their store's canonical addresses. @@ -484,6 +507,9 @@ pub struct Global { pub init: Box<[ConstInstruction]>, } +/// A WebAssembly global type. +/// +/// See #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -517,6 +543,9 @@ impl Default for GlobalType { } } +/// A WebAssembly table type. +/// +/// See #[derive(Copy, Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -556,7 +585,9 @@ impl TableType { } } -/// Represents a memory's type. +/// A WebAssembly memory type. +/// +/// See #[derive(Copy, Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -597,7 +628,7 @@ impl MemoryType { } } - /// The declared maximum page count, or `None` when the memory is unbounded. + /// Returns the declared maximum page count, or `None` if no maximum was declared. #[inline] pub const fn page_count_max_declared(&self) -> Option { self.page_count_max @@ -648,6 +679,8 @@ pub enum MemoryArch { } /// A WebAssembly tag type. +/// +/// See #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] diff --git a/crates/types/src/reference.rs b/crates/types/src/reference.rs index ed59ae5..2d725ca 100644 --- a/crates/types/src/reference.rs +++ b/crates/types/src/reference.rs @@ -1,15 +1,8 @@ -const HOST_REF_TAG: u32 = 1 << 30; - -const fn encode_host_ref(addr: u32) -> Option { - if addr >= HOST_REF_TAG - 1 { - return None; - } - Some((addr | HOST_REF_TAG).wrapping_add(1).wrapping_mul(2)) -} - /// An abstract WebAssembly heap type. /// /// This contains exactly the abstract heap types in core Wasm 3.0. +/// +/// See #[repr(u8)] #[derive(Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "debug", derive(Debug))] @@ -43,6 +36,8 @@ pub enum AbstractHeapType { /// For concrete types, `payload` is a module type index before instantiation /// and a canonical store type address at runtime. /// Otherwise, it is an [`AbstractHeapType`]. +/// +/// See #[derive(Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub struct RefType(u32); @@ -148,156 +143,3 @@ impl RefType { matches!(self.abstract_heap_type(), Some(AbstractHeapType::Exn | AbstractHeapType::NoExn)) } } - -/// A host-facing WebAssembly reference value. -#[derive(Clone, Copy, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] -pub enum RefValue { - Null, - Func(FuncRef), - Extern(ExternRef), - Any(AnyRef), - Exn(ExnRef), -} - -/// A reference to a function in a store. -/// -/// The payload is the function's store-local address. -#[derive(Clone, Copy, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] -pub struct FuncRef(u32); - -impl FuncRef { - #[inline] - pub const fn new(addr: u32) -> Self { - Self(addr) - } - - #[inline] - pub const fn addr(self) -> u32 { - self.0 - } -} - -/// An opaque external reference. -/// -/// Packed as `[payload:31 i31:1]`. Host addresses use the upper payload -/// category, Store-managed objects use the lower category, and odd values -/// contain an externalized i31. -#[derive(Clone, Copy, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] -pub struct ExternRef(u32); - -impl ExternRef { - #[inline] - pub const fn new(addr: u32) -> Self { - let Some(value) = Self::try_new(addr) else { panic!("external reference address is too large") }; - value - } - - /// Creates an external reference when `addr` fits the runtime encoding. - #[inline] - pub const fn try_new(addr: u32) -> Option { - match encode_host_ref(addr) { - Some(encoded) => Some(Self(encoded)), - None => None, - } - } - - #[doc(hidden)] - #[inline] - pub const fn from_raw(raw: u32) -> Self { - Self(raw) - } - - #[doc(hidden)] - #[inline] - pub const fn raw(self) -> u32 { - self.0 - } -} - -/// A reference to an exception in a store. -/// -/// The payload is the exception's store-local address. -#[derive(Clone, Copy, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] -pub struct ExnRef(u32); - -impl ExnRef { - #[inline] - pub const fn new(addr: u32) -> Self { - Self(addr) - } - - #[inline] - pub const fn addr(self) -> u32 { - self.0 - } -} - -/// A WebAssembly `anyref` value. -/// -/// Packed as: -/// -/// ```text -/// [payload:31 i31:1] -/// ``` -/// -/// Odd values contain an inline signed i31. Non-zero even values are reserved -/// for store-managed references, and zero is reserved for null by the runtime. -#[derive(Clone, Copy, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] -pub struct AnyRef(u32); - -impl AnyRef { - /// Creates a host reference when `addr` fits the runtime encoding. - #[inline] - pub const fn from_host(addr: u32) -> Option { - match encode_host_ref(addr) { - Some(encoded) => Some(Self(encoded)), - None => None, - } - } - - #[doc(hidden)] - #[inline] - pub const fn from_raw(raw: u32) -> Self { - Self(raw) - } - - pub const fn from_i31(value: i32) -> Option { - if value < -(1 << 30) || value >= (1 << 30) { - return None; - } - - Some(Self(((value as u32) << 1) | 1)) - } - - pub const fn as_i31(self) -> Option { - if self.0 & 1 == 1 { Some((self.0 as i32) >> 1) } else { None } - } - - #[inline] - pub const fn raw(self) -> u32 { - self.0 - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn host_reference_encoding_is_checked_and_unique() { - assert_ne!(AnyRef::from_host(0), AnyRef::from_host(1)); - assert!(AnyRef::from_host(HOST_REF_TAG - 2).is_some()); - assert!(AnyRef::from_host(HOST_REF_TAG - 1).is_none()); - assert!(ExternRef::try_new(u32::MAX).is_none()); - } -} diff --git a/crates/types/src/types.rs b/crates/types/src/types.rs index 0801849..12386f1 100644 --- a/crates/types/src/types.rs +++ b/crates/types/src/types.rs @@ -3,6 +3,8 @@ use alloc::{boxed::Box, sync::Arc}; use crate::{TypeAddr, WasmType}; /// The dense type index space of a WebAssembly module. +/// +/// See #[derive(Clone, PartialEq, Eq, Default)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -31,6 +33,8 @@ impl TypeSection { } /// A type with optional declared subtyping. +/// +/// See #[derive(Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -58,6 +62,8 @@ impl SubType { } /// A function, struct, or array type. +/// +/// See #[derive(Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -123,6 +129,8 @@ impl FuncType { } /// A WebAssembly struct type. +/// +/// See #[derive(Clone, PartialEq, Eq, Default)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -131,6 +139,8 @@ pub struct StructType { } /// A WebAssembly array type. +/// +/// See #[derive(Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -139,6 +149,8 @@ pub struct ArrayType { } /// A struct field or array element type. +/// +/// See #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -148,6 +160,8 @@ pub struct FieldType { } /// A field's packed or unpacked storage type. +/// +/// See #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -156,3 +170,13 @@ pub enum StorageType { I16, Value(WasmType), } + +impl StorageType { + /// Returns the unpacked WebAssembly value type used on the stack. + pub const fn unpacked(self) -> WasmType { + match self { + Self::I8 | Self::I16 => WasmType::I32, + Self::Value(ty) => ty, + } + } +} diff --git a/crates/types/src/value.rs b/crates/types/src/value.rs index 5049ba2..847e5e1 100644 --- a/crates/types/src/value.rs +++ b/crates/types/src/value.rs @@ -1,307 +1,38 @@ -use core::fmt::Debug; - -use crate::{ConstInstruction, RefType, RefValue}; - -/// A WebAssembly value. -/// -/// See -#[derive(Clone, Copy, PartialEq)] -pub enum WasmValue { - // Num types - /// A 32-bit integer - I32(i32), - /// A 64-bit integer - I64(i64), - /// A 32-bit float - F32(f32), - /// A 64-bit float - F64(f64), - /// A 128-bit vector - V128([u8; 16]), - /// A reference type - Ref(RefValue), -} - -impl WasmValue { - /// Return this value's broad WebAssembly type. - /// - /// A null reference has no intrinsic heap type and returns `None`. - pub const fn ty(self) -> Option { - match self { - Self::I32(_) => Some(WasmType::I32), - Self::I64(_) => Some(WasmType::I64), - Self::F32(_) => Some(WasmType::F32), - Self::F64(_) => Some(WasmType::F64), - Self::V128(_) => Some(WasmType::V128), - Self::Ref(RefValue::Null) => None, - Self::Ref(RefValue::Func(_)) => Some(WasmType::Ref(RefType::FUNCREF)), - Self::Ref(RefValue::Extern(_)) => Some(WasmType::Ref(RefType::EXTERNREF)), - Self::Ref(RefValue::Exn(_)) => Some(WasmType::Ref(RefType::EXNREF)), - Self::Ref(RefValue::Any(_)) => { - Some(WasmType::Ref(RefType::new_abstract(true, crate::AbstractHeapType::Any))) - } - } - } - - #[inline] - pub const fn matches_type(self, ty: WasmType) -> bool { - // Concrete references require a store lookup; this method only classifies their broad heap type. - match (self, ty) { - (Self::I32(_), WasmType::I32) - | (Self::I64(_), WasmType::I64) - | (Self::F32(_), WasmType::F32) - | (Self::F64(_), WasmType::F64) - | (Self::V128(_), WasmType::V128) => true, - (Self::Ref(RefValue::Null), WasmType::Ref(ty)) => ty.is_nullable(), - (Self::Ref(RefValue::Func(_)), WasmType::Ref(ty)) => { - matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Func)) - } - (Self::Ref(RefValue::Extern(_)), WasmType::Ref(ty)) => { - matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Extern)) - } - (Self::Ref(RefValue::Exn(_)), WasmType::Ref(ty)) => { - matches!(ty.abstract_heap_type(), Some(crate::AbstractHeapType::Exn)) - } - (Self::Ref(RefValue::Any(value)), WasmType::Ref(ty)) => matches!( - (value.as_i31(), ty.abstract_heap_type()), - ( - Some(_), - Some(crate::AbstractHeapType::I31 | crate::AbstractHeapType::Eq | crate::AbstractHeapType::Any) - ) | (None, Some(crate::AbstractHeapType::Any)) - ), - _ => false, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{AbstractHeapType, AnyRef, FuncRef, RefType}; - - #[test] - fn concrete_references_require_store_type_information() { - let concrete = WasmType::Ref(RefType::new_concrete(false, 0)); - - assert!(!WasmValue::from(FuncRef::new(0)).matches_type(concrete)); - assert!(!WasmValue::from(AnyRef::from_host(0).unwrap()).matches_type(concrete)); - } - - #[test] - fn i31_only_matches_its_store_independent_supertypes() { - let value = WasmValue::from(AnyRef::from_i31(0).unwrap()); - - for ty in [AbstractHeapType::I31, AbstractHeapType::Eq, AbstractHeapType::Any] { - assert!(value.matches_type(WasmType::Ref(RefType::new_abstract(false, ty)))); - } - assert!(!value.matches_type(WasmType::Ref(RefType::new_abstract(false, AbstractHeapType::Struct)))); - } -} - -impl Debug for WasmValue { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - match self { - Self::I32(i) => write!(f, "i32({i})"), - Self::I64(i) => write!(f, "i64({i})"), - Self::F32(i) => write!(f, "f32({i})"), - Self::F64(i) => write!(f, "f64({i})"), - Self::V128(i) => write!(f, "v128({i:?})"), - #[cfg(feature = "debug")] - Self::Ref(i) => write!(f, "ref({i:?})"), - #[cfg(not(feature = "debug"))] - Self::Ref(_) => write!(f, "ref(...)"), - } - } -} - -impl WasmValue { - #[inline] - /// Get the matching [`ConstInstruction`] for this value. - pub fn const_instr(&self) -> alloc::boxed::Box<[ConstInstruction]> { - alloc::boxed::Box::new([match self { - Self::I32(i) => ConstInstruction::I32Const(*i), - Self::I64(i) => ConstInstruction::I64Const(*i), - Self::F32(i) => ConstInstruction::F32Const(*i), - Self::F64(i) => ConstInstruction::F64Const(*i), - Self::V128(i) => ConstInstruction::V128Const(*i), - Self::Ref(i) => ConstInstruction::Ref(*i), - }]) - } - - #[inline] - /// Get the default value for a given type. - pub const fn default_for(ty: WasmType) -> Option { - match ty { - WasmType::I32 => Some(Self::I32(0)), - WasmType::I64 => Some(Self::I64(0)), - WasmType::F32 => Some(Self::F32(0.0)), - WasmType::F64 => Some(Self::F64(0.0)), - WasmType::V128 => Some(Self::V128([0; 16])), - WasmType::Ref(ty) if ty.is_nullable() => Some(Self::Ref(RefValue::Null)), - WasmType::Ref(_) => None, - } - } - - #[inline] - /// Check if two values are equal, ignoring differences in NaN values. - pub fn eq_loose(&self, other: &Self) -> bool { - match (self, other) { - (Self::I32(a), Self::I32(b)) => a == b, - (Self::I64(a), Self::I64(b)) => a == b, - (Self::V128(a), Self::V128(b)) => a == b || Self::v128_nan_eq(*a, *b), - (Self::Ref(a), Self::Ref(b)) => a == b, - (Self::F32(a), Self::F32(b)) => a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits(), - (Self::F64(a), Self::F64(b)) => a.is_nan() && b.is_nan() || a.to_bits() == b.to_bits(), - _ => false, - } - } - - fn v128_nan_eq(a: [u8; 16], b: [u8; 16]) -> bool { - let a_f32x4: [f32; 4] = [ - f32::from_le_bytes([a[0], a[1], a[2], a[3]]), - f32::from_le_bytes([a[4], a[5], a[6], a[7]]), - f32::from_le_bytes([a[8], a[9], a[10], a[11]]), - f32::from_le_bytes([a[12], a[13], a[14], a[15]]), - ]; - let b_f32x4: [f32; 4] = [ - f32::from_le_bytes([b[0], b[1], b[2], b[3]]), - f32::from_le_bytes([b[4], b[5], b[6], b[7]]), - f32::from_le_bytes([b[8], b[9], b[10], b[11]]), - f32::from_le_bytes([b[12], b[13], b[14], b[15]]), - ]; - - let all_nan_match = a_f32x4.iter().zip(b_f32x4.iter()).all(|(x, y)| { - if x.is_nan() && y.is_nan() { - true - } else if x.is_nan() || y.is_nan() { - false - } else { - x.to_bits() == y.to_bits() - } - }); - - if all_nan_match && a_f32x4.iter().any(|x| x.is_nan()) { - return true; - } - - let a_f64x2: [f64; 2] = [ - f64::from_le_bytes([a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]]), - f64::from_le_bytes([a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]]), - ]; - let b_f64x2: [f64; 2] = [ - f64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]), - f64::from_le_bytes([b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]]), - ]; - - a_f64x2.iter().zip(b_f64x2.iter()).all(|(x, y)| { - if x.is_nan() && y.is_nan() { - true - } else if x.is_nan() || y.is_nan() { - false - } else { - x.to_bits() == y.to_bits() - } - }) && a_f64x2.iter().any(|x| x.is_nan()) - } -} +use crate::{RefType, StorageType}; /// Type of a WebAssembly value. +/// +/// See #[derive(Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub enum WasmType { - /// A 32-bit integer + /// A 32-bit integer. I32, - /// A 64-bit integer + /// A 64-bit integer. I64, - /// A 32-bit float + /// A 32-bit float. F32, - /// A 64-bit float + /// A 64-bit float. F64, - /// A 128-bit vector + /// A 128-bit vector. V128, - /// A reference type + /// A reference type. Ref(RefType), } impl WasmType { #[inline] - pub const fn default_value(&self) -> Option { - WasmValue::default_for(*self) - } - - #[inline] - pub const fn is_simd(&self) -> bool { + pub const fn is_simd(self) -> bool { matches!(self, Self::V128) } } -macro_rules! impl_conversion_for_wasmvalue { - ($($t:ty => $variant:ident, $accessor:ident, $doc:literal);* $(;)?) => { - impl WasmValue { - $( - #[doc = $doc] - pub const fn $accessor(&self) -> Option<$t> { - match self { - Self::$variant(value) => Some(*value), - _ => None, - } - } - )* +impl From for WasmType { + fn from(value: StorageType) -> Self { + match value { + StorageType::I8 | StorageType::I16 => Self::I32, + StorageType::Value(value) => value, } - - $( - impl From<$t> for WasmValue { - #[inline] - fn from(i: $t) -> Self { - Self::$variant(i) - } - } - - impl TryFrom for $t { - type Error = (); - - #[inline] - fn try_from(value: WasmValue) -> Result { - if let WasmValue::$variant(i) = value { Ok(i) } else { Err(()) } - } - } - )* } } - -impl_conversion_for_wasmvalue! { - i32 => I32, as_i32, "Return the `i32` from a `WasmValue`, if it is an `I32`."; - i64 => I64, as_i64, "Return the `i64` from a `WasmValue`, if it is an `I64`."; - f32 => F32, as_f32, "Return the `f32` from a `WasmValue`, if it is a `F32`."; - f64 => F64, as_f64, "Return the `f64` from a `WasmValue`, if it is a `F64`."; - [u8; 16] => V128, as_v128, "Return the raw little-endian bytes from a `WasmValue`, if it is a `V128`."; - RefValue => Ref, as_ref, "Return the `RefValue` from a `WasmValue`, if it is a `Ref`."; -} - -macro_rules! impl_ref_conversion_for_wasmvalue { - ($($ty:ty => $variant:ident);* $(;)?) => { - $( - impl From<$ty> for WasmValue { - fn from(value: $ty) -> Self { - Self::Ref(RefValue::$variant(value)) - } - } - - impl TryFrom for $ty { - type Error = (); - - fn try_from(value: WasmValue) -> Result { - if let WasmValue::Ref(RefValue::$variant(value)) = value { Ok(value) } else { Err(()) } - } - } - )* - }; -} - -impl_ref_conversion_for_wasmvalue! { - crate::FuncRef => Func; - crate::ExternRef => Extern; - crate::AnyRef => Any; - crate::ExnRef => Exn; -} diff --git a/examples/archive.rs b/examples/archive.rs index 3f64704..3f118f2 100644 --- a/examples/archive.rs +++ b/examples/archive.rs @@ -11,13 +11,13 @@ const WASM: &str = r#" "#; fn main() -> Result<()> { - let wasm = wat::parse_str(WASM).expect("Failed to parse WAT"); + let wasm = wat::parse_str(WASM)?; let module = Parser::default().parse_module_bytes(wasm)?; - let twasm = module.serialize_twasm()?; - // Now, you could e.g. write `twasm` to a file called `add.twasm` - // and load it later in a different program. + // Serialize the optimized module for storage or distribution. + let twasm = module.serialize_twasm()?; + // Archived modules load without parsing Wasm again and should only come from trusted sources. let module = Module::try_from_twasm(&twasm)?; let mut store = Store::default(); let instance = ModuleInstance::instantiate(&mut store, &module, None)?; diff --git a/examples/basic.rs b/examples/basic.rs new file mode 100644 index 0000000..1f717c5 --- /dev/null +++ b/examples/basic.rs @@ -0,0 +1,26 @@ +use anyhow::Result; +use tinywasm::{ModuleInstance, Store}; + +const WASM: &str = r#" +(module + (func $add (param $lhs i32) (param $rhs i32) (result i32) + local.get $lhs + local.get $rhs + i32.add) + (export "add" (func $add))) +"#; + +fn main() -> Result<()> { + let wasm = wat::parse_str(WASM)?; + let module = tinywasm::parse_bytes(&wasm)?; + + // Module is reusable, while Store owns the runtime state for this instance. + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + + // Typed handles validate parameters and results. Use func_untyped for dynamic values. + let add = instance.func::<(i32, i32), i32>(&store, "add")?; + + assert_eq!(add.call(&mut store, (1, 2))?, 3); + Ok(()) +} diff --git a/examples/exceptions.rs b/examples/exceptions.rs new file mode 100644 index 0000000..7c2f88e --- /dev/null +++ b/examples/exceptions.rs @@ -0,0 +1,28 @@ +use anyhow::{Result, bail}; +use tinywasm::{Error, ModuleInstance, Store, WasmValue}; + +const WASM: &str = r#" +(module + (tag $failure (export "failure") (param i32)) + (func (export "fail") (param i32) + local.get 0 + throw $failure)) +"#; + +fn main() -> Result<()> { + let wasm = wat::parse_str(WASM)?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let fail = instance.func::(&store, "fail")?; + + // Uncaught guest exceptions cross the host boundary as owned ExnRef handles. + let Err(Error::Exception(exception)) = fail.call(&mut store, 42) else { + bail!("expected a guest exception"); + }; + + // The handle exposes the exception tag and typed payload values. + assert_eq!(exception.tag(&store)?, instance.tag("failure")?); + assert_eq!(exception.fields(&mut store)?, [WasmValue::I32(42)]); + Ok(()) +} diff --git a/examples/funcref_callbacks.rs b/examples/funcref_callbacks.rs deleted file mode 100644 index 959d798..0000000 --- a/examples/funcref_callbacks.rs +++ /dev/null @@ -1,123 +0,0 @@ -use anyhow::Result; -use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store, types::FuncRef}; - -const LHS: i32 = 5; -const RHS: i32 = 3; - -fn main() -> Result<()> { - run_passed_funcref_example()?; - run_returned_funcref_example()?; - Ok(()) -} - -fn run_passed_funcref_example() -> Result<()> { - // Host receives funcref and calls it via an exported proxy. - const WASM: &str = r#" - (module - (import "host" "call_this" (func $host_callback_caller (param funcref))) - (import "host" "mul" (func $host_mul (param $x i32) (param $y i32) (result i32))) - - (func $tell_host_to_call (export "tell_host_to_call") - (call $host_callback_caller (ref.func $add)) - (call $host_callback_caller (ref.func $sub)) - (call $host_callback_caller (ref.func $host_mul)) - ) - - (type $binop (func (param i32 i32) (result i32))) - - (table 3 funcref) - (elem (i32.const 0) $add $sub $host_mul) - (func $add (param $x i32) (param $y i32) (result i32) - local.get $x - local.get $y - i32.add - ) - (func $sub (param $x i32) (param $y i32) (result i32) - local.get $x - local.get $y - i32.sub - ) - - (table $callback_register 1 funcref) - (func (export "call_binop_by_ref") (param funcref i32 i32) (result i32) - (table.set $callback_register (i32.const 0) (local.get 0)) - (call_indirect $callback_register (type $binop) (local.get 1)(local.get 2)(i32.const 0)) - ) - ) - "#; - - let wasm = wat::parse_str(WASM).expect("failed to parse wat"); - let module = tinywasm::parse_bytes(&wasm)?; - let mut store = Store::default(); - - let mul = HostFunction::from(|_, (lhs, rhs): (i32, i32)| -> tinywasm::Result { Ok(lhs * rhs) }); - let call_this = HostFunction::from(|mut ctx: FuncContext<'_>, func_ref: FuncRef| -> tinywasm::Result<()> { - // Host cannot call a funcref directly, so it routes through Wasm. - let call_by_ref = ctx.module().func::<(FuncRef, i32, i32), i32>(ctx.store(), "call_binop_by_ref")?; - let _result = call_by_ref.call(ctx.store_mut(), (func_ref, LHS, RHS))?; - Ok(()) - }); - - let mut imports = Imports::new(); - imports.define("host", "call_this", call_this).define("host", "mul", mul); - - let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; - let caller = instance.func::<(), ()>(&store, "tell_host_to_call")?; - - caller.call(&mut store, ())?; - - Ok(()) -} - -fn run_returned_funcref_example() -> Result<()> { - // Wasm returns funcref values, host executes them through the same proxy. - const WASM: &str = r#" - (module - (import "host" "mul" (func $host_mul (param $x i32) (param $y i32) (result i32))) - (type $binop (func (param i32 i32) (result i32))) - (table 3 funcref) - (elem (i32.const 0) $add $sub $host_mul) - (func $add (param $x i32) (param $y i32) (result i32) - local.get $x - local.get $y - i32.add - ) - (func $sub (param $x i32) (param $y i32) (result i32) - local.get $x - local.get $y - i32.sub - ) - (func $ref_to_funcs (export "what_should_host_call") (result funcref funcref funcref) - (ref.func $add) - (ref.func $sub) - (ref.func $host_mul) - ) - - (table $callback_register 1 funcref) - (func $call (export "call_binop_by_ref") (param funcref i32 i32) (result i32) - (table.set $callback_register (i32.const 0) (local.get 0)) - (call_indirect $callback_register (type $binop) (local.get 1)(local.get 2)(i32.const 0)) - ) - ) - "#; - - let wasm = wat::parse_str(WASM).expect("failed to parse wat"); - let module = tinywasm::parse_bytes(&wasm)?; - let mut store = Store::default(); - let mut imports = Imports::new(); - - let mul = HostFunction::from(|_, (lhs, rhs): (i32, i32)| -> tinywasm::Result { Ok(lhs * rhs) }); - imports.define("host", "mul", mul); - - let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; - let (add_ref, sub_ref, mul_ref) = { - let get_funcrefs = instance.func::<(), (FuncRef, FuncRef, FuncRef)>(&store, "what_should_host_call")?; - get_funcrefs.call(&mut store, ())? - }; - - let call_by_ref = instance.func::<(FuncRef, i32, i32), i32>(&store, "call_binop_by_ref")?; - for func_ref in [add_ref, sub_ref, mul_ref] { - let _result = call_by_ref.call(&mut store, (func_ref, LHS, RHS))?; - } - Ok(()) -} diff --git a/examples/gc.rs b/examples/gc.rs new file mode 100644 index 0000000..9a73d04 --- /dev/null +++ b/examples/gc.rs @@ -0,0 +1,33 @@ +use anyhow::Result; +use tinywasm::{ModuleInstance, Store, StructRef, WasmValue}; + +const WASM: &str = r#" +(module + (type $cube (struct (field (mut i32)) (field (mut i32)))) + (func $make-cube (result (ref $cube)) + i32.const 3 + i32.const 4 + struct.new $cube) + (func (export "cube") (result (ref struct)) + call $make-cube)) +"#; + +fn main() -> Result<()> { + let wasm = wat::parse_str(WASM)?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let cube = instance.func::<(), StructRef>(&store, "cube")?.call(&mut store, ())?; + + // GC handles are Store-bound and expose typed field access through that Store. + assert_eq!(cube.fields(&mut store)?, [WasmValue::I32(3), WasmValue::I32(4)]); + cube.set_field(&mut store, 0, WasmValue::I32(5))?; + + // Cloned handles keep their guest objects live across explicit collection. + let retained = cube.clone(); + drop(cube); + store.gc()?; + + assert_eq!(retained.field(&mut store, 0)?, WasmValue::I32(5)); // still alive + Ok(()) +} diff --git a/examples/linking.rs b/examples/linking.rs index 2df7133..92c0b7d 100644 --- a/examples/linking.rs +++ b/examples/linking.rs @@ -1,7 +1,6 @@ use anyhow::Result; use tinywasm::{ModuleInstance, Store}; -// WebAssembly module defining and exporting an `add` function. const WASM_ADD: &str = r#" (module (func $add (param $lhs i32) (param $rhs i32) (result i32) @@ -11,7 +10,6 @@ const WASM_ADD: &str = r#" (export "add" (func $add))) "#; -// WebAssembly module importing an `add` function and using it. const WASM_IMPORT: &str = r#" (module (import "adder" "add" (func $add (param i32 i32) (result i32))) @@ -24,25 +22,23 @@ const WASM_IMPORT: &str = r#" "#; fn main() -> Result<()> { - let wasm_add = wat::parse_str(WASM_ADD).expect("failed to parse wat"); - let wasm_import = wat::parse_str(WASM_IMPORT).expect("failed to parse wat"); + let wasm_add = wat::parse_str(WASM_ADD)?; + let wasm_import = wat::parse_str(WASM_IMPORT)?; let add_module = tinywasm::parse_bytes(&wasm_add)?; let import_module = tinywasm::parse_bytes(&wasm_import)?; let mut store = Store::default(); - // Instantiate the `add` module. let add_instance = ModuleInstance::instantiate(&mut store, &add_module, None)?; - // Link the `adder` namespace to the `add` module's instance. + // Imports can link a module namespace and define individual host items together. let mut imports = tinywasm::Imports::new(); imports.link_module("adder", add_instance)?; - // Instantiate the `import` module with the linked imports. let import_instance = ModuleInstance::instantiate(&mut store, &import_module, Some(&imports))?; - // Call the `main` function, which uses the imported `add` function. + // Calling `main` crosses the linked module boundary to `add`. let main = import_instance.func::<(), i32>(&store, "main")?; assert_eq!(main.call(&mut store, ())?, 3); diff --git a/examples/reentrance.rs b/examples/reentrance.rs index 0084a61..cf57891 100644 --- a/examples/reentrance.rs +++ b/examples/reentrance.rs @@ -23,10 +23,11 @@ fn main() -> Result<()> { let mut store = Store::default(); let call_add_twice = HostFunction::from(|mut ctx: FuncContext<'_>, value: i32| { + // FuncContext exposes the active module and its Store to the callback. let add_one = ctx.module().func::(ctx.store(), "add_one")?; - // Use ctx.call for reentrant calls from host functions. Function::call - // starts a root invocation and cannot preserve the active call stacks. + // Use ctx.call while a host callback has an active Wasm invocation. + // Function::call only starts top-level invocations. let value = ctx.call(&add_one, value)?; ctx.call(&add_one, value) }); diff --git a/examples/references.rs b/examples/references.rs new file mode 100644 index 0000000..b02dd07 --- /dev/null +++ b/examples/references.rs @@ -0,0 +1,34 @@ +use anyhow::Result; +use tinywasm::{FuncRef, HostFunction, Imports, ModuleInstance, Store}; + +const WASM: &str = r#" +(module + (type $callback (func (param i32) (result i32))) + (import "host" "double" (func $double (type $callback))) + (elem declare func $double) + (func (export "callback") (result funcref) + ref.func $double) + (func (export "apply") (param funcref i32) (result i32) + local.get 1 + local.get 0 + ref.cast (ref $callback) + call_ref $callback)) +"#; + +fn main() -> Result<()> { + let mut store = Store::default(); + let mut imports = Imports::new(); + // Imports resolve reusable host definitions against each module's runtime types. + // HostFunction::instantiate is available when a standalone Function is needed. + imports.define("host", "double", HostFunction::from(|_, value: i32| -> tinywasm::Result { Ok(value * 2) })); + + let wasm = wat::parse_str(WASM)?; + let module = tinywasm::parse_bytes(&wasm)?; + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + // Option maps nullable funcref. Bare FuncRef maps a non-null reference. + let callback = instance.func::<(), Option>(&store, "callback")?.call(&mut store, ())?; + let apply = instance.func::<(Option, i32), i32>(&store, "apply")?; + + assert_eq!(apply.call(&mut store, (callback, 21))?, 42); + Ok(()) +} diff --git a/examples/resumable.rs b/examples/resumable.rs index 26b5f47..70b0db1 100644 --- a/examples/resumable.rs +++ b/examples/resumable.rs @@ -29,10 +29,12 @@ fn main() -> Result<()> { let instance = ModuleInstance::instantiate(&mut store, &module, None)?; let count_down = instance.func::(&store, "count_down")?; + // A resumable call returns execution state instead of running to completion. let mut execution = count_down.call_resumable(&mut store, 10_000)?; let fuel_per_round = 128; let mut fuel_rounds = 0; + // Each resume call limits one round. std builds also support wall-clock budgets. let result = loop { fuel_rounds += 1; match execution.resume_with_fuel(fuel_per_round)? { diff --git a/examples/rust.rs b/examples/rust.rs new file mode 100644 index 0000000..24b3b73 --- /dev/null +++ b/examples/rust.rs @@ -0,0 +1,226 @@ +use std::hint::black_box; + +use anyhow::{Result, anyhow}; +use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store}; + +/// Examples of using WebAssembly compiled from Rust with tinywasm. +/// +/// These examples are meant to be run with `cargo run --example rust `. +/// For example, `cargo run --example rust hello`. +/// +/// To run these, you first need to compile the Rust examples to WebAssembly: +/// +/// ```sh +/// ./examples/rust/build.sh +/// ``` +/// +/// This requires the `wasm32-unknown-unknown` target, `binaryen`, and `wabt` to be installed: +/// +/// `rustup target add wasm32-unknown-unknown`. +/// +/// +fn main() -> Result<()> { + pretty_env_logger::init(); + + if !std::path::Path::new("./examples/rust/out/").exists() { + return Err(anyhow!("No WebAssembly files found. See examples/rust.rs for instructions.")); + } + + let args = std::env::args().collect::>(); + if args.len() < 2 { + println!("Usage: cargo run --example rust "); + println!("Available examples:"); + println!(" hello"); + println!(" printi32"); + println!(" host_fn"); + println!(" fibonacci - calculate fibonacci(30)"); + println!(" tinywasm - run printi32 inside of tinywasm inside of itself"); + println!(" tinywasm_no_std - run a precompiled module inside of no_std tinywasm"); + println!(" argon2id - run argon2id(1000, 2, 1)"); + return Ok(()); + } + + match args[1].as_str() { + "hello" => hello()?, + "printi32" => printi32()?, + "fibonacci" => fibonacci()?, + "tinywasm" => tinywasm()?, + "tinywasm_no_std" => tinywasm_no_std()?, + "argon2id" => argon2id()?, + "host_fn" => host_fn()?, + "all" => { + println!("Running all examples"); + println!("\nhello.wasm:"); + hello()?; + println!("\nprinti32.wasm:"); + printi32()?; + println!("\nfibonacci.wasm:"); + fibonacci()?; + println!("\ntinywasm.wasm:"); + tinywasm()?; + println!("\ntinywasm_no_std.wasm:"); + tinywasm_no_std()?; + println!("argon2id.wasm:"); + argon2id()?; + println!("\nhost_fn.wasm:"); + host_fn()?; + } + _ => {} + } + + Ok(()) +} + +fn tinywasm() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/tinywasm.opt.wasm")?; + let mut store = Store::default(); + + let mut imports = Imports::new(); + imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _x: i32| Ok(()))); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(black_box(&imports)))?; + + let hello = instance.func::<(), ()>(&store, "hello")?; + hello.call(&mut store, black_box(()))?; + hello.call(&mut store, black_box(()))?; + hello.call(&mut store, black_box(()))?; + Ok(()) +} + +fn tinywasm_no_std() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/tinywasm_no_std.wasm")?; + let mut store = Store::default(); + + let mut imports = Imports::new(); + imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _x: i32| Ok(()))); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(black_box(&imports)))?; + + let hello = instance.func::<(), ()>(&store, "hello")?; + hello.call(&mut store, black_box(()))?; + hello.call(&mut store, black_box(()))?; + hello.call(&mut store, black_box(()))?; + Ok(()) +} + +fn hello() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/hello.opt.wasm")?; + let mut store = Store::default(); + + // The host callback reads the guest's exported memory through FuncContext. + let print_utf8 = HostFunction::from(|ctx: FuncContext<'_>, (ptr, len): (i64, i32)| { + let mem = ctx.memory("memory")?; + let string = mem.read_string(ctx.store(), ptr as usize, len as usize)?; + println!("{string}"); + Ok(()) + }); + + let mut imports = Imports::new(); + imports.define("env", "print_utf8", print_utf8); + + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + let arg_ptr = instance.func::<(), i32>(&store, "arg_ptr")?.call(&mut store, ())?; + let arg = b"world"; + + // Write the host argument into guest memory before calling the Rust export. + instance.memory("memory")?.copy_from_slice(&mut store, arg_ptr as usize, arg)?; + let hello = instance.func::(&store, "hello")?; + hello.call(&mut store, arg.len() as i32)?; + + Ok(()) +} + +fn host_fn() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/host_fn.opt.wasm")?; + let mut store = Store::default(); + + let bar = HostFunction::from(|_: FuncContext<'_>, (left, right): (i64, i32)| { + assert_eq!(left, 1); + assert_eq!(right, 2); + Ok(left as i32 + right) + }); + + let mut imports = Imports::new(); + imports.define("env", "bar", bar); + + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + let host_fn = instance.func::<(), i32>(&store, "foo")?; + assert_eq!(host_fn.call(&mut store, ())?, 3); + Ok(()) +} + +fn printi32() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/print.opt.wasm")?; + let mut store = Store::default(); + + let printi32 = HostFunction::from(|_: FuncContext<'_>, x: i32| { + println!("{x}"); + Ok(()) + }); + + let mut imports = Imports::new(); + imports.define("env", "printi32", printi32); + + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; + let add_and_print = instance.func::<(i32, i32), ()>(&store, "add_and_print")?; + add_and_print.call(&mut store, (1, 2))?; + + Ok(()) +} + +fn fibonacci() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/fibonacci.opt.wasm")?; + let mut store = Store::default(); + + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let fibonacci = instance.func::(&store, "fibonacci_recursive")?; + let n = 26; + let result = fibonacci.call(&mut store, n)?; + println!("fibonacci({n}) = {result}"); + + Ok(()) +} + +fn argon2id() -> Result<()> { + let module = tinywasm::parse_file("./examples/rust/out/argon2id.opt.wasm")?; + let mut store = Store::default(); + + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let argon2id = instance.func::<(i32, i32, i32), i32>(&store, "argon2id")?; + argon2id.call(&mut store, (1000, 2, 1))?; + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_hello() { + hello().unwrap(); + } + + #[test] + fn test_printi32() { + printi32().unwrap(); + } + + #[test] + fn test_fibonacci() { + fibonacci().unwrap(); + } + + #[test] + fn test_tinywasm() { + tinywasm().unwrap(); + } + + #[test] + fn test_tinywasm_no_std() { + tinywasm_no_std().unwrap(); + } + + #[test] + fn test_argon2id() { + argon2id().unwrap(); + } +} diff --git a/examples/rust/README.md b/examples/rust/README.md index 8d3178a..305a29c 100644 --- a/examples/rust/README.md +++ b/examples/rust/README.md @@ -1,9 +1,9 @@ # WebAssembly Rust Examples This is a separate crate that generates WebAssembly from Rust code. -It is used by the `wasm-rust` example. +It is used by the `rust` example. Requires the `wasm32-unknown-unknown` target to be installed. -To build the example artifacts used by `cargo run --example wasm-rust -- `, run `./examples/rust/build.sh`. +To build the example artifacts used by `cargo run --example rust -- `, run `./examples/rust/build.sh`. That script also requires `binaryen` and `wabt` to be installed. diff --git a/examples/simple.rs b/examples/simple.rs deleted file mode 100644 index 0d57265..0000000 --- a/examples/simple.rs +++ /dev/null @@ -1,22 +0,0 @@ -use anyhow::Result; -use tinywasm::{ModuleInstance, Store}; - -const WASM: &str = r#" -(module - (func $add (param $lhs i32) (param $rhs i32) (result i32) - local.get $lhs - local.get $rhs - i32.add) - (export "add" (func $add))) -"#; - -fn main() -> Result<()> { - let wasm = wat::parse_str(WASM).expect("failed to parse wat"); - let module = tinywasm::parse_bytes(&wasm)?; - let mut store = Store::default(); - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - let add = instance.func::<(i32, i32), i32>(&store, "add")?; - - assert_eq!(add.call(&mut store, (1, 2))?, 3); - Ok(()) -} diff --git a/examples/simple2.rs b/examples/simple2.rs deleted file mode 100644 index f673dfe..0000000 --- a/examples/simple2.rs +++ /dev/null @@ -1,21 +0,0 @@ -use anyhow::Result; -use tinywasm::{ModuleInstance, Store}; - -const WASM: &str = r#" -(module - (func $return (param $lhs i32) (param $rhs i64) (result i32 i64) - local.get $lhs - local.get $rhs) - (export "return" (func $return))) -"#; - -fn main() -> Result<()> { - let wasm = wat::parse_str(WASM).expect("failed to parse wat"); - let module = tinywasm::parse_bytes(&wasm)?; - let mut store = Store::default(); - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - let add = instance.func::<(i32, i64), (i32, i64)>(&store, "return")?; - - assert_eq!(add.call(&mut store, (1, 2))?, (1, 2)); - Ok(()) -} diff --git a/examples/wasm-rust.rs b/examples/wasm-rust.rs deleted file mode 100644 index 0cfb0ce..0000000 --- a/examples/wasm-rust.rs +++ /dev/null @@ -1,224 +0,0 @@ -use std::hint::black_box; - -use anyhow::{Result, anyhow}; -use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store}; - -/// Examples of using WebAssembly compiled from Rust with tinywasm. -/// -/// These examples are meant to be run with `cargo run --example wasm-rust `. -/// For example, `cargo run --example wasm-rust hello`. -/// -/// To run these, you first need to compile the Rust examples to WebAssembly: -/// -/// ```sh -/// ./examples/rust/build.sh -/// ``` -/// -/// This requires the `wasm32-unknown-unknown` target, `binaryen`, and `wabt` to be installed: -/// -/// `rustup target add wasm32-unknown-unknown`. -/// -/// -fn main() -> Result<()> { - pretty_env_logger::init(); - - if !std::path::Path::new("./examples/rust/out/").exists() { - return Err(anyhow!("No WebAssembly files found. See examples/wasm-rust.rs for instructions.")); - } - - let args = std::env::args().collect::>(); - if args.len() < 2 { - println!("Usage: cargo run --example wasm-rust "); - println!("Available examples:"); - println!(" hello"); - println!(" printi32"); - println!(" host_fn"); - println!(" fibonacci - calculate fibonacci(30)"); - println!(" tinywasm - run printi32 inside of tinywasm inside of itself"); - println!(" tinywasm_no_std - run a precompiled module inside of no_std tinywasm"); - println!(" argon2id - run argon2id(1000, 2, 1)"); - return Ok(()); - } - - match args[1].as_str() { - "hello" => hello()?, - "printi32" => printi32()?, - "fibonacci" => fibonacci()?, - "tinywasm" => tinywasm()?, - "tinywasm_no_std" => tinywasm_no_std()?, - "argon2id" => argon2id()?, - "host_fn" => host_fn()?, - "all" => { - println!("Running all examples"); - println!("\nhello.wasm:"); - hello()?; - println!("\nprinti32.wasm:"); - printi32()?; - println!("\nfibonacci.wasm:"); - fibonacci()?; - println!("\ntinywasm.wasm:"); - tinywasm()?; - println!("\ntinywasm_no_std.wasm:"); - tinywasm_no_std()?; - println!("argon2id.wasm:"); - argon2id()?; - println!("\nhost_fn.wasm:"); - host_fn()?; - } - _ => {} - } - - Ok(()) -} - -fn tinywasm() -> Result<()> { - let module = tinywasm::parse_file("./examples/rust/out/tinywasm.opt.wasm")?; - let mut store = Store::default(); - - let mut imports = Imports::new(); - imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _x: i32| Ok(()))); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(black_box(&imports)))?; - - let hello = instance.func::<(), ()>(&store, "hello")?; - hello.call(&mut store, black_box(()))?; - hello.call(&mut store, black_box(()))?; - hello.call(&mut store, black_box(()))?; - Ok(()) -} - -fn tinywasm_no_std() -> Result<()> { - let module = tinywasm::parse_file("./examples/rust/out/tinywasm_no_std.wasm")?; - let mut store = Store::default(); - - let mut imports = Imports::new(); - imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _x: i32| Ok(()))); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(black_box(&imports)))?; - - let hello = instance.func::<(), ()>(&store, "hello")?; - hello.call(&mut store, black_box(()))?; - hello.call(&mut store, black_box(()))?; - hello.call(&mut store, black_box(()))?; - Ok(()) -} - -fn hello() -> Result<()> { - let module = tinywasm::parse_file("./examples/rust/out/hello.opt.wasm")?; - let mut store = Store::default(); - - let print_utf8 = HostFunction::from(|ctx: FuncContext<'_>, (ptr, len): (i64, i32)| { - let mem = ctx.memory("memory")?; - let string = mem.read_string(ctx.store(), ptr as usize, len as usize)?; - println!("{string}"); - Ok(()) - }); - - let mut imports = Imports::new(); - imports.define("env", "print_utf8", print_utf8); - - let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; - let arg_ptr = instance.func::<(), i32>(&store, "arg_ptr")?.call(&mut store, ())?; - let arg = b"world"; - - instance.memory("memory")?.copy_from_slice(&mut store, arg_ptr as usize, arg)?; - let hello = instance.func::(&store, "hello")?; - hello.call(&mut store, arg.len() as i32)?; - - Ok(()) -} - -fn host_fn() -> Result<()> { - let module = tinywasm::parse_file("./examples/rust/out/host_fn.opt.wasm")?; - let mut store = Store::default(); - - let bar = HostFunction::from(|_: FuncContext<'_>, (left, right): (i64, i32)| { - assert_eq!(left, 1); - assert_eq!(right, 2); - Ok(left as i32 + right) - }); - - let mut imports = Imports::new(); - imports.define("env", "bar", bar); - - let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; - let host_fn = instance.func::<(), i32>(&store, "foo")?; - assert_eq!(host_fn.call(&mut store, ())?, 3); - Ok(()) -} - -fn printi32() -> Result<()> { - let module = tinywasm::parse_file("./examples/rust/out/print.opt.wasm")?; - let mut store = Store::default(); - - let printi32 = HostFunction::from(|_: FuncContext<'_>, x: i32| { - println!("{x}"); - Ok(()) - }); - - let mut imports = Imports::new(); - imports.define("env", "printi32", printi32); - - let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; - let add_and_print = instance.func::<(i32, i32), ()>(&store, "add_and_print")?; - add_and_print.call(&mut store, (1, 2))?; - - Ok(()) -} - -fn fibonacci() -> Result<()> { - let module = tinywasm::parse_file("./examples/rust/out/fibonacci.opt.wasm")?; - let mut store = Store::default(); - - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - let fibonacci = instance.func::(&store, "fibonacci_recursive")?; - let n = 26; - let result = fibonacci.call(&mut store, n)?; - println!("fibonacci({n}) = {result}"); - - Ok(()) -} - -fn argon2id() -> Result<()> { - let module = tinywasm::parse_file("./examples/rust/out/argon2id.opt.wasm")?; - let mut store = Store::default(); - - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - let argon2id = instance.func::<(i32, i32, i32), i32>(&store, "argon2id")?; - argon2id.call(&mut store, (1000, 2, 1))?; - - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_hello() { - hello().unwrap(); - } - - #[test] - fn test_printi32() { - printi32().unwrap(); - } - - #[test] - fn test_fibonacci() { - fibonacci().unwrap(); - } - - #[test] - fn test_tinywasm() { - tinywasm().unwrap(); - } - - #[test] - fn test_tinywasm_no_std() { - tinywasm_no_std().unwrap(); - } - - #[test] - fn test_argon2id() { - argon2id().unwrap(); - } -} -- cgit v1.3.1 From a8f42e481e9cc56834c39f073236c25cb533efc6 Mon Sep 17 00:00:00 2001 From: Henry Date: Tue, 25 Aug 2026 18:11:35 +0200 Subject: chore: share passive data segments across instances Signed-off-by: Henry --- crates/parser/src/conversion.rs | 2 +- crates/tinywasm/src/store/data.rs | 4 ++-- crates/tinywasm/src/store/mod.rs | 2 +- crates/types/src/lib.rs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) (limited to 'crates/parser/src/conversion.rs') diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 6857a19..225b6ae 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -55,7 +55,7 @@ pub(crate) fn convert_module_data( global_types: &[WasmType], ) -> Result { Ok(tinywasm_types::Data { - data: data.data.to_vec().into_boxed_slice(), + data: data.data.into(), range: data.range, kind: match data.kind { wasmparser::DataKind::Active { memory_index, offset_expr } => { diff --git a/crates/tinywasm/src/store/data.rs b/crates/tinywasm/src/store/data.rs index f9d5f5d..75c57ca 100644 --- a/crates/tinywasm/src/store/data.rs +++ b/crates/tinywasm/src/store/data.rs @@ -1,11 +1,11 @@ -use alloc::vec::Vec; +use tinywasm_types::Shared; /// A WebAssembly Data Instance /// /// See #[cfg_attr(feature = "debug", derive(Debug))] pub(crate) struct DataInstance { - pub(crate) data: Option>, + pub(crate) data: Option>, } impl DataInstance { diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 57c7575..93e62a5 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -747,7 +747,7 @@ impl Store { } } } - tinywasm_types::DataKind::Passive => Some(data.data.to_vec()), + tinywasm_types::DataKind::Passive => Some(data.data.clone()), }; self.state.data.push(DataInstance { data: data_val }); diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index 9f363d3..f9f85fa 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -750,7 +750,7 @@ impl From<&ImportKind> for ExternalKind { #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub struct Data { - pub data: Box<[u8]>, + pub data: Shared<[u8]>, pub range: Range, pub kind: DataKind, } -- cgit v1.3.1 From 843e0ff5601479239791f452bec9865df779839b Mon Sep 17 00:00:00 2001 From: Henry Date: Thu, 27 Aug 2026 16:06:57 +0200 Subject: chore: simplify operands, extract more exec_ methods Signed-off-by: Henry --- benches/fibonacci.rs | 2 +- crates/parser/src/conversion.rs | 22 +- crates/parser/src/lib.rs | 4 +- crates/parser/src/macros.rs | 17 +- crates/parser/src/module.rs | 24 +- crates/parser/src/optimize/rewrite.rs | 284 ++-- crates/parser/src/optimize/targets.rs | 193 +-- crates/parser/src/visit.rs | 198 +-- crates/tinywasm/src/func/context.rs | 10 +- crates/tinywasm/src/func/host.rs | 10 +- crates/tinywasm/src/instance.rs | 24 +- crates/tinywasm/src/interpreter/executor.rs | 1385 ++++++++++++-------- crates/tinywasm/src/interpreter/num_helpers.rs | 23 +- crates/tinywasm/src/interpreter/simd/macros.rs | 21 +- .../tinywasm/src/interpreter/stack/value_stack.rs | 8 +- crates/tinywasm/src/interpreter/values.rs | 134 +- crates/tinywasm/src/macros.rs | 18 + crates/tinywasm/src/store/global.rs | 6 +- crates/tinywasm/src/store/mod.rs | 7 +- crates/tinywasm/src/store/state.rs | 4 +- crates/types/src/archive.rs | 12 +- crates/types/src/instructions.rs | 576 ++++---- crates/types/src/lib.rs | 3 + crates/types/src/operands.rs | 386 ++++-- crates/types/src/reference.rs | 3 +- examples/rust/build.sh | 4 + examples/rust/src/print.twasm | Bin 154 -> 155 bytes 27 files changed, 1942 insertions(+), 1436 deletions(-) (limited to 'crates/parser/src/conversion.rs') diff --git a/benches/fibonacci.rs b/benches/fibonacci.rs index 51fd2d3..699dc79 100644 --- a/benches/fibonacci.rs +++ b/benches/fibonacci.rs @@ -44,7 +44,7 @@ fn criterion_benchmark(c: &mut Criterion) { group.bench_function("fibonacci_from_twasm", |b| b.iter(|| fibonacci_from_twasm(&twasm))); group.measurement_time(std::time::Duration::from_secs(10)); - group.bench_function("fibonacci_iterative_60", |b| b.iter(|| fibonacci_run(module.clone(), false, 60))); + group.bench_function("fibonacci_iterative_100", |b| b.iter(|| fibonacci_run(module.clone(), false, 100))); group.bench_function("fibonacci_recursive_26", |b| b.iter(|| fibonacci_run(module.clone(), true, 26))); } diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 225b6ae..4cf0d02 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -186,9 +186,9 @@ pub(crate) fn convert_module_code( } #[cfg(feature = "validate")] - let (body, data, validator_allocs, reader_allocs) = match validator { + let (body, data, uses_local_memory, validator_allocs, reader_allocs) = match validator { Some(validator) => { - let (body, data, validator_allocs, reader_allocs) = process_operators_and_validate( + let (body, data, uses_local_memory, validator_allocs, reader_allocs) = process_operators_and_validate( validator, func, (local_types, local_addr_map), @@ -197,10 +197,10 @@ pub(crate) fn convert_module_code( reader_allocs, options.deduplicate_operands(), )?; - (body, data, Some(validator_allocs), reader_allocs) + (body, data, uses_local_memory, Some(validator_allocs), reader_allocs) } None => { - let (body, data, reader_allocs) = process_operators( + let (body, data, uses_local_memory, reader_allocs) = process_operators( func, (local_types, local_addr_map), metadata, @@ -208,13 +208,13 @@ pub(crate) fn convert_module_code( reader_allocs, options.deduplicate_operands(), )?; - (body, data, None, reader_allocs) + (body, data, uses_local_memory, None, reader_allocs) } }; #[cfg(not(feature = "validate"))] - let (body, data, validator_allocs, reader_allocs) = { + let (body, data, uses_local_memory, validator_allocs, reader_allocs) = { let _ = validator; - let (body, data, reader_allocs) = process_operators( + let (body, data, uses_local_memory, reader_allocs) = process_operators( func, (local_types, local_addr_map), metadata, @@ -222,9 +222,13 @@ pub(crate) fn convert_module_code( reader_allocs, options.deduplicate_operands(), )?; - (body, data, None, reader_allocs) + (body, data, uses_local_memory, None, reader_allocs) }; - Ok((FunctionCode { instructions: body, data, locals: local_counts }, validator_allocs, reader_allocs)) + Ok(( + FunctionCode { instructions: body, data, locals: local_counts, uses_local_memory }, + validator_allocs, + reader_allocs, + )) } pub(crate) fn convert_rec_group(ty: wasmparser::RecGroup, group_start: u32, types: &mut Vec) -> Result { diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs index 3369f7b..4954056 100644 --- a/crates/parser/src/lib.rs +++ b/crates/parser/src/lib.rs @@ -61,11 +61,11 @@ pub struct ParserOptions { /// Disable this only for trusted input. Parsing without validation may produce /// a module that violates runtime assumptions. pub validation: bool, + /// Whether to run the peephole rewrite optimizer. pub optimize_rewrite: bool, + /// Whether to deduplicate immutable function operands while parsing. - /// - /// This uses more parse CPU to reduce precompiled module and archive size. pub deduplicate_operands: bool, #[cfg(parallel_parser)] diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs index 5e675e6..f807c0f 100644 --- a/crates/parser/src/macros.rs +++ b/crates/parser/src/macros.rs @@ -72,7 +72,10 @@ pub(crate) mod visit { ) => { fn $visit(&mut self, memarg: wasmparser::MemArg $(, $lane: $ty)?) -> Self::Output { let address = self.metadata.memory_size(memarg.memory)?; - let memory_arg_idx = self.push_operand(MemoryArg::new(memarg.offset, memarg.memory))?; + self.mark_memory(memarg.memory); + let memory_arg_idx = self.push_operand128(tinywasm_types::Operand128::< + tinywasm_types::MemoryOperand, + >::new(memarg.offset, memarg.memory))?; lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*] lowering_ops!(@memory_instruction $instr memory_arg_idx $(, $lane)?)) } @@ -87,7 +90,17 @@ pub(crate) mod visit { lowering_ops!(@resolved global_size $inputs => $outputs $($operator)*); }; (@memory_index $inputs:tt => $outputs:tt $($operator:tt)*) => { - lowering_ops!(@resolved memory_size $inputs => $outputs $($operator)*); + lowering_ops!(@memory_index_impl $inputs => $outputs $($operator)*); + }; + (@memory_index_impl [$($input:ident),*] => [$($output:ident),*] + $visit:ident($index:ident: $ty:ty) => $instr:ident + ) => { + fn $visit(&mut self, $index: $ty) -> Self::Output { + let address = self.metadata.memory_size($index)?; + self.mark_memory($index); + lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*] + Instruction::$instr($index).into()) + } }; (@table $inputs:tt => $outputs:tt $($operator:tt)*) => { lowering_ops!(@resolved table_size $inputs => $outputs $($operator)*); diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index bfb28ce..4cd4406 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -13,12 +13,14 @@ pub(crate) struct FunctionCode { pub instructions: Vec, pub data: crate::visit::FunctionDataBuilder, pub locals: ValueCounts, + pub uses_local_memory: bool, } pub(crate) struct OptimizedFunctionCode { pub instructions: Vec, pub data: WasmFunctionData, pub locals: ValueCounts, + pub uses_local_memory: bool, } pub(crate) fn optimize_function_code( @@ -30,7 +32,12 @@ pub(crate) fn optimize_function_code( let optimized = optimize::optimize_instructions(code.instructions, &mut code.data, options, function_results, self_func_addr)?; let data = code.data.finish(); - Ok(OptimizedFunctionCode { instructions: optimized.instructions, data, locals: code.locals }) + Ok(OptimizedFunctionCode { + instructions: optimized.instructions, + data, + locals: code.locals, + uses_local_memory: code.uses_local_memory, + }) } #[derive(Default)] @@ -535,6 +542,20 @@ impl<'a> ModuleReader<'a> { .chain(self.code_type_addrs.iter().copied()) .collect(); + let imported_memory_count = + self.imports.iter().filter(|import| matches!(import.kind, ImportKind::Memory(_))).count(); + let uses_local_memory = self.code.iter().any(|code| code.uses_local_memory); + let exports_local_memory = self + .exports + .iter() + .any(|export| export.kind == ExternalKind::Memory && export.index as usize >= imported_memory_count); + let initializes_local_memory = self + .data + .iter() + .any(|data| matches!(data.kind, DataKind::Active { mem, .. } if mem as usize >= imported_memory_count)); + let skip_local_memory_allocation = + !self.memory_types.is_empty() && !uses_local_memory && !exports_local_memory && !initializes_local_memory; + let funcs = self .code .into_iter() @@ -567,6 +588,7 @@ impl<'a> ModuleReader<'a> { exports: self.exports, elements: self.elements, memory_types: self.memory_types, + skip_local_memory_allocation, tags: self.tags, } .into()) diff --git a/crates/parser/src/optimize/rewrite.rs b/crates/parser/src/optimize/rewrite.rs index 1146da7..d0dfb66 100644 --- a/crates/parser/src/optimize/rewrite.rs +++ b/crates/parser/src/optimize/rewrite.rs @@ -5,11 +5,9 @@ use crate::{ParserOptions, Result}; use alloc::vec::Vec; use core::ops::{Deref, DerefMut}; use tinywasm_types::{ - BinOp, BinOp128, CmpOp, CompactMemoryArg, GlobalConst32, GlobalConst64, GlobalUpdate, GlobalV128, I32LocalArg, - I64Operand, Instruction, LocalConst64, LocalConstCmp, LocalConstSet32, LocalConstSet64, LocalConstSetV128, - LocalLocalCmp, LocalTripleArg, LocalU32, LocalUpdate, LocalUpdateCmp, LocalV128, MemoryArg, MemoryFillConstOp, - MemoryLocalArg, OperandIdx, PackedOp, StackConst32, StackConst64, TargetLocal, TargetLocalArg, V128Operand, - ValueCounts, + BinOp, BinOp128, CmpOp, CompactMemoryArg, CompactMemoryOperand, GlobalUpdateOperand, I32LocalArg, Instruction, + LocalTripleArg, LocalUpdateCmpOperand, LocalUpdateOperand, MemoryFillOperand, MemoryLocalArg, MemoryOperand, + Operand64, Operand64Idx, Operand128, Operand128Idx, PackedOp, TargetLocalArg, ValueCounts, }; pub(crate) struct OptimizeResult { @@ -21,18 +19,6 @@ struct CompactOutput { block_start: usize, } -macro_rules! operand { - ($data:expr, $value:expr) => { - $data.push_operand($value) - }; -} - -macro_rules! target_operand { - ($data:expr, $value:expr) => { - $data.push_target_operand($value) - }; -} - impl Deref for CompactOutput { type Target = Vec; @@ -229,7 +215,7 @@ fn rewrite( } } MemoryFill(memory) => rewrite!(output, read, [Const32(value), Const32(size)] => { - let index = operand!(data, MemoryFillConstOp { memory, byte: value as u8, value: size })?; + let index = data.push_operand128(Operand128::::new(memory, value as u8, size))?; replace!(output, read, 2 => MemoryFillConst(index)); }), GlobalGet32(dst) => rewrite!(output, read, [GlobalSet32(src)] if (src == dst) => GlobalTee32(src)), @@ -290,14 +276,13 @@ fn rewrite( for instruction in &mut output.instructions { match *instruction { Instruction::Const64(index) => { - let value = data.operand(index).value; + let value = data.operand64(index).value(); if value == i64::from(value as i32) { *instruction = Instruction::Const64Imm(value as i32); } } Instruction::Const128(index) => { - let value = u128::from_le_bytes(data.operand(index).value); - if let Ok(value) = u32::try_from(value) { + if let Ok(value) = u32::try_from(u128::from_le_bytes(data.operand128(index).value())) { *instruction = Instruction::Const128Imm(value); } } @@ -315,8 +300,8 @@ fn local_const32(data: &WasmFunctionData, instruction: Instruction) -> Option<(B Instruction::SubLocalConst32(arg) => Some((BinOp::ISub, arg.local, arg.value)), Instruction::MulLocalConst32(arg) => Some((BinOp::IMul, arg.local, arg.value)), Instruction::BinOpLocalConst32(packed) => { - let value = data.operand(packed.index); - Some((packed.op, value.local, value.value as i32)) + let value = data.operand64(packed.index); + Some((packed.op, value.a(), value.b() as i32)) } _ => None, } @@ -324,25 +309,25 @@ fn local_const32(data: &WasmFunctionData, instruction: Instruction) -> Option<(B fn local_const64(data: &WasmFunctionData, instruction: Instruction) -> Option<(BinOp, u16, i64)> { let Instruction::BinOpLocalConst64(packed) = instruction else { return None }; - let value = data.operand(packed.index); - Some((packed.op, value.local, value.value as i64)) + let value = data.operand128(packed.index); + Some((packed.op, value.a(), value.b() as i64)) } fn local_const128( data: &WasmFunctionData, instruction: Instruction, -) -> Option<(BinOp128, u16, OperandIdx)> { +) -> Option<(BinOp128, u16, Operand128Idx<[u8; 16]>)> { let Instruction::BinOpLocalConst128(packed) = instruction else { return None }; - let value = data.operand(packed.index); - Some((packed.op, value.local, value.value)) + let value = data.operand64(packed.index); + Some((packed.op, value.a(), value.b())) } fn compact_memory_arg( data: &mut WasmFunctionData, - index: OperandIdx, -) -> Result>> { - let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) else { return Ok(None) }; - Ok(Some(operand!(data, arg)?)) + index: Operand128Idx, +) -> Result>> { + let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) else { return Ok(None) }; + Ok(Some(data.push_operand64(Operand64::from(arg))?)) } fn rewrite_scalar_const32( @@ -365,12 +350,12 @@ fn rewrite_scalar_const32( BinOp::IMul => Instruction::MulLocalConst32(arg), _ => Instruction::BinOpLocalConst32(PackedOp::new( op, - operand!(data, LocalU32 { local: *local, value: *value as u32 })?, + data.push_operand64(Operand64::<(u16, u32)>::new(*local, *value as u32))?, )), } } [Instruction::GlobalGet32(global), Instruction::Const32(value)] => Instruction::BinOpGlobalConst32( - PackedOp::new(op, operand!(data, GlobalConst32 { global: *global, value: *value as u32 })?), + PackedOp::new(op, data.push_operand64(Operand64::<(u32, u32)>::new(*global, *value as u32))?), ), [Instruction::Const32(value), Instruction::LocalGet32(local)] if commutative => { let arg = I32LocalArg { value: *value, local: *local }; @@ -379,14 +364,14 @@ fn rewrite_scalar_const32( BinOp::IMul => Instruction::MulLocalConst32(arg), _ => Instruction::BinOpLocalConst32(PackedOp::new( op, - operand!(data, LocalU32 { local: *local, value: *value as u32 })?, + data.push_operand64(Operand64::<(u16, u32)>::new(*local, *value as u32))?, )), } } [Instruction::Const32(value), Instruction::GlobalGet32(global)] if commutative => { Instruction::BinOpGlobalConst32(PackedOp::new( op, - operand!(data, GlobalConst32 { global: *global, value: *value as u32 })?, + data.push_operand64(Operand64::<(u32, u32)>::new(*global, *value as u32))?, )) } _ => return Ok(false), @@ -409,18 +394,24 @@ fn rewrite_scalar_const64( let replacement = match previous { [Instruction::LocalGet64(local), Instruction::Const64(index)] => Instruction::BinOpLocalConst64(PackedOp::new( op, - operand!(data, LocalConst64 { local, value: data.operand(index).value as u64 })?, + data.push_operand128(Operand128::<(u16, u64)>::new(local, data.operand64(index).value() as u64))?, )), - [Instruction::GlobalGet64(global), Instruction::Const64(index)] => Instruction::BinOpGlobalConst64( - PackedOp::new(op, operand!(data, GlobalConst64 { global, value: data.operand(index).value as u64 })?), - ), - [Instruction::Const64(index), Instruction::LocalGet64(local)] if commutative => Instruction::BinOpLocalConst64( - PackedOp::new(op, operand!(data, LocalConst64 { local, value: data.operand(index).value as u64 })?), - ), + [Instruction::GlobalGet64(global), Instruction::Const64(index)] => { + Instruction::BinOpGlobalConst64(PackedOp::new( + op, + data.push_operand128(Operand128::<(u32, u64)>::new(global, data.operand64(index).value() as u64))?, + )) + } + [Instruction::Const64(index), Instruction::LocalGet64(local)] if commutative => { + Instruction::BinOpLocalConst64(PackedOp::new( + op, + data.push_operand128(Operand128::<(u16, u64)>::new(local, data.operand64(index).value() as u64))?, + )) + } [Instruction::Const64(index), Instruction::GlobalGet64(global)] if commutative => { Instruction::BinOpGlobalConst64(PackedOp::new( op, - operand!(data, GlobalConst64 { global, value: data.operand(index).value as u64 })?, + data.push_operand128(Operand128::<(u32, u64)>::new(global, data.operand64(index).value() as u64))?, )) } _ => return Ok(false), @@ -455,7 +446,7 @@ fn rewrite_sign_extend64(output: &mut CompactOutput, read: &mut usize, data: &Wa } if let Some((BinOp::IShl, local, shift)) = local_const64(data, output[*read - 2]) && let Instruction::Const64(index) = output[*read - 1] - && shift == data.operand(index).value + && shift == data.operand64(index).value() { let instruction = match shift { 56 => Instruction::I64Extend8S, @@ -482,17 +473,26 @@ fn rewrite_vector_binop( let previous = [output[*read - 2], output[*read - 1]]; let replacement = match previous { [Instruction::LocalGet128(a), Instruction::LocalGet128(b)] => Instruction::BinOpLocalLocal128(op, a, b), - [Instruction::LocalGet128(local), Instruction::Const128(value)] => { - Instruction::BinOpLocalConst128(PackedOp::new(op, operand!(data, LocalV128 { local, value })?)) - } + [Instruction::LocalGet128(local), Instruction::Const128(value)] => Instruction::BinOpLocalConst128( + PackedOp::new(op, data.push_operand64(Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(local, value))?), + ), [Instruction::GlobalGet128(global), Instruction::Const128(value)] => { - Instruction::BinOpGlobalConst128(PackedOp::new(op, operand!(data, GlobalV128 { global, value })?)) + Instruction::BinOpGlobalConst128(PackedOp::new( + op, + data.push_operand64(Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(global, value))?, + )) } [Instruction::Const128(value), Instruction::LocalGet128(local)] if commutative => { - Instruction::BinOpLocalConst128(PackedOp::new(op, operand!(data, LocalV128 { local, value })?)) + Instruction::BinOpLocalConst128(PackedOp::new( + op, + data.push_operand64(Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(local, value))?, + )) } [Instruction::Const128(value), Instruction::GlobalGet128(global)] if commutative => { - Instruction::BinOpGlobalConst128(PackedOp::new(op, operand!(data, GlobalV128 { global, value })?)) + Instruction::BinOpGlobalConst128(PackedOp::new( + op, + data.push_operand64(Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(global, value))?, + )) } _ => return Ok(()), }; @@ -505,9 +505,13 @@ fn rewrite_store32( output: &mut CompactOutput, read: &mut usize, data: &mut WasmFunctionData, - index: OperandIdx, + index: Operand128Idx, ) -> Result<()> { - let compact_arg = CompactMemoryArg::try_from(data.operand(index)).ok(); + let compact_arg = CompactMemoryArg::try_from(data.operand128(index)).ok(); + if *read > output.block_start && output[*read - 1] == Instruction::Select32 { + replace!(output, *read, 1 => Instruction::SelectStore32(index)); + return Ok(()); + } if *read >= output.block_start + 3 { let previous = [output[*read - 3], output[*read - 2], output[*read - 1]]; if let [ @@ -515,7 +519,7 @@ fn rewrite_store32( Instruction::LoadLocal32(arg), Instruction::AddConst32(1), ] = previous - && { compact_arg == Some(data.operand(arg.memory_arg_idx)) } + && { compact_arg.map(Operand64::from) == Some(data.operand64(arg.memory_arg_idx)) } && addr == u16::from(arg.local1) { replace!(output, *read, 3 => Instruction::IncMemoryLocal32(arg)); @@ -526,12 +530,12 @@ fn rewrite_store32( let previous = [output[*read - 2], output[*read - 1]]; match previous { [Instruction::F32Mul, Instruction::F32Add] - if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) => + if let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) => { replace!(output, *read, 2 => Instruction::FMaStoreF32(arg)); } [Instruction::BinOpStackLocal32(BinOp::FMul, local), Instruction::F32Add] - if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) => + if let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) => { replace!(output, *read, 2 => [Instruction::LocalGet32(local), Instruction::FMaStoreF32(arg)]); } @@ -539,7 +543,7 @@ fn rewrite_store32( if let (Ok(addr), Ok(value), Some(memory_arg)) = (u8::try_from(addr), u8::try_from(value), compact_arg) => { - let memory_arg_idx = operand!(data, memory_arg)?; + let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?; replace!(output, *read, 2 => Instruction::StoreLocalLocal32(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value })); } _ => {} @@ -552,9 +556,13 @@ fn rewrite_store64( output: &mut CompactOutput, read: &mut usize, data: &mut WasmFunctionData, - index: OperandIdx, + index: Operand128Idx, ) -> Result<()> { - let compact_arg = CompactMemoryArg::try_from(data.operand(index)).ok(); + let compact_arg = CompactMemoryArg::try_from(data.operand128(index)).ok(); + if *read > output.block_start && output[*read - 1] == Instruction::Select64 { + replace!(output, *read, 1 => Instruction::SelectStore64(index)); + return Ok(()); + } if *read >= output.block_start + 3 { let previous = [output[*read - 3], output[*read - 2], output[*read - 1]]; if let [ @@ -562,9 +570,9 @@ fn rewrite_store64( Instruction::LoadLocal64(arg), Instruction::Const64(one), ] = previous - && { compact_arg == Some(data.operand(arg.memory_arg_idx)) } + && { compact_arg.map(Operand64::from) == Some(data.operand64(arg.memory_arg_idx)) } && addr == u16::from(arg.local1) - && data.operand(one).value == 1 + && data.operand64(one).value() == 1 { replace!(output, *read, 3 => Instruction::IncMemoryLocal64(arg)); return Ok(()); @@ -573,7 +581,7 @@ fn rewrite_store64( if *read >= output.block_start + 2 { match [output[*read - 2], output[*read - 1]] { [Instruction::F64Mul, Instruction::F64Add] - if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) => + if let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) => { replace!(output, *read, 2 => Instruction::FMaStoreF64(arg)); } @@ -581,7 +589,7 @@ fn rewrite_store64( if let (Ok(addr), Ok(value), Some(memory_arg)) = (u8::try_from(addr), u8::try_from(value), compact_arg) => { - let memory_arg_idx = operand!(data, memory_arg)?; + let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?; replace!(output, *read, 2 => Instruction::StoreLocalLocal64(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value })); } _ => {} @@ -592,7 +600,7 @@ fn rewrite_store64( macro_rules! local_const_set { ($data:expr, 32, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ - let index = operand!($data, LocalConstSet32 { local: $src, dst: $dst, value: $value as u32 })?; + let index = $data.push_operand64(Operand64::<(u16, u16, u32)>::new($src, $dst, $value as u32))?; if $tee { Instruction::BinOpLocalConstTee32(PackedOp::new($op, index)) } else { @@ -600,7 +608,7 @@ macro_rules! local_const_set { } }}; ($data:expr, 64, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ - let index = operand!($data, LocalConstSet64 { local: $src, dst: $dst, value: $value as u64 })?; + let index = $data.push_operand128(Operand128::<(u16, u16, u64)>::new($src, $dst, $value as u64))?; if $tee { Instruction::BinOpLocalConstTee64(PackedOp::new($op, index)) } else { @@ -608,7 +616,7 @@ macro_rules! local_const_set { } }}; ($data:expr, 128, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ - let index = operand!($data, LocalConstSetV128 { local: $src, dst: $dst, value: $value })?; + let index = $data.push_operand64(Operand64::<(u16, u16, Operand128Idx<[u8; 16]>)>::new($src, $dst, $value))?; if $tee { Instruction::BinOpLocalConstTee128(PackedOp::new($op, index)) } else { @@ -653,7 +661,7 @@ fn rewrite_local_set32( } else { Instruction::BinOpLocalLocalSet32(PackedOp::new( op, - operand!(data, LocalTripleArg { left, right, dst })?, + data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?, )) }; replace!(output, *read, 1 => replacement); @@ -728,13 +736,13 @@ fn rewrite_local_set64( replace!(output, *read, 1 => Instruction::SetLocalConst64(PackedOp::new(dst, index))); } Instruction::BinOpLocalLocal64(op, left, right) => { - let index = operand!(data, LocalTripleArg { left, right, dst })?; + let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?; replace!(output, *read, 1 => Instruction::BinOpLocalLocalSet64(PackedOp::new(op, index))); } instruction if let Some((op, src, value)) = local_const64(data, instruction) => { if src == dst && matches!(op, BinOp::IAdd | BinOp::ISub) { let delta = if op == BinOp::IAdd { value } else { value.wrapping_neg() }; - let index = operand!(data, I64Operand { value: delta })?; + let index = data.push_operand64(Operand64::::new(delta))?; replace!(output, *read, 1 => Instruction::IncLocal64(PackedOp::new(dst, index))); } else { let replacement = local_const_set!(data, 64, op, src, dst, value, false); @@ -756,9 +764,9 @@ fn rewrite_local_set128( if *read >= output.block_start + 2 && let [Instruction::LocalGet32(local), Instruction::V128Load(index)] = [output[*read - 2], output[*read - 1]] && let (Ok(local), Ok(dst), Ok(memory_arg)) = - (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand(index))) + (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand128(index))) { - let memory_arg_idx = operand!(data, memory_arg)?; + let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?; replace!(output, *read, 2 => Instruction::LoadLocalSet128(MemoryLocalArg { memory_arg_idx, local1: local, @@ -778,7 +786,7 @@ fn rewrite_local_set128( replace!(output, *read, 1 => Instruction::SetLocalConst128(PackedOp::new(dst, value))) } Instruction::BinOpLocalLocal128(op, left, right) => { - let index = operand!(data, LocalTripleArg { left, right, dst })?; + let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?; replace!(output, *read, 1 => Instruction::BinOpLocalLocalSet128(PackedOp::new(op, index))); } instruction if let Some((op, src, value)) = local_const128(data, instruction) => { @@ -819,7 +827,7 @@ fn rewrite_local_tee32( } else { Instruction::BinOpLocalLocalTee32(PackedOp::new( op, - operand!(data, LocalTripleArg { left, right, dst })?, + data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?, )) }; replace!(output, *read, 1 => replacement); @@ -880,7 +888,7 @@ fn rewrite_local_tee64( match output[*read - 1] { Instruction::LocalGet64(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet64(src)), Instruction::BinOpLocalLocal64(op, left, right) => { - let index = operand!(data, LocalTripleArg { left, right, dst })?; + let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?; replace!(output, *read, 1 => Instruction::BinOpLocalLocalTee64(PackedOp::new(op, index))); } instruction if let Some((op, src, value)) = local_const64(data, instruction) => { @@ -902,9 +910,9 @@ fn rewrite_local_tee128( if *read >= output.block_start + 2 && let [Instruction::LocalGet32(local), Instruction::V128Load(index)] = [output[*read - 2], output[*read - 1]] && let (Ok(local), Ok(dst), Ok(memory_arg)) = - (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand(index))) + (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand128(index))) { - let memory_arg_idx = operand!(data, memory_arg)?; + let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?; replace!(output, *read, 2 => Instruction::LoadLocalTee128(MemoryLocalArg { memory_arg_idx, local1: local, @@ -916,7 +924,7 @@ fn rewrite_local_tee128( match output[*read - 1] { Instruction::LocalGet128(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet128(src)), Instruction::BinOpLocalLocal128(op, left, right) => { - let index = operand!(data, LocalTripleArg { left, right, dst })?; + let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?; replace!(output, *read, 1 => Instruction::BinOpLocalLocalTee128(PackedOp::new(op, index))); } instruction if let Some((op, src, value)) = local_const128(data, instruction) => { @@ -995,7 +1003,7 @@ fn jump_cmp_local_local( op: CmpOp, width64: bool, ) -> Result { - let index = target_operand!(data, LocalLocalCmp { target, left, right })?; + let index = data.push_target_operand64(Operand64::<(u32, u16, u16)>::new(target, left, right))?; Ok(if width64 { Instruction::JumpCmpLocalLocal64(PackedOp::new(op, index)) } else { @@ -1017,17 +1025,17 @@ fn rewrite_jump( if let Some(instruction) = source.get(target as usize).copied() { match instruction { Instruction::JumpCmpLocalLocal32(side) - if resolve_jump_target(source, data, data.operand(side.index).target) == exit && body > target => + if resolve_jump_target(source, data, data.operand64(side.index).a()) == exit && body > target => { - let value = data.operand(side.index); - output[index] = jump_cmp_local_local(data, body, value.left, value.right, side.op.inverse(), false)?; + let value = data.operand64(side.index); + output[index] = jump_cmp_local_local(data, body, value.b(), value.c(), side.op.inverse(), false)?; return Ok(()); } Instruction::JumpCmpLocalLocal64(side) - if resolve_jump_target(source, data, data.operand(side.index).target) == exit && body > target => + if resolve_jump_target(source, data, data.operand64(side.index).a()) == exit && body > target => { - let value = data.operand(side.index); - output[index] = jump_cmp_local_local(data, body, value.left, value.right, side.op.inverse(), true)?; + let value = data.operand64(side.index); + output[index] = jump_cmp_local_local(data, body, value.b(), value.c(), side.op.inverse(), true)?; return Ok(()); } _ => {} @@ -1048,7 +1056,7 @@ fn jump_cmp_stack_local( op: CmpOp, width64: bool, ) -> Result { - let index = target_operand!(data, TargetLocal { target, local })?; + let index = data.push_target_operand64(Operand64::<(u32, u16)>::new(target, local))?; Ok(if width64 { Instruction::JumpCmpStackLocal64(PackedOp::new(op, index)) } else { @@ -1069,13 +1077,13 @@ fn jump_cmp_local_const32( CmpOp::Ne => Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }), _ => Instruction::JumpCmpLocalConst32(PackedOp::new( op, - target_operand!(data, LocalConstCmp { target, value, local })?, + data.push_target_operand128(Operand128::<(u32, i32, u16)>::new(target, value, local))?, )), }); } Ok(Instruction::JumpCmpLocalConst32(PackedOp::new( op, - target_operand!(data, LocalConstCmp { target, value, local })?, + data.push_target_operand128(Operand128::<(u32, i32, u16)>::new(target, value, local))?, ))) } @@ -1095,7 +1103,7 @@ fn jump_cmp_local_const64( } Ok(Instruction::JumpCmpLocalConst64(PackedOp::new( op, - target_operand!(data, LocalConstCmp { target, value, local })?, + data.push_target_operand128(Operand128::<(u32, i32, u16)>::new(target, value, local))?, ))) } @@ -1107,7 +1115,10 @@ fn jump_cmp_stack_const32(data: &mut WasmFunctionData, target: u32, value: i32, _ => {} } } - Ok(Instruction::JumpCmpStackConst32(PackedOp::new(op, target_operand!(data, StackConst32 { target, value })?))) + Ok(Instruction::JumpCmpStackConst32(PackedOp::new( + op, + data.push_target_operand64(Operand64::<(u32, i32)>::new(target, value))?, + ))) } fn jump_cmp_stack_const64(data: &mut WasmFunctionData, target: u32, value: i64, op: CmpOp) -> Result { @@ -1118,7 +1129,10 @@ fn jump_cmp_stack_const64(data: &mut WasmFunctionData, target: u32, value: i64, _ => {} } } - Ok(Instruction::JumpCmpStackConst64(PackedOp::new(op, target_operand!(data, StackConst64 { target, value })?))) + Ok(Instruction::JumpCmpStackConst64(PackedOp::new( + op, + data.push_target_operand128(Operand128::<(u32, i64)>::new(target, value))?, + ))) } fn update_jump( @@ -1132,32 +1146,34 @@ fn update_jump( ) -> Result { if let Some(delta) = op.inc_delta(immediate) { Ok(if global { - Instruction::IncGlobalJump32(target_operand!( - data, - GlobalUpdate { target, value: delta, global: address, on_zero: u8::from(on_zero) } - )?) + Instruction::IncGlobalJump32( + data.push_target_operand128(Operand128::::new(target, delta, address, on_zero))?, + ) } else { - Instruction::IncLocalJump32(target_operand!( - data, - LocalUpdate { target, value: delta, local: address as u16, on_zero: u8::from(on_zero) } - )?) + Instruction::IncLocalJump32(data.push_target_operand128(Operand128::::new( + target, + delta, + address as u16, + on_zero, + ))?) }) } else { Ok(if global { Instruction::BinOpGlobalConstJump32(PackedOp::new( op, - target_operand!( - data, - GlobalUpdate { target, value: immediate, global: address, on_zero: u8::from(on_zero) } - )?, + data.push_target_operand128(Operand128::::new( + target, immediate, address, on_zero, + ))?, )) } else { Instruction::BinOpLocalConstJump32(PackedOp::new( op, - target_operand!( - data, - LocalUpdate { target, value: immediate, local: address as u16, on_zero: u8::from(on_zero) } - )?, + data.push_target_operand128(Operand128::::new( + target, + immediate, + address as u16, + on_zero, + ))?, )) }) } @@ -1175,10 +1191,10 @@ fn rewrite_conditional( if *read > output.block_start && let Instruction::BinOpLocalConstTee32(packed) = output[*read - 1] { - let value = data.operand(packed.index); - if value.local == value.dst { + let value = data.operand64(packed.index); + if value.a() == value.b() { let replacement = - update_jump(data, target, value.value as i32, u32::from(value.local), packed.op, on_zero, false)?; + update_jump(data, target, value.c() as i32, u32::from(value.a()), packed.op, on_zero, false)?; replace!(output, *read, 1 => replacement); return Ok(()); } @@ -1187,9 +1203,9 @@ fn rewrite_conditional( && let [Instruction::BinOpGlobalConst32(packed), Instruction::GlobalTee32(dst)] = [output[*read - 2], output[*read - 1]] { - let value = data.operand(packed.index); - if value.global == dst { - let replacement = update_jump(data, target, value.value as i32, dst, packed.op, on_zero, true)?; + let value = data.operand64(packed.index); + if value.a() == dst { + let replacement = update_jump(data, target, value.b() as i32, dst, packed.op, on_zero, true)?; replace!(output, *read, 2 => replacement); return Ok(()); } @@ -1199,10 +1215,10 @@ fn rewrite_conditional( [output[*read - 3], output[*read - 2], output[*read - 1]] && local == cond { - let replacement = Instruction::IncStackTeeLocalJump32(target_operand!( - data, - LocalUpdate { target, value, local, on_zero: u8::from(on_zero) } - )?); + let replacement = + Instruction::IncStackTeeLocalJump32( + data.push_target_operand128(Operand128::::new(target, value, local, on_zero))?, + ); replace!(output, *read, 3 => replacement); return Ok(()); } @@ -1220,13 +1236,12 @@ fn rewrite_conditional( let replacement = if let Some(op) = op { Instruction::BinOpStackConstTeeLocalJump32(PackedOp::new( op, - target_operand!(data, LocalUpdate { target, value, local, on_zero: u8::from(on_zero) })?, + data.push_target_operand128(Operand128::::new(target, value, local, on_zero))?, )) } else { - Instruction::IncStackTeeLocalJump32(target_operand!( - data, - LocalUpdate { target, value, local, on_zero: u8::from(on_zero) } - )?) + Instruction::IncStackTeeLocalJump32( + data.push_target_operand128(Operand128::::new(target, value, local, on_zero))?, + ) }; replace!(output, *read, 2 => replacement); return Ok(()); @@ -1237,23 +1252,30 @@ fn rewrite_conditional( [output[*read - 3], output[*read - 2], output[*read - 1]] && let Some(mut cmp) = cmp_op(raw_cmp) { - let value = data.operand(packed.index); - if value.local == value.dst { + let value = data.operand64(packed.index); + if value.a() == value.b() { if on_zero { cmp = cmp.inverse(); } - let replacement = if let Some(delta) = packed.op.inc_delta(value.value as i32) { + let replacement = if let Some(delta) = packed.op.inc_delta(value.c() as i32) { Instruction::IncLocalJumpCmpLocal32(PackedOp::new( cmp, - target_operand!(data, LocalUpdateCmp { target, value: delta, local: value.local, right })?, + data.push_target_operand128(Operand128::::new( + target, + delta, + value.a(), + right, + ))?, )) } else { Instruction::BinOpLocalConstJumpCmpLocal32(PackedOp::new( (packed.op, cmp), - target_operand!( - data, - LocalUpdateCmp { target, value: value.value as i32, local: value.local, right } - )?, + data.push_target_operand128(Operand128::::new( + target, + value.c() as i32, + value.a(), + right, + ))?, )) }; replace!(output, *read, 3 => replacement); @@ -1334,7 +1356,7 @@ fn rewrite_conditional( Some(jump_cmp_local_const32(data, target, local, value, op)?) } [Instruction::LocalGet64(local), Instruction::Const64(index)] - if let Ok(value) = i32::try_from(data.operand(index).value) => + if let Ok(value) = i32::try_from(data.operand64(index).value()) => { Some(jump_cmp_local_const64(data, target, local, value, op)?) } @@ -1363,7 +1385,7 @@ fn rewrite_conditional( Instruction::LocalGet64(local) => Some(jump_cmp_stack_local(data, target, local, op, true)?), Instruction::Const32(value) => Some(jump_cmp_stack_const32(data, target, value, op)?), Instruction::Const64(index) => { - Some(jump_cmp_stack_const64(data, target, data.operand(index).value, op)?) + Some(jump_cmp_stack_const64(data, target, data.operand64(index).value(), op)?) } _ => None, }; diff --git a/crates/parser/src/optimize/targets.rs b/crates/parser/src/optimize/targets.rs index 36bdf2f..c6b2252 100644 --- a/crates/parser/src/optimize/targets.rs +++ b/crates/parser/src/optimize/targets.rs @@ -1,35 +1,7 @@ -use crate::visit::{BuilderRawOperand, FunctionDataBuilder}; +use crate::visit::FunctionDataBuilder; use crate::{ParseError, Result}; use alloc::vec::Vec; -use tinywasm_types::{ - BranchTableArg, CastBranch, GlobalUpdate, Instruction, LocalConstCmp, LocalLocalCmp, LocalUpdate, LocalUpdateCmp, - OperandIdx, OperandType, PackedOp, StackConst32, StackConst64, TargetLocal, -}; - -pub(super) trait TargetOperand: OperandType { - fn set_target(&mut self, target: u32); -} - -macro_rules! target_operands { - ($($name:ty),+ $(,)?) => {$( - impl TargetOperand for $name { - fn set_target(&mut self, target: u32) { self.target = target; } - } - )+}; -} - -target_operands!( - TargetLocal, - CastBranch, - StackConst32, - StackConst64, - LocalUpdate, - GlobalUpdate, - LocalUpdateCmp, - LocalConstCmp, - LocalLocalCmp, - BranchTableArg, -); +use tinywasm_types::{Instruction, PackedOp}; pub(super) fn resolve_jump_target(instructions: &[Instruction], data: &FunctionDataBuilder, target: u32) -> u32 { let mut index = target as usize; @@ -50,58 +22,37 @@ pub(super) fn set_rewrite_target( data: &mut FunctionDataBuilder, target: u32, ) -> Result<()> { + macro_rules! rewrite_target { + ($slot:ident, operand64) => {{ data.push_target_operand64(data.operand64(*$slot).with_target(target))? }}; + ($slot:ident, operand128) => {{ data.push_target_operand128(data.operand128(*$slot).with_target(target))? }}; + ($slot:ident, packed64) => {{ PackedOp::new($slot.op, data.push_target_operand64(data.operand64($slot.index).with_target(target))?) }}; + ($slot:ident, packed128) => {{ PackedOp::new($slot.op, data.push_target_operand128(data.operand128($slot.index).with_target(target))?) }}; + } + use Instruction::*; match instruction { - JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => { - *packed = push_packed_target_copy(data, *packed, target)? - } - BrOnCast(index) | BrOnCastFail(index) => *index = push_target_copy(data, *index, target)?, - JumpCmpStackConst32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, - JumpCmpStackConst64(packed) => *packed = push_packed_target_copy(data, *packed, target)?, - BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => { - *packed = push_packed_target_copy(data, *packed, target)? - } - BinOpLocalConstJumpCmpLocal32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, - BinOpGlobalConstJump32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, - IncLocalJump32(index) | IncStackTeeLocalJump32(index) => *index = push_target_copy(data, *index, target)?, - IncGlobalJump32(index) => *index = push_target_copy(data, *index, target)?, - IncLocalJumpCmpLocal32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, - JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => { - *packed = push_packed_target_copy(data, *packed, target)? - } - JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => { - *packed = push_packed_target_copy(data, *packed, target)? - } - BranchTable(index) => *index = push_target_copy(data, *index, target)?, + JumpCmpStackLocal32(packed) => *packed = rewrite_target!(packed, packed64), + JumpCmpStackLocal64(packed) => *packed = rewrite_target!(packed, packed64), + BrOnCast(index) | BrOnCastFail(index) => *index = rewrite_target!(index, operand64), + JumpCmpStackConst32(packed) => *packed = rewrite_target!(packed, packed64), + JumpCmpStackConst64(packed) => *packed = rewrite_target!(packed, packed128), + BinOpStackConstTeeLocalJump32(packed) => *packed = rewrite_target!(packed, packed128), + BinOpLocalConstJump32(packed) => *packed = rewrite_target!(packed, packed128), + BinOpLocalConstJumpCmpLocal32(packed) => *packed = rewrite_target!(packed, packed128), + BinOpGlobalConstJump32(packed) => *packed = rewrite_target!(packed, packed128), + IncLocalJump32(index) => *index = rewrite_target!(index, operand128), + IncStackTeeLocalJump32(index) => *index = rewrite_target!(index, operand128), + IncGlobalJump32(index) => *index = rewrite_target!(index, operand128), + IncLocalJumpCmpLocal32(packed) => *packed = rewrite_target!(packed, packed128), + JumpCmpLocalConst32(packed) => *packed = rewrite_target!(packed, packed128), + JumpCmpLocalConst64(packed) => *packed = rewrite_target!(packed, packed128), + JumpCmpLocalLocal32(packed) => *packed = rewrite_target!(packed, packed64), + JumpCmpLocalLocal64(packed) => *packed = rewrite_target!(packed, packed64), + BranchTable(index) => *index = rewrite_target!(index, operand128), _ => set_target(instruction, data, target), } - Ok(()) -} -fn push_target_copy( - data: &mut FunctionDataBuilder, - index: OperandIdx, - target: u32, -) -> Result> -where - T::Raw: BuilderRawOperand, -{ - let mut value = data.operand(index); - value.set_target(target); - data.push_target_operand(value) -} - -fn push_packed_target_copy( - data: &mut FunctionDataBuilder, - packed: PackedOp, - target: u32, -) -> Result> -where - T::Raw: BuilderRawOperand, -{ - let mut value = data.operand(packed.index); - value.set_target(target); - Ok(PackedOp::new(packed.op, data.push_target_operand(value)?)) + Ok(()) } fn instruction_target(data: &FunctionDataBuilder, instruction: Instruction) -> Option { @@ -117,24 +68,31 @@ fn instruction_target(data: &FunctionDataBuilder, instruction: Instruction) -> O JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => { arg.target_ip } - JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => data.operand(packed.index).target, - BrOnCast(index) | BrOnCastFail(index) => data.operand(index).target, - JumpCmpStackConst32(packed) => data.operand(packed.index).target, - JumpCmpStackConst64(packed) => data.operand(packed.index).target, - BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => data.operand(packed.index).target, - BinOpLocalConstJumpCmpLocal32(packed) => data.operand(packed.index).target, - BinOpGlobalConstJump32(packed) => data.operand(packed.index).target, - IncLocalJump32(index) | IncStackTeeLocalJump32(index) => data.operand(index).target, - IncGlobalJump32(index) => data.operand(index).target, - IncLocalJumpCmpLocal32(packed) => data.operand(packed.index).target, - JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => data.operand(packed.index).target, - JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => data.operand(packed.index).target, - BranchTable(index) => data.operand(index).target, + JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => data.operand64(packed.index).target(), + BrOnCast(index) | BrOnCastFail(index) => data.operand64(index).target(), + JumpCmpStackConst32(packed) => data.operand64(packed.index).target(), + JumpCmpStackConst64(packed) => data.operand128(packed.index).target(), + BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => data.operand128(packed.index).target(), + BinOpLocalConstJumpCmpLocal32(packed) => data.operand128(packed.index).target(), + BinOpGlobalConstJump32(packed) => data.operand128(packed.index).target(), + IncLocalJump32(index) | IncStackTeeLocalJump32(index) => data.operand128(index).target(), + IncGlobalJump32(index) => data.operand128(index).target(), + IncLocalJumpCmpLocal32(packed) => data.operand128(packed.index).target(), + JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => data.operand128(packed.index).target(), + JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => data.operand64(packed.index).target(), + BranchTable(index) => data.operand128(index).target(), _ => return None, }) } fn set_target(instruction: &mut Instruction, data: &mut FunctionDataBuilder, target: u32) { + macro_rules! set_target { + ($index:expr, operand64) => {{ data.set_operand64($index, data.operand64($index).with_target(target)) }}; + ($index:expr, operand128) => {{ data.set_operand128($index, data.operand128($index).with_target(target)) }}; + ($packed:expr, packed64) => {{ data.set_operand64($packed.index, data.operand64($packed.index).with_target(target)) }}; + ($packed:expr, packed128) => {{ data.set_operand128($packed.index, data.operand128($packed.index).with_target(target)) }}; + } + use Instruction::*; match instruction { Jump(value) @@ -144,53 +102,32 @@ fn set_target(instruction: &mut Instruction, data: &mut FunctionDataBuilder, tar | JumpIfNonZero64(value) | JumpIfRefNull(value) | JumpIfRefNonNull(value) => *value = target, + JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => { arg.target_ip = target } - JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => set_packed_operand_target(data, *packed, target), - BrOnCast(index) | BrOnCastFail(index) => set_operand_target(data, *index, target), - JumpCmpStackConst32(packed) => set_packed_operand_target(data, *packed, target), - JumpCmpStackConst64(packed) => set_packed_operand_target(data, *packed, target), - BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => { - set_packed_operand_target(data, *packed, target) - } - BinOpLocalConstJumpCmpLocal32(packed) => set_packed_operand_target(data, *packed, target), - BinOpGlobalConstJump32(packed) => set_packed_operand_target(data, *packed, target), - IncLocalJump32(index) | IncStackTeeLocalJump32(index) => set_operand_target(data, *index, target), - IncGlobalJump32(index) => set_operand_target(data, *index, target), - IncLocalJumpCmpLocal32(packed) => set_packed_operand_target(data, *packed, target), - JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => set_packed_operand_target(data, *packed, target), - JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => set_packed_operand_target(data, *packed, target), - BranchTable(index) => set_operand_target(data, *index, target), + JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => set_target!(*packed, packed64), + BrOnCast(index) | BrOnCastFail(index) => set_target!(*index, operand64), + JumpCmpStackConst32(packed) => set_target!(*packed, packed64), + JumpCmpStackConst64(packed) => set_target!(*packed, packed128), + BinOpLocalConstJump32(packed) => set_target!(*packed, packed128), + BinOpStackConstTeeLocalJump32(packed) => set_target!(*packed, packed128), + BinOpLocalConstJumpCmpLocal32(packed) => set_target!(*packed, packed128), + BinOpGlobalConstJump32(packed) => set_target!(*packed, packed128), + IncLocalJump32(index) | IncStackTeeLocalJump32(index) => set_target!(*index, operand128), + IncGlobalJump32(index) => set_target!(*index, operand128), + IncLocalJumpCmpLocal32(packed) => set_target!(*packed, packed128), + JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => set_target!(*packed, packed128), + JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => set_target!(*packed, packed64), + BranchTable(index) => set_target!(*index, operand128), _ => {} } } -fn set_operand_target(data: &mut FunctionDataBuilder, index: OperandIdx, target: u32) -where - T::Raw: BuilderRawOperand, -{ - let mut value = data.operand(index); - value.set_target(target); - data.set_operand(index, value); -} - -fn set_packed_operand_target( - data: &mut FunctionDataBuilder, - packed: PackedOp, - target: u32, -) where - T::Raw: BuilderRawOperand, -{ - let mut value = data.operand(packed.index); - value.set_target(target); - data.set_operand(packed.index, value); -} - fn branch_table_range(data: &FunctionDataBuilder, instruction: Instruction) -> Option<(u32, u32)> { let Instruction::BranchTable(index) = instruction else { return None }; - let operand = data.operand(index); - Some((operand.start, operand.len)) + let operand = data.operand128(index); + Some((operand.start(), operand.size())) } pub(super) fn target_boundaries(instructions: &[Instruction], data: &FunctionDataBuilder) -> Result> { diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index b65f77c..724c1bf 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -5,9 +5,9 @@ use crate::{ }; use alloc::{boxed::Box, collections::BTreeMap, string::ToString, vec::Vec}; use tinywasm_types::{ - BranchTableArg, CastBranch, ExceptionHandler, Global, I64Operand, Import, ImportKind, Instruction, MemoryArg, - MemoryType, Operand64, Operand128, OperandIdx, OperandType, StorageType, TableDefinition, TagType, TwoU32, - TypeSection, V128Operand, ValueCounts, ValueLane, WasmFunctionData, + BranchTableOperand, ExceptionHandler, Global, Import, ImportKind, Instruction, MemoryType, Operand64, Operand64Idx, + Operand128, Operand128Idx, StorageType, TableDefinition, TagType, TypeSection, ValueCounts, ValueLane, + WasmFunctionData, }; use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator}; @@ -51,6 +51,7 @@ pub(crate) struct ModuleMetadata { tables: Vec, tags: Vec, aggregate_fields: Vec, + imported_memories: u32, } pub(crate) struct FunctionDataBuilder { @@ -62,42 +63,6 @@ pub(crate) struct FunctionDataBuilder { deduplicate128: Option>, } -pub(crate) trait BuilderRawOperand: tinywasm_types::RawOperand + Ord { - fn push(builder: &mut FunctionDataBuilder, raw: Self, deduplicate: bool) -> Result; - fn get(builder: &FunctionDataBuilder, index: u32) -> Self; - fn set(builder: &mut FunctionDataBuilder, index: u32, raw: Self); -} - -macro_rules! builder_raw_operand { - ($raw:ty, $lane:ident, $map:ident) => { - impl BuilderRawOperand for $raw { - fn push(builder: &mut FunctionDataBuilder, raw: Self, deduplicate: bool) -> Result { - if deduplicate && let Some(index) = builder.$map.as_ref().and_then(|map| map.get(&raw)) { - return Ok(*index); - } - let index = u32::try_from(builder.$lane.len()) - .map_err(|_| crate::ParseError::Other("instruction operand index overflow".into()))?; - builder.$lane.push(raw); - if deduplicate && let Some(map) = &mut builder.$map { - map.insert(raw, index); - } - Ok(index) - } - - fn get(builder: &FunctionDataBuilder, index: u32) -> Self { - *builder.$lane.get(index as usize).unwrap_or_else(|| unreachable!("invalid operand index")) - } - - fn set(builder: &mut FunctionDataBuilder, index: u32, raw: Self) { - *builder.$lane.get_mut(index as usize).unwrap_or_else(|| unreachable!("invalid operand index")) = raw; - } - } - }; -} - -builder_raw_operand!(Operand64, operands64, deduplicate64); -builder_raw_operand!(Operand128, operands128, deduplicate128); - impl FunctionDataBuilder { pub(crate) fn new(deduplicate_operands: bool) -> Self { Self { @@ -110,32 +75,56 @@ impl FunctionDataBuilder { } } - pub(crate) fn push_operand(&mut self, operand: T) -> Result> - where - T::Raw: BuilderRawOperand, - { - ::push(self, operand.encode(), true).map(OperandIdx::new) + pub(crate) fn push_operand64(&mut self, operand: Operand64) -> Result> { + let operand = operand.cast(); + if let Some(index) = self.deduplicate64.as_ref().and_then(|map| map.get(&operand)) { + return Ok(Operand64Idx::new(*index)); + } + let index = self.operands64.len() as u32; + self.operands64.push(operand); + if let Some(map) = &mut self.deduplicate64 { + map.insert(operand, index); + } + Ok(Operand64Idx::new(index)) + } + + pub(crate) fn push_operand128(&mut self, operand: Operand128) -> Result> { + let operand = operand.cast(); + if let Some(index) = self.deduplicate128.as_ref().and_then(|map| map.get(&operand)) { + return Ok(Operand128Idx::new(*index)); + } + let index = self.operands128.len() as u32; + self.operands128.push(operand); + if let Some(map) = &mut self.deduplicate128 { + map.insert(operand, index); + } + Ok(Operand128Idx::new(index)) + } + + pub(crate) fn push_target_operand64(&mut self, operand: Operand64) -> Result> { + self.operands64.push(operand.cast()); + Ok(Operand64Idx::new(self.operands64.len() as u32 - 1)) } - pub(crate) fn push_target_operand(&mut self, operand: T) -> Result> - where - T::Raw: BuilderRawOperand, - { - ::push(self, operand.encode(), false).map(OperandIdx::new) + pub(crate) fn push_target_operand128(&mut self, operand: Operand128) -> Result> { + self.operands128.push(operand.cast()); + Ok(Operand128Idx::new(self.operands128.len() as u32 - 1)) } - pub(crate) fn operand(&self, index: OperandIdx) -> T - where - T::Raw: BuilderRawOperand, - { - T::decode(::get(self, index.index())) + pub(crate) fn operand64(&self, index: Operand64Idx) -> Operand64 { + self.operands64[index.index()].cast() } - pub(crate) fn set_operand(&mut self, index: OperandIdx, operand: T) - where - T::Raw: BuilderRawOperand, - { - ::set(self, index.index(), operand.encode()) + pub(crate) fn operand128(&self, index: Operand128Idx) -> Operand128 { + self.operands128[index.index()].cast() + } + + pub(crate) fn set_operand64(&mut self, index: Operand64Idx, operand: Operand64) { + self.operands64[index.index()] = operand.cast(); + } + + pub(crate) fn set_operand128(&mut self, index: Operand128Idx, operand: Operand128) { + self.operands128[index.index()] = operand.cast(); } pub(crate) fn finish(self) -> WasmFunctionData { @@ -163,6 +152,7 @@ pub(crate) struct FunctionBuilder<'a> { metadata: &'a ModuleMetadata, local_types: Vec, local_addr_map: Vec, + uses_local_memory: bool, } impl<'a> FunctionBuilder<'a> { @@ -195,25 +185,31 @@ impl<'a> FunctionBuilder<'a> { }], operand_stack: Vec::new(), lane_counts: ValueCounts::default(), + uses_local_memory: false, } } + fn mark_memory(&mut self, memory: u32) { + self.uses_local_memory |= memory >= self.metadata.imported_memories; + } + fn visit_struct_get_impl( &mut self, type_index: u32, field_index: u32, - instruction: fn(OperandIdx) -> Instruction, + instruction: fn(Operand64Idx<(u32, u32)>) -> Instruction, ) -> Result<()> { let size = self.metadata.struct_field(type_index, field_index)?; - let operand = self.push_operand(TwoU32 { first: type_index, second: field_index })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, field_index))?; self.emit(&[ValueLane::S32], &[size], instruction(operand)) } - fn push_operand(&mut self, operand: T) -> Result> - where - T::Raw: BuilderRawOperand, - { - self.data.push_operand(operand) + fn push_operand64(&mut self, operand: Operand64) -> Result> { + self.data.push_operand64(operand) + } + + fn push_operand128(&mut self, operand: Operand128) -> Result> { + self.data.push_operand128(operand) } } @@ -246,6 +242,8 @@ impl ModuleMetadata { let mut memory_sizes = Vec::with_capacity(imports.len() + memories.len()); let mut table_sizes = Vec::with_capacity(imports.len() + tables.len()); let mut tag_types = Vec::with_capacity(imports.len() + tags.len()); + let imported_memories = + imports.iter().filter(|import| matches!(import.kind, ImportKind::Memory(_))).count() as u32; for import in imports { match &import.kind { @@ -294,6 +292,7 @@ impl ModuleMetadata { tables: table_sizes, tags: tag_types, aggregate_fields, + imported_memories, } } @@ -378,6 +377,7 @@ impl ModuleMetadata { impl<'a> VisitOperator<'a> for ValidateThenVisit<'_, '_> { type Output = Result<()>; + #[cfg(not(rust_analyzer))] // rust analyzer gets confused and throws a bunch of errors when this macro is expanded wasmparser::for_each_visit_operator!(validate_then_visit); fn simd_visitor(&mut self) -> Option<&mut dyn VisitSimdOperator<'a, Output = Self::Output>> { @@ -387,6 +387,7 @@ impl<'a> VisitOperator<'a> for ValidateThenVisit<'_, '_> { #[cfg(feature = "validate")] impl VisitSimdOperator<'_> for ValidateThenVisit<'_, '_> { + #[cfg(not(rust_analyzer))] // rust analyzer gets confused and throws a bunch of errors when this macro is expanded wasmparser::for_each_visit_simd_operator!(validate_then_visit_simd); } @@ -397,7 +398,7 @@ pub(crate) fn process_operators( ty_idx: u32, allocs: OperatorsReaderAllocations, deduplicate_operands: bool, -) -> Result<(Vec, FunctionDataBuilder, OperatorsReaderAllocations)> { +) -> Result<(Vec, FunctionDataBuilder, bool, OperatorsReaderAllocations)> { let (local_types, local_addr_map) = locals; let body_size = body.as_bytes().len(); let reader = body.get_binary_reader_for_operators()?; @@ -419,7 +420,7 @@ pub(crate) fn process_operators( } reader.finish()?; - Ok((builder.instructions, builder.data, reader.into_allocations())) + Ok((builder.instructions, builder.data, builder.uses_local_memory, reader.into_allocations())) } #[cfg(feature = "validate")] @@ -431,7 +432,7 @@ pub(crate) fn process_operators_and_validate( ty_idx: u32, allocs: OperatorsReaderAllocations, deduplicate_operands: bool, -) -> Result<(Vec, FunctionDataBuilder, FuncValidatorAllocations, OperatorsReaderAllocations)> { +) -> Result<(Vec, FunctionDataBuilder, bool, FuncValidatorAllocations, OperatorsReaderAllocations)> { let (local_types, local_addr_map) = locals; let body_size = body.as_bytes().len(); let reader = body.get_binary_reader_for_operators()?; @@ -453,7 +454,13 @@ pub(crate) fn process_operators_and_validate( } reader.finish()?; - Ok((builder.instructions, builder.data, validator.into_allocations(), reader.into_allocations())) + Ok(( + builder.instructions, + builder.data, + builder.uses_local_memory, + validator.into_allocations(), + reader.into_allocations(), + )) } impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { @@ -612,7 +619,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Self::Output { let size = self.metadata.struct_field(type_index, field_index)?; - let operand = self.push_operand(TwoU32 { first: type_index, second: field_index })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, field_index))?; self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(operand)) } @@ -622,7 +629,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { self.pop_expect(size)?; } self.push_sizes(&[ValueLane::S32])?; - let operand = self.push_operand(TwoU32 { first: type_index, second: array_size })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, array_size))?; self.instructions.push(Instruction::ArrayNewFixed(operand)); Ok(()) } @@ -634,7 +641,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_call_indirect(&mut self, type_index: u32, table_index: u32) -> Self::Output { let table_size = self.metadata.table_size(table_index)?; - let operand = self.push_operand(TwoU32 { first: type_index, second: table_index })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, table_index))?; let signature = self.metadata.signature(type_index)?; self.pop_expect(table_size)?; self.emit(&signature.params, &signature.results, Instruction::CallIndirect(operand)) @@ -660,7 +667,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { self.pop_expect(table_size)?; self.apply_effect(&signature.params, &[])?; self.mark_unreachable(); - let operand = self.push_operand(TwoU32 { first: type_index, second: table_index })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, table_index))?; self.instructions.push(Instruction::ReturnCallIndirect(operand)); Ok(()) } @@ -933,7 +940,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { let header_ip = self.instructions.len(); let branch_table_start = self.data.branch_table_targets.len() as u32; let branch_operand = - self.data.push_target_operand(BranchTableArg { target: 0, start: branch_table_start, len })?; + self.data.push_target_operand128(Operand128::::new(0, branch_table_start, len))?; self.instructions.push(Instruction::BranchTable(branch_operand)); struct PadInfo { @@ -978,9 +985,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { .find(|pad| pad.depth == default_depth) .ok_or_else(|| crate::ParseError::Other("missing default branch table target".into()))?; if let Instruction::BranchTable(index) = self.instructions[header_ip] { - let mut operand = self.data.operand(index); - operand.target = default_pad.pad_start as u32; - self.data.set_operand(index, operand); + let operand = self.data.operand128(index); + self.data.set_operand128(index, operand.with_target(default_pad.pad_start as u32)); } for pad in &pads { @@ -1006,12 +1012,12 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_f64_const(&mut self, val: wasmparser::Ieee64) -> Self::Output { - let operand = self.push_operand(I64Operand { value: val.bits() as i64 })?; + let operand = self.push_operand64(Operand64::::new(val.bits() as i64))?; self.emit(&[], &[ValueLane::S64], Instruction::Const64(operand)) } fn visit_i64_const(&mut self, value: i64) -> Self::Output { - let operand = self.push_operand(I64Operand { value })?; + let operand = self.push_operand64(Operand64::::new(value))?; self.emit(&[], &[ValueLane::S64], Instruction::Const64(operand)) } @@ -1019,52 +1025,55 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { let dst = self.metadata.table_size(dst_table)?; let src = self.metadata.table_size(src_table)?; let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; - let operand = self.push_operand(TwoU32 { first: dst_table, second: src_table })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(dst_table, src_table))?; self.emit(&[dst, src, len], &[], Instruction::TableCopy(operand)) } fn visit_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Self::Output { let dst = self.metadata.memory_size(dst_mem)?; let src = self.metadata.memory_size(src_mem)?; + self.mark_memory(dst_mem); + self.mark_memory(src_mem); let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; - let operand = self.push_operand(TwoU32 { first: dst_mem, second: src_mem })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(dst_mem, src_mem))?; self.emit(&[dst, src, len], &[], Instruction::MemoryCopy(operand)) } fn visit_memory_init(&mut self, data_index: u32, memory: u32) -> Self::Output { let dst = self.metadata.memory_size(memory)?; - let operand = self.push_operand(TwoU32 { first: data_index, second: memory })?; + self.mark_memory(memory); + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(data_index, memory))?; self.emit(&[dst, ValueLane::S32, ValueLane::S32], &[], Instruction::MemoryInit(operand)) } fn visit_table_init(&mut self, elem_index: u32, table: u32) -> Self::Output { let address = self.metadata.table_size(table)?; - let operand = self.push_operand(TwoU32 { first: elem_index, second: table })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(elem_index, table))?; self.emit(&[address, ValueLane::S32, ValueLane::S32], &[], Instruction::TableInit(operand)) } fn visit_array_new_data(&mut self, type_index: u32, data_index: u32) -> Self::Output { - let operand = self.push_operand(TwoU32 { first: type_index, second: data_index })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, data_index))?; self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewData(operand)) } fn visit_array_new_elem(&mut self, type_index: u32, elem_index: u32) -> Self::Output { - let operand = self.push_operand(TwoU32 { first: type_index, second: elem_index })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, elem_index))?; self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewElem(operand)) } fn visit_array_init_data(&mut self, type_index: u32, data_index: u32) -> Self::Output { - let operand = self.push_operand(TwoU32 { first: type_index, second: data_index })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, data_index))?; self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitData(operand)) } fn visit_array_init_elem(&mut self, type_index: u32, elem_index: u32) -> Self::Output { - let operand = self.push_operand(TwoU32 { first: type_index, second: elem_index })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, elem_index))?; self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitElem(operand)) } fn visit_array_copy(&mut self, type_index_dst: u32, type_index_src: u32) -> Self::Output { - let operand = self.push_operand(TwoU32 { first: type_index_dst, second: type_index_src })?; + let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index_dst, type_index_src))?; self.emit(&[ValueLane::S32; 5], &[], Instruction::ArrayCopy(operand)) } @@ -1312,12 +1321,12 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { } fn visit_i8x16_shuffle(&mut self, lanes: [u8; 16]) -> Self::Output { - let index = self.push_operand(V128Operand { value: lanes })?; + let index = self.push_operand128(Operand128::<[u8; 16]>::new(lanes))?; self.emit(&[ValueLane::S128, ValueLane::S128], &[ValueLane::S128], Instruction::I8x16Shuffle(index)) } fn visit_v128_const(&mut self, value: wasmparser::V128) -> Self::Output { - let index = self.push_operand(V128Operand { value: *value.bytes() })?; + let index = self.push_operand128(Operand128::<[u8; 16]>::new(*value.bytes()))?; self.emit(&[], &[ValueLane::S128], Instruction::Const128(index)) } } @@ -1332,7 +1341,7 @@ impl FunctionBuilder<'_> { self.pop_expect(ValueLane::S32)?; let target = convert_heap_type(target.heap_type(), target.is_nullable())?; let conditional_ip = self.instructions.len(); - let operand = self.data.push_target_operand(CastBranch { target: 0, ref_type_bits: target.to_bits() })?; + let operand = self.data.push_target_operand64(Operand64::<(u32, u32)>::new(0, target.to_bits()))?; self.instructions.push(if branch_on_fail { Instruction::BrOnCastFail(operand) } else { @@ -1502,9 +1511,8 @@ impl FunctionBuilder<'_> { *ip = target as u32; } Instruction::BrOnCast(index) | Instruction::BrOnCastFail(index) => { - let mut operand = self.data.operand(*index); - operand.target = target as u32; - self.data.set_operand(*index, operand); + let operand = self.data.operand64(*index); + self.data.set_operand64(*index, operand.with_target(target as u32)); } _ => {} } diff --git a/crates/tinywasm/src/func/context.rs b/crates/tinywasm/src/func/context.rs index 0b9e1f9..9f637f0 100644 --- a/crates/tinywasm/src/func/context.rs +++ b/crates/tinywasm/src/func/context.rs @@ -22,10 +22,12 @@ impl FuncContext<'_> { /// Get the module instance. pub fn module(&self) -> crate::ModuleInstance { - self.store - .get_module_instance(self.module_id) - .unwrap_or_else(|| unreachable!("invalid module instance id in host function context: {}", self.module_id)) - .clone() + unwrap_or_unreachable!( + self.store.get_module_instance(self.module_id), + "invalid module instance id in host function context: {}", + self.module_id + ) + .clone() } /// Get a memory export. diff --git a/crates/tinywasm/src/func/host.rs b/crates/tinywasm/src/func/host.rs index 1dcf3c1..064f6c7 100644 --- a/crates/tinywasm/src/func/host.rs +++ b/crates/tinywasm/src/func/host.rs @@ -261,13 +261,13 @@ where { fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue], results: &mut [WasmValue]) -> Result<()> { let mut values = args.iter().cloned(); - let params = P::from_wasm_values_exact(&mut values)?; + let params = cold_err!(P::from_wasm_values_exact(&mut values))?; let mut values = (self.func)(ctx, params)?.into_wasm_values(); for result in results { - *result = values.next().ok_or_else(|| crate::Error::other("not enough typed function results"))?; + *result = cold_err!(values.next().ok_or_else(|| crate::Error::other("not enough typed function results")))?; } if values.next().is_some() { - return Err(crate::Error::other("too many typed function results")); + return cold!(Err(crate::Error::other("too many typed function results"))); } Ok(()) } @@ -279,10 +279,10 @@ where }; let params = { let mut values = store.stack_value_iter(type_addr, FuncValueTypes::Params, base)?; - P::from_wasm_values_exact(&mut values) + cold_err!(P::from_wasm_values_exact(&mut values)) }; store.value_stack.truncate_to_base(base); - let result = (self.func)(FuncContext { store, module_id }, params?)?; + let result = cold_err!((self.func)(FuncContext { store, module_id }, params?))?; store.push_typed_values::(type_addr, result.into_wasm_values(), base) } } diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs index bd78a57..ea97961 100644 --- a/crates/tinywasm/src/instance.rs +++ b/crates/tinywasm/src/instance.rs @@ -68,25 +68,25 @@ struct ModuleInstanceInner { impl ModuleInstance { #[inline] pub(crate) fn resolve_type_addr(&self, type_addr: TypeAddr) -> TypeAddr { - *self.0.type_addrs.get(type_addr as usize).unwrap_or_else(|| unreachable!("invalid type address: {type_addr}")) + *unwrap_or_unreachable!(self.0.type_addrs.get(type_addr as usize), "invalid type address: {type_addr}") } /// resolve a function address to the global store address #[inline] pub(crate) fn resolve_func_addr(&self, addr: FuncAddr) -> FuncAddr { - *self.0.func_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid function address: {addr}")) + *unwrap_or_unreachable!(self.0.func_addrs.get(addr as usize), "invalid function address: {addr}") } /// resolve a table address to the global store address #[inline] pub(crate) fn resolve_table_addr(&self, addr: TableAddr) -> TableAddr { - *self.0.table_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid table address: {addr}")) + *unwrap_or_unreachable!(self.0.table_addrs.get(addr as usize), "invalid table address: {addr}") } /// resolve a memory address to the global store address #[inline] pub(crate) fn resolve_mem_addr(&self, addr: MemAddr) -> MemAddr { - *self.0.mem_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid memory address: {addr}")) + *unwrap_or_unreachable!(self.0.mem_addrs.get(addr as usize), "invalid memory address: {addr}") } /// The resolved store address of the module's first memory, or `MemAddr::MAX` when the module @@ -103,24 +103,24 @@ impl ModuleInstance { /// resolve a data address to the global store address #[inline] pub(crate) fn resolve_data_addr(&self, addr: DataAddr) -> DataAddr { - *self.0.data_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid data address: {addr}")) + *unwrap_or_unreachable!(self.0.data_addrs.get(addr as usize), "invalid data address: {addr}") } /// resolve an element address to the global store address #[inline] pub(crate) fn resolve_elem_addr(&self, addr: ElemAddr) -> ElemAddr { - *self.0.elem_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid element address: {addr}")) + *unwrap_or_unreachable!(self.0.elem_addrs.get(addr as usize), "invalid element address: {addr}") } /// resolve a global address to the global store address #[inline] pub(crate) fn resolve_global_addr(&self, addr: GlobalAddr) -> GlobalAddr { - *self.0.global_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) + *unwrap_or_unreachable!(self.0.global_addrs.get(addr as usize), "invalid global address: {addr}") } #[inline] pub(crate) fn resolve_tag_addr(&self, addr: TagAddr) -> TagAddr { - *self.0.tag_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid tag address: {addr}")) + *unwrap_or_unreachable!(self.0.tag_addrs.get(addr as usize), "invalid tag address: {addr}") } #[inline] @@ -181,9 +181,11 @@ impl ModuleInstance { addrs.funcs.extend(store.init_funcs(&module.funcs, id, &module.func_type_idxs[imported_funcs..], &type_addrs)); addrs.tags.extend(store.init_tags(&module.tags, &type_addrs)); let limiter = store.engine.config().resource_limiter.clone(); - addrs - .memories - .extend(store.init_memories(&module.memory_types, |ty| MemoryInstance::new(ty, limiter.as_deref()))?); + if !module.skip_local_memory_allocation { + addrs + .memories + .extend(store.init_memories(&module.memory_types, |ty| MemoryInstance::new(ty, limiter.as_deref()))?); + } store.init_globals(&mut addrs.globals, &module.globals, &addrs.funcs, &type_addrs)?; addrs.tables.extend(store.init_tables(&module.tables, &addrs.globals, &addrs.funcs, &type_addrs)?); diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index 4824b63..4011e96 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -1,4 +1,3 @@ -use core::hint::cold_path; use core::ops::ControlFlow; #[cfg(not(feature = "std"))] @@ -8,7 +7,7 @@ use super::no_std_floats::NoStdFloatExt; use alloc::boxed::Box; use alloc::vec::Vec; -use interpreter::stack::CallFrame; +use interpreter::stack::{CallFrame, ValueStack}; use tinywasm_types::*; use super::ExecState; @@ -33,10 +32,8 @@ pub(crate) struct Executor<'store, const BUDGETED: bool> { impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { pub(crate) fn new(store: &'store mut Store, cf: CallFrame, call_stack_base: u32) -> Self { let wasm_func = store.state.get_wasm_func(cf.func_addr); - let module = store - .get_module_instance(wasm_func.owner) - .unwrap_or_else(|| unreachable!("invalid module instance")) - .clone(); + let module = + unwrap_or_unreachable!(store.get_module_instance(wasm_func.owner), "invalid module instance").clone(); let mem0 = module.mem0_addr(); Self { module, cf, func: wasm_func.func.clone(), store, call_stack_base, mem0 } } @@ -50,8 +47,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { /// Switches the executor to another module, keeping the cached memory-0 address in sync. #[inline] fn set_module(&mut self, owner: ModuleInstanceId) { - self.module = - self.store.get_module_instance(owner).unwrap_or_else(|| unreachable!("invalid module instance")).clone(); + self.module = unwrap_or_unreachable!(self.store.get_module_instance(owner), "invalid module instance").clone(); self.mem0 = self.module.mem0_addr(); } @@ -71,324 +67,206 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { fn exec(&mut self, instr_ptr: usize) -> Result> { macro_rules! exec_op { (binary_fallible $ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ - let $rhs = <$ty>::stack_pop(&mut self.store.value_stack); - let $lhs = <$ty>::stack_pop(&mut self.store.value_stack); - <$ty>::stack_push(&mut self.store.value_stack, $expr?)?; + fn exec_binary_fallible(value_stack: &mut ValueStack) -> Result<(), Trap> { + let $rhs = <$ty>::stack_pop(value_stack); + let $lhs = <$ty>::stack_pop(value_stack); + <$ty>::stack_push(value_stack, $expr?) + } + exec_binary_fallible(&mut self.store.value_stack)?; }}; (unary $from:ty => $to:ty, |$v:ident| $expr:expr) => {{ - let $v = <$from>::stack_pop(&mut self.store.value_stack); - <$to>::stack_push(&mut self.store.value_stack, $expr)?; + fn exec_unary(value_stack: &mut ValueStack) -> Result<(), Trap> { + let $v = <$from>::stack_pop(value_stack); + <$to>::stack_push(value_stack, $expr) + } + exec_unary(&mut self.store.value_stack)?; }}; (binary $from:ty => $to:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ - let $rhs = <$from>::stack_pop(&mut self.store.value_stack); - let $lhs = <$from>::stack_pop(&mut self.store.value_stack); - <$to>::stack_push(&mut self.store.value_stack, $expr)?; - }}; - (binary_two_results $from:ty => $to:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ - let $rhs = <$from>::stack_pop(&mut self.store.value_stack); - let $lhs = <$from>::stack_pop(&mut self.store.value_stack); - let out = $expr; - <$to>::stack_push(&mut self.store.value_stack, out.0)?; - <$to>::stack_push(&mut self.store.value_stack, out.1)?; + fn exec_binary(value_stack: &mut ValueStack) -> Result<(), Trap> { + let $rhs = <$from>::stack_pop(value_stack); + let $lhs = <$from>::stack_pop(value_stack); + <$to>::stack_push(value_stack, $expr) + } + exec_binary(&mut self.store.value_stack)?; }}; - (binary_mixed $lhs_ty:ty, $rhs_ty:ty => $res:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ - let $rhs = <$rhs_ty>::stack_pop(&mut self.store.value_stack); - let $lhs = <$lhs_ty>::stack_pop(&mut self.store.value_stack); - <$res>::stack_push(&mut self.store.value_stack, $expr)?; + (binary $lhs_ty:ty, $rhs_ty:ty => $res:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{ + fn exec_binary(value_stack: &mut ValueStack) -> Result<(), Trap> { + let $rhs = <$rhs_ty>::stack_pop(value_stack); + let $lhs = <$lhs_ty>::stack_pop(value_stack); + <$res>::stack_push(value_stack, $expr) + } + exec_binary(&mut self.store.value_stack)?; }}; (ternary $from:ty => $to:ty, |$a:ident, $b:ident, $c:ident| $expr:expr) => {{ - let $c = <$from>::stack_pop(&mut self.store.value_stack); - let $b = <$from>::stack_pop(&mut self.store.value_stack); - let $a = <$from>::stack_pop(&mut self.store.value_stack); - <$to>::stack_push(&mut self.store.value_stack, $expr)?; - }}; - (quaternary_two_results $from:ty => $to:ty, |$a:ident, $b:ident, $c:ident, $d:ident| $expr:expr) => {{ - let $d = <$from>::stack_pop(&mut self.store.value_stack); - let $c = <$from>::stack_pop(&mut self.store.value_stack); - let $b = <$from>::stack_pop(&mut self.store.value_stack); - let $a = <$from>::stack_pop(&mut self.store.value_stack); - let out = $expr; - <$to>::stack_push(&mut self.store.value_stack, out.0)?; - <$to>::stack_push(&mut self.store.value_stack, out.1)?; - }}; - (local_set_pop $ty:ty, $local_index:expr) => {{ - let val = <$ty>::stack_pop(&mut self.store.value_stack); - <$ty>::local_set(&mut self.store.value_stack, &self.cf, *$local_index, val); - }}; - (local_tee $ty:ty, $local_index:expr) => {{ - let val = <$ty>::stack_peek(&self.store.value_stack); - <$ty>::local_set(&mut self.store.value_stack, &self.cf, *$local_index, val); - }}; - (global_get $ty:ty, $global_index:expr) => {{ - let addr = self.module.resolve_global_addr(*$global_index); - let value = <$ty>::global_get(&self.store.state.globals, addr); - <$ty>::stack_push(&mut self.store.value_stack, value)?; - }}; - (global_set $ty:ty, $global_index:expr) => {{ - let addr = self.module.resolve_global_addr(*$global_index); - let value = <$ty>::stack_pop(&mut self.store.value_stack); - <$ty>::global_set(&mut self.store.state.globals, addr, value); - }}; - (global_tee $ty:ty, $global_index:expr) => {{ - let addr = self.module.resolve_global_addr(*$global_index); - let value = <$ty>::stack_peek(&self.store.value_stack); - <$ty>::global_set(&mut self.store.state.globals, addr, value); - }}; - (binop_local_local $vt:ty, $exec:ident, $op:ident, $a:ident, $b:ident) => {{ - let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); - let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); - <$vt>::stack_push(&mut self.store.value_stack, $exec(*$op, lhs, rhs))?; - }}; - (binop_local_local_set $vt:ty, $exec:ident, $op:ident, $a:ident, $b:ident, $dst:ident) => {{ - let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); - let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); - let value = $exec(*$op, lhs, rhs); - <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); - }}; - (binop_local_local_tee $vt:ty, $exec:ident, $op:ident, $a:ident, $b:ident, $dst:ident) => {{ - let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); - let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); - let value = $exec(*$op, lhs, rhs); - <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); - <$vt>::stack_push(&mut self.store.value_stack, value)?; - }}; - (cmp_local_local $vt:ty, $cmp:ident, $op:ident, $a:ident, $b:ident) => {{ - let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a); - let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b); - self.store.value_stack.push(i32::from($cmp(lhs, rhs, *$op)))?; - }}; - (binop_local_const $vt:ty, $exec:ident, $op:ident, $local:ident, $rhs:expr) => {{ - let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - <$vt>::stack_push(&mut self.store.value_stack, $exec(*$op, lhs, $rhs))?; - }}; - (binop_local_const_set $vt:ty, $exec:ident, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{ - let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - let value = $exec(*$op, lhs, $rhs); - <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); - }}; - (binop_local_const_tee $vt:ty, $exec:ident, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{ - let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - let value = $exec(*$op, lhs, $rhs); - <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); - <$vt>::stack_push(&mut self.store.value_stack, value)?; - }}; - (binop_global_const $vt:ty, $exec:ident, $op:ident, $global:ident, $rhs:expr) => {{ - let lhs = <$vt>::global_get(&self.store.state.globals, self.module.resolve_global_addr(*$global)); - self.store.value_stack.push($exec(*$op, lhs, $rhs))?; - }}; - (binop_stack_global $vt:ty, $exec:ident, $op:ident, $global:ident) => {{ - let global_val = - <$vt>::global_get(&self.store.state.globals, self.module.resolve_global_addr(*$global)); - let stack_val = <$vt>::stack_pop(&mut self.store.value_stack); - self.store.value_stack.push($exec(*$op, stack_val, global_val))?; - }}; - (binop_stack_local $vt:ty, $exec:ident, $op:ident, $local:ident) => {{ - let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - let lhs = <$vt>::stack_pop(&mut self.store.value_stack); - <$vt>::stack_push(&mut self.store.value_stack, $exec(*$op, lhs, rhs))?; - }}; - (binop_stack_local_set $vt:ty, $exec:ident, $op:ident, $local:ident, $dst:ident) => {{ - let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - let lhs = <$vt>::stack_pop(&mut self.store.value_stack); - let value = $exec(*$op, lhs, rhs); - <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); - }}; - (binop_stack_local_tee $vt:ty, $exec:ident, $op:ident, $local:ident, $dst:ident) => {{ - let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local); - let lhs = <$vt>::stack_pop(&mut self.store.value_stack); - let value = $exec(*$op, lhs, rhs); - <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); - <$vt>::stack_push(&mut self.store.value_stack, value)?; - }}; - (binop_acc_local $ty:ty, $acc:ident, $mul:expr, $add:expr) => {{ - let rhs = <$ty>::stack_pop(&mut self.store.value_stack); - let lhs = <$ty>::stack_pop(&mut self.store.value_stack); - let value = ($mul)(lhs, rhs); - <$ty>::local_update(&mut self.store.value_stack, &self.cf, *$acc, |acc| ($add)(value, acc)); + fn exec_ternary(value_stack: &mut ValueStack) -> Result<(), Trap> { + let $c = <$from>::stack_pop(value_stack); + let $b = <$from>::stack_pop(value_stack); + let $a = <$from>::stack_pop(value_stack); + <$to>::stack_push(value_stack, $expr) + } + exec_ternary(&mut self.store.value_stack)?; }}; } use tinywasm_types::Instruction::*; #[rustfmt::skip] match &self.func.instructions[instr_ptr] { - Unreachable => { cold_path(); return Err(Trap::Unreachable.into()) }, + Unreachable => return cold!(Err(Trap::Unreachable.into())), Drop32 => { _ = Value32::stack_pop(&mut self.store.value_stack)}, Drop64 => { _ = Value64::stack_pop(&mut self.store.value_stack)}, Drop128 => { _ = Value128::stack_pop(&mut self.store.value_stack)}, Select32 => Value32::stack_select(&mut self.store.value_stack), Select64 => Value64::stack_select(&mut self.store.value_stack), Select128 => Value128::stack_select(&mut self.store.value_stack), + SelectStore32(idx) => self.exec_select_store::(idx.resolve(&self.func.data))?, + SelectStore64(idx) => self.exec_select_store::(idx.resolve(&self.func.data))?, SelectMulti(counts) => self.store.value_stack.select_multi(*counts), - Call(v) => { return Ok(self.exec_call_direct(*v, instr_ptr + 1)?); } - CallSelf => { self.exec_call_self(instr_ptr + 1)?; return Ok(ControlFlow::Continue(0)); } - CallIndirect(idx) => { return Ok(self.exec_call_indirect::(*idx, instr_ptr + 1)?); } - CallRef(ty) => { return Ok(self.exec_call_ref::(*ty, instr_ptr + 1)?); } - ReturnCall(v) => { return Ok(self.exec_return_call_direct(*v)?); } - ReturnCallSelf => { self.exec_return_call_self()?; return Ok(ControlFlow::Continue(0)); } - ReturnCallIndirect(idx) => { return Ok(self.exec_call_indirect::(*idx, instr_ptr + 1)?); } - ReturnCallRef(ty) => { return Ok(self.exec_call_ref::(*ty, instr_ptr + 1)?); } - Throw(tag) => { return Ok(ControlFlow::Continue(self.exec_throw(*tag, instr_ptr)?)); } - ThrowRef => { return Ok(ControlFlow::Continue(self.exec_throw_ref(instr_ptr)?)); } - Jump(ip) => { return Ok(ControlFlow::Continue(*ip as usize)); } - JumpIfZero32(ip) => if Self::exec_jump_if(&self.cf, |_| i32::stack_pop(&mut self.store.value_stack) == 0) { return Ok(ControlFlow::Continue(*ip as usize)) }, - JumpIfNonZero32(ip) => if Self::exec_jump_if(&self.cf, |_| i32::stack_pop(&mut self.store.value_stack) != 0) { return Ok(ControlFlow::Continue(*ip as usize)) }, - JumpIfZero64(ip) => if Self::exec_jump_if(&self.cf, |_| i64::stack_pop(&mut self.store.value_stack) == 0) { return Ok(ControlFlow::Continue(*ip as usize)) }, - JumpIfNonZero64(ip) => if Self::exec_jump_if(&self.cf, |_| i64::stack_pop(&mut self.store.value_stack) != 0) { return Ok(ControlFlow::Continue(*ip as usize)) }, - JumpIfRefNull(ip) => if Self::exec_jump_if(&self.cf, |_| { - let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null(); - if is_null { ValueRef::stack_pop(&mut self.store.value_stack); } - is_null - }) { return Ok(ControlFlow::Continue(*ip as usize)) }, - JumpIfRefNonNull(ip) => if Self::exec_jump_if(&self.cf, |_| { - let is_non_null = !ValueRef::stack_peek(&self.store.value_stack).is_null(); - if !is_non_null { ValueRef::stack_pop(&mut self.store.value_stack); } - is_non_null - }) { return Ok(ControlFlow::Continue(*ip as usize)) }, - BrOnCast(idx) => { let v = idx.get(&self.func.data); if !self.exec_ref_matches(v.ref_type()) { return Ok(ControlFlow::Continue(v.target as usize)); } }, - BrOnCastFail(idx) => { let v = idx.get(&self.func.data); if self.exec_ref_matches(v.ref_type()) { return Ok(ControlFlow::Continue(v.target as usize)); } }, - JumpIfLocalZero32(arg) => if Self::exec_jump_if(&self.cf, |cf| Value32::local_get(&self.store.value_stack, cf, arg.local) == 0) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, - JumpIfLocalNonZero32(arg) => if Self::exec_jump_if(&self.cf, |cf| Value32::local_get(&self.store.value_stack, cf, arg.local) != 0) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, - JumpIfLocalZero64(arg) => if Self::exec_jump_if(&self.cf, |cf| Value64::local_get(&self.store.value_stack, cf, arg.local) == 0) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, - JumpIfLocalNonZero64(arg) => if Self::exec_jump_if(&self.cf, |cf| Value64::local_get(&self.store.value_stack, cf, arg.local) != 0) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, - JumpCmpStackConst32(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&self.cf, |_| cmp_i32(i32::stack_pop(&mut self.store.value_stack), v.value, packed.op)) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - JumpCmpStackConst64(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&self.cf, |_| cmp_i64(i64::stack_pop(&mut self.store.value_stack), v.value, packed.op)) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - JumpCmpStackLocal32(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&self.cf, |cf| { - let lhs = i32::stack_pop(&mut self.store.value_stack); - cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, v.local), packed.op) - }) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - JumpCmpStackLocal64(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&self.cf, |cf| { - let lhs = i64::stack_pop(&mut self.store.value_stack); - cmp_i64(lhs, i64::local_get(&self.store.value_stack, cf, v.local), packed.op) - }) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - BinOpLocalConstJump32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |cf| { let value = exec_binop_32(op, i32::local_get(&self.store.value_stack, cf, v.local) as u32, v.value as u32) as i32; i32::local_set(&mut self.store.value_stack, cf, v.local, value); (value == 0) == (v.on_zero != 0) }) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - BinOpLocalConstJumpCmpLocal32(packed) => { let v = packed.index.get(&self.func.data); let (binop, cmp) = packed.op; if Self::exec_jump_if(&self.cf, |cf| { let lhs = exec_binop_32(binop, i32::local_get(&self.store.value_stack, cf, v.local) as u32, v.value as u32) as i32; i32::local_set(&mut self.store.value_stack, cf, v.local, lhs); cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, v.right), cmp) }) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - BinOpStackConstTeeLocalJump32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; let value = exec_binop_32(op, i32::stack_pop(&mut self.store.value_stack) as u32, v.value as u32) as i32; i32::local_set(&mut self.store.value_stack, &self.cf, v.local, value); i32::stack_push(&mut self.store.value_stack, value)?; if Self::exec_jump_if(&self.cf, |_| (value == 0) == (v.on_zero != 0)) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - BinOpGlobalConstJump32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |_| { - let global = self.module.resolve_global_addr(v.global); - let value = exec_binop_32(op, i32::global_get(&self.store.state.globals, global) as u32, v.value as u32) as i32; - i32::global_set(&mut self.store.state.globals, global, value); - (value == 0) == (v.on_zero != 0) - }) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - IncLocalJump32(idx) => { let v = idx.get(&self.func.data); if Self::exec_jump_if(&self.cf, |cf| { let value = i32::local_get(&self.store.value_stack, cf, v.local).wrapping_add(v.value); i32::local_set(&mut self.store.value_stack, cf, v.local, value); (value == 0) == (v.on_zero != 0) }) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - IncStackTeeLocalJump32(idx) => { let v = idx.get(&self.func.data); let value = i32::stack_pop(&mut self.store.value_stack).wrapping_add(v.value); i32::local_set(&mut self.store.value_stack, &self.cf, v.local, value); i32::stack_push(&mut self.store.value_stack, value)?; if Self::exec_jump_if(&self.cf, |_| (value == 0) == (v.on_zero != 0)) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - IncGlobalJump32(idx) => { let v = idx.get(&self.func.data); if Self::exec_jump_if(&self.cf, |_| { - let global = self.module.resolve_global_addr(v.global); - let value = i32::global_get(&self.store.state.globals, global).wrapping_add(v.value); - i32::global_set(&mut self.store.state.globals, global, value); - (value == 0) == (v.on_zero != 0) - }) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - IncLocalJumpCmpLocal32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |cf| { let lhs = i32::local_get(&self.store.value_stack, cf, v.local).wrapping_add(v.value); i32::local_set(&mut self.store.value_stack, cf, v.local, lhs); cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, v.right), op) }) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - JumpCmpLocalConst32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, v.local), v.value, op)) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - JumpCmpLocalConst64(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, v.local), i64::from(v.value), op)) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - JumpCmpLocalLocal32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, v.left), i32::local_get(&self.store.value_stack, cf, v.right), op)) { return Ok(ControlFlow::Continue(v.target as usize)) } }, - JumpCmpLocalLocal64(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, v.left), i64::local_get(&self.store.value_stack, cf, v.right), op)) { return Ok(ControlFlow::Continue(v.target as usize)) } }, + Call(v) => return self.exec_call_direct(*v, instr_ptr + 1), + CallSelf => return self.exec_call_self(instr_ptr + 1), + CallIndirect(idx) => return self.exec_call_indirect::(*idx, instr_ptr + 1), + CallRef(ty) => return self.exec_call_ref::(*ty, instr_ptr + 1), + ReturnCall(v) => return self.exec_return_call_direct(*v), + ReturnCallSelf => return self.exec_return_call_self(), + ReturnCallIndirect(idx) => return self.exec_call_indirect::(*idx, instr_ptr + 1), + ReturnCallRef(ty) => return self.exec_call_ref::(*ty, instr_ptr + 1), + Throw(tag) => return self.exec_throw(*tag, instr_ptr), + ThrowRef => return self.exec_throw_ref(instr_ptr), + Jump(ip) => return Ok(ControlFlow::Continue(*ip as usize)), + JumpIfZero32(ip) => if i32::stack_pop(&mut self.store.value_stack) == 0 { return Ok(ControlFlow::Continue(*ip as usize)) }, + JumpIfNonZero32(ip) => if i32::stack_pop(&mut self.store.value_stack) != 0 { return Ok(ControlFlow::Continue(*ip as usize)) }, + JumpIfZero64(ip) => if i64::stack_pop(&mut self.store.value_stack) == 0 { return Ok(ControlFlow::Continue(*ip as usize)) }, + JumpIfNonZero64(ip) => if i64::stack_pop(&mut self.store.value_stack) != 0 { return Ok(ControlFlow::Continue(*ip as usize)) }, + JumpIfRefNull(ip) => { let ip = *ip; if self.exec_jump_if_ref::() { return Ok(ControlFlow::Continue(ip as usize)) } }, + JumpIfRefNonNull(ip) => { let ip = *ip; if self.exec_jump_if_ref::() { return Ok(ControlFlow::Continue(ip as usize)) } }, + BrOnCast(idx) => if let Some(ip) = self.exec_br_on_cast::(*idx) { return Ok(ControlFlow::Continue(ip)) }, + BrOnCastFail(idx) => if let Some(ip) = self.exec_br_on_cast::(*idx) { return Ok(ControlFlow::Continue(ip)) }, + JumpIfLocalZero32(arg) => if self.exec_jump_if_local::(arg.local) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, + JumpIfLocalNonZero32(arg) => if self.exec_jump_if_local::(arg.local) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, + JumpIfLocalZero64(arg) => if self.exec_jump_if_local::(arg.local) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, + JumpIfLocalNonZero64(arg) => if self.exec_jump_if_local::(arg.local) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) }, + JumpCmpStackConst32(packed) => if let Some(ip) = self.exec_jump_cmp_stack_const32(*packed) { return Ok(ControlFlow::Continue(ip)) }, + JumpCmpStackConst64(packed) => if let Some(ip) = self.exec_jump_cmp_stack_const64(*packed) { return Ok(ControlFlow::Continue(ip)) }, + JumpCmpStackLocal32(packed) => if let Some(ip) = self.exec_jump_cmp_stack_local32(*packed) { return Ok(ControlFlow::Continue(ip)) }, + JumpCmpStackLocal64(packed) => if let Some(ip) = self.exec_jump_cmp_stack_local64(*packed) { return Ok(ControlFlow::Continue(ip)) }, + BinOpLocalConstJump32(packed) => if let Some(ip) = self.exec_binop_local_const_jump(*packed) { return Ok(ControlFlow::Continue(ip)) }, + BinOpLocalConstJumpCmpLocal32(packed) => if let Some(ip) = self.exec_binop_local_const_jump_cmp_local(*packed) { return Ok(ControlFlow::Continue(ip)) }, + BinOpStackConstTeeLocalJump32(packed) => if let Some(ip) = self.exec_binop_stack_const_tee_local_jump(*packed)? { return Ok(ControlFlow::Continue(ip)) }, + BinOpGlobalConstJump32(packed) => if let Some(ip) = self.exec_binop_global_const_jump(*packed) { return Ok(ControlFlow::Continue(ip)) }, + IncLocalJump32(idx) => if let Some(ip) = self.exec_inc_local_jump(*idx) { return Ok(ControlFlow::Continue(ip)) }, + IncStackTeeLocalJump32(idx) => if let Some(ip) = self.exec_inc_stack_tee_local_jump(*idx)? { return Ok(ControlFlow::Continue(ip)) }, + IncGlobalJump32(idx) => if let Some(ip) = self.exec_inc_global_jump(*idx) { return Ok(ControlFlow::Continue(ip)) }, + IncLocalJumpCmpLocal32(packed) => if let Some(ip) = self.exec_inc_local_jump_cmp_local(*packed) { return Ok(ControlFlow::Continue(ip)) }, + JumpCmpLocalConst32(packed) => if let Some(ip) = self.exec_jump_cmp_local_const32(*packed) { return Ok(ControlFlow::Continue(ip)) }, + JumpCmpLocalConst64(packed) => if let Some(ip) = self.exec_jump_cmp_local_const64(*packed) { return Ok(ControlFlow::Continue(ip)) }, + JumpCmpLocalLocal32(packed) => if let Some(ip) = self.exec_jump_cmp_local_local32(*packed) { return Ok(ControlFlow::Continue(ip)) }, + JumpCmpLocalLocal64(packed) => if let Some(ip) = self.exec_jump_cmp_local_local64(*packed) { return Ok(ControlFlow::Continue(ip)) }, DropKeep32 { base, keep } => self.store.value_stack.stack_32.truncate_keep((self.cf.stack_base().s32 + u32::from(*base)) as usize, *keep as usize), DropKeep64 { base, keep } => self.store.value_stack.stack_64.truncate_keep((self.cf.stack_base().s64 + u32::from(*base)) as usize, *keep as usize), DropKeep128 { base, keep } => self.store.value_stack.stack_128.truncate_keep((self.cf.stack_base().s128 + u32::from(*base)) as usize, *keep as usize), - BranchTable(idx) => { return Ok(ControlFlow::Continue(self.exec_branch_table(*idx))); } - Return => { return Ok(self.exec_return()); } - ReturnVoid => { return Ok(self.exec_return_void()); } - Return32 => { return Ok(self.exec_return_32()); } - Return64 => { return Ok(self.exec_return_64()); } - Return128 => { return Ok(self.exec_return_128()); } + BranchTable(idx) => return Ok(ControlFlow::Continue(self.exec_branch_table(*idx))), + Return => return Ok(self.exec_return()), + ReturnVoid => return Ok(self.exec_return_void()), + Return32 => return Ok(self.exec_return_32()), + Return64 => return Ok(self.exec_return_64()), + Return128 => return Ok(self.exec_return_128()), LocalGet32(local_index) => Value32::local_push(&mut self.store.value_stack, &self.cf, *local_index)?, LocalGet64(local_index) => Value64::local_push(&mut self.store.value_stack, &self.cf, *local_index)?, LocalGet128(local_index) => Value128::local_push(&mut self.store.value_stack, &self.cf, *local_index)?, - LocalSet32(local_index) => exec_op!(local_set_pop Value32, local_index), - LocalSet64(local_index) => exec_op!(local_set_pop Value64, local_index), - LocalSet128(local_index) => exec_op!(local_set_pop Value128, local_index), + LocalSet32(local_index) => self.exec_local_set_pop::(*local_index), + LocalSet64(local_index) => self.exec_local_set_pop::(*local_index), + LocalSet128(local_index) => self.exec_local_set_pop::(*local_index), LocalCopy32(from, to) => Value32::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), LocalCopy64(from, to) => Value64::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), LocalCopy128(from, to) => Value128::local_copy(&mut self.store.value_stack, &self.cf, *from, *to), - AddConst32(c) => exec_op!(unary i32 => i32, |v| v.wrapping_add(*c)), - AddConst64(idx) => { let c = idx.get(&self.func.data).value; exec_op!(unary i64 => i64, |v| v.wrapping_add(c)); }, - IncLocal32(arg) => i32::local_update(&mut self.store.value_stack, &self.cf, arg.local, |v| v.wrapping_add(arg.value)), - IncLocal64(packed) => { let v = packed.index.get(&self.func.data).value; i64::local_update(&mut self.store.value_stack, &self.cf, packed.op, |n| n.wrapping_add(v)); }, + AddConst32(c) => { i32::stack_update(&mut self.store.value_stack, #[inline(always)] |value| value.wrapping_add(*c))?; }, + AddConst64(idx) => { let constant = idx.resolve(&self.func.data).value(); i64::stack_update(&mut self.store.value_stack, #[inline(always)] |value| value.wrapping_add(constant))?; }, + IncLocal32(arg) => { i32::local_update(&mut self.store.value_stack, &self.cf, arg.local, |v| v.wrapping_add(arg.value)); }, + IncLocal64(packed) => { let v = packed.index.resolve(&self.func.data).value(); i64::local_update(&mut self.store.value_stack, &self.cf, packed.op, |n| n.wrapping_add(v)); }, I32Add3 => exec_op!(ternary i32 => i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)), I64Add3 => exec_op!(ternary i64 => i64, |a, b, c| a.wrapping_add(b).wrapping_add(c)), - MulAccLocal32(acc) => exec_op!(binop_acc_local i32, acc, |a: i32, b| a.wrapping_mul(b), |a: i32, b| a.wrapping_add(b)), - MulAccLocal64(acc) => exec_op!(binop_acc_local i64, acc, |a: i64, b| a.wrapping_mul(b), |a: i64, b| a.wrapping_add(b)), - FMulAccLocal32(acc) => exec_op!(binop_acc_local f32, acc, |a: f32, b| a * b, |a: f32, b| a + b), - FMulAccLocal64(acc) => exec_op!(binop_acc_local f64, acc, |a: f64, b| a * b, |a: f64, b| a + b), - BinOpLocalLocal32(op, a, b) => exec_op!(binop_local_local Value32, exec_binop_32, op, a, b), - BinOpLocalLocal64(op, a, b) => exec_op!(binop_local_local Value64, exec_binop_64, op, a, b), - BinOpLocalLocal128(op, a, b) => exec_op!(binop_local_local Value128, exec_binop_128, op, a, b), - CmpLocalLocal32(op, a, b) => exec_op!(cmp_local_local i32, cmp_i32, op, a, b), - CmpLocalLocal64(op, a, b) => exec_op!(cmp_local_local i64, cmp_i64, op, a, b), - AddLocalLocalSet32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.left).wrapping_add(i32::local_get(&self.store.value_stack, &self.cf, arg.right)); i32::local_set(&mut self.store.value_stack, &self.cf, arg.dst, value); }, - AddLocalLocalTee32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.left).wrapping_add(i32::local_get(&self.store.value_stack, &self.cf, arg.right)); i32::local_set(&mut self.store.value_stack, &self.cf, arg.dst, value); i32::stack_push(&mut self.store.value_stack, value)?; }, - BinOpLocalLocalSet32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.left), Value32::local_get(&self.store.value_stack, &self.cf, v.right)); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, - BinOpLocalLocalSet64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.left), Value64::local_get(&self.store.value_stack, &self.cf, v.right)); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, - BinOpLocalLocalSet128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.left), Value128::local_get(&self.store.value_stack, &self.cf, v.right)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, - BinOpLocalLocalTee32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.left), Value32::local_get(&self.store.value_stack, &self.cf, v.right)); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value32::stack_push(&mut self.store.value_stack, value)?; }, - BinOpLocalLocalTee64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.left), Value64::local_get(&self.store.value_stack, &self.cf, v.right)); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value64::stack_push(&mut self.store.value_stack, value)?; }, - BinOpLocalLocalTee128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.left), Value128::local_get(&self.store.value_stack, &self.cf, v.right)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value128::stack_push(&mut self.store.value_stack, value)?; }, - AddLocalConst32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.local).wrapping_add(arg.value); i32::stack_push(&mut self.store.value_stack, value)?; }, - SubLocalConst32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.local).wrapping_sub(arg.value); i32::stack_push(&mut self.store.value_stack, value)?; }, - MulLocalConst32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.local).wrapping_mul(arg.value); i32::stack_push(&mut self.store.value_stack, value)?; }, - BinOpLocalConst32(packed) => { let v = packed.index.get(&self.func.data); let lhs = Value32::local_get(&self.store.value_stack, &self.cf, v.local); Value32::stack_push(&mut self.store.value_stack, exec_binop_32(packed.op, lhs, v.value))?; }, - BinOpLocalConst64(packed) => { let v = packed.index.get(&self.func.data); let lhs = Value64::local_get(&self.store.value_stack, &self.cf, v.local); Value64::stack_push(&mut self.store.value_stack, exec_binop_64(packed.op, lhs, v.value))?; }, - BinOpLocalConst128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.local), Value128(v.value.get(&self.func.data).value)); Value128::stack_push(&mut self.store.value_stack, value)?; }, - BinOpGlobalConst32(packed) => { let v = packed.index.get(&self.func.data); Value32::stack_push(&mut self.store.value_stack, exec_binop_32(packed.op, Value32::global_get(&self.store.state.globals, self.module.resolve_global_addr(v.global)), v.value))?; }, - BinOpGlobalConst64(packed) => { let v = packed.index.get(&self.func.data); Value64::stack_push(&mut self.store.value_stack, exec_binop_64(packed.op, Value64::global_get(&self.store.state.globals, self.module.resolve_global_addr(v.global)), v.value))?; }, - BinOpGlobalConst128(packed) => { let v = packed.index.get(&self.func.data); Value128::stack_push(&mut self.store.value_stack, exec_binop_128(packed.op, Value128::global_get(&self.store.state.globals, self.module.resolve_global_addr(v.global)), Value128(v.value.get(&self.func.data).value)))?; }, - BinOpLocalConstSet32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, - BinOpLocalConstTee32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value32::stack_push(&mut self.store.value_stack, value)?; }, - BinOpLocalConstSet64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, - BinOpLocalConstTee64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value64::stack_push(&mut self.store.value_stack, value)?; }, - BinOpLocalConstSet128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.local), Value128(v.value.get(&self.func.data).value)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); }, - BinOpLocalConstTee128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.local), Value128(v.value.get(&self.func.data).value)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value128::stack_push(&mut self.store.value_stack, value)?; }, - BinOpStackGlobal32(op, global_index) => exec_op!(binop_stack_global Value32, exec_binop_32, op, global_index), - BinOpStackGlobal64(op, global_index) => exec_op!(binop_stack_global Value64, exec_binop_64, op, global_index), - BinOpStackLocal32(op, local) => exec_op!(binop_stack_local Value32, exec_binop_32, op, local), - BinOpStackLocalSet32(op, local, dst) => exec_op!(binop_stack_local_set Value32, exec_binop_32, op, local, dst), - BinOpStackLocalTee32(op, local, dst) => exec_op!(binop_stack_local_tee Value32, exec_binop_32, op, local, dst), - BinOpStackLocal128(op, local) => exec_op!(binop_stack_local Value128, exec_binop_128, op, local), + MulAccLocal32(acc) => self.exec_mul_acc_local::(*acc, i32::wrapping_mul, i32::wrapping_add), + MulAccLocal64(acc) => self.exec_mul_acc_local::(*acc, i64::wrapping_mul, i64::wrapping_add), + FMulAccLocal32(acc) => self.exec_mul_acc_local::(*acc, |a, b| a * b, |a, b| a + b), + FMulAccLocal64(acc) => self.exec_mul_acc_local::(*acc, |a, b| a * b, |a, b| a + b), + BinOpLocalLocal32(op, a, b) => self.exec_binop_local_local::(*a, *b, None, *op)?, + BinOpLocalLocal64(op, a, b) => self.exec_binop_local_local::(*a, *b, None, *op)?, + BinOpLocalLocal128(op, a, b) => self.exec_binop_local_local::(*a, *b, None, *op)?, + CmpLocalLocal32(op, a, b) => self.exec_cmp_local_local::(*a, *b, *op)?, + CmpLocalLocal64(op, a, b) => self.exec_cmp_local_local::(*a, *b, *op)?, + AddLocalLocalSet32(arg) => self.exec_binop_local_local::(arg.left, arg.right, Some(arg.dst), BinOp::IAdd)?, + AddLocalLocalTee32(arg) => self.exec_binop_local_local::(arg.left, arg.right, Some(arg.dst), BinOp::IAdd)?, + BinOpLocalLocalSet32(packed) => self.exec_binop_local_local_indexed::(packed.index, packed.op)?, + BinOpLocalLocalSet64(packed) => self.exec_binop_local_local_indexed::(packed.index, packed.op)?, + BinOpLocalLocalSet128(packed) => self.exec_binop_local_local_indexed::(packed.index, packed.op)?, + BinOpLocalLocalTee32(packed) => self.exec_binop_local_local_indexed::(packed.index, packed.op)?, + BinOpLocalLocalTee64(packed) => self.exec_binop_local_local_indexed::(packed.index, packed.op)?, + BinOpLocalLocalTee128(packed) => self.exec_binop_local_local_indexed::(packed.index, packed.op)?, + AddLocalConst32(arg) => self.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::IAdd)?, + SubLocalConst32(arg) => self.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::ISub)?, + MulLocalConst32(arg) => self.exec_binop_local_const::(arg.local, arg.value as u32, None, BinOp::IMul)?, + BinOpLocalConst32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.b(), None, packed.op)?; }, + BinOpLocalConst64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.b(), None, packed.op)?; }, + BinOpLocalConst128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.b().resolve(&self.func.data).value()); self.exec_binop_local_const::(v.a(), rhs, None, packed.op)?; }, + BinOpGlobalConst32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_global_const::(v.a(), v.b(), packed.op)?; }, + BinOpGlobalConst64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_global_const::(v.a(), v.b(), packed.op)?; }, + BinOpGlobalConst128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.b().resolve(&self.func.data).value()); self.exec_binop_global_const::(v.a(), rhs, packed.op)?; }, + BinOpLocalConstSet32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, + BinOpLocalConstTee32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, + BinOpLocalConstSet64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, + BinOpLocalConstTee64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::(v.a(), v.c(), Some(v.b()), packed.op)?; }, + BinOpLocalConstSet128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.c().resolve(&self.func.data).value()); self.exec_binop_local_const::(v.a(), rhs, Some(v.b()), packed.op)?; }, + BinOpLocalConstTee128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.c().resolve(&self.func.data).value()); self.exec_binop_local_const::(v.a(), rhs, Some(v.b()), packed.op)?; }, + BinOpStackGlobal32(op, global_index) => self.exec_binop_stack_global::(*global_index, *op)?, + BinOpStackGlobal64(op, global_index) => self.exec_binop_stack_global::(*global_index, *op)?, + BinOpStackLocal32(op, local) => self.exec_binop_stack_local::(*local, None, *op)?, + BinOpStackLocalSet32(op, local, dst) => self.exec_binop_stack_local::(*local, Some(*dst), *op)?, + BinOpStackLocalTee32(op, local, dst) => self.exec_binop_stack_local::(*local, Some(*dst), *op)?, + BinOpStackLocal128(op, local) => self.exec_binop_stack_local::(*local, None, *op)?, SetLocalConst32(arg) => i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, arg.value), - SetLocalConst64(packed) => { let v = packed.index.get(&self.func.data).value; i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, v); }, - SetLocalConst128(packed) => Value128::local_set(&mut self.store.value_stack, &self.cf, packed.op, Value128(packed.index.get(&self.func.data).value)), - IncMemoryLocal32(arg) => self.exec_inc_memory_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, |v| v.wrapping_add(1))?, - IncMemoryLocal64(arg) => self.exec_inc_memory_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, |v| v.wrapping_add(1))?, - StoreLocalLocal32(arg) => self.exec_store_local_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2)?, - StoreLocalLocal64(arg) => self.exec_store_local_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2)?, - StoreLocalLocal128(arg) => self.exec_store_local_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2)?, - LoadLocal32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, |v| v)?, - LoadLocal64(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, |v| v)?, - LoadLocal8S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, - LoadLocal8U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, - LoadLocal16S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, - LoadLocal16U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?, - LoadLocalTee32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, - LoadLocalSet32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, - LoadLocalTee8S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, - LoadLocalTee8U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, - LoadLocalTee16S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, - LoadLocalTee16U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, - LoadLocalSet8S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, - LoadLocalSet8U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, - LoadLocalSet16S32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, - LoadLocalSet16U32(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?, - LoadLocalTee128(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, - LoadLocalSet128(arg) => self.exec_load_local::(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?, - AndConstTee32(arg) => { exec_op!(unary i32 => i32, |v| v & arg.value); let value = i32::stack_peek(&self.store.value_stack); i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, value); }, - SubConstTee32(arg) => { exec_op!(unary i32 => i32, |v| v.wrapping_sub(arg.value)); let value = i32::stack_peek(&self.store.value_stack); i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, value); }, - AndConstTee64(packed) => { let v = packed.index.get(&self.func.data).value; exec_op!(unary i64 => i64, |n| n & v); let value = i64::stack_peek(&self.store.value_stack); i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, value); }, - SubConstTee64(packed) => { let v = packed.index.get(&self.func.data).value; exec_op!(unary i64 => i64, |n| n.wrapping_sub(v)); let value = i64::stack_peek(&self.store.value_stack); i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, value); }, - LocalTee32(local_index) => exec_op!(local_tee Value32, local_index), - LocalTee64(local_index) => exec_op!(local_tee Value64, local_index), - LocalTee128(local_index) => exec_op!(local_tee Value128, local_index), - GlobalGet32(global_index) => exec_op!(global_get Value32, global_index), - GlobalGet64(global_index) => exec_op!(global_get Value64, global_index), - GlobalGet128(global_index) => exec_op!(global_get Value128, global_index), - GlobalSet32(global_index) => exec_op!(global_set Value32, global_index), - GlobalSet64(global_index) => exec_op!(global_set Value64, global_index), - GlobalSet128(global_index) => exec_op!(global_set Value128, global_index), - GlobalTee32(global_index) => exec_op!(global_tee Value32, global_index), - GlobalTee64(global_index) => exec_op!(global_tee Value64, global_index), - GlobalTee128(global_index) => exec_op!(global_tee Value128, global_index), + SetLocalConst64(packed) => { let v = packed.index.resolve(&self.func.data).value(); i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, v); }, + SetLocalConst128(packed) => Value128::local_set(&mut self.store.value_stack, &self.cf, packed.op, Value128(packed.index.resolve(&self.func.data).value())), + IncMemoryLocal32(arg) => self.exec_inc_memory_local::(arg.memory_arg_idx, arg.local1, #[inline(always)] |v| v.wrapping_add(1))?, + IncMemoryLocal64(arg) => self.exec_inc_memory_local::(arg.memory_arg_idx, arg.local1, #[inline(always)] |v| v.wrapping_add(1))?, + StoreLocalLocal32(arg) => self.exec_store_local_local::(arg.memory_arg_idx, arg.local1, arg.local2)?, + StoreLocalLocal64(arg) => self.exec_store_local_local::(arg.memory_arg_idx, arg.local1, arg.local2)?, + StoreLocalLocal128(arg) => self.exec_store_local_local::(arg.memory_arg_idx, arg.local1, arg.local2)?, + LoadLocal32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, #[inline(always)] |v| v)?, + LoadLocal64(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, #[inline(always)] |v| v)?, + LoadLocal8S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, + LoadLocal8U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, + LoadLocal16S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, + LoadLocal16U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, 0, i32::from)?, + LoadLocalTee32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?, + LoadLocalSet32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?, + LoadLocalTee8S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalTee8U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalTee16S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalTee16U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalSet8S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalSet8U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalSet16S32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalSet16U32(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?, + LoadLocalTee128(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?, + LoadLocalSet128(arg) => self.exec_load_local::(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?, + AndConstTee32(arg) => self.exec_binop_const_tee::(arg.value as u32, arg.local, BinOp::IAnd)?, + SubConstTee32(arg) => self.exec_binop_const_tee::(arg.value as u32, arg.local, BinOp::ISub)?, + AndConstTee64(packed) => self.exec_binop_const_tee::(packed.index.resolve(&self.func.data).value() as u64, packed.op, BinOp::IAnd)?, + SubConstTee64(packed) => self.exec_binop_const_tee::(packed.index.resolve(&self.func.data).value() as u64, packed.op, BinOp::ISub)?, + LocalTee32(local_index) => self.exec_local_tee::(*local_index), + LocalTee64(local_index) => self.exec_local_tee::(*local_index), + LocalTee128(local_index) => self.exec_local_tee::(*local_index), + GlobalGet32(global_index) => self.exec_global_get::(*global_index)?, + GlobalGet64(global_index) => self.exec_global_get::(*global_index)?, + GlobalGet128(global_index) => self.exec_global_get::(*global_index)?, + GlobalSet32(global_index) => self.exec_global_set::(*global_index), + GlobalSet64(global_index) => self.exec_global_set::(*global_index), + GlobalSet128(global_index) => self.exec_global_set::(*global_index), + GlobalTee32(global_index) => self.exec_global_tee::(*global_index), + GlobalTee64(global_index) => self.exec_global_tee::(*global_index), + GlobalTee128(global_index) => self.exec_global_tee::(*global_index), Const32(val) => i32::stack_push(&mut self.store.value_stack, *val)?, Const64Imm(val) => i64::stack_push(&mut self.store.value_stack, i64::from(*val))?, - Const64(idx) => i64::stack_push(&mut self.store.value_stack, idx.get(&self.func.data).value)?, + Const64(idx) => i64::stack_push(&mut self.store.value_stack, idx.resolve(&self.func.data).value())?, Const128Imm(val) => Value128::stack_push(&mut self.store.value_stack, Value128(u128::from(*val).to_le_bytes()))?, I64Eqz => exec_op!(unary i64 => i32, |v| i32::from(v == 0)), I32Eqz => exec_op!(unary i32 => i32, |v| i32::from(v == 0)), @@ -462,26 +340,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I64Rotl => exec_op!(binary i64 => i64, |a, b| a.rotate_left(b as u32)), I32Rotr => exec_op!(binary i32 => i32, |a, b| a.rotate_right(b as u32)), I64Rotr => exec_op!(binary i64 => i64, |a, b| a.rotate_right(b as u32)), - I64Add128 => exec_op!(quaternary_two_results i64 => i64, |a_lo, a_hi, b_lo, b_hi| { - let lo = a_lo.wrapping_add(b_lo); - let carry = u64::from((lo as u64) < (a_lo as u64)); - let hi = a_hi.wrapping_add(b_hi).wrapping_add(carry as i64); - (lo, hi) - }), - I64Sub128 => exec_op!(quaternary_two_results i64 => i64, |a_lo, a_hi, b_lo, b_hi| { - let lo = a_lo.wrapping_sub(b_lo); - let borrow = u64::from((a_lo as u64) < (b_lo as u64)); - let hi = a_hi.wrapping_sub(b_hi).wrapping_sub(borrow as i64); - (lo, hi) - }), - I64MulWideS => exec_op!(binary_two_results i64 => i64, |a, b| { - let product = (a as i128).wrapping_mul(b as i128); - (product as i64, (product >> 64) as i64) - }), - I64MulWideU => exec_op!(binary_two_results i64 => i64, |a, b| { - let product = (a as u64 as u128).wrapping_mul(b as u64 as u128); - (product as u64 as i64, (product >> 64) as u64 as i64) - }), + I64Add128 => self.exec_i64_add128()?, + I64Sub128 => self.exec_i64_sub128()?, + I64MulWideS => self.exec_i64_mul_wide_s()?, + I64MulWideU => self.exec_i64_mul_wide_u()?, I32Clz => exec_op!(unary i32 => i32, |v| v.leading_zeros() as i32), I64Clz => exec_op!(unary i64 => i64, |v| i64::from(v.leading_zeros())), I32Ctz => exec_op!(unary i32 => i32, |v| v.trailing_zeros() as i32), @@ -500,6 +362,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { RefEq => exec_op!(binary ValueRef => i32, |a, b| i32::from(a == b)), RefTest(ty) => self.exec_ref_test(*ty)?, RefCast(ty) => self.exec_ref_cast(*ty)?, + // GC objects StructNew(ty) => self.exec_struct_new(*ty, false)?, StructNewDefault(ty) => self.exec_struct_new(*ty, true)?, @@ -542,31 +405,31 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { TableCopy(idx) => self.exec_table_copy(*idx)?, // Core memory load/store operations - I32Store(idx) => self.exec_mem_store::(*idx, |v| v)?, - I64Store(idx) => self.exec_mem_store::(*idx, |v| v)?, - F32Store(idx) => self.exec_mem_store::(*idx, |v| v)?, - F64Store(idx) => self.exec_mem_store::(*idx, |v| v)?, + I32Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, + I64Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, + F32Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, + F64Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, FMaStoreF32(m) => self.exec_fma_store::(*m)?, FMaStoreF64(m) => self.exec_fma_store::(*m)?, - I32Store8(idx) => self.exec_mem_store::(*idx, |v| v as i8)?, - I32Store16(idx) => self.exec_mem_store::(*idx, |v| v as i16)?, - I64Store8(idx) => self.exec_mem_store::(*idx, |v| v as i8)?, - I64Store16(idx) => self.exec_mem_store::(*idx, |v| v as i16)?, - I64Store32(idx) => self.exec_mem_store::(*idx, |v| v as i32)?, - I32Load(idx) => self.exec_mem_load::(*idx, |v| v)?, - I64Load(idx) => self.exec_mem_load::(*idx, |v| v)?, - F32Load(idx) => self.exec_mem_load::(*idx, |v| v)?, - F64Load(idx) => self.exec_mem_load::(*idx, |v| v)?, - I32Load8S(idx) => self.exec_mem_load::(*idx, i32::from)?, - I32Load8U(idx) => self.exec_mem_load::(*idx, i32::from)?, - I32Load16S(idx) => self.exec_mem_load::(*idx, i32::from)?, - I32Load16U(idx) => self.exec_mem_load::(*idx, i32::from)?, - I64Load8S(idx) => self.exec_mem_load::(*idx, i64::from)?, - I64Load8U(idx) => self.exec_mem_load::(*idx, i64::from)?, - I64Load16S(idx) => self.exec_mem_load::(*idx, i64::from)?, - I64Load16U(idx) => self.exec_mem_load::(*idx, i64::from)?, - I64Load32S(idx) => self.exec_mem_load::(*idx, i64::from)?, - I64Load32U(idx) => self.exec_mem_load::(*idx, i64::from)?, + I32Store8(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v as i8)?, + I32Store16(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v as i16)?, + I64Store8(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v as i8)?, + I64Store16(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v as i16)?, + I64Store32(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), #[inline(always)] |v| v as i32)?, + I32Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, + I64Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, + F32Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, + F64Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), #[inline(always)] |v| v)?, + I32Load8S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i32::from)?, + I32Load8U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i32::from)?, + I32Load16S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i32::from)?, + I32Load16U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i32::from)?, + I64Load8S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i64::from)?, + I64Load8U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i64::from)?, + I64Load16S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i64::from)?, + I64Load16U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i64::from)?, + I64Load32S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i64::from)?, + I64Load32U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), i64::from)?, // Numeric conversion operations F32ConvertI32S => exec_op!(unary i32 => f32, |v| v as f32), @@ -638,43 +501,43 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { V128AnyTrue => exec_op!(unary Value128 => i32, |v| v.v128_any_true() as i32), I8x16Swizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_swizzle(s)), I8x16RelaxedSwizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_relaxed_swizzle(s)), - V128Load(idx) => self.exec_mem_load::(*idx, |v| v)?, - V128Load8x8S(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load8x8_s(v.to_le_bytes()))?, - V128Load8x8U(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load8x8_u(v.to_le_bytes()))?, - V128Load16x4S(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load16x4_s(v.to_le_bytes()))?, - V128Load16x4U(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load16x4_u(v.to_le_bytes()))?, - V128Load32x2S(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load32x2_s(v.to_le_bytes()))?, - V128Load32x2U(idx) => self.exec_mem_load::(*idx, |v| Value128::v128_load32x2_u(v.to_le_bytes()))?, - V128Load8Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i8)?, - V128Load16Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i16)?, - V128Load32Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i32)?, - V128Load64Splat(idx) => self.exec_mem_load::(*idx, Value128::splat_i64)?, - V128Store(idx) => self.exec_mem_store::(*idx, |v| v)?, + V128Load(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| v)?, + V128Load8x8S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load8x8_s(v.to_le_bytes()))?, + V128Load8x8U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load8x8_u(v.to_le_bytes()))?, + V128Load16x4S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load16x4_s(v.to_le_bytes()))?, + V128Load16x4U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load16x4_u(v.to_le_bytes()))?, + V128Load32x2S(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load32x2_s(v.to_le_bytes()))?, + V128Load32x2U(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::v128_load32x2_u(v.to_le_bytes()))?, + V128Load8Splat(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), Value128::splat_i8)?, + V128Load16Splat(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), Value128::splat_i16)?, + V128Load32Splat(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), Value128::splat_i32)?, + V128Load64Splat(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), Value128::splat_i64)?, + V128Store(idx) => self.exec_mem_store::(idx.resolve(&self.func.data), |v| v)?, V128Store8Lane(arg) => self.exec_mem_store_lane::(*arg)?, V128Store16Lane(arg) => self.exec_mem_store_lane::(*arg)?, V128Store32Lane(arg) => self.exec_mem_store_lane::(*arg)?, V128Store64Lane(arg) => self.exec_mem_store_lane::(*arg)?, - V128Load32Zero(idx) => self.exec_mem_load::(*idx, |v| Value128::from_i32x4([v, 0, 0, 0]))?, - V128Load64Zero(idx) => self.exec_mem_load::(*idx, |v| Value128::from_i64x2([v, 0]))?, - Const128(arg) => Value128::stack_push(&mut self.store.value_stack, Value128(arg.get(&self.func.data).value))?, - I8x16ExtractLaneS(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i8(*lane) as i32), - I8x16ExtractLaneU(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_u8(*lane) as i32), - I16x8ExtractLaneS(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i16(*lane) as i32), - I16x8ExtractLaneU(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_u16(*lane) as i32), - I32x4ExtractLane(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i32(*lane)), - I64x2ExtractLane(lane) => exec_op!(unary Value128 => i64, |v| v.extract_lane_i64(*lane)), - F32x4ExtractLane(lane) => exec_op!(unary Value128 => f32, |v| v.extract_lane_f32(*lane)), - F64x2ExtractLane(lane) => exec_op!(unary Value128 => f64, |v| v.extract_lane_f64(*lane)), + V128Load32Zero(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::from_i32x4([v, 0, 0, 0]))?, + V128Load64Zero(idx) => self.exec_mem_load::(idx.resolve(&self.func.data), |v| Value128::from_i64x2([v, 0]))?, + Const128(arg) => Value128::stack_push(&mut self.store.value_stack, Value128(arg.resolve(&self.func.data).value()))?, + I8x16ExtractLaneS(lane) => self.exec_simd_extract_lane::(*lane, |v, lane| v.extract_lane_i8(lane) as i32)?, + I8x16ExtractLaneU(lane) => self.exec_simd_extract_lane::(*lane, |v, lane| v.extract_lane_u8(lane) as i32)?, + I16x8ExtractLaneS(lane) => self.exec_simd_extract_lane::(*lane, |v, lane| v.extract_lane_i16(lane) as i32)?, + I16x8ExtractLaneU(lane) => self.exec_simd_extract_lane::(*lane, |v, lane| v.extract_lane_u16(lane) as i32)?, + I32x4ExtractLane(lane) => self.exec_simd_extract_lane::(*lane, Value128::extract_lane_i32)?, + I64x2ExtractLane(lane) => self.exec_simd_extract_lane::(*lane, Value128::extract_lane_i64)?, + F32x4ExtractLane(lane) => self.exec_simd_extract_lane::(*lane, Value128::extract_lane_f32)?, + F64x2ExtractLane(lane) => self.exec_simd_extract_lane::(*lane, Value128::extract_lane_f64)?, V128Load8Lane(arg) => self.exec_mem_load_lane::(*arg)?, V128Load16Lane(arg) => self.exec_mem_load_lane::(*arg)?, V128Load32Lane(arg) => self.exec_mem_load_lane::(*arg)?, V128Load64Lane(arg) => self.exec_mem_load_lane::(*arg)?, - I8x16ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i8x16_replace_lane(*lane, value as i8)), - I16x8ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i16x8_replace_lane(*lane, value as i16)), - I32x4ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i32x4_replace_lane(*lane, value)), - I64x2ReplaceLane(lane) => exec_op!(binary_mixed i64, Value128 => Value128, |value, vec| vec.i64x2_replace_lane(*lane, value)), - F32x4ReplaceLane(lane) => exec_op!(binary_mixed f32, Value128 => Value128, |value, vec| vec.f32x4_replace_lane(*lane, value)), - F64x2ReplaceLane(lane) => exec_op!(binary_mixed f64, Value128 => Value128, |value, vec| vec.f64x2_replace_lane(*lane, value)), + I8x16ReplaceLane(lane) => self.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.i8x16_replace_lane(lane, value as i8))?, + I16x8ReplaceLane(lane) => self.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.i16x8_replace_lane(lane, value as i16))?, + I32x4ReplaceLane(lane) => self.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.i32x4_replace_lane(lane, value))?, + I64x2ReplaceLane(lane) => self.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.i64x2_replace_lane(lane, value))?, + F32x4ReplaceLane(lane) => self.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.f32x4_replace_lane(lane, value))?, + F64x2ReplaceLane(lane) => self.exec_simd_replace_lane::(*lane, |value, vector, lane| vector.f64x2_replace_lane(lane, value))?, I8x16Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i8(v as i8)), I16x8Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i16(v as i16)), I32x4Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i32(v)), @@ -745,18 +608,18 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I16x8Bitmask => exec_op!(unary Value128 => i32, |v| v.i16x8_bitmask() as i32), I32x4Bitmask => exec_op!(unary Value128 => i32, |v| v.i32x4_bitmask() as i32), I64x2Bitmask => exec_op!(unary Value128 => i32, |v| v.i64x2_bitmask() as i32), - I8x16Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i8x16_shl(a as u32)), - I16x8Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i16x8_shl(a as u32)), - I32x4Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i32x4_shl(a as u32)), - I64x2Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i64x2_shl(a as u32)), - I8x16ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i8x16_shr_s(a as u32)), - I16x8ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i16x8_shr_s(a as u32)), - I32x4ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i32x4_shr_s(a as u32)), - I64x2ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i64x2_shr_s(a as u32)), - I8x16ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i8x16_shr_u(a as u32)), - I16x8ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i16x8_shr_u(a as u32)), - I32x4ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i32x4_shr_u(a as u32)), - I64x2ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i64x2_shr_u(a as u32)), + I8x16Shl => exec_op!(binary i32, Value128 => Value128, |a, b| b.i8x16_shl(a as u32)), + I16x8Shl => exec_op!(binary i32, Value128 => Value128, |a, b| b.i16x8_shl(a as u32)), + I32x4Shl => exec_op!(binary i32, Value128 => Value128, |a, b| b.i32x4_shl(a as u32)), + I64x2Shl => exec_op!(binary i32, Value128 => Value128, |a, b| b.i64x2_shl(a as u32)), + I8x16ShrS => exec_op!(binary i32, Value128 => Value128, |a, b| b.i8x16_shr_s(a as u32)), + I16x8ShrS => exec_op!(binary i32, Value128 => Value128, |a, b| b.i16x8_shr_s(a as u32)), + I32x4ShrS => exec_op!(binary i32, Value128 => Value128, |a, b| b.i32x4_shr_s(a as u32)), + I64x2ShrS => exec_op!(binary i32, Value128 => Value128, |a, b| b.i64x2_shr_s(a as u32)), + I8x16ShrU => exec_op!(binary i32, Value128 => Value128, |a, b| b.i8x16_shr_u(a as u32)), + I16x8ShrU => exec_op!(binary i32, Value128 => Value128, |a, b| b.i16x8_shr_u(a as u32)), + I32x4ShrU => exec_op!(binary i32, Value128 => Value128, |a, b| b.i32x4_shr_u(a as u32)), + I64x2ShrU => exec_op!(binary i32, Value128 => Value128, |a, b| b.i64x2_shr_u(a as u32)), I8x16Add => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_add(b)), I16x8Add => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_add(b)), I32x4Add => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_add(b)), @@ -823,7 +686,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { I64x2ExtendHighI32x4S => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_s()), I64x2ExtendHighI32x4U => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_u()), I8x16Popcnt => exec_op!(unary Value128 => Value128, |v| v.i8x16_popcnt()), - I8x16Shuffle(idx) => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_shuffle(a, b, Value128(idx.get(&self.func.data).value))), + I8x16Shuffle(idx) => self.exec_simd_shuffle(Value128(idx.resolve(&self.func.data).value()))?, I16x8Q15MulrSatS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_q15mulr_sat_s(b)), I32x4DotI16x8S => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_dot_i16x8_s(b)), I8x16RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i8x16_relaxed_laneselect(a, b, c)), @@ -891,17 +754,424 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } #[inline(always)] - fn exec_jump_if(cf: &CallFrame, condition: impl FnOnce(&CallFrame) -> bool) -> bool { - condition(cf) + fn exec_jump_if_ref(&mut self) -> bool { + let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null(); + if is_null { + ValueRef::stack_pop(&mut self.store.value_stack); + } + is_null == ON_NULL + } + + #[inline(always)] + fn exec_br_on_cast(&self, index: Operand64Idx<(u32, u32)>) -> Option { + let operand = index.resolve(&self.func.data); + let ty = unwrap_or_unreachable!(RefType::from_bits(operand.b())); + (self.exec_ref_matches(ty) == ON_MATCH).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_if_local( + &self, + local: LocalAddr, + ) -> bool { + (T::local_get(&self.store.value_stack, &self.cf, local) == T::default()) == ON_ZERO + } + + #[inline(always)] + fn exec_jump_cmp_stack_const32(&mut self, packed: PackedOp64) -> Option { + let operand = packed.index.resolve(&self.func.data); + packed.op.cmp(i32::stack_pop(&mut self.store.value_stack), operand.b()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_stack_const64(&mut self, packed: PackedOp128) -> Option { + let operand = packed.index.resolve(&self.func.data); + packed.op.cmp(i64::stack_pop(&mut self.store.value_stack), operand.b()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_stack_local32(&mut self, packed: PackedOp64) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i32::stack_pop(&mut self.store.value_stack); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.b()); + packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_stack_local64(&mut self, packed: PackedOp64) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i64::stack_pop(&mut self.store.value_stack); + let rhs = i64::local_get(&self.store.value_stack, &self.cf, operand.b()); + packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_binop_local_const_jump(&mut self, packed: PackedOp128) -> Option { + let operand = packed.index.resolve(&self.func.data); + let value = i32::local_update( + &mut self.store.value_stack, + &self.cf, + operand.local(), + #[inline(always)] + |value| packed.op.exec(value as u32, operand.value() as u32) as i32, + ); + ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_binop_local_const_jump_cmp_local( + &mut self, + packed: PackedOp128<(BinOp, CmpOp), LocalUpdateCmpOperand>, + ) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i32::local_update( + &mut self.store.value_stack, + &self.cf, + operand.local(), + #[inline(always)] + |value| packed.op.0.exec(value as u32, operand.value() as u32) as i32, + ); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.right()); + packed.op.1.cmp(lhs, rhs).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_binop_stack_const_tee_local_jump( + &mut self, + packed: PackedOp128, + ) -> Result, Trap> { + let operand = packed.index.resolve(&self.func.data); + let lhs = i32::stack_pop(&mut self.store.value_stack); + let value = packed.op.exec(lhs as u32, operand.value() as u32) as i32; + i32::local_set(&mut self.store.value_stack, &self.cf, operand.local(), value); + i32::stack_push(&mut self.store.value_stack, value)?; + Ok(((value == 0) == operand.on_zero()).then_some(operand.target() as usize)) + } + + #[inline(always)] + fn exec_binop_global_const_jump(&mut self, packed: PackedOp128) -> Option { + let operand = packed.index.resolve(&self.func.data); + let global = self.module.resolve_global_addr(operand.global()); + let value = i32::global_update( + &mut self.store.state.globals, + global, + #[inline(always)] + |value| packed.op.exec(value as u32, operand.value() as u32) as i32, + ); + ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_inc_local_jump(&mut self, index: Operand128Idx) -> Option { + let operand = index.resolve(&self.func.data); + let value = i32::local_update( + &mut self.store.value_stack, + &self.cf, + operand.local(), + #[inline(always)] + |value| value.wrapping_add(operand.value()), + ); + ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_inc_stack_tee_local_jump( + &mut self, + index: Operand128Idx, + ) -> Result, Trap> { + let operand = index.resolve(&self.func.data); + let value = i32::stack_pop(&mut self.store.value_stack).wrapping_add(operand.value()); + i32::local_set(&mut self.store.value_stack, &self.cf, operand.local(), value); + i32::stack_push(&mut self.store.value_stack, value)?; + Ok(((value == 0) == operand.on_zero()).then_some(operand.target() as usize)) + } + + #[inline(always)] + fn exec_inc_global_jump(&mut self, index: Operand128Idx) -> Option { + let operand = index.resolve(&self.func.data); + let global = self.module.resolve_global_addr(operand.global()); + let value = i32::global_update( + &mut self.store.state.globals, + global, + #[inline(always)] + |value| value.wrapping_add(operand.value()), + ); + ((value == 0) == operand.on_zero()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_inc_local_jump_cmp_local(&mut self, packed: PackedOp128) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i32::local_update( + &mut self.store.value_stack, + &self.cf, + operand.local(), + #[inline(always)] + |value| value.wrapping_add(operand.value()), + ); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.right()); + packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_local_const32(&self, packed: PackedOp128) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i32::local_get(&self.store.value_stack, &self.cf, operand.c()); + packed.op.cmp(lhs, operand.b()).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_local_const64(&self, packed: PackedOp128) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i64::local_get(&self.store.value_stack, &self.cf, operand.c()); + packed.op.cmp(lhs, i64::from(operand.b())).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_local_local32(&self, packed: PackedOp64) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i32::local_get(&self.store.value_stack, &self.cf, operand.b()); + let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.c()); + packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) + } + + #[inline(always)] + fn exec_jump_cmp_local_local64(&self, packed: PackedOp64) -> Option { + let operand = packed.index.resolve(&self.func.data); + let lhs = i64::local_get(&self.store.value_stack, &self.cf, operand.b()); + let rhs = i64::local_get(&self.store.value_stack, &self.cf, operand.c()); + packed.op.cmp(lhs, rhs).then_some(operand.target() as usize) + } + + fn exec_i64_add128(&mut self) -> Result<(), Trap> { + let b_hi = i64::stack_pop(&mut self.store.value_stack); + let b_lo = i64::stack_pop(&mut self.store.value_stack); + let a_hi = i64::stack_pop(&mut self.store.value_stack); + let a_lo = i64::stack_pop(&mut self.store.value_stack); + let lo = a_lo.wrapping_add(b_lo); + let carry = u64::from((lo as u64) < (a_lo as u64)); + let hi = a_hi.wrapping_add(b_hi).wrapping_add(carry as i64); + i64::stack_push(&mut self.store.value_stack, lo)?; + i64::stack_push(&mut self.store.value_stack, hi) + } + + fn exec_i64_sub128(&mut self) -> Result<(), Trap> { + let b_hi = i64::stack_pop(&mut self.store.value_stack); + let b_lo = i64::stack_pop(&mut self.store.value_stack); + let a_hi = i64::stack_pop(&mut self.store.value_stack); + let a_lo = i64::stack_pop(&mut self.store.value_stack); + let lo = a_lo.wrapping_sub(b_lo); + let borrow = u64::from((a_lo as u64) < (b_lo as u64)); + let hi = a_hi.wrapping_sub(b_hi).wrapping_sub(borrow as i64); + i64::stack_push(&mut self.store.value_stack, lo)?; + i64::stack_push(&mut self.store.value_stack, hi) + } + + fn exec_i64_mul_wide_s(&mut self) -> Result<(), Trap> { + let rhs = i64::stack_pop(&mut self.store.value_stack); + let lhs = i64::stack_pop(&mut self.store.value_stack); + let product = (lhs as i128).wrapping_mul(rhs as i128); + i64::stack_push(&mut self.store.value_stack, product as i64)?; + i64::stack_push(&mut self.store.value_stack, (product >> 64) as i64) + } + + fn exec_i64_mul_wide_u(&mut self) -> Result<(), Trap> { + let rhs = i64::stack_pop(&mut self.store.value_stack); + let lhs = i64::stack_pop(&mut self.store.value_stack); + let product = (lhs as u64 as u128).wrapping_mul(rhs as u64 as u128); + i64::stack_push(&mut self.store.value_stack, product as u64 as i64)?; + i64::stack_push(&mut self.store.value_stack, (product >> 64) as u64 as i64) + } + + fn exec_simd_extract_lane( + &mut self, + lane: u8, + operation: impl FnOnce(Value128, u8) -> TO, + ) -> Result<(), Trap> { + let vector = Value128::stack_pop(&mut self.store.value_stack); + TO::stack_push(&mut self.store.value_stack, operation(vector, lane)) + } + + fn exec_simd_replace_lane( + &mut self, + lane: u8, + operation: impl FnOnce(VALUE, Value128, u8) -> Value128, + ) -> Result<(), Trap> { + let vector = Value128::stack_pop(&mut self.store.value_stack); + let value = VALUE::stack_pop(&mut self.store.value_stack); + Value128::stack_push(&mut self.store.value_stack, operation(value, vector, lane)) + } + + fn exec_simd_shuffle(&mut self, lanes: Value128) -> Result<(), Trap> { + let rhs = Value128::stack_pop(&mut self.store.value_stack); + let lhs = Value128::stack_pop(&mut self.store.value_stack); + Value128::stack_push(&mut self.store.value_stack, Value128::i8x16_shuffle(lhs, rhs, lanes)) + } + + #[inline(always)] + fn exec_local_set_pop(&mut self, local: LocalAddr) { + let value = T::stack_pop(&mut self.store.value_stack); + T::local_set(&mut self.store.value_stack, &self.cf, local, value); + } + + #[inline(always)] + fn exec_local_tee(&mut self, local: LocalAddr) { + let value = T::stack_peek(&self.store.value_stack); + T::local_set(&mut self.store.value_stack, &self.cf, local, value); + } + + #[inline(always)] + fn exec_global_get(&mut self, global: GlobalAddr) -> Result<(), Trap> { + let addr = self.module.resolve_global_addr(global); + let value = T::global_get(&self.store.state.globals, addr); + T::stack_push(&mut self.store.value_stack, value) + } + + #[inline(always)] + fn exec_global_set(&mut self, global: GlobalAddr) { + let addr = self.module.resolve_global_addr(global); + let value = T::stack_pop(&mut self.store.value_stack); + T::global_set(&mut self.store.state.globals, addr, value); } - fn exec_branch_table(&mut self, index: OperandIdx) -> usize { - let v = index.get(&self.func.data); + #[inline(always)] + fn exec_global_tee(&mut self, global: GlobalAddr) { + let addr = self.module.resolve_global_addr(global); + let value = T::stack_peek(&self.store.value_stack); + T::global_set(&mut self.store.state.globals, addr, value); + } + + #[inline(always)] + fn exec_binop_result( + &mut self, + dst: Option, + val: T, + ) -> Result<(), Trap> { + if let Some(dst) = dst { + T::local_set(&mut self.store.value_stack, &self.cf, dst, val); + } + if PUSH { T::stack_push(&mut self.store.value_stack, val) } else { Ok(()) } + } + + #[inline(always)] + fn exec_binop_local_local( + &mut self, + lhs: LocalAddr, + rhs: LocalAddr, + destination: Option, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs); + let rhs = T::local_get(&self.store.value_stack, &self.cf, rhs); + self.exec_binop_result::(destination, op.exec(lhs, rhs)) + } + + #[inline(always)] + fn exec_binop_local_local_indexed( + &mut self, + index: Operand64Idx<(u16, u16, u16)>, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let operands = index.resolve(&self.func.data); + self.exec_binop_local_local::(operands.a(), operands.b(), Some(operands.c()), op) + } + + #[inline(always)] + fn exec_binop_local_const( + &mut self, + lhs: LocalAddr, + rhs: T, + destination: Option, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs); + self.exec_binop_result::(destination, op.exec(lhs, rhs)) + } + + #[inline(always)] + fn exec_binop_global_const( + &mut self, + lhs: GlobalAddr, + rhs: T, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let lhs = T::global_get(&self.store.state.globals, self.module.resolve_global_addr(lhs)); + T::stack_push(&mut self.store.value_stack, op.exec(lhs, rhs)) + } + + #[inline(always)] + fn exec_cmp_local_local(&mut self, lhs: LocalAddr, rhs: LocalAddr, op: CmpOp) -> Result<(), Trap> + where + T: InternalValue, + CmpOp: CmpOpExt, + { + let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs); + let rhs = T::local_get(&self.store.value_stack, &self.cf, rhs); + i32::stack_push(&mut self.store.value_stack, i32::from(op.cmp(lhs, rhs))) + } + + #[inline(always)] + fn exec_binop_stack_global( + &mut self, + global: GlobalAddr, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let addr = self.module.resolve_global_addr(global); + let rhs = T::global_get(&self.store.state.globals, addr); + let lhs = T::stack_pop(&mut self.store.value_stack); + T::stack_push(&mut self.store.value_stack, op.exec(lhs, rhs)) + } + + #[inline(always)] + fn exec_binop_stack_local( + &mut self, + local: LocalAddr, + destination: Option, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let rhs = T::local_get(&self.store.value_stack, &self.cf, local); + let lhs = T::stack_pop(&mut self.store.value_stack); + self.exec_binop_result::(destination, op.exec(lhs, rhs)) + } + + #[inline(always)] + fn exec_binop_const_tee( + &mut self, + rhs: T, + destination: LocalAddr, + op: impl BinOpExt, + ) -> Result<(), Trap> { + let value = T::stack_update(&mut self.store.value_stack, |lhs| op.exec(lhs, rhs))?; + T::local_set(&mut self.store.value_stack, &self.cf, destination, value); + Ok(()) + } + + #[inline(always)] + fn exec_mul_acc_local( + &mut self, + accumulator: LocalAddr, + multiply: fn(T, T) -> T, + add: fn(T, T) -> T, + ) { + let rhs = T::stack_pop(&mut self.store.value_stack); + let lhs = T::stack_pop(&mut self.store.value_stack); + let product = multiply(lhs, rhs); + T::local_update( + &mut self.store.value_stack, + &self.cf, + accumulator, + #[inline(always)] + |value| add(product, value), + ); + } + + fn exec_branch_table(&mut self, index: Operand128Idx) -> usize { + let v = index.resolve(&self.func.data); let idx = ::stack_pop(&mut self.store.value_stack); - let target_ip = if idx >= 0 && (idx as u32) < v.len { - self.func.data.branch_table_targets.get((v.start + idx as u32) as usize).copied().unwrap_or(v.target) + let target_ip = if idx >= 0 && (idx as u32) < v.size() { + self.func.data.branch_table_targets.get((v.start() + idx as u32) as usize).copied().unwrap_or(v.target()) } else { - v.target + v.target() }; target_ip as usize @@ -929,12 +1199,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.store.state.alloc_exception(tag_addr, payload, roots) } - fn exec_throw(&mut self, tag_index: TagAddr, instr_ptr: usize) -> Result { + fn exec_throw(&mut self, tag_index: TagAddr, instr_ptr: usize) -> Result> { let exception = self.create_exception(tag_index)?; self.throw_exception(exception, instr_ptr) } - fn exec_throw_ref(&mut self, instr_ptr: usize) -> Result { + fn exec_throw_ref(&mut self, instr_ptr: usize) -> Result> { let exception = ValueRef::stack_pop(&mut self.store.value_stack); if exception.is_null() { return Err(Trap::NullReference.into()); @@ -942,11 +1212,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.throw_exception(exception, instr_ptr) } - fn throw_exception(&mut self, exception: ValueRef, protected_ip: usize) -> Result { - match self.dispatch_exception(exception, protected_ip) { - Ok(Some(landing_pad)) => Ok(landing_pad), - Ok(None) => self.store.root_exception(exception).and_then(|exception| Err(Error::Exception(exception))), - Err(trap) => Err(trap.into()), + fn throw_exception(&mut self, exception: ValueRef, protected_ip: usize) -> Result> { + match self.dispatch_exception(exception, protected_ip)? { + Some(landing_pad) => Ok(ControlFlow::Continue(landing_pad)), + None => self.store.root_exception(exception).and_then(|exception| Err(Error::Exception(exception))), } } @@ -964,6 +1233,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { }) } + #[inline(always)] fn switch_to_frame(&mut self, frame: CallFrame) { let previous = core::mem::replace(&mut self.cf, frame); if previous.func_addr == self.cf.func_addr { @@ -1013,7 +1283,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { return Ok(None); }; self.switch_to_frame(caller); - protected_ip = self.cf.instr_ptr.checked_sub(1).unwrap_or_else(|| unreachable!("invalid caller IP")); + protected_ip = unwrap_or_unreachable!(self.cf.instr_ptr.checked_sub(1), "invalid caller IP"); } } @@ -1066,7 +1336,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { host_func: HostFunction, type_addr: TypeAddr, return_instr_ptr: usize, - ) -> Result, Trap> { + ) -> Result> { if let Some(host_func) = host_func.typed_callback() { cold_err!(host_func.call_stack(self.store, self.module.id(), type_addr)) .map_err(|error| Trap::HostFunction(Box::new(error)))?; @@ -1101,7 +1371,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { if TAIL { Ok(self.exec_return()) } else { Ok(ControlFlow::Continue(return_instr_ptr)) } } - fn exec_call_direct(&mut self, v: u32, return_instr_ptr: usize) -> Result, Trap> { + fn exec_call_direct(&mut self, v: u32, return_instr_ptr: usize) -> Result> { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); let addr = self.module.resolve_func_addr(v); let func = self.store.state.get_func(addr); @@ -1116,7 +1386,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } } - fn exec_return_call_direct(&mut self, v: u32) -> Result, Trap> { + fn exec_return_call_direct(&mut self, v: u32) -> Result> { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); let addr = self.module.resolve_func_addr(v); let func = self.store.state.get_func(addr); @@ -1131,34 +1401,36 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } } - fn exec_call_self(&mut self, return_instr_ptr: usize) -> Result<(), Trap> { + fn exec_call_self(&mut self, return_instr_ptr: usize) -> Result> { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); let Ok(locals_base) = self.store.value_stack.enter_locals(&self.func.params, &self.func.locals) else { - return cold!(Err(Trap::CallStackOverflow)); + return cold!(Err(Trap::CallStackOverflow.into())); }; let new = CallFrame::new(self.cf.func_addr, locals_base, self.func.locals); self.store.call_stack.push(core::mem::replace(&mut self.cf, new), return_instr_ptr)?; - Ok(()) + Ok(ControlFlow::Continue(0)) } - fn exec_return_call_self(&mut self) -> Result<(), Trap> { + fn exec_return_call_self(&mut self) -> Result> { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); self.store.value_stack.truncate_keep_counts(self.cf.locals_base, self.func.params); let Ok(locals_base) = self.store.value_stack.enter_locals(&self.func.params, &self.func.locals) else { - return cold!(Err(Trap::CallStackOverflow)); + return cold!(Err(Trap::CallStackOverflow.into())); }; self.cf = CallFrame::new(self.cf.func_addr, locals_base, self.func.locals); - Ok(()) + Ok(ControlFlow::Continue(0)) } fn exec_call_indirect( &mut self, - index: OperandIdx, + index: Operand64Idx<(u32, u32)>, return_instr_ptr: usize, - ) -> Result, Trap> { - let TwoU32 { first: type_addr, second: table_addr } = index.get(&self.func.data); + ) -> Result> { + let operand = index.resolve(&self.func.data); + let type_addr = operand.a(); + let table_addr = operand.b(); self.charge_call_fuel(FUEL_COST_CALL_TOTAL); // verify that the table is of the right type, this should be validated by the parser already let table_addr = self.module.resolve_table_addr(table_addr); @@ -1166,11 +1438,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let table = self.store.state.get_table(table_addr); let Ok(table) = table.get(table_idx) else { - return cold!(Err(Trap::UndefinedElement { index: table_idx })); + return cold!(Err(Trap::UndefinedElement { index: table_idx }.into())); }; let Some(func_ref) = table.addr() else { - return cold!(Err(Trap::UninitializedElement { index: table_idx })); + return cold!(Err(Trap::UninitializedElement { index: table_idx }.into())); }; self.exec_typed_call::(func_ref, self.module.resolve_type_addr(type_addr), return_instr_ptr) @@ -1181,13 +1453,14 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { func_addr: FuncAddr, expected_type_addr: TypeAddr, return_instr_ptr: usize, - ) -> Result, Trap> { + ) -> Result> { let func = self.store.state.get_func(func_addr); if !self.store.state.type_addr_is_subtype(func.type_addr, expected_type_addr) { return cold!(Err(Trap::IndirectCallTypeMismatch { actual: Box::new(self.store.state.get_canonical_func_type(func.type_addr).clone()), expected: Box::new(self.store.state.get_canonical_func_type(expected_type_addr).clone()), - })); + } + .into())); } match &func.inner { crate::store::FunctionInstanceInner::Wasm(wasm_func) => match IS_RETURN_CALL { @@ -1205,11 +1478,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { &mut self, type_addr: u32, return_instr_ptr: usize, - ) -> Result, Trap> { + ) -> Result> { self.charge_call_fuel(FUEL_COST_CALL_TOTAL); let func_ref = ValueRef::stack_pop(&mut self.store.value_stack); let Some(func_addr) = func_ref.addr() else { - return cold!(Err(Trap::NullFunctionReference)); + return cold!(Err(Trap::NullFunctionReference.into())); }; self.exec_typed_call::(func_addr, self.module.resolve_type_addr(type_addr), return_instr_ptr) @@ -1234,13 +1507,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { ControlFlow::Continue(instr_ptr) } - #[inline(always)] fn exec_return_void(&mut self) -> ControlFlow<(), usize> { self.store.value_stack.truncate_to_base(self.cf.locals_base); self.finish_return() } - #[inline(always)] fn exec_return_32(&mut self) -> ControlFlow<(), usize> { self.store.value_stack.stack_32.truncate_to_one_tail(self.cf.locals_base.s32 as usize); self.store.value_stack.stack_64.truncate_to(self.cf.locals_base.s64 as usize); @@ -1248,7 +1519,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.finish_return() } - #[inline(always)] fn exec_return_64(&mut self) -> ControlFlow<(), usize> { self.store.value_stack.stack_32.truncate_to(self.cf.locals_base.s32 as usize); self.store.value_stack.stack_64.truncate_to_one_tail(self.cf.locals_base.s64 as usize); @@ -1256,7 +1526,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.finish_return() } - #[inline(always)] fn exec_return_128(&mut self) -> ControlFlow<(), usize> { self.store.value_stack.stack_32.truncate_to(self.cf.locals_base.s32 as usize); self.store.value_stack.stack_64.truncate_to(self.cf.locals_base.s64 as usize); @@ -1264,15 +1533,15 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.finish_return() } - #[inline(always)] fn exec_store_local_local, const N: usize>( &mut self, - memarg: CompactMemoryArg, + index: Operand64Idx, addr_local: u8, value_local: u8, ) -> Result<(), Trap> { + let memarg = index.resolve(&self.func.data); let value = T::local_get(&self.store.value_stack, &self.cf, u16::from(value_local)); - let mem_addr = self.mem_addr(memarg.mem_addr()); + let mem_addr = self.mem_addr(MemAddr::from(memarg.memory())); let mem = self.store.state.get_mem_mut(mem_addr); let addr = if mem.is_64bit() { let base = u64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); @@ -1281,22 +1550,22 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { len: N, max: mem.inner.len(), }))?; - mem.effective_addr::(base, memarg.offset())? + cold_err!(mem.effective_addr::(base, u64::from(memarg.offset())))? } else { let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); - mem.effective_addr::(base as usize, memarg.offset())? + cold_err!(mem.effective_addr::(base as usize, u64::from(memarg.offset())))? }; value.store_at(&mut mem.inner, addr) } - #[inline(always)] fn exec_inc_memory_local, const N: usize>( &mut self, - memarg: CompactMemoryArg, + index: Operand64Idx, addr_local: u8, increment: impl FnOnce(T) -> T, ) -> Result<(), Trap> { - let mem_addr = self.mem_addr(memarg.mem_addr()); + let memarg = index.resolve(&self.func.data); + let mem_addr = self.mem_addr(MemAddr::from(memarg.memory())); let mem = self.store.state.get_mem_mut(mem_addr); let addr = if mem.is_64bit() { let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64; @@ -1305,17 +1574,16 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { len: N, max: mem.inner.len(), }))?; - mem.effective_addr::(base, memarg.offset())? + cold_err!(mem.effective_addr::(base, u64::from(memarg.offset())))? } else { let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); - mem.effective_addr::(base as usize, memarg.offset())? + cold_err!(mem.effective_addr::(base as usize, u64::from(memarg.offset())))? }; let value = cold_err!(T::load_at(&mem.inner, addr))?; increment(value).store_at(&mut mem.inner, addr) } - #[inline(always)] fn exec_fma_store< T: InternalValue + MemValue + core::ops::Add + core::ops::Mul, const N: usize, @@ -1330,18 +1598,16 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let mem_addr = self.mem_addr(m.mem_addr()); let mem = self.store.state.get_mem_mut(mem_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, m.offset())?; - fma.store_at(&mut mem.inner, addr)?; - Ok(()) + let addr = cold_err!(mem.effective_addr::(base, m.offset()))?; + cold_err!(fma.store_at(&mut mem.inner, addr)) } - #[inline(always)] fn exec_load_local_value, const N: usize>( &self, - memarg: CompactMemoryArg, + memarg: Operand64, addr_local: u8, ) -> Result { - let mem = self.store.state.get_mem(self.mem_addr(memarg.mem_addr())); + let mem = self.store.state.get_mem(self.mem_addr(MemAddr::from(memarg.memory()))); let addr = if mem.is_64bit() { let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64; let base = cold_err!(usize::try_from(base).map_err(|_| Trap::MemoryOutOfBounds { @@ -1349,15 +1615,14 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { len: N, max: mem.inner.len(), }))?; - mem.effective_addr::(base, memarg.offset())? + cold_err!(mem.effective_addr::(base, u64::from(memarg.offset())))? } else { let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)); - mem.effective_addr::(base as usize, memarg.offset())? + cold_err!(mem.effective_addr::(base as usize, u64::from(memarg.offset())))? }; cold_err!(T::load_at(&mem.inner, addr)) } - #[inline(always)] fn exec_load_local< LOAD: MemValue, const N: usize, @@ -1366,11 +1631,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { const TEE: bool, >( &mut self, - memarg: CompactMemoryArg, + index: Operand64Idx, addr_local: u8, dst_local: u8, cast: impl Fn(LOAD) -> TARGET, ) -> Result<(), Trap> { + let memarg = index.resolve(&self.func.data); let value = cast(self.exec_load_local_value::(memarg, addr_local)?); if SET_LOCAL { TARGET::local_set(&mut self.store.value_stack, &self.cf, u16::from(dst_local), value); @@ -1382,7 +1648,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } fn exec_ref_is_null(&mut self) -> Result<(), Trap> { - let is_null = i32::from(::stack_pop(&mut self.store.value_stack).is_null()); + let is_null = i32::from(ValueRef::stack_pop(&mut self.store.value_stack).is_null()); self.store.value_stack.push::(is_null) } @@ -1463,8 +1729,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_struct_get(&mut self, index: OperandIdx, signed: Option) -> Result<(), Trap> { - let TwoU32 { first: type_index, second: field_index } = index.get(&self.func.data); + fn exec_struct_get(&mut self, index: Operand64Idx<(u32, u32)>, signed: Option) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let field_index = operand.b(); let reference = ValueRef::stack_pop(&mut self.store.value_stack); let type_addr = self.module.resolve_type_addr(type_index); let storage = self.store.state.get_type(type_addr).as_struct().expect("validated struct.get type").fields @@ -1476,8 +1744,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { push_value(&mut self.store.value_stack, value, storage, signed) } - fn exec_struct_set(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: type_index, second: field_index } = index.get(&self.func.data); + fn exec_struct_set(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let field_index = operand.b(); let type_addr = self.module.resolve_type_addr(type_index); let storage = self.store.state.get_type(type_addr).as_struct().expect("validated struct.set type").fields [field_index as usize] @@ -1501,8 +1771,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_array_new_fixed(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: type_index, second: len } = index.get(&self.func.data); + fn exec_array_new_fixed(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let len = operand.b(); let type_addr = self.module.resolve_type_addr(type_index); let storage = self.store.state.get_type(type_addr).as_array().expect("validated array.new_fixed type").field.storage; @@ -1567,8 +1839,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_array_copy(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: dst_type, second: src_type } = index.get(&self.func.data); + fn exec_array_copy(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let dst_type = operand.a(); + let src_type = operand.b(); let len = u32::stack_pop(&mut self.store.value_stack) as usize; let src_index = u32::stack_pop(&mut self.store.value_stack) as usize; let src = ValueRef::stack_pop(&mut self.store.value_stack); @@ -1595,8 +1869,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_array_new_data(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: type_index, second: data_index } = index.get(&self.func.data); + fn exec_array_new_data(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let data_index = operand.b(); let len = u32::stack_pop(&mut self.store.value_stack) as usize; let src = u32::stack_pop(&mut self.store.value_stack) as usize; let type_addr = self.module.resolve_type_addr(type_index); @@ -1609,8 +1885,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_array_new_elem(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: type_index, second: elem_index } = index.get(&self.func.data); + fn exec_array_new_elem(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let elem_index = operand.b(); let len = u32::stack_pop(&mut self.store.value_stack) as usize; let src = u32::stack_pop(&mut self.store.value_stack) as usize; let type_addr = self.module.resolve_type_addr(type_index); @@ -1623,8 +1901,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.push_gc_object(type_addr, values) } - fn exec_array_init_data(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: type_index, second: data_index } = index.get(&self.func.data); + fn exec_array_init_data(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let data_index = operand.b(); let len = u32::stack_pop(&mut self.store.value_stack) as usize; let src = u32::stack_pop(&mut self.store.value_stack) as usize; let dst = u32::stack_pop(&mut self.store.value_stack) as usize; @@ -1641,8 +1921,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_array_init_elem(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: type_index, second: elem_index } = index.get(&self.func.data); + fn exec_array_init_elem(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let type_index = operand.a(); + let elem_index = operand.b(); let len = u32::stack_pop(&mut self.store.value_stack) as usize; let src = u32::stack_pop(&mut self.store.value_stack) as usize; let dst = u32::stack_pop(&mut self.store.value_stack) as usize; @@ -1674,21 +1956,23 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let mem = self.store.state.get_mem_mut(mem_addr); let is_64bit = mem.is_64bit(); let pages_delta = match is_64bit { - true => ::stack_pop(&mut self.store.value_stack), - false => i64::from(::stack_pop(&mut self.store.value_stack)), + true => i64::stack_pop(&mut self.store.value_stack), + false => i64::from(i32::stack_pop(&mut self.store.value_stack)), }; let size = mem.grow(pages_delta, limiter)?.unwrap_or(-1); match is_64bit { - true => self.store.value_stack.push::(size)?, - false => self.store.value_stack.push::(size as i32)?, + true => i64::stack_push(&mut self.store.value_stack, size)?, + false => i32::stack_push(&mut self.store.value_stack, size as i32)?, }; Ok(()) } - fn exec_memory_copy(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: dst_mem, second: src_mem } = index.get(&self.func.data); + fn exec_memory_copy(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let dst_mem = operand.a(); + let src_mem = operand.b(); let dst_mem_addr = self.mem_addr(dst_mem); let src_mem_addr = self.mem_addr(src_mem); let dst_arch = self.store.state.get_mem(dst_mem_addr).kind.arch(); @@ -1720,12 +2004,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { self.exec_memory_fill_impl(mem_addr, dst, val as u8, size) } - fn exec_memory_fill_const(&mut self, index: OperandIdx) -> Result<(), Trap> { - let MemoryFillConstOp { memory: addr, byte: val, value: size } = index.get(&self.func.data); - let mem_addr = self.mem_addr(addr); + fn exec_memory_fill_const(&mut self, index: Operand128Idx) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let mem_addr = self.mem_addr(operand.memory()); let arch = self.store.state.get_mem(mem_addr).kind.arch(); let dst = self.store.value_stack.pop_memory_operand(arch)?; - self.exec_memory_fill_impl(mem_addr, dst, val, size as u32 as usize) + self.exec_memory_fill_impl(mem_addr, dst, operand.byte(), operand.value() as u32 as usize) } fn exec_memory_fill_impl(&mut self, mem_addr: MemAddr, dst: usize, val: u8, size: usize) -> Result<(), Trap> { @@ -1737,8 +2021,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_memory_init(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: data_index, second: mem_index } = index.get(&self.func.data); + fn exec_memory_init(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let data_index = operand.a(); + let mem_index = operand.b(); let size = u32::stack_pop(&mut self.store.value_stack) as usize; let offset = u32::stack_pop(&mut self.store.value_stack) as usize; let mem_addr = self.mem_addr(mem_index); @@ -1770,8 +2056,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_table_copy(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: dst_table, second: src_table } = index.get(&self.func.data); + fn exec_table_copy(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let dst_table = operand.a(); + let src_table = operand.b(); let dst_table_addr = self.module.resolve_table_addr(dst_table); let src_table_addr = self.module.resolve_table_addr(src_table); let dst_arch = self.store.state.get_table(dst_table_addr).kind.arch(); @@ -1796,13 +2084,13 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { &mut self, arg: MemoryLaneArg, ) -> Result<(), Trap> { - let m = arg.memory_arg_idx.get(&self.func.data); - let mem = self.store.state.get_mem(self.mem_addr(m.mem_addr())); + let m = arg.memory_arg_idx.resolve(&self.func.data); + let mem = self.store.state.get_mem(self.mem_addr(m.memory())); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, m.offset())?; + let addr = cold_err!(mem.effective_addr::(base, m.offset()))?; let val = cold_err!(LOAD::load_at(&mem.inner, addr))?; let offset = arg.lane as usize * LOAD_SIZE; - let mut imm = ::stack_pop(&mut self.store.value_stack).to_mem_bytes(); + let mut imm = Value128::stack_pop(&mut self.store.value_stack).to_mem_bytes(); imm[offset..offset + LOAD_SIZE].copy_from_slice(&val.to_mem_bytes()); self.store.value_stack.push(Value128(imm))?; Ok(()) @@ -1811,47 +2099,65 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { #[inline(always)] fn exec_mem_load, const LOAD_SIZE: usize, TARGET: InternalValue>( &mut self, - index: OperandIdx, + m: Operand128, cast: impl Fn(LOAD) -> TARGET, ) -> Result<(), Trap> { - let m = index.get(&self.func.data); - let mem = self.store.state.get_mem(self.mem_addr(m.mem_addr())); + let mem = self.store.state.get_mem(self.mem_addr(m.memory())); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, m.offset())?; + let addr = cold_err!(mem.effective_addr::(base, m.offset()))?; let value = cold_err!(LOAD::load_at(&mem.inner, addr))?; self.store.value_stack.push(cast(value)) } + #[inline(always)] fn exec_mem_store_lane + Copy, const N: usize>(&mut self, arg: MemoryLaneArg) -> Result<(), Trap> { - let bytes = ::stack_pop(&mut self.store.value_stack).to_mem_bytes(); + let bytes = Value128::stack_pop(&mut self.store.value_stack).to_mem_bytes(); let lane_offset = arg.lane as usize * N; let mut val_bytes = [0u8; N]; val_bytes.copy_from_slice(&bytes[lane_offset..lane_offset + N]); let val = U::from_mem_bytes(val_bytes); - let m = arg.memory_arg_idx.get(&self.func.data); - let mem_addr = self.mem_addr(m.mem_addr()); + let m = arg.memory_arg_idx.resolve(&self.func.data); + let mem_addr = self.mem_addr(m.memory()); let mem = self.store.state.get_mem_mut(mem_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, m.offset())?; + let addr = cold_err!(mem.effective_addr::(base, m.offset()))?; cold_err!(val.store_at(&mut mem.inner, addr))?; Ok(()) } + #[inline(always)] fn exec_mem_store, const N: usize>( &mut self, - index: OperandIdx, + memory: Operand128, cast: impl Fn(T) -> U, ) -> Result<(), Trap> { - let val = ::stack_pop(&mut self.store.value_stack); - let val = cast(val); + let val = cast(::stack_pop(&mut self.store.value_stack)); + self.exec_mem_store_value(self.mem_addr(memory.memory()), memory.offset(), val) + } - let m = index.get(&self.func.data); - let mem_addr = self.mem_addr(m.mem_addr()); - let mem = self.store.state.get_mem_mut(mem_addr); + #[inline(always)] + fn exec_select_store, const N: usize>( + &mut self, + memory: Operand128, + ) -> Result<(), Trap> { + let condition = Value32::stack_pop(&mut self.store.value_stack); + let false_value = T::stack_pop(&mut self.store.value_stack); + let true_value = T::stack_pop(&mut self.store.value_stack); + let value = if condition == 0 { false_value } else { true_value }; + self.exec_mem_store_value(self.mem_addr(memory.memory()), memory.offset(), value) + } + + #[inline(always)] + fn exec_mem_store_value, const N: usize>( + &mut self, + memory_addr: MemAddr, + offset: u64, + val: U, + ) -> Result<(), Trap> { + let mem = self.store.state.get_mem_mut(memory_addr); let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?; - let addr = mem.effective_addr::(base, m.offset())?; - cold_err!(val.store_at(&mut mem.inner, addr))?; - Ok(()) + let addr = cold_err!(mem.effective_addr::(base, offset))?; + cold_err!(val.store_at(&mut mem.inner, addr)) } fn exec_table_get(&mut self, table_index: u32) -> Result<(), Trap> { @@ -1862,7 +2168,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } fn exec_table_set(&mut self, table_index: u32) -> Result<(), Trap> { - let val = ::stack_pop(&mut self.store.value_stack); + let val = ValueRef::stack_pop(&mut self.store.value_stack); let table_addr = self.module.resolve_table_addr(table_index); let idx = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?; let table = self.store.state.get_table_mut(table_addr); @@ -1877,8 +2183,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { } } - fn exec_table_init(&mut self, index: OperandIdx) -> Result<(), Trap> { - let TwoU32 { first: elem_index, second: table_index } = index.get(&self.func.data); + fn exec_table_init(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> { + let operand = index.resolve(&self.func.data); + let elem_index = operand.a(); + let table_index = operand.b(); let size = self.pop_table_operand(MemoryArch::I32)?; // n let offset = self.pop_table_operand(MemoryArch::I32)?; // s let table_addr = self.module.resolve_table_addr(table_index); @@ -1896,7 +2204,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let table_addr = self.module.resolve_table_addr(table_index); let arch = self.store.state.get_table(table_addr).kind.arch(); let n = self.pop_table_operand(arch)?; - let val = ::stack_pop(&mut self.store.value_stack); + let val = ValueRef::stack_pop(&mut self.store.value_stack); let limiter = self.store.engine.config().resource_limiter.as_deref(); let table = self.store.state.get_table_mut(table_addr); let sz = table.size(); @@ -1913,15 +2221,15 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let table_addr = self.module.resolve_table_addr(table_index); let arch = self.store.state.get_table(table_addr).kind.arch(); let n = self.pop_table_operand(arch)?; - let val = ::stack_pop(&mut self.store.value_stack); + let val = ValueRef::stack_pop(&mut self.store.value_stack); let i = self.pop_table_operand(arch)?; self.store.state.get_table_mut(table_addr).fill(i, n, val) } fn pop_table_operand(&mut self, arch: MemoryArch) -> Result { let value = match arch { - MemoryArch::I32 => ::stack_pop(&mut self.store.value_stack) as u32 as u64, - MemoryArch::I64 => ::stack_pop(&mut self.store.value_stack) as u64, + MemoryArch::I32 => i32::stack_pop(&mut self.store.value_stack) as u32 as u64, + MemoryArch::I64 => i64::stack_pop(&mut self.store.value_stack) as u64, }; cold_err!(usize::try_from(value).map_err(|_| Trap::TableOutOfBounds { offset: usize::MAX, @@ -1994,92 +2302,3 @@ impl<'store> Executor<'store, true> { } } } - -#[inline(always)] -fn cmp_i32(lhs: i32, rhs: i32, op: CmpOp) -> bool { - match op { - CmpOp::Eq => lhs == rhs, - CmpOp::Ne => lhs != rhs, - CmpOp::LtS => lhs < rhs, - CmpOp::LtU => (lhs as u32) < (rhs as u32), - CmpOp::GtS => lhs > rhs, - CmpOp::GtU => (lhs as u32) > (rhs as u32), - CmpOp::LeS => lhs <= rhs, - CmpOp::LeU => (lhs as u32) <= (rhs as u32), - CmpOp::GeS => lhs >= rhs, - CmpOp::GeU => (lhs as u32) >= (rhs as u32), - } -} - -#[inline(always)] -fn cmp_i64(lhs: i64, rhs: i64, op: CmpOp) -> bool { - match op { - CmpOp::Eq => lhs == rhs, - CmpOp::Ne => lhs != rhs, - CmpOp::LtS => lhs < rhs, - CmpOp::LtU => (lhs as u64) < (rhs as u64), - CmpOp::GtS => lhs > rhs, - CmpOp::GtU => (lhs as u64) > (rhs as u64), - CmpOp::LeS => lhs <= rhs, - CmpOp::LeU => (lhs as u64) <= (rhs as u64), - CmpOp::GeS => lhs >= rhs, - CmpOp::GeU => (lhs as u64) >= (rhs as u64), - } -} - -fn exec_binop_32(op: BinOp, lhs: u32, rhs: u32) -> u32 { - match op { - BinOp::IAdd => lhs.wrapping_add(rhs), - BinOp::ISub => lhs.wrapping_sub(rhs), - BinOp::IMul => lhs.wrapping_mul(rhs), - BinOp::IAnd => lhs & rhs, - BinOp::IOr => lhs | rhs, - BinOp::IXor => lhs ^ rhs, - BinOp::IShl => (lhs as i32).wrapping_shl(rhs) as u32, - BinOp::IShrS => (lhs as i32).wrapping_shr(rhs) as u32, - BinOp::IShrU => lhs.wrapping_shr(rhs), - BinOp::IRotl => (lhs as i32).rotate_left(rhs) as u32, - BinOp::IRotr => (lhs as i32).rotate_right(rhs) as u32, - BinOp::FAdd => (f32::from_bits(lhs) + f32::from_bits(rhs)).to_bits(), - BinOp::FSub => (f32::from_bits(lhs) - f32::from_bits(rhs)).to_bits(), - BinOp::FMul => (f32::from_bits(lhs) * f32::from_bits(rhs)).to_bits(), - BinOp::FDiv => (f32::from_bits(lhs) / f32::from_bits(rhs)).to_bits(), - BinOp::FMin => f32::from_bits(lhs).tw_minimum(f32::from_bits(rhs)).to_bits(), - BinOp::FMax => f32::from_bits(lhs).tw_maximum(f32::from_bits(rhs)).to_bits(), - BinOp::FCopysign => f32::from_bits(lhs).copysign(f32::from_bits(rhs)).to_bits(), - } -} - -fn exec_binop_64(op: BinOp, lhs: u64, rhs: u64) -> u64 { - match op { - BinOp::IAdd => lhs.wrapping_add(rhs), - BinOp::ISub => lhs.wrapping_sub(rhs), - BinOp::IMul => lhs.wrapping_mul(rhs), - BinOp::IAnd => lhs & rhs, - BinOp::IOr => lhs | rhs, - BinOp::IXor => lhs ^ rhs, - BinOp::IShl => (lhs as i64).wrapping_shl(rhs as u32) as u64, - BinOp::IShrS => (lhs as i64).wrapping_shr(rhs as u32) as u64, - BinOp::IShrU => lhs.wrapping_shr(rhs as u32), - BinOp::IRotl => (lhs as i64).rotate_left(rhs as u32) as u64, - BinOp::IRotr => (lhs as i64).rotate_right(rhs as u32) as u64, - BinOp::FAdd => (f64::from_bits(lhs) + f64::from_bits(rhs)).to_bits(), - BinOp::FSub => (f64::from_bits(lhs) - f64::from_bits(rhs)).to_bits(), - BinOp::FMul => (f64::from_bits(lhs) * f64::from_bits(rhs)).to_bits(), - BinOp::FDiv => (f64::from_bits(lhs) / f64::from_bits(rhs)).to_bits(), - BinOp::FMin => f64::from_bits(lhs).tw_minimum(f64::from_bits(rhs)).to_bits(), - BinOp::FMax => f64::from_bits(lhs).tw_maximum(f64::from_bits(rhs)).to_bits(), - BinOp::FCopysign => f64::from_bits(lhs).copysign(f64::from_bits(rhs)).to_bits(), - } -} - -fn exec_binop_128(op: BinOp128, lhs: Value128, rhs: Value128) -> Value128 { - match op { - BinOp128::And => lhs.v128_and(rhs), - BinOp128::AndNot => lhs.v128_andnot(rhs), - BinOp128::Or => lhs.v128_or(rhs), - BinOp128::Xor => lhs.v128_xor(rhs), - BinOp128::I64x2Add => lhs.i64x2_add(rhs), - BinOp128::I64x2Mul => lhs.i64x2_mul(rhs), - } -} diff --git a/crates/tinywasm/src/interpreter/num_helpers.rs b/crates/tinywasm/src/interpreter/num_helpers.rs index 783b10b..d35b217 100644 --- a/crates/tinywasm/src/interpreter/num_helpers.rs +++ b/crates/tinywasm/src/interpreter/num_helpers.rs @@ -7,25 +7,22 @@ pub(crate) trait TinywasmIntExt: Sized { /// we need to check for overflow. This macro generates the min/max values /// for a specific conversion, which are then used in the actual conversion. /// Rust sadly doesn't have wrapping casts for floats yet. -#[rustfmt::skip] macro_rules! float_min_max { - (f32, i32) => {(i32::MIN as f32 - (1 << 8) as f32, i32::MAX as f32 + 1.0)}; // 2^8: f32 precision margin - (f64, i32) => {(i32::MIN as f64 - 1.0, i32::MAX as f64 + 1.0)}; - (f32, u32) => {(-1.0_f32, u32::MAX as f32 + 1.0)}; - (f64, u32) => {(-1.0_f64, u32::MAX as f64 + 1.0)}; - (f32, i64) => {(i64::MIN as f32 - (1i64 << 40) as f32, i64::MAX as f32 + 1.0)}; // 2^40: f32 has 23 mantissa bits - (f64, i64) => {(i64::MIN as f64 - (1i64 << 11) as f64, i64::MAX as f64 + 1.0)}; // 2^11: f64 precision margin - (f32, u64) => {(-1.0_f32, u64::MAX as f32 + 1.0)}; - (f64, u64) => {(-1.0_f64, u64::MAX as f64 + 1.0)}; - ($from:ty, $to:ty) => {compile_error!("invalid float conversion")}; + (f32, i32) => {{ (i32::MIN as f32 - (1 << 8) as f32, i32::MAX as f32 + 1.0) }}; // 2^8: f32 precision margin + (f64, i32) => {{ (i32::MIN as f64 - 1.0, i32::MAX as f64 + 1.0) }}; + (f32, u32) => {{ (-1.0_f32, u32::MAX as f32 + 1.0) }}; + (f64, u32) => {{ (-1.0_f64, u32::MAX as f64 + 1.0) }}; + (f32, i64) => {{ (i64::MIN as f32 - (1i64 << 40) as f32, i64::MAX as f32 + 1.0) }}; // 2^40: f32 has 23 mantissa bits + (f64, i64) => {{ (i64::MIN as f64 - (1i64 << 11) as f64, i64::MAX as f64 + 1.0) }}; // 2^11: f64 precision margin + (f32, u64) => {{ (-1.0_f32, u64::MAX as f32 + 1.0) }}; + (f64, u64) => {{ (-1.0_f64, u64::MAX as f64 + 1.0) }}; + ($from:ty, $to:ty) => {{ compile_error!("invalid float conversion") }}; } /// Convert a value on the stack with error checking macro_rules! checked_conv_float { // Direct conversion with error checking (two types) - ($from:tt, $to:tt, $self:expr) => { - checked_conv_float!($from, $to, $to, $self) - }; + ($from:tt, $to:tt, $self:expr) => {{ checked_conv_float!($from, $to, $to, $self) }}; // Conversion with an intermediate unsigned type and error checking (three types) ($from:tt, $intermediate:tt, $to:tt, $self:expr) => {{ let v = <$from>::stack_pop(&mut $self.store.value_stack); diff --git a/crates/tinywasm/src/interpreter/simd/macros.rs b/crates/tinywasm/src/interpreter/simd/macros.rs index bc7b805..9306d8f 100644 --- a/crates/tinywasm/src/interpreter/simd/macros.rs +++ b/crates/tinywasm/src/interpreter/simd/macros.rs @@ -183,18 +183,17 @@ macro_rules! lane_read { (f64, $bytes:expr, $offset:expr) => { f64::from_bits(u64::from_le_bytes([$bytes[$offset], $bytes[$offset + 1], $bytes[$offset + 2], $bytes[$offset + 3], $bytes[$offset + 4], $bytes[$offset + 5], $bytes[$offset + 6], $bytes[$offset + 7]])) }; } -#[rustfmt::skip] macro_rules! lane_write { - (i8, $value:expr) => { [$value as u8] }; - (u8, $value:expr) => { [$value] }; - (i16, $value:expr) => { $value.to_le_bytes() }; - (u16, $value:expr) => { $value.to_le_bytes() }; - (i32, $value:expr) => { $value.to_le_bytes() }; - (u32, $value:expr) => { $value.to_le_bytes() }; - (i64, $value:expr) => { $value.to_le_bytes() }; - (u64, $value:expr) => { $value.to_le_bytes() }; - (f32, $value:expr) => { $value.to_bits().to_le_bytes() }; - (f64, $value:expr) => { $value.to_bits().to_le_bytes() }; + (i8, $value:expr) => {{ [$value as u8] }}; + (u8, $value:expr) => {{ [$value] }}; + (i16, $value:expr) => {{ $value.to_le_bytes() }}; + (u16, $value:expr) => {{ $value.to_le_bytes() }}; + (i32, $value:expr) => {{ $value.to_le_bytes() }}; + (u32, $value:expr) => {{ $value.to_le_bytes() }}; + (i64, $value:expr) => {{ $value.to_le_bytes() }}; + (u64, $value:expr) => {{ $value.to_le_bytes() }}; + (f32, $value:expr) => {{ $value.to_bits().to_le_bytes() }}; + (f64, $value:expr) => {{ $value.to_bits().to_le_bytes() }}; } macro_rules! impl_lane_accessors { diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index e123a41..3748ef9 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -62,12 +62,12 @@ impl Stack { #[inline(always)] pub(crate) fn pop(&mut self) -> T { - self.data.pop().unwrap_or_else(|| unreachable!("ValueStack underflow, this is a bug")) + unwrap_or_unreachable!(self.data.pop(), "ValueStack underflow, this is a bug") } #[inline(always)] pub(crate) fn last(&self) -> &T { - self.data.last().unwrap_or_else(|| unreachable!("ValueStack underflow, this is a bug")) + unwrap_or_unreachable!(self.data.last(), "ValueStack underflow, this is a bug") } #[inline(always)] @@ -107,7 +107,7 @@ impl Stack { #[inline(always)] pub(crate) fn truncate_to_one_tail(&mut self, n: usize) { debug_assert!(n < self.data.len()); - let last = self.data.pop().unwrap_or_else(|| unreachable!("ValueStack underflow, this is a bug")); + let last = unwrap_or_unreachable!(self.data.pop(), "ValueStack underflow, this is a bug"); self.data.truncate(n); self.data.push(last); } @@ -164,7 +164,7 @@ impl Stack { } let len = self.data.len(); - let needed = count.checked_mul(2).unwrap_or_else(|| unreachable!("Stack underflow, this is a bug")); + let needed = unwrap_or_unreachable!(count.checked_mul(2), "Stack underflow, this is a bug"); if len < needed { unreachable!("Stack underflow, this is a bug"); diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs index 22f20b7..83b520b 100644 --- a/crates/tinywasm/src/interpreter/values.rs +++ b/crates/tinywasm/src/interpreter/values.rs @@ -1,7 +1,8 @@ +use super::num_helpers::TinywasmFloatExt; use super::stack::{CallFrame, ValueStack}; use crate::store::Globals; use crate::{Error, Result, Store, WasmValue, interpreter::simd::Value128}; -use tinywasm_types::{GlobalAddr, LocalAddr, WasmType}; +use tinywasm_types::{BinOp, BinOp128, CmpOp, GlobalAddr, LocalAddr, WasmType}; pub(crate) type Value32 = u32; pub(crate) type Value64 = u64; @@ -114,14 +115,24 @@ pub(crate) trait InternalValue: sealed::Sealed + Copy + Default { fn stack_push(stack: &mut ValueStack, value: Self) -> Result<(), crate::Trap>; fn stack_pop(stack: &mut ValueStack) -> Self; fn stack_peek(stack: &ValueStack) -> Self; + fn stack_update(stack: &mut ValueStack, f: impl FnOnce(Self) -> Self) -> Result { + let value = f(Self::stack_pop(stack)); + Self::stack_push(stack, value)?; + Ok(value) + } fn stack_select(stack: &mut ValueStack); fn local_get(stack: &ValueStack, frame: &CallFrame, index: LocalAddr) -> Self; fn local_push(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr) -> Result<(), crate::Trap>; fn local_set(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, value: Self); - fn local_update(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, f: impl FnOnce(Self) -> Self); + fn local_update(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, f: impl FnOnce(Self) -> Self) -> Self; fn local_copy(stack: &mut ValueStack, frame: &CallFrame, from: LocalAddr, to: LocalAddr); fn global_get(globals: &Globals, addr: GlobalAddr) -> Self; fn global_set(globals: &mut Globals, addr: GlobalAddr, value: Self); + fn global_update(globals: &mut Globals, addr: GlobalAddr, f: impl FnOnce(Self) -> Self) -> Self { + let value = f(Self::global_get(globals, addr)); + Self::global_set(globals, addr, value); + value + } } macro_rules! impl_internalvalue { @@ -136,13 +147,6 @@ macro_rules! impl_internalvalue { impl sealed::Sealed for $outer {} impl InternalValue for $outer { - #[inline(always)] - fn stack_push(stack: &mut ValueStack, value: Self) -> Result<(), crate::Trap> { - let $to_stack_v = value; - cold_err!(stack.$stack.push($to_stack))?; - Ok(()) - } - #[inline(always)] fn local_get(stack: &ValueStack, frame: &CallFrame, index: LocalAddr) -> Self { let $from_stack_v = @@ -168,11 +172,13 @@ macro_rules! impl_internalvalue { frame: &CallFrame, index: LocalAddr, f: impl FnOnce(Self) -> Self, - ) { + ) -> Self { let abs_index = frame.locals_base.$stack_base.wrapping_add(u32::from(index)) as usize; let $from_stack_v = *stack.$stack.get(abs_index); - let $to_stack_v = f($from_stack); + let value = f($from_stack); + let $to_stack_v = value; stack.$stack.set(abs_index, $to_stack); + value } #[inline(always)] @@ -194,6 +200,13 @@ macro_rules! impl_internalvalue { globals.$global_set(addr, $to_stack); } + #[inline(always)] + fn stack_push(stack: &mut ValueStack, value: Self) -> Result<(), crate::Trap> { + let $to_stack_v = value; + cold_err!(stack.$stack.push($to_stack))?; + Ok(()) + } + #[inline(always)] fn stack_pop(stack: &mut ValueStack) -> Self { let $from_stack_v = stack.$stack.pop(); @@ -232,6 +245,105 @@ impl_internalvalue! { stack_128, s128, get_128, set_128, Value128, |v| v, |v| v } +pub(crate) trait BinOpExt: Copy { + fn exec(self, lhs: T, rhs: T) -> T; +} + +impl BinOpExt for BinOp { + #[inline(always)] + fn exec(self, lhs: Value32, rhs: Value32) -> Value32 { + match self { + BinOp::IAdd => lhs.wrapping_add(rhs), + BinOp::ISub => lhs.wrapping_sub(rhs), + BinOp::IMul => lhs.wrapping_mul(rhs), + BinOp::IAnd => lhs & rhs, + BinOp::IOr => lhs | rhs, + BinOp::IXor => lhs ^ rhs, + BinOp::IShl => (lhs as i32).wrapping_shl(rhs) as u32, + BinOp::IShrS => (lhs as i32).wrapping_shr(rhs) as u32, + BinOp::IShrU => lhs.wrapping_shr(rhs), + BinOp::IRotl => (lhs as i32).rotate_left(rhs) as u32, + BinOp::IRotr => (lhs as i32).rotate_right(rhs) as u32, + BinOp::FAdd => (f32::from_bits(lhs) + f32::from_bits(rhs)).to_bits(), + BinOp::FSub => (f32::from_bits(lhs) - f32::from_bits(rhs)).to_bits(), + BinOp::FMul => (f32::from_bits(lhs) * f32::from_bits(rhs)).to_bits(), + BinOp::FDiv => (f32::from_bits(lhs) / f32::from_bits(rhs)).to_bits(), + BinOp::FMin => f32::from_bits(lhs).tw_minimum(f32::from_bits(rhs)).to_bits(), + BinOp::FMax => f32::from_bits(lhs).tw_maximum(f32::from_bits(rhs)).to_bits(), + BinOp::FCopysign => f32::from_bits(lhs).copysign(f32::from_bits(rhs)).to_bits(), + } + } +} + +impl BinOpExt for BinOp { + #[inline(always)] + fn exec(self, lhs: Value64, rhs: Value64) -> Value64 { + match self { + BinOp::IAdd => lhs.wrapping_add(rhs), + BinOp::ISub => lhs.wrapping_sub(rhs), + BinOp::IMul => lhs.wrapping_mul(rhs), + BinOp::IAnd => lhs & rhs, + BinOp::IOr => lhs | rhs, + BinOp::IXor => lhs ^ rhs, + BinOp::IShl => (lhs as i64).wrapping_shl(rhs as u32) as u64, + BinOp::IShrS => (lhs as i64).wrapping_shr(rhs as u32) as u64, + BinOp::IShrU => lhs.wrapping_shr(rhs as u32), + BinOp::IRotl => (lhs as i64).rotate_left(rhs as u32) as u64, + BinOp::IRotr => (lhs as i64).rotate_right(rhs as u32) as u64, + BinOp::FAdd => (f64::from_bits(lhs) + f64::from_bits(rhs)).to_bits(), + BinOp::FSub => (f64::from_bits(lhs) - f64::from_bits(rhs)).to_bits(), + BinOp::FMul => (f64::from_bits(lhs) * f64::from_bits(rhs)).to_bits(), + BinOp::FDiv => (f64::from_bits(lhs) / f64::from_bits(rhs)).to_bits(), + BinOp::FMin => f64::from_bits(lhs).tw_minimum(f64::from_bits(rhs)).to_bits(), + BinOp::FMax => f64::from_bits(lhs).tw_maximum(f64::from_bits(rhs)).to_bits(), + BinOp::FCopysign => f64::from_bits(lhs).copysign(f64::from_bits(rhs)).to_bits(), + } + } +} + +impl BinOpExt for BinOp128 { + #[inline(always)] + fn exec(self, lhs: Value128, rhs: Value128) -> Value128 { + match self { + BinOp128::And => lhs.v128_and(rhs), + BinOp128::AndNot => lhs.v128_andnot(rhs), + BinOp128::Or => lhs.v128_or(rhs), + BinOp128::Xor => lhs.v128_xor(rhs), + BinOp128::I64x2Add => lhs.i64x2_add(rhs), + BinOp128::I64x2Mul => lhs.i64x2_mul(rhs), + } + } +} + +pub(crate) trait CmpOpExt: Copy { + fn cmp(self, lhs: T, rhs: T) -> bool; +} + +macro_rules! impl_cmp_value { + ($ty:ty, $unsigned:ty) => { + impl CmpOpExt<$ty> for CmpOp { + #[inline(always)] + fn cmp(self, lhs: $ty, rhs: $ty) -> bool { + match self { + CmpOp::Eq => lhs == rhs, + CmpOp::Ne => lhs != rhs, + CmpOp::LtS => lhs < rhs, + CmpOp::LtU => (lhs as $unsigned) < (rhs as $unsigned), + CmpOp::GtS => lhs > rhs, + CmpOp::GtU => (lhs as $unsigned) > (rhs as $unsigned), + CmpOp::LeS => lhs <= rhs, + CmpOp::LeU => (lhs as $unsigned) <= (rhs as $unsigned), + CmpOp::GeS => lhs >= rhs, + CmpOp::GeU => (lhs as $unsigned) >= (rhs as $unsigned), + } + } + } + }; +} + +impl_cmp_value!(i32, u32); +impl_cmp_value!(i64, u64); + #[cfg(test)] mod tests { use super::ValueRef; diff --git a/crates/tinywasm/src/macros.rs b/crates/tinywasm/src/macros.rs index 351ae88..b071259 100644 --- a/crates/tinywasm/src/macros.rs +++ b/crates/tinywasm/src/macros.rs @@ -16,3 +16,21 @@ macro_rules! cold_err { } }; } + +macro_rules! unwrap_or_unreachable { + ($value:expr) => {{ + unwrap_or_unreachable!($value, "entered unreachable code") + }}; + ($value:expr, $($message:tt)+) => {{ + match $value { + Some(value) => value, + None => $crate::macros::unwrap_unreachable(format_args!($($message)+)), + } + }}; +} + +#[cold] +#[inline(never)] +pub(crate) fn unwrap_unreachable(message: core::fmt::Arguments<'_>) -> ! { + unreachable!("{message}") +} diff --git a/crates/tinywasm/src/store/global.rs b/crates/tinywasm/src/store/global.rs index 4052eb8..42a2acf 100644 --- a/crates/tinywasm/src/store/global.rs +++ b/crates/tinywasm/src/store/global.rs @@ -30,16 +30,16 @@ impl GlobalLane { #[inline(always)] fn get(&self, index: usize, addr: GlobalAddr) -> T { - *self.values.get(index).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) + *unwrap_or_unreachable!(self.values.get(index), "invalid global address: {addr}") } #[inline(always)] fn set(&mut self, index: usize, addr: GlobalAddr, value: T) { - *self.values.get_mut(index).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) = value; + *unwrap_or_unreachable!(self.values.get_mut(index), "invalid global address: {addr}") = value; } fn ty(&self, index: usize, addr: GlobalAddr) -> GlobalType { - *self.types.get(index).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) + *unwrap_or_unreachable!(self.types.get(index), "invalid global address: {addr}") } } diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 93e62a5..d4c8b15 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -489,15 +489,14 @@ impl Store { } /// Reads typed results from the value stack and restores its previous base. + #[inline] pub(crate) fn take_typed_results( &mut self, type_addr: TypeAddr, stack_base: StackBase, ) -> Result { - let result = { - let mut values = self.stack_value_iter(type_addr, FuncValueTypes::Results, stack_base)?; - R::from_wasm_values_exact(&mut values) - }; + let mut values = cold_err!(self.stack_value_iter(type_addr, FuncValueTypes::Results, stack_base))?; + let result = cold_err!(R::from_wasm_values_exact(&mut values)); self.value_stack.truncate_to_base(stack_base); result } diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index 769fc8b..49efcdc 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -284,11 +284,11 @@ impl State { } pub(super) fn get<'a, T>(items: &'a [T], addr: Addr, kind: &str) -> &'a T { - items.get(addr as usize).unwrap_or_else(|| unreachable!("invalid {kind} address: {addr}")) + unwrap_or_unreachable!(items.get(addr as usize), "invalid {kind} address: {addr}") } fn get_mut<'a, T>(items: &'a mut [T], addr: Addr, kind: &str) -> &'a mut T { - items.get_mut(addr as usize).unwrap_or_else(|| unreachable!("invalid {kind} address: {addr}")) + unwrap_or_unreachable!(items.get_mut(addr as usize), "invalid {kind} address: {addr}") } fn get_disjoint_mut<'a, T>(items: &'a mut [T], addr: Addr, addr2: Addr, kind: &str) -> (&'a mut T, &'a mut T) { diff --git a/crates/types/src/archive.rs b/crates/types/src/archive.rs index db13ab0..bdce379 100644 --- a/crates/types/src/archive.rs +++ b/crates/types/src/archive.rs @@ -64,11 +64,11 @@ impl Module { #[cfg(test)] mod tests { use super::*; + use crate::Operand128Idx; use crate::{ - AbstractHeapType, ConstInstruction, Global, GlobalType, Instruction, ModuleFuncIdx, ModuleInner, RefType, - Shared, V128Operand, WasmFunction, WasmType, + AbstractHeapType, ConstInstruction, Global, GlobalType, Instruction, ModuleFuncIdx, ModuleInner, Operand128, + RefType, Shared, WasmFunction, WasmType, }; - use crate::{OperandIdx, OperandType}; use alloc::boxed::Box; #[test] @@ -91,8 +91,8 @@ mod tests { fn v128_operands_round_trip_archive() { let bytes = [0x00, 0x01, 0x02, 0x03, 0x7f, 0x80, 0xfe, 0xff, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x90]; let mut function = WasmFunction::default(); - let constant = OperandIdx::new(0); - function.data.operands128 = Box::new([V128Operand { value: bytes }.encode()]); + let constant = Operand128Idx::new(0); + function.data.operands128 = Box::new([Operand128::<[u8; 16]>::new(bytes).cast()]); function.instructions = Box::new([Instruction::Const128(constant), Instruction::I8x16Shuffle(constant)]); let module = Module::from(ModuleInner { funcs: Box::new([Shared::new(function)]), ..ModuleInner::default() }); @@ -106,7 +106,7 @@ mod tests { Instruction::Const128(index) | Instruction::I8x16Shuffle(index) => *index, _ => panic!("unexpected instruction"), }; - assert_eq!(index.get(&function.data).value, bytes); + assert_eq!(index.resolve(&function.data).value(), bytes); } } diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index 7e0cd28..9330af6 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -1,18 +1,31 @@ use alloc::boxed::Box; use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TagAddr, TypeAddr, ValueCounts}; -use crate::operands::sealed; -use crate::{DataAddr, ElemAddr, MemAddr, ModuleFuncIdx, Operand64, Operand128, OperandIdx, OperandType, RefType}; +use crate::operands::read_field; +use crate::{ + DataAddr, ElemAddr, MemAddr, ModuleFuncIdx, Operand64, Operand64Idx, Operand128, Operand128Idx, OperandIdx, RefType, +}; -/// Represents a memory immediate in a WebAssembly memory instruction. -#[derive(Copy, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] -#[repr(Rust, packed)] -pub struct MemoryArg { - offset: u64, - mem_addr: MemAddr, -} +/// Identifies the packed full-width memory operand layout. +pub enum MemoryOperand {} + +/// Identifies the packed compact memory operand layout. +pub enum CompactMemoryOperand {} + +/// Identifies a packed branch-table operand. +pub enum BranchTableOperand {} + +/// Identifies a packed constant memory-fill operand. +pub enum MemoryFillOperand {} + +/// Identifies a packed local update and branch operand. +pub enum LocalUpdateOperand {} + +/// Identifies a packed global update and branch operand. +pub enum GlobalUpdateOperand {} + +/// Identifies a packed local update, comparison, and branch operand. +pub enum LocalUpdateCmpOperand {} /// A compact memory immediate used by optimized instructions. /// @@ -33,7 +46,7 @@ pub struct CompactMemoryArg { #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] #[repr(Rust, packed)] pub struct MemoryLocalArg { - pub memory_arg_idx: OperandIdx, + pub memory_arg_idx: Operand64Idx, pub local1: u8, pub local2: u8, } @@ -44,7 +57,7 @@ pub struct MemoryLocalArg { #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] #[repr(Rust, packed)] pub struct MemoryLaneArg { - pub memory_arg_idx: OperandIdx, + pub memory_arg_idx: Operand128Idx, pub lane: u8, } @@ -68,22 +81,6 @@ pub struct LocalTripleArg { pub dst: LocalAddr, } -impl sealed::Sealed for LocalTripleArg {} - -impl OperandType for LocalTripleArg { - type Raw = Operand64; - - #[inline(always)] - fn decode(raw: Self::Raw) -> Self { - Self { left: raw.u16::<0>(), right: raw.u16::<2>(), dst: raw.u16::<4>() } - } - - #[inline] - fn encode(self) -> Self::Raw { - Operand64::default().with_u16::<0>(self.left).with_u16::<2>(self.right).with_u16::<4>(self.dst) - } -} - /// A branch target and local operand that fit in an instruction payload. #[derive(Copy, Clone, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] @@ -94,194 +91,55 @@ pub struct TargetLocalArg { pub local: LocalAddr, } -macro_rules! operand_view { - ($name:ident, $lane:ident, $raw:ty, { $($field:ident : $ty:ty = $read:ident / $write:ident ($offset:expr)),+ $(,)? }) => { - #[derive(Copy, Clone, PartialEq, Eq)] - #[cfg_attr(feature = "debug", derive(Debug))] - pub struct $name { - $(pub $field: $ty),+ - } - - impl sealed::Sealed for $name {} - - impl OperandType for $name { - type Raw = $raw; - - #[inline(always)] - fn decode(raw: Self::Raw) -> Self { - Self { $($field: raw.$read::<$offset>() as $ty),+ } - } - - #[inline] - fn encode(self) -> Self::Raw { - <$raw>::default()$(.$write::<$offset>(self.$field as _))+ - } - } - }; -} - -operand_view!(I64Operand, operands64, Operand64, { value: i64 = u64 / with_u64(0) }); -operand_view!(TwoU32, operands64, Operand64, { - first: u32 = u32 / with_u32(0), second: u32 = u32 / with_u32(4) -}); -operand_view!(LocalU32, operands64, Operand64, { - local: u16 = u16 / with_u16(0), value: u32 = u32 / with_u32(2) -}); -operand_view!(TargetLocal, operands64, Operand64, { - target: u32 = u32 / with_u32(0), local: u16 = u16 / with_u16(4) -}); - -operand_view!(LocalConst64, operands128, Operand128, { - local: u16 = u16 / with_u16(0), value: u64 = u64 / with_u64(2) -}); -operand_view!(GlobalConst32, operands64, Operand64, { - global: u32 = u32 / with_u32(0), value: u32 = u32 / with_u32(4) -}); -operand_view!(GlobalConst64, operands128, Operand128, { - global: u32 = u32 / with_u32(0), value: u64 = u64 / with_u64(4) -}); -operand_view!(LocalConstSet32, operands64, Operand64, { - local: u16 = u16 / with_u16(0), dst: u16 = u16 / with_u16(2), value: u32 = u32 / with_u32(4) -}); -operand_view!(LocalConstSet64, operands128, Operand128, { - local: u16 = u16 / with_u16(0), dst: u16 = u16 / with_u16(2), value: u64 = u64 / with_u64(4) -}); -operand_view!(MemoryFillConstOp, operands128, Operand128, { - memory: u32 = u32 / with_u32(0), byte: u8 = u8 / with_u8(4), value: i32 = u32 / with_u32(5) -}); -operand_view!(CastBranch, operands64, Operand64, { - target: u32 = u32 / with_u32(0), ref_type_bits: u32 = u32 / with_u32(4) -}); -operand_view!(BranchTableArg, operands128, Operand128, { - target: u32 = u32 / with_u32(0), start: u32 = u32 / with_u32(4), len: u32 = u32 / with_u32(8) -}); -operand_view!(StackConst32, operands64, Operand64, { - target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4) -}); -operand_view!(StackConst64, operands128, Operand128, { - target: u32 = u32 / with_u32(0), value: i64 = u64 / with_u64(4) -}); -operand_view!(LocalConstCmp, operands128, Operand128, { - target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8) -}); -operand_view!(LocalLocalCmp, operands64, Operand64, { - target: u32 = u32 / with_u32(0), left: u16 = u16 / with_u16(4), right: u16 = u16 / with_u16(6) -}); -operand_view!(LocalUpdate, operands128, Operand128, { - target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8), on_zero: u8 = u8 / with_u8(10) -}); -operand_view!(GlobalUpdate, operands128, Operand128, { - target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), global: u32 = u32 / with_u32(8), on_zero: u8 = u8 / with_u8(12) -}); -operand_view!(LocalUpdateCmp, operands128, Operand128, { - target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8), right: u16 = u16 / with_u16(10) -}); - /// An operation packed inline with an indexed operand. -#[derive(Copy, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr( feature = "archive", serde(bound(serialize = "Op: Copy + serde::Serialize", deserialize = "Op: Copy + serde::de::DeserializeOwned",)) )] #[repr(Rust, packed)] -pub struct PackedOp { +pub struct PackedOp { pub op: Op, - pub index: OperandIdx, + pub index: OperandIdx, } -impl PackedOp { - /// Creates a packed operation from an operator and operand index. - #[inline] - pub const fn new(op: Op, index: OperandIdx) -> Self { - Self { op, index } - } -} +/// An operation packed with an index into the 64-bit operand lane. +pub type PackedOp64 = PackedOp; -/// A SIMD value stored in the 128-bit operand lane. -#[derive(Copy, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub struct V128Operand { - pub value: [u8; 16], -} +/// An operation packed with an index into the 128-bit operand lane. +pub type PackedOp128 = PackedOp; -/// A local SIMD operation with an indexed constant. -#[derive(Copy, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub struct LocalV128 { - pub local: u16, - pub value: OperandIdx, -} +impl Copy for PackedOp {} -/// A global SIMD operation with an indexed constant. -#[derive(Copy, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub struct GlobalV128 { - pub global: u32, - pub value: OperandIdx, +impl Clone for PackedOp { + fn clone(&self) -> Self { + *self + } } -/// A local SIMD operation, indexed constant, and destination local. -#[derive(Copy, Clone, PartialEq, Eq)] -#[cfg_attr(feature = "debug", derive(Debug))] -pub struct LocalConstSetV128 { - pub local: u16, - pub dst: u16, - pub value: OperandIdx, +impl PartialEq for PackedOp { + fn eq(&self, other: &Self) -> bool { + let (op, index) = (self.op, self.index); + let (other_op, other_index) = (other.op, other.index); + op == other_op && index == other_index + } } -macro_rules! operand_raw_view { - ($name:ident, $raw:ty, $decode:expr, $encode:expr) => { - impl sealed::Sealed for $name {} +impl Eq for PackedOp {} - impl OperandType for $name { - type Raw = $raw; - - #[inline(always)] - fn decode(raw: Self::Raw) -> Self { - $decode(raw) - } +#[cfg(feature = "debug")] +impl core::fmt::Debug for PackedOp { + fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let (op, index) = (self.op, self.index); + formatter.debug_struct("PackedOp").field("op", &op).field("index", &index).finish() + } +} - #[inline] - fn encode(self) -> Self::Raw { - $encode(self) - } - } - }; -} - -operand_raw_view!(V128Operand, Operand128, |raw: Operand128| Self { value: raw.to_le_bytes() }, |value: Self| { - Operand128::from_le_bytes(value.value) -}); -operand_raw_view!( - LocalV128, - Operand64, - |raw: Operand64| Self { local: raw.u16::<0>(), value: OperandIdx::new(raw.u32::<2>()) }, - |value: Self| { Operand64::default().with_u16::<0>(value.local).with_u32::<2>(value.value.index()) } -); -operand_raw_view!( - GlobalV128, - Operand64, - |raw: Operand64| Self { global: raw.u32::<0>(), value: OperandIdx::new(raw.u32::<4>()) }, - |value: Self| { Operand64::default().with_u32::<0>(value.global).with_u32::<4>(value.value.index()) } -); -operand_raw_view!( - LocalConstSetV128, - Operand64, - |raw: Operand64| Self { local: raw.u16::<0>(), dst: raw.u16::<2>(), value: OperandIdx::new(raw.u32::<4>()) }, - |value: Self| { - Operand64::default().with_u16::<0>(value.local).with_u16::<2>(value.dst).with_u32::<4>(value.value.index()) - } -); - -impl CastBranch { +impl PackedOp { + /// Creates a packed operation from an operator and operand index. #[inline] - pub const fn ref_type(self) -> RefType { - match RefType::from_bits(self.ref_type_bits) { - Some(value) => value, - None => unreachable!(), - } + pub const fn new(op: Op, index: OperandIdx) -> Self { + Self { op, index } } } @@ -325,36 +183,163 @@ pub struct ExceptionHandler { pub catches: Box<[ExceptionCatch]>, } -impl MemoryArg { +impl Operand128 { + /// Creates a full-width memory operand. #[inline] - pub const fn new(offset: u64, mem_addr: MemAddr) -> Self { - Self { offset, mem_addr } + pub fn new(offset: u64, memory: MemAddr) -> Self { + let mut operand = Self::default(); + operand.write_u64::<0>(offset); + operand.write_u32::<8>(memory); + operand + } + + /// Returns the static byte offset. + #[inline(always)] + pub fn offset(&self) -> u64 { + read_field!(self, u64, 0) + } + + /// Returns the module-local memory index. + #[inline(always)] + pub fn memory(&self) -> MemAddr { + read_field!(self, u32, 8) } +} +impl Operand64 { + /// Creates a compact memory operand. #[inline] - pub const fn offset(self) -> u64 { - self.offset + pub fn new(offset: u32, memory: u16) -> Self { + let mut operand = Self::default(); + operand.write_u32::<0>(offset); + operand.write_u16::<4>(memory); + operand + } + + /// Returns the static byte offset. + #[inline(always)] + pub fn offset(&self) -> u32 { + read_field!(self, u32, 0) + } + + /// Returns the module-local memory index. + #[inline(always)] + pub fn memory(&self) -> u16 { + read_field!(self, u16, 4) } +} +impl Operand128 { #[inline] - pub const fn mem_addr(self) -> MemAddr { - self.mem_addr + pub fn new(target: u32, start: u32, len: u32) -> Self { + let mut operand = Self::default(); + operand.write_u32::<0>(target); + operand.write_u32::<4>(start); + operand.write_u32::<8>(len); + operand + } + #[inline(always)] + pub fn start(&self) -> u32 { + read_field!(self, u32, 4) + } + #[inline(always)] + pub fn size(&self) -> u32 { + read_field!(self, u32, 8) } } -impl sealed::Sealed for MemoryArg {} +impl Operand128 { + #[inline] + pub fn new(memory: MemAddr, byte: u8, value: i32) -> Self { + let mut operand = Self::default(); + operand.write_u32::<0>(memory); + operand.write_u8::<4>(byte); + operand.write_u32::<5>(value as u32); + operand + } + #[inline(always)] + pub fn memory(&self) -> MemAddr { + read_field!(self, u32, 0) + } + #[inline(always)] + pub fn byte(&self) -> u8 { + read_field!(self, u8, 4) + } + #[inline(always)] + pub fn value(&self) -> i32 { + read_field!(self, i32, 5) + } +} -impl OperandType for MemoryArg { - type Raw = Operand128; +impl Operand128 { + #[inline] + pub fn new(target: u32, value: i32, local: LocalAddr, on_zero: bool) -> Self { + let mut operand = Self::default(); + operand.write_u32::<0>(target); + operand.write_u32::<4>(value as u32); + operand.write_u16::<8>(local); + operand.write_u8::<10>(u8::from(on_zero)); + operand + } + #[inline(always)] + pub fn value(&self) -> i32 { + read_field!(self, i32, 4) + } + #[inline(always)] + pub fn local(&self) -> LocalAddr { + read_field!(self, u16, 8) + } + #[inline(always)] + pub fn on_zero(&self) -> bool { + read_field!(self, u8, 10) != 0 + } +} +impl Operand128 { + #[inline] + pub fn new(target: u32, value: i32, global: GlobalAddr, on_zero: bool) -> Self { + let mut operand = Self::default(); + operand.write_u32::<0>(target); + operand.write_u32::<4>(value as u32); + operand.write_u32::<8>(global); + operand.write_u8::<12>(u8::from(on_zero)); + operand + } + #[inline(always)] + pub fn value(&self) -> i32 { + read_field!(self, i32, 4) + } + #[inline(always)] + pub fn global(&self) -> GlobalAddr { + read_field!(self, u32, 8) + } #[inline(always)] - fn decode(raw: Self::Raw) -> Self { - Self::new(raw.u64::<0>(), raw.u32::<8>()) + pub fn on_zero(&self) -> bool { + read_field!(self, u8, 12) != 0 } +} +impl Operand128 { #[inline] - fn encode(self) -> Self::Raw { - Operand128::default().with_u64::<0>(self.offset).with_u32::<8>(self.mem_addr) + pub fn new(target: u32, value: i32, local: LocalAddr, right: LocalAddr) -> Self { + let mut operand = Self::default(); + operand.write_u32::<0>(target); + operand.write_u32::<4>(value as u32); + operand.write_u16::<8>(local); + operand.write_u16::<10>(right); + operand + } + #[inline(always)] + pub fn value(&self) -> i32 { + read_field!(self, i32, 4) + } + #[inline(always)] + pub fn local(&self) -> LocalAddr { + read_field!(self, u16, 8) + } + #[inline(always)] + pub fn right(&self) -> LocalAddr { + read_field!(self, u16, 10) } } @@ -372,43 +357,27 @@ impl CompactMemoryArg { } } -impl sealed::Sealed for CompactMemoryArg {} - -impl OperandType for CompactMemoryArg { - type Raw = Operand64; - - #[inline(always)] - fn decode(raw: Self::Raw) -> Self { - Self { offset: raw.u32::<0>(), mem_addr: raw.u16::<4>() } - } - - #[inline] - fn encode(self) -> Self::Raw { - Operand64::default().with_u32::<0>(self.offset).with_u16::<4>(self.mem_addr) - } -} - -impl TryFrom for CompactMemoryArg { +impl TryFrom> for CompactMemoryArg { type Error = (); #[inline] - fn try_from(arg: MemoryArg) -> Result { + fn try_from(arg: Operand128) -> Result { Ok(Self { offset: u32::try_from(arg.offset()).map_err(|_| ())?, - mem_addr: u16::try_from(arg.mem_addr()).map_err(|_| ())?, + mem_addr: u16::try_from(arg.memory()).map_err(|_| ())?, }) } } -impl From for MemoryArg { +impl From for Operand64 { #[inline] fn from(arg: CompactMemoryArg) -> Self { - Self::new(arg.offset(), arg.mem_addr()) + Self::new(arg.offset, arg.mem_addr) } } const _: () = { - assert!(core::mem::size_of::>() == 4); + assert!(core::mem::size_of::>() == 4); assert!(core::mem::size_of::() == 8); assert!(core::mem::size_of::() == 16); assert!(core::mem::size_of::() == 6); @@ -542,28 +511,28 @@ pub enum BinOp128 { #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] pub enum Instruction { LocalCopy32(LocalAddr, LocalAddr), LocalCopy64(LocalAddr, LocalAddr), LocalCopy128(LocalAddr, LocalAddr), - AddConst32(i32), AddConst64(OperandIdx), - IncLocal32(I32LocalArg), IncLocal64(PackedOp), + AddConst32(i32), AddConst64(Operand64Idx), + IncLocal32(I32LocalArg), IncLocal64(PackedOp64), // The 32/64 suffix describes the operand width. Future compare-style ops may still yield i32 results. BinOpLocalLocal32(BinOp, LocalAddr, LocalAddr), BinOpLocalLocal64(BinOp, LocalAddr, LocalAddr), BinOpLocalLocal128(BinOp128, LocalAddr, LocalAddr), CmpLocalLocal32(CmpOp, LocalAddr, LocalAddr), CmpLocalLocal64(CmpOp, LocalAddr, LocalAddr), AddLocalLocalSet32(LocalTripleArg), AddLocalLocalTee32(LocalTripleArg), - BinOpLocalLocalSet32(PackedOp), BinOpLocalLocalSet64(PackedOp), BinOpLocalLocalSet128(PackedOp), - BinOpLocalLocalTee32(PackedOp), BinOpLocalLocalTee64(PackedOp), BinOpLocalLocalTee128(PackedOp), + BinOpLocalLocalSet32(PackedOp64), BinOpLocalLocalSet64(PackedOp64), BinOpLocalLocalSet128(PackedOp64), + BinOpLocalLocalTee32(PackedOp64), BinOpLocalLocalTee64(PackedOp64), BinOpLocalLocalTee128(PackedOp64), AddLocalConst32(I32LocalArg), SubLocalConst32(I32LocalArg), MulLocalConst32(I32LocalArg), - BinOpLocalConst32(PackedOp), BinOpLocalConst64(PackedOp), - BinOpGlobalConst32(PackedOp), BinOpGlobalConst64(PackedOp), - BinOpGlobalConst128(PackedOp), BinOpLocalConst128(PackedOp), - BinOpLocalConstSet32(PackedOp), BinOpLocalConstSet64(PackedOp), BinOpLocalConstSet128(PackedOp), - BinOpLocalConstTee32(PackedOp), BinOpLocalConstTee64(PackedOp), BinOpLocalConstTee128(PackedOp), + BinOpLocalConst32(PackedOp64), BinOpLocalConst64(PackedOp128), + BinOpGlobalConst32(PackedOp64), BinOpGlobalConst64(PackedOp128), + BinOpGlobalConst128(PackedOp64)>), BinOpLocalConst128(PackedOp64)>), + BinOpLocalConstSet32(PackedOp64), BinOpLocalConstSet64(PackedOp128), BinOpLocalConstSet128(PackedOp64)>), + BinOpLocalConstTee32(PackedOp64), BinOpLocalConstTee64(PackedOp128), BinOpLocalConstTee128(PackedOp64)>), BinOpStackLocal32(BinOp, LocalAddr), BinOpStackLocalSet32(BinOp, LocalAddr, LocalAddr), BinOpStackLocalTee32(BinOp, LocalAddr, LocalAddr), BinOpStackLocal128(BinOp128, LocalAddr), BinOpStackGlobal32(BinOp, u32), BinOpStackGlobal64(BinOp, u32), - SetLocalConst32(I32LocalArg), SetLocalConst64(PackedOp), SetLocalConst128(PackedOp), + SetLocalConst32(I32LocalArg), SetLocalConst64(PackedOp64), SetLocalConst128(PackedOp128), IncMemoryLocal32(MemoryLocalArg), IncMemoryLocal64(MemoryLocalArg), StoreLocalLocal32(MemoryLocalArg), StoreLocalLocal64(MemoryLocalArg), StoreLocalLocal128(MemoryLocalArg), LoadLocal32(MemoryLocalArg), LoadLocal64(MemoryLocalArg), @@ -576,7 +545,7 @@ pub enum Instruction { LoadLocalSet16S32(MemoryLocalArg), LoadLocalSet16U32(MemoryLocalArg), LoadLocalTee128(MemoryLocalArg), LoadLocalSet128(MemoryLocalArg), AndConstTee32(I32LocalArg), SubConstTee32(I32LocalArg), - AndConstTee64(PackedOp), SubConstTee64(PackedOp), + AndConstTee64(PackedOp64), SubConstTee64(PackedOp64), MulAccLocal32(LocalAddr), MulAccLocal64(LocalAddr), FMulAccLocal32(LocalAddr), FMulAccLocal64(LocalAddr), I32Add3, @@ -596,14 +565,14 @@ pub enum Instruction { JumpIfRefNonNull(u32), JumpIfLocalZero32(TargetLocalArg), JumpIfLocalNonZero32(TargetLocalArg), JumpIfLocalZero64(TargetLocalArg), JumpIfLocalNonZero64(TargetLocalArg), - JumpCmpStackConst32(PackedOp), JumpCmpStackConst64(PackedOp), - JumpCmpStackLocal32(PackedOp), JumpCmpStackLocal64(PackedOp), - BinOpLocalConstJump32(PackedOp), BinOpLocalConstJumpCmpLocal32(PackedOp<(BinOp, CmpOp), LocalUpdateCmp>), - BinOpStackConstTeeLocalJump32(PackedOp), BinOpGlobalConstJump32(PackedOp), - IncLocalJump32(OperandIdx), IncStackTeeLocalJump32(OperandIdx), IncGlobalJump32(OperandIdx), - IncLocalJumpCmpLocal32(PackedOp), JumpCmpLocalConst32(PackedOp), JumpCmpLocalConst64(PackedOp), - JumpCmpLocalLocal32(PackedOp), JumpCmpLocalLocal64(PackedOp), - DropKeep32 { base: u16, keep: u16 }, DropKeep64 { base: u16, keep: u16 }, DropKeep128 { base: u16, keep: u16 }, BranchTable(OperandIdx), + JumpCmpStackConst32(PackedOp64), JumpCmpStackConst64(PackedOp128), + JumpCmpStackLocal32(PackedOp64), JumpCmpStackLocal64(PackedOp64), + BinOpLocalConstJump32(PackedOp128), BinOpLocalConstJumpCmpLocal32(PackedOp128<(BinOp, CmpOp), LocalUpdateCmpOperand>), + BinOpStackConstTeeLocalJump32(PackedOp128), BinOpGlobalConstJump32(PackedOp128), + IncLocalJump32(Operand128Idx), IncStackTeeLocalJump32(Operand128Idx), IncGlobalJump32(Operand128Idx), + IncLocalJumpCmpLocal32(PackedOp128), JumpCmpLocalConst32(PackedOp128), JumpCmpLocalConst64(PackedOp128), + JumpCmpLocalLocal32(PackedOp64), JumpCmpLocalLocal64(PackedOp64), + DropKeep32 { base: u16, keep: u16 }, DropKeep64 { base: u16, keep: u16 }, DropKeep128 { base: u16, keep: u16 }, BranchTable(Operand128Idx), Return, ReturnVoid, Return32, @@ -611,11 +580,11 @@ pub enum Instruction { Return128, Call(FuncAddr), CallSelf, - CallIndirect(OperandIdx), + CallIndirect(Operand64Idx<(u32, u32)>), CallRef(TypeAddr), ReturnCall(FuncAddr), ReturnCallSelf, - ReturnCallIndirect(OperandIdx), + ReturnCallIndirect(Operand64Idx<(u32, u32)>), ReturnCallRef(TypeAddr), Throw(TagAddr), ThrowRef, @@ -634,18 +603,18 @@ pub enum Instruction { GlobalGet128(GlobalAddr), GlobalSet128(GlobalAddr), GlobalTee128(GlobalAddr), LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr), // > Memory Instructions - I32Load(OperandIdx), I64Load(OperandIdx), F32Load(OperandIdx), F64Load(OperandIdx), - I32Load8S(OperandIdx), I32Load8U(OperandIdx), I32Load16S(OperandIdx), I32Load16U(OperandIdx), - I64Load8S(OperandIdx), I64Load8U(OperandIdx), I64Load16S(OperandIdx), I64Load16U(OperandIdx), I64Load32S(OperandIdx), I64Load32U(OperandIdx), - I32Store(OperandIdx), I64Store(OperandIdx), F32Store(OperandIdx), F64Store(OperandIdx), - I32Store8(OperandIdx), I32Store16(OperandIdx), I64Store8(OperandIdx), I64Store16(OperandIdx), I64Store32(OperandIdx), + I32Load(Operand128Idx), I64Load(Operand128Idx), F32Load(Operand128Idx), F64Load(Operand128Idx), + I32Load8S(Operand128Idx), I32Load8U(Operand128Idx), I32Load16S(Operand128Idx), I32Load16U(Operand128Idx), + I64Load8S(Operand128Idx), I64Load8U(Operand128Idx), I64Load16S(Operand128Idx), I64Load16U(Operand128Idx), I64Load32S(Operand128Idx), I64Load32U(Operand128Idx), + I32Store(Operand128Idx), I64Store(Operand128Idx), F32Store(Operand128Idx), F64Store(Operand128Idx), + I32Store8(Operand128Idx), I32Store16(Operand128Idx), I64Store8(Operand128Idx), I64Store16(Operand128Idx), I64Store32(Operand128Idx), MemorySize(MemAddr), MemoryGrow(MemAddr), // > Constants Const32(i32), Const64Imm(i32), - Const64(OperandIdx), + Const64(Operand64Idx), // > Reference Types RefNull(RefType), @@ -658,24 +627,24 @@ pub enum Instruction { RefEq, RefTest(RefType), RefCast(RefType), - BrOnCast(OperandIdx), - BrOnCastFail(OperandIdx), + BrOnCast(Operand64Idx<(u32, u32)>), + BrOnCastFail(Operand64Idx<(u32, u32)>), // > GC Objects StructNew(TypeAddr), StructNewDefault(TypeAddr), - StructGet(OperandIdx), StructGetS(OperandIdx), StructGetU(OperandIdx), StructSet(OperandIdx), + StructGet(Operand64Idx<(u32, u32)>), StructGetS(Operand64Idx<(u32, u32)>), StructGetU(Operand64Idx<(u32, u32)>), StructSet(Operand64Idx<(u32, u32)>), ArrayNew(TypeAddr), ArrayNewDefault(TypeAddr), - ArrayNewFixed(OperandIdx), - ArrayNewData(OperandIdx), ArrayNewElem(OperandIdx), + ArrayNewFixed(Operand64Idx<(u32, u32)>), + ArrayNewData(Operand64Idx<(u32, u32)>), ArrayNewElem(Operand64Idx<(u32, u32)>), ArrayGet(TypeAddr), ArrayGetS(TypeAddr), ArrayGetU(TypeAddr), ArraySet(TypeAddr), ArrayLen, ArrayFill(TypeAddr), - ArrayCopy(OperandIdx), ArrayInitData(OperandIdx), ArrayInitElem(OperandIdx), + ArrayCopy(Operand64Idx<(u32, u32)>), ArrayInitData(Operand64Idx<(u32, u32)>), ArrayInitElem(Operand64Idx<(u32, u32)>), // > Numeric Instructions // See @@ -705,18 +674,18 @@ pub enum Instruction { I64TruncSatF32S, I64TruncSatF32U, I64TruncSatF64S, I64TruncSatF64U, // > Table Instructions - TableInit(OperandIdx), + TableInit(Operand64Idx<(u32, u32)>), TableGet(TableAddr), TableSet(TableAddr), - TableCopy(OperandIdx), + TableCopy(Operand64Idx<(u32, u32)>), TableGrow(TableAddr), TableSize(TableAddr), TableFill(TableAddr), // > Bulk Memory Instructions - MemoryInit(OperandIdx), MemoryCopy(OperandIdx), + MemoryInit(Operand64Idx<(u32, u32)>), MemoryCopy(Operand64Idx<(u32, u32)>), MemoryFill(MemAddr), - MemoryFillConst(OperandIdx), + MemoryFillConst(Operand128Idx), DataDrop(DataAddr), ElemDrop(ElemAddr), @@ -724,18 +693,18 @@ pub enum Instruction { I64Add128, I64Sub128, I64MulWideS, I64MulWideU, // > SIMD - V128Load(OperandIdx), V128Load8x8S(OperandIdx), V128Load8x8U(OperandIdx), - V128Load16x4S(OperandIdx), V128Load16x4U(OperandIdx), V128Load32x2S(OperandIdx), V128Load32x2U(OperandIdx), + V128Load(Operand128Idx), V128Load8x8S(Operand128Idx), V128Load8x8U(Operand128Idx), + V128Load16x4S(Operand128Idx), V128Load16x4U(Operand128Idx), V128Load32x2S(Operand128Idx), V128Load32x2U(Operand128Idx), - V128Load8Splat(OperandIdx), V128Load16Splat(OperandIdx), V128Load32Splat(OperandIdx), V128Load64Splat(OperandIdx), + V128Load8Splat(Operand128Idx), V128Load16Splat(Operand128Idx), V128Load32Splat(Operand128Idx), V128Load64Splat(Operand128Idx), V128Load8Lane(MemoryLaneArg), V128Load16Lane(MemoryLaneArg), V128Load32Lane(MemoryLaneArg), V128Load64Lane(MemoryLaneArg), - V128Load32Zero(OperandIdx), V128Load64Zero(OperandIdx), + V128Load32Zero(Operand128Idx), V128Load64Zero(Operand128Idx), - V128Store(OperandIdx), V128Store8Lane(MemoryLaneArg), V128Store16Lane(MemoryLaneArg), V128Store32Lane(MemoryLaneArg), V128Store64Lane(MemoryLaneArg), + V128Store(Operand128Idx), V128Store8Lane(MemoryLaneArg), V128Store16Lane(MemoryLaneArg), V128Store32Lane(MemoryLaneArg), V128Store64Lane(MemoryLaneArg), - I8x16Shuffle(OperandIdx), - Const128Imm(u32), Const128(OperandIdx), + I8x16Shuffle(Operand128Idx<[u8; 16]>), + Const128Imm(u32), Const128(Operand128Idx<[u8; 16]>), I8x16ExtractLaneS(u8), I8x16ExtractLaneU(u8), I8x16ReplaceLane(u8), I16x8ExtractLaneS(u8), I16x8ExtractLaneU(u8), I16x8ReplaceLane(u8), @@ -794,6 +763,8 @@ pub enum Instruction { I16x8RelaxedQ15mulrS, I16x8RelaxedDotI8x16I7x16S, I32x4RelaxedDotI8x16I7x16AddS, + + SelectStore32(Operand128Idx), SelectStore64(Operand128Idx), } const _: () = assert!(core::mem::size_of::() == 8); @@ -814,43 +785,40 @@ mod tests { #[test] fn operand_lanes_round_trip_max_values() { - let memory = MemoryArg::new(u64::MAX, u32::MAX); - assert_eq!(MemoryArg::decode(memory.encode()), memory); - - let value = Operand128::default() - .with_u8::<0>(u8::MAX) - .with_u16::<1>(u16::MAX) - .with_u32::<3>(u32::MAX) - .with_u64::<7>(u64::MAX); - assert_eq!( - (value.u8::<0>(), value.u16::<1>(), value.u32::<3>(), value.u64::<7>()), - (u8::MAX, u16::MAX, u32::MAX, u64::MAX) - ); - - let bytes = [u8::MAX; 16]; - assert_eq!(Operand128::from_le_bytes(bytes).to_le_bytes(), bytes); + let memory = Operand128::::new(u64::MAX, u32::MAX); + assert_eq!(memory.offset(), u64::MAX); + assert_eq!(memory.memory(), u32::MAX); + + let value = Operand128::::new(u32::MAX, i32::MIN, u16::MAX, true); + assert_eq!(value.target(), u32::MAX); + assert_eq!(value.value(), i32::MIN); + assert_eq!(value.local(), u16::MAX); + assert!(value.on_zero()); } #[test] fn v128_operand_views_round_trip_max_bytes() { - let value = OperandIdx::::new(0); - let local = OperandIdx::::new(0); - let global = OperandIdx::::new(1); - let set = OperandIdx::::new(2); + let value = Operand128Idx::<[u8; 16]>::new(0); + let local = Operand64Idx::<(u16, Operand128Idx<[u8; 16]>)>::new(0); + let global = Operand64Idx::<(u32, Operand128Idx<[u8; 16]>)>::new(1); + let set = Operand64Idx::<(u16, u16, Operand128Idx<[u8; 16]>)>::new(2); let data = super::super::WasmFunctionData { - operands128: vec![V128Operand { value: [u8::MAX; 16] }.encode()].into_boxed_slice(), + operands128: vec![Operand128::<[u8; 16]>::new([u8::MAX; 16]).cast()].into_boxed_slice(), operands64: vec![ - LocalV128 { local: u16::MAX, value }.encode(), - GlobalV128 { global: u32::MAX, value }.encode(), - LocalConstSetV128 { local: u16::MAX, dst: u16::MAX, value }.encode(), + Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(u16::MAX, value).cast(), + Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(u32::MAX, value).cast(), + Operand64::<(u16, u16, Operand128Idx<[u8; 16]>)>::new(u16::MAX, u16::MAX, value).cast(), ] .into_boxed_slice(), ..Default::default() }; - assert_eq!(value.get(&data).value, [u8::MAX; 16]); - assert_eq!(local.get(&data), LocalV128 { local: u16::MAX, value }); - assert_eq!(global.get(&data), GlobalV128 { global: u32::MAX, value }); - assert_eq!(set.get(&data), LocalConstSetV128 { local: u16::MAX, dst: u16::MAX, value }); + assert_eq!(value.resolve(&data).value(), [u8::MAX; 16]); + assert_eq!((local.resolve(&data).a(), local.resolve(&data).b()), (u16::MAX, value)); + assert_eq!((global.resolve(&data).a(), global.resolve(&data).b()), (u32::MAX, value)); + assert_eq!( + (set.resolve(&data).a(), set.resolve(&data).b(), set.resolve(&data).c()), + (u16::MAX, u16::MAX, value) + ); } } diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index f9f85fa..a3f26f2 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -133,6 +133,9 @@ pub struct ModuleInner { /// Corresponds to the `memory` section of the original WebAssembly module. pub memory_types: Box<[MemoryType]>, + /// Whether instantiation should omit unexported local memories that guest code cannot access. + pub skip_local_memory_allocation: bool, + /// Tag components of the WebAssembly module. /// /// Corresponds to the `tag` section of the original WebAssembly module. diff --git a/crates/types/src/operands.rs b/crates/types/src/operands.rs index 3cc311c..1bc4a28 100644 --- a/crates/types/src/operands.rs +++ b/crates/types/src/operands.rs @@ -1,18 +1,22 @@ use core::marker::PhantomData; -use crate::WasmFunctionData; - /// An index into the operand lane used by `T`. #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "archive", serde(transparent))] #[repr(transparent)] -pub struct OperandIdx { +pub struct OperandIdx { index: u32, #[cfg_attr(feature = "archive", serde(skip))] marker: PhantomData, } -impl OperandIdx { +/// An index into the 64-bit operand lane. +pub type Operand64Idx = OperandIdx; + +/// An index into the 128-bit operand lane. +pub type Operand128Idx = OperandIdx; + +impl OperandIdx { #[inline] #[doc(hidden)] pub const fn new(index: u32) -> Self { @@ -21,157 +25,329 @@ impl OperandIdx { /// Returns the underlying lane index. #[inline] - pub const fn index(self) -> u32 { - self.index - } -} - -impl OperandIdx { - /// Returns the typed operand at this index. - /// - /// Panics if the index is outside its statically selected operand lane. - #[inline(always)] - pub fn get(self, data: &WasmFunctionData) -> T { - T::decode(T::Raw::get(data, self.index)) + pub const fn index(self) -> usize { + self.index as usize } } -impl Copy for OperandIdx {} - -impl Clone for OperandIdx { +impl Copy for OperandIdx {} +impl Clone for OperandIdx { fn clone(&self) -> Self { *self } } - -impl PartialEq for OperandIdx { +impl PartialEq for OperandIdx { fn eq(&self, other: &Self) -> bool { self.index == other.index } } - -impl Eq for OperandIdx {} +impl Eq for OperandIdx {} #[cfg(feature = "debug")] -impl core::fmt::Debug for OperandIdx { +impl core::fmt::Debug for OperandIdx { fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.index.fmt(formatter) } } -pub(crate) mod sealed { - pub trait Sealed {} -} - -/// A typed view stored in one of the per-function operand lanes. -pub trait OperandType: sealed::Sealed + Copy { - #[doc(hidden)] - type Raw: RawOperand; - - #[doc(hidden)] - fn decode(raw: Self::Raw) -> Self; - #[doc(hidden)] - fn encode(self) -> Self::Raw; -} - -#[doc(hidden)] -pub trait RawOperand: sealed::Sealed + Copy { - fn get(data: &WasmFunctionData, index: u32) -> Self; -} - macro_rules! define_operand { - ($name:ident, $len:literal, $lane:ident) => { - #[doc = concat!("Raw fields stored in a per-function ", $len, "-byte operand lane.")] - #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default)] - #[cfg_attr(feature = "debug", derive(Debug))] - #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] - #[repr(transparent)] - pub struct $name([u8; $len]); - - impl sealed::Sealed for $name {} - - impl RawOperand for $name { - #[inline(always)] - fn get(data: &WasmFunctionData, index: u32) -> Self { - *data.$lane.get(index as usize).unwrap_or_else(|| unreachable!("invalid operand index")) - } + ($name:ident, $len:literal) => { + #[doc = concat!("A typed packed ", $len, "-byte operand value.")] + #[repr(C)] + pub struct $name { + pub(crate) bytes: [u8; $len], + marker: PhantomData, } - impl $name { - /// Returns the byte at `OFFSET`. + #[allow(dead_code)] + impl $name { #[inline] - pub fn u8(self) -> u8 { + pub(crate) fn write_u8(&mut self, value: u8) { const { assert!(OFFSET < $len) }; - self.0[OFFSET] + self.bytes[OFFSET] = value; } - /// Returns the little-endian `u16` at `OFFSET`. #[inline] - pub fn u16(self) -> u16 { + pub(crate) fn write_u16(&mut self, value: u16) { const { assert!(OFFSET + 2 <= $len) }; - u16::from_le_bytes(self.0[OFFSET..OFFSET + 2].try_into().unwrap_or_else(|_| unreachable!())) + self.bytes[OFFSET..OFFSET + 2].copy_from_slice(&value.to_le_bytes()); } - /// Returns the little-endian `u32` at `OFFSET`. #[inline] - pub fn u32(self) -> u32 { + pub(crate) fn write_u32(&mut self, value: u32) { const { assert!(OFFSET + 4 <= $len) }; - u32::from_le_bytes(self.0[OFFSET..OFFSET + 4].try_into().unwrap_or_else(|_| unreachable!())) + self.bytes[OFFSET..OFFSET + 4].copy_from_slice(&value.to_le_bytes()); } - /// Returns the little-endian `u64` at `OFFSET`. #[inline] - pub fn u64(self) -> u64 { + pub(crate) fn write_u64(&mut self, value: u64) { const { assert!(OFFSET + 8 <= $len) }; - u64::from_le_bytes(self.0[OFFSET..OFFSET + 8].try_into().unwrap_or_else(|_| unreachable!())) + self.bytes[OFFSET..OFFSET + 8].copy_from_slice(&value.to_le_bytes()); } - /// Builds an operand from its raw little-endian bytes. - #[inline] - pub fn from_le_bytes(value: [u8; $len]) -> Self { - Self(value) + #[inline(always)] + #[doc(hidden)] + pub fn cast(self) -> $name { + $name { bytes: self.bytes, marker: PhantomData } } + } - /// Returns the raw little-endian bytes. - #[inline] - pub fn to_le_bytes(self) -> [u8; $len] { - self.0 + impl Copy for $name {} + impl Clone for $name { + fn clone(&self) -> Self { + *self } + } + impl PartialEq for $name { + fn eq(&self, other: &Self) -> bool { + self.bytes == other.bytes + } + } + impl Eq for $name {} + impl PartialOrd for $name { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } + } + impl Ord for $name { + fn cmp(&self, other: &Self) -> core::cmp::Ordering { + self.bytes.cmp(&other.bytes) + } + } + impl Default for $name { + fn default() -> Self { + Self { bytes: [0; $len], marker: PhantomData } + } + } - /// Writes `value` at `OFFSET` and returns the updated operand. - #[inline] - pub fn with_u8(mut self, value: u8) -> Self { - const { assert!(OFFSET < $len) }; - self.0[OFFSET] = value; - self + #[cfg(feature = "debug")] + impl core::fmt::Debug for $name { + fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + self.bytes.fmt(formatter) } + } - /// Writes `value` at `OFFSET` and returns the updated operand. - #[inline] - pub fn with_u16(mut self, value: u16) -> Self { - const { assert!(OFFSET + 2 <= $len) }; - self.0[OFFSET..OFFSET + 2].copy_from_slice(&value.to_le_bytes()); - self + #[cfg(feature = "archive")] + impl serde::Serialize for $name { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + self.bytes.serialize(serializer) } + } - /// Writes `value` at `OFFSET` and returns the updated operand. - #[inline] - pub fn with_u32(mut self, value: u32) -> Self { - const { assert!(OFFSET + 4 <= $len) }; - self.0[OFFSET..OFFSET + 4].copy_from_slice(&value.to_le_bytes()); - self + #[cfg(feature = "archive")] + impl<'de, T> serde::Deserialize<'de> for $name { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + Ok(Self { bytes: <[u8; $len]>::deserialize(deserializer)?, marker: PhantomData }) } + } + }; +} + +define_operand!(Operand64, 8); +define_operand!(Operand128, 16); + +macro_rules! unwrap_or_unreachable { + ($value:expr) => {{ unwrap_or_unreachable!($value, "entered unreachable code") }}; + ($value:expr, $message:literal) => {{ + match $value { + Some(value) => value, + None => operand_unreachable($message), + } + }}; +} + +#[cold] +#[inline(never)] +pub(crate) fn operand_unreachable(message: &'static str) -> ! { + unreachable!("{message}") +} - /// Writes `value` at `OFFSET` and returns the updated operand. +impl Operand64Idx { + /// Resolves this index to a copied 64-bit packed operand. + #[inline(always)] + pub fn resolve(self, data: &crate::WasmFunctionData) -> Operand64 { + (*unwrap_or_unreachable!(data.operands64.get(self.index()), "invalid 64-bit operand index")).cast() + } +} + +impl Operand128Idx { + /// Resolves this index to a copied 128-bit packed operand. + #[inline(always)] + pub fn resolve(self, data: &crate::WasmFunctionData) -> Operand128 { + (*unwrap_or_unreachable!(data.operands128.get(self.index()), "invalid 128-bit operand index")).cast() + } +} + +macro_rules! field_ty { + (u8) => { u8 }; (u16) => { u16 }; (u32) => { u32 }; (u64) => { u64 }; + (i32) => { i32 }; (i64) => { i64 }; (idx128) => { Operand128Idx<[u8; 16]> }; +} +macro_rules! field_size { + (u8) => {{ 1 }}; + (u16) => {{ 2 }}; + (u32) => {{ 4 }}; + (u64) => {{ 8 }}; + (i32) => {{ 4 }}; + (i64) => {{ 8 }}; + (idx128) => {{ 4 }}; +} + +macro_rules! read_field { + ($self:ident, u8, $offset:expr) => {{ $self.bytes[$offset] }}; + ($self:ident, u16, $offset:expr) => {{ u16::from_le_bytes($crate::operands::read_bytes!($self, $offset, 2)) }}; + ($self:ident, u32, $offset:expr) => {{ u32::from_le_bytes($crate::operands::read_bytes!($self, $offset, 4)) }}; + ($self:ident, u64, $offset:expr) => {{ u64::from_le_bytes($crate::operands::read_bytes!($self, $offset, 8)) }}; + ($self:ident, i32, $offset:expr) => {{ read_field!($self, u32, $offset) as i32 }}; + ($self:ident, i64, $offset:expr) => {{ read_field!($self, u64, $offset) as i64 }}; + ($self:ident, idx128, $offset:expr) => {{ Operand128Idx::new(read_field!($self, u32, $offset)) }}; +} +pub(crate) use read_field; + +macro_rules! read_bytes { + ($self:ident, $offset:expr, $len:literal) => {{ + match <[u8; $len]>::try_from(&$self.bytes[$offset..$offset + $len]) { + Ok(bytes) => bytes, + Err(_) => $crate::operands::operand_unreachable("invalid operand field"), + } + }}; +} +pub(crate) use read_bytes; +macro_rules! write_field { + ($self:ident, u8, $offset:expr, $value:expr) => {{ $self.write_u8::<{ $offset }>($value) }}; + ($self:ident, u16, $offset:expr, $value:expr) => {{ $self.write_u16::<{ $offset }>($value) }}; + ($self:ident, u32, $offset:expr, $value:expr) => {{ $self.write_u32::<{ $offset }>($value) }}; + ($self:ident, u64, $offset:expr, $value:expr) => {{ $self.write_u64::<{ $offset }>($value) }}; + ($self:ident, i32, $offset:expr, $value:expr) => {{ $self.write_u32::<{ $offset }>($value as u32) }}; + ($self:ident, i64, $offset:expr, $value:expr) => {{ $self.write_u64::<{ $offset }>($value as u64) }}; + ($self:ident, idx128, $offset:expr, $value:expr) => {{ $self.write_u32::<{ $offset }>($value.index) }}; +} + +impl Operand64 { + /// Returns the jump target stored at the start of a retargetable operand. + #[inline(always)] + pub fn target(&self) -> u32 { + read_field!(self, u32, 0) + } + + /// Replaces the jump target stored at the start of a retargetable operand. + #[inline] + pub fn with_target(mut self, target: u32) -> Self { + self.write_u32::<0>(target); + self + } +} + +impl Operand128 { + /// Returns the jump target stored at the start of a retargetable operand. + #[inline(always)] + pub fn target(&self) -> u32 { + read_field!(self, u32, 0) + } + + /// Replaces the jump target stored at the start of a retargetable operand. + #[inline] + pub fn with_target(mut self, target: u32) -> Self { + self.write_u32::<0>(target); + self + } +} + +macro_rules! packed_layout { + ($operand:ident, $lane:ident, $field:tt) => { + impl $operand { #[inline] - pub fn with_u64(mut self, value: u64) -> Self { - const { assert!(OFFSET + 8 <= $len) }; - self.0[OFFSET..OFFSET + 8].copy_from_slice(&value.to_le_bytes()); - self + pub fn new(value: field_ty!($field)) -> Self { + let mut operand = Self::default(); + write_field!(operand, $field, 0, value); + operand + } + #[inline(always)] + pub fn value(&self) -> field_ty!($field) { + read_field!(self, $field, 0) + } + } + }; + ($operand:ident, $lane:ident, $a:tt, $b:tt) => { + impl $operand<(field_ty!($a), field_ty!($b))> { + #[inline] + pub fn new(a: field_ty!($a), b: field_ty!($b)) -> Self { + let mut operand = Self::default(); + write_field!(operand, $a, 0, a); + write_field!(operand, $b, field_size!($a), b); + operand + } + #[inline(always)] + pub fn a(&self) -> field_ty!($a) { + read_field!(self, $a, 0) + } + #[inline(always)] + pub fn b(&self) -> field_ty!($b) { + read_field!(self, $b, field_size!($a)) + } + } + }; + ($operand:ident, $lane:ident, $a:tt, $b:tt, $c:tt) => { + impl $operand<(field_ty!($a), field_ty!($b), field_ty!($c))> { + #[inline] + pub fn new(a: field_ty!($a), b: field_ty!($b), c: field_ty!($c)) -> Self { + let mut operand = Self::default(); + write_field!(operand, $a, 0, a); + write_field!(operand, $b, field_size!($a), b); + write_field!(operand, $c, field_size!($a) + field_size!($b), c); + operand + } + #[inline(always)] + pub fn a(&self) -> field_ty!($a) { + read_field!(self, $a, 0) + } + #[inline(always)] + pub fn b(&self) -> field_ty!($b) { + read_field!(self, $b, field_size!($a)) + } + #[inline(always)] + pub fn c(&self) -> field_ty!($c) { + read_field!(self, $c, field_size!($a) + field_size!($b)) } } }; } -define_operand!(Operand64, 8, operands64); -define_operand!(Operand128, 16, operands128); +packed_layout!(Operand64, operands64, i64); +packed_layout!(Operand64, operands64, u32, u32); +packed_layout!(Operand64, operands64, u16, u32); +packed_layout!(Operand64, operands64, u32, u16); +packed_layout!(Operand64, operands64, u16, u16, u16); +packed_layout!(Operand64, operands64, u16, u16, u32); +packed_layout!(Operand64, operands64, u32, i32); +packed_layout!(Operand64, operands64, u32, u16, u16); +packed_layout!(Operand64, operands64, u16, idx128); +packed_layout!(Operand64, operands64, u32, idx128); +packed_layout!(Operand64, operands64, u16, u16, idx128); + +packed_layout!(Operand128, operands128, u16, u64); +packed_layout!(Operand128, operands128, u32, u64); +packed_layout!(Operand128, operands128, u16, u16, u64); +packed_layout!(Operand128, operands128, u32, i64); +packed_layout!(Operand128, operands128, u32, i32, u16); + +impl Operand128<[u8; 16]> { + #[inline] + pub fn new(value: [u8; 16]) -> Self { + Self { bytes: value, marker: PhantomData } + } + #[inline(always)] + pub fn value(&self) -> [u8; 16] { + self.bytes + } +} +const _: () = { + assert!(core::mem::size_of::>() == 4); + assert!(core::mem::size_of::() == 8); + assert!(core::mem::size_of::() == 16); +}; diff --git a/crates/types/src/reference.rs b/crates/types/src/reference.rs index 2d725ca..d195a81 100644 --- a/crates/types/src/reference.rs +++ b/crates/types/src/reference.rs @@ -69,7 +69,8 @@ impl RefType { } #[inline] - pub(crate) const fn from_bits(bits: u32) -> Option { + #[doc(hidden)] + pub const fn from_bits(bits: u32) -> Option { let ty = Self(bits); if ty.is_concrete() || ty.abstract_heap_type().is_some() { Some(ty) } else { None } } diff --git a/examples/rust/build.sh b/examples/rust/build.sh index cbd3b27..873028f 100755 --- a/examples/rust/build.sh +++ b/examples/rust/build.sh @@ -12,6 +12,10 @@ wasmopt_features="--enable-simd --enable-relaxed-simd --enable-tail-call --enabl # ensure out dir exists mkdir -p "$dest_dir" +# Keep the embedded archive synchronized with the current archive version and instruction layout. +cargo run --quiet --manifest-path "../../Cargo.toml" --package tinywasm-cli -- \ + compile "src/print.wasm" --output "src/print.twasm" --force || exit + # build no_std RUSTFLAGS="-Zlocation-detail=none -Zfmt-debug=none -C target-feature=$rust_features -C panic=abort" cargo build -Z build-std=core,alloc,panic_abort -Z build-std-features="optimize_for_size" --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin tinywasm_no_std --no-default-features cp "$out_dir/tinywasm_no_std.wasm" "$dest_dir/" diff --git a/examples/rust/src/print.twasm b/examples/rust/src/print.twasm index 7841329..0fb3f39 100644 Binary files a/examples/rust/src/print.twasm and b/examples/rust/src/print.twasm differ -- cgit v1.3.1 From 795ec871806ea189818bbf2fd2a69455384d2004 Mon Sep 17 00:00:00 2001 From: Henry Date: Mon, 14 Sep 2026 10:48:16 +0200 Subject: feat: replace parser optimizer with streaming selection Signed-off-by: Henry --- crates/parser/src/conversion.rs | 41 +- crates/parser/src/emitter.rs | 355 ++++++++ crates/parser/src/lib.rs | 35 +- crates/parser/src/macros.rs | 133 +-- crates/parser/src/module.rs | 49 +- crates/parser/src/optimize/mod.rs | 4 - crates/parser/src/optimize/rewrite.rs | 1500 ------------------------------- crates/parser/src/optimize/targets.rs | 227 ----- crates/parser/src/parallel.rs | 28 +- crates/parser/src/selection.rs | 314 +++++++ crates/parser/src/selection/encoding.rs | 293 ++++++ crates/parser/src/visit.rs | 922 ++++++++++--------- 12 files changed, 1569 insertions(+), 2332 deletions(-) create mode 100644 crates/parser/src/emitter.rs delete mode 100644 crates/parser/src/optimize/mod.rs delete mode 100644 crates/parser/src/optimize/rewrite.rs delete mode 100644 crates/parser/src/optimize/targets.rs create mode 100644 crates/parser/src/selection.rs create mode 100644 crates/parser/src/selection/encoding.rs (limited to 'crates/parser/src/conversion.rs') diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 4cf0d02..36455ee 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -6,6 +6,17 @@ use alloc::{boxed::Box, format, vec::Vec}; use tinywasm_types::*; use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations, UnpackedIndex}; +/// Function identity and result layout shared by lowering and finalization. +#[derive(Clone, Copy)] +pub(crate) struct FunctionLoweringContext { + /// Module type index of the function signature. + pub(crate) ty_idx: u32, + /// Module function index, including imported functions. + pub(crate) self_func_addr: u32, + /// Result counts in each physical value lane. + pub(crate) function_results: ValueCounts, +} + pub(crate) fn value_lane(ty: wasmparser::ValType) -> ValueLane { match ty { wasmparser::ValType::I32 | wasmparser::ValType::F32 | wasmparser::ValType::Ref(_) => ValueLane::S32, @@ -148,11 +159,11 @@ pub(crate) fn convert_module_code( validator: Option>, reader_allocs: OperatorsReaderAllocations, metadata: &crate::visit::ModuleMetadata, - ty_idx: u32, + context: FunctionLoweringContext, options: &ParserOptions, ) -> Result<(FunctionCode, Option, OperatorsReaderAllocations)> { let mut locals_reader = func.get_locals_reader()?; - let mut local_types = metadata.signature(ty_idx)?.params.clone(); + let mut local_types = metadata.signature(context.ty_idx)?.params.clone(); #[cfg(feature = "validate")] let mut validator = validator; @@ -193,39 +204,27 @@ pub(crate) fn convert_module_code( func, (local_types, local_addr_map), metadata, - ty_idx, + context, reader_allocs, - options.deduplicate_operands(), + options, )?; (body, data, uses_local_memory, Some(validator_allocs), reader_allocs) } None => { - let (body, data, uses_local_memory, reader_allocs) = process_operators( - func, - (local_types, local_addr_map), - metadata, - ty_idx, - reader_allocs, - options.deduplicate_operands(), - )?; + let (body, data, uses_local_memory, reader_allocs) = + process_operators(func, (local_types, local_addr_map), metadata, context, reader_allocs, options)?; (body, data, uses_local_memory, None, reader_allocs) } }; #[cfg(not(feature = "validate"))] let (body, data, uses_local_memory, validator_allocs, reader_allocs) = { let _ = validator; - let (body, data, uses_local_memory, reader_allocs) = process_operators( - func, - (local_types, local_addr_map), - metadata, - ty_idx, - reader_allocs, - options.deduplicate_operands(), - )?; + let (body, data, uses_local_memory, reader_allocs) = + process_operators(func, (local_types, local_addr_map), metadata, context, reader_allocs, options)?; (body, data, uses_local_memory, None, reader_allocs) }; Ok(( - FunctionCode { instructions: body, data, locals: local_counts, uses_local_memory }, + FunctionCode { instructions: body, data: data.finish(), locals: local_counts, uses_local_memory }, validator_allocs, reader_allocs, )) diff --git a/crates/parser/src/emitter.rs b/crates/parser/src/emitter.rs new file mode 100644 index 0000000..d36444a --- /dev/null +++ b/crates/parser/src/emitter.rs @@ -0,0 +1,355 @@ +//! Streaming instruction selection with stable labels and target-only relocation. + +use crate::{ + ParseError, ParserOptions, Result, conversion::FunctionLoweringContext, selection, visit::FunctionDataBuilder, +}; +use alloc::vec::Vec; +use tinywasm_types::{BranchTableOperand, ExceptionCatch, ExceptionHandler, Instruction, Operand128, ValueCounts}; + +const LOOKBEHIND: usize = 3; + +/// Restricted vector view, with no readable or mutable access to the committed prefix. +pub(crate) struct PendingTail<'a> { + instructions: &'a mut Vec, + start: usize, +} + +impl<'a> PendingTail<'a> { + fn new(instructions: &'a mut Vec, start: usize) -> Self { + assert!(start < instructions.len() && instructions.len() - start <= LOOKBEHIND + 1); + Self { instructions, start } + } + + /// Copies at most four pending instructions, including the incoming instruction. + pub(crate) fn suffix(&self) -> Option<[Instruction; N]> { + const { assert!(N > 0 && N <= LOOKBEHIND + 1) }; + let pending = &self.instructions[self.start..]; + let start = pending.len().checked_sub(N)?; + Some(pending[start..].try_into().unwrap()) + } + + /// Splices a non-growing suffix and truncates immediately, leaving no holes. + pub(crate) fn replace(&mut self, replacements: [Instruction; M]) { + const { + assert!(N > 0 && N <= LOOKBEHIND + 1); + assert!(M <= N); + } + let pending = &mut self.instructions[self.start..]; + let start = pending.len().checked_sub(N).expect("replacement exceeds pending tail"); + pending[start..start + M].copy_from_slice(&replacements); + self.instructions.truncate(self.start + start + M); + } +} + +/// Identity of a stable instruction boundary. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct LabelId(usize); + +enum PatchSite { + Instruction(usize), + TableEntry(usize), + ExceptionStart(usize), + ExceptionEnd(usize), + Catch(usize, usize), +} + +/// Owns one instruction vector with an immutable prefix and at most three pending instructions. +pub(crate) struct Emitter { + instructions: Vec, + committed: usize, + select: bool, + self_func_addr: u32, + return_instruction: Instruction, + pending_jump: Option, + labels: Vec>, + uses: Vec<(PatchSite, LabelId)>, +} + +impl Emitter { + /// Creates an emitter with a bounded initial allocation. + pub(crate) fn new(body_size: usize, context: FunctionLoweringContext, options: &ParserOptions) -> Self { + use Instruction::*; + let return_instruction = match (options.optimize(), context.function_results) { + (true, ValueCounts { c32: 0, c64: 0, c128: 0 }) => ReturnVoid, + (true, ValueCounts { c32: 1, c64: 0, c128: 0 }) => Return32, + (true, ValueCounts { c32: 0, c64: 1, c128: 0 }) => Return64, + (true, ValueCounts { c32: 0, c64: 0, c128: 1 }) => Return128, + _ => Return, + }; + Self { + instructions: Vec::with_capacity(body_size.min(1024)), + committed: 0, + select: options.optimize(), + self_func_addr: context.self_func_addr, + return_instruction, + pending_jump: None, + labels: Vec::new(), + uses: Vec::new(), + } + } + + /// Whether lowering may select optimized instruction and target forms. + pub(crate) fn optimizations_enabled(&self) -> bool { + self.select + } + + /// Allocates an unbound structural or executable label. + pub(crate) fn new_label(&mut self) -> LabelId { + let label = LabelId(self.labels.len()); + self.labels.push(None); + label + } + + /// Flushes the pending tail and records a stable boundary. + pub(crate) fn bind(&mut self, label: LabelId) -> Result<()> { + // Only the uncommitted jump can disappear. Any other binding seals it, + // so removing it cannot move a previously bound boundary. + if self.pending_jump == Some(label) { + debug_assert_eq!(self.instructions.len(), self.committed + 1); + debug_assert!(matches!(self.instructions.last(), Some(Instruction::Jump(_)))); + self.pending_jump = None; + self.instructions.pop(); + } + self.seal_jump(); + self.commit(self.instructions.len()); + let offset = u32::try_from(self.instructions.len()) + .map_err(|_| ParseError::Other("function body is too large".into()))?; + let binding = self.labels.get_mut(label.0).ok_or_else(|| ParseError::Other("unknown label".into()))?; + if binding.is_some() { + return Err(ParseError::Other("label bound more than once".into())); + } + *binding = Some(offset); + Ok(()) + } + + /// Appends an instruction without applying logical stack effects. + #[inline] + pub(crate) fn emit(&mut self, instruction: Instruction) -> Result<()> { + self.push(instruction)?; + self.commit(self.instructions.len().saturating_sub(LOOKBEHIND).max(self.committed)); + Ok(()) + } + + /// Emits a call or terminator and seals the tail against subsequent fusion. + pub(crate) fn emit_boundary(&mut self, instruction: Instruction) -> Result<()> { + use Instruction::*; + let instruction = match instruction { + Call(address) if self.select && address == self.self_func_addr => CallSelf, + ReturnCall(address) if self.select && address == self.self_func_addr => ReturnCallSelf, + Return => self.return_instruction, + _ => instruction, + }; + self.push(instruction)?; + self.commit(self.instructions.len()); + Ok(()) + } + + fn push(&mut self, instruction: Instruction) -> Result<()> { + self.seal_jump(); + if self.instructions.len() >= u32::MAX as usize { + return Err(ParseError::Other("function body is too large".into())); + } + self.instructions.push(instruction); + Ok(()) + } + + fn seal_jump(&mut self) { + if let Some(label) = self.pending_jump.take() { + self.uses.push((PatchSite::Instruction(self.instructions.len() - 1), label)); + self.committed = self.instructions.len(); + } + } + + /// Appends and applies one statically selected family, without redispatching replacements. + #[inline] + pub(crate) fn emit_with( + &mut self, + data: &mut FunctionDataBuilder, + instruction: Instruction, + rules: impl FnOnce(&mut PendingTail<'_>, &mut FunctionDataBuilder) -> Result<()>, + ) -> Result<()> { + self.push(instruction)?; + if self.select { + rules(&mut PendingTail::new(&mut self.instructions, self.committed), data)?; + } + self.commit(self.instructions.len().saturating_sub(LOOKBEHIND).max(self.committed)); + Ok(()) + } + + /// Selects a conditional branch before sealing and recording its final patch site. + pub(crate) fn branch_if(&mut self, data: &mut FunctionDataBuilder, on_zero: bool, label: LabelId) -> Result<()> { + let instruction = if on_zero { Instruction::JumpIfZero32(0) } else { Instruction::JumpIfNonZero32(0) }; + self.emit_with(data, instruction, |tail, data| selection::conditional(tail, data, on_zero, 0))?; + // Conditional rules always retain a final target-bearing instruction. + assert!(self.instructions.len() > self.committed, "conditional rule removed its branch"); + let site = self.instructions.len() - 1; + self.uses.push((PatchSite::Instruction(site), label)); + self.commit(self.instructions.len()); + Ok(()) + } + + /// Emits a target-bearing instruction and records its symbolic destination. + /// Side operands must come from the non-deduplicating target operand allocators + /// and belong exclusively to this instruction. + pub(crate) fn branch(&mut self, instruction: Instruction, label: LabelId) -> Result<()> { + if self.select && matches!(instruction, Instruction::Jump(_)) { + self.commit(self.instructions.len()); + self.push(instruction)?; + self.pending_jump = Some(label); + return Ok(()); + } + self.emit(instruction)?; + let site = self.instructions.len() - 1; + self.uses.push((PatchSite::Instruction(site), label)); + self.commit(self.instructions.len()); + Ok(()) + } + + /// Commits table storage and records case and default destinations. + pub(crate) fn branch_table( + &mut self, + data: &mut FunctionDataBuilder, + targets: &[LabelId], + default: LabelId, + ) -> Result<()> { + let start = u32::try_from(data.branch_table_targets.len()) + .map_err(|_| ParseError::Other("branch table pool is too large".into()))?; + let count = u32::try_from(targets.len()).map_err(|_| ParseError::Other("branch table is too large".into()))?; + start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; + let operand = data.push_target128(Operand128::::new(0, start, count))?; + self.branch(Instruction::BranchTable(operand), default)?; + for &label in targets { + self.uses.push((PatchSite::TableEntry(data.branch_table_targets.len()), label)); + data.branch_table_targets.push(0); + } + Ok(()) + } + + /// Records exception boundaries and landing pads alongside their metadata. + pub(crate) fn exception_handler( + &mut self, + data: &mut FunctionDataBuilder, + start: LabelId, + end: LabelId, + catches: Vec<(ExceptionCatch, LabelId)>, + ) { + let index = data.exception_handlers.len(); + self.uses.push((PatchSite::ExceptionStart(index), start)); + self.uses.push((PatchSite::ExceptionEnd(index), end)); + let catches = catches + .into_iter() + .enumerate() + .map(|(catch_index, (catch, label))| { + self.uses.push((PatchSite::Catch(index, catch_index), label)); + catch + }) + .collect(); + data.exception_handlers.push(ExceptionHandler { start_ip: 0, end_ip: 0, catches }); + } + + fn commit(&mut self, end: usize) { + debug_assert!(self.committed <= end && end <= self.instructions.len()); + self.committed = end; + } + + /// Flushes the tail and resolves recorded targets without moving instructions. + pub(crate) fn finish(mut self, data: &mut FunctionDataBuilder) -> Result> { + self.seal_jump(); + self.commit(self.instructions.len()); + let invalid_site = || ParseError::Other("invalid label patch site".into()); + for (site, label) in self.uses { + let target = self + .labels + .get(label.0) + .copied() + .flatten() + .ok_or_else(|| ParseError::Other("referenced label is not bound".into()))?; + let boundary = matches!(site, PatchSite::ExceptionEnd(_)); + if target as usize > self.instructions.len() || (!boundary && target as usize == self.instructions.len()) { + return Err(ParseError::Other("label target out of bounds".into())); + } + match site { + PatchSite::Instruction(index) => { + let instruction = self.instructions.get_mut(index).ok_or_else(invalid_site)?; + Self::patch_target(instruction, data, target)?; + if let Instruction::BranchTable(index) = instruction { + let operand = data.operand128(*index); + let end = operand.start().checked_add(operand.size()).ok_or_else(invalid_site)?; + data.branch_table_targets + .get(operand.start() as usize..end as usize) + .ok_or_else(invalid_site)?; + } + } + PatchSite::TableEntry(index) => { + *data.branch_table_targets.get_mut(index).ok_or_else(invalid_site)? = target + } + PatchSite::ExceptionStart(index) => { + data.exception_handlers.get_mut(index).ok_or_else(invalid_site)?.start_ip = target + } + PatchSite::ExceptionEnd(index) => { + data.exception_handlers.get_mut(index).ok_or_else(invalid_site)?.end_ip = target + } + PatchSite::Catch(handler, catch) => { + let catch = data + .exception_handlers + .get_mut(handler) + .and_then(|handler| handler.catches.get_mut(catch)) + .ok_or_else(invalid_site)?; + match catch { + ExceptionCatch::Tag { landing_pad, .. } | ExceptionCatch::All { landing_pad, .. } => { + *landing_pad = target + } + } + } + } + } + for handler in &data.exception_handlers { + if handler.start_ip > handler.end_ip || handler.end_ip as usize > self.instructions.len() { + return Err(ParseError::Other("exception handler range out of bounds".into())); + } + } + Ok(self.instructions) + } + + fn patch_target(instruction: &mut Instruction, data: &mut FunctionDataBuilder, target: u32) -> Result<()> { + // Target operands are allocated separately from deduplicated immutable + // operands. Relocation changes only their target field, not pool layout. + macro_rules! patch { + ($index:expr, $pool:ident) => {{ + let operand = data + .$pool + .get_mut($index.index()) + .ok_or_else(|| ParseError::Other("target operand out of bounds".into()))?; + *operand = operand.with_target(target); + }}; + } + use Instruction::*; + match instruction { + Jump(value) + | JumpIfZero32(value) + | JumpIfNonZero32(value) + | JumpIfZero64(value) + | JumpIfNonZero64(value) + | JumpIfRefNull(value) + | JumpIfRefNonNull(value) => *value = target, + JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => { + arg.target_ip = target + } + JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => patch!(packed.index, operands64), + BrOnCast(index) | BrOnCastFail(index) => patch!(*index, operands64), + JumpCmpStackConst32(packed) => patch!(packed.index, operands64), + JumpCmpStackConst64(packed) => patch!(packed.index, operands128), + BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => patch!(packed.index, operands128), + BinOpLocalConstJumpCmpLocal32(packed) => patch!(packed.index, operands128), + BinOpGlobalConstJump32(packed) => patch!(packed.index, operands128), + IncLocalJump32(index) | IncStackTeeLocalJump32(index) => patch!(*index, operands128), + IncGlobalJump32(index) => patch!(*index, operands128), + IncLocalJumpCmpLocal32(packed) => patch!(packed.index, operands128), + JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => patch!(packed.index, operands128), + JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => patch!(packed.index, operands64), + BranchTable(index) => patch!(*index, operands128), + _ => return Err(ParseError::Other("unsupported instruction label patch".into())), + } + Ok(()) + } +} diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs index 4954056..2752d8b 100644 --- a/crates/parser/src/lib.rs +++ b/crates/parser/src/lib.rs @@ -30,10 +30,11 @@ pub(crate) mod log { } mod conversion; +mod emitter; mod error; mod macros; mod module; -mod optimize; +mod selection; mod validation; mod visit; @@ -62,8 +63,8 @@ pub struct ParserOptions { /// a module that violates runtime assumptions. pub validation: bool, - /// Whether to run the peephole rewrite optimizer. - pub optimize_rewrite: bool, + /// Whether to enable some of the optimizations during lowering, such as bounded instruction selection. + pub optimize: bool, /// Whether to deduplicate immutable function operands while parsing. pub deduplicate_operands: bool, @@ -76,17 +77,17 @@ pub struct ParserOptions { /// - `None`: auto-detect based on available parallelism /// - `Some(1)`: force single-threaded /// - `Some(n)`: use up to `n` workers - pub parser_threads: Option, + pub threads: Option, } impl Default for ParserOptions { fn default() -> Self { Self { validation: cfg!(feature = "validate"), - optimize_rewrite: true, - deduplicate_operands: false, + optimize: true, + deduplicate_operands: true, #[cfg(parallel_parser)] - parser_threads: None, + threads: None, } } } @@ -114,15 +115,15 @@ impl ParserOptions { self.validation } - /// Enable or disable the peephole rewrite optimizer. - pub const fn with_rewrite_optimization(mut self, enabled: bool) -> Self { - self.optimize_rewrite = enabled; + /// Enable or disable some of the optimizations during lowering, such as bounded instruction selection. + pub const fn with_optimize(mut self, enabled: bool) -> Self { + self.optimize = enabled; self } - /// Returns whether the peephole rewrite optimizer is enabled. - pub const fn optimize_rewrite(&self) -> bool { - self.optimize_rewrite + /// Returns whether some of the optimizations during lowering, such as bounded instruction selection, are enabled. + pub const fn optimize(&self) -> bool { + self.optimize } /// Enable or disable parse-time deduplication of immutable function operands. @@ -140,15 +141,15 @@ impl ParserOptions { /// Set the number of threads for parallel parsing. /// /// Requires the `parallel` feature to have any effect. - pub const fn with_parser_threads(mut self, threads: usize) -> Self { - self.parser_threads = Some(threads); + pub const fn with_threads(mut self, threads: usize) -> Self { + self.threads = Some(threads); self } #[cfg(parallel_parser)] /// Returns the configured parser thread count, or `None` for auto-detect. - pub const fn parser_threads(&self) -> Option { - self.parser_threads + pub const fn threads(&self) -> Option { + self.threads } } diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs index f807c0f..fe1364b 100644 --- a/crates/parser/src/macros.rs +++ b/crates/parser/src/macros.rs @@ -1,4 +1,20 @@ pub(crate) mod visit { + // Rule families are chosen at the call site, not by matching the emitted opcode. + // Unary instruction operands are evaluated once and passed after family arguments. + macro_rules! emit_selected { + ($builder:ident, $inputs:expr, $outputs:expr, $op:ident($value:expr) [$family:ident($($arg:expr),* $(,)?)]) => {{ + let operand = $value; + $builder.emit_with($inputs, $outputs, tinywasm_types::Instruction::$op(operand), + |tail, data| crate::selection::$family(tail, data $(, $arg)*, operand)) + }}; + ($builder:ident, $inputs:expr, $outputs:expr, $op:ident [$family:ident($($arg:expr),* $(,)?)]) => { + $builder.emit_with($inputs, $outputs, tinywasm_types::Instruction::$op, + |tail, data| crate::selection::$family(tail, data $(, $arg)*)) + }; + ($builder:ident, $inputs:expr, $outputs:expr, $op:ident $(($($value:expr),*))?) => { + $builder.emit($inputs, $outputs, tinywasm_types::Instruction::$op $(($($value),*))?) + }; + } #[cfg(feature = "validate")] macro_rules! validate_then_visit { ($( @$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*))*) => {$( @@ -25,12 +41,14 @@ pub(crate) mod visit { )*}; } + // Optional `[family(args)]` selects rules alongside the visitor's stack effect + // and fallback opcode. Instructions without a family use plain emission. macro_rules! lowering_ops { () => {}; ($kind:ident $inputs:tt => $outputs:tt { - $($visit:ident $(($($arg:ident: $ty:ty),+))? => $instr:ident),* $(,)? + $($visit:ident $(($($arg:ident: $ty:ty),+))? => $instr:ident $([$family:ident($($rule_arg:expr),*)])?),* $(,)? } $($rest:tt)*) => { - $(lowering_ops!(@$kind $inputs => $outputs $visit $(($($arg: $ty),+))? => $instr);)* + $(lowering_ops!(@$kind $inputs => $outputs $visit $(($($arg: $ty),+))? => $instr $([$family($($rule_arg),*)])?);)* lowering_ops!($($rest)*); }; (effect $inputs:tt => $outputs:tt { $($visit:ident),* $(,)? } $($rest:tt)*) => { @@ -47,7 +65,7 @@ pub(crate) mod visit { $( fn $visit(&mut self, heap_type: wasmparser::HeapType) -> Self::Output { let ty = convert_heap_type(heap_type, $nullable)?; - lowering_ops!(@emit self fixed $inputs => $outputs Instruction::$instr(ty)) + lowering_ops!(@emit self fixed $inputs => $outputs $instr(ty)) } )* lowering_ops!($($rest)*); @@ -60,31 +78,31 @@ pub(crate) mod visit { }; (@fixed [$($input:ident),*] => [$($output:ident),*] - $visit:ident $(($($arg:ident: $ty:ty),+))? => $instr:ident + $visit:ident $(($($arg:ident: $ty:ty),+))? => $instr:ident $([$family:ident($($rule_arg:expr),*)])? ) => { fn $visit(&mut self $(, $($arg: $ty),+)?) -> Self::Output { lowering_ops!(@emit self fixed [$($input),*] => [$($output),*] - Instruction::$instr $(($($arg),+))?.into()) + $instr $(($($arg),+))? $([$family($($rule_arg),*)])?) } }; (@memory [$($input:ident),*] => [$($output:ident),*] - $visit:ident $(($lane:ident: $ty:ty))? => $instr:ident + $visit:ident $(($lane:ident: $ty:ty))? => $instr:ident $([$family:ident($($rule_arg:expr),*)])? ) => { fn $visit(&mut self, memarg: wasmparser::MemArg $(, $lane: $ty)?) -> Self::Output { let address = self.metadata.memory_size(memarg.memory)?; self.mark_memory(memarg.memory); - let memory_arg_idx = self.push_operand128(tinywasm_types::Operand128::< + let memory_arg_idx = self.push128(tinywasm_types::Operand128::< tinywasm_types::MemoryOperand, >::new(memarg.offset, memarg.memory))?; lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*] - lowering_ops!(@memory_instruction $instr memory_arg_idx $(, $lane)?)) + $instr(lowering_ops!(@memory_arg memory_arg_idx $(, $lane)?)) $([$family($($rule_arg),*)])?) } }; - (@memory_instruction $instr:ident $memory_arg_idx:ident) => { - Instruction::$instr($memory_arg_idx) + (@memory_arg $memory_arg_idx:ident) => { + $memory_arg_idx }; - (@memory_instruction $instr:ident $memory_arg_idx:ident, $lane:ident) => { - Instruction::$instr(tinywasm_types::MemoryLaneArg { memory_arg_idx: $memory_arg_idx, lane: $lane }) + (@memory_arg $memory_arg_idx:ident, $lane:ident) => { + tinywasm_types::MemoryLaneArg { memory_arg_idx: $memory_arg_idx, lane: $lane } }; (@global $inputs:tt => $outputs:tt $($operator:tt)*) => { lowering_ops!(@resolved global_size $inputs => $outputs $($operator)*); @@ -93,13 +111,13 @@ pub(crate) mod visit { lowering_ops!(@memory_index_impl $inputs => $outputs $($operator)*); }; (@memory_index_impl [$($input:ident),*] => [$($output:ident),*] - $visit:ident($index:ident: $ty:ty) => $instr:ident + $visit:ident($index:ident: $ty:ty) => $instr:ident $([$family:ident($($rule_arg:expr),*)])? ) => { fn $visit(&mut self, $index: $ty) -> Self::Output { let address = self.metadata.memory_size($index)?; self.mark_memory($index); lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*] - Instruction::$instr($index).into()) + $instr($index) $([$family($($rule_arg),*)])?) } }; (@table $inputs:tt => $outputs:tt $($operator:tt)*) => { @@ -111,7 +129,7 @@ pub(crate) mod visit { fn $visit(&mut self, $type_index: $type_ty $(, $arg: $arg_ty)*) -> Self::Output { let size = self.metadata.array_field($type_index)?; lowering_ops!(@emit self address(size) [$($input),*] => [$($output),*] - Instruction::$instr($type_index $(, $arg)*).into()) + $instr($type_index $(, $arg)*)) } }; (@resolved $resolver:ident [$($input:ident),*] => [$($output:ident),*] @@ -120,7 +138,7 @@ pub(crate) mod visit { fn $visit(&mut self, $index: $ty) -> Self::Output { let address = self.metadata.$resolver($index)?; lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*] - Instruction::$instr($index).into()) + $instr($index)) } }; (@resolved $resolver:ident [$($input:ident),*] => [$($output:ident),*] @@ -129,7 +147,7 @@ pub(crate) mod visit { fn $visit(&mut self, $arg: $arg_ty, $index: $index_ty) -> Self::Output { let address = self.metadata.$resolver($index)?; lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*] - Instruction::$instr($arg, $index).into()) + $instr($arg, $index)) } }; (@effect [$($input:ident),*] => [$($output:ident),*] $visit:ident) => { @@ -140,22 +158,26 @@ pub(crate) mod visit { (@terminating [$($input:ident),*] => [$($output:ident),*] $visit:ident => $instr:ident) => { fn $visit(&mut self) -> Self::Output { self.mark_unreachable(); - lowering_ops!(@emit self fixed [$($input),*] => [$($output),*] Instruction::$instr) + self.emit_boundary( + &[$(lowering_ops!(@size $input)),*], + &[$(lowering_ops!(@size $output)),*], + Instruction::$instr, + ) } }; - (@emit $self:ident fixed [$($input:ident),*] => [$($output:ident),*] $instruction:expr) => { - $self.emit( + (@emit $self:ident fixed [$($input:ident),*] => [$($output:ident),*] $($instruction:tt)+) => { + emit_selected!($self, &[$(lowering_ops!(@size $input)),*], &[$(lowering_ops!(@size $output)),*], - $instruction, + $($instruction)+ ) }; - (@emit $self:ident address($address:ident) [$($input:ident),*] => [$($output:ident),*] $instruction:expr) => { - $self.emit( + (@emit $self:ident address($address:ident) [$($input:ident),*] => [$($output:ident),*] $($instruction:tt)+) => { + emit_selected!($self, &[$(lowering_ops!(@size $input, $address)),*], &[$(lowering_ops!(@size $output, $address)),*], - $instruction, + $($instruction)+ ) }; @@ -189,68 +211,7 @@ pub(crate) mod visit { }; } - pub(crate) use {impl_visit_operator, lowering_ops}; + pub(crate) use {emit_selected, impl_visit_operator, lowering_ops}; #[cfg(feature = "validate")] pub(crate) use {validate_then_visit, validate_then_visit_simd}; } - -pub(crate) mod optimize { - macro_rules! replace { - ($instructions:ident, $read:ident, $consumed:expr => [$($out:expr),+ $(,)?]) => {{ - const { - assert!($consumed >= 1 && $consumed <= 3); - assert!([$(stringify!($out)),+].len() <= $consumed + 1); - } - let replacements = [$($out),+]; - let start = $read - $consumed; - $instructions[start..start + replacements.len()].copy_from_slice(&replacements); - $instructions.truncate(start + replacements.len()); - #[allow(unused_assignments)] - { $read = $instructions.len() - 1; } - }}; - ($instructions:ident, $read:ident, $consumed:expr => $out:expr) => { - replace!($instructions, $read, $consumed => [$out]); - }; - ($instructions:ident, *$read:ident, $consumed:expr => [$($out:expr),+ $(,)?]) => {{ - const { - assert!($consumed >= 1 && $consumed <= 3); - assert!([$(stringify!($out)),+].len() <= $consumed + 1); - } - let replacements = [$($out),+]; - let start = *$read - $consumed; - $instructions[start..start + replacements.len()].copy_from_slice(&replacements); - $instructions.truncate(start + replacements.len()); - *$read = $instructions.len() - 1; - }}; - ($instructions:ident, *$read:ident, $consumed:expr => $out:expr) => { - replace!($instructions, *$read, $consumed => [$out]) - }; - } - - macro_rules! rewrite { - ($instructions:ident, $read:ident, [$($pattern:pat),+] $(if ($($guard:tt)+))? => [$($out:expr),+ $(,)?]) => { - rewrite!($instructions, $read, [$($pattern),+] $(if ($($guard)+))? => { - replace!($instructions, $read, [$(stringify!($pattern)),+].len() => [$($out),+]); - }) - }; - ($instructions:ident, $read:ident, [$($pattern:pat),+] $(if ($($guard:tt)+))? => $body:block $(,)?) => {{ - const CONSUMED: usize = [$(stringify!($pattern)),+].len(); - if $read >= $instructions.block_start + CONSUMED { - let previous: [Instruction; CONSUMED] = $instructions[$read - CONSUMED..$read].try_into().unwrap(); - if let [$($pattern),+] = previous $( - && $($guard)+ - )? { - $body - continue; - } - } - }}; - ($instructions:ident, $read:ident, [$($pattern:pat),+] $(if ($($guard:tt)+))? => $out:expr $(,)?) => { - rewrite!($instructions, $read, [$($pattern),+] $(if ($($guard)+))? => { - replace!($instructions, $read, [$(stringify!($pattern)),+].len() => $out); - }) - }; - } - - pub(crate) use {replace, rewrite}; -} diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index 4cd4406..03c725c 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -2,44 +2,21 @@ use crate::log::debug; #[cfg(parallel_parser)] use crate::validation::{FuncToValidate, ValidatorResources}; use crate::validation::{FuncValidatorAllocations, Validator}; -use crate::{ParseError, ParserOptions, Result, conversion::*, optimize}; +use crate::{ParseError, ParserOptions, Result, conversion::*}; use alloc::{boxed::Box, format, string::ToString, vec::Vec}; use core::marker::PhantomData; use core::ops::Range; use tinywasm_types::*; use wasmparser::{OperatorsReaderAllocations, Payload}; +/// Final bytecode and metadata produced by streaming function lowering. pub(crate) struct FunctionCode { - pub instructions: Vec, - pub data: crate::visit::FunctionDataBuilder, - pub locals: ValueCounts, - pub uses_local_memory: bool, -} - -pub(crate) struct OptimizedFunctionCode { pub instructions: Vec, pub data: WasmFunctionData, pub locals: ValueCounts, pub uses_local_memory: bool, } -pub(crate) fn optimize_function_code( - mut code: FunctionCode, - options: &ParserOptions, - function_results: ValueCounts, - self_func_addr: u32, -) -> Result { - let optimized = - optimize::optimize_instructions(code.instructions, &mut code.data, options, function_results, self_func_addr)?; - let data = code.data.finish(); - Ok(OptimizedFunctionCode { - instructions: optimized.instructions, - data, - locals: code.locals, - uses_local_memory: code.uses_local_memory, - }) -} - #[derive(Default)] pub(crate) struct ModuleReader<'a> { func_validator_allocations: Option, @@ -56,7 +33,7 @@ pub(crate) struct ModuleReader<'a> { pub(crate) code_type_addrs: Box<[u32]>, code_results: Box<[ValueCounts]>, pub(crate) exports: Shared<[Export]>, - pub(crate) code: Vec, + pub(crate) code: Vec, pub(crate) globals: Box<[Global]>, pub(crate) tables: Box<[TableDefinition]>, pub(crate) memory_types: Box<[MemoryType]>, @@ -400,17 +377,21 @@ impl<'a> ModuleReader<'a> { .code_type_addrs .get(ordinal) .ok_or_else(|| ParseError::Other("code entry has no function signature".into()))?; + let context = FunctionLoweringContext { + ty_idx, + self_func_addr: self + .imported_func_count + .checked_add(ordinal) + .and_then(|idx| u32::try_from(idx).ok()) + .ok_or_else(|| ParseError::Other("function index is too large".into()))?, + function_results: self.code_results[ordinal], + }; let metadata = self.translation_metadata(); let (code, func_validator_allocs, operators_reader_allocs) = - convert_module_code(function, func_validator, operators_reader_allocs, metadata, ty_idx, options)?; - - self.code.push(optimize_function_code( - code, - options, - self.code_results[self.code.len()], - (self.imported_func_count + self.code.len()) as u32, - )?); + convert_module_code(function, func_validator, operators_reader_allocs, metadata, context, options)?; + + self.code.push(code); self.func_validator_allocations = func_validator_allocs; self.operators_reader_allocations = Some(operators_reader_allocs); diff --git a/crates/parser/src/optimize/mod.rs b/crates/parser/src/optimize/mod.rs deleted file mode 100644 index 09501f9..0000000 --- a/crates/parser/src/optimize/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -mod rewrite; -mod targets; - -pub(crate) use rewrite::optimize_instructions; diff --git a/crates/parser/src/optimize/rewrite.rs b/crates/parser/src/optimize/rewrite.rs deleted file mode 100644 index 366a094..0000000 --- a/crates/parser/src/optimize/rewrite.rs +++ /dev/null @@ -1,1500 +0,0 @@ -use super::targets::{finalize, resolve_jump_target, set_rewrite_target, target_boundaries}; -use crate::macros::optimize::{replace, rewrite}; -use crate::visit::FunctionDataBuilder as WasmFunctionData; -use crate::{ParserOptions, Result}; -use alloc::vec::Vec; -use core::ops::{Deref, DerefMut}; -use tinywasm_types::{ - BinOp, BinOp128, CmpOp, CompactMemoryArg, CompactMemoryOperand, GlobalUpdateOperand, I32LocalArg, Instruction, - LocalTripleArg, LocalUpdateCmpOperand, LocalUpdateOperand, MemoryFillOperand, MemoryLocalArg, MemoryOperand, - Operand64, Operand64Idx, Operand128, Operand128Idx, PackedOp, TargetLocalArg, ValueCounts, -}; - -pub(crate) struct OptimizeResult { - pub(crate) instructions: Vec, -} - -struct CompactOutput { - instructions: Vec, - block_start: usize, -} - -impl Deref for CompactOutput { - type Target = Vec; - - fn deref(&self) -> &Self::Target { - &self.instructions - } -} - -impl DerefMut for CompactOutput { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.instructions - } -} - -pub(crate) fn optimize_instructions( - mut instructions: Vec, - function_data: &mut WasmFunctionData, - options: &ParserOptions, - function_results: ValueCounts, - self_func_addr: u32, -) -> Result { - let boundaries = target_boundaries(&instructions, function_data)?; - let (rewritten, old_to_new) = if options.optimize_rewrite() { - let (instructions, map) = rewrite(instructions, function_data, &boundaries, function_results, self_func_addr)?; - (instructions, Some(map)) - } else { - (instructions, None) - }; - instructions = rewritten; - finalize(&mut instructions, function_data, old_to_new.as_deref())?; - Ok(OptimizeResult { instructions }) -} - -fn rewrite( - source: Vec, - data: &mut WasmFunctionData, - boundaries: &[bool], - function_results: ValueCounts, - self_func_addr: u32, -) -> Result<(Vec, Vec)> { - #![allow(unused_assignments)] - use Instruction::*; - - let return_instruction = match function_results { - ValueCounts { c32: 0, c64: 0, c128: 0 } => Some(ReturnVoid), - ValueCounts { c32: 1, c64: 0, c128: 0 } => Some(Return32), - ValueCounts { c32: 0, c64: 1, c128: 0 } => Some(Return64), - ValueCounts { c32: 0, c64: 0, c128: 1 } => Some(Return128), - _ => None, - }; - let mut output = CompactOutput { instructions: Vec::with_capacity(source.len()), block_start: 0 }; - let mut old_to_new = alloc::vec![0; source.len() + 1]; - let mut after_terminator = false; - - for (old_index, instruction) in source.iter().copied().enumerate() { - if boundaries[old_index] || after_terminator { - output.block_start = output.len(); - } - after_terminator = is_unconditional_terminator(instruction); - old_to_new[old_index] = output.len() as u32; - output.push(instruction); - let mut read = output.len() - 1; - - match output[read] { - LocalCopy32(a, b) | LocalCopy64(a, b) | LocalCopy128(a, b) if a == b => { - output.pop(); - } - Call(address) if address == self_func_addr => output[read] = CallSelf, - ReturnCall(address) if address == self_func_addr => output[read] = ReturnCallSelf, - Return if let Some(specialized) = return_instruction => output[read] = specialized, - raw @ (I32Add | I32Mul | I32And | I32Or | I32Xor) => { - let op = int_bin_op(raw).unwrap(); - rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); - rewrite!(output, read, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); - rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - if rewrite_scalar_const32(&mut output, &mut read, data, op, true)? { - continue; - } - if op == BinOp::IAdd { - rewrite!(output, read, [Const32(value)] => AddConst32(value)); - rewrite!(output, read, [I32Add] => I32Add3); - if read > output.block_start - && let BinOpStackLocal32(BinOp::IAdd, local) = output[read - 1] - { - output.truncate(read - 1); - output.extend([LocalGet32(local), I32Add3]); - read = output.len() - 1; - } - } else { - rewrite!(output, read, [Const32(value)] => stack_const32(op, value)); - } - } - raw @ (I32Sub | I32Shl | I32ShrS | I32ShrU | I32Rotl | I32Rotr) => { - let op = int_bin_op(raw).unwrap(); - rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); - rewrite!(output, read, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); - rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - if rewrite_scalar_const32(&mut output, &mut read, data, op, false)? { - continue; - } - if rewrite_sign_extend32(&mut output, &mut read, data, op) { - continue; - } - rewrite!(output, read, [Const32(value)] => stack_const32(op, value)); - } - raw @ (I64Add | I64Mul | I64And | I64Or | I64Xor) => { - let op = int_bin_op(raw).unwrap(); - rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite!(output, read, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); - if rewrite_scalar_const64(&mut output, &mut read, data, op, true)? { - continue; - } - if op == BinOp::IAdd { - rewrite!(output, read, [Const64(index)] => AddConst64(index)); - rewrite!(output, read, [I64Add] => I64Add3); - } else { - rewrite!(output, read, [Const64(index)] => BinOpStackConst64(PackedOp::new(op, index))); - } - } - raw @ (I64Sub | I64Shl | I64ShrS | I64ShrU | I64Rotl | I64Rotr) => { - let op = int_bin_op(raw).unwrap(); - rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite!(output, read, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); - if rewrite_scalar_const64(&mut output, &mut read, data, op, false)? { - continue; - } - if rewrite_sign_extend64(&mut output, &mut read, data, op) { - continue; - } - rewrite!(output, read, [Const64(index)] => BinOpStackConst64(PackedOp::new(op, index))); - } - raw if cmp_op(raw).is_some() => { - let op = cmp_op(raw).unwrap(); - rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => CmpLocalLocal32(op, a, b)); - rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => CmpLocalLocal64(op, a, b)); - } - raw @ (F32Add | F32Mul | F32Min | F32Max) => { - let op = float_bin_op(raw).unwrap(); - rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); - rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - if !rewrite_scalar_const32(&mut output, &mut read, data, op, true)? { - rewrite!(output, read, [Const32(value)] => stack_const32(op, value)); - } - } - raw @ (F32Sub | F32Div | F32Copysign) => { - let op = float_bin_op(raw).unwrap(); - rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); - rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - if !rewrite_scalar_const32(&mut output, &mut read, data, op, false)? { - rewrite!(output, read, [Const32(value)] => stack_const32(op, value)); - } - } - raw @ (F64Add | F64Mul | F64Min | F64Max) => { - let op = float_bin_op(raw).unwrap(); - rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - if !rewrite_scalar_const64(&mut output, &mut read, data, op, true)? { - rewrite!(output, read, [Const64(index)] => BinOpStackConst64(PackedOp::new(op, index))); - } - } - raw @ (F64Sub | F64Div | F64Copysign) => { - let op = float_bin_op(raw).unwrap(); - rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - if !rewrite_scalar_const64(&mut output, &mut read, data, op, false)? { - rewrite!(output, read, [Const64(index)] => BinOpStackConst64(PackedOp::new(op, index))); - } - } - raw @ (V128And | V128Or | V128Xor | I64x2Add | I64x2Mul | V128AndNot) => { - let op = bin_op_128(raw).unwrap(); - rewrite!(output, read, [LocalGet128(local)] => - BinOpStackLocal128(op, local) - ); - rewrite_vector_binop(&mut output, &mut read, data, op, raw != V128AndNot)?; - } - I32Store(index) | F32Store(index) => rewrite_store32(&mut output, &mut read, data, index)?, - I64Store(index) | F64Store(index) => rewrite_store64(&mut output, &mut read, data, index)?, - V128Store(index) => { - if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { - rewrite!(output, read, - [LocalGet32(addr), LocalGet128(value)] if - (let (Ok(addr), Ok(value)) = (u8::try_from(addr), u8::try_from(value))) => - StoreLocalLocal128(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value }) - ); - } - } - I32Load(index) | F32Load(index) => { - if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { - rewrite!(output, read, [LocalGet32(local) | LocalGet64(local)] if - (let Ok(local) = u8::try_from(local)) => - LoadLocal32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }) - ); - } - } - I64Load(index) | F64Load(index) => { - if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { - rewrite!(output, read, [LocalGet32(local) | LocalGet64(local)] if - (let Ok(local) = u8::try_from(local)) => - LoadLocal64(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }) - ); - } - } - raw @ (I32Load8S(index) | I32Load8U(index) | I32Load16S(index) | I32Load16U(index)) => { - if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { - rewrite!(output, read, [LocalGet32(local) | LocalGet64(local)] if - (let Ok(local) = u8::try_from(local)) => match raw { - I32Load8S(_) => LoadLocal8S32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), - I32Load8U(_) => LoadLocal8U32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), - I32Load16S(_) => LoadLocal16S32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), - I32Load16U(_) => LoadLocal16U32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), - _ => unreachable!(), - } - ); - } - } - MemoryFill(memory) => rewrite!(output, read, [Const32(value), Const32(size)] => { - let index = data.push_operand128(Operand128::::new(memory, value as u8, size))?; - replace!(output, read, 2 => MemoryFillConst(index)); - }), - GlobalGet32(dst) => rewrite!(output, read, [GlobalSet32(src)] if (src == dst) => GlobalTee32(src)), - GlobalGet64(dst) => rewrite!(output, read, [GlobalSet64(src)] if (src == dst) => GlobalTee64(src)), - GlobalGet128(dst) => rewrite!(output, read, [GlobalSet128(src)] if (src == dst) => GlobalTee128(src)), - LocalGet32(dst) => rewrite!(output, read, [LocalSet32(src)] if (src == dst) => LocalTee32(src)), - LocalGet64(dst) => rewrite!(output, read, [LocalSet64(src)] if (src == dst) => LocalTee64(src)), - LocalGet128(dst) => rewrite!(output, read, [LocalSet128(src)] if (src == dst) => LocalTee128(src)), - LocalSet32(dst) => rewrite_local_set32(&mut output, &mut read, data, dst)?, - LocalSet64(dst) => rewrite_local_set64(&mut output, &mut read, data, dst)?, - LocalSet128(dst) => rewrite_local_set128(&mut output, &mut read, data, dst)?, - LocalTee32(dst) => rewrite_local_tee32(&mut output, &mut read, data, dst)?, - LocalTee64(dst) => rewrite_local_tee64(&mut output, &mut read, data, dst)?, - LocalTee128(dst) => rewrite_local_tee128(&mut output, &mut read, data, dst)?, - Drop32 => { - rewrite!(output, read, [LocalTee32(local)] => LocalSet32(local)); - rewrite!(output, read, [BinOpStackLocalTee32(op, local, dst)] => BinOpStackLocalSet32(op, local, dst)); - rewrite!(output, read, [AddLocalLocalTee32(arg)] => AddLocalLocalSet32(arg)); - rewrite!(output, read, [BinOpLocalLocalTee32(packed)] => BinOpLocalLocalSet32(packed)); - rewrite!(output, read, [BinOpLocalConstTee32(packed)] => BinOpLocalConstSet32(packed)); - } - Drop64 => { - rewrite!(output, read, [LocalTee64(local)] => LocalSet64(local)); - rewrite!(output, read, [BinOpLocalLocalTee64(packed)] => BinOpLocalLocalSet64(packed)); - rewrite!(output, read, [BinOpLocalConstTee64(packed)] => BinOpLocalConstSet64(packed)); - } - Drop128 => { - rewrite!(output, read, [LocalTee128(local)] => LocalSet128(local)); - rewrite!(output, read, [BinOpLocalLocalTee128(packed)] => BinOpLocalLocalSet128(packed)); - rewrite!(output, read, [BinOpLocalConstTee128(packed)] => BinOpLocalConstSet128(packed)); - } - Jump(target) => rewrite_jump(&source, &mut output, read, data, old_index as u32, target)?, - JumpIfZero32(target) => rewrite_conditional(&source, &mut output, &mut read, data, target, true)?, - JumpIfNonZero32(target) => rewrite_conditional(&source, &mut output, &mut read, data, target, false)?, - JumpIfZero64(target) => { - rewrite!(output, read, [LocalGet64(local)] => - JumpIfLocalZero64(TargetLocalArg { target_ip: target, local }) - ); - } - JumpIfNonZero64(target) => { - rewrite!(output, read, [LocalGet64(local)] => - JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local }) - ); - } - JumpCmpStackConst32(_) - | JumpCmpStackConst64(_) - | JumpCmpLocalConst32(_) - | JumpCmpLocalConst64(_) - | JumpCmpLocalLocal32(_) - | JumpCmpLocalLocal64(_) - | JumpIfLocalZero32(_) - | JumpIfLocalNonZero32(_) - | JumpIfLocalZero64(_) - | JumpIfLocalNonZero64(_) => {} - _ => {} - } - } - for instruction in &mut output.instructions { - match *instruction { - Instruction::Const64(index) => { - let value = data.operand64(index).value(); - if value == i64::from(value as i32) { - *instruction = Instruction::Const64Imm(value as i32); - } - } - Instruction::Const128(index) => { - if let Ok(value) = u32::try_from(u128::from_le_bytes(data.operand128(index).value())) { - *instruction = Instruction::Const128Imm(value); - } - } - _ => {} - } - } - let end = old_to_new.len() - 1; - old_to_new[end] = output.len() as u32; - Ok((output.instructions, old_to_new)) -} - -fn local_const32(data: &WasmFunctionData, instruction: Instruction) -> Option<(BinOp, u16, i32)> { - match instruction { - Instruction::AddLocalConst32(arg) => Some((BinOp::IAdd, arg.local, arg.value)), - Instruction::SubLocalConst32(arg) => Some((BinOp::ISub, arg.local, arg.value)), - Instruction::MulLocalConst32(arg) => Some((BinOp::IMul, arg.local, arg.value)), - Instruction::AndLocalConst32(arg) => Some((BinOp::IAnd, arg.local, arg.value)), - Instruction::ShrULocalConst32(arg) => Some((BinOp::IShrU, arg.local, arg.value)), - Instruction::BinOpLocalConst32(packed) => { - let value = data.operand64(packed.index); - Some((packed.op, value.a(), value.b() as i32)) - } - _ => None, - } -} - -fn local_const64(data: &WasmFunctionData, instruction: Instruction) -> Option<(BinOp, u16, i64)> { - let Instruction::BinOpLocalConst64(packed) = instruction else { return None }; - let value = data.operand128(packed.index); - Some((packed.op, value.a(), value.b() as i64)) -} - -fn local_const128( - data: &WasmFunctionData, - instruction: Instruction, -) -> Option<(BinOp128, u16, Operand128Idx<[u8; 16]>)> { - let Instruction::BinOpLocalConst128(packed) = instruction else { return None }; - let value = data.operand64(packed.index); - Some((packed.op, value.a(), value.b())) -} - -fn compact_memory_arg( - data: &mut WasmFunctionData, - index: Operand128Idx, -) -> Result>> { - let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) else { return Ok(None) }; - Ok(Some(data.push_operand64(Operand64::from(arg))?)) -} - -fn rewrite_scalar_const32( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - op: BinOp, - commutative: bool, -) -> Result { - if *read < output.block_start + 2 { - return Ok(false); - } - let previous = &output[*read - 2..*read]; - let replacement = match previous { - [Instruction::LocalGet32(local), Instruction::Const32(value)] => { - let arg = I32LocalArg { value: *value, local: *local }; - match op { - BinOp::IAdd => Instruction::AddLocalConst32(arg), - BinOp::ISub => Instruction::SubLocalConst32(arg), - BinOp::IMul => Instruction::MulLocalConst32(arg), - BinOp::IAnd => Instruction::AndLocalConst32(arg), - BinOp::IShrU => Instruction::ShrULocalConst32(arg), - _ => Instruction::BinOpLocalConst32(PackedOp::new( - op, - data.push_operand64(Operand64::<(u16, u32)>::new(*local, *value as u32))?, - )), - } - } - [Instruction::GlobalGet32(global), Instruction::Const32(value)] => Instruction::BinOpGlobalConst32( - PackedOp::new(op, data.push_operand64(Operand64::<(u32, u32)>::new(*global, *value as u32))?), - ), - [Instruction::Const32(value), Instruction::LocalGet32(local)] if commutative => { - let arg = I32LocalArg { value: *value, local: *local }; - match op { - BinOp::IAdd => Instruction::AddLocalConst32(arg), - BinOp::IMul => Instruction::MulLocalConst32(arg), - BinOp::IAnd => Instruction::AndLocalConst32(arg), - _ => Instruction::BinOpLocalConst32(PackedOp::new( - op, - data.push_operand64(Operand64::<(u16, u32)>::new(*local, *value as u32))?, - )), - } - } - [Instruction::Const32(value), Instruction::GlobalGet32(global)] if commutative => { - Instruction::BinOpGlobalConst32(PackedOp::new( - op, - data.push_operand64(Operand64::<(u32, u32)>::new(*global, *value as u32))?, - )) - } - _ => return Ok(false), - }; - replace!(output, *read, 2 => replacement); - Ok(true) -} - -fn stack_const32(op: BinOp, value: i32) -> Instruction { - match op { - BinOp::IAnd => Instruction::AndConst32(value), - BinOp::IXor => Instruction::XorConst32(value), - BinOp::IShrU => Instruction::ShrUConst32(value), - _ => Instruction::BinOpStackConst32(op, value), - } -} - -fn rewrite_scalar_const64( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - op: BinOp, - commutative: bool, -) -> Result { - if *read < output.block_start + 2 { - return Ok(false); - } - let previous = [output[*read - 2], output[*read - 1]]; - let replacement = match previous { - [Instruction::LocalGet64(local), Instruction::Const64(index)] => Instruction::BinOpLocalConst64(PackedOp::new( - op, - data.push_operand128(Operand128::<(u16, u64)>::new(local, data.operand64(index).value() as u64))?, - )), - [Instruction::GlobalGet64(global), Instruction::Const64(index)] => { - Instruction::BinOpGlobalConst64(PackedOp::new( - op, - data.push_operand128(Operand128::<(u32, u64)>::new(global, data.operand64(index).value() as u64))?, - )) - } - [Instruction::Const64(index), Instruction::LocalGet64(local)] if commutative => { - Instruction::BinOpLocalConst64(PackedOp::new( - op, - data.push_operand128(Operand128::<(u16, u64)>::new(local, data.operand64(index).value() as u64))?, - )) - } - [Instruction::Const64(index), Instruction::GlobalGet64(global)] if commutative => { - Instruction::BinOpGlobalConst64(PackedOp::new( - op, - data.push_operand128(Operand128::<(u32, u64)>::new(global, data.operand64(index).value() as u64))?, - )) - } - _ => return Ok(false), - }; - replace!(output, *read, 2 => replacement); - Ok(true) -} - -fn rewrite_sign_extend32(output: &mut CompactOutput, read: &mut usize, data: &WasmFunctionData, op: BinOp) -> bool { - if op != BinOp::IShrS || *read < output.block_start + 2 { - return false; - } - if let Some((BinOp::IShl, local, shift)) = local_const32(data, output[*read - 2]) - && let Instruction::Const32(right) = output[*read - 1] - && shift == right - && matches!(shift, 16 | 24) - { - output.truncate(*read - 2); - output.extend([ - Instruction::LocalGet32(local), - if shift == 24 { Instruction::I32Extend8S } else { Instruction::I32Extend16S }, - ]); - *read = output.len() - 1; - return true; - } - false -} - -fn rewrite_sign_extend64(output: &mut CompactOutput, read: &mut usize, data: &WasmFunctionData, op: BinOp) -> bool { - if op != BinOp::IShrS || *read < output.block_start + 2 { - return false; - } - if let Some((BinOp::IShl, local, shift)) = local_const64(data, output[*read - 2]) - && let Instruction::Const64(index) = output[*read - 1] - && shift == data.operand64(index).value() - { - let instruction = match shift { - 56 => Instruction::I64Extend8S, - 48 => Instruction::I64Extend16S, - 32 => Instruction::I64Extend32S, - _ => return false, - }; - output.truncate(*read - 2); - output.extend([Instruction::LocalGet64(local), instruction]); - *read = output.len() - 1; - return true; - } - false -} - -fn rewrite_vector_binop( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - op: BinOp128, - commutative: bool, -) -> Result<()> { - if *read >= output.block_start + 2 { - let previous = [output[*read - 2], output[*read - 1]]; - let replacement = match previous { - [Instruction::LocalGet128(a), Instruction::LocalGet128(b)] => Instruction::BinOpLocalLocal128(op, a, b), - [Instruction::LocalGet128(local), Instruction::Const128(value)] => Instruction::BinOpLocalConst128( - PackedOp::new(op, data.push_operand64(Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(local, value))?), - ), - [Instruction::GlobalGet128(global), Instruction::Const128(value)] => { - Instruction::BinOpGlobalConst128(PackedOp::new( - op, - data.push_operand64(Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(global, value))?, - )) - } - [Instruction::Const128(value), Instruction::LocalGet128(local)] if commutative => { - Instruction::BinOpLocalConst128(PackedOp::new( - op, - data.push_operand64(Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(local, value))?, - )) - } - [Instruction::Const128(value), Instruction::GlobalGet128(global)] if commutative => { - Instruction::BinOpGlobalConst128(PackedOp::new( - op, - data.push_operand64(Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(global, value))?, - )) - } - _ => return Ok(()), - }; - replace!(output, *read, 2 => replacement); - } - Ok(()) -} - -fn rewrite_store32( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - index: Operand128Idx, -) -> Result<()> { - let compact_arg = CompactMemoryArg::try_from(data.operand128(index)).ok(); - if *read > output.block_start && output[*read - 1] == Instruction::Select32 { - replace!(output, *read, 1 => Instruction::SelectStore32(index)); - return Ok(()); - } - if *read >= output.block_start + 3 { - let previous = [output[*read - 3], output[*read - 2], output[*read - 1]]; - if let [ - Instruction::LocalGet32(addr) | Instruction::LocalGet64(addr), - Instruction::LoadLocal32(arg), - Instruction::AddConst32(1), - ] = previous - && { compact_arg.map(Operand64::from) == Some(data.operand64(arg.memory_arg_idx)) } - && addr == u16::from(arg.local1) - { - replace!(output, *read, 3 => Instruction::IncMemoryLocal32(arg)); - return Ok(()); - } - } - if *read >= output.block_start + 2 { - let previous = [output[*read - 2], output[*read - 1]]; - match previous { - [Instruction::F32Mul, Instruction::F32Add] - if let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) => - { - replace!(output, *read, 2 => Instruction::FMaStoreF32(arg)); - } - [Instruction::BinOpStackLocal32(BinOp::FMul, local), Instruction::F32Add] - if let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) => - { - replace!(output, *read, 2 => [Instruction::LocalGet32(local), Instruction::FMaStoreF32(arg)]); - } - [Instruction::LocalGet32(addr), Instruction::LocalGet32(value)] - if let (Ok(addr), Ok(value), Some(memory_arg)) = - (u8::try_from(addr), u8::try_from(value), compact_arg) => - { - let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?; - replace!(output, *read, 2 => Instruction::StoreLocalLocal32(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value })); - } - _ => {} - } - } - Ok(()) -} - -fn rewrite_store64( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - index: Operand128Idx, -) -> Result<()> { - let compact_arg = CompactMemoryArg::try_from(data.operand128(index)).ok(); - if *read > output.block_start && output[*read - 1] == Instruction::Select64 { - replace!(output, *read, 1 => Instruction::SelectStore64(index)); - return Ok(()); - } - if *read >= output.block_start + 3 { - let previous = [output[*read - 3], output[*read - 2], output[*read - 1]]; - if let [ - Instruction::LocalGet32(addr) | Instruction::LocalGet64(addr), - Instruction::LoadLocal64(arg), - Instruction::AddConst64(one), - ] = previous - && { compact_arg.map(Operand64::from) == Some(data.operand64(arg.memory_arg_idx)) } - && addr == u16::from(arg.local1) - && data.operand64(one).value() == 1 - { - replace!(output, *read, 3 => Instruction::IncMemoryLocal64(arg)); - return Ok(()); - } - } - if *read >= output.block_start + 2 { - match [output[*read - 2], output[*read - 1]] { - [Instruction::F64Mul, Instruction::F64Add] - if let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) => - { - replace!(output, *read, 2 => Instruction::FMaStoreF64(arg)); - } - [Instruction::LocalGet32(addr), Instruction::LocalGet64(value)] - if let (Ok(addr), Ok(value), Some(memory_arg)) = - (u8::try_from(addr), u8::try_from(value), compact_arg) => - { - let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?; - replace!(output, *read, 2 => Instruction::StoreLocalLocal64(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value })); - } - _ => {} - } - } - Ok(()) -} - -macro_rules! local_const_set { - ($data:expr, 32, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ - let index = $data.push_operand64(Operand64::<(u16, u16, u32)>::new($src, $dst, $value as u32))?; - if $tee { - Instruction::BinOpLocalConstTee32(PackedOp::new($op, index)) - } else { - Instruction::BinOpLocalConstSet32(PackedOp::new($op, index)) - } - }}; - ($data:expr, 64, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ - let index = $data.push_operand128(Operand128::<(u16, u16, u64)>::new($src, $dst, $value as u64))?; - if $tee { - Instruction::BinOpLocalConstTee64(PackedOp::new($op, index)) - } else { - Instruction::BinOpLocalConstSet64(PackedOp::new($op, index)) - } - }}; - ($data:expr, 128, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ - let index = $data.push_operand64(Operand64::<(u16, u16, Operand128Idx<[u8; 16]>)>::new($src, $dst, $value))?; - if $tee { - Instruction::BinOpLocalConstTee128(PackedOp::new($op, index)) - } else { - Instruction::BinOpLocalConstSet128(PackedOp::new($op, index)) - } - }}; -} - -fn rewrite_local_set32( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - dst: u16, -) -> Result<()> { - if *read >= output.block_start + 2 { - match [output[*read - 2], output[*read - 1]] { - [Instruction::I32Mul, Instruction::BinOpStackLocal32(BinOp::IAdd, acc)] if acc == dst => { - replace!(output, *read, 2 => Instruction::MulAccLocal32(dst)); - return Ok(()); - } - [Instruction::F32Mul, Instruction::BinOpStackLocal32(BinOp::FAdd, acc)] if acc == dst => { - replace!(output, *read, 2 => Instruction::FMulAccLocal32(dst)); - return Ok(()); - } - _ => {} - } - } - if *read > output.block_start { - match output[*read - 1] { - Instruction::LocalGet32(src) if src == dst => { - output.truncate(*read - 1); - *read = output.len(); - return Ok(()); - } - Instruction::LocalGet32(src) => replace!(output, *read, 1 => Instruction::LocalCopy32(src, dst)), - Instruction::Const32(value) => { - replace!(output, *read, 1 => Instruction::SetLocalConst32(I32LocalArg { value, local: dst })) - } - Instruction::BinOpLocalLocal32(op, left, right) => { - let replacement = if op == BinOp::IAdd { - Instruction::AddLocalLocalSet32(LocalTripleArg { left, right, dst }) - } else { - Instruction::BinOpLocalLocalSet32(PackedOp::new( - op, - data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?, - )) - }; - replace!(output, *read, 1 => replacement); - } - instruction if let Some((op, src, value)) = local_const32(data, instruction) => { - if src == dst - && let Some(delta) = op.inc_delta(value) - { - replace!(output, *read, 1 => Instruction::IncLocal32(I32LocalArg { value: delta, local: dst })); - } else { - let replacement = local_const_set!(data, 32, op, src, dst, value, false); - replace!(output, *read, 1 => replacement); - } - } - Instruction::BinOpStackLocal32(op, local) => { - replace!(output, *read, 1 => Instruction::BinOpStackLocalSet32(op, local, dst)); - } - Instruction::LoadLocal32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalSet32(arg)); - } - Instruction::LoadLocal8S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalSet8S32(arg)); - } - Instruction::LoadLocal8U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalSet8U32(arg)); - } - Instruction::LoadLocal16S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalSet16S32(arg)); - } - Instruction::LoadLocal16U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalSet16U32(arg)); - } - _ => {} - } - } - Ok(()) -} - -fn rewrite_local_set64( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - dst: u16, -) -> Result<()> { - if *read >= output.block_start + 3 { - match [output[*read - 3], output[*read - 2], output[*read - 1]] { - [Instruction::I64Mul, Instruction::LocalGet64(acc), Instruction::I64Add] if acc == dst => { - replace!(output, *read, 3 => Instruction::MulAccLocal64(dst)); - return Ok(()); - } - [Instruction::F64Mul, Instruction::LocalGet64(acc), Instruction::F64Add] if acc == dst => { - replace!(output, *read, 3 => Instruction::FMulAccLocal64(dst)); - return Ok(()); - } - _ => {} - } - } - if *read > output.block_start { - match output[*read - 1] { - Instruction::LocalGet64(src) if src == dst => { - output.truncate(*read - 1); - *read = output.len(); - return Ok(()); - } - Instruction::LocalGet64(src) => replace!(output, *read, 1 => Instruction::LocalCopy64(src, dst)), - Instruction::Const64(index) => { - replace!(output, *read, 1 => Instruction::SetLocalConst64(PackedOp::new(dst, index))); - } - Instruction::BinOpLocalLocal64(op, left, right) => { - let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?; - replace!(output, *read, 1 => Instruction::BinOpLocalLocalSet64(PackedOp::new(op, index))); - } - instruction if let Some((op, src, value)) = local_const64(data, instruction) => { - if src == dst && matches!(op, BinOp::IAdd | BinOp::ISub) { - let delta = if op == BinOp::IAdd { value } else { value.wrapping_neg() }; - let index = data.push_operand64(Operand64::::new(delta))?; - replace!(output, *read, 1 => Instruction::IncLocal64(PackedOp::new(dst, index))); - } else { - let replacement = local_const_set!(data, 64, op, src, dst, value, false); - replace!(output, *read, 1 => replacement); - } - } - _ => {} - } - } - Ok(()) -} - -fn rewrite_local_set128( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - dst: u16, -) -> Result<()> { - if *read >= output.block_start + 2 - && let [Instruction::LocalGet32(local), Instruction::V128Load(index)] = [output[*read - 2], output[*read - 1]] - && let (Ok(local), Ok(dst), Ok(memory_arg)) = - (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand128(index))) - { - let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?; - replace!(output, *read, 2 => Instruction::LoadLocalSet128(MemoryLocalArg { - memory_arg_idx, - local1: local, - local2: dst, - })); - return Ok(()); - } - if *read > output.block_start { - match output[*read - 1] { - Instruction::LocalGet128(src) if src == dst => { - output.truncate(*read - 1); - *read = output.len(); - return Ok(()); - } - Instruction::LocalGet128(src) => replace!(output, *read, 1 => Instruction::LocalCopy128(src, dst)), - Instruction::Const128(value) => { - replace!(output, *read, 1 => Instruction::SetLocalConst128(PackedOp::new(dst, value))) - } - Instruction::BinOpLocalLocal128(op, left, right) => { - let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?; - replace!(output, *read, 1 => Instruction::BinOpLocalLocalSet128(PackedOp::new(op, index))); - } - instruction if let Some((op, src, value)) = local_const128(data, instruction) => { - let replacement = local_const_set!(data, 128, op, src, dst, value, false); - replace!(output, *read, 1 => replacement); - } - _ => {} - } - } - Ok(()) -} - -fn rewrite_local_tee32( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - dst: u16, -) -> Result<()> { - if *read >= output.block_start + 2 { - match [output[*read - 2], output[*read - 1]] { - [Instruction::Const32(value), Instruction::I32And] => { - replace!(output, *read, 2 => Instruction::AndConstTee32(I32LocalArg { value, local: dst })); - return Ok(()); - } - [Instruction::Const32(value), Instruction::I32Sub] => { - replace!(output, *read, 2 => Instruction::SubConstTee32(I32LocalArg { value, local: dst })); - return Ok(()); - } - _ => {} - } - } - if *read > output.block_start { - match output[*read - 1] { - Instruction::AndConst32(value) => { - replace!(output, *read, 1 => Instruction::AndConstTee32(I32LocalArg { value, local: dst })); - } - Instruction::BinOpStackConst32(BinOp::ISub, value) => { - replace!(output, *read, 1 => Instruction::SubConstTee32(I32LocalArg { value, local: dst })); - } - Instruction::LocalGet32(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet32(src)), - Instruction::LocalGet32(src) => { - replace!(output, *read, 1 => [Instruction::LocalCopy32(src, dst), Instruction::LocalGet32(dst)]); - } - Instruction::BinOpLocalLocal32(op, left, right) => { - let replacement = if op == BinOp::IAdd { - Instruction::AddLocalLocalTee32(LocalTripleArg { left, right, dst }) - } else { - Instruction::BinOpLocalLocalTee32(PackedOp::new( - op, - data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?, - )) - }; - replace!(output, *read, 1 => replacement); - } - instruction if let Some((op, src, value)) = local_const32(data, instruction) => { - let replacement = local_const_set!(data, 32, op, src, dst, value, true); - replace!(output, *read, 1 => replacement); - } - Instruction::BinOpStackLocal32(op, local) => { - replace!(output, *read, 1 => Instruction::BinOpStackLocalTee32(op, local, dst)); - } - Instruction::LoadLocal32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalTee32(arg)); - } - Instruction::LoadLocal8S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalTee8S32(arg)); - } - Instruction::LoadLocal8U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalTee8U32(arg)); - } - Instruction::LoadLocal16S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalTee16S32(arg)); - } - Instruction::LoadLocal16U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { - arg.local2 = dst; - replace!(output, *read, 1 => Instruction::LoadLocalTee16U32(arg)); - } - _ => {} - } - } - Ok(()) -} - -fn rewrite_local_tee64( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - dst: u16, -) -> Result<()> { - if *read >= output.block_start + 2 { - match [output[*read - 2], output[*read - 1]] { - [Instruction::Const64(value), Instruction::I64And] => { - replace!(output, *read, 2 => Instruction::AndConstTee64(PackedOp::new(dst, value))); - return Ok(()); - } - [Instruction::Const64(value), Instruction::I64Sub] => { - replace!(output, *read, 2 => Instruction::SubConstTee64(PackedOp::new(dst, value))); - return Ok(()); - } - _ => {} - } - } - if *read > output.block_start { - match output[*read - 1] { - Instruction::BinOpStackConst64(packed) if packed.op == BinOp::IAnd => { - replace!(output, *read, 1 => Instruction::AndConstTee64(PackedOp::new(dst, packed.index))); - } - Instruction::BinOpStackConst64(packed) if packed.op == BinOp::ISub => { - replace!(output, *read, 1 => Instruction::SubConstTee64(PackedOp::new(dst, packed.index))); - } - Instruction::LocalGet64(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet64(src)), - Instruction::LocalGet64(src) => { - replace!(output, *read, 1 => [Instruction::LocalCopy64(src, dst), Instruction::LocalGet64(dst)]); - } - Instruction::BinOpLocalLocal64(op, left, right) => { - let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?; - replace!(output, *read, 1 => Instruction::BinOpLocalLocalTee64(PackedOp::new(op, index))); - } - instruction if let Some((op, src, value)) = local_const64(data, instruction) => { - let replacement = local_const_set!(data, 64, op, src, dst, value, true); - replace!(output, *read, 1 => replacement); - } - _ => {} - } - } - Ok(()) -} - -fn rewrite_local_tee128( - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - dst: u16, -) -> Result<()> { - if *read >= output.block_start + 2 - && let [Instruction::LocalGet32(local), Instruction::V128Load(index)] = [output[*read - 2], output[*read - 1]] - && let (Ok(local), Ok(dst), Ok(memory_arg)) = - (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand128(index))) - { - let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?; - replace!(output, *read, 2 => Instruction::LoadLocalTee128(MemoryLocalArg { - memory_arg_idx, - local1: local, - local2: dst, - })); - return Ok(()); - } - if *read > output.block_start { - match output[*read - 1] { - Instruction::LocalGet128(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet128(src)), - Instruction::LocalGet128(src) => { - replace!(output, *read, 1 => [Instruction::LocalCopy128(src, dst), Instruction::LocalGet128(dst)]); - } - Instruction::BinOpLocalLocal128(op, left, right) => { - let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?; - replace!(output, *read, 1 => Instruction::BinOpLocalLocalTee128(PackedOp::new(op, index))); - } - instruction if let Some((op, src, value)) = local_const128(data, instruction) => { - let replacement = local_const_set!(data, 128, op, src, dst, value, true); - replace!(output, *read, 1 => replacement); - } - _ => {} - } - } - Ok(()) -} - -fn int_bin_op(instruction: Instruction) -> Option { - Some(match instruction { - Instruction::I32Add | Instruction::I64Add => BinOp::IAdd, - Instruction::I32Sub | Instruction::I64Sub => BinOp::ISub, - Instruction::I32Mul | Instruction::I64Mul => BinOp::IMul, - Instruction::I32And | Instruction::I64And => BinOp::IAnd, - Instruction::I32Or | Instruction::I64Or => BinOp::IOr, - Instruction::I32Xor | Instruction::I64Xor => BinOp::IXor, - Instruction::I32Shl | Instruction::I64Shl => BinOp::IShl, - Instruction::I32ShrS | Instruction::I64ShrS => BinOp::IShrS, - Instruction::I32ShrU | Instruction::I64ShrU => BinOp::IShrU, - Instruction::I32Rotl | Instruction::I64Rotl => BinOp::IRotl, - Instruction::I32Rotr | Instruction::I64Rotr => BinOp::IRotr, - _ => return None, - }) -} - -fn float_bin_op(instruction: Instruction) -> Option { - Some(match instruction { - Instruction::F32Add | Instruction::F64Add => BinOp::FAdd, - Instruction::F32Sub | Instruction::F64Sub => BinOp::FSub, - Instruction::F32Mul | Instruction::F64Mul => BinOp::FMul, - Instruction::F32Div | Instruction::F64Div => BinOp::FDiv, - Instruction::F32Min | Instruction::F64Min => BinOp::FMin, - Instruction::F32Max | Instruction::F64Max => BinOp::FMax, - Instruction::F32Copysign | Instruction::F64Copysign => BinOp::FCopysign, - _ => return None, - }) -} - -fn cmp_op(instruction: Instruction) -> Option { - Some(match instruction { - Instruction::I32Eq | Instruction::I64Eq => CmpOp::Eq, - Instruction::I32Ne | Instruction::I64Ne => CmpOp::Ne, - Instruction::I32LtS | Instruction::I64LtS => CmpOp::LtS, - Instruction::I32LtU | Instruction::I64LtU => CmpOp::LtU, - Instruction::I32GtS | Instruction::I64GtS => CmpOp::GtS, - Instruction::I32GtU | Instruction::I64GtU => CmpOp::GtU, - Instruction::I32LeS | Instruction::I64LeS => CmpOp::LeS, - Instruction::I32LeU | Instruction::I64LeU => CmpOp::LeU, - Instruction::I32GeS | Instruction::I64GeS => CmpOp::GeS, - Instruction::I32GeU | Instruction::I64GeU => CmpOp::GeU, - _ => return None, - }) -} - -fn bin_op_128(instruction: Instruction) -> Option { - Some(match instruction { - Instruction::V128And => BinOp128::And, - Instruction::V128AndNot => BinOp128::AndNot, - Instruction::V128Or => BinOp128::Or, - Instruction::V128Xor => BinOp128::Xor, - Instruction::I64x2Add => BinOp128::I64x2Add, - Instruction::I64x2Mul => BinOp128::I64x2Mul, - _ => return None, - }) -} - -fn jump_cmp_local_local( - data: &mut WasmFunctionData, - target: u32, - left: u16, - right: u16, - op: CmpOp, - width64: bool, -) -> Result { - let index = data.push_target_operand64(Operand64::<(u32, u16, u16)>::new(target, left, right))?; - Ok(if width64 { - Instruction::JumpCmpLocalLocal64(PackedOp::new(op, index)) - } else { - Instruction::JumpCmpLocalLocal32(PackedOp::new(op, index)) - }) -} - -fn rewrite_jump( - source: &[Instruction], - output: &mut CompactOutput, - index: usize, - data: &mut WasmFunctionData, - old_index: u32, - target: u32, -) -> Result<()> { - let target = resolve_jump_target(source, data, target); - let exit = old_index + 1; - let body = target + 1; - if let Some(instruction) = source.get(target as usize).copied() { - match instruction { - Instruction::JumpCmpLocalLocal32(side) - if resolve_jump_target(source, data, data.operand64(side.index).a()) == exit && body > target => - { - let value = data.operand64(side.index); - output[index] = jump_cmp_local_local(data, body, value.b(), value.c(), side.op.inverse(), false)?; - return Ok(()); - } - Instruction::JumpCmpLocalLocal64(side) - if resolve_jump_target(source, data, data.operand64(side.index).a()) == exit && body > target => - { - let value = data.operand64(side.index); - output[index] = jump_cmp_local_local(data, body, value.b(), value.c(), side.op.inverse(), true)?; - return Ok(()); - } - _ => {} - } - } - if matches!(output[index], Instruction::Jump(_)) && target == exit { - output.truncate(index); - } else { - set_rewrite_target(&mut output[index], data, target)?; - } - Ok(()) -} - -fn jump_cmp_stack_local( - data: &mut WasmFunctionData, - target: u32, - local: u16, - op: CmpOp, - width64: bool, -) -> Result { - let index = data.push_target_operand64(Operand64::<(u32, u16)>::new(target, local))?; - Ok(if width64 { - Instruction::JumpCmpStackLocal64(PackedOp::new(op, index)) - } else { - Instruction::JumpCmpStackLocal32(PackedOp::new(op, index)) - }) -} - -fn jump_cmp_local_const32( - data: &mut WasmFunctionData, - target: u32, - local: u16, - value: i32, - op: CmpOp, -) -> Result { - if value == 0 { - return Ok(match op { - CmpOp::Eq => Instruction::JumpIfLocalZero32(TargetLocalArg { target_ip: target, local }), - CmpOp::Ne => Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }), - _ => Instruction::JumpCmpLocalConst32(PackedOp::new( - op, - data.push_target_operand128(Operand128::<(u32, i32, u16)>::new(target, value, local))?, - )), - }); - } - Ok(Instruction::JumpCmpLocalConst32(PackedOp::new( - op, - data.push_target_operand128(Operand128::<(u32, i32, u16)>::new(target, value, local))?, - ))) -} - -fn jump_cmp_local_const64( - data: &mut WasmFunctionData, - target: u32, - local: u16, - value: i32, - op: CmpOp, -) -> Result { - if value == 0 { - match op { - CmpOp::Eq => return Ok(Instruction::JumpIfLocalZero64(TargetLocalArg { target_ip: target, local })), - CmpOp::Ne => return Ok(Instruction::JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local })), - _ => {} - } - } - Ok(Instruction::JumpCmpLocalConst64(PackedOp::new( - op, - data.push_target_operand128(Operand128::<(u32, i32, u16)>::new(target, value, local))?, - ))) -} - -fn jump_cmp_stack_const32(data: &mut WasmFunctionData, target: u32, value: i32, op: CmpOp) -> Result { - if value == 0 { - match op { - CmpOp::Eq => return Ok(Instruction::JumpIfZero32(target)), - CmpOp::Ne => return Ok(Instruction::JumpIfNonZero32(target)), - _ => {} - } - } - Ok(Instruction::JumpCmpStackConst32(PackedOp::new( - op, - data.push_target_operand64(Operand64::<(u32, i32)>::new(target, value))?, - ))) -} - -fn jump_cmp_stack_const64(data: &mut WasmFunctionData, target: u32, value: i64, op: CmpOp) -> Result { - if value == 0 { - match op { - CmpOp::Eq => return Ok(Instruction::JumpIfZero64(target)), - CmpOp::Ne => return Ok(Instruction::JumpIfNonZero64(target)), - _ => {} - } - } - Ok(Instruction::JumpCmpStackConst64(PackedOp::new( - op, - data.push_target_operand128(Operand128::<(u32, i64)>::new(target, value))?, - ))) -} - -fn update_jump( - data: &mut WasmFunctionData, - target: u32, - immediate: i32, - address: u32, - op: BinOp, - on_zero: bool, - global: bool, -) -> Result { - if let Some(delta) = op.inc_delta(immediate) { - Ok(if global { - Instruction::IncGlobalJump32( - data.push_target_operand128(Operand128::::new(target, delta, address, on_zero))?, - ) - } else { - Instruction::IncLocalJump32(data.push_target_operand128(Operand128::::new( - target, - delta, - address as u16, - on_zero, - ))?) - }) - } else { - Ok(if global { - Instruction::BinOpGlobalConstJump32(PackedOp::new( - op, - data.push_target_operand128(Operand128::::new( - target, immediate, address, on_zero, - ))?, - )) - } else { - Instruction::BinOpLocalConstJump32(PackedOp::new( - op, - data.push_target_operand128(Operand128::::new( - target, - immediate, - address as u16, - on_zero, - ))?, - )) - }) - } -} - -fn rewrite_conditional( - source: &[Instruction], - output: &mut CompactOutput, - read: &mut usize, - data: &mut WasmFunctionData, - target: u32, - on_zero: bool, -) -> Result<()> { - let target = resolve_jump_target(source, data, target); - if *read > output.block_start - && let Instruction::BinOpLocalConstTee32(packed) = output[*read - 1] - { - let value = data.operand64(packed.index); - if value.a() == value.b() { - let replacement = - update_jump(data, target, value.c() as i32, u32::from(value.a()), packed.op, on_zero, false)?; - replace!(output, *read, 1 => replacement); - return Ok(()); - } - } - if *read >= output.block_start + 2 - && let [Instruction::BinOpGlobalConst32(packed), Instruction::GlobalTee32(dst)] = - [output[*read - 2], output[*read - 1]] - { - let value = data.operand64(packed.index); - if value.a() == dst { - let replacement = update_jump(data, target, value.b() as i32, dst, packed.op, on_zero, true)?; - replace!(output, *read, 2 => replacement); - return Ok(()); - } - } - if *read >= output.block_start + 3 - && let [Instruction::AddConst32(value), Instruction::LocalTee32(local), Instruction::LocalGet32(cond)] = - [output[*read - 3], output[*read - 2], output[*read - 1]] - && local == cond - { - let replacement = - Instruction::IncStackTeeLocalJump32( - data.push_target_operand128(Operand128::::new(target, value, local, on_zero))?, - ); - replace!(output, *read, 3 => replacement); - return Ok(()); - } - if *read >= output.block_start + 3 { - let update = match [output[*read - 3], output[*read - 2], output[*read - 1]] { - [Instruction::XorConst32(value), Instruction::LocalTee32(local), Instruction::LocalGet32(cond)] - if local == cond => - { - Some((BinOp::IXor, value, local)) - } - [Instruction::ShrUConst32(value), Instruction::LocalTee32(local), Instruction::LocalGet32(cond)] - if local == cond => - { - Some((BinOp::IShrU, value, local)) - } - [ - Instruction::BinOpStackConst32(op, value), - Instruction::LocalTee32(local), - Instruction::LocalGet32(cond), - ] if local == cond => Some((op, value, local)), - _ => None, - }; - if let Some((op, value, local)) = update { - let replacement = Instruction::BinOpStackConstTeeLocalJump32(PackedOp::new( - op, - data.push_target_operand128(Operand128::::new(target, value, local, on_zero))?, - )); - replace!(output, *read, 3 => replacement); - return Ok(()); - } - } - if *read >= output.block_start + 2 { - let update = match [output[*read - 2], output[*read - 1]] { - [Instruction::AndConstTee32(arg), Instruction::LocalGet32(cond)] if arg.local == cond => { - Some((arg.local, arg.value, Some(BinOp::IAnd))) - } - [Instruction::SubConstTee32(arg), Instruction::LocalGet32(cond)] if arg.local == cond => { - Some((arg.local, arg.value.wrapping_neg(), None)) - } - _ => None, - }; - if let Some((local, value, op)) = update { - let replacement = if let Some(op) = op { - Instruction::BinOpStackConstTeeLocalJump32(PackedOp::new( - op, - data.push_target_operand128(Operand128::::new(target, value, local, on_zero))?, - )) - } else { - Instruction::IncStackTeeLocalJump32( - data.push_target_operand128(Operand128::::new(target, value, local, on_zero))?, - ) - }; - replace!(output, *read, 2 => replacement); - return Ok(()); - } - } - if *read >= output.block_start + 3 - && let [Instruction::BinOpLocalConstTee32(packed), Instruction::LocalGet32(right), raw_cmp] = - [output[*read - 3], output[*read - 2], output[*read - 1]] - && let Some(mut cmp) = cmp_op(raw_cmp) - { - let value = data.operand64(packed.index); - if value.a() == value.b() { - if on_zero { - cmp = cmp.inverse(); - } - let replacement = if let Some(delta) = packed.op.inc_delta(value.c() as i32) { - Instruction::IncLocalJumpCmpLocal32(PackedOp::new( - cmp, - data.push_target_operand128(Operand128::::new( - target, - delta, - value.a(), - right, - ))?, - )) - } else { - Instruction::BinOpLocalConstJumpCmpLocal32(PackedOp::new( - (packed.op, cmp), - data.push_target_operand128(Operand128::::new( - target, - value.c() as i32, - value.a(), - right, - ))?, - )) - }; - replace!(output, *read, 3 => replacement); - return Ok(()); - } - } - if *read >= output.block_start + 2 { - match [output[*read - 2], output[*read - 1]] { - [Instruction::LocalGet32(local), Instruction::I32Eqz] => { - replace!(output, *read, 2 => - if on_zero { - Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }) - } else { - Instruction::JumpIfLocalZero32(TargetLocalArg { target_ip: target, local }) - } - ); - return Ok(()); - } - [Instruction::LocalGet64(local), Instruction::I64Eqz] => { - replace!(output, *read, 2 => - if on_zero { - Instruction::JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local }) - } else { - Instruction::JumpIfLocalZero64(TargetLocalArg { target_ip: target, local }) - } - ); - return Ok(()); - } - [Instruction::CmpLocalLocal32(op, left, right), Instruction::I32Eqz] => { - let op = if on_zero { op } else { op.inverse() }; - let replacement = jump_cmp_local_local(data, target, left, right, op, false)?; - replace!(output, *read, 2 => replacement); - return Ok(()); - } - _ => {} - } - } - if *read > output.block_start { - let previous = output[*read - 1]; - let replacement = match previous { - Instruction::I32Eqz => { - Some(if on_zero { Instruction::JumpIfNonZero32(target) } else { Instruction::JumpIfZero32(target) }) - } - Instruction::I64Eqz => { - Some(if on_zero { Instruction::JumpIfNonZero64(target) } else { Instruction::JumpIfZero64(target) }) - } - Instruction::CmpLocalLocal32(op, left, right) => { - Some(jump_cmp_local_local(data, target, left, right, if !on_zero { op } else { op.inverse() }, false)?) - } - Instruction::CmpLocalLocal64(op, left, right) => { - Some(jump_cmp_local_local(data, target, left, right, if !on_zero { op } else { op.inverse() }, true)?) - } - Instruction::LocalGet32(local) => Some(if on_zero { - Instruction::JumpIfLocalZero32(TargetLocalArg { target_ip: target, local }) - } else { - Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }) - }), - Instruction::LocalGet64(local) => Some(if on_zero { - Instruction::JumpIfLocalZero64(TargetLocalArg { target_ip: target, local }) - } else { - Instruction::JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local }) - }), - _ => None, - }; - if let Some(replacement) = replacement { - replace!(output, *read, 1 => replacement); - return Ok(()); - } - } - if *read >= output.block_start + 3 { - let raw_cmp = output[*read - 1]; - if let Some(mut op) = cmp_op(raw_cmp) { - if on_zero { - op = op.inverse(); - } - let replacement = match [output[*read - 3], output[*read - 2]] { - [Instruction::LocalGet32(local), Instruction::Const32(value)] => { - Some(jump_cmp_local_const32(data, target, local, value, op)?) - } - [Instruction::LocalGet64(local), Instruction::Const64(index)] - if let Ok(value) = i32::try_from(data.operand64(index).value()) => - { - Some(jump_cmp_local_const64(data, target, local, value, op)?) - } - [Instruction::LocalGet32(left), Instruction::LocalGet32(right)] => { - Some(jump_cmp_local_local(data, target, left, right, op, false)?) - } - [Instruction::LocalGet64(left), Instruction::LocalGet64(right)] => { - Some(jump_cmp_local_local(data, target, left, right, op, true)?) - } - _ => None, - }; - if let Some(replacement) = replacement { - replace!(output, *read, 3 => replacement); - return Ok(()); - } - } - } - if *read >= output.block_start + 2 { - let raw_cmp = output[*read - 1]; - if let Some(mut op) = cmp_op(raw_cmp) { - if on_zero { - op = op.inverse(); - } - let replacement = match output[*read - 2] { - Instruction::LocalGet32(local) => Some(jump_cmp_stack_local(data, target, local, op, false)?), - Instruction::LocalGet64(local) => Some(jump_cmp_stack_local(data, target, local, op, true)?), - Instruction::Const32(value) => Some(jump_cmp_stack_const32(data, target, value, op)?), - Instruction::Const64(index) => { - Some(jump_cmp_stack_const64(data, target, data.operand64(index).value(), op)?) - } - _ => None, - }; - if let Some(replacement) = replacement { - replace!(output, *read, 2 => replacement); - return Ok(()); - } - } - } - Ok(()) -} - -fn is_unconditional_terminator(instruction: Instruction) -> bool { - matches!( - instruction, - Instruction::Unreachable - | Instruction::Jump(_) - | Instruction::BranchTable(_) - | Instruction::Return - | Instruction::ReturnVoid - | Instruction::Return32 - | Instruction::Return64 - | Instruction::Return128 - | Instruction::ReturnCall(_) - | Instruction::ReturnCallSelf - | Instruction::ReturnCallIndirect(_) - | Instruction::ReturnCallRef(_) - | Instruction::Throw(_) - | Instruction::ThrowRef - ) -} diff --git a/crates/parser/src/optimize/targets.rs b/crates/parser/src/optimize/targets.rs deleted file mode 100644 index c6b2252..0000000 --- a/crates/parser/src/optimize/targets.rs +++ /dev/null @@ -1,227 +0,0 @@ -use crate::visit::FunctionDataBuilder; -use crate::{ParseError, Result}; -use alloc::vec::Vec; -use tinywasm_types::{Instruction, PackedOp}; - -pub(super) fn resolve_jump_target(instructions: &[Instruction], data: &FunctionDataBuilder, target: u32) -> u32 { - let mut index = target as usize; - let mut steps = 0; - while let Some(instruction) = instructions.get(index) - && let Some(next) = instruction_target(data, *instruction) - && matches!(instruction, Instruction::Jump(_)) - && steps < instructions.len() - { - index = next as usize; - steps += 1; - } - index as u32 -} - -pub(super) fn set_rewrite_target( - instruction: &mut Instruction, - data: &mut FunctionDataBuilder, - target: u32, -) -> Result<()> { - macro_rules! rewrite_target { - ($slot:ident, operand64) => {{ data.push_target_operand64(data.operand64(*$slot).with_target(target))? }}; - ($slot:ident, operand128) => {{ data.push_target_operand128(data.operand128(*$slot).with_target(target))? }}; - ($slot:ident, packed64) => {{ PackedOp::new($slot.op, data.push_target_operand64(data.operand64($slot.index).with_target(target))?) }}; - ($slot:ident, packed128) => {{ PackedOp::new($slot.op, data.push_target_operand128(data.operand128($slot.index).with_target(target))?) }}; - } - - use Instruction::*; - match instruction { - JumpCmpStackLocal32(packed) => *packed = rewrite_target!(packed, packed64), - JumpCmpStackLocal64(packed) => *packed = rewrite_target!(packed, packed64), - BrOnCast(index) | BrOnCastFail(index) => *index = rewrite_target!(index, operand64), - JumpCmpStackConst32(packed) => *packed = rewrite_target!(packed, packed64), - JumpCmpStackConst64(packed) => *packed = rewrite_target!(packed, packed128), - BinOpStackConstTeeLocalJump32(packed) => *packed = rewrite_target!(packed, packed128), - BinOpLocalConstJump32(packed) => *packed = rewrite_target!(packed, packed128), - BinOpLocalConstJumpCmpLocal32(packed) => *packed = rewrite_target!(packed, packed128), - BinOpGlobalConstJump32(packed) => *packed = rewrite_target!(packed, packed128), - IncLocalJump32(index) => *index = rewrite_target!(index, operand128), - IncStackTeeLocalJump32(index) => *index = rewrite_target!(index, operand128), - IncGlobalJump32(index) => *index = rewrite_target!(index, operand128), - IncLocalJumpCmpLocal32(packed) => *packed = rewrite_target!(packed, packed128), - JumpCmpLocalConst32(packed) => *packed = rewrite_target!(packed, packed128), - JumpCmpLocalConst64(packed) => *packed = rewrite_target!(packed, packed128), - JumpCmpLocalLocal32(packed) => *packed = rewrite_target!(packed, packed64), - JumpCmpLocalLocal64(packed) => *packed = rewrite_target!(packed, packed64), - BranchTable(index) => *index = rewrite_target!(index, operand128), - _ => set_target(instruction, data, target), - } - - Ok(()) -} - -fn instruction_target(data: &FunctionDataBuilder, instruction: Instruction) -> Option { - use Instruction::*; - Some(match instruction { - Jump(target) - | JumpIfZero32(target) - | JumpIfNonZero32(target) - | JumpIfZero64(target) - | JumpIfNonZero64(target) - | JumpIfRefNull(target) - | JumpIfRefNonNull(target) => target, - JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => { - arg.target_ip - } - JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => data.operand64(packed.index).target(), - BrOnCast(index) | BrOnCastFail(index) => data.operand64(index).target(), - JumpCmpStackConst32(packed) => data.operand64(packed.index).target(), - JumpCmpStackConst64(packed) => data.operand128(packed.index).target(), - BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => data.operand128(packed.index).target(), - BinOpLocalConstJumpCmpLocal32(packed) => data.operand128(packed.index).target(), - BinOpGlobalConstJump32(packed) => data.operand128(packed.index).target(), - IncLocalJump32(index) | IncStackTeeLocalJump32(index) => data.operand128(index).target(), - IncGlobalJump32(index) => data.operand128(index).target(), - IncLocalJumpCmpLocal32(packed) => data.operand128(packed.index).target(), - JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => data.operand128(packed.index).target(), - JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => data.operand64(packed.index).target(), - BranchTable(index) => data.operand128(index).target(), - _ => return None, - }) -} - -fn set_target(instruction: &mut Instruction, data: &mut FunctionDataBuilder, target: u32) { - macro_rules! set_target { - ($index:expr, operand64) => {{ data.set_operand64($index, data.operand64($index).with_target(target)) }}; - ($index:expr, operand128) => {{ data.set_operand128($index, data.operand128($index).with_target(target)) }}; - ($packed:expr, packed64) => {{ data.set_operand64($packed.index, data.operand64($packed.index).with_target(target)) }}; - ($packed:expr, packed128) => {{ data.set_operand128($packed.index, data.operand128($packed.index).with_target(target)) }}; - } - - use Instruction::*; - match instruction { - Jump(value) - | JumpIfZero32(value) - | JumpIfNonZero32(value) - | JumpIfZero64(value) - | JumpIfNonZero64(value) - | JumpIfRefNull(value) - | JumpIfRefNonNull(value) => *value = target, - - JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => { - arg.target_ip = target - } - JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => set_target!(*packed, packed64), - BrOnCast(index) | BrOnCastFail(index) => set_target!(*index, operand64), - JumpCmpStackConst32(packed) => set_target!(*packed, packed64), - JumpCmpStackConst64(packed) => set_target!(*packed, packed128), - BinOpLocalConstJump32(packed) => set_target!(*packed, packed128), - BinOpStackConstTeeLocalJump32(packed) => set_target!(*packed, packed128), - BinOpLocalConstJumpCmpLocal32(packed) => set_target!(*packed, packed128), - BinOpGlobalConstJump32(packed) => set_target!(*packed, packed128), - IncLocalJump32(index) | IncStackTeeLocalJump32(index) => set_target!(*index, operand128), - IncGlobalJump32(index) => set_target!(*index, operand128), - IncLocalJumpCmpLocal32(packed) => set_target!(*packed, packed128), - JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => set_target!(*packed, packed128), - JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => set_target!(*packed, packed64), - BranchTable(index) => set_target!(*index, operand128), - _ => {} - } -} - -fn branch_table_range(data: &FunctionDataBuilder, instruction: Instruction) -> Option<(u32, u32)> { - let Instruction::BranchTable(index) = instruction else { return None }; - let operand = data.operand128(index); - Some((operand.start(), operand.size())) -} - -pub(super) fn target_boundaries(instructions: &[Instruction], data: &FunctionDataBuilder) -> Result> { - let mut boundaries = alloc::vec![false; instructions.len() + 1]; - for handler in &data.exception_handlers { - for target in [handler.start_ip, handler.end_ip] { - *boundaries.get_mut(target as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("exception handler boundary out of bounds: {target}")) - })? = true; - } - for catch in &handler.catches { - let target = catch.landing_pad(); - *boundaries - .get_mut(target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("exception landing pad out of bounds: {target}")))? = - true; - } - } - for &instruction in instructions { - if let Some(target) = instruction_target(data, instruction) { - *boundaries - .get_mut(target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))? = true; - } - if let Some((start, count)) = branch_table_range(data, instruction) { - let end = - start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; - let targets = data - .branch_table_targets - .get(start as usize..end as usize) - .ok_or_else(|| ParseError::Other("branch table range out of bounds".into()))?; - for &target in targets { - *boundaries.get_mut(target as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("branch table target out of bounds: {target}")) - })? = true; - } - } - } - Ok(boundaries) -} - -fn remap_target(target: u32, old_to_new: Option<&[u32]>, len: u32) -> Result { - let target = if let Some(map) = old_to_new { - *map.get(target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))? - } else { - target - }; - if target >= len { - return Err(ParseError::Other(alloc::format!("instruction target out of bounds: {target}"))); - } - Ok(target) -} - -pub(super) fn finalize( - instructions: &mut [Instruction], - data: &mut FunctionDataBuilder, - old_to_new: Option<&[u32]>, -) -> Result<()> { - let len = instructions.len() as u32; - for handler in &mut data.exception_handlers { - if let Some(map) = old_to_new { - handler.start_ip = *map - .get(handler.start_ip as usize) - .ok_or_else(|| ParseError::Other("exception handler boundary out of bounds".into()))?; - handler.end_ip = *map - .get(handler.end_ip as usize) - .ok_or_else(|| ParseError::Other("exception handler boundary out of bounds".into()))?; - for catch in &mut handler.catches { - let landing_pad = match catch { - tinywasm_types::ExceptionCatch::Tag { landing_pad, .. } - | tinywasm_types::ExceptionCatch::All { landing_pad, .. } => landing_pad, - }; - *landing_pad = remap_target(*landing_pad, Some(map), len)?; - } - } - if handler.start_ip > handler.end_ip || handler.end_ip > len { - return Err(ParseError::Other("exception handler range out of bounds".into())); - } - } - for target in &mut data.branch_table_targets { - *target = remap_target(*target, old_to_new, len)?; - } - for instruction in instructions { - if let Some(target) = instruction_target(data, *instruction) { - set_target(instruction, data, remap_target(target, old_to_new, len)?); - } - if let Some((start, count)) = branch_table_range(data, *instruction) { - let end = - start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; - data.branch_table_targets - .get(start as usize..end as usize) - .ok_or_else(|| ParseError::Other("branch table range out of bounds".into()))?; - } - } - Ok(()) -} diff --git a/crates/parser/src/parallel.rs b/crates/parser/src/parallel.rs index 4ad16cf..69dbac9 100644 --- a/crates/parser/src/parallel.rs +++ b/crates/parser/src/parallel.rs @@ -1,4 +1,4 @@ -use crate::module::{OptimizedFunctionCode, optimize_function_code}; +use crate::module::FunctionCode; use crate::validation::{FuncToValidate, FuncValidatorAllocations, ValidatorResources}; use crate::{ParseError, ParserOptions, Result, conversion}; use alloc::vec::Vec; @@ -48,10 +48,8 @@ pub(crate) fn should_use_parallel(options: &ParserOptions, num_functions: usize, } fn worker_count(options: &ParserOptions, num_functions: usize) -> usize { - let requested = options - .parser_threads() - .unwrap_or_else(|| std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1)) - .max(1); + let requested = + options.threads().unwrap_or_else(|| std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1)).max(1); requested.min(MAX_WORKERS).min(num_functions.div_ceil(MIN_FUNCTIONS_PER_WORKER)).max(1) } @@ -62,7 +60,15 @@ fn process_function_job( imported_func_count: usize, validator_allocs: Option, reader_allocs: OperatorsReaderAllocations, -) -> Result<(OptimizedFunctionCode, Option, OperatorsReaderAllocations)> { +) -> Result<(FunctionCode, Option, OperatorsReaderAllocations)> { + let context = conversion::FunctionLoweringContext { + ty_idx: job.ty_idx, + self_func_addr: imported_func_count + .checked_add(job.ordinal) + .and_then(|idx| u32::try_from(idx).ok()) + .ok_or_else(|| ParseError::Other("function index is too large".into()))?, + function_results: job.results, + }; #[cfg(feature = "validate")] let validator = job.func_to_validate.map(|func| func.into_validator(validator_allocs.unwrap_or_default())); #[cfg(not(feature = "validate"))] @@ -72,17 +78,15 @@ fn process_function_job( }; let (code, validator_allocs, reader_allocs) = match job.body { FunctionBodyInput::Borrowed(func) => { - conversion::convert_module_code(func, validator, reader_allocs, metadata, job.ty_idx, options)? + conversion::convert_module_code(func, validator, reader_allocs, metadata, context, options)? } FunctionBodyInput::Owned(body) => { let reader = wasmparser::BinaryReader::new(&body.section_bytes[body.body_range], body.body_offset); let func = wasmparser::FunctionBody::new(reader); - conversion::convert_module_code(func, validator, reader_allocs, metadata, job.ty_idx, options)? + conversion::convert_module_code(func, validator, reader_allocs, metadata, context, options)? } }; - let code = optimize_function_code(code, options, job.results, (imported_func_count + job.ordinal) as u32)?; - Ok((code, validator_allocs, reader_allocs)) } @@ -91,7 +95,7 @@ fn process_chunk<'a>( metadata: &crate::visit::ModuleMetadata, options: &ParserOptions, imported_func_count: usize, -) -> Result> { +) -> Result> { let mut validator_allocs = None; let mut reader_allocs = OperatorsReaderAllocations::default(); let jobs = jobs.into_iter(); @@ -113,7 +117,7 @@ pub(crate) fn process_pending( metadata: &crate::visit::ModuleMetadata, options: &ParserOptions, imported_func_count: usize, -) -> Result> { +) -> Result> { let num_workers = worker_count(options, pending.len()); if num_workers == 1 { return process_chunk(pending, metadata, options, imported_func_count); diff --git a/crates/parser/src/selection.rs b/crates/parser/src/selection.rs new file mode 100644 index 0000000..2d96b66 --- /dev/null +++ b/crates/parser/src/selection.rs @@ -0,0 +1,314 @@ +//! Ordered rule families selected by lowering, not by the incoming opcode. +//! Replacements are contiguous, non-growing suffixes and are not dispatched again. +//! Small literals stay inline until a selected encoding needs a pooled operand. + +mod encoding; +use crate::{Result, emitter::PendingTail, visit::FunctionDataBuilder}; +use encoding::*; +use tinywasm_types::{Instruction, Instruction::*, *}; + +// Patterns include the incoming instruction. First match wins, including identity +// replacements. Parenthesized guards support expressions and let chains. +macro_rules! families { + ($($name:ident($tail:ident, $data:ident $(, $arg:ident: $ty:ty)*) { + $([$($pattern:pat),+ $(,)?] $(if ($($guard:tt)+))? => $replacement:expr),+ $(,)? + })*) => {$( + #[doc = concat!("Applies the ordered `", stringify!($name), "` rules to the pending suffix.")] + #[inline] + pub(crate) fn $name($tail: &mut PendingTail<'_>, $data: &mut FunctionDataBuilder $(, $arg: $ty)*) -> Result<()> { + let _ = &$data; + $( + if let Some([$($pattern),+]) = $tail.suffix::<{ [$(stringify!($pattern)),+].len() }>() + $( && $($guard)+ )? + { + $tail.replace::<{ [$(stringify!($pattern)),+].len() }, _>($replacement); + return Ok(()); + } + )+ + Ok(()) + } + )*}; +} + +#[rustfmt::skip] +families! { + integer32(tail, data, op: BinOp, commutative: bool) { + [LocalGet32(a), LocalGet32(b), _] => [BinOpLocalLocal32(op, a, b)], + [GlobalGet32(global), _] => [BinOpStackGlobal32(op, global)], + [LocalGet32(local), _] => [BinOpStackLocal32(op, local)], + // Both producers only read locals, and the outer integer operation commutes. + [LocalGet32(local), producer, _] if (commutative && local_const32(data, producer).is_some()) => [producer, BinOpStackLocal32(op, local)], + [LocalGet32(local), Const32(value), _] => [encode_local_const32(data, op, local, value)?], + [GlobalGet32(global), Const32(value), _] => [BinOpGlobalConst32(PackedOp::new(op, data.push64(Operand64::<(u32, u32)>::new(global, value as u32))?))], + [Const32(value), LocalGet32(local), _] if (commutative) => [encode_local_const32(data, op, local, value)?], + [Const32(value), GlobalGet32(global), _] if (commutative) => [BinOpGlobalConst32(PackedOp::new(op, data.push64(Operand64::<(u32, u32)>::new(global, value as u32))?))], + [Const32(value), I32Add] => [AddConst32(value)], + [I32Add, I32Add] => [I32Add3], + [BinOpStackLocal32(BinOp::IAdd, local), I32Add] => [LocalGet32(local), I32Add3], + [left, Const32(right), _] if (op == BinOp::IShrS + && let Some((BinOp::IShl, local, shift)) = local_const32(data, left) + && shift == right && matches!(shift, 16 | 24)) => + [LocalGet32(local), if shift == 24 { I32Extend8S } else { I32Extend16S }], + [Const32(value), _] if (op != BinOp::IAdd) => [stack_const32(op, value)], + } + integer64(tail, data, op: BinOp, commutative: bool) { + [LocalGet64(a), LocalGet64(b), _] => [BinOpLocalLocal64(op, a, b)], + [GlobalGet64(global), _] => [BinOpStackGlobal64(op, global)], + [LocalGet64(local), constant, _] if (let Some(value) = const64(data, constant)) => [BinOpLocalConst64(PackedOp::new(op, data.push128(Operand128::<(u16, u64)>::new(local, value as u64))?))], + [GlobalGet64(global), constant, _] if (let Some(value) = const64(data, constant)) => [BinOpGlobalConst64(PackedOp::new(op, data.push128(Operand128::<(u32, u64)>::new(global, value as u64))?))], + [constant, LocalGet64(local), _] if (commutative && let Some(value) = const64(data, constant)) => [BinOpLocalConst64(PackedOp::new(op, data.push128(Operand128::<(u16, u64)>::new(local, value as u64))?))], + [constant, GlobalGet64(global), _] if (commutative && let Some(value) = const64(data, constant)) => [BinOpGlobalConst64(PackedOp::new(op, data.push128(Operand128::<(u32, u64)>::new(global, value as u64))?))], + [constant @ (Const64(_) | Const64Imm(_)), I64Add] => [AddConst64(pool64(data, constant)?)], + [I64Add, I64Add] => [I64Add3], + [left, constant, _] if (op == BinOp::IShrS + && let Some((BinOp::IShl, local, shift)) = local_const64(data, left) + && Some(shift) == const64(data, constant) && matches!(shift, 56 | 48 | 32)) => + [LocalGet64(local), match shift { 56 => I64Extend8S, 48 => I64Extend16S, _ => I64Extend32S }], + [constant @ (Const64(_) | Const64Imm(_)), _] if (op != BinOp::IAdd) => [BinOpStackConst64(PackedOp::new(op, pool64(data, constant)?))], + } + compare(tail, data, op: CmpOp) { + [LocalGet32(a), LocalGet32(b), _] => [CmpLocalLocal32(op, a, b)], + [LocalGet64(a), LocalGet64(b), _] => [CmpLocalLocal64(op, a, b)], + } + extend_i32(tail, data, signed: bool) { + [Const32(value), _] => [{ + let value = if signed { i64::from(value) } else { i64::from(value as u32) }; + match i32::try_from(value) { + Ok(value) => Const64Imm(value), + Err(_) => Const64(data.push64(Operand64::::new(value))?), + } + }], + } + float32(tail, data, op: BinOp, commutative: bool) { + [LocalGet32(a), LocalGet32(b), _] => [BinOpLocalLocal32(op, a, b)], + [LocalGet32(local), _] => [BinOpStackLocal32(op, local)], + [LocalGet32(local), Const32(value), _] => [encode_local_const32(data, op, local, value)?], + [GlobalGet32(global), Const32(value), _] => [BinOpGlobalConst32(PackedOp::new(op, data.push64(Operand64::<(u32, u32)>::new(global, value as u32))?))], + [Const32(value), LocalGet32(local), _] if (commutative) => [encode_local_const32(data, op, local, value)?], + [Const32(value), GlobalGet32(global), _] if (commutative) => [BinOpGlobalConst32(PackedOp::new(op, data.push64(Operand64::<(u32, u32)>::new(global, value as u32))?))], + [Const32(value), _] => [stack_const32(op, value)], + } + float64(tail, data, op: BinOp, commutative: bool) { + [LocalGet64(a), LocalGet64(b), _] => [BinOpLocalLocal64(op, a, b)], + [LocalGet64(local), constant, _] if (let Some(value) = const64(data, constant)) => [BinOpLocalConst64(PackedOp::new(op, data.push128(Operand128::<(u16, u64)>::new(local, value as u64))?))], + [GlobalGet64(global), constant, _] if (let Some(value) = const64(data, constant)) => [BinOpGlobalConst64(PackedOp::new(op, data.push128(Operand128::<(u32, u64)>::new(global, value as u64))?))], + [constant, LocalGet64(local), _] if (commutative && let Some(value) = const64(data, constant)) => [BinOpLocalConst64(PackedOp::new(op, data.push128(Operand128::<(u16, u64)>::new(local, value as u64))?))], + [constant, GlobalGet64(global), _] if (commutative && let Some(value) = const64(data, constant)) => [BinOpGlobalConst64(PackedOp::new(op, data.push128(Operand128::<(u32, u64)>::new(global, value as u64))?))], + [constant @ (Const64(_) | Const64Imm(_)), _] => [BinOpStackConst64(PackedOp::new(op, pool64(data, constant)?))], + } + vector(tail, data, op: BinOp128, commutative: bool) { + // Stack/local deliberately shadows local/local and reversed local constants. + [LocalGet128(local), _] => [BinOpStackLocal128(op, local)], + [LocalGet128(a), LocalGet128(b), _] => [BinOpLocalLocal128(op, a, b)], + [LocalGet128(local), constant @ (Const128(_) | Const128Imm(_)), _] => [{ + let value = pool128(data, constant)?; + BinOpLocalConst128(PackedOp::new(op, data.push64(Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(local, value))?)) + }], + [GlobalGet128(global), constant @ (Const128(_) | Const128Imm(_)), _] => [{ + let value = pool128(data, constant)?; + BinOpGlobalConst128(PackedOp::new(op, data.push64(Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(global, value))?)) + }], + [constant @ (Const128(_) | Const128Imm(_)), LocalGet128(local), _] if (commutative) => [{ + let value = pool128(data, constant)?; + BinOpLocalConst128(PackedOp::new(op, data.push64(Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(local, value))?)) + }], + [constant @ (Const128(_) | Const128Imm(_)), GlobalGet128(global), _] if (commutative) => [{ + let value = pool128(data, constant)?; + BinOpGlobalConst128(PackedOp::new(op, data.push64(Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(global, value))?)) + }], + } + store32(tail, data, index: Operand128Idx) { + [Select32, _] => [SelectStore32(index)], + [LocalGet32(addr) | LocalGet64(addr), LoadLocal32(arg), AddConst32(1), _] + if (CompactMemoryArg::try_from(data.operand128(index)).ok().map(Operand64::from) + == Some(data.operand64(arg.memory_arg_idx)) && addr == u16::from(arg.local1)) => [IncMemoryLocal32(arg)], + [F32Mul, F32Add, _] if (let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index))) => [FMaStoreF32(arg)], + [BinOpStackLocal32(BinOp::FMul, local), F32Add, _] + if (let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index))) => [LocalGet32(local), FMaStoreF32(arg)], + [LocalGet32(addr), LocalGet32(value), _] + if (let (Ok(addr), Ok(value), Ok(arg)) = (u8::try_from(addr), u8::try_from(value), + CompactMemoryArg::try_from(data.operand128(index)))) => [StoreLocalLocal32(MemoryLocalArg { + memory_arg_idx: data.push64(Operand64::from(arg))?, local1: addr, local2: value })], + } + store64(tail, data, index: Operand128Idx) { + [Select64, _] => [SelectStore64(index)], + [LocalGet32(addr) | LocalGet64(addr), LoadLocal64(arg), AddConst64(one), _] + if (CompactMemoryArg::try_from(data.operand128(index)).ok().map(Operand64::from) + == Some(data.operand64(arg.memory_arg_idx)) && addr == u16::from(arg.local1) + && data.operand64(one).value() == 1) => [IncMemoryLocal64(arg)], + [F64Mul, F64Add, _] if (let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index))) => [FMaStoreF64(arg)], + [LocalGet32(addr), LocalGet64(value), _] + if (let (Ok(addr), Ok(value), Ok(arg)) = (u8::try_from(addr), u8::try_from(value), + CompactMemoryArg::try_from(data.operand128(index)))) => [StoreLocalLocal64(MemoryLocalArg { + memory_arg_idx: data.push64(Operand64::from(arg))?, local1: addr, local2: value })], + } + memory_fill(tail, data, memory: u32) { + [Const32(value), Const32(size), _] => [MemoryFillConst(data.push128(Operand128::::new(memory, value as u8, size))?)], + } + global_get32(tail, data, dst: u32) { [GlobalSet32(src), _] if (src == dst) => [GlobalTee32(src)] } + global_get64(tail, data, dst: u32) { [GlobalSet64(src), _] if (src == dst) => [GlobalTee64(src)] } + global_get128(tail, data, dst: u32) { [GlobalSet128(src), _] if (src == dst) => [GlobalTee128(src)] } + local_get32(tail, data, dst: u16) { [LocalSet32(src), _] if (src == dst) => [LocalTee32(src)] } + local_get64(tail, data, dst: u16) { [LocalSet64(src), _] if (src == dst) => [LocalTee64(src)] } + local_get128(tail, data, dst: u16) { [LocalSet128(src), _] if (src == dst) => [LocalTee128(src)] } + local_set32(tail, data, dst: u16) { + [I32Mul, BinOpStackLocal32(BinOp::IAdd, acc), _] if (acc == dst) => [MulAccLocal32(dst)], + [F32Mul, BinOpStackLocal32(BinOp::FAdd, acc), _] if (acc == dst) => [FMulAccLocal32(dst)], + [LocalGet32(src), _] if (src == dst) => [], + [LocalGet32(src), _] => [LocalCopy32(src, dst)], + [Const32(value), _] => [SetLocalConst32(I32LocalArg { value, local: dst })], + [BinOpLocalLocal32(BinOp::IAdd, left, right), _] => [AddLocalLocalSet32(LocalTripleArg { left, right, dst })], + [BinOpLocalLocal32(op, left, right), _] => [BinOpLocalLocalSet32(PackedOp::new(op, data.push64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?))], + [instruction, _] if (let Some((op, src, value)) = local_const32(data, instruction)) => [{ + if src == dst && let Some(delta) = op.inc_delta(value) { + IncLocal32(I32LocalArg { value: delta, local: dst }) + } else { local_const_set32(data, op, src, dst, value, false)? } + }], + [BinOpStackLocal32(op, local), _] => [BinOpStackLocalSet32(op, local, dst)], + [LoadLocal32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalSet32(MemoryLocalArg { local2: dst, ..arg })], + [LoadLocal8S32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalSet8S32(MemoryLocalArg { local2: dst, ..arg })], + [LoadLocal8U32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalSet8U32(MemoryLocalArg { local2: dst, ..arg })], + [LoadLocal16S32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalSet16S32(MemoryLocalArg { local2: dst, ..arg })], + [LoadLocal16U32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalSet16U32(MemoryLocalArg { local2: dst, ..arg })], + } + local_set64(tail, data, dst: u16) { + [I64Mul, LocalGet64(acc), I64Add, _] if (acc == dst) => [MulAccLocal64(dst)], + [F64Mul, LocalGet64(acc), F64Add, _] if (acc == dst) => [FMulAccLocal64(dst)], + [LocalGet64(src), _] if (src == dst) => [], + [LocalGet64(src), _] => [LocalCopy64(src, dst)], + [constant @ (Const64(_) | Const64Imm(_)), _] => [SetLocalConst64(PackedOp::new(dst, pool64(data, constant)?))], + [BinOpLocalLocal64(op, left, right), _] => [BinOpLocalLocalSet64(PackedOp::new(op, data.push64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?))], + [instruction, _] if (let Some((op, src, value)) = local_const64(data, instruction)) => [{ + if src == dst && matches!(op, BinOp::IAdd | BinOp::ISub) { + let delta = if op == BinOp::IAdd { value } else { value.wrapping_neg() }; + IncLocal64(PackedOp::new(dst, data.push64(Operand64::::new(delta))?)) + } else { local_const_set64(data, op, src, dst, value, false)? } + }], + } + local_set128(tail, data, dst: u16) { + [LocalGet32(local), V128Load(index), _] if (let (Ok(local), Ok(dst), Ok(arg)) = + (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand128(index)))) => + [LoadLocalSet128(MemoryLocalArg { memory_arg_idx: data.push64(Operand64::from(arg))?, local1: local, local2: dst })], + [LocalGet128(src), _] if (src == dst) => [], + [LocalGet128(src), _] => [LocalCopy128(src, dst)], + [constant @ (Const128(_) | Const128Imm(_)), _] => [SetLocalConst128(PackedOp::new(dst, pool128(data, constant)?))], + [BinOpLocalLocal128(op, left, right), _] => [BinOpLocalLocalSet128(PackedOp::new(op, data.push64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?))], + [instruction, _] if (let Some((op, src, value)) = local_const128(data, instruction)) => + [local_const_set128(data, op, src, dst, value, false)?], + } + local_tee32(tail, data, dst: u16) { + [Const32(value), I32And, _] => [AndConstTee32(I32LocalArg { value, local: dst })], + [Const32(value), I32Sub, _] => [SubConstTee32(I32LocalArg { value, local: dst })], + [AndConst32(value), _] => [AndConstTee32(I32LocalArg { value, local: dst })], + [BinOpStackConst32(BinOp::ISub, value), _] => [SubConstTee32(I32LocalArg { value, local: dst })], + [LocalGet32(src), _] if (src == dst) => [LocalGet32(src)], + [LocalGet32(src), _] => [LocalCopy32(src, dst), LocalGet32(dst)], + [BinOpLocalLocal32(BinOp::IAdd, left, right), _] => [AddLocalLocalTee32(LocalTripleArg { left, right, dst })], + [BinOpLocalLocal32(op, left, right), _] => [BinOpLocalLocalTee32(PackedOp::new(op, data.push64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?))], + [instruction, _] if (let Some((op, src, value)) = local_const32(data, instruction)) => + [local_const_set32(data, op, src, dst, value, true)?], + [BinOpStackLocal32(op, local), _] => [BinOpStackLocalTee32(op, local, dst)], + [LoadLocal32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalTee32(MemoryLocalArg { local2: dst, ..arg })], + [LoadLocal8S32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalTee8S32(MemoryLocalArg { local2: dst, ..arg })], + [LoadLocal8U32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalTee8U32(MemoryLocalArg { local2: dst, ..arg })], + [LoadLocal16S32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalTee16S32(MemoryLocalArg { local2: dst, ..arg })], + [LoadLocal16U32(arg), _] if (let Ok(dst) = u8::try_from(dst)) => [LoadLocalTee16U32(MemoryLocalArg { local2: dst, ..arg })], + } + local_tee64(tail, data, dst: u16) { + [constant @ (Const64(_) | Const64Imm(_)), I64And, _] => [AndConstTee64(PackedOp::new(dst, pool64(data, constant)?))], + [constant @ (Const64(_) | Const64Imm(_)), I64Sub, _] => [SubConstTee64(PackedOp::new(dst, pool64(data, constant)?))], + [BinOpStackConst64(packed), _] if (packed.op == BinOp::IAnd) => [AndConstTee64(PackedOp::new(dst, packed.index))], + [BinOpStackConst64(packed), _] if (packed.op == BinOp::ISub) => [SubConstTee64(PackedOp::new(dst, packed.index))], + [LocalGet64(src), _] if (src == dst) => [LocalGet64(src)], + [LocalGet64(src), _] => [LocalCopy64(src, dst), LocalGet64(dst)], + [BinOpLocalLocal64(op, left, right), _] => [BinOpLocalLocalTee64(PackedOp::new(op, data.push64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?))], + [instruction, _] if (let Some((op, src, value)) = local_const64(data, instruction)) => [local_const_set64(data, op, src, dst, value, true)?], + } + local_tee128(tail, data, dst: u16) { + [LocalGet32(local), V128Load(index), _] if (let (Ok(local), Ok(dst), Ok(arg)) = + (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand128(index)))) => + [LoadLocalTee128(MemoryLocalArg { memory_arg_idx: data.push64(Operand64::from(arg))?, local1: local, local2: dst })], + [LocalGet128(src), _] if (src == dst) => [LocalGet128(src)], + [LocalGet128(src), _] => [LocalCopy128(src, dst), LocalGet128(dst)], + [BinOpLocalLocal128(op, left, right), _] => [BinOpLocalLocalTee128(PackedOp::new(op, data.push64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?))], + [instruction, _] if (let Some((op, src, value)) = local_const128(data, instruction)) => [local_const_set128(data, op, src, dst, value, true)?], + } + drop32(tail, data) { + [LocalTee32(local), _] => [LocalSet32(local)], + [BinOpStackLocalTee32(op, local, dst), _] => [BinOpStackLocalSet32(op, local, dst)], + [AddLocalLocalTee32(arg), _] => [AddLocalLocalSet32(arg)], + [BinOpLocalLocalTee32(packed), _] => [BinOpLocalLocalSet32(packed)], + [BinOpLocalConstTee32(packed), _] => [BinOpLocalConstSet32(packed)], + } + drop64(tail, data) { + [LocalTee64(local), _] => [LocalSet64(local)], + [BinOpLocalLocalTee64(packed), _] => [BinOpLocalLocalSet64(packed)], + [BinOpLocalConstTee64(packed), _] => [BinOpLocalConstSet64(packed)], + } + drop128(tail, data) { + [LocalTee128(local), _] => [LocalSet128(local)], + [BinOpLocalLocalTee128(packed), _] => [BinOpLocalLocalSet128(packed)], + [BinOpLocalConstTee128(packed), _] => [BinOpLocalConstSet128(packed)], + } + load(tail, data, instruction: impl FnOnce(MemoryLocalArg) -> Instruction, index: Operand128Idx) { + [LocalGet32(local) | LocalGet64(local), _] + if (let Ok(local) = u8::try_from(local) + && let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index))) => + [instruction(MemoryLocalArg { + memory_arg_idx: data.push64(Operand64::from(arg))?, local1: local, local2: 0 })], + } + store128(tail, data, index: Operand128Idx) { + [LocalGet32(addr), LocalGet128(value), _] + if (let (Ok(addr), Ok(value)) = (u8::try_from(addr), u8::try_from(value)) + && let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index))) => + [StoreLocalLocal128(MemoryLocalArg { + memory_arg_idx: data.push64(Operand64::from(arg))?, local1: addr, local2: value })], + } + conditional(tail, data, on_zero: bool, target: u32) { + [BinOpLocalConstTee32(packed), _] if (data.operand64(packed.index).a() == data.operand64(packed.index).b()) => [{ + let value = data.operand64(packed.index); + update_jump(data, target, value.c() as i32, u32::from(value.a()), packed.op, on_zero, false)? + }], + [BinOpGlobalConst32(packed), GlobalTee32(dst), _] if (data.operand64(packed.index).a() == dst) => [update_jump(data, target, data.operand64(packed.index).b() as i32, dst, packed.op, on_zero, true)?], + [AddConst32(value), LocalTee32(local), LocalGet32(cond), _] if (local == cond) => [IncStackTeeLocalJump32(data.push_target128(Operand128::::new(target, value, local, on_zero))?)], + [XorConst32(value), LocalTee32(local), LocalGet32(cond), _] if (local == cond) => [stack_update_jump(data, target, value, local, BinOp::IXor, on_zero)?], + [ShrUConst32(value), LocalTee32(local), LocalGet32(cond), _] if (local == cond) => [stack_update_jump(data, target, value, local, BinOp::IShrU, on_zero)?], + [BinOpStackConst32(op, value), LocalTee32(local), LocalGet32(cond), _] if (local == cond) => [stack_update_jump(data, target, value, local, op, on_zero)?], + [AndConstTee32(arg), LocalGet32(cond), _] if (arg.local == cond) => [stack_update_jump(data, target, arg.value, arg.local, BinOp::IAnd, on_zero)?], + [SubConstTee32(arg), LocalGet32(cond), _] if (arg.local == cond) => + [IncStackTeeLocalJump32(data.push_target128(Operand128::::new( + target, arg.value.wrapping_neg(), arg.local, on_zero))?)], + [BinOpLocalConstTee32(packed), LocalGet32(right), raw_cmp, _] + if (let Some(cmp) = cmp_op(raw_cmp) + && data.operand64(packed.index).a() == data.operand64(packed.index).b()) => [{ + let value = data.operand64(packed.index); + let cmp = if on_zero { cmp.inverse() } else { cmp }; + if let Some(delta) = packed.op.inc_delta(value.c() as i32) { + IncLocalJumpCmpLocal32(PackedOp::new(cmp, data.push_target128( + Operand128::::new(target, delta, value.a(), right))?)) + } else { + BinOpLocalConstJumpCmpLocal32(PackedOp::new((packed.op, cmp), data.push_target128( + Operand128::::new(target, value.c() as i32, value.a(), right))?)) + } + }], + [LocalGet32(local), I32Eqz, _] => [local_jump(target, local, !on_zero, false)], + [LocalGet64(local), I64Eqz, _] => [local_jump(target, local, !on_zero, true)], + [CmpLocalLocal32(op, left, right), I32Eqz, _] => [jump_cmp_local_local(data, target, left, right, if on_zero { op } else { op.inverse() }, false)?], + [I32Eqz, _] => [if on_zero { JumpIfNonZero32(target) } else { JumpIfZero32(target) }], + [I64Eqz, _] => [if on_zero { JumpIfNonZero64(target) } else { JumpIfZero64(target) }], + [CmpLocalLocal32(op, left, right), _] => [jump_cmp_local_local(data, target, left, right, if on_zero { op.inverse() } else { op }, false)?], + [CmpLocalLocal64(op, left, right), _] => [jump_cmp_local_local(data, target, left, right, if on_zero { op.inverse() } else { op }, true)?], + [LocalGet32(local), _] => [local_jump(target, local, on_zero, false)], + [LocalGet64(local), _] => [local_jump(target, local, on_zero, true)], + [LocalGet32(local), Const32(value), raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero)) => [jump_cmp_local_const32(data, target, local, value, op)?], + [LocalGet64(local), constant, raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero) + && let Some(value) = const64(data, constant) && let Ok(value) = i32::try_from(value)) => + [jump_cmp_local_const64(data, target, local, value, op)?], + [LocalGet32(left), LocalGet32(right), raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero)) => [jump_cmp_local_local(data, target, left, right, op, false)?], + [LocalGet64(left), LocalGet64(right), raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero)) => [jump_cmp_local_local(data, target, left, right, op, true)?], + [LocalGet32(local), raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero)) => [jump_cmp_stack_local(data, target, local, op, false)?], + [LocalGet64(local), raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero)) => [jump_cmp_stack_local(data, target, local, op, true)?], + [Const32(value), raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero)) => [jump_cmp_stack_const32(data, target, value, op)?], + [constant, raw_cmp, _] if (let Some(op) = branch_cmp(raw_cmp, on_zero) && let Some(value) = const64(data, constant)) => [jump_cmp_stack_const64(data, target, value, op)?], + } +} diff --git a/crates/parser/src/selection/encoding.rs b/crates/parser/src/selection/encoding.rs new file mode 100644 index 0000000..0b407e5 --- /dev/null +++ b/crates/parser/src/selection/encoding.rs @@ -0,0 +1,293 @@ +//! Operand decoding and encoding, without access to the instruction tail. +use crate::{Result, visit::FunctionDataBuilder}; +use tinywasm_types::{Instruction, Instruction::*, *}; + +/// Reads a 64-bit literal without requiring a pool entry for immediate values. +pub(super) fn const64(data: &FunctionDataBuilder, instruction: Instruction) -> Option { + match instruction { + Const64(index) => Some(data.operand64(index).value()), + Const64Imm(value) => Some(i64::from(value)), + _ => None, + } +} + +/// Materializes a literal only when the selected encoding requires an operand index. +pub(super) fn pool64(data: &mut FunctionDataBuilder, instruction: Instruction) -> Result> { + match instruction { + Const64(index) => Ok(index), + Const64Imm(value) => data.push64(Operand64::::new(i64::from(value))), + _ => unreachable!("expected a 64-bit constant"), + } +} + +/// Materializes a vector literal only when the selected encoding requires an operand index. +pub(super) fn pool128(data: &mut FunctionDataBuilder, instruction: Instruction) -> Result> { + match instruction { + Const128(index) => Ok(index), + Const128Imm(value) => data.push128(Operand128::<[u8; 16]>::new(u128::from(value).to_le_bytes())), + _ => unreachable!("expected a vector constant"), + } +} + +/// Decodes specialized and pooled local constants uniformly. +pub(super) fn local_const32(data: &FunctionDataBuilder, instruction: Instruction) -> Option<(BinOp, u16, i32)> { + match instruction { + AddLocalConst32(arg) => Some((BinOp::IAdd, arg.local, arg.value)), + SubLocalConst32(arg) => Some((BinOp::ISub, arg.local, arg.value)), + MulLocalConst32(arg) => Some((BinOp::IMul, arg.local, arg.value)), + AndLocalConst32(arg) => Some((BinOp::IAnd, arg.local, arg.value)), + ShrULocalConst32(arg) => Some((BinOp::IShrU, arg.local, arg.value)), + BinOpLocalConst32(packed) => { + let value = data.operand64(packed.index); + Some((packed.op, value.a(), value.b() as i32)) + } + _ => None, + } +} + +/// Decodes a pooled 64-bit local constant. +pub(super) fn local_const64(data: &FunctionDataBuilder, instruction: Instruction) -> Option<(BinOp, u16, i64)> { + let BinOpLocalConst64(packed) = instruction else { return None }; + let value = data.operand128(packed.index); + Some((packed.op, value.a(), value.b() as i64)) +} + +/// Decodes a pooled vector local constant. +pub(super) fn local_const128( + data: &FunctionDataBuilder, + instruction: Instruction, +) -> Option<(BinOp128, u16, Operand128Idx<[u8; 16]>)> { + let BinOpLocalConst128(packed) = instruction else { return None }; + let value = data.operand64(packed.index); + Some((packed.op, value.a(), value.b())) +} + +/// Encodes the dedicated 32-bit local operations before falling back to a pooled operand. +pub(super) fn encode_local_const32( + data: &mut FunctionDataBuilder, + op: BinOp, + local: u16, + value: i32, +) -> Result { + let arg = I32LocalArg { value, local }; + Ok(match op { + BinOp::IAdd => AddLocalConst32(arg), + BinOp::ISub => SubLocalConst32(arg), + BinOp::IMul => MulLocalConst32(arg), + BinOp::IAnd => AndLocalConst32(arg), + BinOp::IShrU => ShrULocalConst32(arg), + _ => BinOpLocalConst32(PackedOp::new(op, data.push64(Operand64::<(u16, u32)>::new(local, value as u32))?)), + }) +} + +/// Encodes dedicated stack-immediate operations. +pub(super) fn stack_const32(op: BinOp, value: i32) -> Instruction { + match op { + BinOp::IAnd => AndConst32(value), + BinOp::IXor => XorConst32(value), + BinOp::IShrU => ShrUConst32(value), + _ => BinOpStackConst32(op, value), + } +} + +macro_rules! local_const_set { + ($($name:ident, $op:ty, $value:ty, [$($cast:tt)*], $pool:ident, $operand:ty, $set:ident, $tee:ident;)*) => {$( + /// Encodes a local constant operation with a destination local. + pub(super) fn $name(data: &mut FunctionDataBuilder, op: $op, src: u16, dst: u16, value: $value, tee: bool) -> Result { + let index = data.$pool(<$operand>::new(src, dst, value $($cast)*))?; + Ok(if tee { $tee(PackedOp::new(op, index)) } else { $set(PackedOp::new(op, index)) }) + } + )*}; +} +local_const_set! { + local_const_set32, BinOp, i32, [as u32], push64, Operand64<(u16, u16, u32)>, BinOpLocalConstSet32, BinOpLocalConstTee32; + local_const_set64, BinOp, i64, [as u64], push128, Operand128<(u16, u16, u64)>, BinOpLocalConstSet64, BinOpLocalConstTee64; + local_const_set128, BinOp128, Operand128Idx<[u8; 16]>, [], push64, Operand64<(u16, u16, Operand128Idx<[u8; 16]>)>, BinOpLocalConstSet128, BinOpLocalConstTee128; +} + +/// Decodes a preceding integer comparison, not the incoming instruction. +pub(super) fn cmp_op(instruction: Instruction) -> Option { + Some(match instruction { + I32Eq | I64Eq => CmpOp::Eq, + I32Ne | I64Ne => CmpOp::Ne, + I32LtS | I64LtS => CmpOp::LtS, + I32LtU | I64LtU => CmpOp::LtU, + I32GtS | I64GtS => CmpOp::GtS, + I32GtU | I64GtU => CmpOp::GtU, + I32LeS | I64LeS => CmpOp::LeS, + I32LeU | I64LeU => CmpOp::LeU, + I32GeS | I64GeS => CmpOp::GeS, + I32GeU | I64GeU => CmpOp::GeU, + _ => return None, + }) +} + +/// Applies branch polarity to a preceding integer comparison. +pub(super) fn branch_cmp(instruction: Instruction, on_zero: bool) -> Option { + cmp_op(instruction).map(|op| if on_zero { op.inverse() } else { op }) +} + +/// Encodes a local zero test of the requested width and polarity. +pub(super) fn local_jump(target: u32, local: u16, on_zero: bool, width64: bool) -> Instruction { + let arg = TargetLocalArg { target_ip: target, local }; + match (on_zero, width64) { + (true, false) => JumpIfLocalZero32(arg), + (false, false) => JumpIfLocalNonZero32(arg), + (true, true) => JumpIfLocalZero64(arg), + (false, true) => JumpIfLocalNonZero64(arg), + } +} + +/// Allocates a private target operand for a local/local comparison. +pub(super) fn jump_cmp_local_local( + data: &mut FunctionDataBuilder, + target: u32, + left: u16, + right: u16, + op: CmpOp, + width64: bool, +) -> Result { + let index = data.push_target64(Operand64::<(u32, u16, u16)>::new(target, left, right))?; + Ok(if width64 { + JumpCmpLocalLocal64(PackedOp::new(op, index)) + } else { + JumpCmpLocalLocal32(PackedOp::new(op, index)) + }) +} + +/// Allocates a private target operand for a stack/local comparison. +pub(super) fn jump_cmp_stack_local( + data: &mut FunctionDataBuilder, + target: u32, + local: u16, + op: CmpOp, + width64: bool, +) -> Result { + let index = data.push_target64(Operand64::<(u32, u16)>::new(target, local))?; + Ok(if width64 { + JumpCmpStackLocal64(PackedOp::new(op, index)) + } else { + JumpCmpStackLocal32(PackedOp::new(op, index)) + }) +} + +/// Encodes a local/immediate comparison, specializing zero equality tests. +pub(super) fn jump_cmp_local_const32( + data: &mut FunctionDataBuilder, + target: u32, + local: u16, + value: i32, + op: CmpOp, +) -> Result { + if value == 0 && matches!(op, CmpOp::Eq | CmpOp::Ne) { + return Ok(local_jump(target, local, op == CmpOp::Eq, false)); + } + Ok(JumpCmpLocalConst32(PackedOp::new( + op, + data.push_target128(Operand128::<(u32, i32, u16)>::new(target, value, local))?, + ))) +} + +/// Encodes a 64-bit local comparison with a representable 32-bit immediate. +pub(super) fn jump_cmp_local_const64( + data: &mut FunctionDataBuilder, + target: u32, + local: u16, + value: i32, + op: CmpOp, +) -> Result { + if value == 0 && matches!(op, CmpOp::Eq | CmpOp::Ne) { + return Ok(local_jump(target, local, op == CmpOp::Eq, true)); + } + Ok(JumpCmpLocalConst64(PackedOp::new( + op, + data.push_target128(Operand128::<(u32, i32, u16)>::new(target, value, local))?, + ))) +} + +/// Encodes a 32-bit stack/immediate comparison. +pub(super) fn jump_cmp_stack_const32( + data: &mut FunctionDataBuilder, + target: u32, + value: i32, + op: CmpOp, +) -> Result { + if value == 0 { + match op { + CmpOp::Eq => return Ok(JumpIfZero32(target)), + CmpOp::Ne => return Ok(JumpIfNonZero32(target)), + _ => {} + } + } + Ok(JumpCmpStackConst32(PackedOp::new(op, data.push_target64(Operand64::<(u32, i32)>::new(target, value))?))) +} + +/// Encodes a 64-bit stack/immediate comparison. +pub(super) fn jump_cmp_stack_const64( + data: &mut FunctionDataBuilder, + target: u32, + value: i64, + op: CmpOp, +) -> Result { + if value == 0 { + match op { + CmpOp::Eq => return Ok(JumpIfZero64(target)), + CmpOp::Ne => return Ok(JumpIfNonZero64(target)), + _ => {} + } + } + Ok(JumpCmpStackConst64(PackedOp::new(op, data.push_target128(Operand128::<(u32, i64)>::new(target, value))?))) +} + +/// Encodes a stack update, tee, and branch using a private target operand. +pub(super) fn stack_update_jump( + data: &mut FunctionDataBuilder, + target: u32, + value: i32, + local: u16, + op: BinOp, + on_zero: bool, +) -> Result { + Ok(BinOpStackConstTeeLocalJump32(PackedOp::new( + op, + data.push_target128(Operand128::::new(target, value, local, on_zero))?, + ))) +} + +/// Encodes local/global updates, specializing increments when possible. +pub(super) fn update_jump( + data: &mut FunctionDataBuilder, + target: u32, + immediate: i32, + address: u32, + op: BinOp, + on_zero: bool, + global: bool, +) -> Result { + if let Some(delta) = op.inc_delta(immediate) { + Ok(if global { + IncGlobalJump32( + data.push_target128(Operand128::::new(target, delta, address, on_zero))?, + ) + } else { + IncLocalJump32(data.push_target128(Operand128::::new( + target, + delta, + address as u16, + on_zero, + ))?) + }) + } else { + Ok(if global { + BinOpGlobalConstJump32(PackedOp::new( + op, + data.push_target128(Operand128::::new(target, immediate, address, on_zero))?, + )) + } else { + BinOpLocalConstJump32(PackedOp::new( + op, + data.push_target128(Operand128::::new(target, immediate, address as u16, on_zero))?, + )) + }) + } +} diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index 7daef52..a362f84 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -1,13 +1,19 @@ use crate::{ - Result, - conversion::{convert_heap_type, value_lane}, + ParserOptions, Result, + conversion::{FunctionLoweringContext, convert_heap_type, value_lane}, + emitter::{Emitter, LabelId}, macros::visit::*, }; -use alloc::{boxed::Box, collections::BTreeMap, string::ToString, vec::Vec}; +use alloc::{ + boxed::Box, + collections::{BTreeMap, btree_map::Entry}, + string::ToString, + vec::Vec, +}; use tinywasm_types::{ - BranchTableOperand, ExceptionHandler, Global, Import, ImportKind, Instruction, MemoryType, Operand64, Operand64Idx, - Operand128, Operand128Idx, StorageType, TableDefinition, TagType, TypeSection, ValueCounts, ValueLane, - WasmFunctionData, + BinOp, BinOp128, CmpOp, ExceptionHandler, Global, Import, ImportKind, Instruction, MemoryType, Operand64, + Operand64Idx, Operand128, Operand128Idx, StorageType, TableDefinition, TagType, TypeSection, ValueCounts, + ValueLane, WasmFunctionData, }; use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator}; @@ -20,29 +26,53 @@ enum BlockKind { Block, Loop, If, - TryTable(usize), + TryTable, } -struct ControlFrame { +struct ControlFrame<'a> { kind: BlockKind, has_else: bool, - start_ip: usize, - branch_jumps: Vec, + loop_start: Option, + end: Option, + else_entry: Option, height: usize, base: ValueCounts, - params: Vec, - results: Vec, + signature: BlockSignature<'a>, unreachable: bool, entry_unreachable: bool, end_reachable: bool, } -#[derive(Clone)] +/// Module-owned physical lane signature, borrowed by control frames. pub(crate) struct Signature { pub params: Vec, results: Vec, } +#[derive(Clone, Copy)] +enum BlockSignature<'a> { + Empty, + Result(ValueLane), + Function(&'a Signature), +} + +impl BlockSignature<'_> { + fn params(&self) -> &[ValueLane] { + match self { + Self::Function(signature) => &signature.params, + _ => &[], + } + } + + fn results(&self) -> &[ValueLane] { + match self { + Self::Empty => &[], + Self::Result(lane) => core::slice::from_ref(lane), + Self::Function(signature) => &signature.results, + } + } +} + pub(crate) struct ModuleMetadata { signatures: Vec>, functions: Vec, @@ -75,40 +105,54 @@ impl FunctionDataBuilder { } } - pub(crate) fn push_operand64(&mut self, operand: Operand64) -> Result> { + /// Allocates an immutable 64-bit operand, reusing it when deduplication is enabled. + pub(crate) fn push64(&mut self, operand: Operand64) -> Result> { let operand = operand.cast(); - if let Some(index) = self.deduplicate64.as_ref().and_then(|map| map.get(&operand)) { - return Ok(Operand64Idx::new(*index)); - } - let index = self.operands64.len() as u32; + let entry = match self.deduplicate64.as_mut().map(|map| map.entry(operand)) { + Some(Entry::Occupied(entry)) => return Ok(Operand64Idx::new(*entry.get())), + Some(Entry::Vacant(entry)) => Some(entry), + None => None, + }; + let index = u32::try_from(self.operands64.len()) + .map_err(|_| crate::ParseError::Other("operand pool is too large".into()))?; self.operands64.push(operand); - if let Some(map) = &mut self.deduplicate64 { - map.insert(operand, index); + if let Some(entry) = entry { + entry.insert(index); } Ok(Operand64Idx::new(index)) } - pub(crate) fn push_operand128(&mut self, operand: Operand128) -> Result> { + /// Allocates an immutable 128-bit operand, reusing it when deduplication is enabled. + pub(crate) fn push128(&mut self, operand: Operand128) -> Result> { let operand = operand.cast(); - if let Some(index) = self.deduplicate128.as_ref().and_then(|map| map.get(&operand)) { - return Ok(Operand128Idx::new(*index)); - } - let index = self.operands128.len() as u32; + let entry = match self.deduplicate128.as_mut().map(|map| map.entry(operand)) { + Some(Entry::Occupied(entry)) => return Ok(Operand128Idx::new(*entry.get())), + Some(Entry::Vacant(entry)) => Some(entry), + None => None, + }; + let index = u32::try_from(self.operands128.len()) + .map_err(|_| crate::ParseError::Other("operand pool is too large".into()))?; self.operands128.push(operand); - if let Some(map) = &mut self.deduplicate128 { - map.insert(operand, index); + if let Some(entry) = entry { + entry.insert(index); } Ok(Operand128Idx::new(index)) } - pub(crate) fn push_target_operand64(&mut self, operand: Operand64) -> Result> { + /// Allocates a private mutable target operand outside immutable deduplication. + pub(crate) fn push_target64(&mut self, operand: Operand64) -> Result> { + let index = u32::try_from(self.operands64.len()) + .map_err(|_| crate::ParseError::Other("operand pool is too large".into()))?; self.operands64.push(operand.cast()); - Ok(Operand64Idx::new(self.operands64.len() as u32 - 1)) + Ok(Operand64Idx::new(index)) } - pub(crate) fn push_target_operand128(&mut self, operand: Operand128) -> Result> { + /// Allocates a private mutable target operand outside immutable deduplication. + pub(crate) fn push_target128(&mut self, operand: Operand128) -> Result> { + let index = u32::try_from(self.operands128.len()) + .map_err(|_| crate::ParseError::Other("operand pool is too large".into()))?; self.operands128.push(operand.cast()); - Ok(Operand128Idx::new(self.operands128.len() as u32 - 1)) + Ok(Operand128Idx::new(index)) } pub(crate) fn operand64(&self, index: Operand64Idx) -> Operand64 { @@ -119,14 +163,6 @@ impl FunctionDataBuilder { self.operands128[index.index()].cast() } - pub(crate) fn set_operand64(&mut self, index: Operand64Idx, operand: Operand64) { - self.operands64[index.index()] = operand.cast(); - } - - pub(crate) fn set_operand128(&mut self, index: Operand128Idx, operand: Operand128) { - self.operands128[index.index()] = operand.cast(); - } - pub(crate) fn finish(self) -> WasmFunctionData { WasmFunctionData { operands64: self.operands64.into_boxed_slice(), @@ -144,9 +180,9 @@ enum AggregateFields { } pub(crate) struct FunctionBuilder<'a> { - instructions: Vec, + emitter: Emitter, data: FunctionDataBuilder, - control_stack: Vec, + control_stack: Vec>, operand_stack: Vec, lane_counts: ValueCounts, metadata: &'a ModuleMetadata, @@ -156,29 +192,31 @@ pub(crate) struct FunctionBuilder<'a> { } impl<'a> FunctionBuilder<'a> { + /// Creates lowering state with a borrowed function signature. pub(crate) fn new( metadata: &'a ModuleMetadata, - signature: &Signature, + signature: &'a Signature, local_types: Vec, local_addr_map: Vec, body_size: usize, - deduplicate_operands: bool, + context: FunctionLoweringContext, + options: &ParserOptions, ) -> Self { Self { local_types, local_addr_map, metadata, - instructions: Vec::with_capacity(body_size.min(1024)), - data: FunctionDataBuilder::new(deduplicate_operands), + emitter: Emitter::new(body_size, context, options), + data: FunctionDataBuilder::new(options.deduplicate_operands()), control_stack: alloc::vec![ControlFrame { kind: BlockKind::Function, has_else: false, - start_ip: 0, - branch_jumps: Vec::new(), + loop_start: None, + end: None, + else_entry: None, height: 0, base: ValueCounts::default(), - params: Vec::new(), - results: signature.results.clone(), + signature: BlockSignature::Function(signature), unreachable: false, entry_unreachable: false, end_reachable: false, @@ -200,16 +238,16 @@ impl<'a> FunctionBuilder<'a> { instruction: fn(Operand64Idx<(u32, u32)>) -> Instruction, ) -> Result<()> { let size = self.metadata.struct_field(type_index, field_index)?; - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, field_index))?; + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, field_index))?; self.emit(&[ValueLane::S32], &[size], instruction(operand)) } - fn push_operand64(&mut self, operand: Operand64) -> Result> { - self.data.push_operand64(operand) + fn push64(&mut self, operand: Operand64) -> Result> { + self.data.push64(operand) } - fn push_operand128(&mut self, operand: Operand128) -> Result> { - self.data.push_operand128(operand) + fn push128(&mut self, operand: Operand128) -> Result> { + self.data.push128(operand) } } @@ -380,7 +418,7 @@ impl<'a> VisitOperator<'a> for ValidateThenVisit<'_, '_> { #[cfg(not(rust_analyzer))] // rust analyzer gets confused and throws a bunch of errors when this macro is expanded wasmparser::for_each_visit_operator!(validate_then_visit); - fn simd_visitor(&mut self) -> Option<&mut dyn VisitSimdOperator<'a, Output = Self::Output>> { + fn simd_visitor(&mut self) -> Option<&mut dyn VisitSimdOperator<'a, Output = Result<()>>> { Some(self) } } @@ -395,17 +433,17 @@ pub(crate) fn process_operators( body: FunctionBody<'_>, locals: (Vec, Vec), metadata: &ModuleMetadata, - ty_idx: u32, + context: FunctionLoweringContext, allocs: OperatorsReaderAllocations, - deduplicate_operands: bool, + options: &ParserOptions, ) -> Result<(Vec, FunctionDataBuilder, bool, OperatorsReaderAllocations)> { let (local_types, local_addr_map) = locals; let body_size = body.as_bytes().len(); let reader = body.get_binary_reader_for_operators()?; let mut reader = OperatorsReader::new_with_allocs(reader, allocs); - let signature = metadata.signature(ty_idx)?; + let signature = metadata.signature(context.ty_idx)?; let mut builder = - FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, deduplicate_operands); + FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, context, options); while !reader.eof() { let position = reader.original_position(); @@ -420,7 +458,8 @@ pub(crate) fn process_operators( } reader.finish()?; - Ok((builder.instructions, builder.data, builder.uses_local_memory, reader.into_allocations())) + let instructions = builder.emitter.finish(&mut builder.data)?; + Ok((instructions, builder.data, builder.uses_local_memory, reader.into_allocations())) } #[cfg(feature = "validate")] @@ -429,17 +468,17 @@ pub(crate) fn process_operators_and_validate( body: FunctionBody<'_>, locals: (Vec, Vec), metadata: &ModuleMetadata, - ty_idx: u32, + context: FunctionLoweringContext, allocs: OperatorsReaderAllocations, - deduplicate_operands: bool, + options: &ParserOptions, ) -> Result<(Vec, FunctionDataBuilder, bool, FuncValidatorAllocations, OperatorsReaderAllocations)> { let (local_types, local_addr_map) = locals; let body_size = body.as_bytes().len(); let reader = body.get_binary_reader_for_operators()?; let mut reader = OperatorsReader::new_with_allocs(reader, allocs); - let signature = metadata.signature(ty_idx)?; + let signature = metadata.signature(context.ty_idx)?; let mut builder = - FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, deduplicate_operands); + FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, context, options); while !reader.eof() { let position = reader.original_position(); @@ -454,19 +493,14 @@ pub(crate) fn process_operators_and_validate( } reader.finish()?; - Ok(( - builder.instructions, - builder.data, - builder.uses_local_memory, - validator.into_allocations(), - reader.into_allocations(), - )) + let instructions = builder.emitter.finish(&mut builder.data)?; + Ok((instructions, builder.data, builder.uses_local_memory, validator.into_allocations(), reader.into_allocations())) } impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { type Output = Result<()>; - fn simd_visitor(&mut self) -> Option<&mut dyn VisitSimdOperator<'a, Output = Self::Output>> { + fn simd_visitor(&mut self) -> Option<&mut dyn VisitSimdOperator<'a, Output = Result<()>>> { Some(self) } @@ -474,23 +508,27 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { lowering_ops! { memory [Addr] => [S32] { - visit_i32_load => I32Load, visit_f32_load => F32Load, visit_i32_load8_s => I32Load8S, - visit_i32_load8_u => I32Load8U, visit_i32_load16_s => I32Load16S, - visit_i32_load16_u => I32Load16U, + visit_i32_load => I32Load [load(Instruction::LoadLocal32)], + visit_f32_load => F32Load [load(Instruction::LoadLocal32)], + visit_i32_load8_s => I32Load8S [load(Instruction::LoadLocal8S32)], + visit_i32_load8_u => I32Load8U [load(Instruction::LoadLocal8U32)], + visit_i32_load16_s => I32Load16S [load(Instruction::LoadLocal16S32)], + visit_i32_load16_u => I32Load16U [load(Instruction::LoadLocal16U32)], } memory [Addr] => [S64] { - visit_i64_load => I64Load, visit_f64_load => F64Load, visit_i64_load8_s => I64Load8S, + visit_i64_load => I64Load [load(Instruction::LoadLocal64)], + visit_f64_load => F64Load [load(Instruction::LoadLocal64)], visit_i64_load8_s => I64Load8S, visit_i64_load8_u => I64Load8U, visit_i64_load16_s => I64Load16S, visit_i64_load16_u => I64Load16U, visit_i64_load32_s => I64Load32S, visit_i64_load32_u => I64Load32U, } memory [Addr, S32] => [] { - visit_f32_store => F32Store, visit_i32_store8 => I32Store8, - visit_i32_store16 => I32Store16, visit_i32_store => I32Store, + visit_f32_store => F32Store [store32()], visit_i32_store8 => I32Store8, + visit_i32_store16 => I32Store16, visit_i32_store => I32Store [store32()], } memory [Addr, S64] => [] { - visit_f64_store => F64Store, visit_i64_store8 => I64Store8, - visit_i64_store16 => I64Store16, visit_i64_store32 => I64Store32, visit_i64_store => I64Store, + visit_f64_store => F64Store [store64()], visit_i64_store8 => I64Store8, + visit_i64_store16 => I64Store16, visit_i64_store32 => I64Store32, visit_i64_store => I64Store [store64()], } fixed [] => [] { visit_data_drop(segment: u32) => DataDrop, visit_elem_drop(segment: u32) => ElemDrop } fixed [] => [S32] { visit_i32_const(value: i32) => Const32, visit_ref_func(function: u32) => RefFunc } @@ -531,41 +569,83 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { visit_i32_trunc_sat_f64_s => I32TruncSatF64S, visit_i32_trunc_sat_f64_u => I32TruncSatF64U, } fixed [S32] => [S64] { - visit_i64_extend_i32_s => I64ExtendI32S, visit_i64_extend_i32_u => I64ExtendI32U, + visit_i64_extend_i32_s => I64ExtendI32S [extend_i32(true)], + visit_i64_extend_i32_u => I64ExtendI32U [extend_i32(false)], visit_i64_trunc_f32_s => I64TruncF32S, visit_i64_trunc_f32_u => I64TruncF32U, visit_f64_convert_i32_s => F64ConvertI32S, visit_f64_convert_i32_u => F64ConvertI32U, visit_f64_promote_f32 => F64PromoteF32, visit_i64_trunc_sat_f32_s => I64TruncSatF32S, visit_i64_trunc_sat_f32_u => I64TruncSatF32U, } fixed [S32, S32] => [S32] { - visit_ref_eq => RefEq, visit_i32_eq => I32Eq, visit_i32_ne => I32Ne, - visit_i32_lt_s => I32LtS, visit_i32_lt_u => I32LtU, - visit_i32_gt_s => I32GtS, visit_i32_gt_u => I32GtU, visit_i32_le_s => I32LeS, - visit_i32_le_u => I32LeU, visit_i32_ge_s => I32GeS, visit_i32_ge_u => I32GeU, + visit_ref_eq => RefEq, + visit_i32_eq => I32Eq [compare(CmpOp::Eq)], + visit_i32_ne => I32Ne [compare(CmpOp::Ne)], + visit_i32_lt_s => I32LtS [compare(CmpOp::LtS)], + visit_i32_lt_u => I32LtU [compare(CmpOp::LtU)], + visit_i32_gt_s => I32GtS [compare(CmpOp::GtS)], + visit_i32_gt_u => I32GtU [compare(CmpOp::GtU)], + visit_i32_le_s => I32LeS [compare(CmpOp::LeS)], + visit_i32_le_u => I32LeU [compare(CmpOp::LeU)], + visit_i32_ge_s => I32GeS [compare(CmpOp::GeS)], + visit_i32_ge_u => I32GeU [compare(CmpOp::GeU)], visit_f32_eq => F32Eq, visit_f32_ne => F32Ne, visit_f32_lt => F32Lt, visit_f32_gt => F32Gt, - visit_f32_le => F32Le, visit_f32_ge => F32Ge, visit_i32_add => I32Add, visit_i32_sub => I32Sub, - visit_i32_mul => I32Mul, visit_i32_div_s => I32DivS, visit_i32_div_u => I32DivU, - visit_i32_rem_s => I32RemS, visit_i32_rem_u => I32RemU, visit_i32_and => I32And, - visit_i32_or => I32Or, visit_i32_xor => I32Xor, visit_i32_shl => I32Shl, visit_i32_shr_s => I32ShrS, - visit_i32_shr_u => I32ShrU, visit_i32_rotl => I32Rotl, visit_i32_rotr => I32Rotr, - visit_f32_add => F32Add, visit_f32_sub => F32Sub, visit_f32_mul => F32Mul, visit_f32_div => F32Div, - visit_f32_min => F32Min, visit_f32_max => F32Max, visit_f32_copysign => F32Copysign, + visit_f32_le => F32Le, visit_f32_ge => F32Ge, + visit_i32_add => I32Add [integer32(BinOp::IAdd, true)], + visit_i32_sub => I32Sub [integer32(BinOp::ISub, false)], + visit_i32_mul => I32Mul [integer32(BinOp::IMul, true)], + visit_i32_div_s => I32DivS, visit_i32_div_u => I32DivU, + visit_i32_rem_s => I32RemS, visit_i32_rem_u => I32RemU, + visit_i32_and => I32And [integer32(BinOp::IAnd, true)], + visit_i32_or => I32Or [integer32(BinOp::IOr, true)], + visit_i32_xor => I32Xor [integer32(BinOp::IXor, true)], + visit_i32_shl => I32Shl [integer32(BinOp::IShl, false)], + visit_i32_shr_s => I32ShrS [integer32(BinOp::IShrS, false)], + visit_i32_shr_u => I32ShrU [integer32(BinOp::IShrU, false)], + visit_i32_rotl => I32Rotl [integer32(BinOp::IRotl, false)], + visit_i32_rotr => I32Rotr [integer32(BinOp::IRotr, false)], + visit_f32_add => F32Add [float32(BinOp::FAdd, true)], + visit_f32_sub => F32Sub [float32(BinOp::FSub, false)], + visit_f32_mul => F32Mul [float32(BinOp::FMul, true)], + visit_f32_div => F32Div [float32(BinOp::FDiv, false)], + visit_f32_min => F32Min [float32(BinOp::FMin, true)], + visit_f32_max => F32Max [float32(BinOp::FMax, true)], + visit_f32_copysign => F32Copysign [float32(BinOp::FCopysign, false)], } fixed [S64, S64] => [S32] { - visit_i64_eq => I64Eq, visit_i64_ne => I64Ne, visit_i64_lt_s => I64LtS, visit_i64_lt_u => I64LtU, - visit_i64_gt_s => I64GtS, visit_i64_gt_u => I64GtU, visit_i64_le_s => I64LeS, - visit_i64_le_u => I64LeU, visit_i64_ge_s => I64GeS, visit_i64_ge_u => I64GeU, + visit_i64_eq => I64Eq [compare(CmpOp::Eq)], + visit_i64_ne => I64Ne [compare(CmpOp::Ne)], + visit_i64_lt_s => I64LtS [compare(CmpOp::LtS)], + visit_i64_lt_u => I64LtU [compare(CmpOp::LtU)], + visit_i64_gt_s => I64GtS [compare(CmpOp::GtS)], + visit_i64_gt_u => I64GtU [compare(CmpOp::GtU)], + visit_i64_le_s => I64LeS [compare(CmpOp::LeS)], + visit_i64_le_u => I64LeU [compare(CmpOp::LeU)], + visit_i64_ge_s => I64GeS [compare(CmpOp::GeS)], + visit_i64_ge_u => I64GeU [compare(CmpOp::GeU)], visit_f64_eq => F64Eq, visit_f64_ne => F64Ne, visit_f64_lt => F64Lt, visit_f64_gt => F64Gt, visit_f64_le => F64Le, visit_f64_ge => F64Ge, } fixed [S64, S64] => [S64] { - visit_i64_add => I64Add, visit_i64_sub => I64Sub, visit_i64_mul => I64Mul, + visit_i64_add => I64Add [integer64(BinOp::IAdd, true)], + visit_i64_sub => I64Sub [integer64(BinOp::ISub, false)], + visit_i64_mul => I64Mul [integer64(BinOp::IMul, true)], visit_i64_div_s => I64DivS, visit_i64_div_u => I64DivU, visit_i64_rem_s => I64RemS, - visit_i64_rem_u => I64RemU, visit_i64_and => I64And, visit_i64_or => I64Or, visit_i64_xor => I64Xor, - visit_i64_shl => I64Shl, visit_i64_shr_s => I64ShrS, visit_i64_shr_u => I64ShrU, - visit_i64_rotl => I64Rotl, visit_i64_rotr => I64Rotr, visit_f64_add => F64Add, - visit_f64_sub => F64Sub, visit_f64_mul => F64Mul, visit_f64_div => F64Div, - visit_f64_min => F64Min, visit_f64_max => F64Max, visit_f64_copysign => F64Copysign, + visit_i64_rem_u => I64RemU, + visit_i64_and => I64And [integer64(BinOp::IAnd, true)], + visit_i64_or => I64Or [integer64(BinOp::IOr, true)], + visit_i64_xor => I64Xor [integer64(BinOp::IXor, true)], + visit_i64_shl => I64Shl [integer64(BinOp::IShl, false)], + visit_i64_shr_s => I64ShrS [integer64(BinOp::IShrS, false)], + visit_i64_shr_u => I64ShrU [integer64(BinOp::IShrU, false)], + visit_i64_rotl => I64Rotl [integer64(BinOp::IRotl, false)], + visit_i64_rotr => I64Rotr [integer64(BinOp::IRotr, false)], + visit_f64_add => F64Add [float64(BinOp::FAdd, true)], + visit_f64_sub => F64Sub [float64(BinOp::FSub, false)], + visit_f64_mul => F64Mul [float64(BinOp::FMul, true)], + visit_f64_div => F64Div [float64(BinOp::FDiv, false)], + visit_f64_min => F64Min [float64(BinOp::FMin, true)], + visit_f64_max => F64Max [float64(BinOp::FMax, true)], + visit_f64_copysign => F64Copysign [float64(BinOp::FCopysign, false)], } fixed [S64, S64, S64, S64] => [S64, S64] { visit_i64_add128 => I64Add128, visit_i64_sub128 => I64Sub128 } fixed [S64, S64] => [S64, S64] { visit_i64_mul_wide_s => I64MulWideS, visit_i64_mul_wide_u => I64MulWideU } @@ -575,7 +655,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { terminating [] => [] { visit_unreachable => Unreachable, visit_return => Return } memory_index [] => [Addr] { visit_memory_size(memory: u32) => MemorySize } memory_index [Addr] => [Addr] { visit_memory_grow(memory: u32) => MemoryGrow } - memory_index [Addr, S32, Addr] => [] { visit_memory_fill(memory: u32) => MemoryFill } + memory_index [Addr, S32, Addr] => [] { visit_memory_fill(memory: u32) => MemoryFill [memory_fill()] } table [Addr] => [S32] { visit_table_get(table: u32) => TableGet } table [Addr, S32] => [] { visit_table_set(table: u32) => TableSet } table [] => [Addr] { visit_table_size(table: u32) => TableSize } @@ -594,94 +674,94 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { array_field [S32, S32, Field, S32] => [] { visit_array_fill(type_index: u32) => ArrayFill } } - fn visit_struct_new(&mut self, type_index: u32) -> Self::Output { + fn visit_struct_new(&mut self, type_index: u32) -> Result<()> { let field_count = self.metadata.struct_fields(type_index)?.len(); for field_index in (0..field_count).rev() { let size = self.metadata.struct_field(type_index, field_index as u32)?; self.pop_expect(size)?; } self.push_sizes(&[ValueLane::S32])?; - self.instructions.push(Instruction::StructNew(type_index)); + self.emitter.emit(Instruction::StructNew(type_index))?; Ok(()) } - fn visit_struct_get(&mut self, type_index: u32, field_index: u32) -> Self::Output { + fn visit_struct_get(&mut self, type_index: u32, field_index: u32) -> Result<()> { self.visit_struct_get_impl(type_index, field_index, Instruction::StructGet) } - fn visit_struct_get_s(&mut self, type_index: u32, field_index: u32) -> Self::Output { + fn visit_struct_get_s(&mut self, type_index: u32, field_index: u32) -> Result<()> { self.visit_struct_get_impl(type_index, field_index, Instruction::StructGetS) } - fn visit_struct_get_u(&mut self, type_index: u32, field_index: u32) -> Self::Output { + fn visit_struct_get_u(&mut self, type_index: u32, field_index: u32) -> Result<()> { self.visit_struct_get_impl(type_index, field_index, Instruction::StructGetU) } - fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Self::Output { + fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Result<()> { let size = self.metadata.struct_field(type_index, field_index)?; - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, field_index))?; + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, field_index))?; self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(operand)) } - fn visit_array_new_fixed(&mut self, type_index: u32, array_size: u32) -> Self::Output { + fn visit_array_new_fixed(&mut self, type_index: u32, array_size: u32) -> Result<()> { let size = self.metadata.array_field(type_index)?; for _ in 0..array_size { self.pop_expect(size)?; } self.push_sizes(&[ValueLane::S32])?; - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, array_size))?; - self.instructions.push(Instruction::ArrayNewFixed(operand)); + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, array_size))?; + self.emitter.emit(Instruction::ArrayNewFixed(operand))?; Ok(()) } - fn visit_call(&mut self, function_index: u32) -> Self::Output { + fn visit_call(&mut self, function_index: u32) -> Result<()> { let signature = self.metadata.function_signature(function_index)?; - self.emit(&signature.params, &signature.results, Instruction::Call(function_index)) + self.emit_boundary(&signature.params, &signature.results, Instruction::Call(function_index)) } - fn visit_call_indirect(&mut self, type_index: u32, table_index: u32) -> Self::Output { + fn visit_call_indirect(&mut self, type_index: u32, table_index: u32) -> Result<()> { let table_size = self.metadata.table_size(table_index)?; - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, table_index))?; + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, table_index))?; let signature = self.metadata.signature(type_index)?; self.pop_expect(table_size)?; - self.emit(&signature.params, &signature.results, Instruction::CallIndirect(operand)) + self.emit_boundary(&signature.params, &signature.results, Instruction::CallIndirect(operand)) } - fn visit_call_ref(&mut self, type_index: u32) -> Self::Output { + fn visit_call_ref(&mut self, type_index: u32) -> Result<()> { let signature = self.metadata.signature(type_index)?; self.pop_expect(ValueLane::S32)?; - self.emit(&signature.params, &signature.results, Instruction::CallRef(type_index)) + self.emit_boundary(&signature.params, &signature.results, Instruction::CallRef(type_index)) } - fn visit_return_call(&mut self, function_index: u32) -> Self::Output { + fn visit_return_call(&mut self, function_index: u32) -> Result<()> { let signature = self.metadata.function_signature(function_index)?; self.apply_effect(&signature.params, &[])?; self.mark_unreachable(); - self.instructions.push(Instruction::ReturnCall(function_index)); + self.emitter.emit_boundary(Instruction::ReturnCall(function_index))?; Ok(()) } - fn visit_return_call_indirect(&mut self, type_index: u32, table_index: u32) -> Self::Output { + fn visit_return_call_indirect(&mut self, type_index: u32, table_index: u32) -> Result<()> { let table_size = self.metadata.table_size(table_index)?; let signature = self.metadata.signature(type_index)?; self.pop_expect(table_size)?; self.apply_effect(&signature.params, &[])?; self.mark_unreachable(); - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, table_index))?; - self.instructions.push(Instruction::ReturnCallIndirect(operand)); + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, table_index))?; + self.emitter.emit_boundary(Instruction::ReturnCallIndirect(operand))?; Ok(()) } - fn visit_return_call_ref(&mut self, type_index: u32) -> Self::Output { + fn visit_return_call_ref(&mut self, type_index: u32) -> Result<()> { let signature = self.metadata.signature(type_index)?; self.pop_expect(ValueLane::S32)?; self.apply_effect(&signature.params, &[])?; self.mark_unreachable(); - self.instructions.push(Instruction::ReturnCallRef(type_index)); + self.emitter.emit_boundary(Instruction::ReturnCallRef(type_index))?; Ok(()) } - fn visit_global_set(&mut self, global_index: u32) -> Self::Output { + fn visit_global_set(&mut self, global_index: u32) -> Result<()> { let size = self.metadata.global_size(global_index)?; let instruction = size.select( Instruction::GlobalSet32(global_index), @@ -691,87 +771,86 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { self.emit(&[size], &[], instruction) } - fn visit_global_get(&mut self, global_index: u32) -> Self::Output { + fn visit_global_get(&mut self, global_index: u32) -> Result<()> { let size = self.metadata.global_size(global_index)?; - let instruction = size.select( - Instruction::GlobalGet32(global_index), - Instruction::GlobalGet64(global_index), - Instruction::GlobalGet128(global_index), - ); - self.emit(&[], &[size], instruction) + match size { + ValueLane::S32 => emit_selected!(self, &[], &[size], GlobalGet32(global_index)[global_get32()]), + ValueLane::S64 => emit_selected!(self, &[], &[size], GlobalGet64(global_index)[global_get64()]), + ValueLane::S128 => emit_selected!(self, &[], &[size], GlobalGet128(global_index)[global_get128()]), + } } - fn visit_drop(&mut self) -> Self::Output { + fn visit_drop(&mut self) -> Result<()> { let size = self.operand_stack.last().copied().unwrap_or(ValueLane::S32); - let instruction = size.select(Instruction::Drop32, Instruction::Drop64, Instruction::Drop128); - self.emit(&[size], &[], instruction) + match size { + ValueLane::S32 => emit_selected!(self, &[size], &[], Drop32[drop32()]), + ValueLane::S64 => emit_selected!(self, &[size], &[], Drop64[drop64()]), + ValueLane::S128 => emit_selected!(self, &[size], &[], Drop128[drop128()]), + } } - fn visit_select(&mut self) -> Self::Output { + fn visit_select(&mut self) -> Result<()> { let size = self.operand_stack.iter().rev().nth(1).copied().unwrap_or(ValueLane::S32); let instruction = size.select(Instruction::Select32, Instruction::Select64, Instruction::Select128); self.emit(&[size, size, ValueLane::S32], &[size], instruction) } - fn visit_local_get(&mut self, idx: u32) -> Self::Output { + fn visit_local_get(&mut self, idx: u32) -> Result<()> { let (size, local_idx) = self.local(idx)?; - let instruction = size.select( - Instruction::LocalGet32(local_idx), - Instruction::LocalGet64(local_idx), - Instruction::LocalGet128(local_idx), - ); - self.emit(&[], &[size], instruction) + match size { + ValueLane::S32 => emit_selected!(self, &[], &[size], LocalGet32(local_idx)[local_get32()]), + ValueLane::S64 => emit_selected!(self, &[], &[size], LocalGet64(local_idx)[local_get64()]), + ValueLane::S128 => emit_selected!(self, &[], &[size], LocalGet128(local_idx)[local_get128()]), + } } - fn visit_local_set(&mut self, idx: u32) -> Self::Output { + fn visit_local_set(&mut self, idx: u32) -> Result<()> { let (size, local_idx) = self.local(idx)?; - let instruction = size.select( - Instruction::LocalSet32(local_idx), - Instruction::LocalSet64(local_idx), - Instruction::LocalSet128(local_idx), - ); - self.emit(&[size], &[], instruction) + match size { + ValueLane::S32 => emit_selected!(self, &[size], &[], LocalSet32(local_idx)[local_set32()]), + ValueLane::S64 => emit_selected!(self, &[size], &[], LocalSet64(local_idx)[local_set64()]), + ValueLane::S128 => emit_selected!(self, &[size], &[], LocalSet128(local_idx)[local_set128()]), + } } - fn visit_local_tee(&mut self, idx: u32) -> Self::Output { + fn visit_local_tee(&mut self, idx: u32) -> Result<()> { let (size, local_idx) = self.local(idx)?; - // No peephole here: this position may be a branch target (block end, - // loop start, if/else join), and fusing with the preceding `local.get` - // would move the label past the tee. The rewriter fuses the same pair - // within a basic block, where no branch can land between them. - let instruction = size.select( - Instruction::LocalTee32(local_idx), - Instruction::LocalTee64(local_idx), - Instruction::LocalTee128(local_idx), - ); - self.emit(&[size], &[size], instruction) + // Bound labels seal the tail, so these rules cannot fuse across a loop + // entry or another branch destination. + match size { + ValueLane::S32 => emit_selected!(self, &[size], &[size], LocalTee32(local_idx)[local_tee32()]), + ValueLane::S64 => emit_selected!(self, &[size], &[size], LocalTee64(local_idx)[local_tee64()]), + ValueLane::S128 => emit_selected!(self, &[size], &[size], LocalTee128(local_idx)[local_tee128()]), + } } - fn visit_block(&mut self, blockty: wasmparser::BlockType) -> Self::Output { + fn visit_block(&mut self, blockty: wasmparser::BlockType) -> Result<()> { self.push_control(BlockKind::Block, blockty, None) } - fn visit_loop(&mut self, ty: wasmparser::BlockType) -> Self::Output { + fn visit_loop(&mut self, ty: wasmparser::BlockType) -> Result<()> { self.push_control(BlockKind::Loop, ty, None) } - fn visit_if(&mut self, ty: wasmparser::BlockType) -> Self::Output { + fn visit_if(&mut self, ty: wasmparser::BlockType) -> Result<()> { self.pop_expect(ValueLane::S32)?; - self.instructions.push(Instruction::JumpIfZero32(0)); - self.push_control(BlockKind::If, ty, Some(self.instructions.len() - 1)) + let else_entry = self.emitter.new_label(); + self.emitter.branch_if(&mut self.data, true, else_entry)?; + self.push_control(BlockKind::If, ty, Some(else_entry)) } - fn visit_try_table(&mut self, try_table: wasmparser::TryTable) -> Self::Output { + fn visit_try_table(&mut self, try_table: wasmparser::TryTable) -> Result<()> { let signature = self.block_signature(try_table.ty)?; - for &size in signature.params.iter().rev() { + for &size in signature.params().iter().rev() { self.pop_expect(size)?; } let height = self.operand_stack.len(); let base = self.lane_counts; let entry_unreachable = self.is_unreachable(); - let body_jump = self.instructions.len(); - self.instructions.push(Instruction::Jump(0)); + let body_start = self.emitter.new_label(); + let body_end = self.emitter.new_label(); + self.emitter.branch(Instruction::Jump(0), body_start)?; let mut catches = Vec::with_capacity(try_table.catches.len()); for catch in try_table.catches { let (tag, depth, with_ref) = match catch { @@ -785,43 +864,31 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } let target_idx = self.get_ctx_idx(depth)?; let target_base = self.control_stack[target_idx].base; - let landing_pad = u32::try_from(self.instructions.len()) - .map_err(|_| crate::ParseError::Other("function body is too large".into()))?; - match self.control_stack[target_idx].kind { - BlockKind::Function => self.instructions.push(Instruction::Return), - BlockKind::Loop => { - self.instructions.push(Instruction::Jump(self.control_stack[target_idx].start_ip as u32)); - } - BlockKind::Block | BlockKind::If | BlockKind::TryTable(_) => { - self.control_stack[target_idx].branch_jumps.push(self.instructions.len()); - self.control_stack[target_idx].end_reachable = true; - self.instructions.push(Instruction::Jump(0)); - } - } - catches.push(match tag { - Some(tag) => tinywasm_types::ExceptionCatch::Tag { tag, landing_pad, base: target_base, with_ref }, - None => tinywasm_types::ExceptionCatch::All { landing_pad, base: target_base, with_ref }, - }); - } - - let body_start = self.instructions.len(); - self.patch_jump(body_jump, body_start); - let handler_idx = self.data.exception_handlers.len(); - self.data.exception_handlers.push(tinywasm_types::ExceptionHandler { - start_ip: body_start as u32, - end_ip: 0, - catches: catches.into_boxed_slice(), - }); - self.push_sizes(&signature.params)?; + let landing_label = self.emitter.new_label(); + self.emitter.bind(landing_label)?; + self.emit_branch_jump_or_return(depth)?; + let landing_pad = 0; + catches.push(( + match tag { + Some(tag) => tinywasm_types::ExceptionCatch::Tag { tag, landing_pad, base: target_base, with_ref }, + None => tinywasm_types::ExceptionCatch::All { landing_pad, base: target_base, with_ref }, + }, + landing_label, + )); + } + + self.emitter.bind(body_start)?; + self.emitter.exception_handler(&mut self.data, body_start, body_end, catches); + self.push_sizes(signature.params())?; self.control_stack.push(ControlFrame { - kind: BlockKind::TryTable(handler_idx), + kind: BlockKind::TryTable, has_else: false, - start_ip: body_start, - branch_jumps: Vec::new(), + loop_start: None, + end: Some(body_end), + else_entry: None, height, base, - params: signature.params, - results: signature.results, + signature, unreachable: entry_unreachable, entry_unreachable, end_reachable: false, @@ -829,238 +896,229 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { Ok(()) } - fn visit_throw(&mut self, tag_index: u32) -> Self::Output { + fn visit_throw(&mut self, tag_index: u32) -> Result<()> { let signature = self.metadata.tag_signature(tag_index)?; self.apply_effect(&signature.params, &[])?; - self.instructions.push(Instruction::Throw(tag_index)); + self.emitter.emit_boundary(Instruction::Throw(tag_index))?; self.mark_unreachable(); Ok(()) } - fn visit_throw_ref(&mut self) -> Self::Output { + fn visit_throw_ref(&mut self) -> Result<()> { self.apply_effect(&[ValueLane::S32], &[])?; - self.instructions.push(Instruction::ThrowRef); + self.emitter.emit_boundary(Instruction::ThrowRef)?; self.mark_unreachable(); Ok(()) } - fn visit_else(&mut self) -> Self::Output { - let (cond_jump_ip, height, base, params, entry_unreachable) = { + fn visit_else(&mut self) -> Result<()> { + let (else_entry, end, height, base, signature, entry_unreachable) = { let ctx = self .control_stack .last_mut() - .filter(|ctx| matches!(ctx.kind, BlockKind::If)) + .filter(|ctx| matches!(ctx.kind, BlockKind::If) && !ctx.has_else) .ok_or_else(|| crate::ParseError::Other("else without matching if".into()))?; ctx.end_reachable |= !ctx.unreachable; ctx.has_else = true; - (ctx.branch_jumps[0], ctx.height, ctx.base, ctx.params.clone(), ctx.entry_unreachable) + let end = *ctx.end.get_or_insert_with(|| self.emitter.new_label()); + (ctx.else_entry.unwrap(), end, ctx.height, ctx.base, ctx.signature, ctx.entry_unreachable) }; - let jump_ip = self.instructions.len(); - self.instructions.push(Instruction::Jump(0)); - self.control_stack.last_mut().unwrap().branch_jumps.push(jump_ip); - self.patch_jump(cond_jump_ip, self.instructions.len()); + self.emitter.branch(Instruction::Jump(0), end)?; + self.emitter.bind(else_entry)?; self.reset_stack(height, base); - self.push_sizes(¶ms)?; + self.push_sizes(signature.params())?; self.control_stack.last_mut().unwrap().unreachable = entry_unreachable; Ok(()) } - fn visit_end(&mut self) -> Self::Output { + fn visit_end(&mut self) -> Result<()> { let ctx = self.control_stack.pop().ok_or_else(|| crate::ParseError::Other("end without control frame".into()))?; - if let BlockKind::TryTable(handler_idx) = ctx.kind { - self.data.exception_handlers[handler_idx].end_ip = self.instructions.len() as u32; + if let Some(end) = ctx.end { + self.emitter.bind(end)?; + } + if !ctx.has_else + && let Some(else_entry) = ctx.else_entry + { + self.emitter.bind(else_entry)?; } if matches!(ctx.kind, BlockKind::Function) { - self.instructions.push(Instruction::Return); + self.emitter.emit_boundary(Instruction::Return)?; } else { let reachable = !ctx.entry_unreachable && (!ctx.unreachable || ctx.end_reachable || matches!(ctx.kind, BlockKind::If) && !ctx.has_else); self.reset_stack(ctx.height, ctx.base); - self.push_sizes(&ctx.results)?; + self.push_sizes(ctx.signature.results())?; if let Some(parent) = self.control_stack.last_mut() { parent.unreachable = !reachable; } - self.patch_end_jumps(ctx, self.instructions.len()); } Ok(()) } - fn visit_br(&mut self, depth: u32) -> Self::Output { + fn visit_br(&mut self, depth: u32) -> Result<()> { self.emit_dropkeep_to_label(depth)?; self.emit_branch_jump_or_return(depth)?; self.mark_unreachable(); Ok(()) } - fn visit_br_if(&mut self, depth: u32) -> Self::Output { + fn visit_br_if(&mut self, depth: u32) -> Result<()> { self.pop_expect(ValueLane::S32)?; - let cond_jump_ip = self.instructions.len(); - self.instructions.push(Instruction::JumpIfZero32(0)); - - let branch_side_start = self.instructions.len(); - self.emit_dropkeep_to_label(depth)?; - - if self.instructions.len() == branch_side_start - && let Ok(ctx_idx) = self.get_ctx_idx(depth) - && !matches!(self.control_stack[ctx_idx].kind, BlockKind::Function) - { - self.instructions[cond_jump_ip] = Instruction::JumpIfNonZero32(0); - self.control_stack[ctx_idx].branch_jumps.push(cond_jump_ip); + let ctx_idx = self.get_ctx_idx(depth)?; + let frame = &self.control_stack[ctx_idx]; + let types = + if matches!(frame.kind, BlockKind::Loop) { frame.signature.params() } else { frame.signature.results() }; + let keep = Self::value_counts(types); + let needs_shaping = !self.is_unreachable() && self.needs_dropkeep(frame.base, keep); + if !needs_shaping && !matches!(frame.kind, BlockKind::Function) { + let target = if let Some(start) = frame.loop_start { + start + } else { + *self.control_stack[ctx_idx].end.get_or_insert_with(|| self.emitter.new_label()) + }; + self.emitter.branch_if(&mut self.data, false, target)?; self.control_stack[ctx_idx].end_reachable = true; return Ok(()); } - + let fallthrough = self.emitter.new_label(); + self.emitter.branch_if(&mut self.data, true, fallthrough)?; + self.emit_dropkeep_to_label(depth)?; self.emit_branch_jump_or_return(depth)?; - self.patch_jump(cond_jump_ip, self.instructions.len()); + self.emitter.bind(fallthrough)?; Ok(()) } - fn visit_br_table(&mut self, targets: wasmparser::BrTable<'_>) -> Self::Output { + fn visit_br_table(&mut self, targets: wasmparser::BrTable<'_>) -> Result<()> { let ts = targets.targets().collect::, wasmparser::Error>>()?; self.pop_expect(ValueLane::S32)?; let default_depth = targets.default(); - let len = ts.len() as u32; let target_depths: Vec = ts; - - let header_ip = self.instructions.len(); - let branch_table_start = self.data.branch_table_targets.len() as u32; - let branch_operand = - self.data.push_target_operand128(Operand128::::new(0, branch_table_start, len))?; - self.instructions.push(Instruction::BranchTable(branch_operand)); - - struct PadInfo { - depth: u32, - pad_start: usize, - jump_or_ret_ip: usize, - is_return: bool, - } - let mut pads: Vec = Vec::new(); - + let mut pads: Vec<(u32, LabelId)> = Vec::new(); + let label_count = target_depths + .len() + .checked_add(1) + .ok_or_else(|| crate::ParseError::Other("branch table is too large".into()))?; + let mut labels = Vec::with_capacity(label_count); for &depth in target_depths.iter().chain(core::iter::once(&default_depth)) { - if pads.iter().any(|pad| pad.depth == depth) { - continue; + if self.emitter.optimizations_enabled() && !self.is_unreachable() { + let ctx_idx = self.get_ctx_idx(depth)?; + let frame = &self.control_stack[ctx_idx]; + let is_loop = matches!(frame.kind, BlockKind::Loop); + let types = if is_loop { frame.signature.params() } else { frame.signature.results() }; + if !matches!(frame.kind, BlockKind::Function) + && !self.needs_dropkeep(frame.base, Self::value_counts(types)) + { + let target = if let Some(start) = frame.loop_start { + start + } else { + *self.control_stack[ctx_idx].end.get_or_insert_with(|| self.emitter.new_label()) + }; + labels.push(target); + if !is_loop { + self.control_stack[ctx_idx].end_reachable = true; + } + continue; + } } - - let pad_start = self.instructions.len(); - let (jump_or_ret_ip, is_return) = if self.is_unreachable() { - self.instructions.push(Instruction::Return); - (pad_start, true) + let label = if let Some((_, label)) = pads.iter().find(|(pad_depth, _)| *pad_depth == depth) { + *label } else { - let frame = &self.control_stack[self.get_ctx_idx(depth)?]; - let base = frame.base; - let label_types = if matches!(frame.kind, BlockKind::Loop) { &frame.params } else { &frame.results }; - self.emit_dropkeep(base, Self::value_counts(label_types)); - let jump_ip = self.instructions.len(); - self.instructions.push(Instruction::Jump(0)); - (jump_ip, false) + let label = self.emitter.new_label(); + pads.push((depth, label)); + label }; - pads.push(PadInfo { depth, pad_start, jump_or_ret_ip, is_return }); - } - - for &depth in &target_depths { - let pad = pads - .iter() - .find(|pad| pad.depth == depth) - .ok_or_else(|| crate::ParseError::Other("missing branch table target".into()))?; - self.data.branch_table_targets.push(pad.pad_start as u32); - } - - let default_pad = pads - .iter() - .find(|pad| pad.depth == default_depth) - .ok_or_else(|| crate::ParseError::Other("missing default branch table target".into()))?; - if let Instruction::BranchTable(index) = self.instructions[header_ip] { - let operand = self.data.operand128(index); - self.data.set_operand128(index, operand.with_target(default_pad.pad_start as u32)); - } - - for pad in &pads { - if pad.is_return { - continue; - } - let ctx_idx = self.get_ctx_idx(pad.depth)?; - if matches!(self.control_stack[ctx_idx].kind, BlockKind::Function) { - self.instructions[pad.jump_or_ret_ip] = Instruction::Return; - } else if matches!(self.control_stack[ctx_idx].kind, BlockKind::Loop) { - self.patch_jump(pad.jump_or_ret_ip, self.control_stack[ctx_idx].start_ip); + labels.push(label); + } + let default = labels.pop().unwrap(); + self.emitter.branch_table(&mut self.data, &labels, default)?; + for (depth, label) in pads { + self.emitter.bind(label)?; + if self.is_unreachable() { + self.emitter.emit_boundary(Instruction::Return)?; } else { - self.control_stack[ctx_idx].branch_jumps.push(pad.jump_or_ret_ip); - self.control_stack[ctx_idx].end_reachable = true; + self.emit_dropkeep_to_label(depth)?; + self.emit_branch_jump_or_return(depth)?; } } self.mark_unreachable(); Ok(()) } - fn visit_f32_const(&mut self, val: wasmparser::Ieee32) -> Self::Output { + fn visit_f32_const(&mut self, val: wasmparser::Ieee32) -> Result<()> { self.emit(&[], &[ValueLane::S32], Instruction::Const32(val.bits() as i32)) } - fn visit_f64_const(&mut self, val: wasmparser::Ieee64) -> Self::Output { - let operand = self.push_operand64(Operand64::::new(val.bits() as i64))?; - self.emit(&[], &[ValueLane::S64], Instruction::Const64(operand)) + #[cfg(not(rust_analyzer))] // rust-analyzer thinks the return type is wrong + fn visit_f64_const(&mut self, val: wasmparser::Ieee64) -> Result<()> { + self.visit_i64_const(val.bits() as i64) } - fn visit_i64_const(&mut self, value: i64) -> Self::Output { - let operand = self.push_operand64(Operand64::::new(value))?; - self.emit(&[], &[ValueLane::S64], Instruction::Const64(operand)) + fn visit_i64_const(&mut self, value: i64) -> Result<()> { + let instruction = if self.emitter.optimizations_enabled() + && let Ok(value) = i32::try_from(value) + { + Instruction::Const64Imm(value) + } else { + Instruction::Const64(self.push64(Operand64::::new(value))?) + }; + self.emit(&[], &[ValueLane::S64], instruction) } - fn visit_table_copy(&mut self, dst_table: u32, src_table: u32) -> Self::Output { + fn visit_table_copy(&mut self, dst_table: u32, src_table: u32) -> Result<()> { let dst = self.metadata.table_size(dst_table)?; let src = self.metadata.table_size(src_table)?; let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(dst_table, src_table))?; + let operand = self.push64(Operand64::<(u32, u32)>::new(dst_table, src_table))?; self.emit(&[dst, src, len], &[], Instruction::TableCopy(operand)) } - fn visit_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Self::Output { + fn visit_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Result<()> { let dst = self.metadata.memory_size(dst_mem)?; let src = self.metadata.memory_size(src_mem)?; self.mark_memory(dst_mem); self.mark_memory(src_mem); let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(dst_mem, src_mem))?; + let operand = self.push64(Operand64::<(u32, u32)>::new(dst_mem, src_mem))?; self.emit(&[dst, src, len], &[], Instruction::MemoryCopy(operand)) } - fn visit_memory_init(&mut self, data_index: u32, memory: u32) -> Self::Output { + fn visit_memory_init(&mut self, data_index: u32, memory: u32) -> Result<()> { let dst = self.metadata.memory_size(memory)?; self.mark_memory(memory); - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(data_index, memory))?; + let operand = self.push64(Operand64::<(u32, u32)>::new(data_index, memory))?; self.emit(&[dst, ValueLane::S32, ValueLane::S32], &[], Instruction::MemoryInit(operand)) } - fn visit_table_init(&mut self, elem_index: u32, table: u32) -> Self::Output { + fn visit_table_init(&mut self, elem_index: u32, table: u32) -> Result<()> { let address = self.metadata.table_size(table)?; - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(elem_index, table))?; + let operand = self.push64(Operand64::<(u32, u32)>::new(elem_index, table))?; self.emit(&[address, ValueLane::S32, ValueLane::S32], &[], Instruction::TableInit(operand)) } - fn visit_array_new_data(&mut self, type_index: u32, data_index: u32) -> Self::Output { - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, data_index))?; + fn visit_array_new_data(&mut self, type_index: u32, data_index: u32) -> Result<()> { + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, data_index))?; self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewData(operand)) } - fn visit_array_new_elem(&mut self, type_index: u32, elem_index: u32) -> Self::Output { - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, elem_index))?; + fn visit_array_new_elem(&mut self, type_index: u32, elem_index: u32) -> Result<()> { + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, elem_index))?; self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewElem(operand)) } - fn visit_array_init_data(&mut self, type_index: u32, data_index: u32) -> Self::Output { - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, data_index))?; + fn visit_array_init_data(&mut self, type_index: u32, data_index: u32) -> Result<()> { + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, data_index))?; self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitData(operand)) } - fn visit_array_init_elem(&mut self, type_index: u32, elem_index: u32) -> Self::Output { - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, elem_index))?; + fn visit_array_init_elem(&mut self, type_index: u32, elem_index: u32) -> Result<()> { + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, elem_index))?; self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitElem(operand)) } - fn visit_array_copy(&mut self, type_index_dst: u32, type_index_src: u32) -> Self::Output { - let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index_dst, type_index_src))?; + fn visit_array_copy(&mut self, type_index_dst: u32, type_index_src: u32) -> Result<()> { + let operand = self.push64(Operand64::<(u32, u32)>::new(type_index_dst, type_index_src))?; self.emit(&[ValueLane::S32; 5], &[], Instruction::ArrayCopy(operand)) } @@ -1069,7 +1127,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { relative_depth: u32, _from_ref_type: wasmparser::RefType, to_ref_type: wasmparser::RefType, - ) -> Self::Output { + ) -> Result<()> { self.emit_cast_branch(relative_depth, to_ref_type, false) } @@ -1078,33 +1136,33 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { relative_depth: u32, _from_ref_type: wasmparser::RefType, to_ref_type: wasmparser::RefType, - ) -> Self::Output { + ) -> Result<()> { self.emit_cast_branch(relative_depth, to_ref_type, true) } - fn visit_br_on_null(&mut self, relative_depth: u32) -> Self::Output { + fn visit_br_on_null(&mut self, relative_depth: u32) -> Result<()> { self.pop_expect(ValueLane::S32)?; - let fallthrough_jump = self.instructions.len(); - self.instructions.push(Instruction::JumpIfRefNonNull(0)); + let fallthrough = self.emitter.new_label(); + self.emitter.branch(Instruction::JumpIfRefNonNull(0), fallthrough)?; self.emit_dropkeep_to_label(relative_depth)?; self.emit_branch_jump_or_return(relative_depth)?; - self.patch_jump(fallthrough_jump, self.instructions.len()); + self.emitter.bind(fallthrough)?; self.push_sizes(&[ValueLane::S32]) } - fn visit_br_on_non_null(&mut self, relative_depth: u32) -> Self::Output { + fn visit_br_on_non_null(&mut self, relative_depth: u32) -> Result<()> { self.pop_expect(ValueLane::S32)?; - let fallthrough_jump = self.instructions.len(); - self.instructions.push(Instruction::JumpIfRefNull(0)); + let fallthrough = self.emitter.new_label(); + self.emitter.branch(Instruction::JumpIfRefNull(0), fallthrough)?; self.push_sizes(&[ValueLane::S32])?; self.emit_dropkeep_to_label(relative_depth)?; self.pop_expect(ValueLane::S32)?; self.emit_branch_jump_or_return(relative_depth)?; - self.patch_jump(fallthrough_jump, self.instructions.len()); + self.emitter.bind(fallthrough)?; Ok(()) } - fn visit_typed_select_multi(&mut self, tys: Vec) -> Self::Output { + fn visit_typed_select_multi(&mut self, tys: Vec) -> Result<()> { let sizes: Vec<_> = tys.into_iter().map(value_lane).collect(); let counts = Self::value_counts(&sizes); self.emit( @@ -1114,7 +1172,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { ) } - fn visit_typed_select(&mut self, ty: wasmparser::ValType) -> Self::Output { + fn visit_typed_select(&mut self, ty: wasmparser::ValType) -> Result<()> { let size = value_lane(ty); let instruction = size.select(Instruction::Select32, Instruction::Select64, Instruction::Select128); self.emit(&[size, size, ValueLane::S32], &[size], instruction) @@ -1129,7 +1187,7 @@ macro_rules! impl_visit_simd_operator { (@@simd $($rest:tt)* ) => {}; (@@relaxed_simd $($rest:tt)* ) => {}; (@@$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*)) => { - fn $visit(&mut self $($(,$arg: $argty)*)?) -> Self::Output { + fn $visit(&mut self $($(,$arg: $argty)*)?) -> Result<()> { Err(crate::ParseError::UnsupportedOperator(stringify!($visit).to_string())) } }; @@ -1148,7 +1206,7 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { visit_v128_load64_splat => V128Load64Splat, visit_v128_load32_zero => V128Load32Zero, visit_v128_load64_zero => V128Load64Zero, } - memory [Addr, S128] => [] { visit_v128_store => V128Store } + memory [Addr, S128] => [] { visit_v128_store => V128Store [store128()] } memory [Addr, S128] => [S128] { visit_v128_load8_lane(lane: u8) => V128Load8Lane, visit_v128_load16_lane(lane: u8) => V128Load16Lane, @@ -1237,8 +1295,11 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { visit_i32x4_relaxed_trunc_f64x2_u_zero => I32x4RelaxedTruncF64x2UZero, } fixed [S128, S128] => [S128] { - visit_v128_and => V128And, visit_v128_andnot => V128AndNot, visit_v128_or => V128Or, - visit_v128_xor => V128Xor, visit_i8x16_swizzle => I8x16Swizzle, visit_i8x16_eq => I8x16Eq, + visit_v128_and => V128And [vector(BinOp128::And, true)], + visit_v128_andnot => V128AndNot [vector(BinOp128::AndNot, false)], + visit_v128_or => V128Or [vector(BinOp128::Or, true)], + visit_v128_xor => V128Xor [vector(BinOp128::Xor, true)], + visit_i8x16_swizzle => I8x16Swizzle, visit_i8x16_eq => I8x16Eq, visit_i8x16_ne => I8x16Ne, visit_i8x16_lt_s => I8x16LtS, visit_i8x16_lt_u => I8x16LtU, visit_i8x16_gt_s => I8x16GtS, visit_i8x16_gt_u => I8x16GtU, visit_i8x16_le_s => I8x16LeS, visit_i8x16_le_u => I8x16LeU, visit_i8x16_ge_s => I8x16GeS, visit_i8x16_ge_u => I8x16GeU, @@ -1269,8 +1330,10 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { visit_i16x8_sub_sat_u => I16x8SubSatU, visit_i16x8_avgr_u => I16x8AvgrU, visit_i16x8_mul => I16x8Mul, visit_i32x4_add => I32x4Add, visit_i32x4_sub => I32x4Sub, visit_i32x4_min_s => I32x4MinS, visit_i32x4_min_u => I32x4MinU, visit_i32x4_max_s => I32x4MaxS, - visit_i32x4_max_u => I32x4MaxU, visit_i32x4_mul => I32x4Mul, visit_i64x2_add => I64x2Add, - visit_i64x2_sub => I64x2Sub, visit_i64x2_mul => I64x2Mul, + visit_i32x4_max_u => I32x4MaxU, visit_i32x4_mul => I32x4Mul, + visit_i64x2_add => I64x2Add [vector(BinOp128::I64x2Add, true)], + visit_i64x2_sub => I64x2Sub, + visit_i64x2_mul => I64x2Mul [vector(BinOp128::I64x2Mul, true)], visit_i16x8_extmul_low_i8x16_s => I16x8ExtMulLowI8x16S, visit_i16x8_extmul_low_i8x16_u => I16x8ExtMulLowI8x16U, visit_i16x8_extmul_high_i8x16_s => I16x8ExtMulHighI8x16S, @@ -1307,18 +1370,24 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { } } - fn visit_i8x16_shuffle(&mut self, lanes: [u8; 16]) -> Self::Output { - let index = self.push_operand128(Operand128::<[u8; 16]>::new(lanes))?; + fn visit_i8x16_shuffle(&mut self, lanes: [u8; 16]) -> Result<()> { + let index = self.push128(Operand128::<[u8; 16]>::new(lanes))?; self.emit(&[ValueLane::S128, ValueLane::S128], &[ValueLane::S128], Instruction::I8x16Shuffle(index)) } - fn visit_v128_const(&mut self, value: wasmparser::V128) -> Self::Output { - let index = self.push_operand128(Operand128::<[u8; 16]>::new(*value.bytes()))?; - self.emit(&[], &[ValueLane::S128], Instruction::Const128(index)) + fn visit_v128_const(&mut self, value: wasmparser::V128) -> Result<()> { + let instruction = if self.emitter.optimizations_enabled() + && let Ok(value) = u32::try_from(u128::from_le_bytes(*value.bytes())) + { + Instruction::Const128Imm(value) + } else { + Instruction::Const128(self.push128(Operand128::<[u8; 16]>::new(*value.bytes()))?) + }; + self.emit(&[], &[ValueLane::S128], instruction) } } -impl FunctionBuilder<'_> { +impl<'a> FunctionBuilder<'a> { fn emit_cast_branch( &mut self, relative_depth: u32, @@ -1327,17 +1396,16 @@ impl FunctionBuilder<'_> { ) -> Result<()> { self.pop_expect(ValueLane::S32)?; let target = convert_heap_type(target.heap_type(), target.is_nullable())?; - let conditional_ip = self.instructions.len(); - let operand = self.data.push_target_operand64(Operand64::<(u32, u32)>::new(0, target.to_bits()))?; - self.instructions.push(if branch_on_fail { - Instruction::BrOnCastFail(operand) - } else { - Instruction::BrOnCast(operand) - }); + let fallthrough = self.emitter.new_label(); + let operand = self.data.push_target64(Operand64::<(u32, u32)>::new(0, target.to_bits()))?; + self.emitter.branch( + if branch_on_fail { Instruction::BrOnCastFail(operand) } else { Instruction::BrOnCast(operand) }, + fallthrough, + )?; self.push_sizes(&[ValueLane::S32])?; self.emit_dropkeep_to_label(relative_depth)?; self.emit_branch_jump_or_return(relative_depth)?; - self.patch_jump(conditional_ip, self.instructions.len()); + self.emitter.bind(fallthrough)?; Ok(()) } @@ -1411,8 +1479,26 @@ impl FunctionBuilder<'_> { /// Applies an instruction's stack effect before adding it to the bytecode. fn emit(&mut self, inputs: &[ValueLane], outputs: &[ValueLane], instruction: Instruction) -> Result<()> { self.apply_effect(inputs, outputs)?; - self.instructions.push(instruction); - Ok(()) + self.emitter.emit(instruction) + } + + /// Applies stack effects and seals a call or terminator's instruction boundary. + fn emit_boundary(&mut self, inputs: &[ValueLane], outputs: &[ValueLane], instruction: Instruction) -> Result<()> { + self.apply_effect(inputs, outputs)?; + self.emitter.emit_boundary(instruction) + } + + /// Applies logical stack effects before invoking a statically selected rule family. + #[inline] + fn emit_with( + &mut self, + inputs: &[ValueLane], + outputs: &[ValueLane], + instruction: Instruction, + rules: impl FnOnce(&mut crate::emitter::PendingTail<'_>, &mut FunctionDataBuilder) -> Result<()>, + ) -> Result<()> { + self.apply_effect(inputs, outputs)?; + self.emitter.emit_with(&mut self.data, instruction, rules) } /// Restores both logical operand order and lane counts to a control-frame base. @@ -1431,42 +1517,42 @@ impl FunctionBuilder<'_> { } } - /// Enters a control frame with its parameters restored above the saved base. - fn push_control(&mut self, kind: BlockKind, ty: wasmparser::BlockType, initial_jump: Option) -> Result<()> { - let signature = self.block_signature(ty)?; - self.push_control_signature(kind, signature, initial_jump) - } - - fn block_signature(&self, ty: wasmparser::BlockType) -> Result { + fn block_signature(&self, ty: wasmparser::BlockType) -> Result> { Ok(match ty { - wasmparser::BlockType::Empty => Signature { params: Vec::new(), results: Vec::new() }, - wasmparser::BlockType::Type(ty) => Signature { params: Vec::new(), results: alloc::vec![value_lane(ty)] }, - wasmparser::BlockType::FuncType(idx) => self.metadata.signature(idx)?.clone(), + wasmparser::BlockType::Empty => BlockSignature::Empty, + wasmparser::BlockType::Type(ty) => BlockSignature::Result(value_lane(ty)), + wasmparser::BlockType::FuncType(idx) => BlockSignature::Function(self.metadata.signature(idx)?), }) } - fn push_control_signature( - &mut self, - kind: BlockKind, - signature: Signature, - initial_jump: Option, - ) -> Result<()> { - for &size in signature.params.iter().rev() { + /// Enters a control frame with its parameters restored above the saved base. + fn push_control(&mut self, kind: BlockKind, ty: wasmparser::BlockType, else_entry: Option) -> Result<()> { + let signature = self.block_signature(ty)?; + for &size in signature.params().iter().rev() { self.pop_expect(size)?; } let height = self.operand_stack.len(); let base = self.lane_counts; - self.push_sizes(&signature.params)?; + self.push_sizes(signature.params())?; let entry_unreachable = self.is_unreachable(); + // Backedges are not known yet, so loop headers always seal the tail. + // Other constructs have no entry target and allocate exits on first use. + let loop_start = if matches!(kind, BlockKind::Loop) { + let start = self.emitter.new_label(); + self.emitter.bind(start)?; + Some(start) + } else { + None + }; self.control_stack.push(ControlFrame { kind, has_else: false, - start_ip: self.instructions.len(), - branch_jumps: initial_jump.into_iter().collect(), + loop_start, + end: None, + else_entry, height, base, - params: signature.params, - results: signature.results, + signature, unreachable: entry_unreachable, entry_unreachable, end_reachable: false, @@ -1475,34 +1561,23 @@ impl FunctionBuilder<'_> { } /// Emits the stack-shaping instruction required by a branch. - fn emit_dropkeep(&mut self, base: ValueCounts, keep: ValueCounts) { - let target = ValueCounts { c32: base.c32 + keep.c32, c64: base.c64 + keep.c64, c128: base.c128 + keep.c128 }; - if self.lane_counts.c32 != target.c32 { - self.instructions.push(Instruction::DropKeep32 { base: base.c32, keep: keep.c32 }); + fn emit_dropkeep(&mut self, base: ValueCounts, keep: ValueCounts) -> Result<()> { + if Some(self.lane_counts.c32) != base.c32.checked_add(keep.c32) { + self.emitter.emit(Instruction::DropKeep32 { base: base.c32, keep: keep.c32 })?; } - if self.lane_counts.c64 != target.c64 { - self.instructions.push(Instruction::DropKeep64 { base: base.c64, keep: keep.c64 }); + if Some(self.lane_counts.c64) != base.c64.checked_add(keep.c64) { + self.emitter.emit(Instruction::DropKeep64 { base: base.c64, keep: keep.c64 })?; } - if self.lane_counts.c128 != target.c128 { - self.instructions.push(Instruction::DropKeep128 { base: base.c128, keep: keep.c128 }); + if Some(self.lane_counts.c128) != base.c128.checked_add(keep.c128) { + self.emitter.emit(Instruction::DropKeep128 { base: base.c128, keep: keep.c128 })?; } + Ok(()) } - fn patch_jump(&mut self, jump_ip: usize, target: usize) { - match &mut self.instructions[jump_ip] { - Instruction::Jump(ip) - | Instruction::JumpIfZero32(ip) - | Instruction::JumpIfNonZero32(ip) - | Instruction::JumpIfRefNull(ip) - | Instruction::JumpIfRefNonNull(ip) => { - *ip = target as u32; - } - Instruction::BrOnCast(index) | Instruction::BrOnCastFail(index) => { - let operand = self.data.operand64(*index); - self.data.set_operand64(*index, operand.with_target(target as u32)); - } - _ => {} - } + fn needs_dropkeep(&self, base: ValueCounts, keep: ValueCounts) -> bool { + Some(self.lane_counts.c32) != base.c32.checked_add(keep.c32) + || Some(self.lane_counts.c64) != base.c64.checked_add(keep.c64) + || Some(self.lane_counts.c128) != base.c128.checked_add(keep.c128) } fn value_counts(sizes: &[ValueLane]) -> ValueCounts { @@ -1524,39 +1599,24 @@ impl FunctionBuilder<'_> { } let frame = &self.control_stack[self.get_ctx_idx(label_depth)?]; let base = frame.base; - let label_types = if matches!(frame.kind, BlockKind::Loop) { &frame.params } else { &frame.results }; - self.emit_dropkeep(base, Self::value_counts(label_types)); - Ok(()) + let label_types = + if matches!(frame.kind, BlockKind::Loop) { frame.signature.params() } else { frame.signature.results() }; + self.emit_dropkeep(base, Self::value_counts(label_types)) } fn emit_branch_jump_or_return(&mut self, depth: u32) -> Result<()> { let ctx_idx = self.get_ctx_idx(depth)?; match self.control_stack[ctx_idx].kind { - BlockKind::Function => self.instructions.push(Instruction::Return), - BlockKind::Loop => self.instructions.push(Instruction::Jump(self.control_stack[ctx_idx].start_ip as u32)), - BlockKind::Block | BlockKind::If | BlockKind::TryTable(_) => { - self.control_stack[ctx_idx].branch_jumps.push(self.instructions.len()); + BlockKind::Function => self.emitter.emit_boundary(Instruction::Return)?, + BlockKind::Loop => { + self.emitter.branch(Instruction::Jump(0), self.control_stack[ctx_idx].loop_start.unwrap())? + } + BlockKind::Block | BlockKind::If | BlockKind::TryTable => { self.control_stack[ctx_idx].end_reachable = true; - self.instructions.push(Instruction::Jump(0)); + let end = *self.control_stack[ctx_idx].end.get_or_insert_with(|| self.emitter.new_label()); + self.emitter.branch(Instruction::Jump(0), end)?; } } Ok(()) } - - /// Resolves all jumps owned by a completed control frame. - fn patch_end_jumps(&mut self, ctx: ControlFrame, end_ip: usize) { - let target = if matches!(ctx.kind, BlockKind::Loop) { ctx.start_ip } else { end_ip }; - let mut jumps = ctx.branch_jumps.as_slice(); - if matches!(ctx.kind, BlockKind::If) - && let Some((cond_jump, branch_jumps)) = jumps.split_first() - { - if !ctx.has_else { - self.patch_jump(*cond_jump, end_ip); - } - jumps = branch_jumps; - } - for &jump in jumps { - self.patch_jump(jump, target); - } - } } -- cgit v1.3.1