diff options
| author | Henry Gressmann <mail@henrygressmann.de> | 2026-08-17 20:07:51 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-08-17 20:07:51 +0200 |
| commit | 358a183e5c12c32b8836acf9c71799f56e00b036 (patch) | |
| tree | ffe63de847cebf5935951454eb8d76d9c76c222a /crates/parser/src | |
| parent | a42cb3434bd79accb6a49298f498e016e9c93b9e (diff) | |
chore: reduce instruction enum size (#52)
this is a fairly big commit since I've been just playing around with
this
for a while now. the main goal is to reduce instruction size by moving
some operands into two separate vecs. memory operations still seem like
the biggest issue right now, so as a follow op I'll probably remove the
public linear memory trait again but let's see how this goes first.
performance wise this is about the same as before, but
serialization/deserialization
is about 20% faster now.
Signed-off-by: Henry <mail@henrygressmann.de>
---------
Signed-off-by: Henry <mail@henrygressmann.de>
Diffstat (limited to 'crates/parser/src')
| -rw-r--r-- | crates/parser/src/conversion.rs | 33 | ||||
| -rw-r--r-- | crates/parser/src/lib.rs | 16 | ||||
| -rw-r--r-- | crates/parser/src/macros.rs | 155 | ||||
| -rw-r--r-- | crates/parser/src/module.rs | 42 | ||||
| -rw-r--r-- | crates/parser/src/optimize.rs | 1201 | ||||
| -rw-r--r-- | crates/parser/src/optimize/mod.rs | 4 | ||||
| -rw-r--r-- | crates/parser/src/optimize/rewrite.rs | 1397 | ||||
| -rw-r--r-- | crates/parser/src/optimize/targets.rs | 290 | ||||
| -rw-r--r-- | crates/parser/src/parallel.rs | 12 | ||||
| -rw-r--r-- | crates/parser/src/visit.rs | 281 |
10 files changed, 1989 insertions, 1442 deletions
diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 480a8d0..b94ebe6 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -1,7 +1,7 @@ use crate::validation::{FuncValidator, FuncValidatorAllocations, ValidatorResources}; #[cfg(feature = "validate")] use crate::visit::process_operators_and_validate; -use crate::{Result, module::FunctionCode, visit::process_operators}; +use crate::{ParserOptions, Result, module::FunctionCode, visit::process_operators}; use alloc::{boxed::Box, format, vec::Vec}; use tinywasm_types::*; use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations, UnpackedIndex}; @@ -149,6 +149,7 @@ pub(crate) fn convert_module_code( reader_allocs: OperatorsReaderAllocations, metadata: &crate::visit::ModuleMetadata, ty_idx: u32, + options: &ParserOptions, ) -> Result<(FunctionCode, Option<FuncValidatorAllocations>, OperatorsReaderAllocations)> { let locals_reader = func.get_locals_reader()?; #[cfg(feature = "validate")] @@ -194,32 +195,40 @@ pub(crate) fn convert_module_code( let (body, data, validator_allocs, reader_allocs) = process_operators_and_validate( validator, func, - local_types, - local_addr_map, + (local_types, local_addr_map), metadata, ty_idx, reader_allocs, + options.deduplicate_operands(), )?; (body, data, Some(validator_allocs), reader_allocs) } None => { - let (body, data, reader_allocs) = - process_operators(func, local_types, local_addr_map, metadata, ty_idx, reader_allocs)?; + let (body, data, reader_allocs) = process_operators( + func, + (local_types, local_addr_map), + metadata, + ty_idx, + reader_allocs, + options.deduplicate_operands(), + )?; (body, data, None, reader_allocs) } }; #[cfg(not(feature = "validate"))] let (body, data, validator_allocs, reader_allocs) = { let _ = validator; - let (body, data, reader_allocs) = - process_operators(func, local_types, local_addr_map, metadata, ty_idx, reader_allocs)?; + let (body, data, reader_allocs) = process_operators( + func, + (local_types, local_addr_map), + metadata, + ty_idx, + reader_allocs, + options.deduplicate_operands(), + )?; (body, data, None, reader_allocs) }; - Ok(( - FunctionCode { instructions: body, data, locals: local_counts, uses_local_memory: false }, - validator_allocs, - reader_allocs, - )) + Ok((FunctionCode { instructions: body, data, locals: local_counts }, validator_allocs, reader_allocs)) } pub(crate) fn convert_rec_group(ty: wasmparser::RecGroup, group_start: u32, types: &mut Vec<SubType>) -> Result<u32> { diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs index 8db7920..90e239b 100644 --- a/crates/parser/src/lib.rs +++ b/crates/parser/src/lib.rs @@ -65,6 +65,10 @@ pub struct ParserOptions { pub optimize_local_memory_allocation: bool, /// Whether to run the peephole rewrite optimizer. pub optimize_rewrite: bool, + /// Whether to deduplicate immutable function operands while parsing. + /// + /// This uses more parse CPU to reduce precompiled module and archive size. + pub deduplicate_operands: bool, #[cfg(parallel_parser)] /// Number of threads to use for parallel parsing. @@ -83,6 +87,7 @@ impl Default for ParserOptions { validation: cfg!(feature = "validate"), optimize_local_memory_allocation: true, optimize_rewrite: true, + deduplicate_operands: false, #[cfg(parallel_parser)] parser_threads: None, } @@ -134,6 +139,17 @@ impl ParserOptions { self.optimize_rewrite } + /// Enable or disable parse-time deduplication of immutable function operands. + pub const fn with_operand_deduplication(mut self, enabled: bool) -> Self { + self.deduplicate_operands = enabled; + self + } + + /// Returns whether immutable function operands are deduplicated while parsing. + pub const fn deduplicate_operands(&self) -> bool { + self.deduplicate_operands + } + #[cfg(parallel_parser)] /// Set the number of threads for parallel parsing. /// diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs index 9fa7a01..5e675e6 100644 --- a/crates/parser/src/macros.rs +++ b/crates/parser/src/macros.rs @@ -72,10 +72,17 @@ pub(crate) mod visit { ) => { fn $visit(&mut self, memarg: wasmparser::MemArg $(, $lane: $ty)?) -> Self::Output { let address = self.metadata.memory_size(memarg.memory)?; + let memory_arg_idx = self.push_operand(MemoryArg::new(memarg.offset, memarg.memory))?; lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*] - Instruction::$instr(MemoryArg::new(memarg.offset, memarg.memory) $(, $lane)?).into()) + lowering_ops!(@memory_instruction $instr memory_arg_idx $(, $lane)?)) } }; + (@memory_instruction $instr:ident $memory_arg_idx:ident) => { + Instruction::$instr($memory_arg_idx) + }; + (@memory_instruction $instr:ident $memory_arg_idx:ident, $lane:ident) => { + Instruction::$instr(tinywasm_types::MemoryLaneArg { memory_arg_idx: $memory_arg_idx, lane: $lane }) + }; (@global $inputs:tt => $outputs:tt $($operator:tt)*) => { lowering_ops!(@resolved global_size $inputs => $outputs $($operator)*); }; @@ -191,6 +198,20 @@ pub(crate) mod optimize { ($instructions:ident, $read:ident, $consumed:expr => $out:expr) => { replace!($instructions, $read, $consumed => [$out]); }; + ($instructions:ident, *$read:ident, $consumed:expr => [$($out:expr),+ $(,)?]) => {{ + const { + assert!($consumed >= 1 && $consumed <= 3); + assert!([$(stringify!($out)),+].len() <= $consumed + 1); + } + let replacements = [$($out),+]; + let start = *$read - $consumed; + $instructions[start..start + replacements.len()].copy_from_slice(&replacements); + $instructions.truncate(start + replacements.len()); + *$read = $instructions.len() - 1; + }}; + ($instructions:ident, *$read:ident, $consumed:expr => $out:expr) => { + replace!($instructions, *$read, $consumed => [$out]) + }; } macro_rules! rewrite { @@ -201,16 +222,13 @@ pub(crate) mod optimize { }; ($instructions:ident, $read:ident, [$($pattern:pat),+] $(if ($($guard:tt)+))? => $body:block $(,)?) => {{ const CONSUMED: usize = [$(stringify!($pattern)),+].len(); - if !$instructions.tail_rewritten - && $read < $instructions.len() - && $read >= $instructions.block_start + CONSUMED - { + if $read >= $instructions.block_start + CONSUMED { let previous: [Instruction; CONSUMED] = $instructions[$read - CONSUMED..$read].try_into().unwrap(); if let [$($pattern),+] = previous $( && $($guard)+ )? { - $instructions.tail_rewritten = true; $body + continue; } } }}; @@ -221,128 +239,5 @@ pub(crate) mod optimize { }; } - macro_rules! define_local_source_resolver { - ( - $name:ident, - get = $get:ident, - tee = $tee:ident, - set = $set:ident, - binop_local_local_tee = $lltee:ident, - binop_local_local_set = $llset:ident, - binop_local_const_tee = $lctee:ident, - binop_local_const_set = $lcset:ident - $(, load_local_tee = $loadtee:ident, load_local_set = $loadset:ident)? - ) => { - fn $name(instr: Instruction) -> Option<(Option<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 {replace, rewrite}; } diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index 3d38ad6..8138666 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -11,6 +11,12 @@ use wasmparser::{OperatorsReaderAllocations, Payload}; pub(crate) struct FunctionCode { pub instructions: Vec<Instruction>, + pub data: crate::visit::FunctionDataBuilder, + pub locals: ValueCounts, +} + +pub(crate) struct OptimizedFunctionCode { + pub instructions: Vec<Instruction>, pub data: WasmFunctionData, pub locals: ValueCounts, pub uses_local_memory: bool, @@ -22,19 +28,15 @@ pub(crate) fn optimize_function_code( 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) +) -> Result<OptimizedFunctionCode> { + let optimized = + optimize::optimize_instructions(code.instructions, &mut code.data, options, function_results, self_func_addr)?; + let data = code.data.finish(); + let uses_local_memory = optimized + .instructions + .iter() + .any(|instruction| instruction.memory_addr(&data).is_some_and(|memory| memory >= imported_memory_count)); + Ok(OptimizedFunctionCode { instructions: optimized.instructions, data, locals: code.locals, uses_local_memory }) } #[derive(Default)] @@ -53,7 +55,7 @@ pub(crate) struct ModuleReader<'a> { pub(crate) code_type_addrs: Box<[u32]>, code_results: Box<[ValueCounts]>, pub(crate) exports: Arc<[Export]>, - pub(crate) code: Vec<FunctionCode>, + pub(crate) code: Vec<OptimizedFunctionCode>, pub(crate) globals: Box<[Global]>, pub(crate) tables: Box<[TableDefinition]>, pub(crate) memory_types: Box<[MemoryType]>, @@ -402,7 +404,7 @@ impl<'a> ModuleReader<'a> { let metadata = self.translation_metadata(); let (code, func_validator_allocs, operators_reader_allocs) = - convert_module_code(function, func_validator, operators_reader_allocs, metadata, ty_idx)?; + convert_module_code(function, func_validator, operators_reader_allocs, metadata, ty_idx, options)?; self.code.push(optimize_function_code( code, @@ -565,7 +567,7 @@ impl<'a> ModuleReader<'a> { .into_iter() .zip(self.code_type_addrs) .zip(self.code_results) - .map(|((code, ty_idx), results)| { + .map(|((code, ty_idx), results)| -> Result<_> { let ty = self.types.get(ty_idx).and_then(SubType::as_func).expect("function type was checked while parsing"); let params = ValueCounts::from_iter(ty.params()); @@ -573,15 +575,15 @@ impl<'a> ModuleReader<'a> { local_memory_allocation = LocalMemoryAllocation::Eager; } - Arc::new(WasmFunction { - instructions: code.instructions.into(), + Ok(Arc::new(WasmFunction { + instructions: code.instructions.into_boxed_slice(), data: code.data, locals: code.locals, params, results, - }) + })) }) - .collect(); + .collect::<Result<_>>()?; Ok(ModuleInner { funcs, diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs deleted file mode 100644 index 969d686..0000000 --- a/crates/parser/src/optimize.rs +++ /dev/null @@ -1,1201 +0,0 @@ -use crate::macros::optimize::*; -use crate::{ParseError, ParserOptions, Result}; -use alloc::vec::Vec; -use core::ops::{Deref, DerefMut}; -use tinywasm_types::{BinOp, BinOp128, CmpOp, ConstIdx, Instruction, ValueCounts, WasmFunctionData}; - -pub(crate) struct OptimizeResult { - pub(crate) instructions: Vec<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, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [Const32(c), GlobalGet32(global)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); - rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - if matches!(op, BinOp::IAdd) { - rewrite!(instrs, i, [Const32(c)] => AddConst32(c)); - rewrite!(instrs, i, [I32Add] => I32Add3); - rewrite!(instrs, i, - [BinOpStackLocal32(BinOp::IAdd, local)] => - [LocalGet32(local), I32Add3] - ); - } - } - instr @ (I32Sub | I32Shl | I32ShrS | I32ShrU | I32Rotl | I32Rotr) => { - let Some(op) = int_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); - rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); - rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - if matches!(op, BinOp::IShrS) { - rewrite!(instrs, i, [BinOpLocalConst32(BinOp::IShl, local, 8), Const32(8)] => [LocalGet32(local), I32Extend8S]); - rewrite!(instrs, i, [BinOpLocalConst32(BinOp::IShl, local, 16), Const32(16)] => [LocalGet32(local), I32Extend16S]); - } - } - instr @ (I64Add | I64Mul | I64And | I64Or | I64Xor) => { - let Some(op) = int_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); - rewrite!(instrs, i, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [Const64(c), GlobalGet64(global)] => BinOpGlobalConst64(op, global, c)); - rewrite!(instrs, i, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); - if matches!(op, BinOp::IAdd) { - rewrite!(instrs, i, [Const64(c)] => AddConst64(c)); - rewrite!(instrs, i, [I64Add] => I64Add3); - } - } - instr @ (I64Sub | I64Shl | I64ShrS | I64ShrU | I64Rotl | I64Rotr) => { - let Some(op) = int_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); - rewrite!(instrs, i, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); - if matches!(op, BinOp::IShrS) { - rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 8), Const64(8)] => [LocalGet64(local), I64Extend8S]); - rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 16), Const64(16)] => [LocalGet64(local), I64Extend16S]); - rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 32), Const64(32)] => [LocalGet64(local), I64Extend32S]); - } - } - instr @ (I32Eq | I32Ne | I32LtS | I32LtU | I32GtS | I32GtU | I32LeS | I32LeU | I32GeS | I32GeU) => { - let Some(op) = cmp_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet32(left), LocalGet32(right)] => CmpLocalLocal32(op, left, right)); - } - instr @ (I64Eq | I64Ne | I64LtS | I64LtU | I64GtS | I64GtU | I64LeS | I64LeU | I64GeS | I64GeU) => { - let Some(op) = cmp_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet64(left), LocalGet64(right)] => CmpLocalLocal64(op, left, right)); - } - instr @ (F32Add | F32Mul | F32Min | F32Max) => { - let Some(op) = float_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); - rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [Const32(c), GlobalGet32(global)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - } - instr @ (F32Sub | F32Div | F32Copysign) => { - let Some(op) = float_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); - rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [GlobalGet32(global), Const32(c)] => BinOpGlobalConst32(op, global, c)); - rewrite!(instrs, i, [LocalGet32(local)] => BinOpStackLocal32(op, local)); - } - instr @ (F64Add | F64Mul | F64Min | F64Max) => { - let Some(op) = float_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); - rewrite!(instrs, i, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [Const64(c), GlobalGet64(global)] => BinOpGlobalConst64(op, global, c)); - } - instr @ (F64Sub | F64Div | F64Copysign) => { - let Some(op) = float_bin_op(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); - rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [GlobalGet64(global), Const64(c)] => BinOpGlobalConst64(op, global, c)); - } - instr @ (V128And | V128Or | V128Xor | I64x2Add | I64x2Mul) => { - let Some(op) = bin_op_128(instr) else { unreachable!() }; - rewrite!(instrs, i, [LocalGet128(a), LocalGet128(b)] => BinOpLocalLocal128(op, a, b)); - rewrite!(instrs, i, [LocalGet128(local), Const128(c)] => BinOpLocalConst128(op, local, c)); - rewrite!(instrs, i, [GlobalGet128(global), Const128(c)] => BinOpGlobalConst128(op, global, c)); - rewrite!(instrs, i, [Const128(c), LocalGet128(local)] => BinOpLocalConst128(op, local, c)); - rewrite!(instrs, i, [Const128(c), GlobalGet128(global)] => BinOpGlobalConst128(op, global, c)); - } - V128AndNot => { - rewrite!(instrs, i, [LocalGet128(a), LocalGet128(b)] => BinOpLocalLocal128(BinOp128::AndNot, a, b)); - rewrite!(instrs, i, [LocalGet128(local), Const128(c)] => BinOpLocalConst128(BinOp128::AndNot, local, c)); - rewrite!(instrs, i, [GlobalGet128(global), Const128(c)] => BinOpGlobalConst128(BinOp128::AndNot, global, c)); - } - I32Store(memarg) | F32Store(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr), LoadLocal32(load_memarg, load_addr), AddConst32(1)] if - (load_memarg == memarg && addr == u16::from(load_addr)) => - IncMemoryLocal32(memarg, load_addr) - ); - rewrite!(instrs, i, - [LocalGet64(addr), LoadLocal32(load_memarg, load_addr), AddConst32(1)] if - (load_memarg == memarg && addr == u16::from(load_addr)) => - IncMemoryLocal32(memarg, load_addr) - ); - rewrite!(instrs, i, [F32Mul, F32Add] => FMaStoreF32(memarg)); - rewrite!(instrs, i, - [BinOpStackLocal32(BinOp::FMul, local), F32Add] => - [LocalGet32(local), FMaStoreF32(memarg)] - ); - rewrite!(instrs, i, - [LocalGet32(addr_local), LocalGet32(value_local)] if - (let (Ok(addr_local), Ok(value_local)) = (u8::try_from(addr_local), u8::try_from(value_local))) => - StoreLocalLocal32(memarg, addr_local, value_local) - ); - } - I64Store(memarg) | F64Store(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr), LoadLocal64(load_memarg, load_addr), AddConst64(1)] if - (load_memarg == memarg && addr == u16::from(load_addr)) => - IncMemoryLocal64(memarg, load_addr) - ); - rewrite!(instrs, i, - [LocalGet64(addr), LoadLocal64(load_memarg, load_addr), AddConst64(1)] if - (load_memarg == memarg && addr == u16::from(load_addr)) => - IncMemoryLocal64(memarg, load_addr) - ); - rewrite!(instrs, i, [F64Mul, F64Add] => FMaStoreF64(memarg)); - rewrite!(instrs, i, - [LocalGet32(addr_local), LocalGet64(value_local)] if - (let (Ok(addr_local), Ok(value_local)) = (u8::try_from(addr_local), u8::try_from(value_local))) => - StoreLocalLocal64(memarg, addr_local, value_local) - ); - } - V128Store(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local), LocalGet128(value_local)] if - (let (Ok(addr_local), Ok(value_local)) = (u8::try_from(addr_local), u8::try_from(value_local))) => - StoreLocalLocal128(memarg, addr_local, value_local) - ); - } - I32Load(memarg) | F32Load(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal32(memarg, addr_local) - ); - rewrite!(instrs, i, - [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal32(memarg, addr_local) - ); - } - I64Load(memarg) | F64Load(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal64(memarg, addr_local) - ); - rewrite!(instrs, i, - [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal64(memarg, addr_local) - ); - } - I32Load8S(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal8S32(memarg, addr_local) - ); - rewrite!(instrs, i, - [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal8S32(memarg, addr_local) - ); - } - I32Load8U(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal8U32(memarg, addr_local) - ); - rewrite!(instrs, i, - [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal8U32(memarg, addr_local) - ); - } - I32Load16S(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal16S32(memarg, addr_local) - ); - rewrite!(instrs, i, - [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal16S32(memarg, addr_local) - ); - } - I32Load16U(memarg) => { - rewrite!(instrs, i, - [LocalGet32(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal16U32(memarg, addr_local) - ); - rewrite!(instrs, i, - [LocalGet64(addr_local)] if (let Ok(addr_local) = u8::try_from(addr_local)) => - LoadLocal16U32(memarg, addr_local) - ); - } - MemoryFill(mem) => { - rewrite!(instrs, i, [Const32(val), Const32(size)] => MemoryFillImm(mem, val as u8, size)) - } - GlobalGet32(dst) => rewrite!(instrs, i, [GlobalSet32(src)] if (src == dst) => GlobalTee32(src)), - GlobalGet64(dst) => rewrite!(instrs, i, [GlobalSet64(src)] if (src == dst) => GlobalTee64(src)), - GlobalGet128(dst) => rewrite!(instrs, i, [GlobalSet128(src)] if (src == dst) => GlobalTee128(src)), - LocalGet32(dst) => rewrite!(instrs, i, [LocalSet32(src)] if (src == dst) => LocalTee32(src)), - LocalGet64(dst) => rewrite!(instrs, i, [LocalSet64(src)] if (src == dst) => LocalTee64(src)), - LocalGet128(dst) => rewrite!(instrs, i, [LocalSet128(src)] if (src == dst) => LocalTee128(src)), - LocalSet32(dst) => { - fold_local_binop!( - instrs, i, dst, - source = resolve_local_source_32, - op = scalar_bin_op, - const = scalar_const_32, - local_local = BinOpLocalLocalSet32, - local_const = |dst, lhs, op, imm| match (dst == lhs, op) { - (true, BinOp::IAdd) => Instruction::IncLocal32(dst, imm), - (true, BinOp::ISub) => Instruction::IncLocal32(dst, imm.wrapping_neg()), - _ => Instruction::BinOpLocalConstSet32(op, lhs, imm, dst), - } - ); - rewrite!(instrs, i, [I32Mul, LocalGet32(acc), I32Add] if (acc == dst) => MulAccLocal32(dst)); - rewrite!(instrs, i, [F32Mul, LocalGet32(acc), F32Add] if (acc == dst) => FMulAccLocal32(dst)); - rewrite!(instrs, i, - [I32Mul, BinOpStackLocal32(BinOp::IAdd, acc)] if (acc == dst) => - MulAccLocal32(dst) - ); - rewrite!(instrs, i, - [F32Mul, BinOpStackLocal32(BinOp::FAdd, acc)] if (acc == dst) => - FMulAccLocal32(dst) - ); - rewrite!(instrs, i, [BinOpStackLocal32(op, local)] => BinOpStackLocalSet32(op, local, dst)); - rewrite_local_set_direct!( - instrs, - i, - dst, - get = LocalGet32, - copy = LocalCopy32, - binop_local_local = BinOpLocalLocal32, - binop_local_local_set = BinOpLocalLocalSet32, - binop_local_const = BinOpLocalConst32, - binop_local_const_set = |dst, src, op, c| match (dst == src, op) { - (true, BinOp::IAdd) => IncLocal32(dst, c), - (true, BinOp::ISub) => IncLocal32(dst, c.wrapping_neg()), - _ => BinOpLocalConstSet32(op, src, c, dst), - }, - const_instr = Const32, - set_local_const = SetLocalConst32 - ); - rewrite!(instrs, i, [LoadLocal32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet32(memarg, addr, dst)); - rewrite!(instrs, i, [LoadLocal8S32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet8S32(memarg, addr, dst)); - rewrite!(instrs, i, [LoadLocal8U32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet8U32(memarg, addr, dst)); - rewrite!(instrs, i, [LoadLocal16S32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet16S32(memarg, addr, dst)); - rewrite!(instrs, i, [LoadLocal16U32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => LoadLocalSet16U32(memarg, addr, dst)); - rewrite!(instrs, i, - [LocalGet32(addr), I32Load(memarg)] if - (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) => - LoadLocalSet32(memarg, addr, dst) - ); - } - LocalSet64(dst) => { - fold_local_binop!( - instrs, i, dst, - source = resolve_local_source_64, - op = scalar_bin_op, - const = scalar_const_64, - local_local = BinOpLocalLocalSet64, - local_const = |dst, lhs, op, imm| match (dst == lhs, op) { - (true, BinOp::IAdd) => Instruction::IncLocal64(dst, imm), - (true, BinOp::ISub) => Instruction::IncLocal64(dst, imm.wrapping_neg()), - _ => Instruction::BinOpLocalConstSet64(op, lhs, imm, dst), - } - ); - rewrite!(instrs, i, [I64Mul, LocalGet64(acc), I64Add] if (acc == dst) => MulAccLocal64(dst)); - rewrite!(instrs, i, [F64Mul, LocalGet64(acc), F64Add] if (acc == dst) => FMulAccLocal64(dst)); - rewrite_local_set_direct!( - instrs, - i, - dst, - get = LocalGet64, - copy = LocalCopy64, - binop_local_local = BinOpLocalLocal64, - binop_local_local_set = BinOpLocalLocalSet64, - binop_local_const = BinOpLocalConst64, - binop_local_const_set = |dst, src, op, c| match (dst == src, op) { - (true, BinOp::IAdd) => IncLocal64(dst, c), - (true, BinOp::ISub) => IncLocal64(dst, c.wrapping_neg()), - _ => BinOpLocalConstSet64(op, src, c, dst), - }, - const_instr = Const64, - set_local_const = SetLocalConst64 - ); - } - LocalSet128(dst) => { - fold_local_binop!( - instrs, i, dst, - source = resolve_local_source_128, - op = bin_op_128, - const = const_128, - local_local = BinOpLocalLocalSet128, - local_const = |dst, lhs, op, imm| Instruction::BinOpLocalConstSet128(op, lhs, imm, dst) - ); - rewrite_local_set_direct!( - instrs, - i, - dst, - get = LocalGet128, - copy = LocalCopy128, - binop_local_local = BinOpLocalLocal128, - binop_local_local_set = BinOpLocalLocalSet128, - binop_local_const = BinOpLocalConst128, - binop_local_const_set = |dst, src, op, c| BinOpLocalConstSet128(op, src, c, dst), - const_instr = Const128, - set_local_const = SetLocalConst128 - ); - rewrite!(instrs, i, - [LocalGet32(addr), V128Load(memarg)] if - (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) => - LoadLocalSet128(memarg, addr, dst) - ); - } - LocalTee32(dst) => { - rewrite!(instrs, i, [BinOpStackLocal32(op, local)] => BinOpStackLocalTee32(op, local, dst)); - fold_local_binop!( - instrs, i, dst, - source = resolve_local_source_32, - op = scalar_bin_op, - const = scalar_const_32, - local_local = BinOpLocalLocalTee32, - local_const = |dst, lhs, op, imm| Instruction::BinOpLocalConstTee32(op, lhs, imm, dst) - ); - rewrite_local_tee_direct!( - instrs, - i, - dst, - get = LocalGet32, - binop_local_local = BinOpLocalLocal32, - binop_local_local_tee = BinOpLocalLocalTee32, - binop_local_const = BinOpLocalConst32, - binop_local_const_tee = BinOpLocalConstTee32 - ); - rewrite!(instrs, i, [Const32(c), I32And] => AndConstTee32(c, dst)); - rewrite!(instrs, i, [Const32(c), I32Sub] => SubConstTee32(c, dst)); - rewrite!(instrs, i, - [LocalGet32(addr), I32Load(memarg)] if - (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) => - LoadLocalTee32(memarg, addr, dst) - ); - rewrite!(instrs, i, - [LocalGet32(addr), F32Load(memarg)] if - (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) => - LoadLocalTee32(memarg, addr, dst) - ); - rewrite!(instrs, i, - [LoadLocal32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => - LoadLocalTee32(memarg, addr, dst) - ); - rewrite!(instrs, i, - [LoadLocal8S32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => - LoadLocalTee8S32(memarg, addr, dst) - ); - rewrite!(instrs, i, - [LoadLocal8U32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => - LoadLocalTee8U32(memarg, addr, dst) - ); - rewrite!(instrs, i, - [LoadLocal16S32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => - LoadLocalTee16S32(memarg, addr, dst) - ); - rewrite!(instrs, i, - [LoadLocal16U32(memarg, addr)] if (let Ok(dst) = u8::try_from(dst)) => - LoadLocalTee16U32(memarg, addr, dst) - ); - } - LocalTee64(dst) => { - fold_local_binop!( - instrs, i, dst, - source = resolve_local_source_64, - op = scalar_bin_op, - const = scalar_const_64, - local_local = BinOpLocalLocalTee64, - local_const = |dst, lhs, op, imm| Instruction::BinOpLocalConstTee64(op, lhs, imm, dst) - ); - rewrite_local_tee_direct!( - instrs, - i, - dst, - get = LocalGet64, - binop_local_local = BinOpLocalLocal64, - binop_local_local_tee = BinOpLocalLocalTee64, - binop_local_const = BinOpLocalConst64, - binop_local_const_tee = BinOpLocalConstTee64 - ); - rewrite!(instrs, i, [Const64(c), I64And] => AndConstTee64(c, dst)); - rewrite!(instrs, i, [Const64(c), I64Sub] => SubConstTee64(c, dst)); - } - LocalTee128(dst) => { - fold_local_binop!( - instrs, i, dst, - source = resolve_local_source_128, - op = bin_op_128, - const = const_128, - local_local = BinOpLocalLocalTee128, - local_const = |dst, lhs, op, imm| Instruction::BinOpLocalConstTee128(op, lhs, imm, dst) - ); - rewrite_local_tee_direct!( - instrs, - i, - dst, - get = LocalGet128, - binop_local_local = BinOpLocalLocal128, - binop_local_local_tee = BinOpLocalLocalTee128, - binop_local_const = BinOpLocalConst128, - binop_local_const_tee = BinOpLocalConstTee128 - ); - rewrite!(instrs, i, - [LocalGet32(addr), V128Load(memarg)] if - (let (Ok(addr), Ok(dst)) = (u8::try_from(addr), u8::try_from(dst))) => - LoadLocalTee128(memarg, addr, dst) - ); - } - Drop32 => { - rewrite!(instrs, i, - [BinOpStackLocalTee32(op, local, dst)] => - BinOpStackLocalSet32(op, local, dst) - ); - rewrite_drop_tee_direct!( - instrs, - i, - tee = LocalTee32, - set = LocalSet32, - binop_local_local_tee = BinOpLocalLocalTee32, - binop_local_local_set = BinOpLocalLocalSet32, - binop_local_const_tee = BinOpLocalConstTee32, - binop_local_const_set = BinOpLocalConstSet32 - ); - } - Drop64 => rewrite_drop_tee_direct!( - instrs, - i, - tee = LocalTee64, - set = LocalSet64, - binop_local_local_tee = BinOpLocalLocalTee64, - binop_local_local_set = BinOpLocalLocalSet64, - binop_local_const_tee = BinOpLocalConstTee64, - binop_local_const_set = BinOpLocalConstSet64 - ), - Drop128 => rewrite_drop_tee_direct!( - instrs, - i, - tee = LocalTee128, - set = LocalSet128, - binop_local_local_tee = BinOpLocalLocalTee128, - binop_local_local_set = BinOpLocalLocalSet128, - binop_local_const_tee = BinOpLocalConstTee128, - binop_local_const_set = BinOpLocalConstSet128 - ), - Jump(ip) => { - let target = resolve_jump_target(&source, ip); - let exit = old_idx as u32 + 1; - let body = target + 1; - - match source.get(target as usize).copied() { - Some(JumpCmpLocalLocal32 { target_ip, left, right, op }) - if resolve_jump_target(&source, target_ip) == exit && body > target => - { - instrs[i] = JumpCmpLocalLocal32 { target_ip: body, left, right, op: inverse_cmp_op(op) }; - } - Some(JumpCmpLocalLocal64 { target_ip, left, right, op }) - if resolve_jump_target(&source, target_ip) == exit && body > target => - { - instrs[i] = JumpCmpLocalLocal64 { target_ip: body, left, right, op: inverse_cmp_op(op) }; - } - _ => canonicalize_jump_like_with_target(&mut instrs, i, target, exit), - } - } - JumpIfZero32(ip) => { - let target = resolve_jump_target(&source, ip); - rewrite!(instrs, i, [LocalGet32(local), I32Eqz] => { - replace!(instrs, i, 2 => JumpIfLocalNonZero32 { target_ip: target, local }); - continue; - }); - rewrite!(instrs, i, [I32Eqz] => { - replace!(instrs, i, 1 => JumpIfNonZero32(target)); - continue; - }); - rewrite!(instrs, i, [LocalGet64(local), I64Eqz] => { - replace!(instrs, i, 2 => JumpIfLocalNonZero64 { target_ip: target, local }); - continue; - }); - rewrite!(instrs, i, [I64Eqz] => { - replace!(instrs, i, 1 => JumpIfNonZero64(target)); - continue; - }); - rewrite!(instrs, i, - [BinOpLocalConstTee32(op, local, imm, dst)] if (local == dst) => - match inc_delta(op, imm) { - Some(delta) => IncLocalJump32 { target_ip: target, local, delta, on_zero: true }, - None => BinOpLocalConstJump32 { target_ip: target, local, imm, op, on_zero: true }, - } - ); - rewrite!(instrs, i, - [AddConst32(imm), LocalTee32(local), LocalGet32(cond)] if (local == cond) => - IncStackTeeLocalJump32 { target_ip: target, local, delta: imm, on_zero: true } - ); - rewrite!(instrs, i, - [AndConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => - BinOpStackConstTeeLocalJump32 { target_ip: target, local, imm, op: BinOp::IAnd, on_zero: true } - ); - rewrite!(instrs, i, - [SubConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => - IncStackTeeLocalJump32 { target_ip: target, local, delta: imm.wrapping_neg(), on_zero: true } - ); - rewrite!(instrs, i, - [BinOpGlobalConst32(op, global, imm), GlobalTee32(dst)] if (global == dst) => - match inc_delta(op, imm) { - Some(delta) => IncGlobalJump32 { target_ip: target, global, delta, on_zero: true }, - None => BinOpGlobalConstJump32 { target_ip: target, global, imm, op, on_zero: true }, - } - ); - rewrite!(instrs, i, - [CmpLocalLocal32(op, left, right)] => - JumpCmpLocalLocal32 { target_ip: target, left, right, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, - [CmpLocalLocal64(op, left, right)] => - JumpCmpLocalLocal64 { target_ip: target, left, right, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, - [BinOpLocalConstTee32(binop, local, imm, dst), LocalGet32(right), cmp] if - (local == dst && let Some(cmp) = cmp_op(cmp)) => - match inc_delta(binop, imm) { - Some(delta) => IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op: inverse_cmp_op(cmp) }, - None => BinOpLocalConstJumpCmpLocal32 { target_ip: target, local, imm, binop, right, cmp: inverse_cmp_op(cmp) }, - } - ); - rewrite!(instrs, i, - [LocalGet32(local), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpStackLocal32 { target_ip: target, local, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, - [LocalGet64(local), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpStackLocal64 { target_ip: target, local, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, - [LocalGet32(local), Const32(imm), cmp] if (let Some(op) = cmp_op(cmp)) => - match (imm, inverse_cmp_op(op)) { - (0, CmpOp::Eq) => JumpIfLocalZero32 { target_ip: target, local }, - (0, CmpOp::Ne) => JumpIfLocalNonZero32 { target_ip: target, local }, - (imm, op) => JumpCmpLocalConst32 { target_ip: target, local, imm, op }, - } - ); - rewrite!(instrs, i, - [LocalGet64(local), Const64(imm), cmp] if - (let Some(op) = cmp_op(cmp) && let Ok(imm) = i32::try_from(imm)) => - match (imm, inverse_cmp_op(op)) { - (0, CmpOp::Eq) => JumpIfLocalZero64 { target_ip: target, local }, - (0, CmpOp::Ne) => JumpIfLocalNonZero64 { target_ip: target, local }, - (imm, op) => JumpCmpLocalConst64 { target_ip: target, local, imm, op }, - } - ); - rewrite!(instrs, i, - [LocalGet32(left), LocalGet32(right), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpLocalLocal32 { target_ip: target, left, right, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, - [LocalGet64(left), LocalGet64(right), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpLocalLocal64 { target_ip: target, left, right, op: inverse_cmp_op(op) } - ); - rewrite!(instrs, i, [Const32(imm), cmp] if (let Some(op) = cmp_op(cmp)) => match (imm, inverse_cmp_op(op)) { - (0, CmpOp::Eq) => JumpIfZero32(target), - (0, CmpOp::Ne) => JumpIfNonZero32(target), - (imm, op) => JumpCmpStackConst32 { target_ip: target, imm, op }, - }); - rewrite!(instrs, i, [Const64(imm), cmp] if (let Some(op) = cmp_op(cmp)) => match (imm, inverse_cmp_op(op)) { - (0, CmpOp::Eq) => JumpIfZero64(target), - (0, CmpOp::Ne) => JumpIfNonZero64(target), - (imm, op) => JumpCmpStackConst64 { target_ip: target, imm, op }, - }); - rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalZero32 { target_ip: target, local }); - rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalZero64 { target_ip: target, local }); - canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1); - } - JumpIfNonZero32(ip) => { - let target = resolve_jump_target(&source, ip); - rewrite!(instrs, i, [LocalGet32(local), I32Eqz] => { - replace!(instrs, i, 2 => JumpIfLocalZero32 { target_ip: target, local }); - continue; - }); - rewrite!(instrs, i, [I32Eqz] => { - replace!(instrs, i, 1 => JumpIfZero32(target)); - continue; - }); - rewrite!(instrs, i, [LocalGet64(local), I64Eqz] => { - replace!(instrs, i, 2 => JumpIfLocalZero64 { target_ip: target, local }); - continue; - }); - rewrite!(instrs, i, [I64Eqz] => { - replace!(instrs, i, 1 => JumpIfZero64(target)); - continue; - }); - rewrite!(instrs, i, - [BinOpLocalConstTee32(op, local, imm, dst)] if (local == dst) => - match inc_delta(op, imm) { - Some(delta) => IncLocalJump32 { target_ip: target, local, delta, on_zero: false }, - None => BinOpLocalConstJump32 { target_ip: target, local, imm, op, on_zero: false }, - } - ); - rewrite!(instrs, i, - [AddConst32(imm), LocalTee32(local), LocalGet32(cond)] if (local == cond) => - IncStackTeeLocalJump32 { target_ip: target, local, delta: imm, on_zero: false } - ); - rewrite!(instrs, i, - [AndConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => - BinOpStackConstTeeLocalJump32 { target_ip: target, local, imm, op: BinOp::IAnd, on_zero: false } - ); - rewrite!(instrs, i, - [SubConstTee32(imm, local), LocalGet32(cond)] if (local == cond) => - IncStackTeeLocalJump32 { target_ip: target, local, delta: imm.wrapping_neg(), on_zero: false } - ); - rewrite!(instrs, i, - [BinOpGlobalConst32(op, global, imm), GlobalTee32(dst)] if (global == dst) => - match inc_delta(op, imm) { - Some(delta) => IncGlobalJump32 { target_ip: target, global, delta, on_zero: false }, - None => BinOpGlobalConstJump32 { target_ip: target, global, imm, op, on_zero: false }, - } - ); - rewrite!(instrs, i, - [CmpLocalLocal32(op, left, right)] => - JumpCmpLocalLocal32 { target_ip: target, left, right, op } - ); - rewrite!(instrs, i, - [CmpLocalLocal64(op, left, right)] => - JumpCmpLocalLocal64 { target_ip: target, left, right, op } - ); - rewrite!(instrs, i, - [BinOpLocalConstTee32(binop, local, imm, dst), LocalGet32(right), cmp] if - (local == dst && let Some(cmp) = cmp_op(cmp)) => - match inc_delta(binop, imm) { - Some(delta) => IncLocalJumpCmpLocal32 { target_ip: target, local, delta, right, op: cmp }, - None => BinOpLocalConstJumpCmpLocal32 { target_ip: target, local, imm, binop, right, cmp }, - } - ); - rewrite!(instrs, i, - [LocalGet32(local), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpStackLocal32 { target_ip: target, local, op } - ); - rewrite!(instrs, i, - [LocalGet64(local), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpStackLocal64 { target_ip: target, local, op } - ); - rewrite!(instrs, i, - [LocalGet32(local), Const32(imm), cmp] if (let Some(op) = cmp_op(cmp)) => - match (imm, op) { - (0, CmpOp::Eq) => JumpIfLocalZero32 { target_ip: target, local }, - (0, CmpOp::Ne) => JumpIfLocalNonZero32 { target_ip: target, local }, - (imm, op) => JumpCmpLocalConst32 { target_ip: target, local, imm, op }, - } - ); - rewrite!(instrs, i, - [LocalGet64(local), Const64(imm), cmp] if - (let Some(op) = cmp_op(cmp) && let Ok(imm) = i32::try_from(imm)) => - match (imm, op) { - (0, CmpOp::Eq) => JumpIfLocalZero64 { target_ip: target, local }, - (0, CmpOp::Ne) => JumpIfLocalNonZero64 { target_ip: target, local }, - (imm, op) => JumpCmpLocalConst64 { target_ip: target, local, imm, op }, - } - ); - rewrite!(instrs, i, - [LocalGet32(left), LocalGet32(right), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpLocalLocal32 { target_ip: target, left, right, op } - ); - rewrite!(instrs, i, - [LocalGet64(left), LocalGet64(right), cmp] if (let Some(op) = cmp_op(cmp)) => - JumpCmpLocalLocal64 { target_ip: target, left, right, op } - ); - rewrite!(instrs, i, [Const32(imm), cmp] if (let Some(op) = cmp_op(cmp)) => match (imm, op) { - (0, CmpOp::Eq) => JumpIfZero32(target), - (0, CmpOp::Ne) => JumpIfNonZero32(target), - (imm, op) => JumpCmpStackConst32 { target_ip: target, imm, op }, - }); - rewrite!(instrs, i, [Const64(imm), cmp] if (let Some(op) = cmp_op(cmp)) => match (imm, op) { - (0, CmpOp::Eq) => JumpIfZero64(target), - (0, CmpOp::Ne) => JumpIfNonZero64(target), - (imm, op) => JumpCmpStackConst64 { target_ip: target, imm, op }, - }); - rewrite!(instrs, i, [LocalGet32(local)] => JumpIfLocalNonZero32 { target_ip: target, local }); - rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalNonZero64 { target_ip: target, local }); - canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1); - } - JumpIfZero64(ip) => { - let target = resolve_jump_target(&source, ip); - rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalZero64 { target_ip: target, local }); - canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1); - } - JumpIfNonZero64(ip) => { - let target = resolve_jump_target(&source, ip); - rewrite!(instrs, i, [LocalGet64(local)] => JumpIfLocalNonZero64 { target_ip: target, local }); - canonicalize_jump_like_with_target(&mut instrs, i, target, old_idx as u32 + 1); - } - JumpCmpStackConst32 { target_ip, imm: 0, op } => { - match op { - CmpOp::Eq => instrs[i] = JumpIfZero32(target_ip), - CmpOp::Ne => instrs[i] = JumpIfNonZero32(target_ip), - _ => {} - } - canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1); - } - JumpCmpStackConst64 { target_ip, imm: 0, op } => { - match op { - CmpOp::Eq => instrs[i] = JumpIfZero64(target_ip), - CmpOp::Ne => instrs[i] = JumpIfNonZero64(target_ip), - _ => {} - } - canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1); - } - JumpCmpLocalConst32 { target_ip, local, imm: 0, op } => { - match op { - CmpOp::Eq => instrs[i] = JumpIfLocalZero32 { target_ip, local }, - CmpOp::Ne => instrs[i] = JumpIfLocalNonZero32 { target_ip, local }, - _ => {} - } - canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1); - } - JumpCmpLocalConst64 { target_ip, local, imm: 0, op } => { - match op { - CmpOp::Eq => instrs[i] = JumpIfLocalZero64 { target_ip, local }, - CmpOp::Ne => instrs[i] = JumpIfLocalNonZero64 { target_ip, local }, - _ => {} - } - canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1); - } - JumpCmpStackConst32 { .. } - | JumpCmpStackConst64 { .. } - | JumpCmpLocalConst32 { .. } - | JumpCmpLocalConst64 { .. } - | JumpCmpLocalLocal32 { .. } - | JumpCmpLocalLocal64 { .. } - | JumpIfLocalZero32 { .. } - | JumpIfLocalNonZero32 { .. } - | JumpIfLocalZero64 { .. } - | JumpIfLocalNonZero64 { .. } => { - canonicalize_jump_like(&source, &mut instrs, i, old_idx as u32 + 1); - } - _ => {} - } - - after_terminator = is_unconditional_terminator(instr); - } - - old_to_new[source.len()] = instrs.len() as u32; - (instrs.instructions, old_to_new) -} - -fn cmp_op(instr: Instruction) -> Option<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 inc_delta(op: BinOp, imm: i32) -> Option<i32> { - match op { - BinOp::IAdd => Some(imm), - BinOp::ISub => Some(imm.wrapping_neg()), - _ => 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::BrOnCast(ip, _, _) - | Instruction::JumpCmpStackConst32 { target_ip: ip, .. } - | Instruction::JumpCmpStackConst64 { target_ip: ip, .. } - | Instruction::JumpCmpStackLocal32 { target_ip: ip, .. } - | Instruction::JumpCmpStackLocal64 { target_ip: ip, .. } - | Instruction::BinOpLocalConstJump32 { target_ip: ip, .. } - | Instruction::BinOpLocalConstJumpCmpLocal32 { target_ip: ip, .. } - | Instruction::BinOpStackConstTeeLocalJump32 { target_ip: ip, .. } - | Instruction::BinOpGlobalConstJump32 { target_ip: ip, .. } - | Instruction::IncLocalJump32 { target_ip: ip, .. } - | Instruction::IncStackTeeLocalJump32 { target_ip: ip, .. } - | Instruction::IncGlobalJump32 { target_ip: ip, .. } - | Instruction::IncLocalJumpCmpLocal32 { target_ip: ip, .. } - | Instruction::JumpIfLocalZero32 { target_ip: ip, .. } - | Instruction::JumpIfLocalNonZero32 { target_ip: ip, .. } - | Instruction::JumpIfLocalZero64 { target_ip: ip, .. } - | Instruction::JumpIfLocalNonZero64 { target_ip: ip, .. } - | Instruction::JumpCmpLocalConst32 { target_ip: ip, .. } - | Instruction::JumpCmpLocalConst64 { target_ip: ip, .. } - | Instruction::JumpCmpLocalLocal32 { target_ip: ip, .. } - | Instruction::JumpCmpLocalLocal64 { target_ip: ip, .. } => ip, - Instruction::BranchTable(ip, _, _) => ip, - _ => return None, - }) -} - -fn instruction_target(instr: &Instruction) -> Option<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(_) - | Instruction::Throw(_) - | Instruction::ThrowRef - ) -} - -fn target_boundaries(instructions: &[Instruction], function_data: &WasmFunctionData) -> Result<Vec<bool>> { - let mut boundaries = alloc::vec![false; instructions.len() + 1]; - for handler in &function_data.exception_handlers { - for target in [handler.start_ip, handler.end_ip] { - let boundary = boundaries.get_mut(target as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("exception handler boundary out of bounds: {target}")) - })?; - *boundary = true; - } - for catch in &handler.catches { - let target = catch.landing_pad(); - let boundary = boundaries - .get_mut(target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("exception landing pad out of bounds: {target}")))?; - *boundary = true; - } - } - for instr in instructions { - if let Some(target) = instruction_target(instr) { - let boundary = boundaries - .get_mut(target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))?; - *boundary = true; - } - if let Instruction::BranchTable(_, start, count) = *instr { - let end = - start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; - let targets = function_data - .branch_table_targets - .get(start as usize..end as usize) - .ok_or_else(|| ParseError::Other("branch table range out of bounds".into()))?; - for &target in targets { - let boundary = boundaries - .get_mut(target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("branch table target out of bounds: {target}")))?; - *boundary = true; - } - } - } - Ok(boundaries) -} - -/// Remaps rewritten targets, then validates targets and ranges while detecting local memory use. -fn finalize( - instructions: &mut [Instruction], - function_data: &mut WasmFunctionData, - old_to_new: Option<&[u32]>, - imported_memory_count: u32, -) -> Result<bool> { - let len = instructions.len() as u32; - for handler in &mut function_data.exception_handlers { - if let Some(old_to_new) = old_to_new { - handler.start_ip = *old_to_new.get(handler.start_ip as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("exception handler boundary out of bounds: {}", handler.start_ip)) - })?; - handler.end_ip = *old_to_new.get(handler.end_ip as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("exception handler boundary out of bounds: {}", handler.end_ip)) - })?; - for catch in &mut handler.catches { - let landing_pad = match catch { - tinywasm_types::ExceptionCatch::Tag { landing_pad, .. } - | tinywasm_types::ExceptionCatch::All { landing_pad, .. } => landing_pad, - }; - *landing_pad = *old_to_new.get(*landing_pad as usize).ok_or_else(|| { - ParseError::Other(alloc::format!("exception landing pad out of bounds: {landing_pad}")) - })?; - } - } - if handler.start_ip > handler.end_ip || handler.end_ip > len { - return Err(ParseError::Other("exception handler range out of bounds".into())); - } - if handler.catches.iter().any(|catch| catch.landing_pad() >= len) { - return Err(ParseError::Other("exception landing pad out of bounds".into())); - } - } - for target in &mut function_data.branch_table_targets { - if let Some(old_to_new) = old_to_new { - *target = *old_to_new - .get(*target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))?; - } - if *target >= len { - return Err(ParseError::Other(alloc::format!("branch table target out of bounds: {target}"))); - } - } - - let mut uses_local_memory = false; - for instr in instructions { - if let Some(target) = instruction_target_mut(instr) { - if let Some(old_to_new) = old_to_new { - *target = *old_to_new - .get(*target as usize) - .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))?; - } - if *target >= len { - return Err(ParseError::Other(alloc::format!("instruction target out of bounds: {target}"))); - } - } - if let Instruction::BranchTable(_, start, count) = *instr { - let end = - start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; - function_data - .branch_table_targets - .get(start as usize..end as usize) - .ok_or_else(|| ParseError::Other("branch table range out of bounds".into()))?; - } - uses_local_memory |= instr.memory_addr().is_some_and(|mem| mem >= imported_memory_count); - } - Ok(uses_local_memory) -} diff --git a/crates/parser/src/optimize/mod.rs b/crates/parser/src/optimize/mod.rs new file mode 100644 index 0000000..09501f9 --- /dev/null +++ b/crates/parser/src/optimize/mod.rs @@ -0,0 +1,4 @@ +mod rewrite; +mod targets; + +pub(crate) use rewrite::optimize_instructions; diff --git a/crates/parser/src/optimize/rewrite.rs b/crates/parser/src/optimize/rewrite.rs new file mode 100644 index 0000000..1146da7 --- /dev/null +++ b/crates/parser/src/optimize/rewrite.rs @@ -0,0 +1,1397 @@ +use super::targets::{finalize, resolve_jump_target, set_rewrite_target, target_boundaries}; +use crate::macros::optimize::{replace, rewrite}; +use crate::visit::FunctionDataBuilder as WasmFunctionData; +use crate::{ParserOptions, Result}; +use alloc::vec::Vec; +use core::ops::{Deref, DerefMut}; +use tinywasm_types::{ + BinOp, BinOp128, CmpOp, CompactMemoryArg, GlobalConst32, GlobalConst64, GlobalUpdate, GlobalV128, I32LocalArg, + I64Operand, Instruction, LocalConst64, LocalConstCmp, LocalConstSet32, LocalConstSet64, LocalConstSetV128, + LocalLocalCmp, LocalTripleArg, LocalU32, LocalUpdate, LocalUpdateCmp, LocalV128, MemoryArg, MemoryFillConstOp, + MemoryLocalArg, OperandIdx, PackedOp, StackConst32, StackConst64, TargetLocal, TargetLocalArg, V128Operand, + ValueCounts, +}; + +pub(crate) struct OptimizeResult { + pub(crate) instructions: Vec<Instruction>, +} + +struct CompactOutput { + instructions: Vec<Instruction>, + block_start: usize, +} + +macro_rules! operand { + ($data:expr, $value:expr) => { + $data.push_operand($value) + }; +} + +macro_rules! target_operand { + ($data:expr, $value:expr) => { + $data.push_target_operand($value) + }; +} + +impl Deref for CompactOutput { + type Target = Vec<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( + mut instructions: Vec<Instruction>, + function_data: &mut WasmFunctionData, + options: &ParserOptions, + function_results: ValueCounts, + self_func_addr: u32, +) -> Result<OptimizeResult> { + let boundaries = target_boundaries(&instructions, function_data)?; + let (rewritten, old_to_new) = if options.optimize_rewrite() { + let (instructions, map) = rewrite(instructions, function_data, &boundaries, function_results, self_func_addr)?; + (instructions, Some(map)) + } else { + (instructions, None) + }; + instructions = rewritten; + finalize(&mut instructions, function_data, old_to_new.as_deref())?; + Ok(OptimizeResult { instructions }) +} + +fn rewrite( + source: Vec<Instruction>, + data: &mut WasmFunctionData, + boundaries: &[bool], + function_results: ValueCounts, + self_func_addr: u32, +) -> Result<(Vec<Instruction>, Vec<u32>)> { + #![allow(unused_assignments)] + use Instruction::*; + + let return_instruction = match function_results { + ValueCounts { c32: 0, c64: 0, c128: 0 } => Some(ReturnVoid), + ValueCounts { c32: 1, c64: 0, c128: 0 } => Some(Return32), + ValueCounts { c32: 0, c64: 1, c128: 0 } => Some(Return64), + ValueCounts { c32: 0, c64: 0, c128: 1 } => Some(Return128), + _ => None, + }; + let mut output = CompactOutput { instructions: Vec::with_capacity(source.len()), block_start: 0 }; + let mut old_to_new = alloc::vec![0; source.len() + 1]; + let mut after_terminator = false; + + for (old_index, instruction) in source.iter().copied().enumerate() { + if boundaries[old_index] || after_terminator { + output.block_start = output.len(); + } + after_terminator = is_unconditional_terminator(instruction); + old_to_new[old_index] = output.len() as u32; + output.push(instruction); + let mut read = output.len() - 1; + + match output[read] { + LocalCopy32(a, b) | LocalCopy64(a, b) | LocalCopy128(a, b) if a == b => { + output.pop(); + } + Call(address) if address == self_func_addr => output[read] = CallSelf, + ReturnCall(address) if address == self_func_addr => output[read] = ReturnCallSelf, + Return if let Some(specialized) = return_instruction => output[read] = specialized, + raw @ (I32Add | I32Mul | I32And | I32Or | I32Xor) => { + let op = int_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); + rewrite!(output, read, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); + rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); + if rewrite_scalar_const32(&mut output, &mut read, data, op, true)? { + continue; + } + if op == BinOp::IAdd { + rewrite!(output, read, [Const32(value)] => AddConst32(value)); + rewrite!(output, read, [I32Add] => I32Add3); + if read > output.block_start + && let BinOpStackLocal32(BinOp::IAdd, local) = output[read - 1] + { + output.truncate(read - 1); + output.extend([LocalGet32(local), I32Add3]); + read = output.len() - 1; + } + } + } + raw @ (I32Sub | I32Shl | I32ShrS | I32ShrU | I32Rotl | I32Rotr) => { + let op = int_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); + rewrite!(output, read, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); + rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); + if rewrite_scalar_const32(&mut output, &mut read, data, op, false)? { + continue; + } + rewrite_sign_extend32(&mut output, &mut read, data, op); + } + raw @ (I64Add | I64Mul | I64And | I64Or | I64Xor) => { + let op = int_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); + rewrite!(output, read, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); + if rewrite_scalar_const64(&mut output, &mut read, data, op, true)? { + continue; + } + if op == BinOp::IAdd { + rewrite!(output, read, [Const64(index)] => AddConst64(index)); + rewrite!(output, read, [I64Add] => I64Add3); + } + } + raw @ (I64Sub | I64Shl | I64ShrS | I64ShrU | I64Rotl | I64Rotr) => { + let op = int_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); + rewrite!(output, read, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); + if rewrite_scalar_const64(&mut output, &mut read, data, op, false)? { + continue; + } + rewrite_sign_extend64(&mut output, &mut read, data, op); + } + raw if cmp_op(raw).is_some() => { + let op = cmp_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => CmpLocalLocal32(op, a, b)); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => CmpLocalLocal64(op, a, b)); + } + raw @ (F32Add | F32Mul | F32Min | F32Max) => { + let op = float_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); + rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); + rewrite_scalar_const32(&mut output, &mut read, data, op, true)?; + } + raw @ (F32Sub | F32Div | F32Copysign) => { + let op = float_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); + rewrite!(output, read, [LocalGet32(local)] => BinOpStackLocal32(op, local)); + rewrite_scalar_const32(&mut output, &mut read, data, op, false)?; + } + raw @ (F64Add | F64Mul | F64Min | F64Max) => { + let op = float_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); + rewrite_scalar_const64(&mut output, &mut read, data, op, true)?; + } + raw @ (F64Sub | F64Div | F64Copysign) => { + let op = float_bin_op(raw).unwrap(); + rewrite!(output, read, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); + rewrite_scalar_const64(&mut output, &mut read, data, op, false)?; + } + raw @ (V128And | V128Or | V128Xor | I64x2Add | I64x2Mul | V128AndNot) => { + let op = bin_op_128(raw).unwrap(); + rewrite!(output, read, [LocalGet128(local)] => + BinOpStackLocal128(op, local) + ); + rewrite_vector_binop(&mut output, &mut read, data, op, raw != V128AndNot)?; + } + I32Store(index) | F32Store(index) => rewrite_store32(&mut output, &mut read, data, index)?, + I64Store(index) | F64Store(index) => rewrite_store64(&mut output, &mut read, data, index)?, + V128Store(index) => { + if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { + rewrite!(output, read, + [LocalGet32(addr), LocalGet128(value)] if + (let (Ok(addr), Ok(value)) = (u8::try_from(addr), u8::try_from(value))) => + StoreLocalLocal128(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value }) + ); + } + } + I32Load(index) | F32Load(index) => { + if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { + rewrite!(output, read, [LocalGet32(local) | LocalGet64(local)] if + (let Ok(local) = u8::try_from(local)) => + LoadLocal32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }) + ); + } + } + I64Load(index) | F64Load(index) => { + if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { + rewrite!(output, read, [LocalGet32(local) | LocalGet64(local)] if + (let Ok(local) = u8::try_from(local)) => + LoadLocal64(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }) + ); + } + } + raw @ (I32Load8S(index) | I32Load8U(index) | I32Load16S(index) | I32Load16U(index)) => { + if let Some(memory_arg_idx) = compact_memory_arg(data, index)? { + rewrite!(output, read, [LocalGet32(local) | LocalGet64(local)] if + (let Ok(local) = u8::try_from(local)) => match raw { + I32Load8S(_) => LoadLocal8S32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), + I32Load8U(_) => LoadLocal8U32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), + I32Load16S(_) => LoadLocal16S32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), + I32Load16U(_) => LoadLocal16U32(MemoryLocalArg { memory_arg_idx, local1: local, local2: 0 }), + _ => unreachable!(), + } + ); + } + } + MemoryFill(memory) => rewrite!(output, read, [Const32(value), Const32(size)] => { + let index = operand!(data, MemoryFillConstOp { memory, byte: value as u8, value: size })?; + replace!(output, read, 2 => MemoryFillConst(index)); + }), + GlobalGet32(dst) => rewrite!(output, read, [GlobalSet32(src)] if (src == dst) => GlobalTee32(src)), + GlobalGet64(dst) => rewrite!(output, read, [GlobalSet64(src)] if (src == dst) => GlobalTee64(src)), + GlobalGet128(dst) => rewrite!(output, read, [GlobalSet128(src)] if (src == dst) => GlobalTee128(src)), + LocalGet32(dst) => rewrite!(output, read, [LocalSet32(src)] if (src == dst) => LocalTee32(src)), + LocalGet64(dst) => rewrite!(output, read, [LocalSet64(src)] if (src == dst) => LocalTee64(src)), + LocalGet128(dst) => rewrite!(output, read, [LocalSet128(src)] if (src == dst) => LocalTee128(src)), + LocalSet32(dst) => rewrite_local_set32(&mut output, &mut read, data, dst)?, + LocalSet64(dst) => rewrite_local_set64(&mut output, &mut read, data, dst)?, + LocalSet128(dst) => rewrite_local_set128(&mut output, &mut read, data, dst)?, + LocalTee32(dst) => rewrite_local_tee32(&mut output, &mut read, data, dst)?, + LocalTee64(dst) => rewrite_local_tee64(&mut output, &mut read, data, dst)?, + LocalTee128(dst) => rewrite_local_tee128(&mut output, &mut read, data, dst)?, + Drop32 => { + rewrite!(output, read, [LocalTee32(local)] => LocalSet32(local)); + rewrite!(output, read, [BinOpStackLocalTee32(op, local, dst)] => BinOpStackLocalSet32(op, local, dst)); + rewrite!(output, read, [AddLocalLocalTee32(arg)] => AddLocalLocalSet32(arg)); + rewrite!(output, read, [BinOpLocalLocalTee32(packed)] => BinOpLocalLocalSet32(packed)); + rewrite!(output, read, [BinOpLocalConstTee32(packed)] => BinOpLocalConstSet32(packed)); + } + Drop64 => { + rewrite!(output, read, [LocalTee64(local)] => LocalSet64(local)); + rewrite!(output, read, [BinOpLocalLocalTee64(packed)] => BinOpLocalLocalSet64(packed)); + rewrite!(output, read, [BinOpLocalConstTee64(packed)] => BinOpLocalConstSet64(packed)); + } + Drop128 => { + rewrite!(output, read, [LocalTee128(local)] => LocalSet128(local)); + rewrite!(output, read, [BinOpLocalLocalTee128(packed)] => BinOpLocalLocalSet128(packed)); + rewrite!(output, read, [BinOpLocalConstTee128(packed)] => BinOpLocalConstSet128(packed)); + } + Jump(target) => rewrite_jump(&source, &mut output, read, data, old_index as u32, target)?, + JumpIfZero32(target) => rewrite_conditional(&source, &mut output, &mut read, data, target, true)?, + JumpIfNonZero32(target) => rewrite_conditional(&source, &mut output, &mut read, data, target, false)?, + JumpIfZero64(target) => { + rewrite!(output, read, [LocalGet64(local)] => + JumpIfLocalZero64(TargetLocalArg { target_ip: target, local }) + ); + } + JumpIfNonZero64(target) => { + rewrite!(output, read, [LocalGet64(local)] => + JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local }) + ); + } + JumpCmpStackConst32(_) + | JumpCmpStackConst64(_) + | JumpCmpLocalConst32(_) + | JumpCmpLocalConst64(_) + | JumpCmpLocalLocal32(_) + | JumpCmpLocalLocal64(_) + | JumpIfLocalZero32(_) + | JumpIfLocalNonZero32(_) + | JumpIfLocalZero64(_) + | JumpIfLocalNonZero64(_) => {} + _ => {} + } + } + for instruction in &mut output.instructions { + match *instruction { + Instruction::Const64(index) => { + let value = data.operand(index).value; + if value == i64::from(value as i32) { + *instruction = Instruction::Const64Imm(value as i32); + } + } + Instruction::Const128(index) => { + let value = u128::from_le_bytes(data.operand(index).value); + if let Ok(value) = u32::try_from(value) { + *instruction = Instruction::Const128Imm(value); + } + } + _ => {} + } + } + let end = old_to_new.len() - 1; + old_to_new[end] = output.len() as u32; + Ok((output.instructions, old_to_new)) +} + +fn local_const32(data: &WasmFunctionData, instruction: Instruction) -> Option<(BinOp, u16, i32)> { + match instruction { + Instruction::AddLocalConst32(arg) => Some((BinOp::IAdd, arg.local, arg.value)), + Instruction::SubLocalConst32(arg) => Some((BinOp::ISub, arg.local, arg.value)), + Instruction::MulLocalConst32(arg) => Some((BinOp::IMul, arg.local, arg.value)), + Instruction::BinOpLocalConst32(packed) => { + let value = data.operand(packed.index); + Some((packed.op, value.local, value.value as i32)) + } + _ => None, + } +} + +fn local_const64(data: &WasmFunctionData, instruction: Instruction) -> Option<(BinOp, u16, i64)> { + let Instruction::BinOpLocalConst64(packed) = instruction else { return None }; + let value = data.operand(packed.index); + Some((packed.op, value.local, value.value as i64)) +} + +fn local_const128( + data: &WasmFunctionData, + instruction: Instruction, +) -> Option<(BinOp128, u16, OperandIdx<V128Operand>)> { + let Instruction::BinOpLocalConst128(packed) = instruction else { return None }; + let value = data.operand(packed.index); + Some((packed.op, value.local, value.value)) +} + +fn compact_memory_arg( + data: &mut WasmFunctionData, + index: OperandIdx<MemoryArg>, +) -> Result<Option<OperandIdx<CompactMemoryArg>>> { + let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) else { return Ok(None) }; + Ok(Some(operand!(data, arg)?)) +} + +fn rewrite_scalar_const32( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + op: BinOp, + commutative: bool, +) -> Result<bool> { + if *read < output.block_start + 2 { + return Ok(false); + } + let previous = &output[*read - 2..*read]; + let replacement = match previous { + [Instruction::LocalGet32(local), Instruction::Const32(value)] => { + let arg = I32LocalArg { value: *value, local: *local }; + match op { + BinOp::IAdd => Instruction::AddLocalConst32(arg), + BinOp::ISub => Instruction::SubLocalConst32(arg), + BinOp::IMul => Instruction::MulLocalConst32(arg), + _ => Instruction::BinOpLocalConst32(PackedOp::new( + op, + operand!(data, LocalU32 { local: *local, value: *value as u32 })?, + )), + } + } + [Instruction::GlobalGet32(global), Instruction::Const32(value)] => Instruction::BinOpGlobalConst32( + PackedOp::new(op, operand!(data, GlobalConst32 { global: *global, value: *value as u32 })?), + ), + [Instruction::Const32(value), Instruction::LocalGet32(local)] if commutative => { + let arg = I32LocalArg { value: *value, local: *local }; + match op { + BinOp::IAdd => Instruction::AddLocalConst32(arg), + BinOp::IMul => Instruction::MulLocalConst32(arg), + _ => Instruction::BinOpLocalConst32(PackedOp::new( + op, + operand!(data, LocalU32 { local: *local, value: *value as u32 })?, + )), + } + } + [Instruction::Const32(value), Instruction::GlobalGet32(global)] if commutative => { + Instruction::BinOpGlobalConst32(PackedOp::new( + op, + operand!(data, GlobalConst32 { global: *global, value: *value as u32 })?, + )) + } + _ => return Ok(false), + }; + replace!(output, *read, 2 => replacement); + Ok(true) +} + +fn rewrite_scalar_const64( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + op: BinOp, + commutative: bool, +) -> Result<bool> { + if *read < output.block_start + 2 { + return Ok(false); + } + let previous = [output[*read - 2], output[*read - 1]]; + let replacement = match previous { + [Instruction::LocalGet64(local), Instruction::Const64(index)] => Instruction::BinOpLocalConst64(PackedOp::new( + op, + operand!(data, LocalConst64 { local, value: data.operand(index).value as u64 })?, + )), + [Instruction::GlobalGet64(global), Instruction::Const64(index)] => Instruction::BinOpGlobalConst64( + PackedOp::new(op, operand!(data, GlobalConst64 { global, value: data.operand(index).value as u64 })?), + ), + [Instruction::Const64(index), Instruction::LocalGet64(local)] if commutative => Instruction::BinOpLocalConst64( + PackedOp::new(op, operand!(data, LocalConst64 { local, value: data.operand(index).value as u64 })?), + ), + [Instruction::Const64(index), Instruction::GlobalGet64(global)] if commutative => { + Instruction::BinOpGlobalConst64(PackedOp::new( + op, + operand!(data, GlobalConst64 { global, value: data.operand(index).value as u64 })?, + )) + } + _ => return Ok(false), + }; + replace!(output, *read, 2 => replacement); + Ok(true) +} + +fn rewrite_sign_extend32(output: &mut CompactOutput, read: &mut usize, data: &WasmFunctionData, op: BinOp) -> bool { + if op != BinOp::IShrS || *read < output.block_start + 2 { + return false; + } + if let Some((BinOp::IShl, local, shift)) = local_const32(data, output[*read - 2]) + && let Instruction::Const32(right) = output[*read - 1] + && shift == right + && matches!(shift, 16 | 24) + { + output.truncate(*read - 2); + output.extend([ + Instruction::LocalGet32(local), + if shift == 24 { Instruction::I32Extend8S } else { Instruction::I32Extend16S }, + ]); + *read = output.len() - 1; + return true; + } + false +} + +fn rewrite_sign_extend64(output: &mut CompactOutput, read: &mut usize, data: &WasmFunctionData, op: BinOp) -> bool { + if op != BinOp::IShrS || *read < output.block_start + 2 { + return false; + } + if let Some((BinOp::IShl, local, shift)) = local_const64(data, output[*read - 2]) + && let Instruction::Const64(index) = output[*read - 1] + && shift == data.operand(index).value + { + let instruction = match shift { + 56 => Instruction::I64Extend8S, + 48 => Instruction::I64Extend16S, + 32 => Instruction::I64Extend32S, + _ => return false, + }; + output.truncate(*read - 2); + output.extend([Instruction::LocalGet64(local), instruction]); + *read = output.len() - 1; + return true; + } + false +} + +fn rewrite_vector_binop( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + op: BinOp128, + commutative: bool, +) -> Result<()> { + if *read >= output.block_start + 2 { + let previous = [output[*read - 2], output[*read - 1]]; + let replacement = match previous { + [Instruction::LocalGet128(a), Instruction::LocalGet128(b)] => Instruction::BinOpLocalLocal128(op, a, b), + [Instruction::LocalGet128(local), Instruction::Const128(value)] => { + Instruction::BinOpLocalConst128(PackedOp::new(op, operand!(data, LocalV128 { local, value })?)) + } + [Instruction::GlobalGet128(global), Instruction::Const128(value)] => { + Instruction::BinOpGlobalConst128(PackedOp::new(op, operand!(data, GlobalV128 { global, value })?)) + } + [Instruction::Const128(value), Instruction::LocalGet128(local)] if commutative => { + Instruction::BinOpLocalConst128(PackedOp::new(op, operand!(data, LocalV128 { local, value })?)) + } + [Instruction::Const128(value), Instruction::GlobalGet128(global)] if commutative => { + Instruction::BinOpGlobalConst128(PackedOp::new(op, operand!(data, GlobalV128 { global, value })?)) + } + _ => return Ok(()), + }; + replace!(output, *read, 2 => replacement); + } + Ok(()) +} + +fn rewrite_store32( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + index: OperandIdx<MemoryArg>, +) -> Result<()> { + let compact_arg = CompactMemoryArg::try_from(data.operand(index)).ok(); + if *read >= output.block_start + 3 { + let previous = [output[*read - 3], output[*read - 2], output[*read - 1]]; + if let [ + Instruction::LocalGet32(addr) | Instruction::LocalGet64(addr), + Instruction::LoadLocal32(arg), + Instruction::AddConst32(1), + ] = previous + && { compact_arg == Some(data.operand(arg.memory_arg_idx)) } + && addr == u16::from(arg.local1) + { + replace!(output, *read, 3 => Instruction::IncMemoryLocal32(arg)); + return Ok(()); + } + } + if *read >= output.block_start + 2 { + let previous = [output[*read - 2], output[*read - 1]]; + match previous { + [Instruction::F32Mul, Instruction::F32Add] + if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) => + { + replace!(output, *read, 2 => Instruction::FMaStoreF32(arg)); + } + [Instruction::BinOpStackLocal32(BinOp::FMul, local), Instruction::F32Add] + if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) => + { + replace!(output, *read, 2 => [Instruction::LocalGet32(local), Instruction::FMaStoreF32(arg)]); + } + [Instruction::LocalGet32(addr), Instruction::LocalGet32(value)] + if let (Ok(addr), Ok(value), Some(memory_arg)) = + (u8::try_from(addr), u8::try_from(value), compact_arg) => + { + let memory_arg_idx = operand!(data, memory_arg)?; + replace!(output, *read, 2 => Instruction::StoreLocalLocal32(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value })); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_store64( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + index: OperandIdx<MemoryArg>, +) -> Result<()> { + let compact_arg = CompactMemoryArg::try_from(data.operand(index)).ok(); + if *read >= output.block_start + 3 { + let previous = [output[*read - 3], output[*read - 2], output[*read - 1]]; + if let [ + Instruction::LocalGet32(addr) | Instruction::LocalGet64(addr), + Instruction::LoadLocal64(arg), + Instruction::Const64(one), + ] = previous + && { compact_arg == Some(data.operand(arg.memory_arg_idx)) } + && addr == u16::from(arg.local1) + && data.operand(one).value == 1 + { + replace!(output, *read, 3 => Instruction::IncMemoryLocal64(arg)); + return Ok(()); + } + } + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::F64Mul, Instruction::F64Add] + if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) => + { + replace!(output, *read, 2 => Instruction::FMaStoreF64(arg)); + } + [Instruction::LocalGet32(addr), Instruction::LocalGet64(value)] + if let (Ok(addr), Ok(value), Some(memory_arg)) = + (u8::try_from(addr), u8::try_from(value), compact_arg) => + { + let memory_arg_idx = operand!(data, memory_arg)?; + replace!(output, *read, 2 => Instruction::StoreLocalLocal64(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value })); + } + _ => {} + } + } + Ok(()) +} + +macro_rules! local_const_set { + ($data:expr, 32, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ + let index = operand!($data, LocalConstSet32 { local: $src, dst: $dst, value: $value as u32 })?; + if $tee { + Instruction::BinOpLocalConstTee32(PackedOp::new($op, index)) + } else { + Instruction::BinOpLocalConstSet32(PackedOp::new($op, index)) + } + }}; + ($data:expr, 64, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ + let index = operand!($data, LocalConstSet64 { local: $src, dst: $dst, value: $value as u64 })?; + if $tee { + Instruction::BinOpLocalConstTee64(PackedOp::new($op, index)) + } else { + Instruction::BinOpLocalConstSet64(PackedOp::new($op, index)) + } + }}; + ($data:expr, 128, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{ + let index = operand!($data, LocalConstSetV128 { local: $src, dst: $dst, value: $value })?; + if $tee { + Instruction::BinOpLocalConstTee128(PackedOp::new($op, index)) + } else { + Instruction::BinOpLocalConstSet128(PackedOp::new($op, index)) + } + }}; +} + +fn rewrite_local_set32( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::I32Mul, Instruction::BinOpStackLocal32(BinOp::IAdd, acc)] if acc == dst => { + replace!(output, *read, 2 => Instruction::MulAccLocal32(dst)); + return Ok(()); + } + [Instruction::F32Mul, Instruction::BinOpStackLocal32(BinOp::FAdd, acc)] if acc == dst => { + replace!(output, *read, 2 => Instruction::FMulAccLocal32(dst)); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet32(src) if src == dst => { + output.truncate(*read - 1); + *read = output.len(); + return Ok(()); + } + Instruction::LocalGet32(src) => replace!(output, *read, 1 => Instruction::LocalCopy32(src, dst)), + Instruction::Const32(value) => { + replace!(output, *read, 1 => Instruction::SetLocalConst32(I32LocalArg { value, local: dst })) + } + Instruction::BinOpLocalLocal32(op, left, right) => { + let replacement = if op == BinOp::IAdd { + Instruction::AddLocalLocalSet32(LocalTripleArg { left, right, dst }) + } else { + Instruction::BinOpLocalLocalSet32(PackedOp::new( + op, + operand!(data, LocalTripleArg { left, right, dst })?, + )) + }; + replace!(output, *read, 1 => replacement); + } + instruction if let Some((op, src, value)) = local_const32(data, instruction) => { + if src == dst + && let Some(delta) = op.inc_delta(value) + { + replace!(output, *read, 1 => Instruction::IncLocal32(I32LocalArg { value: delta, local: dst })); + } else { + let replacement = local_const_set!(data, 32, op, src, dst, value, false); + replace!(output, *read, 1 => replacement); + } + } + Instruction::BinOpStackLocal32(op, local) => { + replace!(output, *read, 1 => Instruction::BinOpStackLocalSet32(op, local, dst)); + } + Instruction::LoadLocal32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet32(arg)); + } + Instruction::LoadLocal8S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet8S32(arg)); + } + Instruction::LoadLocal8U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet8U32(arg)); + } + Instruction::LoadLocal16S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet16S32(arg)); + } + Instruction::LoadLocal16U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalSet16U32(arg)); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_set64( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 3 { + match [output[*read - 3], output[*read - 2], output[*read - 1]] { + [Instruction::I64Mul, Instruction::LocalGet64(acc), Instruction::I64Add] if acc == dst => { + replace!(output, *read, 3 => Instruction::MulAccLocal64(dst)); + return Ok(()); + } + [Instruction::F64Mul, Instruction::LocalGet64(acc), Instruction::F64Add] if acc == dst => { + replace!(output, *read, 3 => Instruction::FMulAccLocal64(dst)); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet64(src) if src == dst => { + output.truncate(*read - 1); + *read = output.len(); + return Ok(()); + } + Instruction::LocalGet64(src) => replace!(output, *read, 1 => Instruction::LocalCopy64(src, dst)), + Instruction::Const64(index) => { + replace!(output, *read, 1 => Instruction::SetLocalConst64(PackedOp::new(dst, index))); + } + Instruction::BinOpLocalLocal64(op, left, right) => { + let index = operand!(data, LocalTripleArg { left, right, dst })?; + replace!(output, *read, 1 => Instruction::BinOpLocalLocalSet64(PackedOp::new(op, index))); + } + instruction if let Some((op, src, value)) = local_const64(data, instruction) => { + if src == dst && matches!(op, BinOp::IAdd | BinOp::ISub) { + let delta = if op == BinOp::IAdd { value } else { value.wrapping_neg() }; + let index = operand!(data, I64Operand { value: delta })?; + replace!(output, *read, 1 => Instruction::IncLocal64(PackedOp::new(dst, index))); + } else { + let replacement = local_const_set!(data, 64, op, src, dst, value, false); + replace!(output, *read, 1 => replacement); + } + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_set128( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 + && let [Instruction::LocalGet32(local), Instruction::V128Load(index)] = [output[*read - 2], output[*read - 1]] + && let (Ok(local), Ok(dst), Ok(memory_arg)) = + (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand(index))) + { + let memory_arg_idx = operand!(data, memory_arg)?; + replace!(output, *read, 2 => Instruction::LoadLocalSet128(MemoryLocalArg { + memory_arg_idx, + local1: local, + local2: dst, + })); + return Ok(()); + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet128(src) if src == dst => { + output.truncate(*read - 1); + *read = output.len(); + return Ok(()); + } + Instruction::LocalGet128(src) => replace!(output, *read, 1 => Instruction::LocalCopy128(src, dst)), + Instruction::Const128(value) => { + replace!(output, *read, 1 => Instruction::SetLocalConst128(PackedOp::new(dst, value))) + } + Instruction::BinOpLocalLocal128(op, left, right) => { + let index = operand!(data, LocalTripleArg { left, right, dst })?; + replace!(output, *read, 1 => Instruction::BinOpLocalLocalSet128(PackedOp::new(op, index))); + } + instruction if let Some((op, src, value)) = local_const128(data, instruction) => { + let replacement = local_const_set!(data, 128, op, src, dst, value, false); + replace!(output, *read, 1 => replacement); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_tee32( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::Const32(value), Instruction::I32And] => { + replace!(output, *read, 2 => Instruction::AndConstTee32(I32LocalArg { value, local: dst })); + return Ok(()); + } + [Instruction::Const32(value), Instruction::I32Sub] => { + replace!(output, *read, 2 => Instruction::SubConstTee32(I32LocalArg { value, local: dst })); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet32(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet32(src)), + Instruction::BinOpLocalLocal32(op, left, right) => { + let replacement = if op == BinOp::IAdd { + Instruction::AddLocalLocalTee32(LocalTripleArg { left, right, dst }) + } else { + Instruction::BinOpLocalLocalTee32(PackedOp::new( + op, + operand!(data, LocalTripleArg { left, right, dst })?, + )) + }; + replace!(output, *read, 1 => replacement); + } + instruction if let Some((op, src, value)) = local_const32(data, instruction) => { + let replacement = local_const_set!(data, 32, op, src, dst, value, true); + replace!(output, *read, 1 => replacement); + } + Instruction::BinOpStackLocal32(op, local) => { + replace!(output, *read, 1 => Instruction::BinOpStackLocalTee32(op, local, dst)); + } + Instruction::LoadLocal32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee32(arg)); + } + Instruction::LoadLocal8S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee8S32(arg)); + } + Instruction::LoadLocal8U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee8U32(arg)); + } + Instruction::LoadLocal16S32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee16S32(arg)); + } + Instruction::LoadLocal16U32(mut arg) if let Ok(dst) = u8::try_from(dst) => { + arg.local2 = dst; + replace!(output, *read, 1 => Instruction::LoadLocalTee16U32(arg)); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_tee64( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::Const64(value), Instruction::I64And] => { + replace!(output, *read, 2 => Instruction::AndConstTee64(PackedOp::new(dst, value))); + return Ok(()); + } + [Instruction::Const64(value), Instruction::I64Sub] => { + replace!(output, *read, 2 => Instruction::SubConstTee64(PackedOp::new(dst, value))); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet64(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet64(src)), + Instruction::BinOpLocalLocal64(op, left, right) => { + let index = operand!(data, LocalTripleArg { left, right, dst })?; + replace!(output, *read, 1 => Instruction::BinOpLocalLocalTee64(PackedOp::new(op, index))); + } + instruction if let Some((op, src, value)) = local_const64(data, instruction) => { + let replacement = local_const_set!(data, 64, op, src, dst, value, true); + replace!(output, *read, 1 => replacement); + } + _ => {} + } + } + Ok(()) +} + +fn rewrite_local_tee128( + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + dst: u16, +) -> Result<()> { + if *read >= output.block_start + 2 + && let [Instruction::LocalGet32(local), Instruction::V128Load(index)] = [output[*read - 2], output[*read - 1]] + && let (Ok(local), Ok(dst), Ok(memory_arg)) = + (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand(index))) + { + let memory_arg_idx = operand!(data, memory_arg)?; + replace!(output, *read, 2 => Instruction::LoadLocalTee128(MemoryLocalArg { + memory_arg_idx, + local1: local, + local2: dst, + })); + return Ok(()); + } + if *read > output.block_start { + match output[*read - 1] { + Instruction::LocalGet128(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet128(src)), + Instruction::BinOpLocalLocal128(op, left, right) => { + let index = operand!(data, LocalTripleArg { left, right, dst })?; + replace!(output, *read, 1 => Instruction::BinOpLocalLocalTee128(PackedOp::new(op, index))); + } + instruction if let Some((op, src, value)) = local_const128(data, instruction) => { + let replacement = local_const_set!(data, 128, op, src, dst, value, true); + replace!(output, *read, 1 => replacement); + } + _ => {} + } + } + Ok(()) +} + +fn int_bin_op(instruction: Instruction) -> Option<BinOp> { + Some(match instruction { + Instruction::I32Add | Instruction::I64Add => BinOp::IAdd, + Instruction::I32Sub | Instruction::I64Sub => BinOp::ISub, + Instruction::I32Mul | Instruction::I64Mul => BinOp::IMul, + Instruction::I32And | Instruction::I64And => BinOp::IAnd, + Instruction::I32Or | Instruction::I64Or => BinOp::IOr, + Instruction::I32Xor | Instruction::I64Xor => BinOp::IXor, + Instruction::I32Shl | Instruction::I64Shl => BinOp::IShl, + Instruction::I32ShrS | Instruction::I64ShrS => BinOp::IShrS, + Instruction::I32ShrU | Instruction::I64ShrU => BinOp::IShrU, + Instruction::I32Rotl | Instruction::I64Rotl => BinOp::IRotl, + Instruction::I32Rotr | Instruction::I64Rotr => BinOp::IRotr, + _ => return None, + }) +} + +fn float_bin_op(instruction: Instruction) -> Option<BinOp> { + Some(match instruction { + Instruction::F32Add | Instruction::F64Add => BinOp::FAdd, + Instruction::F32Sub | Instruction::F64Sub => BinOp::FSub, + Instruction::F32Mul | Instruction::F64Mul => BinOp::FMul, + Instruction::F32Div | Instruction::F64Div => BinOp::FDiv, + Instruction::F32Min | Instruction::F64Min => BinOp::FMin, + Instruction::F32Max | Instruction::F64Max => BinOp::FMax, + Instruction::F32Copysign | Instruction::F64Copysign => BinOp::FCopysign, + _ => return None, + }) +} + +fn cmp_op(instruction: Instruction) -> Option<CmpOp> { + Some(match instruction { + Instruction::I32Eq | Instruction::I64Eq => CmpOp::Eq, + Instruction::I32Ne | Instruction::I64Ne => CmpOp::Ne, + Instruction::I32LtS | Instruction::I64LtS => CmpOp::LtS, + Instruction::I32LtU | Instruction::I64LtU => CmpOp::LtU, + Instruction::I32GtS | Instruction::I64GtS => CmpOp::GtS, + Instruction::I32GtU | Instruction::I64GtU => CmpOp::GtU, + Instruction::I32LeS | Instruction::I64LeS => CmpOp::LeS, + Instruction::I32LeU | Instruction::I64LeU => CmpOp::LeU, + Instruction::I32GeS | Instruction::I64GeS => CmpOp::GeS, + Instruction::I32GeU | Instruction::I64GeU => CmpOp::GeU, + _ => return None, + }) +} + +fn bin_op_128(instruction: Instruction) -> Option<BinOp128> { + Some(match instruction { + Instruction::V128And => BinOp128::And, + Instruction::V128AndNot => BinOp128::AndNot, + Instruction::V128Or => BinOp128::Or, + Instruction::V128Xor => BinOp128::Xor, + Instruction::I64x2Add => BinOp128::I64x2Add, + Instruction::I64x2Mul => BinOp128::I64x2Mul, + _ => return None, + }) +} + +fn jump_cmp_local_local( + data: &mut WasmFunctionData, + target: u32, + left: u16, + right: u16, + op: CmpOp, + width64: bool, +) -> Result<Instruction> { + let index = target_operand!(data, LocalLocalCmp { target, left, right })?; + Ok(if width64 { + Instruction::JumpCmpLocalLocal64(PackedOp::new(op, index)) + } else { + Instruction::JumpCmpLocalLocal32(PackedOp::new(op, index)) + }) +} + +fn rewrite_jump( + source: &[Instruction], + output: &mut CompactOutput, + index: usize, + data: &mut WasmFunctionData, + old_index: u32, + target: u32, +) -> Result<()> { + let target = resolve_jump_target(source, data, target); + let exit = old_index + 1; + let body = target + 1; + if let Some(instruction) = source.get(target as usize).copied() { + match instruction { + Instruction::JumpCmpLocalLocal32(side) + if resolve_jump_target(source, data, data.operand(side.index).target) == exit && body > target => + { + let value = data.operand(side.index); + output[index] = jump_cmp_local_local(data, body, value.left, value.right, side.op.inverse(), false)?; + return Ok(()); + } + Instruction::JumpCmpLocalLocal64(side) + if resolve_jump_target(source, data, data.operand(side.index).target) == exit && body > target => + { + let value = data.operand(side.index); + output[index] = jump_cmp_local_local(data, body, value.left, value.right, side.op.inverse(), true)?; + return Ok(()); + } + _ => {} + } + } + if matches!(output[index], Instruction::Jump(_)) && target == exit { + output.truncate(index); + } else { + set_rewrite_target(&mut output[index], data, target)?; + } + Ok(()) +} + +fn jump_cmp_stack_local( + data: &mut WasmFunctionData, + target: u32, + local: u16, + op: CmpOp, + width64: bool, +) -> Result<Instruction> { + let index = target_operand!(data, TargetLocal { target, local })?; + Ok(if width64 { + Instruction::JumpCmpStackLocal64(PackedOp::new(op, index)) + } else { + Instruction::JumpCmpStackLocal32(PackedOp::new(op, index)) + }) +} + +fn jump_cmp_local_const32( + data: &mut WasmFunctionData, + target: u32, + local: u16, + value: i32, + op: CmpOp, +) -> Result<Instruction> { + if value == 0 { + return Ok(match op { + CmpOp::Eq => Instruction::JumpIfLocalZero32(TargetLocalArg { target_ip: target, local }), + CmpOp::Ne => Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }), + _ => Instruction::JumpCmpLocalConst32(PackedOp::new( + op, + target_operand!(data, LocalConstCmp { target, value, local })?, + )), + }); + } + Ok(Instruction::JumpCmpLocalConst32(PackedOp::new( + op, + target_operand!(data, LocalConstCmp { target, value, local })?, + ))) +} + +fn jump_cmp_local_const64( + data: &mut WasmFunctionData, + target: u32, + local: u16, + value: i32, + op: CmpOp, +) -> Result<Instruction> { + if value == 0 { + match op { + CmpOp::Eq => return Ok(Instruction::JumpIfLocalZero64(TargetLocalArg { target_ip: target, local })), + CmpOp::Ne => return Ok(Instruction::JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local })), + _ => {} + } + } + Ok(Instruction::JumpCmpLocalConst64(PackedOp::new( + op, + target_operand!(data, LocalConstCmp { target, value, local })?, + ))) +} + +fn jump_cmp_stack_const32(data: &mut WasmFunctionData, target: u32, value: i32, op: CmpOp) -> Result<Instruction> { + if value == 0 { + match op { + CmpOp::Eq => return Ok(Instruction::JumpIfZero32(target)), + CmpOp::Ne => return Ok(Instruction::JumpIfNonZero32(target)), + _ => {} + } + } + Ok(Instruction::JumpCmpStackConst32(PackedOp::new(op, target_operand!(data, StackConst32 { target, value })?))) +} + +fn jump_cmp_stack_const64(data: &mut WasmFunctionData, target: u32, value: i64, op: CmpOp) -> Result<Instruction> { + if value == 0 { + match op { + CmpOp::Eq => return Ok(Instruction::JumpIfZero64(target)), + CmpOp::Ne => return Ok(Instruction::JumpIfNonZero64(target)), + _ => {} + } + } + Ok(Instruction::JumpCmpStackConst64(PackedOp::new(op, target_operand!(data, StackConst64 { target, value })?))) +} + +fn update_jump( + data: &mut WasmFunctionData, + target: u32, + immediate: i32, + address: u32, + op: BinOp, + on_zero: bool, + global: bool, +) -> Result<Instruction> { + if let Some(delta) = op.inc_delta(immediate) { + Ok(if global { + Instruction::IncGlobalJump32(target_operand!( + data, + GlobalUpdate { target, value: delta, global: address, on_zero: u8::from(on_zero) } + )?) + } else { + Instruction::IncLocalJump32(target_operand!( + data, + LocalUpdate { target, value: delta, local: address as u16, on_zero: u8::from(on_zero) } + )?) + }) + } else { + Ok(if global { + Instruction::BinOpGlobalConstJump32(PackedOp::new( + op, + target_operand!( + data, + GlobalUpdate { target, value: immediate, global: address, on_zero: u8::from(on_zero) } + )?, + )) + } else { + Instruction::BinOpLocalConstJump32(PackedOp::new( + op, + target_operand!( + data, + LocalUpdate { target, value: immediate, local: address as u16, on_zero: u8::from(on_zero) } + )?, + )) + }) + } +} + +fn rewrite_conditional( + source: &[Instruction], + output: &mut CompactOutput, + read: &mut usize, + data: &mut WasmFunctionData, + target: u32, + on_zero: bool, +) -> Result<()> { + let target = resolve_jump_target(source, data, target); + if *read > output.block_start + && let Instruction::BinOpLocalConstTee32(packed) = output[*read - 1] + { + let value = data.operand(packed.index); + if value.local == value.dst { + let replacement = + update_jump(data, target, value.value as i32, u32::from(value.local), packed.op, on_zero, false)?; + replace!(output, *read, 1 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 2 + && let [Instruction::BinOpGlobalConst32(packed), Instruction::GlobalTee32(dst)] = + [output[*read - 2], output[*read - 1]] + { + let value = data.operand(packed.index); + if value.global == dst { + let replacement = update_jump(data, target, value.value as i32, dst, packed.op, on_zero, true)?; + replace!(output, *read, 2 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 3 + && let [Instruction::AddConst32(value), Instruction::LocalTee32(local), Instruction::LocalGet32(cond)] = + [output[*read - 3], output[*read - 2], output[*read - 1]] + && local == cond + { + let replacement = Instruction::IncStackTeeLocalJump32(target_operand!( + data, + LocalUpdate { target, value, local, on_zero: u8::from(on_zero) } + )?); + replace!(output, *read, 3 => replacement); + return Ok(()); + } + if *read >= output.block_start + 2 { + let update = match [output[*read - 2], output[*read - 1]] { + [Instruction::AndConstTee32(arg), Instruction::LocalGet32(cond)] if arg.local == cond => { + Some((arg.local, arg.value, Some(BinOp::IAnd))) + } + [Instruction::SubConstTee32(arg), Instruction::LocalGet32(cond)] if arg.local == cond => { + Some((arg.local, arg.value.wrapping_neg(), None)) + } + _ => None, + }; + if let Some((local, value, op)) = update { + let replacement = if let Some(op) = op { + Instruction::BinOpStackConstTeeLocalJump32(PackedOp::new( + op, + target_operand!(data, LocalUpdate { target, value, local, on_zero: u8::from(on_zero) })?, + )) + } else { + Instruction::IncStackTeeLocalJump32(target_operand!( + data, + LocalUpdate { target, value, local, on_zero: u8::from(on_zero) } + )?) + }; + replace!(output, *read, 2 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 3 + && let [Instruction::BinOpLocalConstTee32(packed), Instruction::LocalGet32(right), raw_cmp] = + [output[*read - 3], output[*read - 2], output[*read - 1]] + && let Some(mut cmp) = cmp_op(raw_cmp) + { + let value = data.operand(packed.index); + if value.local == value.dst { + if on_zero { + cmp = cmp.inverse(); + } + let replacement = if let Some(delta) = packed.op.inc_delta(value.value as i32) { + Instruction::IncLocalJumpCmpLocal32(PackedOp::new( + cmp, + target_operand!(data, LocalUpdateCmp { target, value: delta, local: value.local, right })?, + )) + } else { + Instruction::BinOpLocalConstJumpCmpLocal32(PackedOp::new( + (packed.op, cmp), + target_operand!( + data, + LocalUpdateCmp { target, value: value.value as i32, local: value.local, right } + )?, + )) + }; + replace!(output, *read, 3 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 2 { + match [output[*read - 2], output[*read - 1]] { + [Instruction::LocalGet32(local), Instruction::I32Eqz] => { + replace!(output, *read, 2 => + if on_zero { + Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }) + } else { + Instruction::JumpIfLocalZero32(TargetLocalArg { target_ip: target, local }) + } + ); + return Ok(()); + } + [Instruction::LocalGet64(local), Instruction::I64Eqz] => { + replace!(output, *read, 2 => + if on_zero { + Instruction::JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local }) + } else { + Instruction::JumpIfLocalZero64(TargetLocalArg { target_ip: target, local }) + } + ); + return Ok(()); + } + [Instruction::CmpLocalLocal32(op, left, right), Instruction::I32Eqz] => { + let op = if on_zero { op } else { op.inverse() }; + let replacement = jump_cmp_local_local(data, target, left, right, op, false)?; + replace!(output, *read, 2 => replacement); + return Ok(()); + } + _ => {} + } + } + if *read > output.block_start { + let previous = output[*read - 1]; + let replacement = match previous { + Instruction::I32Eqz => { + Some(if on_zero { Instruction::JumpIfNonZero32(target) } else { Instruction::JumpIfZero32(target) }) + } + Instruction::I64Eqz => { + Some(if on_zero { Instruction::JumpIfNonZero64(target) } else { Instruction::JumpIfZero64(target) }) + } + Instruction::CmpLocalLocal32(op, left, right) => { + Some(jump_cmp_local_local(data, target, left, right, if !on_zero { op } else { op.inverse() }, false)?) + } + Instruction::CmpLocalLocal64(op, left, right) => { + Some(jump_cmp_local_local(data, target, left, right, if !on_zero { op } else { op.inverse() }, true)?) + } + Instruction::LocalGet32(local) => Some(if on_zero { + Instruction::JumpIfLocalZero32(TargetLocalArg { target_ip: target, local }) + } else { + Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }) + }), + Instruction::LocalGet64(local) => Some(if on_zero { + Instruction::JumpIfLocalZero64(TargetLocalArg { target_ip: target, local }) + } else { + Instruction::JumpIfLocalNonZero64(TargetLocalArg { target_ip: target, local }) + }), + _ => None, + }; + if let Some(replacement) = replacement { + replace!(output, *read, 1 => replacement); + return Ok(()); + } + } + if *read >= output.block_start + 3 { + let raw_cmp = output[*read - 1]; + if let Some(mut op) = cmp_op(raw_cmp) { + if on_zero { + op = op.inverse(); + } + let replacement = match [output[*read - 3], output[*read - 2]] { + [Instruction::LocalGet32(local), Instruction::Const32(value)] => { + Some(jump_cmp_local_const32(data, target, local, value, op)?) + } + [Instruction::LocalGet64(local), Instruction::Const64(index)] + if let Ok(value) = i32::try_from(data.operand(index).value) => + { + Some(jump_cmp_local_const64(data, target, local, value, op)?) + } + [Instruction::LocalGet32(left), Instruction::LocalGet32(right)] => { + Some(jump_cmp_local_local(data, target, left, right, op, false)?) + } + [Instruction::LocalGet64(left), Instruction::LocalGet64(right)] => { + Some(jump_cmp_local_local(data, target, left, right, op, true)?) + } + _ => None, + }; + if let Some(replacement) = replacement { + replace!(output, *read, 3 => replacement); + return Ok(()); + } + } + } + if *read >= output.block_start + 2 { + let raw_cmp = output[*read - 1]; + if let Some(mut op) = cmp_op(raw_cmp) { + if on_zero { + op = op.inverse(); + } + let replacement = match output[*read - 2] { + Instruction::LocalGet32(local) => Some(jump_cmp_stack_local(data, target, local, op, false)?), + Instruction::LocalGet64(local) => Some(jump_cmp_stack_local(data, target, local, op, true)?), + Instruction::Const32(value) => Some(jump_cmp_stack_const32(data, target, value, op)?), + Instruction::Const64(index) => { + Some(jump_cmp_stack_const64(data, target, data.operand(index).value, op)?) + } + _ => None, + }; + if let Some(replacement) = replacement { + replace!(output, *read, 2 => replacement); + return Ok(()); + } + } + } + Ok(()) +} + +fn is_unconditional_terminator(instruction: Instruction) -> bool { + matches!( + instruction, + Instruction::Unreachable + | Instruction::Jump(_) + | Instruction::BranchTable(_) + | Instruction::Return + | Instruction::ReturnVoid + | Instruction::Return32 + | Instruction::Return64 + | Instruction::Return128 + | Instruction::ReturnCall(_) + | Instruction::ReturnCallSelf + | Instruction::ReturnCallIndirect(_) + | Instruction::ReturnCallRef(_) + | Instruction::Throw(_) + | Instruction::ThrowRef + ) +} diff --git a/crates/parser/src/optimize/targets.rs b/crates/parser/src/optimize/targets.rs new file mode 100644 index 0000000..36bdf2f --- /dev/null +++ b/crates/parser/src/optimize/targets.rs @@ -0,0 +1,290 @@ +use crate::visit::{BuilderRawOperand, FunctionDataBuilder}; +use crate::{ParseError, Result}; +use alloc::vec::Vec; +use tinywasm_types::{ + BranchTableArg, CastBranch, GlobalUpdate, Instruction, LocalConstCmp, LocalLocalCmp, LocalUpdate, LocalUpdateCmp, + OperandIdx, OperandType, PackedOp, StackConst32, StackConst64, TargetLocal, +}; + +pub(super) trait TargetOperand: OperandType { + fn set_target(&mut self, target: u32); +} + +macro_rules! target_operands { + ($($name:ty),+ $(,)?) => {$( + impl TargetOperand for $name { + fn set_target(&mut self, target: u32) { self.target = target; } + } + )+}; +} + +target_operands!( + TargetLocal, + CastBranch, + StackConst32, + StackConst64, + LocalUpdate, + GlobalUpdate, + LocalUpdateCmp, + LocalConstCmp, + LocalLocalCmp, + BranchTableArg, +); + +pub(super) fn resolve_jump_target(instructions: &[Instruction], data: &FunctionDataBuilder, target: u32) -> u32 { + let mut index = target as usize; + let mut steps = 0; + while let Some(instruction) = instructions.get(index) + && let Some(next) = instruction_target(data, *instruction) + && matches!(instruction, Instruction::Jump(_)) + && steps < instructions.len() + { + index = next as usize; + steps += 1; + } + index as u32 +} + +pub(super) fn set_rewrite_target( + instruction: &mut Instruction, + data: &mut FunctionDataBuilder, + target: u32, +) -> Result<()> { + use Instruction::*; + match instruction { + JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => { + *packed = push_packed_target_copy(data, *packed, target)? + } + BrOnCast(index) | BrOnCastFail(index) => *index = push_target_copy(data, *index, target)?, + JumpCmpStackConst32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + JumpCmpStackConst64(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => { + *packed = push_packed_target_copy(data, *packed, target)? + } + BinOpLocalConstJumpCmpLocal32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + BinOpGlobalConstJump32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + IncLocalJump32(index) | IncStackTeeLocalJump32(index) => *index = push_target_copy(data, *index, target)?, + IncGlobalJump32(index) => *index = push_target_copy(data, *index, target)?, + IncLocalJumpCmpLocal32(packed) => *packed = push_packed_target_copy(data, *packed, target)?, + JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => { + *packed = push_packed_target_copy(data, *packed, target)? + } + JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => { + *packed = push_packed_target_copy(data, *packed, target)? + } + BranchTable(index) => *index = push_target_copy(data, *index, target)?, + _ => set_target(instruction, data, target), + } + Ok(()) +} + +fn push_target_copy<T: TargetOperand>( + data: &mut FunctionDataBuilder, + index: OperandIdx<T>, + target: u32, +) -> Result<OperandIdx<T>> +where + T::Raw: BuilderRawOperand, +{ + let mut value = data.operand(index); + value.set_target(target); + data.push_target_operand(value) +} + +fn push_packed_target_copy<Op: Copy, T: TargetOperand>( + data: &mut FunctionDataBuilder, + packed: PackedOp<Op, T>, + target: u32, +) -> Result<PackedOp<Op, T>> +where + T::Raw: BuilderRawOperand, +{ + let mut value = data.operand(packed.index); + value.set_target(target); + Ok(PackedOp::new(packed.op, data.push_target_operand(value)?)) +} + +fn instruction_target(data: &FunctionDataBuilder, instruction: Instruction) -> Option<u32> { + use Instruction::*; + Some(match instruction { + Jump(target) + | JumpIfZero32(target) + | JumpIfNonZero32(target) + | JumpIfZero64(target) + | JumpIfNonZero64(target) + | JumpIfRefNull(target) + | JumpIfRefNonNull(target) => target, + JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => { + arg.target_ip + } + JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => data.operand(packed.index).target, + BrOnCast(index) | BrOnCastFail(index) => data.operand(index).target, + JumpCmpStackConst32(packed) => data.operand(packed.index).target, + JumpCmpStackConst64(packed) => data.operand(packed.index).target, + BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => data.operand(packed.index).target, + BinOpLocalConstJumpCmpLocal32(packed) => data.operand(packed.index).target, + BinOpGlobalConstJump32(packed) => data.operand(packed.index).target, + IncLocalJump32(index) | IncStackTeeLocalJump32(index) => data.operand(index).target, + IncGlobalJump32(index) => data.operand(index).target, + IncLocalJumpCmpLocal32(packed) => data.operand(packed.index).target, + JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => data.operand(packed.index).target, + JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => data.operand(packed.index).target, + BranchTable(index) => data.operand(index).target, + _ => return None, + }) +} + +fn set_target(instruction: &mut Instruction, data: &mut FunctionDataBuilder, target: u32) { + use Instruction::*; + match instruction { + Jump(value) + | JumpIfZero32(value) + | JumpIfNonZero32(value) + | JumpIfZero64(value) + | JumpIfNonZero64(value) + | JumpIfRefNull(value) + | JumpIfRefNonNull(value) => *value = target, + JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => { + arg.target_ip = target + } + JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => set_packed_operand_target(data, *packed, target), + BrOnCast(index) | BrOnCastFail(index) => set_operand_target(data, *index, target), + JumpCmpStackConst32(packed) => set_packed_operand_target(data, *packed, target), + JumpCmpStackConst64(packed) => set_packed_operand_target(data, *packed, target), + BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => { + set_packed_operand_target(data, *packed, target) + } + BinOpLocalConstJumpCmpLocal32(packed) => set_packed_operand_target(data, *packed, target), + BinOpGlobalConstJump32(packed) => set_packed_operand_target(data, *packed, target), + IncLocalJump32(index) | IncStackTeeLocalJump32(index) => set_operand_target(data, *index, target), + IncGlobalJump32(index) => set_operand_target(data, *index, target), + IncLocalJumpCmpLocal32(packed) => set_packed_operand_target(data, *packed, target), + JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => set_packed_operand_target(data, *packed, target), + JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => set_packed_operand_target(data, *packed, target), + BranchTable(index) => set_operand_target(data, *index, target), + _ => {} + } +} + +fn set_operand_target<T: TargetOperand>(data: &mut FunctionDataBuilder, index: OperandIdx<T>, target: u32) +where + T::Raw: BuilderRawOperand, +{ + let mut value = data.operand(index); + value.set_target(target); + data.set_operand(index, value); +} + +fn set_packed_operand_target<Op: Copy, T: TargetOperand>( + data: &mut FunctionDataBuilder, + packed: PackedOp<Op, T>, + target: u32, +) where + T::Raw: BuilderRawOperand, +{ + let mut value = data.operand(packed.index); + value.set_target(target); + data.set_operand(packed.index, value); +} + +fn branch_table_range(data: &FunctionDataBuilder, instruction: Instruction) -> Option<(u32, u32)> { + let Instruction::BranchTable(index) = instruction else { return None }; + let operand = data.operand(index); + Some((operand.start, operand.len)) +} + +pub(super) fn target_boundaries(instructions: &[Instruction], data: &FunctionDataBuilder) -> Result<Vec<bool>> { + let mut boundaries = alloc::vec![false; instructions.len() + 1]; + for handler in &data.exception_handlers { + for target in [handler.start_ip, handler.end_ip] { + *boundaries.get_mut(target as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("exception handler boundary out of bounds: {target}")) + })? = true; + } + for catch in &handler.catches { + let target = catch.landing_pad(); + *boundaries + .get_mut(target as usize) + .ok_or_else(|| ParseError::Other(alloc::format!("exception landing pad out of bounds: {target}")))? = + true; + } + } + for &instruction in instructions { + if let Some(target) = instruction_target(data, instruction) { + *boundaries + .get_mut(target as usize) + .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))? = true; + } + if let Some((start, count)) = branch_table_range(data, instruction) { + let end = + start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; + let targets = data + .branch_table_targets + .get(start as usize..end as usize) + .ok_or_else(|| ParseError::Other("branch table range out of bounds".into()))?; + for &target in targets { + *boundaries.get_mut(target as usize).ok_or_else(|| { + ParseError::Other(alloc::format!("branch table target out of bounds: {target}")) + })? = true; + } + } + } + Ok(boundaries) +} + +fn remap_target(target: u32, old_to_new: Option<&[u32]>, len: u32) -> Result<u32> { + let target = if let Some(map) = old_to_new { + *map.get(target as usize) + .ok_or_else(|| ParseError::Other(alloc::format!("instruction target out of bounds: {target}")))? + } else { + target + }; + if target >= len { + return Err(ParseError::Other(alloc::format!("instruction target out of bounds: {target}"))); + } + Ok(target) +} + +pub(super) fn finalize( + instructions: &mut [Instruction], + data: &mut FunctionDataBuilder, + old_to_new: Option<&[u32]>, +) -> Result<()> { + let len = instructions.len() as u32; + for handler in &mut data.exception_handlers { + if let Some(map) = old_to_new { + handler.start_ip = *map + .get(handler.start_ip as usize) + .ok_or_else(|| ParseError::Other("exception handler boundary out of bounds".into()))?; + handler.end_ip = *map + .get(handler.end_ip as usize) + .ok_or_else(|| ParseError::Other("exception handler boundary out of bounds".into()))?; + for catch in &mut handler.catches { + let landing_pad = match catch { + tinywasm_types::ExceptionCatch::Tag { landing_pad, .. } + | tinywasm_types::ExceptionCatch::All { landing_pad, .. } => landing_pad, + }; + *landing_pad = remap_target(*landing_pad, Some(map), len)?; + } + } + if handler.start_ip > handler.end_ip || handler.end_ip > len { + return Err(ParseError::Other("exception handler range out of bounds".into())); + } + } + for target in &mut data.branch_table_targets { + *target = remap_target(*target, old_to_new, len)?; + } + for instruction in instructions { + if let Some(target) = instruction_target(data, *instruction) { + set_target(instruction, data, remap_target(target, old_to_new, len)?); + } + if let Some((start, count)) = branch_table_range(data, *instruction) { + let end = + start.checked_add(count).ok_or_else(|| ParseError::Other("branch table range overflow".into()))?; + data.branch_table_targets + .get(start as usize..end as usize) + .ok_or_else(|| ParseError::Other("branch table range out of bounds".into()))?; + } + } + Ok(()) +} diff --git a/crates/parser/src/parallel.rs b/crates/parser/src/parallel.rs index e0e3858..e29b38f 100644 --- a/crates/parser/src/parallel.rs +++ b/crates/parser/src/parallel.rs @@ -1,4 +1,4 @@ -use crate::module::{FunctionCode, optimize_function_code}; +use crate::module::{OptimizedFunctionCode, optimize_function_code}; use crate::validation::{FuncToValidate, FuncValidatorAllocations, ValidatorResources}; use crate::{ParseError, ParserOptions, Result, conversion}; use alloc::sync::Arc; @@ -64,7 +64,7 @@ fn process_function_job( imported_memory_count: u32, validator_allocs: Option<FuncValidatorAllocations>, reader_allocs: OperatorsReaderAllocations, -) -> Result<(FunctionCode, Option<FuncValidatorAllocations>, OperatorsReaderAllocations)> { +) -> Result<(OptimizedFunctionCode, Option<FuncValidatorAllocations>, OperatorsReaderAllocations)> { #[cfg(feature = "validate")] let validator = job.func_to_validate.map(|func| func.into_validator(validator_allocs.unwrap_or_default())); #[cfg(not(feature = "validate"))] @@ -74,12 +74,12 @@ fn process_function_job( }; let (code, validator_allocs, reader_allocs) = match job.body { FunctionBodyInput::Borrowed(func) => { - conversion::convert_module_code(func, validator, reader_allocs, metadata, job.ty_idx)? + conversion::convert_module_code(func, validator, reader_allocs, metadata, job.ty_idx, options)? } FunctionBodyInput::Owned(body) => { let reader = wasmparser::BinaryReader::new(&body.section_bytes[body.body_range], body.body_offset); let func = wasmparser::FunctionBody::new(reader); - conversion::convert_module_code(func, validator, reader_allocs, metadata, job.ty_idx)? + conversion::convert_module_code(func, validator, reader_allocs, metadata, job.ty_idx, options)? } }; @@ -100,7 +100,7 @@ fn process_chunk<'a>( options: &ParserOptions, imported_func_count: usize, imported_memory_count: u32, -) -> Result<Vec<FunctionCode>> { +) -> Result<Vec<OptimizedFunctionCode>> { let mut validator_allocs = None; let mut reader_allocs = OperatorsReaderAllocations::default(); let jobs = jobs.into_iter(); @@ -130,7 +130,7 @@ pub(crate) fn process_pending( options: &ParserOptions, imported_func_count: usize, imported_memory_count: u32, -) -> Result<Vec<FunctionCode>> { +) -> Result<Vec<OptimizedFunctionCode>> { let num_workers = worker_count(options, pending.len()); if num_workers == 1 { return process_chunk(pending, metadata, options, imported_func_count, imported_memory_count); diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index cecbb8c..8315fb5 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -3,10 +3,11 @@ use crate::{ conversion::{convert_heap_type, value_lane}, macros::visit::*, }; -use alloc::{boxed::Box, string::ToString, vec::Vec}; +use alloc::{boxed::Box, collections::BTreeMap, string::ToString, vec::Vec}; use tinywasm_types::{ - Global, Import, ImportKind, Instruction, MemoryArg, MemoryType, StorageType, TableDefinition, TagType, TypeSection, - ValueCounts, ValueLane, WasmFunctionData, + BranchTableArg, CastBranch, ExceptionHandler, Global, I64Operand, Import, ImportKind, Instruction, MemoryArg, + MemoryType, Operand64, Operand128, OperandIdx, OperandType, StorageType, TableDefinition, TagType, TwoU32, + TypeSection, V128Operand, ValueCounts, ValueLane, WasmFunctionData, }; use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator}; @@ -52,19 +53,107 @@ pub(crate) struct ModuleMetadata { aggregate_fields: Vec<AggregateFields>, } +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>>, +} + +pub(crate) trait BuilderRawOperand: tinywasm_types::RawOperand + Ord { + fn push(builder: &mut FunctionDataBuilder, raw: Self, deduplicate: bool) -> Result<u32>; + fn get(builder: &FunctionDataBuilder, index: u32) -> Self; + fn set(builder: &mut FunctionDataBuilder, index: u32, raw: Self); +} + +macro_rules! builder_raw_operand { + ($raw:ty, $lane:ident, $map:ident) => { + impl BuilderRawOperand for $raw { + fn push(builder: &mut FunctionDataBuilder, raw: Self, deduplicate: bool) -> Result<u32> { + if deduplicate && let Some(index) = builder.$map.as_ref().and_then(|map| map.get(&raw)) { + return Ok(*index); + } + let index = u32::try_from(builder.$lane.len()) + .map_err(|_| crate::ParseError::Other("instruction operand index overflow".into()))?; + builder.$lane.push(raw); + if deduplicate && let Some(map) = &mut builder.$map { + map.insert(raw, index); + } + Ok(index) + } + + fn get(builder: &FunctionDataBuilder, index: u32) -> Self { + *builder.$lane.get(index as usize).unwrap_or_else(|| unreachable!("invalid operand index")) + } + + fn set(builder: &mut FunctionDataBuilder, index: u32, raw: Self) { + *builder.$lane.get_mut(index as usize).unwrap_or_else(|| unreachable!("invalid operand index")) = raw; + } + } + }; +} + +builder_raw_operand!(Operand64, operands64, deduplicate64); +builder_raw_operand!(Operand128, operands128, deduplicate128); + +impl FunctionDataBuilder { + pub(crate) fn new(deduplicate_operands: bool) -> Self { + Self { + operands64: Vec::new(), + operands128: Vec::new(), + branch_table_targets: Vec::new(), + exception_handlers: Vec::new(), + deduplicate64: deduplicate_operands.then(BTreeMap::new), + deduplicate128: deduplicate_operands.then(BTreeMap::new), + } + } + + pub(crate) fn push_operand<T: OperandType>(&mut self, operand: T) -> Result<OperandIdx<T>> + where + T::Raw: BuilderRawOperand, + { + <T::Raw as BuilderRawOperand>::push(self, operand.encode(), true).map(OperandIdx::new) + } + + pub(crate) fn push_target_operand<T: OperandType>(&mut self, operand: T) -> Result<OperandIdx<T>> + where + T::Raw: BuilderRawOperand, + { + <T::Raw as BuilderRawOperand>::push(self, operand.encode(), false).map(OperandIdx::new) + } + + pub(crate) fn operand<T: OperandType>(&self, index: OperandIdx<T>) -> T + where + T::Raw: BuilderRawOperand, + { + T::decode(<T::Raw as BuilderRawOperand>::get(self, index.index())) + } + + pub(crate) fn set_operand<T: OperandType>(&mut self, index: OperandIdx<T>, operand: T) + where + T::Raw: BuilderRawOperand, + { + <T::Raw as BuilderRawOperand>::set(self, index.index(), operand.encode()) + } + + pub(crate) fn finish(self) -> WasmFunctionData { + WasmFunctionData { + operands64: self.operands64.into_boxed_slice(), + operands128: self.operands128.into_boxed_slice(), + branch_table_targets: self.branch_table_targets.into_boxed_slice(), + exception_handlers: self.exception_handlers.into_boxed_slice(), + } + } +} + enum AggregateFields { Other, Struct(Box<[ValueLane]>), Array(ValueLane), } -#[derive(Default)] -struct FunctionDataBuilder { - v128_constants: Vec<[u8; 16]>, - branch_table_targets: Vec<u32>, - exception_handlers: Vec<tinywasm_types::ExceptionHandler>, -} - pub(crate) struct FunctionBuilder<'a> { instructions: Vec<Instruction>, data: FunctionDataBuilder, @@ -83,13 +172,14 @@ impl<'a> FunctionBuilder<'a> { local_types: Vec<ValueLane>, local_addr_map: Vec<u16>, body_size: usize, + deduplicate_operands: bool, ) -> Self { Self { local_types, local_addr_map, metadata, instructions: Vec::with_capacity(body_size.min(1024)), - data: FunctionDataBuilder::default(), + data: FunctionDataBuilder::new(deduplicate_operands), control_stack: alloc::vec![ControlFrame { kind: BlockKind::Function, has_else: false, @@ -112,10 +202,18 @@ impl<'a> FunctionBuilder<'a> { &mut self, type_index: u32, field_index: u32, - instruction: fn(u32, u32) -> Instruction, + instruction: fn(OperandIdx<TwoU32>) -> Instruction, ) -> Result<()> { let size = self.metadata.struct_field(type_index, field_index)?; - self.emit(&[ValueLane::S32], &[size], instruction(type_index, field_index)) + let operand = self.push_operand(TwoU32 { first: type_index, second: field_index })?; + self.emit(&[ValueLane::S32], &[size], instruction(operand)) + } + + fn push_operand<T: OperandType>(&mut self, operand: T) -> Result<OperandIdx<T>> + where + T::Raw: BuilderRawOperand, + { + self.data.push_operand(operand) } } @@ -294,17 +392,19 @@ impl VisitSimdOperator<'_> for ValidateThenVisit<'_, '_> { pub(crate) fn process_operators( body: FunctionBody<'_>, - local_types: Vec<ValueLane>, - local_addr_map: Vec<u16>, + locals: (Vec<ValueLane>, Vec<u16>), metadata: &ModuleMetadata, ty_idx: u32, allocs: OperatorsReaderAllocations, -) -> Result<(Vec<Instruction>, WasmFunctionData, OperatorsReaderAllocations)> { + deduplicate_operands: bool, +) -> Result<(Vec<Instruction>, FunctionDataBuilder, OperatorsReaderAllocations)> { + let (local_types, local_addr_map) = locals; let body_size = body.as_bytes().len(); let reader = body.get_binary_reader_for_operators()?; let mut reader = OperatorsReader::new_with_allocs(reader, allocs); let signature = metadata.signature(ty_idx)?.clone(); - let mut builder = FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size); + let mut builder = + FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, deduplicate_operands); while !reader.eof() { let position = reader.original_position(); @@ -319,29 +419,26 @@ pub(crate) fn process_operators( } reader.finish()?; - let data = WasmFunctionData { - v128_constants: builder.data.v128_constants.into_boxed_slice(), - branch_table_targets: builder.data.branch_table_targets.into_boxed_slice(), - exception_handlers: builder.data.exception_handlers.into_boxed_slice(), - }; - Ok((builder.instructions, data, reader.into_allocations())) + Ok((builder.instructions, builder.data, reader.into_allocations())) } #[cfg(feature = "validate")] pub(crate) fn process_operators_and_validate( mut validator: FuncValidator<ValidatorResources>, body: FunctionBody<'_>, - local_types: Vec<ValueLane>, - local_addr_map: Vec<u16>, + locals: (Vec<ValueLane>, Vec<u16>), metadata: &ModuleMetadata, ty_idx: u32, allocs: OperatorsReaderAllocations, -) -> Result<(Vec<Instruction>, WasmFunctionData, FuncValidatorAllocations, OperatorsReaderAllocations)> { + deduplicate_operands: bool, +) -> Result<(Vec<Instruction>, FunctionDataBuilder, FuncValidatorAllocations, OperatorsReaderAllocations)> { + let (local_types, local_addr_map) = locals; let body_size = body.as_bytes().len(); let reader = body.get_binary_reader_for_operators()?; let mut reader = OperatorsReader::new_with_allocs(reader, allocs); let signature = metadata.signature(ty_idx)?.clone(); - let mut builder = FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size); + let mut builder = + FunctionBuilder::new(metadata, signature, local_types, local_addr_map, body_size, deduplicate_operands); while !reader.eof() { let position = reader.original_position(); @@ -356,12 +453,7 @@ pub(crate) fn process_operators_and_validate( } reader.finish()?; - let data = WasmFunctionData { - v128_constants: builder.data.v128_constants.into_boxed_slice(), - branch_table_targets: builder.data.branch_table_targets.into_boxed_slice(), - exception_handlers: builder.data.exception_handlers.into_boxed_slice(), - }; - Ok((builder.instructions, data, validator.into_allocations(), reader.into_allocations())) + Ok((builder.instructions, builder.data, validator.into_allocations(), reader.into_allocations())) } impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { @@ -395,7 +487,6 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fixed [] => [] { visit_data_drop(segment: u32) => DataDrop, visit_elem_drop(segment: u32) => ElemDrop } fixed [] => [S32] { visit_i32_const(value: i32) => Const32, visit_ref_func(function: u32) => RefFunc } - fixed [] => [S64] { visit_i64_const(value: i64) => Const64 } heap false [] => [S32] { visit_ref_null => RefNull } heap false [S32] => [S32] { visit_ref_test_non_null => RefTest, visit_ref_cast_non_null => RefCast, @@ -483,22 +574,10 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { table [] => [Addr] { visit_table_size(table: u32) => TableSize } table [S32, Addr] => [Addr] { visit_table_grow(table: u32) => TableGrow } table [Addr, S32, Addr] => [] { visit_table_fill(table: u32) => TableFill } - table [Addr, S32, S32] => [] { visit_table_init(elem_index: u32, table: u32) => TableInit } fixed [] => [S32] { visit_struct_new_default(type_index: u32) => StructNewDefault } fixed [S32] => [S32] { visit_array_new_default(type_index: u32) => ArrayNewDefault, visit_array_len => ArrayLen, } - fixed [S32, S32] => [S32] { - visit_array_new_data(type_index: u32, data_index: u32) => ArrayNewData, - visit_array_new_elem(type_index: u32, elem_index: u32) => ArrayNewElem, - } - fixed [S32, S32, S32, S32] => [] { - visit_array_init_data(type_index: u32, data_index: u32) => ArrayInitData, - visit_array_init_elem(type_index: u32, elem_index: u32) => ArrayInitElem, - } - fixed [S32, S32, S32, S32, S32] => [] { - visit_array_copy(type_index_dst: u32, type_index_src: u32) => ArrayCopy, - } array_field [Field, S32] => [S32] { visit_array_new(type_index: u32) => ArrayNew } array_field [S32, S32] => [Field] { visit_array_get(type_index: u32) => ArrayGet, visit_array_get_s(type_index: u32) => ArrayGetS, @@ -533,7 +612,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Self::Output { let size = self.metadata.struct_field(type_index, field_index)?; - self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(type_index, field_index)) + let operand = self.push_operand(TwoU32 { first: type_index, second: field_index })?; + self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(operand)) } fn visit_array_new_fixed(&mut self, type_index: u32, array_size: u32) -> Self::Output { @@ -542,7 +622,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { self.pop_expect(size)?; } self.push_sizes(&[ValueLane::S32])?; - self.instructions.push(Instruction::ArrayNewFixed(type_index, array_size)); + let operand = self.push_operand(TwoU32 { first: type_index, second: array_size })?; + self.instructions.push(Instruction::ArrayNewFixed(operand)); Ok(()) } @@ -555,7 +636,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { let signature = self.metadata.signature(type_index)?.clone(); let mut inputs = signature.params; inputs.push(self.metadata.table_size(table_index)?); - self.emit(&inputs, &signature.results, Instruction::CallIndirect(type_index, table_index)) + let operand = self.push_operand(TwoU32 { first: type_index, second: table_index })?; + self.emit(&inputs, &signature.results, Instruction::CallIndirect(operand)) } fn visit_call_ref(&mut self, type_index: u32) -> Self::Output { @@ -579,7 +661,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { inputs.push(self.metadata.table_size(table_index)?); self.apply_effect(&inputs, &[])?; self.mark_unreachable(); - self.instructions.push(Instruction::ReturnCallIndirect(type_index, table_index)); + let operand = self.push_operand(TwoU32 { first: type_index, second: table_index })?; + self.instructions.push(Instruction::ReturnCallIndirect(operand)); Ok(()) } @@ -851,7 +934,9 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { let header_ip = self.instructions.len(); let branch_table_start = self.data.branch_table_targets.len() as u32; - self.instructions.push(Instruction::BranchTable(0, branch_table_start, len)); + let branch_operand = + self.data.push_target_operand(BranchTableArg { target: 0, start: branch_table_start, len })?; + self.instructions.push(Instruction::BranchTable(branch_operand)); struct PadInfo { depth: u32, @@ -894,8 +979,10 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { .iter() .find(|pad| pad.depth == default_depth) .ok_or_else(|| crate::ParseError::Other("missing default branch table target".into()))?; - if let Instruction::BranchTable(default_ip, _, _) = &mut self.instructions[header_ip] { - *default_ip = default_pad.pad_start as u32; + if let Instruction::BranchTable(index) = self.instructions[header_ip] { + let mut operand = self.data.operand(index); + operand.target = default_pad.pad_start as u32; + self.data.set_operand(index, operand); } for pad in &pads { @@ -921,26 +1008,66 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_f64_const(&mut self, val: wasmparser::Ieee64) -> Self::Output { - self.emit(&[], &[ValueLane::S64], Instruction::Const64(val.bits() as i64)) + let operand = self.push_operand(I64Operand { value: val.bits() as i64 })?; + self.emit(&[], &[ValueLane::S64], Instruction::Const64(operand)) + } + + fn visit_i64_const(&mut self, value: i64) -> Self::Output { + let operand = self.push_operand(I64Operand { value })?; + self.emit(&[], &[ValueLane::S64], Instruction::Const64(operand)) } fn visit_table_copy(&mut self, dst_table: u32, src_table: u32) -> Self::Output { let dst = self.metadata.table_size(dst_table)?; let src = self.metadata.table_size(src_table)?; let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; - self.emit(&[dst, src, len], &[], Instruction::TableCopy { dst_table, src_table }) + let operand = self.push_operand(TwoU32 { first: dst_table, second: src_table })?; + self.emit(&[dst, src, len], &[], Instruction::TableCopy(operand)) } fn visit_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Self::Output { let dst = self.metadata.memory_size(dst_mem)?; let src = self.metadata.memory_size(src_mem)?; let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; - self.emit(&[dst, src, len], &[], Instruction::MemoryCopy { dst_mem, src_mem }) + let operand = self.push_operand(TwoU32 { first: dst_mem, second: src_mem })?; + self.emit(&[dst, src, len], &[], Instruction::MemoryCopy(operand)) } fn visit_memory_init(&mut self, data_index: u32, memory: u32) -> Self::Output { let dst = self.metadata.memory_size(memory)?; - self.emit(&[dst, ValueLane::S32, ValueLane::S32], &[], Instruction::MemoryInit(data_index, memory)) + let operand = self.push_operand(TwoU32 { first: data_index, second: memory })?; + self.emit(&[dst, ValueLane::S32, ValueLane::S32], &[], Instruction::MemoryInit(operand)) + } + + fn visit_table_init(&mut self, elem_index: u32, table: u32) -> Self::Output { + let address = self.metadata.table_size(table)?; + let operand = self.push_operand(TwoU32 { first: elem_index, second: table })?; + self.emit(&[address, ValueLane::S32, ValueLane::S32], &[], Instruction::TableInit(operand)) + } + + fn visit_array_new_data(&mut self, type_index: u32, data_index: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index, second: data_index })?; + self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewData(operand)) + } + + fn visit_array_new_elem(&mut self, type_index: u32, elem_index: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index, second: elem_index })?; + self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewElem(operand)) + } + + fn visit_array_init_data(&mut self, type_index: u32, data_index: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index, second: data_index })?; + self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitData(operand)) + } + + fn visit_array_init_elem(&mut self, type_index: u32, elem_index: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index, second: elem_index })?; + self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitElem(operand)) + } + + fn visit_array_copy(&mut self, type_index_dst: u32, type_index_src: u32) -> Self::Output { + let operand = self.push_operand(TwoU32 { first: type_index_dst, second: type_index_src })?; + self.emit(&[ValueLane::S32; 5], &[], Instruction::ArrayCopy(operand)) } fn visit_br_on_cast( @@ -1187,19 +1314,13 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { } fn visit_i8x16_shuffle(&mut self, lanes: [u8; 16]) -> Self::Output { - self.emit( - &[ValueLane::S128, ValueLane::S128], - &[ValueLane::S128], - Instruction::I8x16Shuffle(self.data.v128_constants.len() as u32), - )?; - self.data.v128_constants.push(lanes); - Ok(()) + let index = self.push_operand(V128Operand { value: lanes })?; + self.emit(&[ValueLane::S128, ValueLane::S128], &[ValueLane::S128], Instruction::I8x16Shuffle(index)) } fn visit_v128_const(&mut self, value: wasmparser::V128) -> Self::Output { - self.emit(&[], &[ValueLane::S128], Instruction::Const128(self.data.v128_constants.len() as u32))?; - self.data.v128_constants.push(*value.bytes()); - Ok(()) + let index = self.push_operand(V128Operand { value: *value.bytes() })?; + self.emit(&[], &[ValueLane::S128], Instruction::Const128(index)) } } @@ -1213,7 +1334,12 @@ impl FunctionBuilder<'_> { self.pop_expect(ValueLane::S32)?; let target = convert_heap_type(target.heap_type(), target.is_nullable())?; let conditional_ip = self.instructions.len(); - self.instructions.push(Instruction::BrOnCast(0, target, branch_on_fail)); + let operand = self.data.push_target_operand(CastBranch { target: 0, ref_type_bits: target.to_bits() })?; + self.instructions.push(if branch_on_fail { + Instruction::BrOnCastFail(operand) + } else { + Instruction::BrOnCast(operand) + }); self.push_sizes(&[ValueLane::S32])?; self.emit_dropkeep_to_label(relative_depth)?; self.emit_branch_jump_or_return(relative_depth)?; @@ -1357,10 +1483,15 @@ impl FunctionBuilder<'_> { /// Emits the stack-shaping instruction required by a branch. fn emit_dropkeep(&mut self, base: ValueCounts, keep: ValueCounts) { let target = ValueCounts { c32: base.c32 + keep.c32, c64: base.c64 + keep.c64, c128: base.c128 + keep.c128 }; - if self.lane_counts == target { - return; + if self.lane_counts.c32 != target.c32 { + self.instructions.push(Instruction::DropKeep32 { base: base.c32, keep: keep.c32 }); + } + if self.lane_counts.c64 != target.c64 { + self.instructions.push(Instruction::DropKeep64 { base: base.c64, keep: keep.c64 }); + } + if self.lane_counts.c128 != target.c128 { + self.instructions.push(Instruction::DropKeep128 { base: base.c128, keep: keep.c128 }); } - self.instructions.push(Instruction::DropKeep((base, keep).into())); } fn patch_jump(&mut self, jump_ip: usize, target: usize) { @@ -1369,10 +1500,14 @@ impl FunctionBuilder<'_> { | Instruction::JumpIfZero32(ip) | Instruction::JumpIfNonZero32(ip) | Instruction::JumpIfRefNull(ip) - | Instruction::JumpIfRefNonNull(ip) - | Instruction::BrOnCast(ip, _, _) => { + | Instruction::JumpIfRefNonNull(ip) => { *ip = target as u32; } + Instruction::BrOnCast(index) | Instruction::BrOnCastFail(index) => { + let mut operand = self.data.operand(*index); + operand.target = target as u32; + self.data.set_operand(*index, operand); + } _ => {} } } |
