summaryrefslogtreecommitdiff
path: root/crates/parser/src
diff options
context:
space:
mode:
authorHenry <mail@henrygressmann.de>2026-08-27 16:06:57 +0200
committerHenry <mail@henrygressmann.de>2026-08-27 16:06:57 +0200
commit843e0ff5601479239791f452bec9865df779839b (patch)
tree622e042f6f6cacec2a72c70f22816e8296997e41 /crates/parser/src
parenta8f42e481e9cc56834c39f073236c25cb533efc6 (diff)
chore: simplify operands, extract more exec_ methods
Signed-off-by: Henry <mail@henrygressmann.de>
Diffstat (limited to 'crates/parser/src')
-rw-r--r--crates/parser/src/conversion.rs22
-rw-r--r--crates/parser/src/lib.rs4
-rw-r--r--crates/parser/src/macros.rs17
-rw-r--r--crates/parser/src/module.rs24
-rw-r--r--crates/parser/src/optimize/rewrite.rs284
-rw-r--r--crates/parser/src/optimize/targets.rs193
-rw-r--r--crates/parser/src/visit.rs198
7 files changed, 374 insertions, 368 deletions
diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs
index 225b6ae..4cf0d02 100644
--- a/crates/parser/src/conversion.rs
+++ b/crates/parser/src/conversion.rs
@@ -186,9 +186,9 @@ pub(crate) fn convert_module_code(
}
#[cfg(feature = "validate")]
- let (body, data, validator_allocs, reader_allocs) = match validator {
+ let (body, data, uses_local_memory, validator_allocs, reader_allocs) = match validator {
Some(validator) => {
- let (body, data, validator_allocs, reader_allocs) = process_operators_and_validate(
+ let (body, data, uses_local_memory, validator_allocs, reader_allocs) = process_operators_and_validate(
validator,
func,
(local_types, local_addr_map),
@@ -197,10 +197,10 @@ pub(crate) fn convert_module_code(
reader_allocs,
options.deduplicate_operands(),
)?;
- (body, data, Some(validator_allocs), reader_allocs)
+ (body, data, uses_local_memory, Some(validator_allocs), reader_allocs)
}
None => {
- let (body, data, reader_allocs) = process_operators(
+ let (body, data, uses_local_memory, reader_allocs) = process_operators(
func,
(local_types, local_addr_map),
metadata,
@@ -208,13 +208,13 @@ pub(crate) fn convert_module_code(
reader_allocs,
options.deduplicate_operands(),
)?;
- (body, data, None, reader_allocs)
+ (body, data, uses_local_memory, None, reader_allocs)
}
};
#[cfg(not(feature = "validate"))]
- let (body, data, validator_allocs, reader_allocs) = {
+ let (body, data, uses_local_memory, validator_allocs, reader_allocs) = {
let _ = validator;
- let (body, data, reader_allocs) = process_operators(
+ let (body, data, uses_local_memory, reader_allocs) = process_operators(
func,
(local_types, local_addr_map),
metadata,
@@ -222,9 +222,13 @@ pub(crate) fn convert_module_code(
reader_allocs,
options.deduplicate_operands(),
)?;
- (body, data, None, reader_allocs)
+ (body, data, uses_local_memory, None, reader_allocs)
};
- Ok((FunctionCode { instructions: body, data, locals: local_counts }, validator_allocs, reader_allocs))
+ Ok((
+ FunctionCode { instructions: body, data, locals: local_counts, uses_local_memory },
+ validator_allocs,
+ reader_allocs,
+ ))
}
pub(crate) fn convert_rec_group(ty: wasmparser::RecGroup, group_start: u32, types: &mut Vec<SubType>) -> Result<u32> {
diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs
index 3369f7b..4954056 100644
--- a/crates/parser/src/lib.rs
+++ b/crates/parser/src/lib.rs
@@ -61,11 +61,11 @@ pub struct ParserOptions {
/// Disable this only for trusted input. Parsing without validation may produce
/// a module that violates runtime assumptions.
pub validation: bool,
+
/// Whether to run the peephole rewrite optimizer.
pub optimize_rewrite: bool,
+
/// Whether to deduplicate immutable function operands while parsing.
- ///
- /// This uses more parse CPU to reduce precompiled module and archive size.
pub deduplicate_operands: bool,
#[cfg(parallel_parser)]
diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs
index 5e675e6..f807c0f 100644
--- a/crates/parser/src/macros.rs
+++ b/crates/parser/src/macros.rs
@@ -72,7 +72,10 @@ pub(crate) mod visit {
) => {
fn $visit(&mut self, memarg: wasmparser::MemArg $(, $lane: $ty)?) -> Self::Output {
let address = self.metadata.memory_size(memarg.memory)?;
- let memory_arg_idx = self.push_operand(MemoryArg::new(memarg.offset, memarg.memory))?;
+ self.mark_memory(memarg.memory);
+ let memory_arg_idx = self.push_operand128(tinywasm_types::Operand128::<
+ tinywasm_types::MemoryOperand,
+ >::new(memarg.offset, memarg.memory))?;
lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*]
lowering_ops!(@memory_instruction $instr memory_arg_idx $(, $lane)?))
}
@@ -87,7 +90,17 @@ pub(crate) mod visit {
lowering_ops!(@resolved global_size $inputs => $outputs $($operator)*);
};
(@memory_index $inputs:tt => $outputs:tt $($operator:tt)*) => {
- lowering_ops!(@resolved memory_size $inputs => $outputs $($operator)*);
+ lowering_ops!(@memory_index_impl $inputs => $outputs $($operator)*);
+ };
+ (@memory_index_impl [$($input:ident),*] => [$($output:ident),*]
+ $visit:ident($index:ident: $ty:ty) => $instr:ident
+ ) => {
+ fn $visit(&mut self, $index: $ty) -> Self::Output {
+ let address = self.metadata.memory_size($index)?;
+ self.mark_memory($index);
+ lowering_ops!(@emit self address(address) [$($input),*] => [$($output),*]
+ Instruction::$instr($index).into())
+ }
};
(@table $inputs:tt => $outputs:tt $($operator:tt)*) => {
lowering_ops!(@resolved table_size $inputs => $outputs $($operator)*);
diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs
index bfb28ce..4cd4406 100644
--- a/crates/parser/src/module.rs
+++ b/crates/parser/src/module.rs
@@ -13,12 +13,14 @@ pub(crate) struct FunctionCode {
pub instructions: Vec<Instruction>,
pub data: crate::visit::FunctionDataBuilder,
pub locals: ValueCounts,
+ pub uses_local_memory: bool,
}
pub(crate) struct OptimizedFunctionCode {
pub instructions: Vec<Instruction>,
pub data: WasmFunctionData,
pub locals: ValueCounts,
+ pub uses_local_memory: bool,
}
pub(crate) fn optimize_function_code(
@@ -30,7 +32,12 @@ pub(crate) fn optimize_function_code(
let optimized =
optimize::optimize_instructions(code.instructions, &mut code.data, options, function_results, self_func_addr)?;
let data = code.data.finish();
- Ok(OptimizedFunctionCode { instructions: optimized.instructions, data, locals: code.locals })
+ Ok(OptimizedFunctionCode {
+ instructions: optimized.instructions,
+ data,
+ locals: code.locals,
+ uses_local_memory: code.uses_local_memory,
+ })
}
#[derive(Default)]
@@ -535,6 +542,20 @@ impl<'a> ModuleReader<'a> {
.chain(self.code_type_addrs.iter().copied())
.collect();
+ let imported_memory_count =
+ self.imports.iter().filter(|import| matches!(import.kind, ImportKind::Memory(_))).count();
+ let uses_local_memory = self.code.iter().any(|code| code.uses_local_memory);
+ let exports_local_memory = self
+ .exports
+ .iter()
+ .any(|export| export.kind == ExternalKind::Memory && export.index as usize >= imported_memory_count);
+ let initializes_local_memory = self
+ .data
+ .iter()
+ .any(|data| matches!(data.kind, DataKind::Active { mem, .. } if mem as usize >= imported_memory_count));
+ let skip_local_memory_allocation =
+ !self.memory_types.is_empty() && !uses_local_memory && !exports_local_memory && !initializes_local_memory;
+
let funcs = self
.code
.into_iter()
@@ -567,6 +588,7 @@ impl<'a> ModuleReader<'a> {
exports: self.exports,
elements: self.elements,
memory_types: self.memory_types,
+ skip_local_memory_allocation,
tags: self.tags,
}
.into())
diff --git a/crates/parser/src/optimize/rewrite.rs b/crates/parser/src/optimize/rewrite.rs
index 1146da7..d0dfb66 100644
--- a/crates/parser/src/optimize/rewrite.rs
+++ b/crates/parser/src/optimize/rewrite.rs
@@ -5,11 +5,9 @@ use crate::{ParserOptions, Result};
use alloc::vec::Vec;
use core::ops::{Deref, DerefMut};
use tinywasm_types::{
- BinOp, BinOp128, CmpOp, CompactMemoryArg, GlobalConst32, GlobalConst64, GlobalUpdate, GlobalV128, I32LocalArg,
- I64Operand, Instruction, LocalConst64, LocalConstCmp, LocalConstSet32, LocalConstSet64, LocalConstSetV128,
- LocalLocalCmp, LocalTripleArg, LocalU32, LocalUpdate, LocalUpdateCmp, LocalV128, MemoryArg, MemoryFillConstOp,
- MemoryLocalArg, OperandIdx, PackedOp, StackConst32, StackConst64, TargetLocal, TargetLocalArg, V128Operand,
- ValueCounts,
+ BinOp, BinOp128, CmpOp, CompactMemoryArg, CompactMemoryOperand, GlobalUpdateOperand, I32LocalArg, Instruction,
+ LocalTripleArg, LocalUpdateCmpOperand, LocalUpdateOperand, MemoryFillOperand, MemoryLocalArg, MemoryOperand,
+ Operand64, Operand64Idx, Operand128, Operand128Idx, PackedOp, TargetLocalArg, ValueCounts,
};
pub(crate) struct OptimizeResult {
@@ -21,18 +19,6 @@ struct CompactOutput {
block_start: usize,
}
-macro_rules! operand {
- ($data:expr, $value:expr) => {
- $data.push_operand($value)
- };
-}
-
-macro_rules! target_operand {
- ($data:expr, $value:expr) => {
- $data.push_target_operand($value)
- };
-}
-
impl Deref for CompactOutput {
type Target = Vec<Instruction>;
@@ -229,7 +215,7 @@ fn rewrite(
}
}
MemoryFill(memory) => rewrite!(output, read, [Const32(value), Const32(size)] => {
- let index = operand!(data, MemoryFillConstOp { memory, byte: value as u8, value: size })?;
+ let index = data.push_operand128(Operand128::<MemoryFillOperand>::new(memory, value as u8, size))?;
replace!(output, read, 2 => MemoryFillConst(index));
}),
GlobalGet32(dst) => rewrite!(output, read, [GlobalSet32(src)] if (src == dst) => GlobalTee32(src)),
@@ -290,14 +276,13 @@ fn rewrite(
for instruction in &mut output.instructions {
match *instruction {
Instruction::Const64(index) => {
- let value = data.operand(index).value;
+ let value = data.operand64(index).value();
if value == i64::from(value as i32) {
*instruction = Instruction::Const64Imm(value as i32);
}
}
Instruction::Const128(index) => {
- let value = u128::from_le_bytes(data.operand(index).value);
- if let Ok(value) = u32::try_from(value) {
+ if let Ok(value) = u32::try_from(u128::from_le_bytes(data.operand128(index).value())) {
*instruction = Instruction::Const128Imm(value);
}
}
@@ -315,8 +300,8 @@ fn local_const32(data: &WasmFunctionData, instruction: Instruction) -> Option<(B
Instruction::SubLocalConst32(arg) => Some((BinOp::ISub, arg.local, arg.value)),
Instruction::MulLocalConst32(arg) => Some((BinOp::IMul, arg.local, arg.value)),
Instruction::BinOpLocalConst32(packed) => {
- let value = data.operand(packed.index);
- Some((packed.op, value.local, value.value as i32))
+ let value = data.operand64(packed.index);
+ Some((packed.op, value.a(), value.b() as i32))
}
_ => None,
}
@@ -324,25 +309,25 @@ fn local_const32(data: &WasmFunctionData, instruction: Instruction) -> Option<(B
fn local_const64(data: &WasmFunctionData, instruction: Instruction) -> Option<(BinOp, u16, i64)> {
let Instruction::BinOpLocalConst64(packed) = instruction else { return None };
- let value = data.operand(packed.index);
- Some((packed.op, value.local, value.value as i64))
+ let value = data.operand128(packed.index);
+ Some((packed.op, value.a(), value.b() as i64))
}
fn local_const128(
data: &WasmFunctionData,
instruction: Instruction,
-) -> Option<(BinOp128, u16, OperandIdx<V128Operand>)> {
+) -> Option<(BinOp128, u16, Operand128Idx<[u8; 16]>)> {
let Instruction::BinOpLocalConst128(packed) = instruction else { return None };
- let value = data.operand(packed.index);
- Some((packed.op, value.local, value.value))
+ let value = data.operand64(packed.index);
+ Some((packed.op, value.a(), value.b()))
}
fn compact_memory_arg(
data: &mut WasmFunctionData,
- index: OperandIdx<MemoryArg>,
-) -> Result<Option<OperandIdx<CompactMemoryArg>>> {
- let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) else { return Ok(None) };
- Ok(Some(operand!(data, arg)?))
+ index: Operand128Idx<MemoryOperand>,
+) -> Result<Option<Operand64Idx<CompactMemoryOperand>>> {
+ let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) else { return Ok(None) };
+ Ok(Some(data.push_operand64(Operand64::from(arg))?))
}
fn rewrite_scalar_const32(
@@ -365,12 +350,12 @@ fn rewrite_scalar_const32(
BinOp::IMul => Instruction::MulLocalConst32(arg),
_ => Instruction::BinOpLocalConst32(PackedOp::new(
op,
- operand!(data, LocalU32 { local: *local, value: *value as u32 })?,
+ data.push_operand64(Operand64::<(u16, u32)>::new(*local, *value as u32))?,
)),
}
}
[Instruction::GlobalGet32(global), Instruction::Const32(value)] => Instruction::BinOpGlobalConst32(
- PackedOp::new(op, operand!(data, GlobalConst32 { global: *global, value: *value as u32 })?),
+ PackedOp::new(op, data.push_operand64(Operand64::<(u32, u32)>::new(*global, *value as u32))?),
),
[Instruction::Const32(value), Instruction::LocalGet32(local)] if commutative => {
let arg = I32LocalArg { value: *value, local: *local };
@@ -379,14 +364,14 @@ fn rewrite_scalar_const32(
BinOp::IMul => Instruction::MulLocalConst32(arg),
_ => Instruction::BinOpLocalConst32(PackedOp::new(
op,
- operand!(data, LocalU32 { local: *local, value: *value as u32 })?,
+ data.push_operand64(Operand64::<(u16, u32)>::new(*local, *value as u32))?,
)),
}
}
[Instruction::Const32(value), Instruction::GlobalGet32(global)] if commutative => {
Instruction::BinOpGlobalConst32(PackedOp::new(
op,
- operand!(data, GlobalConst32 { global: *global, value: *value as u32 })?,
+ data.push_operand64(Operand64::<(u32, u32)>::new(*global, *value as u32))?,
))
}
_ => return Ok(false),
@@ -409,18 +394,24 @@ fn rewrite_scalar_const64(
let replacement = match previous {
[Instruction::LocalGet64(local), Instruction::Const64(index)] => Instruction::BinOpLocalConst64(PackedOp::new(
op,
- operand!(data, LocalConst64 { local, value: data.operand(index).value as u64 })?,
+ data.push_operand128(Operand128::<(u16, u64)>::new(local, data.operand64(index).value() as u64))?,
)),
- [Instruction::GlobalGet64(global), Instruction::Const64(index)] => Instruction::BinOpGlobalConst64(
- PackedOp::new(op, operand!(data, GlobalConst64 { global, value: data.operand(index).value as u64 })?),
- ),
- [Instruction::Const64(index), Instruction::LocalGet64(local)] if commutative => Instruction::BinOpLocalConst64(
- PackedOp::new(op, operand!(data, LocalConst64 { local, value: data.operand(index).value as u64 })?),
- ),
+ [Instruction::GlobalGet64(global), Instruction::Const64(index)] => {
+ Instruction::BinOpGlobalConst64(PackedOp::new(
+ op,
+ data.push_operand128(Operand128::<(u32, u64)>::new(global, data.operand64(index).value() as u64))?,
+ ))
+ }
+ [Instruction::Const64(index), Instruction::LocalGet64(local)] if commutative => {
+ Instruction::BinOpLocalConst64(PackedOp::new(
+ op,
+ data.push_operand128(Operand128::<(u16, u64)>::new(local, data.operand64(index).value() as u64))?,
+ ))
+ }
[Instruction::Const64(index), Instruction::GlobalGet64(global)] if commutative => {
Instruction::BinOpGlobalConst64(PackedOp::new(
op,
- operand!(data, GlobalConst64 { global, value: data.operand(index).value as u64 })?,
+ data.push_operand128(Operand128::<(u32, u64)>::new(global, data.operand64(index).value() as u64))?,
))
}
_ => return Ok(false),
@@ -455,7 +446,7 @@ fn rewrite_sign_extend64(output: &mut CompactOutput, read: &mut usize, data: &Wa
}
if let Some((BinOp::IShl, local, shift)) = local_const64(data, output[*read - 2])
&& let Instruction::Const64(index) = output[*read - 1]
- && shift == data.operand(index).value
+ && shift == data.operand64(index).value()
{
let instruction = match shift {
56 => Instruction::I64Extend8S,
@@ -482,17 +473,26 @@ fn rewrite_vector_binop(
let previous = [output[*read - 2], output[*read - 1]];
let replacement = match previous {
[Instruction::LocalGet128(a), Instruction::LocalGet128(b)] => Instruction::BinOpLocalLocal128(op, a, b),
- [Instruction::LocalGet128(local), Instruction::Const128(value)] => {
- Instruction::BinOpLocalConst128(PackedOp::new(op, operand!(data, LocalV128 { local, value })?))
- }
+ [Instruction::LocalGet128(local), Instruction::Const128(value)] => Instruction::BinOpLocalConst128(
+ PackedOp::new(op, data.push_operand64(Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(local, value))?),
+ ),
[Instruction::GlobalGet128(global), Instruction::Const128(value)] => {
- Instruction::BinOpGlobalConst128(PackedOp::new(op, operand!(data, GlobalV128 { global, value })?))
+ Instruction::BinOpGlobalConst128(PackedOp::new(
+ op,
+ data.push_operand64(Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(global, value))?,
+ ))
}
[Instruction::Const128(value), Instruction::LocalGet128(local)] if commutative => {
- Instruction::BinOpLocalConst128(PackedOp::new(op, operand!(data, LocalV128 { local, value })?))
+ Instruction::BinOpLocalConst128(PackedOp::new(
+ op,
+ data.push_operand64(Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(local, value))?,
+ ))
}
[Instruction::Const128(value), Instruction::GlobalGet128(global)] if commutative => {
- Instruction::BinOpGlobalConst128(PackedOp::new(op, operand!(data, GlobalV128 { global, value })?))
+ Instruction::BinOpGlobalConst128(PackedOp::new(
+ op,
+ data.push_operand64(Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(global, value))?,
+ ))
}
_ => return Ok(()),
};
@@ -505,9 +505,13 @@ fn rewrite_store32(
output: &mut CompactOutput,
read: &mut usize,
data: &mut WasmFunctionData,
- index: OperandIdx<MemoryArg>,
+ index: Operand128Idx<MemoryOperand>,
) -> Result<()> {
- let compact_arg = CompactMemoryArg::try_from(data.operand(index)).ok();
+ let compact_arg = CompactMemoryArg::try_from(data.operand128(index)).ok();
+ if *read > output.block_start && output[*read - 1] == Instruction::Select32 {
+ replace!(output, *read, 1 => Instruction::SelectStore32(index));
+ return Ok(());
+ }
if *read >= output.block_start + 3 {
let previous = [output[*read - 3], output[*read - 2], output[*read - 1]];
if let [
@@ -515,7 +519,7 @@ fn rewrite_store32(
Instruction::LoadLocal32(arg),
Instruction::AddConst32(1),
] = previous
- && { compact_arg == Some(data.operand(arg.memory_arg_idx)) }
+ && { compact_arg.map(Operand64::from) == Some(data.operand64(arg.memory_arg_idx)) }
&& addr == u16::from(arg.local1)
{
replace!(output, *read, 3 => Instruction::IncMemoryLocal32(arg));
@@ -526,12 +530,12 @@ fn rewrite_store32(
let previous = [output[*read - 2], output[*read - 1]];
match previous {
[Instruction::F32Mul, Instruction::F32Add]
- if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) =>
+ if let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) =>
{
replace!(output, *read, 2 => Instruction::FMaStoreF32(arg));
}
[Instruction::BinOpStackLocal32(BinOp::FMul, local), Instruction::F32Add]
- if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) =>
+ if let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) =>
{
replace!(output, *read, 2 => [Instruction::LocalGet32(local), Instruction::FMaStoreF32(arg)]);
}
@@ -539,7 +543,7 @@ fn rewrite_store32(
if let (Ok(addr), Ok(value), Some(memory_arg)) =
(u8::try_from(addr), u8::try_from(value), compact_arg) =>
{
- let memory_arg_idx = operand!(data, memory_arg)?;
+ let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?;
replace!(output, *read, 2 => Instruction::StoreLocalLocal32(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value }));
}
_ => {}
@@ -552,9 +556,13 @@ fn rewrite_store64(
output: &mut CompactOutput,
read: &mut usize,
data: &mut WasmFunctionData,
- index: OperandIdx<MemoryArg>,
+ index: Operand128Idx<MemoryOperand>,
) -> Result<()> {
- let compact_arg = CompactMemoryArg::try_from(data.operand(index)).ok();
+ let compact_arg = CompactMemoryArg::try_from(data.operand128(index)).ok();
+ if *read > output.block_start && output[*read - 1] == Instruction::Select64 {
+ replace!(output, *read, 1 => Instruction::SelectStore64(index));
+ return Ok(());
+ }
if *read >= output.block_start + 3 {
let previous = [output[*read - 3], output[*read - 2], output[*read - 1]];
if let [
@@ -562,9 +570,9 @@ fn rewrite_store64(
Instruction::LoadLocal64(arg),
Instruction::Const64(one),
] = previous
- && { compact_arg == Some(data.operand(arg.memory_arg_idx)) }
+ && { compact_arg.map(Operand64::from) == Some(data.operand64(arg.memory_arg_idx)) }
&& addr == u16::from(arg.local1)
- && data.operand(one).value == 1
+ && data.operand64(one).value() == 1
{
replace!(output, *read, 3 => Instruction::IncMemoryLocal64(arg));
return Ok(());
@@ -573,7 +581,7 @@ fn rewrite_store64(
if *read >= output.block_start + 2 {
match [output[*read - 2], output[*read - 1]] {
[Instruction::F64Mul, Instruction::F64Add]
- if let Ok(arg) = CompactMemoryArg::try_from(data.operand(index)) =>
+ if let Ok(arg) = CompactMemoryArg::try_from(data.operand128(index)) =>
{
replace!(output, *read, 2 => Instruction::FMaStoreF64(arg));
}
@@ -581,7 +589,7 @@ fn rewrite_store64(
if let (Ok(addr), Ok(value), Some(memory_arg)) =
(u8::try_from(addr), u8::try_from(value), compact_arg) =>
{
- let memory_arg_idx = operand!(data, memory_arg)?;
+ let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?;
replace!(output, *read, 2 => Instruction::StoreLocalLocal64(MemoryLocalArg { memory_arg_idx, local1: addr, local2: value }));
}
_ => {}
@@ -592,7 +600,7 @@ fn rewrite_store64(
macro_rules! local_const_set {
($data:expr, 32, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{
- let index = operand!($data, LocalConstSet32 { local: $src, dst: $dst, value: $value as u32 })?;
+ let index = $data.push_operand64(Operand64::<(u16, u16, u32)>::new($src, $dst, $value as u32))?;
if $tee {
Instruction::BinOpLocalConstTee32(PackedOp::new($op, index))
} else {
@@ -600,7 +608,7 @@ macro_rules! local_const_set {
}
}};
($data:expr, 64, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{
- let index = operand!($data, LocalConstSet64 { local: $src, dst: $dst, value: $value as u64 })?;
+ let index = $data.push_operand128(Operand128::<(u16, u16, u64)>::new($src, $dst, $value as u64))?;
if $tee {
Instruction::BinOpLocalConstTee64(PackedOp::new($op, index))
} else {
@@ -608,7 +616,7 @@ macro_rules! local_const_set {
}
}};
($data:expr, 128, $op:expr, $src:expr, $dst:expr, $value:expr, $tee:expr) => {{
- let index = operand!($data, LocalConstSetV128 { local: $src, dst: $dst, value: $value })?;
+ let index = $data.push_operand64(Operand64::<(u16, u16, Operand128Idx<[u8; 16]>)>::new($src, $dst, $value))?;
if $tee {
Instruction::BinOpLocalConstTee128(PackedOp::new($op, index))
} else {
@@ -653,7 +661,7 @@ fn rewrite_local_set32(
} else {
Instruction::BinOpLocalLocalSet32(PackedOp::new(
op,
- operand!(data, LocalTripleArg { left, right, dst })?,
+ data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?,
))
};
replace!(output, *read, 1 => replacement);
@@ -728,13 +736,13 @@ fn rewrite_local_set64(
replace!(output, *read, 1 => Instruction::SetLocalConst64(PackedOp::new(dst, index)));
}
Instruction::BinOpLocalLocal64(op, left, right) => {
- let index = operand!(data, LocalTripleArg { left, right, dst })?;
+ let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?;
replace!(output, *read, 1 => Instruction::BinOpLocalLocalSet64(PackedOp::new(op, index)));
}
instruction if let Some((op, src, value)) = local_const64(data, instruction) => {
if src == dst && matches!(op, BinOp::IAdd | BinOp::ISub) {
let delta = if op == BinOp::IAdd { value } else { value.wrapping_neg() };
- let index = operand!(data, I64Operand { value: delta })?;
+ let index = data.push_operand64(Operand64::<i64>::new(delta))?;
replace!(output, *read, 1 => Instruction::IncLocal64(PackedOp::new(dst, index)));
} else {
let replacement = local_const_set!(data, 64, op, src, dst, value, false);
@@ -756,9 +764,9 @@ fn rewrite_local_set128(
if *read >= output.block_start + 2
&& let [Instruction::LocalGet32(local), Instruction::V128Load(index)] = [output[*read - 2], output[*read - 1]]
&& let (Ok(local), Ok(dst), Ok(memory_arg)) =
- (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand(index)))
+ (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand128(index)))
{
- let memory_arg_idx = operand!(data, memory_arg)?;
+ let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?;
replace!(output, *read, 2 => Instruction::LoadLocalSet128(MemoryLocalArg {
memory_arg_idx,
local1: local,
@@ -778,7 +786,7 @@ fn rewrite_local_set128(
replace!(output, *read, 1 => Instruction::SetLocalConst128(PackedOp::new(dst, value)))
}
Instruction::BinOpLocalLocal128(op, left, right) => {
- let index = operand!(data, LocalTripleArg { left, right, dst })?;
+ let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?;
replace!(output, *read, 1 => Instruction::BinOpLocalLocalSet128(PackedOp::new(op, index)));
}
instruction if let Some((op, src, value)) = local_const128(data, instruction) => {
@@ -819,7 +827,7 @@ fn rewrite_local_tee32(
} else {
Instruction::BinOpLocalLocalTee32(PackedOp::new(
op,
- operand!(data, LocalTripleArg { left, right, dst })?,
+ data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?,
))
};
replace!(output, *read, 1 => replacement);
@@ -880,7 +888,7 @@ fn rewrite_local_tee64(
match output[*read - 1] {
Instruction::LocalGet64(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet64(src)),
Instruction::BinOpLocalLocal64(op, left, right) => {
- let index = operand!(data, LocalTripleArg { left, right, dst })?;
+ let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?;
replace!(output, *read, 1 => Instruction::BinOpLocalLocalTee64(PackedOp::new(op, index)));
}
instruction if let Some((op, src, value)) = local_const64(data, instruction) => {
@@ -902,9 +910,9 @@ fn rewrite_local_tee128(
if *read >= output.block_start + 2
&& let [Instruction::LocalGet32(local), Instruction::V128Load(index)] = [output[*read - 2], output[*read - 1]]
&& let (Ok(local), Ok(dst), Ok(memory_arg)) =
- (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand(index)))
+ (u8::try_from(local), u8::try_from(dst), CompactMemoryArg::try_from(data.operand128(index)))
{
- let memory_arg_idx = operand!(data, memory_arg)?;
+ let memory_arg_idx = data.push_operand64(Operand64::from(memory_arg))?;
replace!(output, *read, 2 => Instruction::LoadLocalTee128(MemoryLocalArg {
memory_arg_idx,
local1: local,
@@ -916,7 +924,7 @@ fn rewrite_local_tee128(
match output[*read - 1] {
Instruction::LocalGet128(src) if src == dst => replace!(output, *read, 1 => Instruction::LocalGet128(src)),
Instruction::BinOpLocalLocal128(op, left, right) => {
- let index = operand!(data, LocalTripleArg { left, right, dst })?;
+ let index = data.push_operand64(Operand64::<(u16, u16, u16)>::new(left, right, dst))?;
replace!(output, *read, 1 => Instruction::BinOpLocalLocalTee128(PackedOp::new(op, index)));
}
instruction if let Some((op, src, value)) = local_const128(data, instruction) => {
@@ -995,7 +1003,7 @@ fn jump_cmp_local_local(
op: CmpOp,
width64: bool,
) -> Result<Instruction> {
- let index = target_operand!(data, LocalLocalCmp { target, left, right })?;
+ let index = data.push_target_operand64(Operand64::<(u32, u16, u16)>::new(target, left, right))?;
Ok(if width64 {
Instruction::JumpCmpLocalLocal64(PackedOp::new(op, index))
} else {
@@ -1017,17 +1025,17 @@ fn rewrite_jump(
if let Some(instruction) = source.get(target as usize).copied() {
match instruction {
Instruction::JumpCmpLocalLocal32(side)
- if resolve_jump_target(source, data, data.operand(side.index).target) == exit && body > target =>
+ if resolve_jump_target(source, data, data.operand64(side.index).a()) == exit && body > target =>
{
- let value = data.operand(side.index);
- output[index] = jump_cmp_local_local(data, body, value.left, value.right, side.op.inverse(), false)?;
+ let value = data.operand64(side.index);
+ output[index] = jump_cmp_local_local(data, body, value.b(), value.c(), side.op.inverse(), false)?;
return Ok(());
}
Instruction::JumpCmpLocalLocal64(side)
- if resolve_jump_target(source, data, data.operand(side.index).target) == exit && body > target =>
+ if resolve_jump_target(source, data, data.operand64(side.index).a()) == exit && body > target =>
{
- let value = data.operand(side.index);
- output[index] = jump_cmp_local_local(data, body, value.left, value.right, side.op.inverse(), true)?;
+ let value = data.operand64(side.index);
+ output[index] = jump_cmp_local_local(data, body, value.b(), value.c(), side.op.inverse(), true)?;
return Ok(());
}
_ => {}
@@ -1048,7 +1056,7 @@ fn jump_cmp_stack_local(
op: CmpOp,
width64: bool,
) -> Result<Instruction> {
- let index = target_operand!(data, TargetLocal { target, local })?;
+ let index = data.push_target_operand64(Operand64::<(u32, u16)>::new(target, local))?;
Ok(if width64 {
Instruction::JumpCmpStackLocal64(PackedOp::new(op, index))
} else {
@@ -1069,13 +1077,13 @@ fn jump_cmp_local_const32(
CmpOp::Ne => Instruction::JumpIfLocalNonZero32(TargetLocalArg { target_ip: target, local }),
_ => Instruction::JumpCmpLocalConst32(PackedOp::new(
op,
- target_operand!(data, LocalConstCmp { target, value, local })?,
+ data.push_target_operand128(Operand128::<(u32, i32, u16)>::new(target, value, local))?,
)),
});
}
Ok(Instruction::JumpCmpLocalConst32(PackedOp::new(
op,
- target_operand!(data, LocalConstCmp { target, value, local })?,
+ data.push_target_operand128(Operand128::<(u32, i32, u16)>::new(target, value, local))?,
)))
}
@@ -1095,7 +1103,7 @@ fn jump_cmp_local_const64(
}
Ok(Instruction::JumpCmpLocalConst64(PackedOp::new(
op,
- target_operand!(data, LocalConstCmp { target, value, local })?,
+ data.push_target_operand128(Operand128::<(u32, i32, u16)>::new(target, value, local))?,
)))
}
@@ -1107,7 +1115,10 @@ fn jump_cmp_stack_const32(data: &mut WasmFunctionData, target: u32, value: i32,
_ => {}
}
}
- Ok(Instruction::JumpCmpStackConst32(PackedOp::new(op, target_operand!(data, StackConst32 { target, value })?)))
+ Ok(Instruction::JumpCmpStackConst32(PackedOp::new(
+ op,
+ data.push_target_operand64(Operand64::<(u32, i32)>::new(target, value))?,
+ )))
}
fn jump_cmp_stack_const64(data: &mut WasmFunctionData, target: u32, value: i64, op: CmpOp) -> Result<Instruction> {
@@ -1118,7 +1129,10 @@ fn jump_cmp_stack_const64(data: &mut WasmFunctionData, target: u32, value: i64,
_ => {}
}
}
- Ok(Instruction::JumpCmpStackConst64(PackedOp::new(op, target_operand!(data, StackConst64 { target, value })?)))
+ Ok(Instruction::JumpCmpStackConst64(PackedOp::new(
+ op,
+ data.push_target_operand128(Operand128::<(u32, i64)>::new(target, value))?,
+ )))
}
fn update_jump(
@@ -1132,32 +1146,34 @@ fn update_jump(
) -> Result<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) }
- )?)
+ Instruction::IncGlobalJump32(
+ data.push_target_operand128(Operand128::<GlobalUpdateOperand>::new(target, delta, address, on_zero))?,
+ )
} else {
- Instruction::IncLocalJump32(target_operand!(
- data,
- LocalUpdate { target, value: delta, local: address as u16, on_zero: u8::from(on_zero) }
- )?)
+ Instruction::IncLocalJump32(data.push_target_operand128(Operand128::<LocalUpdateOperand>::new(
+ target,
+ delta,
+ address as u16,
+ on_zero,
+ ))?)
})
} else {
Ok(if global {
Instruction::BinOpGlobalConstJump32(PackedOp::new(
op,
- target_operand!(
- data,
- GlobalUpdate { target, value: immediate, global: address, on_zero: u8::from(on_zero) }
- )?,
+ data.push_target_operand128(Operand128::<GlobalUpdateOperand>::new(
+ target, immediate, address, on_zero,
+ ))?,
))
} else {
Instruction::BinOpLocalConstJump32(PackedOp::new(
op,
- target_operand!(
- data,
- LocalUpdate { target, value: immediate, local: address as u16, on_zero: u8::from(on_zero) }
- )?,
+ data.push_target_operand128(Operand128::<LocalUpdateOperand>::new(
+ target,
+ immediate,
+ address as u16,
+ on_zero,
+ ))?,
))
})
}
@@ -1175,10 +1191,10 @@ fn rewrite_conditional(
if *read > output.block_start
&& let Instruction::BinOpLocalConstTee32(packed) = output[*read - 1]
{
- let value = data.operand(packed.index);
- if value.local == value.dst {
+ let value = data.operand64(packed.index);
+ if value.a() == value.b() {
let replacement =
- update_jump(data, target, value.value as i32, u32::from(value.local), packed.op, on_zero, false)?;
+ update_jump(data, target, value.c() as i32, u32::from(value.a()), packed.op, on_zero, false)?;
replace!(output, *read, 1 => replacement);
return Ok(());
}
@@ -1187,9 +1203,9 @@ fn rewrite_conditional(
&& let [Instruction::BinOpGlobalConst32(packed), Instruction::GlobalTee32(dst)] =
[output[*read - 2], output[*read - 1]]
{
- let value = data.operand(packed.index);
- if value.global == dst {
- let replacement = update_jump(data, target, value.value as i32, dst, packed.op, on_zero, true)?;
+ let value = data.operand64(packed.index);
+ if value.a() == dst {
+ let replacement = update_jump(data, target, value.b() as i32, dst, packed.op, on_zero, true)?;
replace!(output, *read, 2 => replacement);
return Ok(());
}
@@ -1199,10 +1215,10 @@ fn rewrite_conditional(
[output[*read - 3], output[*read - 2], output[*read - 1]]
&& local == cond
{
- let replacement = Instruction::IncStackTeeLocalJump32(target_operand!(
- data,
- LocalUpdate { target, value, local, on_zero: u8::from(on_zero) }
- )?);
+ let replacement =
+ Instruction::IncStackTeeLocalJump32(
+ data.push_target_operand128(Operand128::<LocalUpdateOperand>::new(target, value, local, on_zero))?,
+ );
replace!(output, *read, 3 => replacement);
return Ok(());
}
@@ -1220,13 +1236,12 @@ fn rewrite_conditional(
let replacement = if let Some(op) = op {
Instruction::BinOpStackConstTeeLocalJump32(PackedOp::new(
op,
- target_operand!(data, LocalUpdate { target, value, local, on_zero: u8::from(on_zero) })?,
+ data.push_target_operand128(Operand128::<LocalUpdateOperand>::new(target, value, local, on_zero))?,
))
} else {
- Instruction::IncStackTeeLocalJump32(target_operand!(
- data,
- LocalUpdate { target, value, local, on_zero: u8::from(on_zero) }
- )?)
+ Instruction::IncStackTeeLocalJump32(
+ data.push_target_operand128(Operand128::<LocalUpdateOperand>::new(target, value, local, on_zero))?,
+ )
};
replace!(output, *read, 2 => replacement);
return Ok(());
@@ -1237,23 +1252,30 @@ fn rewrite_conditional(
[output[*read - 3], output[*read - 2], output[*read - 1]]
&& let Some(mut cmp) = cmp_op(raw_cmp)
{
- let value = data.operand(packed.index);
- if value.local == value.dst {
+ let value = data.operand64(packed.index);
+ if value.a() == value.b() {
if on_zero {
cmp = cmp.inverse();
}
- let replacement = if let Some(delta) = packed.op.inc_delta(value.value as i32) {
+ let replacement = if let Some(delta) = packed.op.inc_delta(value.c() as i32) {
Instruction::IncLocalJumpCmpLocal32(PackedOp::new(
cmp,
- target_operand!(data, LocalUpdateCmp { target, value: delta, local: value.local, right })?,
+ data.push_target_operand128(Operand128::<LocalUpdateCmpOperand>::new(
+ target,
+ delta,
+ value.a(),
+ right,
+ ))?,
))
} else {
Instruction::BinOpLocalConstJumpCmpLocal32(PackedOp::new(
(packed.op, cmp),
- target_operand!(
- data,
- LocalUpdateCmp { target, value: value.value as i32, local: value.local, right }
- )?,
+ data.push_target_operand128(Operand128::<LocalUpdateCmpOperand>::new(
+ target,
+ value.c() as i32,
+ value.a(),
+ right,
+ ))?,
))
};
replace!(output, *read, 3 => replacement);
@@ -1334,7 +1356,7 @@ fn rewrite_conditional(
Some(jump_cmp_local_const32(data, target, local, value, op)?)
}
[Instruction::LocalGet64(local), Instruction::Const64(index)]
- if let Ok(value) = i32::try_from(data.operand(index).value) =>
+ if let Ok(value) = i32::try_from(data.operand64(index).value()) =>
{
Some(jump_cmp_local_const64(data, target, local, value, op)?)
}
@@ -1363,7 +1385,7 @@ fn rewrite_conditional(
Instruction::LocalGet64(local) => Some(jump_cmp_stack_local(data, target, local, op, true)?),
Instruction::Const32(value) => Some(jump_cmp_stack_const32(data, target, value, op)?),
Instruction::Const64(index) => {
- Some(jump_cmp_stack_const64(data, target, data.operand(index).value, op)?)
+ Some(jump_cmp_stack_const64(data, target, data.operand64(index).value(), op)?)
}
_ => None,
};
diff --git a/crates/parser/src/optimize/targets.rs b/crates/parser/src/optimize/targets.rs
index 36bdf2f..c6b2252 100644
--- a/crates/parser/src/optimize/targets.rs
+++ b/crates/parser/src/optimize/targets.rs
@@ -1,35 +1,7 @@
-use crate::visit::{BuilderRawOperand, FunctionDataBuilder};
+use crate::visit::FunctionDataBuilder;
use crate::{ParseError, Result};
use alloc::vec::Vec;
-use tinywasm_types::{
- BranchTableArg, CastBranch, GlobalUpdate, Instruction, LocalConstCmp, LocalLocalCmp, LocalUpdate, LocalUpdateCmp,
- OperandIdx, OperandType, PackedOp, StackConst32, StackConst64, TargetLocal,
-};
-
-pub(super) trait TargetOperand: OperandType {
- fn set_target(&mut self, target: u32);
-}
-
-macro_rules! target_operands {
- ($($name:ty),+ $(,)?) => {$(
- impl TargetOperand for $name {
- fn set_target(&mut self, target: u32) { self.target = target; }
- }
- )+};
-}
-
-target_operands!(
- TargetLocal,
- CastBranch,
- StackConst32,
- StackConst64,
- LocalUpdate,
- GlobalUpdate,
- LocalUpdateCmp,
- LocalConstCmp,
- LocalLocalCmp,
- BranchTableArg,
-);
+use tinywasm_types::{Instruction, PackedOp};
pub(super) fn resolve_jump_target(instructions: &[Instruction], data: &FunctionDataBuilder, target: u32) -> u32 {
let mut index = target as usize;
@@ -50,58 +22,37 @@ pub(super) fn set_rewrite_target(
data: &mut FunctionDataBuilder,
target: u32,
) -> Result<()> {
+ macro_rules! rewrite_target {
+ ($slot:ident, operand64) => {{ data.push_target_operand64(data.operand64(*$slot).with_target(target))? }};
+ ($slot:ident, operand128) => {{ data.push_target_operand128(data.operand128(*$slot).with_target(target))? }};
+ ($slot:ident, packed64) => {{ PackedOp::new($slot.op, data.push_target_operand64(data.operand64($slot.index).with_target(target))?) }};
+ ($slot:ident, packed128) => {{ PackedOp::new($slot.op, data.push_target_operand128(data.operand128($slot.index).with_target(target))?) }};
+ }
+
use Instruction::*;
match instruction {
- JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => {
- *packed = push_packed_target_copy(data, *packed, target)?
- }
- BrOnCast(index) | BrOnCastFail(index) => *index = push_target_copy(data, *index, target)?,
- JumpCmpStackConst32(packed) => *packed = push_packed_target_copy(data, *packed, target)?,
- JumpCmpStackConst64(packed) => *packed = push_packed_target_copy(data, *packed, target)?,
- BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => {
- *packed = push_packed_target_copy(data, *packed, target)?
- }
- BinOpLocalConstJumpCmpLocal32(packed) => *packed = push_packed_target_copy(data, *packed, target)?,
- BinOpGlobalConstJump32(packed) => *packed = push_packed_target_copy(data, *packed, target)?,
- IncLocalJump32(index) | IncStackTeeLocalJump32(index) => *index = push_target_copy(data, *index, target)?,
- IncGlobalJump32(index) => *index = push_target_copy(data, *index, target)?,
- IncLocalJumpCmpLocal32(packed) => *packed = push_packed_target_copy(data, *packed, target)?,
- JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => {
- *packed = push_packed_target_copy(data, *packed, target)?
- }
- JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => {
- *packed = push_packed_target_copy(data, *packed, target)?
- }
- BranchTable(index) => *index = push_target_copy(data, *index, target)?,
+ JumpCmpStackLocal32(packed) => *packed = rewrite_target!(packed, packed64),
+ JumpCmpStackLocal64(packed) => *packed = rewrite_target!(packed, packed64),
+ BrOnCast(index) | BrOnCastFail(index) => *index = rewrite_target!(index, operand64),
+ JumpCmpStackConst32(packed) => *packed = rewrite_target!(packed, packed64),
+ JumpCmpStackConst64(packed) => *packed = rewrite_target!(packed, packed128),
+ BinOpStackConstTeeLocalJump32(packed) => *packed = rewrite_target!(packed, packed128),
+ BinOpLocalConstJump32(packed) => *packed = rewrite_target!(packed, packed128),
+ BinOpLocalConstJumpCmpLocal32(packed) => *packed = rewrite_target!(packed, packed128),
+ BinOpGlobalConstJump32(packed) => *packed = rewrite_target!(packed, packed128),
+ IncLocalJump32(index) => *index = rewrite_target!(index, operand128),
+ IncStackTeeLocalJump32(index) => *index = rewrite_target!(index, operand128),
+ IncGlobalJump32(index) => *index = rewrite_target!(index, operand128),
+ IncLocalJumpCmpLocal32(packed) => *packed = rewrite_target!(packed, packed128),
+ JumpCmpLocalConst32(packed) => *packed = rewrite_target!(packed, packed128),
+ JumpCmpLocalConst64(packed) => *packed = rewrite_target!(packed, packed128),
+ JumpCmpLocalLocal32(packed) => *packed = rewrite_target!(packed, packed64),
+ JumpCmpLocalLocal64(packed) => *packed = rewrite_target!(packed, packed64),
+ BranchTable(index) => *index = rewrite_target!(index, operand128),
_ => set_target(instruction, data, target),
}
- Ok(())
-}
-fn push_target_copy<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)?))
+ Ok(())
}
fn instruction_target(data: &FunctionDataBuilder, instruction: Instruction) -> Option<u32> {
@@ -117,24 +68,31 @@ fn instruction_target(data: &FunctionDataBuilder, instruction: Instruction) -> O
JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => {
arg.target_ip
}
- JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => data.operand(packed.index).target,
- BrOnCast(index) | BrOnCastFail(index) => data.operand(index).target,
- JumpCmpStackConst32(packed) => data.operand(packed.index).target,
- JumpCmpStackConst64(packed) => data.operand(packed.index).target,
- BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => data.operand(packed.index).target,
- BinOpLocalConstJumpCmpLocal32(packed) => data.operand(packed.index).target,
- BinOpGlobalConstJump32(packed) => data.operand(packed.index).target,
- IncLocalJump32(index) | IncStackTeeLocalJump32(index) => data.operand(index).target,
- IncGlobalJump32(index) => data.operand(index).target,
- IncLocalJumpCmpLocal32(packed) => data.operand(packed.index).target,
- JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => data.operand(packed.index).target,
- JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => data.operand(packed.index).target,
- BranchTable(index) => data.operand(index).target,
+ JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => data.operand64(packed.index).target(),
+ BrOnCast(index) | BrOnCastFail(index) => data.operand64(index).target(),
+ JumpCmpStackConst32(packed) => data.operand64(packed.index).target(),
+ JumpCmpStackConst64(packed) => data.operand128(packed.index).target(),
+ BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => data.operand128(packed.index).target(),
+ BinOpLocalConstJumpCmpLocal32(packed) => data.operand128(packed.index).target(),
+ BinOpGlobalConstJump32(packed) => data.operand128(packed.index).target(),
+ IncLocalJump32(index) | IncStackTeeLocalJump32(index) => data.operand128(index).target(),
+ IncGlobalJump32(index) => data.operand128(index).target(),
+ IncLocalJumpCmpLocal32(packed) => data.operand128(packed.index).target(),
+ JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => data.operand128(packed.index).target(),
+ JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => data.operand64(packed.index).target(),
+ BranchTable(index) => data.operand128(index).target(),
_ => return None,
})
}
fn set_target(instruction: &mut Instruction, data: &mut FunctionDataBuilder, target: u32) {
+ macro_rules! set_target {
+ ($index:expr, operand64) => {{ data.set_operand64($index, data.operand64($index).with_target(target)) }};
+ ($index:expr, operand128) => {{ data.set_operand128($index, data.operand128($index).with_target(target)) }};
+ ($packed:expr, packed64) => {{ data.set_operand64($packed.index, data.operand64($packed.index).with_target(target)) }};
+ ($packed:expr, packed128) => {{ data.set_operand128($packed.index, data.operand128($packed.index).with_target(target)) }};
+ }
+
use Instruction::*;
match instruction {
Jump(value)
@@ -144,53 +102,32 @@ fn set_target(instruction: &mut Instruction, data: &mut FunctionDataBuilder, tar
| JumpIfNonZero64(value)
| JumpIfRefNull(value)
| JumpIfRefNonNull(value) => *value = target,
+
JumpIfLocalZero32(arg) | JumpIfLocalNonZero32(arg) | JumpIfLocalZero64(arg) | JumpIfLocalNonZero64(arg) => {
arg.target_ip = target
}
- JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => set_packed_operand_target(data, *packed, target),
- BrOnCast(index) | BrOnCastFail(index) => set_operand_target(data, *index, target),
- JumpCmpStackConst32(packed) => set_packed_operand_target(data, *packed, target),
- JumpCmpStackConst64(packed) => set_packed_operand_target(data, *packed, target),
- BinOpLocalConstJump32(packed) | BinOpStackConstTeeLocalJump32(packed) => {
- set_packed_operand_target(data, *packed, target)
- }
- BinOpLocalConstJumpCmpLocal32(packed) => set_packed_operand_target(data, *packed, target),
- BinOpGlobalConstJump32(packed) => set_packed_operand_target(data, *packed, target),
- IncLocalJump32(index) | IncStackTeeLocalJump32(index) => set_operand_target(data, *index, target),
- IncGlobalJump32(index) => set_operand_target(data, *index, target),
- IncLocalJumpCmpLocal32(packed) => set_packed_operand_target(data, *packed, target),
- JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => set_packed_operand_target(data, *packed, target),
- JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => set_packed_operand_target(data, *packed, target),
- BranchTable(index) => set_operand_target(data, *index, target),
+ JumpCmpStackLocal32(packed) | JumpCmpStackLocal64(packed) => set_target!(*packed, packed64),
+ BrOnCast(index) | BrOnCastFail(index) => set_target!(*index, operand64),
+ JumpCmpStackConst32(packed) => set_target!(*packed, packed64),
+ JumpCmpStackConst64(packed) => set_target!(*packed, packed128),
+ BinOpLocalConstJump32(packed) => set_target!(*packed, packed128),
+ BinOpStackConstTeeLocalJump32(packed) => set_target!(*packed, packed128),
+ BinOpLocalConstJumpCmpLocal32(packed) => set_target!(*packed, packed128),
+ BinOpGlobalConstJump32(packed) => set_target!(*packed, packed128),
+ IncLocalJump32(index) | IncStackTeeLocalJump32(index) => set_target!(*index, operand128),
+ IncGlobalJump32(index) => set_target!(*index, operand128),
+ IncLocalJumpCmpLocal32(packed) => set_target!(*packed, packed128),
+ JumpCmpLocalConst32(packed) | JumpCmpLocalConst64(packed) => set_target!(*packed, packed128),
+ JumpCmpLocalLocal32(packed) | JumpCmpLocalLocal64(packed) => set_target!(*packed, packed64),
+ BranchTable(index) => set_target!(*index, operand128),
_ => {}
}
}
-fn set_operand_target<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))
+ let operand = data.operand128(index);
+ Some((operand.start(), operand.size()))
}
pub(super) fn target_boundaries(instructions: &[Instruction], data: &FunctionDataBuilder) -> Result<Vec<bool>> {
diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs
index b65f77c..724c1bf 100644
--- a/crates/parser/src/visit.rs
+++ b/crates/parser/src/visit.rs
@@ -5,9 +5,9 @@ use crate::{
};
use alloc::{boxed::Box, collections::BTreeMap, string::ToString, vec::Vec};
use tinywasm_types::{
- BranchTableArg, CastBranch, ExceptionHandler, Global, I64Operand, Import, ImportKind, Instruction, MemoryArg,
- MemoryType, Operand64, Operand128, OperandIdx, OperandType, StorageType, TableDefinition, TagType, TwoU32,
- TypeSection, V128Operand, ValueCounts, ValueLane, WasmFunctionData,
+ BranchTableOperand, ExceptionHandler, Global, Import, ImportKind, Instruction, MemoryType, Operand64, Operand64Idx,
+ Operand128, Operand128Idx, StorageType, TableDefinition, TagType, TypeSection, ValueCounts, ValueLane,
+ WasmFunctionData,
};
use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator};
@@ -51,6 +51,7 @@ pub(crate) struct ModuleMetadata {
tables: Vec<ValueLane>,
tags: Vec<u32>,
aggregate_fields: Vec<AggregateFields>,
+ imported_memories: u32,
}
pub(crate) struct FunctionDataBuilder {
@@ -62,42 +63,6 @@ pub(crate) struct FunctionDataBuilder {
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 {
@@ -110,32 +75,56 @@ impl FunctionDataBuilder {
}
}
- 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_operand64<T>(&mut self, operand: Operand64<T>) -> Result<Operand64Idx<T>> {
+ let operand = operand.cast();
+ if let Some(index) = self.deduplicate64.as_ref().and_then(|map| map.get(&operand)) {
+ return Ok(Operand64Idx::new(*index));
+ }
+ let index = self.operands64.len() as u32;
+ self.operands64.push(operand);
+ if let Some(map) = &mut self.deduplicate64 {
+ map.insert(operand, index);
+ }
+ Ok(Operand64Idx::new(index))
+ }
+
+ pub(crate) fn push_operand128<T>(&mut self, operand: Operand128<T>) -> Result<Operand128Idx<T>> {
+ let operand = operand.cast();
+ if let Some(index) = self.deduplicate128.as_ref().and_then(|map| map.get(&operand)) {
+ return Ok(Operand128Idx::new(*index));
+ }
+ let index = self.operands128.len() as u32;
+ self.operands128.push(operand);
+ if let Some(map) = &mut self.deduplicate128 {
+ map.insert(operand, index);
+ }
+ Ok(Operand128Idx::new(index))
+ }
+
+ pub(crate) fn push_target_operand64<T>(&mut self, operand: Operand64<T>) -> Result<Operand64Idx<T>> {
+ self.operands64.push(operand.cast());
+ Ok(Operand64Idx::new(self.operands64.len() as u32 - 1))
}
- 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 push_target_operand128<T>(&mut self, operand: Operand128<T>) -> Result<Operand128Idx<T>> {
+ self.operands128.push(operand.cast());
+ Ok(Operand128Idx::new(self.operands128.len() as u32 - 1))
}
- 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 operand64<T>(&self, index: Operand64Idx<T>) -> Operand64<T> {
+ self.operands64[index.index()].cast()
}
- 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 operand128<T>(&self, index: Operand128Idx<T>) -> Operand128<T> {
+ self.operands128[index.index()].cast()
+ }
+
+ pub(crate) fn set_operand64<T>(&mut self, index: Operand64Idx<T>, operand: Operand64<T>) {
+ self.operands64[index.index()] = operand.cast();
+ }
+
+ pub(crate) fn set_operand128<T>(&mut self, index: Operand128Idx<T>, operand: Operand128<T>) {
+ self.operands128[index.index()] = operand.cast();
}
pub(crate) fn finish(self) -> WasmFunctionData {
@@ -163,6 +152,7 @@ pub(crate) struct FunctionBuilder<'a> {
metadata: &'a ModuleMetadata,
local_types: Vec<ValueLane>,
local_addr_map: Vec<u16>,
+ uses_local_memory: bool,
}
impl<'a> FunctionBuilder<'a> {
@@ -195,25 +185,31 @@ impl<'a> FunctionBuilder<'a> {
}],
operand_stack: Vec::new(),
lane_counts: ValueCounts::default(),
+ uses_local_memory: false,
}
}
+ fn mark_memory(&mut self, memory: u32) {
+ self.uses_local_memory |= memory >= self.metadata.imported_memories;
+ }
+
fn visit_struct_get_impl(
&mut self,
type_index: u32,
field_index: u32,
- instruction: fn(OperandIdx<TwoU32>) -> Instruction,
+ instruction: fn(Operand64Idx<(u32, u32)>) -> Instruction,
) -> Result<()> {
let size = self.metadata.struct_field(type_index, field_index)?;
- let operand = self.push_operand(TwoU32 { first: type_index, second: field_index })?;
+ let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, field_index))?;
self.emit(&[ValueLane::S32], &[size], instruction(operand))
}
- fn push_operand<T: OperandType>(&mut self, operand: T) -> Result<OperandIdx<T>>
- where
- T::Raw: BuilderRawOperand,
- {
- self.data.push_operand(operand)
+ fn push_operand64<T>(&mut self, operand: Operand64<T>) -> Result<Operand64Idx<T>> {
+ self.data.push_operand64(operand)
+ }
+
+ fn push_operand128<T>(&mut self, operand: Operand128<T>) -> Result<Operand128Idx<T>> {
+ self.data.push_operand128(operand)
}
}
@@ -246,6 +242,8 @@ impl ModuleMetadata {
let mut memory_sizes = Vec::with_capacity(imports.len() + memories.len());
let mut table_sizes = Vec::with_capacity(imports.len() + tables.len());
let mut tag_types = Vec::with_capacity(imports.len() + tags.len());
+ let imported_memories =
+ imports.iter().filter(|import| matches!(import.kind, ImportKind::Memory(_))).count() as u32;
for import in imports {
match &import.kind {
@@ -294,6 +292,7 @@ impl ModuleMetadata {
tables: table_sizes,
tags: tag_types,
aggregate_fields,
+ imported_memories,
}
}
@@ -378,6 +377,7 @@ impl ModuleMetadata {
impl<'a> VisitOperator<'a> for ValidateThenVisit<'_, '_> {
type Output = Result<()>;
+ #[cfg(not(rust_analyzer))] // rust analyzer gets confused and throws a bunch of errors when this macro is expanded
wasmparser::for_each_visit_operator!(validate_then_visit);
fn simd_visitor(&mut self) -> Option<&mut dyn VisitSimdOperator<'a, Output = Self::Output>> {
@@ -387,6 +387,7 @@ impl<'a> VisitOperator<'a> for ValidateThenVisit<'_, '_> {
#[cfg(feature = "validate")]
impl VisitSimdOperator<'_> for ValidateThenVisit<'_, '_> {
+ #[cfg(not(rust_analyzer))] // rust analyzer gets confused and throws a bunch of errors when this macro is expanded
wasmparser::for_each_visit_simd_operator!(validate_then_visit_simd);
}
@@ -397,7 +398,7 @@ pub(crate) fn process_operators(
ty_idx: u32,
allocs: OperatorsReaderAllocations,
deduplicate_operands: bool,
-) -> Result<(Vec<Instruction>, FunctionDataBuilder, OperatorsReaderAllocations)> {
+) -> Result<(Vec<Instruction>, FunctionDataBuilder, bool, OperatorsReaderAllocations)> {
let (local_types, local_addr_map) = locals;
let body_size = body.as_bytes().len();
let reader = body.get_binary_reader_for_operators()?;
@@ -419,7 +420,7 @@ pub(crate) fn process_operators(
}
reader.finish()?;
- Ok((builder.instructions, builder.data, reader.into_allocations()))
+ Ok((builder.instructions, builder.data, builder.uses_local_memory, reader.into_allocations()))
}
#[cfg(feature = "validate")]
@@ -431,7 +432,7 @@ pub(crate) fn process_operators_and_validate(
ty_idx: u32,
allocs: OperatorsReaderAllocations,
deduplicate_operands: bool,
-) -> Result<(Vec<Instruction>, FunctionDataBuilder, FuncValidatorAllocations, OperatorsReaderAllocations)> {
+) -> Result<(Vec<Instruction>, FunctionDataBuilder, bool, FuncValidatorAllocations, OperatorsReaderAllocations)> {
let (local_types, local_addr_map) = locals;
let body_size = body.as_bytes().len();
let reader = body.get_binary_reader_for_operators()?;
@@ -453,7 +454,13 @@ pub(crate) fn process_operators_and_validate(
}
reader.finish()?;
- Ok((builder.instructions, builder.data, validator.into_allocations(), reader.into_allocations()))
+ Ok((
+ builder.instructions,
+ builder.data,
+ builder.uses_local_memory,
+ validator.into_allocations(),
+ reader.into_allocations(),
+ ))
}
impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
@@ -612,7 +619,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Self::Output {
let size = self.metadata.struct_field(type_index, field_index)?;
- let operand = self.push_operand(TwoU32 { first: type_index, second: field_index })?;
+ let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, field_index))?;
self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(operand))
}
@@ -622,7 +629,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
self.pop_expect(size)?;
}
self.push_sizes(&[ValueLane::S32])?;
- let operand = self.push_operand(TwoU32 { first: type_index, second: array_size })?;
+ let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, array_size))?;
self.instructions.push(Instruction::ArrayNewFixed(operand));
Ok(())
}
@@ -634,7 +641,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
fn visit_call_indirect(&mut self, type_index: u32, table_index: u32) -> Self::Output {
let table_size = self.metadata.table_size(table_index)?;
- let operand = self.push_operand(TwoU32 { first: type_index, second: table_index })?;
+ let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, table_index))?;
let signature = self.metadata.signature(type_index)?;
self.pop_expect(table_size)?;
self.emit(&signature.params, &signature.results, Instruction::CallIndirect(operand))
@@ -660,7 +667,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
self.pop_expect(table_size)?;
self.apply_effect(&signature.params, &[])?;
self.mark_unreachable();
- let operand = self.push_operand(TwoU32 { first: type_index, second: table_index })?;
+ let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, table_index))?;
self.instructions.push(Instruction::ReturnCallIndirect(operand));
Ok(())
}
@@ -933,7 +940,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
let header_ip = self.instructions.len();
let branch_table_start = self.data.branch_table_targets.len() as u32;
let branch_operand =
- self.data.push_target_operand(BranchTableArg { target: 0, start: branch_table_start, len })?;
+ self.data.push_target_operand128(Operand128::<BranchTableOperand>::new(0, branch_table_start, len))?;
self.instructions.push(Instruction::BranchTable(branch_operand));
struct PadInfo {
@@ -978,9 +985,8 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
.find(|pad| pad.depth == default_depth)
.ok_or_else(|| crate::ParseError::Other("missing default branch table target".into()))?;
if let Instruction::BranchTable(index) = self.instructions[header_ip] {
- let mut operand = self.data.operand(index);
- operand.target = default_pad.pad_start as u32;
- self.data.set_operand(index, operand);
+ let operand = self.data.operand128(index);
+ self.data.set_operand128(index, operand.with_target(default_pad.pad_start as u32));
}
for pad in &pads {
@@ -1006,12 +1012,12 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
}
fn visit_f64_const(&mut self, val: wasmparser::Ieee64) -> Self::Output {
- let operand = self.push_operand(I64Operand { value: val.bits() as i64 })?;
+ let operand = self.push_operand64(Operand64::<i64>::new(val.bits() as i64))?;
self.emit(&[], &[ValueLane::S64], Instruction::Const64(operand))
}
fn visit_i64_const(&mut self, value: i64) -> Self::Output {
- let operand = self.push_operand(I64Operand { value })?;
+ let operand = self.push_operand64(Operand64::<i64>::new(value))?;
self.emit(&[], &[ValueLane::S64], Instruction::Const64(operand))
}
@@ -1019,52 +1025,55 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> {
let dst = self.metadata.table_size(dst_table)?;
let src = self.metadata.table_size(src_table)?;
let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 };
- let operand = self.push_operand(TwoU32 { first: dst_table, second: src_table })?;
+ let operand = self.push_operand64(Operand64::<(u32, u32)>::new(dst_table, src_table))?;
self.emit(&[dst, src, len], &[], Instruction::TableCopy(operand))
}
fn visit_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Self::Output {
let dst = self.metadata.memory_size(dst_mem)?;
let src = self.metadata.memory_size(src_mem)?;
+ self.mark_memory(dst_mem);
+ self.mark_memory(src_mem);
let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 };
- let operand = self.push_operand(TwoU32 { first: dst_mem, second: src_mem })?;
+ let operand = self.push_operand64(Operand64::<(u32, u32)>::new(dst_mem, src_mem))?;
self.emit(&[dst, src, len], &[], Instruction::MemoryCopy(operand))
}
fn visit_memory_init(&mut self, data_index: u32, memory: u32) -> Self::Output {
let dst = self.metadata.memory_size(memory)?;
- let operand = self.push_operand(TwoU32 { first: data_index, second: memory })?;
+ self.mark_memory(memory);
+ let operand = self.push_operand64(Operand64::<(u32, u32)>::new(data_index, memory))?;
self.emit(&[dst, ValueLane::S32, ValueLane::S32], &[], Instruction::MemoryInit(operand))
}
fn visit_table_init(&mut self, elem_index: u32, table: u32) -> Self::Output {
let address = self.metadata.table_size(table)?;
- let operand = self.push_operand(TwoU32 { first: elem_index, second: table })?;
+ let operand = self.push_operand64(Operand64::<(u32, u32)>::new(elem_index, table))?;
self.emit(&[address, ValueLane::S32, ValueLane::S32], &[], Instruction::TableInit(operand))
}
fn visit_array_new_data(&mut self, type_index: u32, data_index: u32) -> Self::Output {
- let operand = self.push_operand(TwoU32 { first: type_index, second: data_index })?;
+ let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, data_index))?;
self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewData(operand))
}
fn visit_array_new_elem(&mut self, type_index: u32, elem_index: u32) -> Self::Output {
- let operand = self.push_operand(TwoU32 { first: type_index, second: elem_index })?;
+ let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, elem_index))?;
self.emit(&[ValueLane::S32, ValueLane::S32], &[ValueLane::S32], Instruction::ArrayNewElem(operand))
}
fn visit_array_init_data(&mut self, type_index: u32, data_index: u32) -> Self::Output {
- let operand = self.push_operand(TwoU32 { first: type_index, second: data_index })?;
+ let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, data_index))?;
self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitData(operand))
}
fn visit_array_init_elem(&mut self, type_index: u32, elem_index: u32) -> Self::Output {
- let operand = self.push_operand(TwoU32 { first: type_index, second: elem_index })?;
+ let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index, elem_index))?;
self.emit(&[ValueLane::S32; 4], &[], Instruction::ArrayInitElem(operand))
}
fn visit_array_copy(&mut self, type_index_dst: u32, type_index_src: u32) -> Self::Output {
- let operand = self.push_operand(TwoU32 { first: type_index_dst, second: type_index_src })?;
+ let operand = self.push_operand64(Operand64::<(u32, u32)>::new(type_index_dst, type_index_src))?;
self.emit(&[ValueLane::S32; 5], &[], Instruction::ArrayCopy(operand))
}
@@ -1312,12 +1321,12 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> {
}
fn visit_i8x16_shuffle(&mut self, lanes: [u8; 16]) -> Self::Output {
- let index = self.push_operand(V128Operand { value: lanes })?;
+ let index = self.push_operand128(Operand128::<[u8; 16]>::new(lanes))?;
self.emit(&[ValueLane::S128, ValueLane::S128], &[ValueLane::S128], Instruction::I8x16Shuffle(index))
}
fn visit_v128_const(&mut self, value: wasmparser::V128) -> Self::Output {
- let index = self.push_operand(V128Operand { value: *value.bytes() })?;
+ let index = self.push_operand128(Operand128::<[u8; 16]>::new(*value.bytes()))?;
self.emit(&[], &[ValueLane::S128], Instruction::Const128(index))
}
}
@@ -1332,7 +1341,7 @@ impl FunctionBuilder<'_> {
self.pop_expect(ValueLane::S32)?;
let target = convert_heap_type(target.heap_type(), target.is_nullable())?;
let conditional_ip = self.instructions.len();
- let operand = self.data.push_target_operand(CastBranch { target: 0, ref_type_bits: target.to_bits() })?;
+ let operand = self.data.push_target_operand64(Operand64::<(u32, u32)>::new(0, target.to_bits()))?;
self.instructions.push(if branch_on_fail {
Instruction::BrOnCastFail(operand)
} else {
@@ -1502,9 +1511,8 @@ impl FunctionBuilder<'_> {
*ip = target as u32;
}
Instruction::BrOnCast(index) | Instruction::BrOnCastFail(index) => {
- let mut operand = self.data.operand(*index);
- operand.target = target as u32;
- self.data.set_operand(*index, operand);
+ let operand = self.data.operand64(*index);
+ self.data.set_operand64(*index, operand.with_target(target as u32));
}
_ => {}
}