summaryrefslogtreecommitdiff
path: root/crates/parser
diff options
context:
space:
mode:
Diffstat (limited to 'crates/parser')
-rw-r--r--crates/parser/Cargo.toml21
-rw-r--r--crates/parser/README.md9
-rw-r--r--crates/parser/src/conversion.rs318
-rw-r--r--crates/parser/src/emitter.rs355
-rw-r--r--crates/parser/src/error.rs2
-rw-r--r--crates/parser/src/lib.rs179
-rw-r--r--crates/parser/src/macros.rs304
-rw-r--r--crates/parser/src/module.rs282
-rw-r--r--crates/parser/src/optimize.rs984
-rw-r--r--crates/parser/src/parallel.rs67
-rw-r--r--crates/parser/src/selection.rs314
-rw-r--r--crates/parser/src/selection/encoding.rs293
-rw-r--r--crates/parser/src/validation.rs15
-rw-r--r--crates/parser/src/visit.rs1380
14 files changed, 2590 insertions, 1933 deletions
diff --git a/crates/parser/Cargo.toml b/crates/parser/Cargo.toml
index 3e71403..afedeed 100644
--- a/crates/parser/Cargo.toml
+++ b/crates/parser/Cargo.toml
@@ -4,7 +4,7 @@ version.workspace = true
edition.workspace = true
rust-version.workspace = true
description = "Parser and lowering pipeline for TinyWasm"
-readme = "README.md"
+homepage.workspace = true
repository.workspace = true
license.workspace = true
keywords.workspace = true
@@ -13,10 +13,25 @@ categories.workspace = true
[dependencies]
log = { workspace = true, optional = true }
tinywasm-types = { workspace = true }
-wasmparser = { workspace = true, features = ["features", "simd", "validate"] }
+wasmparser = { workspace = true, features = ["simd"] }
[features]
-default = ["log", "parallel", "std"]
+default = ["log", "parallel", "std", "validate"]
+
+# enable integration with the log crate
log = ["dep:log"]
+
+# parse and validate function bodies in parallel (requires std)
parallel = ["std"]
+
+# support targets without native atomic CAS
+portable-atomic = ["tinywasm-types/portable-atomic"]
+
+# enable standard library support
std = ["tinywasm-types/std", "wasmparser/std"]
+
+# validate WebAssembly while parsing
+validate = ["wasmparser/features", "wasmparser/validate"]
+
+[lints]
+workspace = true
diff --git a/crates/parser/README.md b/crates/parser/README.md
index 91145f1..cf1a6c4 100644
--- a/crates/parser/README.md
+++ b/crates/parser/README.md
@@ -6,7 +6,8 @@ This crate provides the parser and lowering pipeline that converts WebAssembly b
- `std`: Enables the use of `std` and `std::io` for parsing from files and streams.
- `log`: Enables logging of the parsing process using the `log` crate.
-- `parallel`: Enables multithreaded parsing and validation when `std` is available.
+- `parallel`: Enables multithreaded function parsing. Requires `std`.
+- `validate`: Enables `wasmparser` validation. Enabled by default and configurable through `ParserOptions`.
## Usage
@@ -15,10 +16,10 @@ use tinywasm_parser::{Parser, ParserOptions};
let bytes = include_bytes!("./file.wasm");
-let parser = Parser::new();
+let parser = Parser::default();
let module = parser.parse_module_bytes(bytes)?;
-let parser = Parser::with_options(ParserOptions::default().with_rewrite_optimization(false));
+let parser = Parser::new(ParserOptions::default().with_rewrite_optimization(false));
let module = parser.parse_module_bytes(bytes)?;
let module = parser.parse_module_file("path/to/file.wasm")?;
@@ -26,4 +27,4 @@ let mut stream = std::fs::File::open("path/to/file.wasm")?;
let module = parser.parse_module_stream(&mut stream)?;
```
-If you just want the default configuration, the top-level `parse_bytes`, `parse_file`, and `parse_stream` helpers are thin wrappers around `Parser::new()`.
+If you just want the default configuration, the top-level `parse_bytes`, `parse_file`, and `parse_stream` helpers are thin wrappers around `Parser::default()`.
diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs
index db8d2aa..36455ee 100644
--- a/crates/parser/src/conversion.rs
+++ b/crates/parser/src/conversion.rs
@@ -1,16 +1,38 @@
-use crate::{Result, module::FunctionCode, visit::process_operators_and_validate};
-use alloc::{boxed::Box, format, string::ToString, vec::Vec};
+use crate::validation::{FuncValidator, FuncValidatorAllocations, ValidatorResources};
+#[cfg(feature = "validate")]
+use crate::visit::process_operators_and_validate;
+use crate::{ParserOptions, Result, module::FunctionCode, visit::process_operators};
+use alloc::{boxed::Box, format, vec::Vec};
use tinywasm_types::*;
-use wasmparser::{
- CompositeInnerType, FuncValidator, FuncValidatorAllocations, OperatorsReader, OperatorsReaderAllocations,
- ValidatorResources,
-};
+use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations, UnpackedIndex};
-pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result<tinywasm_types::Element> {
+/// 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,
+ wasmparser::ValType::I64 | wasmparser::ValType::F64 => ValueLane::S64,
+ wasmparser::ValType::V128 => ValueLane::S128,
+ }
+}
+
+pub(crate) fn convert_module_element(
+ element: wasmparser::Element<'_>,
+ global_types: &[WasmType],
+) -> Result<tinywasm_types::Element> {
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,
@@ -30,7 +52,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::<Result<Vec<_>>>()?
.into_boxed_slice();
@@ -39,13 +61,16 @@ pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result
}
}
-pub(crate) fn convert_module_data(data: wasmparser::Data<'_>) -> Result<tinywasm_types::Data> {
+pub(crate) fn convert_module_data(
+ data: wasmparser::Data<'_>,
+ global_types: &[WasmType],
+) -> Result<tinywasm_types::Data> {
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 } => {
- 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,
@@ -68,9 +93,7 @@ pub(crate) fn convert_module_import(import: wasmparser::Import<'_>) -> Result<Im
wasmparser::TypeRef::Global(ty) => {
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)));
}
@@ -90,16 +113,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<WasmType>,
) -> Result<Box<[Global]>> {
- 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::<Result<Box<_>>>()
+ 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<Export> {
@@ -108,7 +132,8 @@ pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result<Ex
wasmparser::ExternalKind::Table => 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)));
}
};
@@ -116,72 +141,166 @@ pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result<Ex
Ok(Export { index: export.index, name: Box::from(export.name), kind })
}
+pub(crate) const fn convert_tag_type(ty: wasmparser::TagType) -> TagType {
+ TagType::new(ty.func_type_idx)
+}
+
+fn extend_local_types(local_types: &mut Vec<ValueLane>, 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);
+ local_types.extend(core::iter::repeat_n(size, count));
+ Ok(())
+}
+
pub(crate) fn convert_module_code(
func: wasmparser::FunctionBody<'_>,
- mut validator: Option<FuncValidator<ValidatorResources>>,
+ validator: Option<FuncValidator<ValidatorResources>>,
reader_allocs: OperatorsReaderAllocations,
metadata: &crate::visit::ModuleMetadata,
- ty_idx: u32,
+ context: FunctionLoweringContext,
+ options: &ParserOptions,
) -> Result<(FunctionCode, Option<FuncValidatorAllocations>, OperatorsReaderAllocations)> {
- let locals_reader = func.get_locals_reader()?;
- let pos = locals_reader.original_position();
- let signature = metadata.signature(ty_idx)?.clone();
- let mut local_types = signature.params.clone();
+ let mut locals_reader = func.get_locals_reader()?;
+ let mut local_types = metadata.signature(context.ty_idx)?.params.clone();
- for (i, local) in locals_reader.into_iter().enumerate() {
- let local = local?;
+ #[cfg(feature = "validate")]
+ let mut validator = validator;
+
+ 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(pos + i, local.0, local.1)?;
+ validator.define_locals(position, 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"))]
+ 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());
let mut local_counts = ValueCounts::default();
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()))?;
}
- 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, uses_local_memory, validator_allocs, reader_allocs) = match validator {
+ Some(validator) => {
+ let (body, data, uses_local_memory, validator_allocs, reader_allocs) = process_operators_and_validate(
+ validator,
+ func,
+ (local_types, local_addr_map),
+ metadata,
+ context,
+ reader_allocs,
+ 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, 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, context, reader_allocs, options)?;
+ (body, data, uses_local_memory, None, reader_allocs)
+ };
Ok((
- FunctionCode { instructions: body, data, locals: local_counts, uses_local_memory: false },
+ FunctionCode { instructions: body, data: data.finish(), locals: local_counts, uses_local_memory },
validator_allocs,
reader_allocs,
))
}
-pub(crate) fn convert_module_type(ty: wasmparser::RecGroup) -> Result<FuncType> {
- 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<SubType>) -> Result<u32> {
+ 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::<Result<Vec<_>>>()?;
+ let results = ty
+ .results()
+ .iter()
+ .map(|ty| convert_valtype_in_group(ty, group_start, group_len))
+ .collect::<Result<Vec<_>>>()?;
+ CompositeType::Func(FuncType::new(&params, &results))
+ }
+ CompositeInnerType::Struct(ty) => CompositeType::Struct(StructType {
+ fields: ty
+ .fields
+ .iter()
+ .map(|field| convert_field_type(field, group_start, group_len))
+ .collect::<Result<_>>()?,
+ }),
+ 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<TypeAddr> {
+ 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<FieldType> {
+ 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::<Result<Vec<_>>>()?;
- let results = ty.results().iter().map(convert_valtype).collect::<Result<Vec<_>>>()?;
- Ok(FuncType::new(&params, &results))
+ Ok(FieldType { storage, mutable: field.mutable })
}
pub(crate) fn convert_ref_type(ty: wasmparser::RefType) -> Result<RefType> {
@@ -189,17 +308,30 @@ pub(crate) fn convert_ref_type(ty: wasmparser::RefType) -> Result<RefType> {
}
pub(crate) fn convert_valtype(valtype: &wasmparser::ValType) -> Result<WasmType> {
+ convert_valtype_with_group(valtype, None)
+}
+
+fn convert_valtype_in_group(valtype: &wasmparser::ValType, group_start: u32, group_len: u32) -> Result<WasmType> {
+ convert_valtype_with_group(valtype, Some((group_start, group_len)))
+}
+
+fn convert_valtype_with_group(valtype: &wasmparser::ValType, group: Option<(u32, u32)>) -> Result<WasmType> {
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)?))
+ }
}
}
-pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<Box<[ConstInstruction]>> {
+pub(crate) fn process_const_operators(
+ ops: OperatorsReader<'_>,
+ global_types: &[WasmType],
+) -> Result<Box<[ConstInstruction]>> {
let mut out = Vec::new();
let mut operator_count = 0;
let mut end_reached = false;
@@ -213,19 +345,36 @@ pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<Box<[C
}
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,
+ 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())),
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,
@@ -249,6 +398,14 @@ pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<Box<[C
}
pub(crate) fn convert_heap_type(heap: wasmparser::HeapType, nullable: bool) -> Result<RefType> {
+ convert_heap_type_with_group(heap, nullable, None)
+}
+
+fn convert_heap_type_with_group(
+ heap: wasmparser::HeapType,
+ nullable: bool,
+ group: Option<(u32, u32)>,
+) -> Result<RefType> {
match heap {
wasmparser::HeapType::Abstract { shared: false, ty } => Ok(RefType::new_abstract(
nullable,
@@ -271,11 +428,24 @@ 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:?}"))
- })?;
- RefType::new_concrete(nullable, index)
- .ok_or_else(|| crate::ParseError::Other(format!("heap type index is too large: {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}"
+ )));
+ }
+ };
+ 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/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<Instruction>,
+ start: usize,
+}
+
+impl<'a> PendingTail<'a> {
+ fn new(instructions: &'a mut Vec<Instruction>, 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<const N: usize>(&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<const N: usize, const M: usize>(&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<Instruction>,
+ committed: usize,
+ select: bool,
+ self_func_addr: u32,
+ return_instruction: Instruction,
+ pending_jump: Option<LabelId>,
+ labels: Vec<Option<u32>>,
+ 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::<BranchTableOperand>::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<Vec<Instruction>> {
+ 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/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 aa5e0b0..019e027 100644
--- a/crates/parser/src/lib.rs
+++ b/crates/parser/src/lib.rs
@@ -30,10 +30,12 @@ pub(crate) mod log {
}
mod conversion;
+mod emitter;
mod error;
mod macros;
mod module;
-mod optimize;
+mod selection;
+mod validation;
mod visit;
#[cfg(parallel_parser)]
@@ -41,7 +43,10 @@ mod parallel;
pub use error::*;
use module::ModuleReader;
-use wasmparser::{Validator, WasmFeatures};
+use validation::Validator;
+
+#[cfg(feature = "validate")]
+use wasmparser::WasmFeatures;
pub use tinywasm_types::Module;
@@ -49,15 +54,20 @@ pub use tinywasm_types::Module;
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct ParserOptions {
- /// Whether to validate modules while parsing. Enabled by default.
+ /// Whether to validate modules while parsing. Enabled by default when the
+ /// `validate` feature is enabled.
+ ///
+ /// Requires the `validate` feature to have any effect.
///
/// 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 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,
#[cfg(parallel_parser)]
/// Number of threads to use for parallel parsing.
@@ -67,27 +77,35 @@ 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<usize>,
+ pub threads: Option<usize>,
}
impl Default for ParserOptions {
fn default() -> Self {
Self {
- validation: true,
- optimize_local_memory_allocation: true,
- optimize_rewrite: true,
+ validation: cfg!(feature = "validate"),
+ optimize: true,
+ deduplicate_operands: true,
#[cfg(parallel_parser)]
- parser_threads: None,
+ threads: None,
}
}
}
impl ParserOptions {
+ /// Create parser options with default settings.
+ pub fn new() -> Self {
+ Self::default()
+ }
+
/// Enable or disable WebAssembly validation.
///
+ /// Requires the `validate` feature to have any effect.
+ ///
/// Disable this only for trusted input. Parsing without validation may produce
/// a module that violates runtime assumptions.
pub const fn with_validation(mut self, enabled: bool) -> Self {
+ assert!(!enabled || cfg!(feature = "validate"), "validation requires the `validate` feature");
self.validation = enabled;
self
}
@@ -97,41 +115,41 @@ 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;
+ /// 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 unused local memory allocation optimization is enabled.
- pub const fn optimize_local_memory_allocation(&self) -> bool {
- self.optimize_local_memory_allocation
+ /// 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 the peephole rewrite optimizer.
- pub const fn with_rewrite_optimization(mut self, enabled: bool) -> Self {
- self.optimize_rewrite = enabled;
+ /// 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 the peephole rewrite optimizer is enabled.
- pub const fn optimize_rewrite(&self) -> bool {
- self.optimize_rewrite
+ /// 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.
///
/// 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<usize> {
- self.parser_threads
+ pub const fn threads(&self) -> Option<usize> {
+ self.threads
}
}
@@ -142,13 +160,8 @@ pub struct Parser {
}
impl Parser {
- /// Create a new parser instance
- pub fn new() -> Self {
- Self::default()
- }
-
- /// Create a new parser with explicit options.
- pub fn with_options(options: ParserOptions) -> Self {
+ /// Create a parser with the given options.
+ pub const fn new(options: ParserOptions) -> Self {
Self { options }
}
@@ -157,36 +170,44 @@ impl Parser {
&self.options
}
- fn create_validator(_options: ParserOptions) -> Validator {
- let features = WasmFeatures::CALL_INDIRECT_OVERLONG
- | WasmFeatures::BULK_MEMORY_OPT
- | WasmFeatures::RELAXED_SIMD
- | WasmFeatures::GC_TYPES
- | WasmFeatures::REFERENCE_TYPES
- | WasmFeatures::MUTABLE_GLOBAL
- | WasmFeatures::MULTI_VALUE
- | WasmFeatures::FLOATS
- | WasmFeatures::BULK_MEMORY
- | WasmFeatures::SATURATING_FLOAT_TO_INT
- | WasmFeatures::SIGN_EXTENSION
- | WasmFeatures::EXTENDED_CONST
- | WasmFeatures::FUNCTION_REFERENCES
- | WasmFeatures::TAIL_CALL
- | WasmFeatures::MULTI_MEMORY
- | WasmFeatures::SIMD
- | WasmFeatures::MEMORY64
- | WasmFeatures::CUSTOM_PAGE_SIZES
- | WasmFeatures::WIDE_ARITHMETIC;
- Validator::new_with_features(features)
+ fn validator(&self) -> Option<Validator> {
+ #[cfg(feature = "validate")]
+ {
+ let features = WasmFeatures::WASM3
+ .difference(WasmFeatures::THREADS)
+ .union(WasmFeatures::CUSTOM_PAGE_SIZES)
+ .union(WasmFeatures::WIDE_ARITHMETIC)
+ .union(WasmFeatures::COMPACT_IMPORTS);
+ self.options.validation().then(|| Validator::new_with_features(features))
+ }
+ #[cfg(not(feature = "validate"))]
+ {
+ assert!(!self.options.validation(), "validation requires the `validate` feature");
+ None
+ }
}
#[cfg(feature = "std")]
fn read_more(stream: &mut impl std::io::Read, buffer: &mut alloc::vec::Vec<u8>, hint: usize) -> Result<usize> {
let len = buffer.len();
- buffer.resize(len + hint, 0);
- let read_bytes = stream
- .read(&mut buffer[len..])
- .map_err(|e| ParseError::Other(alloc::format!("Error reading from stream: {e}")))?;
+ // Size hints can come from untrusted section lengths.
+ let increment = hint.clamp(1, 64 * 1024);
+ let new_len =
+ len.checked_add(increment).ok_or_else(|| ParseError::Other("stream buffer is too large".into()))?;
+ buffer
+ .try_reserve(increment)
+ .map_err(|e| ParseError::Other(alloc::format!("Error reserving stream buffer: {e}")))?;
+ buffer.resize(new_len, 0);
+ let read_bytes = loop {
+ match stream.read(&mut buffer[len..]) {
+ Ok(read_bytes) => break read_bytes,
+ Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
+ Err(e) => {
+ buffer.truncate(len);
+ return Err(ParseError::Other(alloc::format!("Error reading from stream: {e}")));
+ }
+ }
+ };
buffer.truncate(len + read_bytes);
Ok(read_bytes)
}
@@ -194,7 +215,7 @@ impl Parser {
/// Parse a [`Module`] from bytes
pub fn parse_module_bytes(&self, wasm: impl AsRef<[u8]>) -> Result<Module> {
let wasm = wasm.as_ref();
- let mut validator = self.options.validation().then(|| Self::create_validator(self.options.clone()));
+ let mut validator = self.validator();
let mut reader = ModuleReader::default();
for payload in wasmparser::Parser::new(0).parse_all(wasm) {
@@ -214,7 +235,7 @@ impl Parser {
}
reader.process_pending_functions(&self.options)?;
- reader.into_module(&self.options)
+ reader.into_module()
}
#[cfg(feature = "std")]
@@ -228,7 +249,7 @@ impl Parser {
#[cfg(feature = "std")]
/// Parse a [`Module`] from a stream. Requires `std` feature.
pub fn parse_module_stream(&self, mut stream: impl std::io::Read) -> Result<Module> {
- let mut validator = self.options.validation().then(|| Self::create_validator(self.options.clone()));
+ let mut validator = self.validator();
let mut reader = ModuleReader::default();
let mut buffer = alloc::vec::Vec::new();
let mut parser = wasmparser::Parser::new(0);
@@ -243,7 +264,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 } => {
@@ -252,17 +273,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))]
@@ -278,21 +294,22 @@ 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())?;
+ let section_bytes =
+ tinywasm_types::Shared::<[u8]>::from(buffer[buffer_offset..section_end].to_vec());
+ reader.queue_owned_code_section(count, parser.offset(), section_bytes, validator.as_mut())?;
parser.skip_section();
buffer_offset = section_end;
continue;
@@ -315,7 +332,7 @@ impl Parser {
if reader.end_reached || eof {
reader.process_pending_functions(&self.options)?;
- return reader.into_module(&self.options);
+ return reader.into_module();
}
}
};
@@ -327,23 +344,23 @@ impl TryFrom<ModuleReader<'_>> for Module {
type Error = ParseError;
fn try_from(reader: ModuleReader<'_>) -> Result<Self> {
- reader.into_module(&ParserOptions::default())
+ reader.into_module()
}
}
/// Parse a module from bytes
pub fn parse_bytes(wasm: &[u8]) -> Result<Module> {
- Parser::new().parse_module_bytes(wasm)
+ Parser::default().parse_module_bytes(wasm)
}
#[cfg(feature = "std")]
/// Parse a module from a file. Requires the `std` feature.
pub fn parse_file(path: impl AsRef<crate::std::path::Path> + Clone) -> Result<Module> {
- Parser::new().parse_module_file(path)
+ Parser::default().parse_module_file(path)
}
#[cfg(feature = "std")]
/// Parse a module from a stream. Requires the `std` feature.
pub fn parse_stream(stream: impl crate::std::io::Read) -> Result<Module> {
- Parser::new().parse_module_stream(stream)
+ Parser::default().parse_module_stream(stream)
}
diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs
index 723f691..fe1364b 100644
--- a/crates/parser/src/macros.rs
+++ b/crates/parser/src/macros.rs
@@ -1,78 +1,144 @@
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)*))*) => {$(
fn $visit(&mut self $($(,$arg: $argty)*)?) -> Self::Output {
- if let Some(validator) = self.validator.as_mut() {
- if let Err(e) = validator.visitor(self.position).$visit($($($arg.clone()),*)?) {
- core::hint::cold_path();
- return Err(crate::ParseError::ParseError { message: e.to_string(), offset: self.position });
- }
+ if let Err(e) = self.validator.visitor(self.position).$visit($($($arg.clone()),*)?) {
+ core::hint::cold_path();
+ return Err(crate::ParseError::ParseError { message: e.to_string(), offset: self.position });
}
self.builder.$visit($($($arg),*)?)
}
)*};
}
+ #[cfg(feature = "validate")]
macro_rules! validate_then_visit_simd {
($( @$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*))*) => {$(
fn $visit(&mut self $($(,$arg: $argty)*)?) -> Self::Output {
- if let Some(validator) = self.validator.as_mut() {
- if let Err(e) = validator.simd_visitor(self.position).$visit($($($arg.clone()),*)?) {
- core::hint::cold_path();
- return Err(crate::ParseError::ParseError { message: e.to_string(), offset: self.position });
- }
+ if let Err(e) = self.validator.simd_visitor(self.position).$visit($($($arg.clone()),*)?) {
+ core::hint::cold_path();
+ return Err(crate::ParseError::ParseError { message: e.to_string(), offset: self.position });
}
self.builder.$visit($($($arg),*)?)
}
)*};
}
+ // 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)*) => {
$(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 $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
+ $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.push128(tinywasm_types::Operand128::<
+ tinywasm_types::MemoryOperand,
+ >::new(memarg.offset, memarg.memory))?;
lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*]
- Instruction::$instr(MemoryArg::new(memarg.offset, memarg.memory) $(, $lane)?).into())
+ $instr(lowering_ops!(@memory_arg memory_arg_idx $(, $lane)?)) $([$family($($rule_arg),*)])?)
}
};
+ (@memory_arg $memory_arg_idx:ident) => {
+ $memory_arg_idx
+ };
+ (@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)*);
};
(@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 $([$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),*]
+ $instr($index) $([$family($($rule_arg),*)])?)
+ }
};
(@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 = self.metadata.array_field($type_index)?;
+ lowering_ops!(@emit self address(size) [$($input),*] => [$($output),*]
+ $instr($type_index $(, $arg)*))
+ }
+ };
(@resolved $resolver:ident [$($input:ident),*] => [$($output:ident),*]
$visit:ident($index:ident: $ty:ty) => $instr:ident
) => {
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),*]
@@ -81,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) => {
@@ -92,27 +158,32 @@ 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)+
)
};
(@size Addr, $address:ident) => { $address };
- (@size $size:ident $(, $address:ident)?) => { OperandSize::$size };
+ (@size Field, $address:ident) => { $address };
+ (@size $size:ident $(, $address:ident)?) => { ValueLane::$size };
}
macro_rules! impl_visit_operator {
@@ -130,6 +201,8 @@ pub(crate) mod visit {
(@@relaxed_simd $($rest:tt)* ) => {};
(@@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 {
@@ -138,178 +211,7 @@ pub(crate) mod visit {
};
}
- pub(crate) use {impl_visit_operator, lowering_ops, 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]);
- };
- }
-
- 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 !$instructions.tail_rewritten
- && $read < $instructions.len()
- && $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
- }
- }
- }};
- ($instructions:ident, $read:ident, [$($pattern:pat),+] $(if ($($guard:tt)+))? => $out:expr $(,)?) => {
- rewrite!($instructions, $read, [$($pattern),+] $(if ($($guard)+))? => {
- replace!($instructions, $read, [$(stringify!($pattern)),+].len() => $out);
- })
- };
- }
-
- 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<Instruction>, 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 {emit_selected, impl_visit_operator, lowering_ops};
+ #[cfg(feature = "validate")]
+ pub(crate) use {validate_then_visit, validate_then_visit_simd};
}
diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs
index c2199f3..03c725c 100644
--- a/crates/parser/src/module.rs
+++ b/crates/parser/src/module.rs
@@ -1,11 +1,15 @@
use crate::log::debug;
-use crate::{ParseError, ParserOptions, Result, conversion::*, optimize};
-use alloc::{boxed::Box, format, string::ToString, sync::Arc, vec::Vec};
+#[cfg(parallel_parser)]
+use crate::validation::{FuncToValidate, ValidatorResources};
+use crate::validation::{FuncValidatorAllocations, Validator};
+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::{FuncValidatorAllocations, OperatorsReaderAllocations, Payload, Validator};
+use wasmparser::{OperatorsReaderAllocations, Payload};
+/// Final bytecode and metadata produced by streaming function lowering.
pub(crate) struct FunctionCode {
pub instructions: Vec<Instruction>,
pub data: WasmFunctionData,
@@ -13,52 +17,33 @@ pub(crate) struct FunctionCode {
pub uses_local_memory: bool,
}
-pub(crate) fn optimize_function_code(
- mut code: FunctionCode,
- options: &ParserOptions,
- function_results: ValueCounts,
- self_func_addr: u32,
- imported_memory_count: u32,
-) -> Result<FunctionCode> {
- 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)
-}
-
#[derive(Default)]
pub(crate) struct ModuleReader<'a> {
func_validator_allocations: Option<FuncValidatorAllocations>,
operators_reader_allocations: Option<OperatorsReaderAllocations>,
- translation_metadata: Option<Arc<crate::visit::ModuleMetadata>>,
+ translation_metadata: Option<crate::visit::ModuleMetadata>,
has_code_section: bool,
+ has_type_section: bool,
marker: PhantomData<&'a [u8]>,
pub(crate) version: Option<u16>,
pub(crate) start_func: Option<u32>,
- 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]>,
+ pub(crate) exports: Shared<[Export]>,
pub(crate) code: Vec<FunctionCode>,
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]>,
pub(crate) end_reached: bool,
imported_func_count: usize,
- imported_memory_count: u32,
+ global_types: Vec<WasmType>,
#[cfg(parallel_parser)]
pending_functions: Option<Vec<crate::parallel::PendingFunction<'a>>>,
@@ -67,23 +52,24 @@ pub(crate) struct ModuleReader<'a> {
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.translation_metadata = Some(crate::visit::ModuleMetadata::new(
+ &self.types,
&self.code_type_addrs,
&self.imports,
&self.globals,
&self.memory_types,
&self.tables,
- )));
+ &self.tags,
+ ));
}
- self.translation_metadata.as_deref().unwrap()
+ self.translation_metadata.as_ref().unwrap()
}
- pub(crate) fn process_payload(
- &mut self,
- payload: Payload<'_>,
- mut validator: Option<&mut Validator>,
- ) -> Result<()> {
+ pub(crate) fn process_payload(&mut self, payload: Payload<'_>, validator: Option<&mut Validator>) -> Result<()> {
+ #[cfg(feature = "validate")]
+ let mut validator = validator;
+ #[cfg(not(feature = "validate"))]
+ let _ = validator;
fn check_section(section: &str, duplicate: bool) -> Result<()> {
debug!("found {section} section");
if duplicate {
@@ -94,9 +80,12 @@ impl<'a> ModuleReader<'a> {
match payload {
Payload::Version { num, encoding, range } => {
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.version(num, encoding, &range)?;
}
+ #[cfg(not(feature = "validate"))]
+ let _ = range;
self.version = Some(num);
if let wasmparser::Encoding::Component = encoding {
return Err(ParseError::InvalidEncoding(encoding));
@@ -104,27 +93,46 @@ impl<'a> ModuleReader<'a> {
}
Payload::StartSection { func, range } => {
check_section("start", self.start_func.is_some())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.start_section(func, &range)?;
}
+ #[cfg(not(feature = "validate"))]
+ let _ = range;
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::<Result<_>>()?;
+ 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())?;
+ #[cfg(feature = "validate")]
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())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.table_section(&reader)?;
}
@@ -140,7 +148,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 });
@@ -149,38 +157,69 @@ impl<'a> ModuleReader<'a> {
}
Payload::MemorySection(reader) => {
check_section("memory", !self.memory_types.is_empty())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.memory_section(&reader)?;
}
self.memory_types =
reader.into_iter().map(|memory| Ok(convert_module_memory(memory?))).collect::<Result<_>>()?;
}
+ 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")]
if let Some(validator) = validator.as_mut() {
validator.element_section(&reader)?;
}
- self.elements =
- reader.into_iter().map(|element| convert_module_element(element?)).collect::<Result<_>>()?;
+ self.elements = reader
+ .into_iter()
+ .map(|element| convert_module_element(element?, &self.global_types))
+ .collect::<Result<_>>()?;
}
Payload::DataSection(reader) => {
check_section("data", !self.data.is_empty())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.data_section(&reader)?;
}
- self.data = reader.into_iter().map(|data| convert_module_data(data?)).collect::<Result<_>>()?;
+ self.data = reader
+ .into_iter()
+ .map(|data| convert_module_data(data?, &self.global_types))
+ .collect::<Result<_>>()?;
}
Payload::DataCountSection { count, range } => {
debug!("Found data count section");
if !self.data.is_empty() {
return Err(ParseError::UnsupportedSection("Data count section after data section".into()));
}
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.data_count_section(count, &range)?;
}
+ #[cfg(not(feature = "validate"))]
+ let _ = (count, range);
}
Payload::FunctionSection(reader) => {
check_section("function", !self.code_type_addrs.is_empty())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.function_section(&reader)?;
}
@@ -188,10 +227,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()));
}
@@ -200,6 +238,7 @@ impl<'a> ModuleReader<'a> {
}
Payload::ImportSection(reader) => {
check_section("import", !self.imports.is_empty())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.import_section(&reader)?;
}
@@ -207,8 +246,29 @@ 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::Memory(_) => self.imported_memory_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::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!(
+ "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);
@@ -217,6 +277,7 @@ impl<'a> ModuleReader<'a> {
}
Payload::ExportSection(reader) => {
check_section("export", !self.exports.is_empty())?;
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.export_section(&reader)?;
}
@@ -228,9 +289,12 @@ impl<'a> ModuleReader<'a> {
return Err(ParseError::DuplicateSection("End section".into()));
}
+ #[cfg(feature = "validate")]
if let Some(validator) = validator.as_mut() {
validator.end(offset)?;
}
+ #[cfg(not(feature = "validate"))]
+ let _ = offset;
self.end_reached = true;
}
Payload::CustomSection(_reader) => {
@@ -250,7 +314,7 @@ impl<'a> ModuleReader<'a> {
pub(crate) fn begin_code_section(
&mut self,
count: u32,
- range: Range<usize>,
+ range: Range<u64>,
size: u32,
validator: Option<&mut Validator>,
options: &ParserOptions,
@@ -262,9 +326,12 @@ impl<'a> ModuleReader<'a> {
self.has_code_section = true;
self.code.reserve(count as usize);
+ #[cfg(feature = "validate")]
if let Some(validator) = validator {
validator.code_section_start(&range)?;
}
+ #[cfg(not(feature = "validate"))]
+ let _ = (range, validator);
#[cfg(parallel_parser)]
{
@@ -294,28 +361,37 @@ impl<'a> ModuleReader<'a> {
let func_validator_allocs = self.func_validator_allocations.take();
let operators_reader_allocs = self.operators_reader_allocations.take().unwrap_or_default();
+ #[cfg(feature = "validate")]
let func_validator = validator
.map(|validator| validator.code_section_entry(&function))
.transpose()?
.map(|func| func.into_validator(func_validator_allocs.unwrap_or_default()));
+ #[cfg(not(feature = "validate"))]
+ let func_validator = {
+ let _ = (validator, func_validator_allocs);
+ None
+ };
let ordinal = self.code.len();
let ty_idx = *self
.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)?;
+ convert_module_code(function, func_validator, operators_reader_allocs, metadata, context, options)?;
- self.code.push(optimize_function_code(
- code,
- options,
- self.code_results[self.code.len()],
- (self.imported_func_count + self.code.len()) as u32,
- self.imported_memory_count,
- )?);
+ self.code.push(code);
self.func_validator_allocations = func_validator_allocs;
self.operators_reader_allocations = Some(operators_reader_allocs);
@@ -332,7 +408,10 @@ impl<'a> ModuleReader<'a> {
#[cfg(parallel_parser)]
if self.pending_functions.is_some() {
+ #[cfg(feature = "validate")]
let func_to_validate = validator.map(|validator| validator.code_section_entry(&function)).transpose()?;
+ #[cfg(not(feature = "validate"))]
+ let func_to_validate = None;
return self.queue_function(crate::parallel::FunctionBodyInput::Borrowed(function), func_to_validate);
}
@@ -343,21 +422,31 @@ impl<'a> ModuleReader<'a> {
pub(crate) fn queue_owned_code_section(
&mut self,
count: u32,
- body_offset: usize,
- section_bytes: Arc<[u8]>,
- mut validator: Option<&mut Validator>,
+ body_offset: u64,
+ section_bytes: Shared<[u8]>,
+ validator: Option<&mut Validator>,
) -> Result<()> {
+ #[cfg(feature = "validate")]
+ let mut validator = validator;
+ #[cfg(not(feature = "validate"))]
+ let _ = validator;
let mut reader = wasmparser::BinaryReader::new(&section_bytes, body_offset);
for _ in 0..count {
let body_reader = reader.read_reader()?;
let body_range = body_reader.range();
- let function = wasmparser::FunctionBody::new(body_reader);
- let func_to_validate =
- validator.as_mut().map(|validator| validator.code_section_entry(&function)).transpose()?;
+ 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);
+ validator.as_mut().map(|validator| validator.code_section_entry(&function)).transpose()?
+ };
+ #[cfg(not(feature = "validate"))]
+ let func_to_validate = None;
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,
@@ -378,7 +467,7 @@ impl<'a> ModuleReader<'a> {
fn queue_function(
&mut self,
body: crate::parallel::FunctionBodyInput<'a>,
- func_to_validate: Option<wasmparser::FuncToValidate<wasmparser::ValidatorResources>>,
+ func_to_validate: Option<FuncToValidate<ValidatorResources>>,
) -> Result<()> {
let ordinal = self.code.len() + self.pending_functions.as_ref().map_or(0, Vec::len);
let results = *self
@@ -404,10 +493,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(())
}
@@ -417,7 +504,7 @@ impl<'a> ModuleReader<'a> {
Ok(())
}
- pub(crate) fn into_module(self, options: &ParserOptions) -> Result<Module> {
+ pub(crate) fn into_module(self) -> Result<Module> {
if !self.end_reached {
return Err(ParseError::EndNotReached);
}
@@ -426,24 +513,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()
@@ -454,31 +523,43 @@ 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()
.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();
+ .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());
- if code.uses_local_memory {
- local_memory_allocation = LocalMemoryAllocation::Eager;
- }
- Arc::new(WasmFunction {
- instructions: code.instructions.into(),
+ Ok(Shared::new(WasmFunction {
+ instructions: code.instructions.into_boxed_slice(),
data: code.data,
locals: code.locals,
params,
results,
- })
+ }))
})
- .collect();
+ .collect::<Result<_>>()?;
Ok(ModuleInner {
funcs,
- func_types: self.func_types,
+ types: self.types,
func_type_idxs,
globals: self.globals,
tables: self.tables,
@@ -488,7 +569,8 @@ impl<'a> ModuleReader<'a> {
exports: self.exports,
elements: self.elements,
memory_types: self.memory_types,
- local_memory_allocation,
+ skip_local_memory_allocation,
+ tags: self.tags,
}
.into())
}
diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs
deleted file mode 100644
index dcb7568..0000000
--- a/crates/parser/src/optimize.rs
+++ /dev/null
@@ -1,984 +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<Instruction>,
- pub(crate) uses_local_memory: bool,
-}
-
-struct CompactOutput {
- instructions: Vec<Instruction>,
- block_start: usize,
- tail_rewritten: bool,
-}
-
-impl Deref for CompactOutput {
- type Target = Vec<Instruction>;
-
- 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<Instruction>,
- function_data: &mut WasmFunctionData,
- options: &ParserOptions,
- function_results: ValueCounts,
- self_func_addr: u32,
- imported_memory_count: u32,
-) -> Result<OptimizeResult> {
- 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<Instruction>,
- boundaries: &[bool],
- function_results: ValueCounts,
- self_func_addr: u32,
-) -> (Vec<Instruction>, Vec<u32>) {
- 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, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c));
- rewrite!(instrs, i, [GlobalGet(global)] => BinOpStackGlobal32(op, global));
- if matches!(op, BinOp::IAdd) {
- rewrite!(instrs, i, [Const32(c)] => AddConst32(c));
- rewrite!(instrs, i, [I32Add] => 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, [GlobalGet(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]);
- }
- }
- 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, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c));
- rewrite!(instrs, i, [GlobalGet(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, [GlobalGet(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 @ (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, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, 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));
- }
- 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, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, 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));
- }
- 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, [Const128(c), LocalGet128(local)] => BinOpLocalConst128(op, local, 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));
- }
- 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,
- [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))
- }
- 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_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) => {
- 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_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, [LocalGet32(local)] => JumpIfLocalZero32 { target_ip: target, local });
- 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,
- [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 },
- });
- 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, [LocalGet32(local)] => JumpIfLocalNonZero32 { target_ip: target, local });
- 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,
- [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 },
- });
- 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<CmpOp> {
- 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 int_bin_op(instr: Instruction) -> Option<BinOp> {
- 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<BinOp> {
- 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<BinOp> {
- int_bin_op(instr).or_else(|| float_bin_op(instr))
-}
-
-fn scalar_const_32(instr: Instruction, op_instr: Instruction) -> Option<i32> {
- 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<i64> {
- 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<ConstIdx> {
- 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<BinOp128> {
- 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::JumpCmpStackConst32 { target_ip: ip, .. }
- | Instruction::JumpCmpStackConst64 { 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<u32> {
- let mut instr = *instr;
- instruction_target_mut(&mut instr).copied()
-}
-
-fn canonicalize_jump_like(source: &[Instruction], instrs: &mut Vec<Instruction>, 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<Instruction>, 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(_)
- )
-}
-
-fn target_boundaries(instructions: &[Instruction], function_data: &WasmFunctionData) -> Result<Vec<bool>> {
- let mut boundaries = alloc::vec![false; instructions.len() + 1];
- 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<bool> {
- let len = instructions.len() as u32;
- 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/parallel.rs b/crates/parser/src/parallel.rs
index 88d1035..69dbac9 100644
--- a/crates/parser/src/parallel.rs
+++ b/crates/parser/src/parallel.rs
@@ -1,10 +1,10 @@
-use crate::module::{FunctionCode, optimize_function_code};
+use crate::module::FunctionCode;
+use crate::validation::{FuncToValidate, FuncValidatorAllocations, ValidatorResources};
use crate::{ParseError, ParserOptions, Result, conversion};
-use alloc::sync::Arc;
use alloc::vec::Vec;
use core::ops::Range;
-use tinywasm_types::ValueCounts;
-use wasmparser::{FuncValidatorAllocations, OperatorsReaderAllocations, ValidatorResources};
+use tinywasm_types::{Shared, ValueCounts};
+use wasmparser::OperatorsReaderAllocations;
pub(crate) enum FunctionBodyInput<'a> {
Borrowed(wasmparser::FunctionBody<'a>),
@@ -14,15 +14,15 @@ pub(crate) enum FunctionBodyInput<'a> {
pub(crate) struct OwnedFunctionBody {
// A deferred stream code section is copied once, then shared by all queued
// function jobs from that section.
- pub section_bytes: Arc<[u8]>,
+ pub section_bytes: Shared<[u8]>,
pub body_range: Range<usize>,
- pub body_offset: usize,
+ pub body_offset: u64,
}
pub(crate) struct PendingFunction<'a> {
pub ordinal: usize,
pub results: ValueCounts,
- pub func_to_validate: Option<wasmparser::FuncToValidate<ValidatorResources>>,
+ pub func_to_validate: Option<FuncToValidate<ValidatorResources>>,
pub ty_idx: u32,
pub body: FunctionBodyInput<'a>,
}
@@ -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)
}
@@ -60,30 +58,35 @@ fn process_function_job(
metadata: &crate::visit::ModuleMetadata,
options: &ParserOptions,
imported_func_count: usize,
- imported_memory_count: u32,
validator_allocs: Option<FuncValidatorAllocations>,
reader_allocs: OperatorsReaderAllocations,
) -> Result<(FunctionCode, Option<FuncValidatorAllocations>, 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"))]
+ let validator = {
+ let _ = (job.func_to_validate, validator_allocs);
+ None
+ };
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, 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)?
+ 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,
- imported_memory_count,
- )?;
-
Ok((code, validator_allocs, reader_allocs))
}
@@ -92,7 +95,6 @@ fn process_chunk<'a>(
metadata: &crate::visit::ModuleMetadata,
options: &ParserOptions,
imported_func_count: usize,
- imported_memory_count: u32,
) -> Result<Vec<FunctionCode>> {
let mut validator_allocs = None;
let mut reader_allocs = OperatorsReaderAllocations::default();
@@ -100,15 +102,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;
@@ -122,11 +117,10 @@ pub(crate) fn process_pending(
metadata: &crate::visit::ModuleMetadata,
options: &ParserOptions,
imported_func_count: usize,
- imported_memory_count: u32,
) -> Result<Vec<FunctionCode>> {
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);
@@ -144,10 +138,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/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::<i64>::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<MemoryOperand>) {
+ [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<MemoryOperand>) {
+ [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::<MemoryFillOperand>::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::<i64>::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<MemoryOperand>) {
+ [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<MemoryOperand>) {
+ [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::<LocalUpdateOperand>::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::<LocalUpdateOperand>::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::<LocalUpdateCmpOperand>::new(target, delta, value.a(), right))?))
+ } else {
+ BinOpLocalConstJumpCmpLocal32(PackedOp::new((packed.op, cmp), data.push_target128(
+ Operand128::<LocalUpdateCmpOperand>::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<i64> {
+ 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<Operand64Idx<i64>> {
+ match instruction {
+ Const64(index) => Ok(index),
+ Const64Imm(value) => data.push64(Operand64::<i64>::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<Operand128Idx<[u8; 16]>> {
+ 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<Instruction> {
+ 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<Instruction> {
+ 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<CmpOp> {
+ 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<CmpOp> {
+ 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<Instruction> {
+ 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<Instruction> {
+ 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<Instruction> {
+ 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<Instruction> {
+ 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<Instruction> {
+ 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<Instruction> {
+ 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<Instruction> {
+ Ok(BinOpStackConstTeeLocalJump32(PackedOp::new(
+ op,
+ data.push_target128(Operand128::<LocalUpdateOperand>::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<Instruction> {
+ if let Some(delta) = op.inc_delta(immediate) {
+ Ok(if global {
+ IncGlobalJump32(
+ data.push_target128(Operand128::<GlobalUpdateOperand>::new(target, delta, address, on_zero))?,
+ )
+ } else {
+ IncLocalJump32(data.push_target128(Operand128::<LocalUpdateOperand>::new(
+ target,
+ delta,
+ address as u16,
+ on_zero,
+ ))?)
+ })
+ } else {
+ Ok(if global {
+ BinOpGlobalConstJump32(PackedOp::new(
+ op,
+ data.push_target128(Operand128::<GlobalUpdateOperand>::new(target, immediate, address, on_zero))?,
+ ))
+ } else {
+ BinOpLocalConstJump32(PackedOp::new(
+ op,
+ data.push_target128(Operand128::<LocalUpdateOperand>::new(target, immediate, address as u16, on_zero))?,
+ ))
+ })
+ }
+}
diff --git a/crates/parser/src/validation.rs b/crates/parser/src/validation.rs
new file mode 100644
index 0000000..b2bb084
--- /dev/null
+++ b/crates/parser/src/validation.rs
@@ -0,0 +1,15 @@
+#[cfg(all(feature = "validate", parallel_parser))]
+pub(crate) use wasmparser::FuncToValidate;
+#[cfg(feature = "validate")]
+pub(crate) use wasmparser::{FuncValidator, FuncValidatorAllocations, Validator, ValidatorResources};
+
+#[cfg(all(not(feature = "validate"), parallel_parser))]
+pub(crate) type FuncToValidate<T> = core::marker::PhantomData<T>;
+#[cfg(not(feature = "validate"))]
+pub(crate) type FuncValidator<T> = core::marker::PhantomData<T>;
+#[cfg(not(feature = "validate"))]
+pub(crate) type FuncValidatorAllocations = ();
+#[cfg(not(feature = "validate"))]
+pub(crate) type Validator = ();
+#[cfg(not(feature = "validate"))]
+pub(crate) type ValidatorResources = ();
diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs
index d0e970b..a362f84 100644
--- a/crates/parser/src/visit.rs
+++ b/crates/parser/src/visit.rs
@@ -1,14 +1,24 @@
-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,
+use crate::{
+ ParserOptions, Result,
+ conversion::{FunctionLoweringContext, convert_heap_type, value_lane},
+ emitter::{Emitter, LabelId},
+ macros::visit::*,
+};
+use alloc::{
+ boxed::Box,
+ collections::{BTreeMap, btree_map::Entry},
+ string::ToString,
+ vec::Vec,
};
-use wasmparser::{
- FuncValidator, FuncValidatorAllocations, FunctionBody, OperatorsReader, OperatorsReaderAllocations,
- ValidatorResources, VisitOperator, VisitSimdOperator,
+use tinywasm_types::{
+ 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};
+
+#[cfg(feature = "validate")]
+use wasmparser::{FuncValidator, FuncValidatorAllocations, ValidatorResources, VisitOperator};
#[derive(Debug, Clone, Copy)]
enum BlockKind {
@@ -16,180 +26,319 @@ enum BlockKind {
Block,
Loop,
If,
+ TryTable,
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(crate) enum OperandSize {
- S32,
- S64,
- S128,
+struct ControlFrame<'a> {
+ kind: BlockKind,
+ has_else: bool,
+ loop_start: Option<LabelId>,
+ end: Option<LabelId>,
+ else_entry: Option<LabelId>,
+ height: usize,
+ base: ValueCounts,
+ signature: BlockSignature<'a>,
+ unreachable: bool,
+ entry_unreachable: bool,
+ end_reachable: bool,
+}
+
+/// Module-owned physical lane signature, borrowed by control frames.
+pub(crate) struct Signature {
+ pub params: Vec<ValueLane>,
+ results: Vec<ValueLane>,
+}
+
+#[derive(Clone, Copy)]
+enum BlockSignature<'a> {
+ Empty,
+ Result(ValueLane),
+ Function(&'a Signature),
}
-impl OperandSize {
- fn choose<T>(self, s32: T, s64: T, s128: T) -> T {
+impl BlockSignature<'_> {
+ fn params(&self) -> &[ValueLane] {
match self {
- Self::S32 => s32,
- Self::S64 => s64,
- Self::S128 => s128,
+ Self::Function(signature) => &signature.params,
+ _ => &[],
}
}
-}
-impl From<wasmparser::ValType> 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,
+ fn results(&self) -> &[ValueLane] {
+ match self {
+ Self::Empty => &[],
+ Self::Result(lane) => core::slice::from_ref(lane),
+ Self::Function(signature) => &signature.results,
}
}
}
-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,
+pub(crate) struct ModuleMetadata {
+ signatures: Vec<Option<Signature>>,
+ functions: Vec<u32>,
+ globals: Vec<ValueLane>,
+ memories: Vec<ValueLane>,
+ tables: Vec<ValueLane>,
+ tags: Vec<u32>,
+ aggregate_fields: Vec<AggregateFields>,
+ imported_memories: u32,
+}
+
+pub(crate) struct FunctionDataBuilder {
+ pub(crate) operands64: Vec<Operand64>,
+ pub(crate) operands128: Vec<Operand128>,
+ pub(crate) branch_table_targets: Vec<u32>,
+ pub(crate) exception_handlers: Vec<ExceptionHandler>,
+ deduplicate64: Option<BTreeMap<Operand64, u32>>,
+ deduplicate128: Option<BTreeMap<Operand128, u32>>,
+}
+
+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),
}
}
-}
-impl From<MemoryArch> for OperandSize {
- fn from(arch: MemoryArch) -> Self {
- match arch {
- MemoryArch::I32 => Self::S32,
- MemoryArch::I64 => Self::S64,
+ /// Allocates an immutable 64-bit operand, reusing it when deduplication is enabled.
+ pub(crate) fn push64<T>(&mut self, operand: Operand64<T>) -> Result<Operand64Idx<T>> {
+ let operand = operand.cast();
+ 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(entry) = entry {
+ entry.insert(index);
}
+ Ok(Operand64Idx::new(index))
}
-}
-struct ControlFrame {
- kind: BlockKind,
- has_else: bool,
- start_ip: usize,
- branch_jumps: Vec<usize>,
- height: usize,
- base: ValueCounts,
- params: Vec<OperandSize>,
- results: Vec<OperandSize>,
- unreachable: bool,
- entry_unreachable: bool,
- end_reachable: bool,
-}
+ /// Allocates an immutable 128-bit operand, reusing it when deduplication is enabled.
+ pub(crate) fn push128<T>(&mut self, operand: Operand128<T>) -> Result<Operand128Idx<T>> {
+ let operand = operand.cast();
+ 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(entry) = entry {
+ entry.insert(index);
+ }
+ Ok(Operand128Idx::new(index))
+ }
-#[derive(Clone)]
-pub(crate) struct Signature {
- pub params: Vec<OperandSize>,
- results: Vec<OperandSize>,
-}
+ /// Allocates a private mutable target operand outside immutable deduplication.
+ pub(crate) fn push_target64<T>(&mut self, operand: Operand64<T>) -> Result<Operand64Idx<T>> {
+ 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(index))
+ }
-pub(crate) struct ModuleMetadata {
- signatures: Vec<Signature>,
- functions: Vec<u32>,
- globals: Vec<OperandSize>,
- memories: Vec<OperandSize>,
- tables: Vec<OperandSize>,
+ /// Allocates a private mutable target operand outside immutable deduplication.
+ pub(crate) fn push_target128<T>(&mut self, operand: Operand128<T>) -> Result<Operand128Idx<T>> {
+ 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(index))
+ }
+
+ pub(crate) fn operand64<T>(&self, index: Operand64Idx<T>) -> Operand64<T> {
+ self.operands64[index.index()].cast()
+ }
+
+ pub(crate) fn operand128<T>(&self, index: Operand128Idx<T>) -> Operand128<T> {
+ self.operands128[index.index()].cast()
+ }
+
+ 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(),
+ }
+ }
}
-#[derive(Default)]
-struct FunctionDataBuilder {
- v128_constants: Vec<[u8; 16]>,
- branch_table_targets: Vec<u32>,
+enum AggregateFields {
+ Other,
+ Struct(Box<[ValueLane]>),
+ Array(ValueLane),
}
pub(crate) struct FunctionBuilder<'a> {
- instructions: Vec<Instruction>,
+ emitter: Emitter,
data: FunctionDataBuilder,
- control_stack: Vec<ControlFrame>,
- operand_stack: Vec<OperandSize>,
+ control_stack: Vec<ControlFrame<'a>>,
+ operand_stack: Vec<ValueLane>,
lane_counts: ValueCounts,
metadata: &'a ModuleMetadata,
- local_types: Vec<OperandSize>,
+ local_types: Vec<ValueLane>,
local_addr_map: Vec<u16>,
+ uses_local_memory: bool,
}
impl<'a> FunctionBuilder<'a> {
+ /// Creates lowering state with a borrowed function signature.
pub(crate) fn new(
metadata: &'a ModuleMetadata,
- signature: Signature,
- local_types: Vec<OperandSize>,
+ signature: &'a Signature,
+ local_types: Vec<ValueLane>,
local_addr_map: Vec<u16>,
body_size: usize,
+ context: FunctionLoweringContext,
+ options: &ParserOptions,
) -> Self {
Self {
local_types,
local_addr_map,
metadata,
- instructions: Vec::with_capacity(body_size.min(1024)),
- data: FunctionDataBuilder::default(),
+ 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,
+ signature: BlockSignature::Function(signature),
unreachable: false,
entry_unreachable: false,
end_reachable: false,
}],
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(Operand64Idx<(u32, u32)>) -> Instruction,
+ ) -> Result<()> {
+ let size = self.metadata.struct_field(type_index, field_index)?;
+ let operand = self.push64(Operand64::<(u32, u32)>::new(type_index, field_index))?;
+ self.emit(&[ValueLane::S32], &[size], instruction(operand))
+ }
+
+ fn push64<T>(&mut self, operand: Operand64<T>) -> Result<Operand64Idx<T>> {
+ self.data.push64(operand)
+ }
+
+ fn push128<T>(&mut self, operand: Operand128<T>) -> Result<Operand128Idx<T>> {
+ self.data.push128(operand)
+ }
}
+#[cfg(feature = "validate")]
struct ValidateThenVisit<'a, 'm> {
- validator: Option<&'a mut FuncValidator<ValidatorResources>>,
+ validator: &'a mut FuncValidator<ValidatorResources>,
builder: &'a mut FunctionBuilder<'m>,
- position: usize,
+ position: u64,
}
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: &[FuncType],
+ types: &TypeSection,
code_type_addrs: &[u32],
imports: &[Import],
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());
+ let imported_memories =
+ imports.iter().filter(|import| matches!(import.kind, ImportKind::Memory(_))).count() as u32;
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())),
+ ImportKind::Tag(ty) => tag_types.push(ty.type_idx),
}
}
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())));
+ tag_types.extend(tags.iter().map(|tag| tag.type_idx));
let signatures = types
+ .types
+ .iter()
+ .map(|ty| {
+ ty.as_func().map(|ty| Signature {
+ params: ty.params().iter().map(ValueLane::from).collect(),
+ results: ty.results().iter().map(ValueLane::from).collect(),
+ })
+ })
+ .collect();
+ let aggregate_fields = types
+ .types
.iter()
- .map(|ty| Signature {
- params: ty.params().iter().map(OperandSize::from).collect(),
- results: ty.results().iter().map(OperandSize::from).collect(),
+ .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, globals: global_sizes, memories: memory_sizes, tables: table_sizes }
+ Self {
+ signatures,
+ functions,
+ globals: global_sizes,
+ memories: memory_sizes,
+ tables: table_sizes,
+ tags: tag_types,
+ aggregate_fields,
+ imported_memories,
+ }
}
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> {
@@ -200,59 +349,106 @@ impl ModuleMetadata {
self.signature(ty)
}
- fn global_size(&self, idx: u32) -> Result<OperandSize> {
+ 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<ValueLane> {
Self::indexed_size(&self.globals, "global", idx)
}
- fn memory_size(&self, idx: u32) -> Result<OperandSize> {
+ fn memory_size(&self, idx: u32) -> Result<ValueLane> {
Self::indexed_size(&self.memories, "memory", idx)
}
- fn table_size(&self, idx: u32) -> Result<OperandSize> {
+ fn table_size(&self, idx: u32) -> Result<ValueLane> {
Self::indexed_size(&self.tables, "table", idx)
}
- fn indexed_size(sizes: &[OperandSize], entity: &str, idx: u32) -> Result<OperandSize> {
+ fn indexed_size(sizes: &[ValueLane], entity: &str, idx: u32) -> Result<ValueLane> {
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) -> ValueLane {
+ match storage {
+ StorageType::I8 | StorageType::I16 => ValueLane::S32,
+ StorageType::Value(ref ty) => ValueLane::from(ty),
+ }
+ }
+
+ fn struct_fields(&self, idx: u32) -> Result<&[ValueLane]> {
+ self.aggregate_fields
+ .get(idx as usize)
+ .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<ValueLane> {
+ 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<ValueLane> {
+ self.aggregate_fields
+ .get(idx as usize)
+ .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}")))
+ }
}
+#[cfg(feature = "validate")]
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>> {
+ fn simd_visitor(&mut self) -> Option<&mut dyn VisitSimdOperator<'a, Output = Result<()>>> {
Some(self)
}
}
+#[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);
}
-pub(crate) fn process_operators_and_validate(
- mut validator: Option<FuncValidator<ValidatorResources>>,
+pub(crate) fn process_operators(
body: FunctionBody<'_>,
- local_types: Vec<OperandSize>,
- local_addr_map: Vec<u16>,
+ locals: (Vec<ValueLane>, Vec<u16>),
metadata: &ModuleMetadata,
- ty_idx: u32,
+ context: FunctionLoweringContext,
allocs: OperatorsReaderAllocations,
-) -> Result<(Vec<Instruction>, WasmFunctionData, Option<FuncValidatorAllocations>, OperatorsReaderAllocations)> {
+ options: &ParserOptions,
+) -> Result<(Vec<Instruction>, 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)?.clone();
- let mut builder = FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size);
+ let signature = metadata.signature(context.ty_idx)?;
+ let mut builder =
+ FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, context, options);
while !reader.eof() {
let position = reader.original_position();
let res = reader
- .visit_operator(&mut ValidateThenVisit { validator: validator.as_mut(), builder: &mut builder, position })
+ .visit_operator(&mut builder)
.map_err(|e| crate::ParseError::ParseError { message: e.to_string(), offset: position });
if let Err(e) = res.flatten() {
@@ -262,19 +458,49 @@ pub(crate) fn process_operators_and_validate(
}
reader.finish()?;
+ let instructions = builder.emitter.finish(&mut builder.data)?;
+ Ok((instructions, builder.data, builder.uses_local_memory, reader.into_allocations()))
+}
- let validator_allocations = validator.map(FuncValidator::into_allocations);
- let data = WasmFunctionData {
- v128_constants: builder.data.v128_constants.into_boxed_slice(),
- branch_table_targets: builder.data.branch_table_targets.into_boxed_slice(),
- };
- Ok((builder.instructions, data, validator_allocations, reader.into_allocations()))
+#[cfg(feature = "validate")]
+pub(crate) fn process_operators_and_validate(
+ mut validator: FuncValidator<ValidatorResources>,
+ body: FunctionBody<'_>,
+ locals: (Vec<ValueLane>, Vec<u16>),
+ metadata: &ModuleMetadata,
+ context: FunctionLoweringContext,
+ allocs: OperatorsReaderAllocations,
+ options: &ParserOptions,
+) -> Result<(Vec<Instruction>, 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(context.ty_idx)?;
+ let mut builder =
+ FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, context, options);
+
+ while !reader.eof() {
+ let position = reader.original_position();
+ let res = reader
+ .visit_operator(&mut ValidateThenVisit { validator: &mut validator, builder: &mut builder, position })
+ .map_err(|e| crate::ParseError::ParseError { message: e.to_string(), offset: position });
+
+ if let Err(e) = res.flatten() {
+ core::hint::cold_path();
+ return Err(e);
+ }
+ }
+
+ reader.finish()?;
+ 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)
}
@@ -282,29 +508,41 @@ 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 }
- 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,
@@ -313,6 +551,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,
@@ -330,40 +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_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 }
@@ -371,71 +653,117 @@ 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] => [] {
- visit_memory_init(data_index: u32, memory: u32) => MemoryInit,
- 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 }
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,
+ }
+ 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_call(&mut self, function_index: u32) -> Self::Output {
- let signature = self.metadata.function_signature(function_index)?.clone();
- self.emit(&signature.params, &signature.results, Instruction::Call(function_index))
+ 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.emitter.emit(Instruction::StructNew(type_index))?;
+ Ok(())
+ }
+
+ 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_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.emit(&inputs, &signature.results, Instruction::CallIndirect(type_index, table_index))
+ 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_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);
- self.emit(&inputs, &signature.results, Instruction::CallRef(type_index))
+ 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_return_call(&mut self, function_index: u32) -> Self::Output {
- let signature = self.metadata.function_signature(function_index)?.clone();
+ 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.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) -> 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.push64(Operand64::<(u32, u32)>::new(type_index, array_size))?;
+ self.emitter.emit(Instruction::ArrayNewFixed(operand))?;
+ Ok(())
+ }
+
+ fn visit_call(&mut self, function_index: u32) -> Result<()> {
+ let signature = self.metadata.function_signature(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) -> Result<()> {
+ let table_size = self.metadata.table_size(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_boundary(&signature.params, &signature.results, Instruction::CallIndirect(operand))
+ }
+
+ fn visit_call_ref(&mut self, type_index: u32) -> Result<()> {
+ let signature = self.metadata.signature(type_index)?;
+ self.pop_expect(ValueLane::S32)?;
+ self.emit_boundary(&signature.params, &signature.results, Instruction::CallRef(type_index))
+ }
+
+ 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 {
- 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, &[])?;
+ 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();
- self.instructions.push(Instruction::ReturnCallIndirect(type_index, table_index));
+ 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 {
- let signature = self.metadata.signature(type_index)?.clone();
- let mut inputs = signature.params;
- inputs.push(OperandSize::S32);
- self.apply_effect(&inputs, &[])?;
+ 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.choose(
+ let instruction = size.select(
Instruction::GlobalSet32(global_index),
Instruction::GlobalSet64(global_index),
Instruction::GlobalSet128(global_index),
@@ -443,291 +771,411 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
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);
- self.emit(&[size], &[], instruction)
+ fn visit_global_get(&mut self, global_index: u32) -> Result<()> {
+ let size = self.metadata.global_size(global_index)?;
+ 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) -> Result<()> {
+ let size = self.operand_stack.last().copied().unwrap_or(ValueLane::S32);
+ 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 {
- 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)
+ 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.choose(
- 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.choose(
- 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)?;
- 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),
- _ => 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)],
- };
- self.instructions.extend(instructions);
- } else {
- self.instructions.push(size.choose(
- Instruction::LocalTee32(local_idx),
- Instruction::LocalTee64(local_idx),
- Instruction::LocalTee128(local_idx),
- ));
+ // 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()]),
}
- Ok(())
}
- 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 {
- self.pop_expect(OperandSize::S32)?;
- self.instructions.push(Instruction::JumpIfZero32(0));
- self.push_control(BlockKind::If, ty, Some(self.instructions.len() - 1))
+ fn visit_if(&mut self, ty: wasmparser::BlockType) -> Result<()> {
+ self.pop_expect(ValueLane::S32)?;
+ 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) -> Result<()> {
+ 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_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 {
+ 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_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,
+ has_else: false,
+ loop_start: None,
+ end: Some(body_end),
+ else_entry: None,
+ height,
+ base,
+ signature,
+ unreachable: entry_unreachable,
+ entry_unreachable,
+ end_reachable: false,
+ });
+ Ok(())
+ }
+
+ fn visit_throw(&mut self, tag_index: u32) -> Result<()> {
+ let signature = self.metadata.tag_signature(tag_index)?;
+ self.apply_effect(&signature.params, &[])?;
+ self.emitter.emit_boundary(Instruction::Throw(tag_index))?;
+ self.mark_unreachable();
+ Ok(())
+ }
+
+ fn visit_throw_ref(&mut self) -> Result<()> {
+ self.apply_effect(&[ValueLane::S32], &[])?;
+ 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(&params)?;
+ 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 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 {
- self.pop_expect(OperandSize::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);
+ fn visit_br_if(&mut self, depth: u32) -> Result<()> {
+ self.pop_expect(ValueLane::S32)?;
+ 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::<Result<Vec<_>, wasmparser::Error>>()?;
- self.pop_expect(OperandSize::S32)?;
+ self.pop_expect(ValueLane::S32)?;
let default_depth = targets.default();
- let len = ts.len() as u32;
let target_depths: Vec<u32> = ts;
-
- 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));
-
- struct PadInfo {
- depth: u32,
- pad_start: usize,
- jump_or_ret_ip: usize,
- is_return: bool,
- }
- let mut pads: Vec<PadInfo> = 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 });
+ labels.push(label);
}
-
- 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(default_ip, _, _) = &mut self.instructions[header_ip] {
- *default_ip = 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);
+ 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 {
- self.emit(&[], &[OperandSize::S32], Instruction::Const32(val.bits() as i32))
+ 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 {
- self.emit(&[], &[OperandSize::S64], Instruction::Const64(val.bits() as i64))
+ #[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_table_copy(&mut self, dst_table: u32, src_table: u32) -> Self::Output {
+ 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::<i64>::new(value))?)
+ };
+ self.emit(&[], &[ValueLane::S64], instruction)
+ }
+
+ 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 == OperandSize::S32 || src == OperandSize::S32 { OperandSize::S32 } else { OperandSize::S64 };
- self.emit(&[dst, src, len], &[], Instruction::TableCopy { dst_table, src_table })
+ let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 };
+ 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)?;
- let len = if dst == OperandSize::S32 || src == OperandSize::S32 { OperandSize::S32 } else { OperandSize::S64 };
- self.emit(&[dst, src, len], &[], Instruction::MemoryCopy { dst_mem, 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.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) -> Result<()> {
+ let dst = self.metadata.memory_size(memory)?;
+ self.mark_memory(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) -> Result<()> {
+ let address = self.metadata.table_size(table)?;
+ let operand = self.push64(Operand64::<(u32, u32)>::new(elem_index, table))?;
+ self.emit(&[address, ValueLane::S32, ValueLane::S32], &[], Instruction::TableInit(operand))
}
- // 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_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_ref_as_non_null(&mut self) -> Self::Output {
- self.emit(&[OperandSize::S32], &[OperandSize::S32], Instruction::RefAsNonNull)
+ 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_br_on_null(&mut self, relative_depth: u32) -> Self::Output {
- self.pop_expect(OperandSize::S32)?;
- let fallthrough_jump = self.instructions.len();
- self.instructions.push(Instruction::JumpIfRefNonNull(0));
+ 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) -> 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) -> Result<()> {
+ let operand = self.push64(Operand64::<(u32, u32)>::new(type_index_dst, type_index_src))?;
+ self.emit(&[ValueLane::S32; 5], &[], Instruction::ArrayCopy(operand))
+ }
+
+ fn visit_br_on_cast(
+ &mut self,
+ relative_depth: u32,
+ _from_ref_type: wasmparser::RefType,
+ to_ref_type: wasmparser::RefType,
+ ) -> Result<()> {
+ self.emit_cast_branch(relative_depth, to_ref_type, false)
+ }
+
+ fn visit_br_on_cast_fail(
+ &mut self,
+ relative_depth: u32,
+ _from_ref_type: wasmparser::RefType,
+ to_ref_type: wasmparser::RefType,
+ ) -> Result<()> {
+ self.emit_cast_branch(relative_depth, to_ref_type, true)
+ }
+
+ fn visit_br_on_null(&mut self, relative_depth: u32) -> Result<()> {
+ self.pop_expect(ValueLane::S32)?;
+ 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.push_sizes(&[OperandSize::S32])
+ self.emitter.bind(fallthrough)?;
+ self.push_sizes(&[ValueLane::S32])
}
- fn visit_br_on_non_null(&mut self, relative_depth: u32) -> Self::Output {
- self.pop_expect(OperandSize::S32)?;
- let fallthrough_jump = self.instructions.len();
- self.instructions.push(Instruction::JumpIfRefNull(0));
- self.push_sizes(&[OperandSize::S32])?;
+ fn visit_br_on_non_null(&mut self, relative_depth: u32) -> Result<()> {
+ self.pop_expect(ValueLane::S32)?;
+ 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(OperandSize::S32)?;
+ 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<wasmparser::ValType>) -> Self::Output {
- let sizes: Vec<_> = tys.into_iter().map(OperandSize::from).collect();
+ fn visit_typed_select_multi(&mut self, tys: Vec<wasmparser::ValType>) -> Result<()> {
+ 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)
+ 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)
}
}
@@ -739,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()))
}
};
@@ -758,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,
@@ -847,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,
@@ -879,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,
@@ -917,24 +1370,45 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> {
}
}
- fn visit_i8x16_shuffle(&mut self, lanes: [u8; 16]) -> Self::Output {
- self.emit(
- &[OperandSize::S128, OperandSize::S128],
- &[OperandSize::S128],
- Instruction::I8x16Shuffle(self.data.v128_constants.len() as u32),
- )?;
- self.data.v128_constants.push(lanes);
- Ok(())
+ 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 {
- self.emit(&[], &[OperandSize::S128], Instruction::Const128(self.data.v128_constants.len() as u32))?;
- self.data.v128_constants.push(*value.bytes());
- Ok(())
+ 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,
+ target: wasmparser::RefType,
+ branch_on_fail: bool,
+ ) -> Result<()> {
+ self.pop_expect(ValueLane::S32)?;
+ let target = convert_heap_type(target.heap_type(), target.is_nullable())?;
+ 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.emitter.bind(fallthrough)?;
+ Ok(())
+ }
+
fn is_unreachable(&self) -> bool {
self.control_stack.last().is_none_or(|frame| frame.unreachable)
}
@@ -946,7 +1420,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)
@@ -959,12 +1433,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)
@@ -975,7 +1449,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(());
@@ -988,25 +1462,43 @@ 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(())
+ 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.
@@ -1025,31 +1517,42 @@ impl FunctionBuilder<'_> {
}
}
+ fn block_signature(&self, ty: wasmparser::BlockType) -> Result<BlockSignature<'a>> {
+ Ok(match ty {
+ wasmparser::BlockType::Empty => BlockSignature::Empty,
+ wasmparser::BlockType::Type(ty) => BlockSignature::Result(value_lane(ty)),
+ wasmparser::BlockType::FuncType(idx) => BlockSignature::Function(self.metadata.signature(idx)?),
+ })
+ }
+
/// 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<usize>) -> 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::FuncType(idx) => self.metadata.signature(idx)?.clone(),
- };
- for &size in signature.params.iter().rev() {
+ fn push_control(&mut self, kind: BlockKind, ty: wasmparser::BlockType, else_entry: Option<LabelId>) -> 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,
@@ -1058,34 +1561,32 @@ 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;
+ 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 Some(self.lane_counts.c64) != base.c64.checked_add(keep.c64) {
+ self.emitter.emit(Instruction::DropKeep64 { base: base.c64, keep: keep.c64 })?;
}
- self.instructions.push(Instruction::DropKeep((base, keep).into()));
+ 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;
- }
- _ => {}
- }
+ 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: &[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
@@ -1098,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 => {
- 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);
- }
- }
}