summaryrefslogtreecommitdiff
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
parenta8f42e481e9cc56834c39f073236c25cb533efc6 (diff)
chore: simplify operands, extract more exec_ methods
Signed-off-by: Henry <mail@henrygressmann.de>
-rw-r--r--benches/fibonacci.rs2
-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
-rw-r--r--crates/tinywasm/src/func/context.rs10
-rw-r--r--crates/tinywasm/src/func/host.rs10
-rw-r--r--crates/tinywasm/src/instance.rs24
-rw-r--r--crates/tinywasm/src/interpreter/executor.rs1385
-rw-r--r--crates/tinywasm/src/interpreter/num_helpers.rs23
-rw-r--r--crates/tinywasm/src/interpreter/simd/macros.rs21
-rw-r--r--crates/tinywasm/src/interpreter/stack/value_stack.rs8
-rw-r--r--crates/tinywasm/src/interpreter/values.rs134
-rw-r--r--crates/tinywasm/src/macros.rs18
-rw-r--r--crates/tinywasm/src/store/global.rs6
-rw-r--r--crates/tinywasm/src/store/mod.rs7
-rw-r--r--crates/tinywasm/src/store/state.rs4
-rw-r--r--crates/types/src/archive.rs12
-rw-r--r--crates/types/src/instructions.rs572
-rw-r--r--crates/types/src/lib.rs3
-rw-r--r--crates/types/src/operands.rs386
-rw-r--r--crates/types/src/reference.rs3
-rwxr-xr-xexamples/rust/build.sh4
-rw-r--r--examples/rust/src/print.twasmbin154 -> 155 bytes
27 files changed, 1940 insertions, 1434 deletions
diff --git a/benches/fibonacci.rs b/benches/fibonacci.rs
index 51fd2d3..699dc79 100644
--- a/benches/fibonacci.rs
+++ b/benches/fibonacci.rs
@@ -44,7 +44,7 @@ fn criterion_benchmark(c: &mut Criterion) {
group.bench_function("fibonacci_from_twasm", |b| b.iter(|| fibonacci_from_twasm(&twasm)));
group.measurement_time(std::time::Duration::from_secs(10));
- group.bench_function("fibonacci_iterative_60", |b| b.iter(|| fibonacci_run(module.clone(), false, 60)));
+ group.bench_function("fibonacci_iterative_100", |b| b.iter(|| fibonacci_run(module.clone(), false, 100)));
group.bench_function("fibonacci_recursive_26", |b| b.iter(|| fibonacci_run(module.clone(), true, 26)));
}
diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs
index 225b6ae..4cf0d02 100644
--- a/crates/parser/src/conversion.rs
+++ b/crates/parser/src/conversion.rs
@@ -186,9 +186,9 @@ pub(crate) fn convert_module_code(
}
#[cfg(feature = "validate")]
- let (body, data, validator_allocs, reader_allocs) = match validator {
+ let (body, data, uses_local_memory, validator_allocs, reader_allocs) = match validator {
Some(validator) => {
- let (body, data, validator_allocs, reader_allocs) = process_operators_and_validate(
+ let (body, data, uses_local_memory, validator_allocs, reader_allocs) = process_operators_and_validate(
validator,
func,
(local_types, local_addr_map),
@@ -197,10 +197,10 @@ pub(crate) fn convert_module_code(
reader_allocs,
options.deduplicate_operands(),
)?;
- (body, data, Some(validator_allocs), reader_allocs)
+ (body, data, uses_local_memory, Some(validator_allocs), reader_allocs)
}
None => {
- let (body, data, reader_allocs) = process_operators(
+ let (body, data, uses_local_memory, reader_allocs) = process_operators(
func,
(local_types, local_addr_map),
metadata,
@@ -208,13 +208,13 @@ pub(crate) fn convert_module_code(
reader_allocs,
options.deduplicate_operands(),
)?;
- (body, data, None, reader_allocs)
+ (body, data, uses_local_memory, None, reader_allocs)
}
};
#[cfg(not(feature = "validate"))]
- let (body, data, validator_allocs, reader_allocs) = {
+ let (body, data, uses_local_memory, validator_allocs, reader_allocs) = {
let _ = validator;
- let (body, data, reader_allocs) = process_operators(
+ let (body, data, uses_local_memory, reader_allocs) = process_operators(
func,
(local_types, local_addr_map),
metadata,
@@ -222,9 +222,13 @@ pub(crate) fn convert_module_code(
reader_allocs,
options.deduplicate_operands(),
)?;
- (body, data, None, reader_allocs)
+ (body, data, uses_local_memory, None, reader_allocs)
};
- Ok((FunctionCode { instructions: body, data, locals: local_counts }, validator_allocs, reader_allocs))
+ Ok((
+ FunctionCode { instructions: body, data, locals: local_counts, uses_local_memory },
+ validator_allocs,
+ reader_allocs,
+ ))
}
pub(crate) fn convert_rec_group(ty: wasmparser::RecGroup, group_start: u32, types: &mut Vec<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));
}
_ => {}
}
diff --git a/crates/tinywasm/src/func/context.rs b/crates/tinywasm/src/func/context.rs
index 0b9e1f9..9f637f0 100644
--- a/crates/tinywasm/src/func/context.rs
+++ b/crates/tinywasm/src/func/context.rs
@@ -22,10 +22,12 @@ impl FuncContext<'_> {
/// Get the module instance.
pub fn module(&self) -> crate::ModuleInstance {
- self.store
- .get_module_instance(self.module_id)
- .unwrap_or_else(|| unreachable!("invalid module instance id in host function context: {}", self.module_id))
- .clone()
+ unwrap_or_unreachable!(
+ self.store.get_module_instance(self.module_id),
+ "invalid module instance id in host function context: {}",
+ self.module_id
+ )
+ .clone()
}
/// Get a memory export.
diff --git a/crates/tinywasm/src/func/host.rs b/crates/tinywasm/src/func/host.rs
index 1dcf3c1..064f6c7 100644
--- a/crates/tinywasm/src/func/host.rs
+++ b/crates/tinywasm/src/func/host.rs
@@ -261,13 +261,13 @@ where
{
fn call(&self, ctx: FuncContext<'_>, args: &[WasmValue], results: &mut [WasmValue]) -> Result<()> {
let mut values = args.iter().cloned();
- let params = P::from_wasm_values_exact(&mut values)?;
+ let params = cold_err!(P::from_wasm_values_exact(&mut values))?;
let mut values = (self.func)(ctx, params)?.into_wasm_values();
for result in results {
- *result = values.next().ok_or_else(|| crate::Error::other("not enough typed function results"))?;
+ *result = cold_err!(values.next().ok_or_else(|| crate::Error::other("not enough typed function results")))?;
}
if values.next().is_some() {
- return Err(crate::Error::other("too many typed function results"));
+ return cold!(Err(crate::Error::other("too many typed function results")));
}
Ok(())
}
@@ -279,10 +279,10 @@ where
};
let params = {
let mut values = store.stack_value_iter(type_addr, FuncValueTypes::Params, base)?;
- P::from_wasm_values_exact(&mut values)
+ cold_err!(P::from_wasm_values_exact(&mut values))
};
store.value_stack.truncate_to_base(base);
- let result = (self.func)(FuncContext { store, module_id }, params?)?;
+ let result = cold_err!((self.func)(FuncContext { store, module_id }, params?))?;
store.push_typed_values::<true>(type_addr, result.into_wasm_values(), base)
}
}
diff --git a/crates/tinywasm/src/instance.rs b/crates/tinywasm/src/instance.rs
index bd78a57..ea97961 100644
--- a/crates/tinywasm/src/instance.rs
+++ b/crates/tinywasm/src/instance.rs
@@ -68,25 +68,25 @@ struct ModuleInstanceInner {
impl ModuleInstance {
#[inline]
pub(crate) fn resolve_type_addr(&self, type_addr: TypeAddr) -> TypeAddr {
- *self.0.type_addrs.get(type_addr as usize).unwrap_or_else(|| unreachable!("invalid type address: {type_addr}"))
+ *unwrap_or_unreachable!(self.0.type_addrs.get(type_addr as usize), "invalid type address: {type_addr}")
}
/// resolve a function address to the global store address
#[inline]
pub(crate) fn resolve_func_addr(&self, addr: FuncAddr) -> FuncAddr {
- *self.0.func_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid function address: {addr}"))
+ *unwrap_or_unreachable!(self.0.func_addrs.get(addr as usize), "invalid function address: {addr}")
}
/// resolve a table address to the global store address
#[inline]
pub(crate) fn resolve_table_addr(&self, addr: TableAddr) -> TableAddr {
- *self.0.table_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid table address: {addr}"))
+ *unwrap_or_unreachable!(self.0.table_addrs.get(addr as usize), "invalid table address: {addr}")
}
/// resolve a memory address to the global store address
#[inline]
pub(crate) fn resolve_mem_addr(&self, addr: MemAddr) -> MemAddr {
- *self.0.mem_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid memory address: {addr}"))
+ *unwrap_or_unreachable!(self.0.mem_addrs.get(addr as usize), "invalid memory address: {addr}")
}
/// The resolved store address of the module's first memory, or `MemAddr::MAX` when the module
@@ -103,24 +103,24 @@ impl ModuleInstance {
/// resolve a data address to the global store address
#[inline]
pub(crate) fn resolve_data_addr(&self, addr: DataAddr) -> DataAddr {
- *self.0.data_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid data address: {addr}"))
+ *unwrap_or_unreachable!(self.0.data_addrs.get(addr as usize), "invalid data address: {addr}")
}
/// resolve an element address to the global store address
#[inline]
pub(crate) fn resolve_elem_addr(&self, addr: ElemAddr) -> ElemAddr {
- *self.0.elem_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid element address: {addr}"))
+ *unwrap_or_unreachable!(self.0.elem_addrs.get(addr as usize), "invalid element address: {addr}")
}
/// resolve a global address to the global store address
#[inline]
pub(crate) fn resolve_global_addr(&self, addr: GlobalAddr) -> GlobalAddr {
- *self.0.global_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid global address: {addr}"))
+ *unwrap_or_unreachable!(self.0.global_addrs.get(addr as usize), "invalid global address: {addr}")
}
#[inline]
pub(crate) fn resolve_tag_addr(&self, addr: TagAddr) -> TagAddr {
- *self.0.tag_addrs.get(addr as usize).unwrap_or_else(|| unreachable!("invalid tag address: {addr}"))
+ *unwrap_or_unreachable!(self.0.tag_addrs.get(addr as usize), "invalid tag address: {addr}")
}
#[inline]
@@ -181,9 +181,11 @@ impl ModuleInstance {
addrs.funcs.extend(store.init_funcs(&module.funcs, id, &module.func_type_idxs[imported_funcs..], &type_addrs));
addrs.tags.extend(store.init_tags(&module.tags, &type_addrs));
let limiter = store.engine.config().resource_limiter.clone();
- addrs
- .memories
- .extend(store.init_memories(&module.memory_types, |ty| MemoryInstance::new(ty, limiter.as_deref()))?);
+ if !module.skip_local_memory_allocation {
+ addrs
+ .memories
+ .extend(store.init_memories(&module.memory_types, |ty| MemoryInstance::new(ty, limiter.as_deref()))?);
+ }
store.init_globals(&mut addrs.globals, &module.globals, &addrs.funcs, &type_addrs)?;
addrs.tables.extend(store.init_tables(&module.tables, &addrs.globals, &addrs.funcs, &type_addrs)?);
diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs
index 4824b63..4011e96 100644
--- a/crates/tinywasm/src/interpreter/executor.rs
+++ b/crates/tinywasm/src/interpreter/executor.rs
@@ -1,4 +1,3 @@
-use core::hint::cold_path;
use core::ops::ControlFlow;
#[cfg(not(feature = "std"))]
@@ -8,7 +7,7 @@ use super::no_std_floats::NoStdFloatExt;
use alloc::boxed::Box;
use alloc::vec::Vec;
-use interpreter::stack::CallFrame;
+use interpreter::stack::{CallFrame, ValueStack};
use tinywasm_types::*;
use super::ExecState;
@@ -33,10 +32,8 @@ pub(crate) struct Executor<'store, const BUDGETED: bool> {
impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
pub(crate) fn new(store: &'store mut Store, cf: CallFrame, call_stack_base: u32) -> Self {
let wasm_func = store.state.get_wasm_func(cf.func_addr);
- let module = store
- .get_module_instance(wasm_func.owner)
- .unwrap_or_else(|| unreachable!("invalid module instance"))
- .clone();
+ let module =
+ unwrap_or_unreachable!(store.get_module_instance(wasm_func.owner), "invalid module instance").clone();
let mem0 = module.mem0_addr();
Self { module, cf, func: wasm_func.func.clone(), store, call_stack_base, mem0 }
}
@@ -50,8 +47,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
/// Switches the executor to another module, keeping the cached memory-0 address in sync.
#[inline]
fn set_module(&mut self, owner: ModuleInstanceId) {
- self.module =
- self.store.get_module_instance(owner).unwrap_or_else(|| unreachable!("invalid module instance")).clone();
+ self.module = unwrap_or_unreachable!(self.store.get_module_instance(owner), "invalid module instance").clone();
self.mem0 = self.module.mem0_addr();
}
@@ -71,324 +67,206 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
fn exec(&mut self, instr_ptr: usize) -> Result<ControlFlow<(), usize>> {
macro_rules! exec_op {
(binary_fallible $ty:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{
- let $rhs = <$ty>::stack_pop(&mut self.store.value_stack);
- let $lhs = <$ty>::stack_pop(&mut self.store.value_stack);
- <$ty>::stack_push(&mut self.store.value_stack, $expr?)?;
+ fn exec_binary_fallible(value_stack: &mut ValueStack) -> Result<(), Trap> {
+ let $rhs = <$ty>::stack_pop(value_stack);
+ let $lhs = <$ty>::stack_pop(value_stack);
+ <$ty>::stack_push(value_stack, $expr?)
+ }
+ exec_binary_fallible(&mut self.store.value_stack)?;
}};
(unary $from:ty => $to:ty, |$v:ident| $expr:expr) => {{
- let $v = <$from>::stack_pop(&mut self.store.value_stack);
- <$to>::stack_push(&mut self.store.value_stack, $expr)?;
+ fn exec_unary(value_stack: &mut ValueStack) -> Result<(), Trap> {
+ let $v = <$from>::stack_pop(value_stack);
+ <$to>::stack_push(value_stack, $expr)
+ }
+ exec_unary(&mut self.store.value_stack)?;
}};
(binary $from:ty => $to:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{
- let $rhs = <$from>::stack_pop(&mut self.store.value_stack);
- let $lhs = <$from>::stack_pop(&mut self.store.value_stack);
- <$to>::stack_push(&mut self.store.value_stack, $expr)?;
- }};
- (binary_two_results $from:ty => $to:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{
- let $rhs = <$from>::stack_pop(&mut self.store.value_stack);
- let $lhs = <$from>::stack_pop(&mut self.store.value_stack);
- let out = $expr;
- <$to>::stack_push(&mut self.store.value_stack, out.0)?;
- <$to>::stack_push(&mut self.store.value_stack, out.1)?;
+ fn exec_binary(value_stack: &mut ValueStack) -> Result<(), Trap> {
+ let $rhs = <$from>::stack_pop(value_stack);
+ let $lhs = <$from>::stack_pop(value_stack);
+ <$to>::stack_push(value_stack, $expr)
+ }
+ exec_binary(&mut self.store.value_stack)?;
}};
- (binary_mixed $lhs_ty:ty, $rhs_ty:ty => $res:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{
- let $rhs = <$rhs_ty>::stack_pop(&mut self.store.value_stack);
- let $lhs = <$lhs_ty>::stack_pop(&mut self.store.value_stack);
- <$res>::stack_push(&mut self.store.value_stack, $expr)?;
+ (binary $lhs_ty:ty, $rhs_ty:ty => $res:ty, |$lhs:ident, $rhs:ident| $expr:expr) => {{
+ fn exec_binary(value_stack: &mut ValueStack) -> Result<(), Trap> {
+ let $rhs = <$rhs_ty>::stack_pop(value_stack);
+ let $lhs = <$lhs_ty>::stack_pop(value_stack);
+ <$res>::stack_push(value_stack, $expr)
+ }
+ exec_binary(&mut self.store.value_stack)?;
}};
(ternary $from:ty => $to:ty, |$a:ident, $b:ident, $c:ident| $expr:expr) => {{
- let $c = <$from>::stack_pop(&mut self.store.value_stack);
- let $b = <$from>::stack_pop(&mut self.store.value_stack);
- let $a = <$from>::stack_pop(&mut self.store.value_stack);
- <$to>::stack_push(&mut self.store.value_stack, $expr)?;
- }};
- (quaternary_two_results $from:ty => $to:ty, |$a:ident, $b:ident, $c:ident, $d:ident| $expr:expr) => {{
- let $d = <$from>::stack_pop(&mut self.store.value_stack);
- let $c = <$from>::stack_pop(&mut self.store.value_stack);
- let $b = <$from>::stack_pop(&mut self.store.value_stack);
- let $a = <$from>::stack_pop(&mut self.store.value_stack);
- let out = $expr;
- <$to>::stack_push(&mut self.store.value_stack, out.0)?;
- <$to>::stack_push(&mut self.store.value_stack, out.1)?;
- }};
- (local_set_pop $ty:ty, $local_index:expr) => {{
- let val = <$ty>::stack_pop(&mut self.store.value_stack);
- <$ty>::local_set(&mut self.store.value_stack, &self.cf, *$local_index, val);
- }};
- (local_tee $ty:ty, $local_index:expr) => {{
- let val = <$ty>::stack_peek(&self.store.value_stack);
- <$ty>::local_set(&mut self.store.value_stack, &self.cf, *$local_index, val);
- }};
- (global_get $ty:ty, $global_index:expr) => {{
- let addr = self.module.resolve_global_addr(*$global_index);
- let value = <$ty>::global_get(&self.store.state.globals, addr);
- <$ty>::stack_push(&mut self.store.value_stack, value)?;
- }};
- (global_set $ty:ty, $global_index:expr) => {{
- let addr = self.module.resolve_global_addr(*$global_index);
- let value = <$ty>::stack_pop(&mut self.store.value_stack);
- <$ty>::global_set(&mut self.store.state.globals, addr, value);
- }};
- (global_tee $ty:ty, $global_index:expr) => {{
- let addr = self.module.resolve_global_addr(*$global_index);
- let value = <$ty>::stack_peek(&self.store.value_stack);
- <$ty>::global_set(&mut self.store.state.globals, addr, value);
- }};
- (binop_local_local $vt:ty, $exec:ident, $op:ident, $a:ident, $b:ident) => {{
- let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a);
- let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b);
- <$vt>::stack_push(&mut self.store.value_stack, $exec(*$op, lhs, rhs))?;
- }};
- (binop_local_local_set $vt:ty, $exec:ident, $op:ident, $a:ident, $b:ident, $dst:ident) => {{
- let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a);
- let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b);
- let value = $exec(*$op, lhs, rhs);
- <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value);
- }};
- (binop_local_local_tee $vt:ty, $exec:ident, $op:ident, $a:ident, $b:ident, $dst:ident) => {{
- let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a);
- let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b);
- let value = $exec(*$op, lhs, rhs);
- <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value);
- <$vt>::stack_push(&mut self.store.value_stack, value)?;
- }};
- (cmp_local_local $vt:ty, $cmp:ident, $op:ident, $a:ident, $b:ident) => {{
- let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$a);
- let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$b);
- self.store.value_stack.push(i32::from($cmp(lhs, rhs, *$op)))?;
- }};
- (binop_local_const $vt:ty, $exec:ident, $op:ident, $local:ident, $rhs:expr) => {{
- let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local);
- <$vt>::stack_push(&mut self.store.value_stack, $exec(*$op, lhs, $rhs))?;
- }};
- (binop_local_const_set $vt:ty, $exec:ident, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{
- let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local);
- let value = $exec(*$op, lhs, $rhs);
- <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value);
- }};
- (binop_local_const_tee $vt:ty, $exec:ident, $op:ident, $local:ident, $rhs:expr, $dst:ident) => {{
- let lhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local);
- let value = $exec(*$op, lhs, $rhs);
- <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value);
- <$vt>::stack_push(&mut self.store.value_stack, value)?;
- }};
- (binop_global_const $vt:ty, $exec:ident, $op:ident, $global:ident, $rhs:expr) => {{
- let lhs = <$vt>::global_get(&self.store.state.globals, self.module.resolve_global_addr(*$global));
- self.store.value_stack.push($exec(*$op, lhs, $rhs))?;
- }};
- (binop_stack_global $vt:ty, $exec:ident, $op:ident, $global:ident) => {{
- let global_val =
- <$vt>::global_get(&self.store.state.globals, self.module.resolve_global_addr(*$global));
- let stack_val = <$vt>::stack_pop(&mut self.store.value_stack);
- self.store.value_stack.push($exec(*$op, stack_val, global_val))?;
- }};
- (binop_stack_local $vt:ty, $exec:ident, $op:ident, $local:ident) => {{
- let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local);
- let lhs = <$vt>::stack_pop(&mut self.store.value_stack);
- <$vt>::stack_push(&mut self.store.value_stack, $exec(*$op, lhs, rhs))?;
- }};
- (binop_stack_local_set $vt:ty, $exec:ident, $op:ident, $local:ident, $dst:ident) => {{
- let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local);
- let lhs = <$vt>::stack_pop(&mut self.store.value_stack);
- let value = $exec(*$op, lhs, rhs);
- <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value);
- }};
- (binop_stack_local_tee $vt:ty, $exec:ident, $op:ident, $local:ident, $dst:ident) => {{
- let rhs = <$vt>::local_get(&self.store.value_stack, &self.cf, *$local);
- let lhs = <$vt>::stack_pop(&mut self.store.value_stack);
- let value = $exec(*$op, lhs, rhs);
- <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value);
- <$vt>::stack_push(&mut self.store.value_stack, value)?;
- }};
- (binop_acc_local $ty:ty, $acc:ident, $mul:expr, $add:expr) => {{
- let rhs = <$ty>::stack_pop(&mut self.store.value_stack);
- let lhs = <$ty>::stack_pop(&mut self.store.value_stack);
- let value = ($mul)(lhs, rhs);
- <$ty>::local_update(&mut self.store.value_stack, &self.cf, *$acc, |acc| ($add)(value, acc));
+ fn exec_ternary(value_stack: &mut ValueStack) -> Result<(), Trap> {
+ let $c = <$from>::stack_pop(value_stack);
+ let $b = <$from>::stack_pop(value_stack);
+ let $a = <$from>::stack_pop(value_stack);
+ <$to>::stack_push(value_stack, $expr)
+ }
+ exec_ternary(&mut self.store.value_stack)?;
}};
}
use tinywasm_types::Instruction::*;
#[rustfmt::skip]
match &self.func.instructions[instr_ptr] {
- Unreachable => { cold_path(); return Err(Trap::Unreachable.into()) },
+ Unreachable => return cold!(Err(Trap::Unreachable.into())),
Drop32 => { _ = Value32::stack_pop(&mut self.store.value_stack)},
Drop64 => { _ = Value64::stack_pop(&mut self.store.value_stack)},
Drop128 => { _ = Value128::stack_pop(&mut self.store.value_stack)},
Select32 => Value32::stack_select(&mut self.store.value_stack),
Select64 => Value64::stack_select(&mut self.store.value_stack),
Select128 => Value128::stack_select(&mut self.store.value_stack),
+ SelectStore32(idx) => self.exec_select_store::<Value32, 4>(idx.resolve(&self.func.data))?,
+ SelectStore64(idx) => self.exec_select_store::<Value64, 8>(idx.resolve(&self.func.data))?,
SelectMulti(counts) => self.store.value_stack.select_multi(*counts),
- Call(v) => { return Ok(self.exec_call_direct(*v, instr_ptr + 1)?); }
- CallSelf => { self.exec_call_self(instr_ptr + 1)?; return Ok(ControlFlow::Continue(0)); }
- CallIndirect(idx) => { return Ok(self.exec_call_indirect::<false>(*idx, instr_ptr + 1)?); }
- CallRef(ty) => { return Ok(self.exec_call_ref::<false>(*ty, instr_ptr + 1)?); }
- ReturnCall(v) => { return Ok(self.exec_return_call_direct(*v)?); }
- ReturnCallSelf => { self.exec_return_call_self()?; return Ok(ControlFlow::Continue(0)); }
- ReturnCallIndirect(idx) => { return Ok(self.exec_call_indirect::<true>(*idx, instr_ptr + 1)?); }
- ReturnCallRef(ty) => { return Ok(self.exec_call_ref::<true>(*ty, instr_ptr + 1)?); }
- Throw(tag) => { return Ok(ControlFlow::Continue(self.exec_throw(*tag, instr_ptr)?)); }
- ThrowRef => { return Ok(ControlFlow::Continue(self.exec_throw_ref(instr_ptr)?)); }
- Jump(ip) => { return Ok(ControlFlow::Continue(*ip as usize)); }
- JumpIfZero32(ip) => if Self::exec_jump_if(&self.cf, |_| i32::stack_pop(&mut self.store.value_stack) == 0) { return Ok(ControlFlow::Continue(*ip as usize)) },
- JumpIfNonZero32(ip) => if Self::exec_jump_if(&self.cf, |_| i32::stack_pop(&mut self.store.value_stack) != 0) { return Ok(ControlFlow::Continue(*ip as usize)) },
- JumpIfZero64(ip) => if Self::exec_jump_if(&self.cf, |_| i64::stack_pop(&mut self.store.value_stack) == 0) { return Ok(ControlFlow::Continue(*ip as usize)) },
- JumpIfNonZero64(ip) => if Self::exec_jump_if(&self.cf, |_| i64::stack_pop(&mut self.store.value_stack) != 0) { return Ok(ControlFlow::Continue(*ip as usize)) },
- JumpIfRefNull(ip) => if Self::exec_jump_if(&self.cf, |_| {
- let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null();
- if is_null { ValueRef::stack_pop(&mut self.store.value_stack); }
- is_null
- }) { return Ok(ControlFlow::Continue(*ip as usize)) },
- JumpIfRefNonNull(ip) => if Self::exec_jump_if(&self.cf, |_| {
- let is_non_null = !ValueRef::stack_peek(&self.store.value_stack).is_null();
- if !is_non_null { ValueRef::stack_pop(&mut self.store.value_stack); }
- is_non_null
- }) { return Ok(ControlFlow::Continue(*ip as usize)) },
- BrOnCast(idx) => { let v = idx.get(&self.func.data); if !self.exec_ref_matches(v.ref_type()) { return Ok(ControlFlow::Continue(v.target as usize)); } },
- BrOnCastFail(idx) => { let v = idx.get(&self.func.data); if self.exec_ref_matches(v.ref_type()) { return Ok(ControlFlow::Continue(v.target as usize)); } },
- JumpIfLocalZero32(arg) => if Self::exec_jump_if(&self.cf, |cf| Value32::local_get(&self.store.value_stack, cf, arg.local) == 0) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) },
- JumpIfLocalNonZero32(arg) => if Self::exec_jump_if(&self.cf, |cf| Value32::local_get(&self.store.value_stack, cf, arg.local) != 0) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) },
- JumpIfLocalZero64(arg) => if Self::exec_jump_if(&self.cf, |cf| Value64::local_get(&self.store.value_stack, cf, arg.local) == 0) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) },
- JumpIfLocalNonZero64(arg) => if Self::exec_jump_if(&self.cf, |cf| Value64::local_get(&self.store.value_stack, cf, arg.local) != 0) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) },
- JumpCmpStackConst32(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&self.cf, |_| cmp_i32(i32::stack_pop(&mut self.store.value_stack), v.value, packed.op)) { return Ok(ControlFlow::Continue(v.target as usize)) } },
- JumpCmpStackConst64(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&self.cf, |_| cmp_i64(i64::stack_pop(&mut self.store.value_stack), v.value, packed.op)) { return Ok(ControlFlow::Continue(v.target as usize)) } },
- JumpCmpStackLocal32(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&self.cf, |cf| {
- let lhs = i32::stack_pop(&mut self.store.value_stack);
- cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, v.local), packed.op)
- }) { return Ok(ControlFlow::Continue(v.target as usize)) } },
- JumpCmpStackLocal64(packed) => { let v = packed.index.get(&self.func.data); if Self::exec_jump_if(&self.cf, |cf| {
- let lhs = i64::stack_pop(&mut self.store.value_stack);
- cmp_i64(lhs, i64::local_get(&self.store.value_stack, cf, v.local), packed.op)
- }) { return Ok(ControlFlow::Continue(v.target as usize)) } },
- BinOpLocalConstJump32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |cf| { let value = exec_binop_32(op, i32::local_get(&self.store.value_stack, cf, v.local) as u32, v.value as u32) as i32; i32::local_set(&mut self.store.value_stack, cf, v.local, value); (value == 0) == (v.on_zero != 0) }) { return Ok(ControlFlow::Continue(v.target as usize)) } },
- BinOpLocalConstJumpCmpLocal32(packed) => { let v = packed.index.get(&self.func.data); let (binop, cmp) = packed.op; if Self::exec_jump_if(&self.cf, |cf| { let lhs = exec_binop_32(binop, i32::local_get(&self.store.value_stack, cf, v.local) as u32, v.value as u32) as i32; i32::local_set(&mut self.store.value_stack, cf, v.local, lhs); cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, v.right), cmp) }) { return Ok(ControlFlow::Continue(v.target as usize)) } },
- BinOpStackConstTeeLocalJump32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; let value = exec_binop_32(op, i32::stack_pop(&mut self.store.value_stack) as u32, v.value as u32) as i32; i32::local_set(&mut self.store.value_stack, &self.cf, v.local, value); i32::stack_push(&mut self.store.value_stack, value)?; if Self::exec_jump_if(&self.cf, |_| (value == 0) == (v.on_zero != 0)) { return Ok(ControlFlow::Continue(v.target as usize)) } },
- BinOpGlobalConstJump32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |_| {
- let global = self.module.resolve_global_addr(v.global);
- let value = exec_binop_32(op, i32::global_get(&self.store.state.globals, global) as u32, v.value as u32) as i32;
- i32::global_set(&mut self.store.state.globals, global, value);
- (value == 0) == (v.on_zero != 0)
- }) { return Ok(ControlFlow::Continue(v.target as usize)) } },
- IncLocalJump32(idx) => { let v = idx.get(&self.func.data); if Self::exec_jump_if(&self.cf, |cf| { let value = i32::local_get(&self.store.value_stack, cf, v.local).wrapping_add(v.value); i32::local_set(&mut self.store.value_stack, cf, v.local, value); (value == 0) == (v.on_zero != 0) }) { return Ok(ControlFlow::Continue(v.target as usize)) } },
- IncStackTeeLocalJump32(idx) => { let v = idx.get(&self.func.data); let value = i32::stack_pop(&mut self.store.value_stack).wrapping_add(v.value); i32::local_set(&mut self.store.value_stack, &self.cf, v.local, value); i32::stack_push(&mut self.store.value_stack, value)?; if Self::exec_jump_if(&self.cf, |_| (value == 0) == (v.on_zero != 0)) { return Ok(ControlFlow::Continue(v.target as usize)) } },
- IncGlobalJump32(idx) => { let v = idx.get(&self.func.data); if Self::exec_jump_if(&self.cf, |_| {
- let global = self.module.resolve_global_addr(v.global);
- let value = i32::global_get(&self.store.state.globals, global).wrapping_add(v.value);
- i32::global_set(&mut self.store.state.globals, global, value);
- (value == 0) == (v.on_zero != 0)
- }) { return Ok(ControlFlow::Continue(v.target as usize)) } },
- IncLocalJumpCmpLocal32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |cf| { let lhs = i32::local_get(&self.store.value_stack, cf, v.local).wrapping_add(v.value); i32::local_set(&mut self.store.value_stack, cf, v.local, lhs); cmp_i32(lhs, i32::local_get(&self.store.value_stack, cf, v.right), op) }) { return Ok(ControlFlow::Continue(v.target as usize)) } },
- JumpCmpLocalConst32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, v.local), v.value, op)) { return Ok(ControlFlow::Continue(v.target as usize)) } },
- JumpCmpLocalConst64(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, v.local), i64::from(v.value), op)) { return Ok(ControlFlow::Continue(v.target as usize)) } },
- JumpCmpLocalLocal32(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |cf| cmp_i32(i32::local_get(&self.store.value_stack, cf, v.left), i32::local_get(&self.store.value_stack, cf, v.right), op)) { return Ok(ControlFlow::Continue(v.target as usize)) } },
- JumpCmpLocalLocal64(packed) => { let v = packed.index.get(&self.func.data); let op = packed.op; if Self::exec_jump_if(&self.cf, |cf| cmp_i64(i64::local_get(&self.store.value_stack, cf, v.left), i64::local_get(&self.store.value_stack, cf, v.right), op)) { return Ok(ControlFlow::Continue(v.target as usize)) } },
+ Call(v) => return self.exec_call_direct(*v, instr_ptr + 1),
+ CallSelf => return self.exec_call_self(instr_ptr + 1),
+ CallIndirect(idx) => return self.exec_call_indirect::<false>(*idx, instr_ptr + 1),
+ CallRef(ty) => return self.exec_call_ref::<false>(*ty, instr_ptr + 1),
+ ReturnCall(v) => return self.exec_return_call_direct(*v),
+ ReturnCallSelf => return self.exec_return_call_self(),
+ ReturnCallIndirect(idx) => return self.exec_call_indirect::<true>(*idx, instr_ptr + 1),
+ ReturnCallRef(ty) => return self.exec_call_ref::<true>(*ty, instr_ptr + 1),
+ Throw(tag) => return self.exec_throw(*tag, instr_ptr),
+ ThrowRef => return self.exec_throw_ref(instr_ptr),
+ Jump(ip) => return Ok(ControlFlow::Continue(*ip as usize)),
+ JumpIfZero32(ip) => if i32::stack_pop(&mut self.store.value_stack) == 0 { return Ok(ControlFlow::Continue(*ip as usize)) },
+ JumpIfNonZero32(ip) => if i32::stack_pop(&mut self.store.value_stack) != 0 { return Ok(ControlFlow::Continue(*ip as usize)) },
+ JumpIfZero64(ip) => if i64::stack_pop(&mut self.store.value_stack) == 0 { return Ok(ControlFlow::Continue(*ip as usize)) },
+ JumpIfNonZero64(ip) => if i64::stack_pop(&mut self.store.value_stack) != 0 { return Ok(ControlFlow::Continue(*ip as usize)) },
+ JumpIfRefNull(ip) => { let ip = *ip; if self.exec_jump_if_ref::<true>() { return Ok(ControlFlow::Continue(ip as usize)) } },
+ JumpIfRefNonNull(ip) => { let ip = *ip; if self.exec_jump_if_ref::<false>() { return Ok(ControlFlow::Continue(ip as usize)) } },
+ BrOnCast(idx) => if let Some(ip) = self.exec_br_on_cast::<false>(*idx) { return Ok(ControlFlow::Continue(ip)) },
+ BrOnCastFail(idx) => if let Some(ip) = self.exec_br_on_cast::<true>(*idx) { return Ok(ControlFlow::Continue(ip)) },
+ JumpIfLocalZero32(arg) => if self.exec_jump_if_local::<Value32, true>(arg.local) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) },
+ JumpIfLocalNonZero32(arg) => if self.exec_jump_if_local::<Value32, false>(arg.local) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) },
+ JumpIfLocalZero64(arg) => if self.exec_jump_if_local::<Value64, true>(arg.local) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) },
+ JumpIfLocalNonZero64(arg) => if self.exec_jump_if_local::<Value64, false>(arg.local) { return Ok(ControlFlow::Continue(arg.target_ip as usize)) },
+ JumpCmpStackConst32(packed) => if let Some(ip) = self.exec_jump_cmp_stack_const32(*packed) { return Ok(ControlFlow::Continue(ip)) },
+ JumpCmpStackConst64(packed) => if let Some(ip) = self.exec_jump_cmp_stack_const64(*packed) { return Ok(ControlFlow::Continue(ip)) },
+ JumpCmpStackLocal32(packed) => if let Some(ip) = self.exec_jump_cmp_stack_local32(*packed) { return Ok(ControlFlow::Continue(ip)) },
+ JumpCmpStackLocal64(packed) => if let Some(ip) = self.exec_jump_cmp_stack_local64(*packed) { return Ok(ControlFlow::Continue(ip)) },
+ BinOpLocalConstJump32(packed) => if let Some(ip) = self.exec_binop_local_const_jump(*packed) { return Ok(ControlFlow::Continue(ip)) },
+ BinOpLocalConstJumpCmpLocal32(packed) => if let Some(ip) = self.exec_binop_local_const_jump_cmp_local(*packed) { return Ok(ControlFlow::Continue(ip)) },
+ BinOpStackConstTeeLocalJump32(packed) => if let Some(ip) = self.exec_binop_stack_const_tee_local_jump(*packed)? { return Ok(ControlFlow::Continue(ip)) },
+ BinOpGlobalConstJump32(packed) => if let Some(ip) = self.exec_binop_global_const_jump(*packed) { return Ok(ControlFlow::Continue(ip)) },
+ IncLocalJump32(idx) => if let Some(ip) = self.exec_inc_local_jump(*idx) { return Ok(ControlFlow::Continue(ip)) },
+ IncStackTeeLocalJump32(idx) => if let Some(ip) = self.exec_inc_stack_tee_local_jump(*idx)? { return Ok(ControlFlow::Continue(ip)) },
+ IncGlobalJump32(idx) => if let Some(ip) = self.exec_inc_global_jump(*idx) { return Ok(ControlFlow::Continue(ip)) },
+ IncLocalJumpCmpLocal32(packed) => if let Some(ip) = self.exec_inc_local_jump_cmp_local(*packed) { return Ok(ControlFlow::Continue(ip)) },
+ JumpCmpLocalConst32(packed) => if let Some(ip) = self.exec_jump_cmp_local_const32(*packed) { return Ok(ControlFlow::Continue(ip)) },
+ JumpCmpLocalConst64(packed) => if let Some(ip) = self.exec_jump_cmp_local_const64(*packed) { return Ok(ControlFlow::Continue(ip)) },
+ JumpCmpLocalLocal32(packed) => if let Some(ip) = self.exec_jump_cmp_local_local32(*packed) { return Ok(ControlFlow::Continue(ip)) },
+ JumpCmpLocalLocal64(packed) => if let Some(ip) = self.exec_jump_cmp_local_local64(*packed) { return Ok(ControlFlow::Continue(ip)) },
DropKeep32 { base, keep } => self.store.value_stack.stack_32.truncate_keep((self.cf.stack_base().s32 + u32::from(*base)) as usize, *keep as usize),
DropKeep64 { base, keep } => self.store.value_stack.stack_64.truncate_keep((self.cf.stack_base().s64 + u32::from(*base)) as usize, *keep as usize),
DropKeep128 { base, keep } => self.store.value_stack.stack_128.truncate_keep((self.cf.stack_base().s128 + u32::from(*base)) as usize, *keep as usize),
- BranchTable(idx) => { return Ok(ControlFlow::Continue(self.exec_branch_table(*idx))); }
- Return => { return Ok(self.exec_return()); }
- ReturnVoid => { return Ok(self.exec_return_void()); }
- Return32 => { return Ok(self.exec_return_32()); }
- Return64 => { return Ok(self.exec_return_64()); }
- Return128 => { return Ok(self.exec_return_128()); }
+ BranchTable(idx) => return Ok(ControlFlow::Continue(self.exec_branch_table(*idx))),
+ Return => return Ok(self.exec_return()),
+ ReturnVoid => return Ok(self.exec_return_void()),
+ Return32 => return Ok(self.exec_return_32()),
+ Return64 => return Ok(self.exec_return_64()),
+ Return128 => return Ok(self.exec_return_128()),
LocalGet32(local_index) => Value32::local_push(&mut self.store.value_stack, &self.cf, *local_index)?,
LocalGet64(local_index) => Value64::local_push(&mut self.store.value_stack, &self.cf, *local_index)?,
LocalGet128(local_index) => Value128::local_push(&mut self.store.value_stack, &self.cf, *local_index)?,
- LocalSet32(local_index) => exec_op!(local_set_pop Value32, local_index),
- LocalSet64(local_index) => exec_op!(local_set_pop Value64, local_index),
- LocalSet128(local_index) => exec_op!(local_set_pop Value128, local_index),
+ LocalSet32(local_index) => self.exec_local_set_pop::<Value32>(*local_index),
+ LocalSet64(local_index) => self.exec_local_set_pop::<Value64>(*local_index),
+ LocalSet128(local_index) => self.exec_local_set_pop::<Value128>(*local_index),
LocalCopy32(from, to) => Value32::local_copy(&mut self.store.value_stack, &self.cf, *from, *to),
LocalCopy64(from, to) => Value64::local_copy(&mut self.store.value_stack, &self.cf, *from, *to),
LocalCopy128(from, to) => Value128::local_copy(&mut self.store.value_stack, &self.cf, *from, *to),
- AddConst32(c) => exec_op!(unary i32 => i32, |v| v.wrapping_add(*c)),
- AddConst64(idx) => { let c = idx.get(&self.func.data).value; exec_op!(unary i64 => i64, |v| v.wrapping_add(c)); },
- IncLocal32(arg) => i32::local_update(&mut self.store.value_stack, &self.cf, arg.local, |v| v.wrapping_add(arg.value)),
- IncLocal64(packed) => { let v = packed.index.get(&self.func.data).value; i64::local_update(&mut self.store.value_stack, &self.cf, packed.op, |n| n.wrapping_add(v)); },
+ AddConst32(c) => { i32::stack_update(&mut self.store.value_stack, #[inline(always)] |value| value.wrapping_add(*c))?; },
+ AddConst64(idx) => { let constant = idx.resolve(&self.func.data).value(); i64::stack_update(&mut self.store.value_stack, #[inline(always)] |value| value.wrapping_add(constant))?; },
+ IncLocal32(arg) => { i32::local_update(&mut self.store.value_stack, &self.cf, arg.local, |v| v.wrapping_add(arg.value)); },
+ IncLocal64(packed) => { let v = packed.index.resolve(&self.func.data).value(); i64::local_update(&mut self.store.value_stack, &self.cf, packed.op, |n| n.wrapping_add(v)); },
I32Add3 => exec_op!(ternary i32 => i32, |a, b, c| a.wrapping_add(b).wrapping_add(c)),
I64Add3 => exec_op!(ternary i64 => i64, |a, b, c| a.wrapping_add(b).wrapping_add(c)),
- MulAccLocal32(acc) => exec_op!(binop_acc_local i32, acc, |a: i32, b| a.wrapping_mul(b), |a: i32, b| a.wrapping_add(b)),
- MulAccLocal64(acc) => exec_op!(binop_acc_local i64, acc, |a: i64, b| a.wrapping_mul(b), |a: i64, b| a.wrapping_add(b)),
- FMulAccLocal32(acc) => exec_op!(binop_acc_local f32, acc, |a: f32, b| a * b, |a: f32, b| a + b),
- FMulAccLocal64(acc) => exec_op!(binop_acc_local f64, acc, |a: f64, b| a * b, |a: f64, b| a + b),
- BinOpLocalLocal32(op, a, b) => exec_op!(binop_local_local Value32, exec_binop_32, op, a, b),
- BinOpLocalLocal64(op, a, b) => exec_op!(binop_local_local Value64, exec_binop_64, op, a, b),
- BinOpLocalLocal128(op, a, b) => exec_op!(binop_local_local Value128, exec_binop_128, op, a, b),
- CmpLocalLocal32(op, a, b) => exec_op!(cmp_local_local i32, cmp_i32, op, a, b),
- CmpLocalLocal64(op, a, b) => exec_op!(cmp_local_local i64, cmp_i64, op, a, b),
- AddLocalLocalSet32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.left).wrapping_add(i32::local_get(&self.store.value_stack, &self.cf, arg.right)); i32::local_set(&mut self.store.value_stack, &self.cf, arg.dst, value); },
- AddLocalLocalTee32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.left).wrapping_add(i32::local_get(&self.store.value_stack, &self.cf, arg.right)); i32::local_set(&mut self.store.value_stack, &self.cf, arg.dst, value); i32::stack_push(&mut self.store.value_stack, value)?; },
- BinOpLocalLocalSet32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.left), Value32::local_get(&self.store.value_stack, &self.cf, v.right)); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); },
- BinOpLocalLocalSet64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.left), Value64::local_get(&self.store.value_stack, &self.cf, v.right)); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); },
- BinOpLocalLocalSet128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.left), Value128::local_get(&self.store.value_stack, &self.cf, v.right)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); },
- BinOpLocalLocalTee32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.left), Value32::local_get(&self.store.value_stack, &self.cf, v.right)); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value32::stack_push(&mut self.store.value_stack, value)?; },
- BinOpLocalLocalTee64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.left), Value64::local_get(&self.store.value_stack, &self.cf, v.right)); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value64::stack_push(&mut self.store.value_stack, value)?; },
- BinOpLocalLocalTee128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.left), Value128::local_get(&self.store.value_stack, &self.cf, v.right)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value128::stack_push(&mut self.store.value_stack, value)?; },
- AddLocalConst32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.local).wrapping_add(arg.value); i32::stack_push(&mut self.store.value_stack, value)?; },
- SubLocalConst32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.local).wrapping_sub(arg.value); i32::stack_push(&mut self.store.value_stack, value)?; },
- MulLocalConst32(arg) => { let value = i32::local_get(&self.store.value_stack, &self.cf, arg.local).wrapping_mul(arg.value); i32::stack_push(&mut self.store.value_stack, value)?; },
- BinOpLocalConst32(packed) => { let v = packed.index.get(&self.func.data); let lhs = Value32::local_get(&self.store.value_stack, &self.cf, v.local); Value32::stack_push(&mut self.store.value_stack, exec_binop_32(packed.op, lhs, v.value))?; },
- BinOpLocalConst64(packed) => { let v = packed.index.get(&self.func.data); let lhs = Value64::local_get(&self.store.value_stack, &self.cf, v.local); Value64::stack_push(&mut self.store.value_stack, exec_binop_64(packed.op, lhs, v.value))?; },
- BinOpLocalConst128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.local), Value128(v.value.get(&self.func.data).value)); Value128::stack_push(&mut self.store.value_stack, value)?; },
- BinOpGlobalConst32(packed) => { let v = packed.index.get(&self.func.data); Value32::stack_push(&mut self.store.value_stack, exec_binop_32(packed.op, Value32::global_get(&self.store.state.globals, self.module.resolve_global_addr(v.global)), v.value))?; },
- BinOpGlobalConst64(packed) => { let v = packed.index.get(&self.func.data); Value64::stack_push(&mut self.store.value_stack, exec_binop_64(packed.op, Value64::global_get(&self.store.state.globals, self.module.resolve_global_addr(v.global)), v.value))?; },
- BinOpGlobalConst128(packed) => { let v = packed.index.get(&self.func.data); Value128::stack_push(&mut self.store.value_stack, exec_binop_128(packed.op, Value128::global_get(&self.store.state.globals, self.module.resolve_global_addr(v.global)), Value128(v.value.get(&self.func.data).value)))?; },
- BinOpLocalConstSet32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); },
- BinOpLocalConstTee32(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_32(packed.op, Value32::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value32::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value32::stack_push(&mut self.store.value_stack, value)?; },
- BinOpLocalConstSet64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); },
- BinOpLocalConstTee64(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_64(packed.op, Value64::local_get(&self.store.value_stack, &self.cf, v.local), v.value); Value64::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value64::stack_push(&mut self.store.value_stack, value)?; },
- BinOpLocalConstSet128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.local), Value128(v.value.get(&self.func.data).value)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); },
- BinOpLocalConstTee128(packed) => { let v = packed.index.get(&self.func.data); let value = exec_binop_128(packed.op, Value128::local_get(&self.store.value_stack, &self.cf, v.local), Value128(v.value.get(&self.func.data).value)); Value128::local_set(&mut self.store.value_stack, &self.cf, v.dst, value); Value128::stack_push(&mut self.store.value_stack, value)?; },
- BinOpStackGlobal32(op, global_index) => exec_op!(binop_stack_global Value32, exec_binop_32, op, global_index),
- BinOpStackGlobal64(op, global_index) => exec_op!(binop_stack_global Value64, exec_binop_64, op, global_index),
- BinOpStackLocal32(op, local) => exec_op!(binop_stack_local Value32, exec_binop_32, op, local),
- BinOpStackLocalSet32(op, local, dst) => exec_op!(binop_stack_local_set Value32, exec_binop_32, op, local, dst),
- BinOpStackLocalTee32(op, local, dst) => exec_op!(binop_stack_local_tee Value32, exec_binop_32, op, local, dst),
- BinOpStackLocal128(op, local) => exec_op!(binop_stack_local Value128, exec_binop_128, op, local),
+ MulAccLocal32(acc) => self.exec_mul_acc_local::<i32>(*acc, i32::wrapping_mul, i32::wrapping_add),
+ MulAccLocal64(acc) => self.exec_mul_acc_local::<i64>(*acc, i64::wrapping_mul, i64::wrapping_add),
+ FMulAccLocal32(acc) => self.exec_mul_acc_local::<f32>(*acc, |a, b| a * b, |a, b| a + b),
+ FMulAccLocal64(acc) => self.exec_mul_acc_local::<f64>(*acc, |a, b| a * b, |a, b| a + b),
+ BinOpLocalLocal32(op, a, b) => self.exec_binop_local_local::<Value32, true>(*a, *b, None, *op)?,
+ BinOpLocalLocal64(op, a, b) => self.exec_binop_local_local::<Value64, true>(*a, *b, None, *op)?,
+ BinOpLocalLocal128(op, a, b) => self.exec_binop_local_local::<Value128, true>(*a, *b, None, *op)?,
+ CmpLocalLocal32(op, a, b) => self.exec_cmp_local_local::<i32>(*a, *b, *op)?,
+ CmpLocalLocal64(op, a, b) => self.exec_cmp_local_local::<i64>(*a, *b, *op)?,
+ AddLocalLocalSet32(arg) => self.exec_binop_local_local::<Value32, false>(arg.left, arg.right, Some(arg.dst), BinOp::IAdd)?,
+ AddLocalLocalTee32(arg) => self.exec_binop_local_local::<Value32, true>(arg.left, arg.right, Some(arg.dst), BinOp::IAdd)?,
+ BinOpLocalLocalSet32(packed) => self.exec_binop_local_local_indexed::<Value32, false>(packed.index, packed.op)?,
+ BinOpLocalLocalSet64(packed) => self.exec_binop_local_local_indexed::<Value64, false>(packed.index, packed.op)?,
+ BinOpLocalLocalSet128(packed) => self.exec_binop_local_local_indexed::<Value128, false>(packed.index, packed.op)?,
+ BinOpLocalLocalTee32(packed) => self.exec_binop_local_local_indexed::<Value32, true>(packed.index, packed.op)?,
+ BinOpLocalLocalTee64(packed) => self.exec_binop_local_local_indexed::<Value64, true>(packed.index, packed.op)?,
+ BinOpLocalLocalTee128(packed) => self.exec_binop_local_local_indexed::<Value128, true>(packed.index, packed.op)?,
+ AddLocalConst32(arg) => self.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::IAdd)?,
+ SubLocalConst32(arg) => self.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::ISub)?,
+ MulLocalConst32(arg) => self.exec_binop_local_const::<Value32, true>(arg.local, arg.value as u32, None, BinOp::IMul)?,
+ BinOpLocalConst32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::<Value32, true>(v.a(), v.b(), None, packed.op)?; },
+ BinOpLocalConst64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::<Value64, true>(v.a(), v.b(), None, packed.op)?; },
+ BinOpLocalConst128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.b().resolve(&self.func.data).value()); self.exec_binop_local_const::<Value128, true>(v.a(), rhs, None, packed.op)?; },
+ BinOpGlobalConst32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_global_const::<Value32>(v.a(), v.b(), packed.op)?; },
+ BinOpGlobalConst64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_global_const::<Value64>(v.a(), v.b(), packed.op)?; },
+ BinOpGlobalConst128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.b().resolve(&self.func.data).value()); self.exec_binop_global_const::<Value128>(v.a(), rhs, packed.op)?; },
+ BinOpLocalConstSet32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::<Value32, false>(v.a(), v.c(), Some(v.b()), packed.op)?; },
+ BinOpLocalConstTee32(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::<Value32, true>(v.a(), v.c(), Some(v.b()), packed.op)?; },
+ BinOpLocalConstSet64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::<Value64, false>(v.a(), v.c(), Some(v.b()), packed.op)?; },
+ BinOpLocalConstTee64(packed) => { let v = packed.index.resolve(&self.func.data); self.exec_binop_local_const::<Value64, true>(v.a(), v.c(), Some(v.b()), packed.op)?; },
+ BinOpLocalConstSet128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.c().resolve(&self.func.data).value()); self.exec_binop_local_const::<Value128, false>(v.a(), rhs, Some(v.b()), packed.op)?; },
+ BinOpLocalConstTee128(packed) => { let v = packed.index.resolve(&self.func.data); let rhs = Value128(v.c().resolve(&self.func.data).value()); self.exec_binop_local_const::<Value128, true>(v.a(), rhs, Some(v.b()), packed.op)?; },
+ BinOpStackGlobal32(op, global_index) => self.exec_binop_stack_global::<Value32>(*global_index, *op)?,
+ BinOpStackGlobal64(op, global_index) => self.exec_binop_stack_global::<Value64>(*global_index, *op)?,
+ BinOpStackLocal32(op, local) => self.exec_binop_stack_local::<Value32, true>(*local, None, *op)?,
+ BinOpStackLocalSet32(op, local, dst) => self.exec_binop_stack_local::<Value32, false>(*local, Some(*dst), *op)?,
+ BinOpStackLocalTee32(op, local, dst) => self.exec_binop_stack_local::<Value32, true>(*local, Some(*dst), *op)?,
+ BinOpStackLocal128(op, local) => self.exec_binop_stack_local::<Value128, true>(*local, None, *op)?,
SetLocalConst32(arg) => i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, arg.value),
- SetLocalConst64(packed) => { let v = packed.index.get(&self.func.data).value; i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, v); },
- SetLocalConst128(packed) => Value128::local_set(&mut self.store.value_stack, &self.cf, packed.op, Value128(packed.index.get(&self.func.data).value)),
- IncMemoryLocal32(arg) => self.exec_inc_memory_local::<i32, 4>(arg.memory_arg_idx.get(&self.func.data), arg.local1, |v| v.wrapping_add(1))?,
- IncMemoryLocal64(arg) => self.exec_inc_memory_local::<i64, 8>(arg.memory_arg_idx.get(&self.func.data), arg.local1, |v| v.wrapping_add(1))?,
- StoreLocalLocal32(arg) => self.exec_store_local_local::<u32, 4>(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2)?,
- StoreLocalLocal64(arg) => self.exec_store_local_local::<i64, 8>(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2)?,
- StoreLocalLocal128(arg) => self.exec_store_local_local::<Value128, 16>(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2)?,
- LoadLocal32(arg) => self.exec_load_local::<i32, 4, _, false, false>(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, |v| v)?,
- LoadLocal64(arg) => self.exec_load_local::<i64, 8, _, false, false>(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, |v| v)?,
- LoadLocal8S32(arg) => self.exec_load_local::<i8, 1, _, false, false>(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?,
- LoadLocal8U32(arg) => self.exec_load_local::<u8, 1, _, false, false>(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?,
- LoadLocal16S32(arg) => self.exec_load_local::<i16, 2, _, false, false>(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?,
- LoadLocal16U32(arg) => self.exec_load_local::<u16, 2, _, false, false>(arg.memory_arg_idx.get(&self.func.data), arg.local1, 0, i32::from)?,
- LoadLocalTee32(arg) => self.exec_load_local::<i32, 4, _, true, true>(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?,
- LoadLocalSet32(arg) => self.exec_load_local::<i32, 4, _, true, false>(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?,
- LoadLocalTee8S32(arg) => self.exec_load_local::<i8, 1, _, true, true>(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?,
- LoadLocalTee8U32(arg) => self.exec_load_local::<u8, 1, _, true, true>(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?,
- LoadLocalTee16S32(arg) => self.exec_load_local::<i16, 2, _, true, true>(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?,
- LoadLocalTee16U32(arg) => self.exec_load_local::<u16, 2, _, true, true>(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?,
- LoadLocalSet8S32(arg) => self.exec_load_local::<i8, 1, _, true, false>(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?,
- LoadLocalSet8U32(arg) => self.exec_load_local::<u8, 1, _, true, false>(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?,
- LoadLocalSet16S32(arg) => self.exec_load_local::<i16, 2, _, true, false>(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?,
- LoadLocalSet16U32(arg) => self.exec_load_local::<u16, 2, _, true, false>(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, i32::from)?,
- LoadLocalTee128(arg) => self.exec_load_local::<Value128, 16, _, true, true>(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?,
- LoadLocalSet128(arg) => self.exec_load_local::<Value128, 16, _, true, false>(arg.memory_arg_idx.get(&self.func.data), arg.local1, arg.local2, |v| v)?,
- AndConstTee32(arg) => { exec_op!(unary i32 => i32, |v| v & arg.value); let value = i32::stack_peek(&self.store.value_stack); i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, value); },
- SubConstTee32(arg) => { exec_op!(unary i32 => i32, |v| v.wrapping_sub(arg.value)); let value = i32::stack_peek(&self.store.value_stack); i32::local_set(&mut self.store.value_stack, &self.cf, arg.local, value); },
- AndConstTee64(packed) => { let v = packed.index.get(&self.func.data).value; exec_op!(unary i64 => i64, |n| n & v); let value = i64::stack_peek(&self.store.value_stack); i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, value); },
- SubConstTee64(packed) => { let v = packed.index.get(&self.func.data).value; exec_op!(unary i64 => i64, |n| n.wrapping_sub(v)); let value = i64::stack_peek(&self.store.value_stack); i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, value); },
- LocalTee32(local_index) => exec_op!(local_tee Value32, local_index),
- LocalTee64(local_index) => exec_op!(local_tee Value64, local_index),
- LocalTee128(local_index) => exec_op!(local_tee Value128, local_index),
- GlobalGet32(global_index) => exec_op!(global_get Value32, global_index),
- GlobalGet64(global_index) => exec_op!(global_get Value64, global_index),
- GlobalGet128(global_index) => exec_op!(global_get Value128, global_index),
- GlobalSet32(global_index) => exec_op!(global_set Value32, global_index),
- GlobalSet64(global_index) => exec_op!(global_set Value64, global_index),
- GlobalSet128(global_index) => exec_op!(global_set Value128, global_index),
- GlobalTee32(global_index) => exec_op!(global_tee Value32, global_index),
- GlobalTee64(global_index) => exec_op!(global_tee Value64, global_index),
- GlobalTee128(global_index) => exec_op!(global_tee Value128, global_index),
+ SetLocalConst64(packed) => { let v = packed.index.resolve(&self.func.data).value(); i64::local_set(&mut self.store.value_stack, &self.cf, packed.op, v); },
+ SetLocalConst128(packed) => Value128::local_set(&mut self.store.value_stack, &self.cf, packed.op, Value128(packed.index.resolve(&self.func.data).value())),
+ IncMemoryLocal32(arg) => self.exec_inc_memory_local::<i32, 4>(arg.memory_arg_idx, arg.local1, #[inline(always)] |v| v.wrapping_add(1))?,
+ IncMemoryLocal64(arg) => self.exec_inc_memory_local::<i64, 8>(arg.memory_arg_idx, arg.local1, #[inline(always)] |v| v.wrapping_add(1))?,
+ StoreLocalLocal32(arg) => self.exec_store_local_local::<u32, 4>(arg.memory_arg_idx, arg.local1, arg.local2)?,
+ StoreLocalLocal64(arg) => self.exec_store_local_local::<i64, 8>(arg.memory_arg_idx, arg.local1, arg.local2)?,
+ StoreLocalLocal128(arg) => self.exec_store_local_local::<Value128, 16>(arg.memory_arg_idx, arg.local1, arg.local2)?,
+ LoadLocal32(arg) => self.exec_load_local::<i32, 4, _, false, false>(arg.memory_arg_idx, arg.local1, 0, #[inline(always)] |v| v)?,
+ LoadLocal64(arg) => self.exec_load_local::<i64, 8, _, false, false>(arg.memory_arg_idx, arg.local1, 0, #[inline(always)] |v| v)?,
+ LoadLocal8S32(arg) => self.exec_load_local::<i8, 1, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?,
+ LoadLocal8U32(arg) => self.exec_load_local::<u8, 1, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?,
+ LoadLocal16S32(arg) => self.exec_load_local::<i16, 2, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?,
+ LoadLocal16U32(arg) => self.exec_load_local::<u16, 2, _, false, false>(arg.memory_arg_idx, arg.local1, 0, i32::from)?,
+ LoadLocalTee32(arg) => self.exec_load_local::<i32, 4, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?,
+ LoadLocalSet32(arg) => self.exec_load_local::<i32, 4, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?,
+ LoadLocalTee8S32(arg) => self.exec_load_local::<i8, 1, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?,
+ LoadLocalTee8U32(arg) => self.exec_load_local::<u8, 1, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?,
+ LoadLocalTee16S32(arg) => self.exec_load_local::<i16, 2, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?,
+ LoadLocalTee16U32(arg) => self.exec_load_local::<u16, 2, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?,
+ LoadLocalSet8S32(arg) => self.exec_load_local::<i8, 1, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?,
+ LoadLocalSet8U32(arg) => self.exec_load_local::<u8, 1, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?,
+ LoadLocalSet16S32(arg) => self.exec_load_local::<i16, 2, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?,
+ LoadLocalSet16U32(arg) => self.exec_load_local::<u16, 2, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, i32::from)?,
+ LoadLocalTee128(arg) => self.exec_load_local::<Value128, 16, _, true, true>(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?,
+ LoadLocalSet128(arg) => self.exec_load_local::<Value128, 16, _, true, false>(arg.memory_arg_idx, arg.local1, arg.local2, #[inline(always)] |v| v)?,
+ AndConstTee32(arg) => self.exec_binop_const_tee::<Value32>(arg.value as u32, arg.local, BinOp::IAnd)?,
+ SubConstTee32(arg) => self.exec_binop_const_tee::<Value32>(arg.value as u32, arg.local, BinOp::ISub)?,
+ AndConstTee64(packed) => self.exec_binop_const_tee::<Value64>(packed.index.resolve(&self.func.data).value() as u64, packed.op, BinOp::IAnd)?,
+ SubConstTee64(packed) => self.exec_binop_const_tee::<Value64>(packed.index.resolve(&self.func.data).value() as u64, packed.op, BinOp::ISub)?,
+ LocalTee32(local_index) => self.exec_local_tee::<Value32>(*local_index),
+ LocalTee64(local_index) => self.exec_local_tee::<Value64>(*local_index),
+ LocalTee128(local_index) => self.exec_local_tee::<Value128>(*local_index),
+ GlobalGet32(global_index) => self.exec_global_get::<Value32>(*global_index)?,
+ GlobalGet64(global_index) => self.exec_global_get::<Value64>(*global_index)?,
+ GlobalGet128(global_index) => self.exec_global_get::<Value128>(*global_index)?,
+ GlobalSet32(global_index) => self.exec_global_set::<Value32>(*global_index),
+ GlobalSet64(global_index) => self.exec_global_set::<Value64>(*global_index),
+ GlobalSet128(global_index) => self.exec_global_set::<Value128>(*global_index),
+ GlobalTee32(global_index) => self.exec_global_tee::<Value32>(*global_index),
+ GlobalTee64(global_index) => self.exec_global_tee::<Value64>(*global_index),
+ GlobalTee128(global_index) => self.exec_global_tee::<Value128>(*global_index),
Const32(val) => i32::stack_push(&mut self.store.value_stack, *val)?,
Const64Imm(val) => i64::stack_push(&mut self.store.value_stack, i64::from(*val))?,
- Const64(idx) => i64::stack_push(&mut self.store.value_stack, idx.get(&self.func.data).value)?,
+ Const64(idx) => i64::stack_push(&mut self.store.value_stack, idx.resolve(&self.func.data).value())?,
Const128Imm(val) => Value128::stack_push(&mut self.store.value_stack, Value128(u128::from(*val).to_le_bytes()))?,
I64Eqz => exec_op!(unary i64 => i32, |v| i32::from(v == 0)),
I32Eqz => exec_op!(unary i32 => i32, |v| i32::from(v == 0)),
@@ -462,26 +340,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
I64Rotl => exec_op!(binary i64 => i64, |a, b| a.rotate_left(b as u32)),
I32Rotr => exec_op!(binary i32 => i32, |a, b| a.rotate_right(b as u32)),
I64Rotr => exec_op!(binary i64 => i64, |a, b| a.rotate_right(b as u32)),
- I64Add128 => exec_op!(quaternary_two_results i64 => i64, |a_lo, a_hi, b_lo, b_hi| {
- let lo = a_lo.wrapping_add(b_lo);
- let carry = u64::from((lo as u64) < (a_lo as u64));
- let hi = a_hi.wrapping_add(b_hi).wrapping_add(carry as i64);
- (lo, hi)
- }),
- I64Sub128 => exec_op!(quaternary_two_results i64 => i64, |a_lo, a_hi, b_lo, b_hi| {
- let lo = a_lo.wrapping_sub(b_lo);
- let borrow = u64::from((a_lo as u64) < (b_lo as u64));
- let hi = a_hi.wrapping_sub(b_hi).wrapping_sub(borrow as i64);
- (lo, hi)
- }),
- I64MulWideS => exec_op!(binary_two_results i64 => i64, |a, b| {
- let product = (a as i128).wrapping_mul(b as i128);
- (product as i64, (product >> 64) as i64)
- }),
- I64MulWideU => exec_op!(binary_two_results i64 => i64, |a, b| {
- let product = (a as u64 as u128).wrapping_mul(b as u64 as u128);
- (product as u64 as i64, (product >> 64) as u64 as i64)
- }),
+ I64Add128 => self.exec_i64_add128()?,
+ I64Sub128 => self.exec_i64_sub128()?,
+ I64MulWideS => self.exec_i64_mul_wide_s()?,
+ I64MulWideU => self.exec_i64_mul_wide_u()?,
I32Clz => exec_op!(unary i32 => i32, |v| v.leading_zeros() as i32),
I64Clz => exec_op!(unary i64 => i64, |v| i64::from(v.leading_zeros())),
I32Ctz => exec_op!(unary i32 => i32, |v| v.trailing_zeros() as i32),
@@ -500,6 +362,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
RefEq => exec_op!(binary ValueRef => i32, |a, b| i32::from(a == b)),
RefTest(ty) => self.exec_ref_test(*ty)?,
RefCast(ty) => self.exec_ref_cast(*ty)?,
+
// GC objects
StructNew(ty) => self.exec_struct_new(*ty, false)?,
StructNewDefault(ty) => self.exec_struct_new(*ty, true)?,
@@ -542,31 +405,31 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
TableCopy(idx) => self.exec_table_copy(*idx)?,
// Core memory load/store operations
- I32Store(idx) => self.exec_mem_store::<i32, i32, 4>(*idx, |v| v)?,
- I64Store(idx) => self.exec_mem_store::<i64, i64, 8>(*idx, |v| v)?,
- F32Store(idx) => self.exec_mem_store::<f32, f32, 4>(*idx, |v| v)?,
- F64Store(idx) => self.exec_mem_store::<f64, f64, 8>(*idx, |v| v)?,
+ I32Store(idx) => self.exec_mem_store::<i32, i32, 4>(idx.resolve(&self.func.data), #[inline(always)] |v| v)?,
+ I64Store(idx) => self.exec_mem_store::<i64, i64, 8>(idx.resolve(&self.func.data), #[inline(always)] |v| v)?,
+ F32Store(idx) => self.exec_mem_store::<f32, f32, 4>(idx.resolve(&self.func.data), #[inline(always)] |v| v)?,
+ F64Store(idx) => self.exec_mem_store::<f64, f64, 8>(idx.resolve(&self.func.data), #[inline(always)] |v| v)?,
FMaStoreF32(m) => self.exec_fma_store::<f32, 4>(*m)?,
FMaStoreF64(m) => self.exec_fma_store::<f64, 8>(*m)?,
- I32Store8(idx) => self.exec_mem_store::<i32, i8, 1>(*idx, |v| v as i8)?,
- I32Store16(idx) => self.exec_mem_store::<i32, i16, 2>(*idx, |v| v as i16)?,
- I64Store8(idx) => self.exec_mem_store::<i64, i8, 1>(*idx, |v| v as i8)?,
- I64Store16(idx) => self.exec_mem_store::<i64, i16, 2>(*idx, |v| v as i16)?,
- I64Store32(idx) => self.exec_mem_store::<i64, i32, 4>(*idx, |v| v as i32)?,
- I32Load(idx) => self.exec_mem_load::<i32, 4, _>(*idx, |v| v)?,
- I64Load(idx) => self.exec_mem_load::<i64, 8, _>(*idx, |v| v)?,
- F32Load(idx) => self.exec_mem_load::<f32, 4, _>(*idx, |v| v)?,
- F64Load(idx) => self.exec_mem_load::<f64, 8, _>(*idx, |v| v)?,
- I32Load8S(idx) => self.exec_mem_load::<i8, 1, _>(*idx, i32::from)?,
- I32Load8U(idx) => self.exec_mem_load::<u8, 1, _>(*idx, i32::from)?,
- I32Load16S(idx) => self.exec_mem_load::<i16, 2, _>(*idx, i32::from)?,
- I32Load16U(idx) => self.exec_mem_load::<u16, 2, _>(*idx, i32::from)?,
- I64Load8S(idx) => self.exec_mem_load::<i8, 1, _>(*idx, i64::from)?,
- I64Load8U(idx) => self.exec_mem_load::<u8, 1, _>(*idx, i64::from)?,
- I64Load16S(idx) => self.exec_mem_load::<i16, 2, _>(*idx, i64::from)?,
- I64Load16U(idx) => self.exec_mem_load::<u16, 2, _>(*idx, i64::from)?,
- I64Load32S(idx) => self.exec_mem_load::<i32, 4, _>(*idx, i64::from)?,
- I64Load32U(idx) => self.exec_mem_load::<u32, 4, _>(*idx, i64::from)?,
+ I32Store8(idx) => self.exec_mem_store::<i32, i8, 1>(idx.resolve(&self.func.data), #[inline(always)] |v| v as i8)?,
+ I32Store16(idx) => self.exec_mem_store::<i32, i16, 2>(idx.resolve(&self.func.data), #[inline(always)] |v| v as i16)?,
+ I64Store8(idx) => self.exec_mem_store::<i64, i8, 1>(idx.resolve(&self.func.data), #[inline(always)] |v| v as i8)?,
+ I64Store16(idx) => self.exec_mem_store::<i64, i16, 2>(idx.resolve(&self.func.data), #[inline(always)] |v| v as i16)?,
+ I64Store32(idx) => self.exec_mem_store::<i64, i32, 4>(idx.resolve(&self.func.data), #[inline(always)] |v| v as i32)?,
+ I32Load(idx) => self.exec_mem_load::<i32, 4, _>(idx.resolve(&self.func.data), #[inline(always)] |v| v)?,
+ I64Load(idx) => self.exec_mem_load::<i64, 8, _>(idx.resolve(&self.func.data), #[inline(always)] |v| v)?,
+ F32Load(idx) => self.exec_mem_load::<f32, 4, _>(idx.resolve(&self.func.data), #[inline(always)] |v| v)?,
+ F64Load(idx) => self.exec_mem_load::<f64, 8, _>(idx.resolve(&self.func.data), #[inline(always)] |v| v)?,
+ I32Load8S(idx) => self.exec_mem_load::<i8, 1, _>(idx.resolve(&self.func.data), i32::from)?,
+ I32Load8U(idx) => self.exec_mem_load::<u8, 1, _>(idx.resolve(&self.func.data), i32::from)?,
+ I32Load16S(idx) => self.exec_mem_load::<i16, 2, _>(idx.resolve(&self.func.data), i32::from)?,
+ I32Load16U(idx) => self.exec_mem_load::<u16, 2, _>(idx.resolve(&self.func.data), i32::from)?,
+ I64Load8S(idx) => self.exec_mem_load::<i8, 1, _>(idx.resolve(&self.func.data), i64::from)?,
+ I64Load8U(idx) => self.exec_mem_load::<u8, 1, _>(idx.resolve(&self.func.data), i64::from)?,
+ I64Load16S(idx) => self.exec_mem_load::<i16, 2, _>(idx.resolve(&self.func.data), i64::from)?,
+ I64Load16U(idx) => self.exec_mem_load::<u16, 2, _>(idx.resolve(&self.func.data), i64::from)?,
+ I64Load32S(idx) => self.exec_mem_load::<i32, 4, _>(idx.resolve(&self.func.data), i64::from)?,
+ I64Load32U(idx) => self.exec_mem_load::<u32, 4, _>(idx.resolve(&self.func.data), i64::from)?,
// Numeric conversion operations
F32ConvertI32S => exec_op!(unary i32 => f32, |v| v as f32),
@@ -638,43 +501,43 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
V128AnyTrue => exec_op!(unary Value128 => i32, |v| v.v128_any_true() as i32),
I8x16Swizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_swizzle(s)),
I8x16RelaxedSwizzle => exec_op!(binary Value128 => Value128, |a, s| a.i8x16_relaxed_swizzle(s)),
- V128Load(idx) => self.exec_mem_load::<Value128, 16, _>(*idx, |v| v)?,
- V128Load8x8S(idx) => self.exec_mem_load::<u64, 8, Value128>(*idx, |v| Value128::v128_load8x8_s(v.to_le_bytes()))?,
- V128Load8x8U(idx) => self.exec_mem_load::<u64, 8, Value128>(*idx, |v| Value128::v128_load8x8_u(v.to_le_bytes()))?,
- V128Load16x4S(idx) => self.exec_mem_load::<u64, 8, Value128>(*idx, |v| Value128::v128_load16x4_s(v.to_le_bytes()))?,
- V128Load16x4U(idx) => self.exec_mem_load::<u64, 8, Value128>(*idx, |v| Value128::v128_load16x4_u(v.to_le_bytes()))?,
- V128Load32x2S(idx) => self.exec_mem_load::<u64, 8, Value128>(*idx, |v| Value128::v128_load32x2_s(v.to_le_bytes()))?,
- V128Load32x2U(idx) => self.exec_mem_load::<u64, 8, Value128>(*idx, |v| Value128::v128_load32x2_u(v.to_le_bytes()))?,
- V128Load8Splat(idx) => self.exec_mem_load::<i8, 1, Value128>(*idx, Value128::splat_i8)?,
- V128Load16Splat(idx) => self.exec_mem_load::<i16, 2, Value128>(*idx, Value128::splat_i16)?,
- V128Load32Splat(idx) => self.exec_mem_load::<i32, 4, Value128>(*idx, Value128::splat_i32)?,
- V128Load64Splat(idx) => self.exec_mem_load::<i64, 8, Value128>(*idx, Value128::splat_i64)?,
- V128Store(idx) => self.exec_mem_store::<Value128, Value128, 16>(*idx, |v| v)?,
+ V128Load(idx) => self.exec_mem_load::<Value128, 16, _>(idx.resolve(&self.func.data), |v| v)?,
+ V128Load8x8S(idx) => self.exec_mem_load::<u64, 8, Value128>(idx.resolve(&self.func.data), |v| Value128::v128_load8x8_s(v.to_le_bytes()))?,
+ V128Load8x8U(idx) => self.exec_mem_load::<u64, 8, Value128>(idx.resolve(&self.func.data), |v| Value128::v128_load8x8_u(v.to_le_bytes()))?,
+ V128Load16x4S(idx) => self.exec_mem_load::<u64, 8, Value128>(idx.resolve(&self.func.data), |v| Value128::v128_load16x4_s(v.to_le_bytes()))?,
+ V128Load16x4U(idx) => self.exec_mem_load::<u64, 8, Value128>(idx.resolve(&self.func.data), |v| Value128::v128_load16x4_u(v.to_le_bytes()))?,
+ V128Load32x2S(idx) => self.exec_mem_load::<u64, 8, Value128>(idx.resolve(&self.func.data), |v| Value128::v128_load32x2_s(v.to_le_bytes()))?,
+ V128Load32x2U(idx) => self.exec_mem_load::<u64, 8, Value128>(idx.resolve(&self.func.data), |v| Value128::v128_load32x2_u(v.to_le_bytes()))?,
+ V128Load8Splat(idx) => self.exec_mem_load::<i8, 1, Value128>(idx.resolve(&self.func.data), Value128::splat_i8)?,
+ V128Load16Splat(idx) => self.exec_mem_load::<i16, 2, Value128>(idx.resolve(&self.func.data), Value128::splat_i16)?,
+ V128Load32Splat(idx) => self.exec_mem_load::<i32, 4, Value128>(idx.resolve(&self.func.data), Value128::splat_i32)?,
+ V128Load64Splat(idx) => self.exec_mem_load::<i64, 8, Value128>(idx.resolve(&self.func.data), Value128::splat_i64)?,
+ V128Store(idx) => self.exec_mem_store::<Value128, Value128, 16>(idx.resolve(&self.func.data), |v| v)?,
V128Store8Lane(arg) => self.exec_mem_store_lane::<i8, 1>(*arg)?,
V128Store16Lane(arg) => self.exec_mem_store_lane::<i16, 2>(*arg)?,
V128Store32Lane(arg) => self.exec_mem_store_lane::<i32, 4>(*arg)?,
V128Store64Lane(arg) => self.exec_mem_store_lane::<i64, 8>(*arg)?,
- V128Load32Zero(idx) => self.exec_mem_load::<i32, 4, Value128>(*idx, |v| Value128::from_i32x4([v, 0, 0, 0]))?,
- V128Load64Zero(idx) => self.exec_mem_load::<i64, 8, Value128>(*idx, |v| Value128::from_i64x2([v, 0]))?,
- Const128(arg) => Value128::stack_push(&mut self.store.value_stack, Value128(arg.get(&self.func.data).value))?,
- I8x16ExtractLaneS(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i8(*lane) as i32),
- I8x16ExtractLaneU(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_u8(*lane) as i32),
- I16x8ExtractLaneS(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i16(*lane) as i32),
- I16x8ExtractLaneU(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_u16(*lane) as i32),
- I32x4ExtractLane(lane) => exec_op!(unary Value128 => i32, |v| v.extract_lane_i32(*lane)),
- I64x2ExtractLane(lane) => exec_op!(unary Value128 => i64, |v| v.extract_lane_i64(*lane)),
- F32x4ExtractLane(lane) => exec_op!(unary Value128 => f32, |v| v.extract_lane_f32(*lane)),
- F64x2ExtractLane(lane) => exec_op!(unary Value128 => f64, |v| v.extract_lane_f64(*lane)),
+ V128Load32Zero(idx) => self.exec_mem_load::<i32, 4, Value128>(idx.resolve(&self.func.data), |v| Value128::from_i32x4([v, 0, 0, 0]))?,
+ V128Load64Zero(idx) => self.exec_mem_load::<i64, 8, Value128>(idx.resolve(&self.func.data), |v| Value128::from_i64x2([v, 0]))?,
+ Const128(arg) => Value128::stack_push(&mut self.store.value_stack, Value128(arg.resolve(&self.func.data).value()))?,
+ I8x16ExtractLaneS(lane) => self.exec_simd_extract_lane::<i32>(*lane, |v, lane| v.extract_lane_i8(lane) as i32)?,
+ I8x16ExtractLaneU(lane) => self.exec_simd_extract_lane::<i32>(*lane, |v, lane| v.extract_lane_u8(lane) as i32)?,
+ I16x8ExtractLaneS(lane) => self.exec_simd_extract_lane::<i32>(*lane, |v, lane| v.extract_lane_i16(lane) as i32)?,
+ I16x8ExtractLaneU(lane) => self.exec_simd_extract_lane::<i32>(*lane, |v, lane| v.extract_lane_u16(lane) as i32)?,
+ I32x4ExtractLane(lane) => self.exec_simd_extract_lane::<i32>(*lane, Value128::extract_lane_i32)?,
+ I64x2ExtractLane(lane) => self.exec_simd_extract_lane::<i64>(*lane, Value128::extract_lane_i64)?,
+ F32x4ExtractLane(lane) => self.exec_simd_extract_lane::<f32>(*lane, Value128::extract_lane_f32)?,
+ F64x2ExtractLane(lane) => self.exec_simd_extract_lane::<f64>(*lane, Value128::extract_lane_f64)?,
V128Load8Lane(arg) => self.exec_mem_load_lane::<i8, 1>(*arg)?,
V128Load16Lane(arg) => self.exec_mem_load_lane::<i16, 2>(*arg)?,
V128Load32Lane(arg) => self.exec_mem_load_lane::<i32, 4>(*arg)?,
V128Load64Lane(arg) => self.exec_mem_load_lane::<i64, 8>(*arg)?,
- I8x16ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i8x16_replace_lane(*lane, value as i8)),
- I16x8ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i16x8_replace_lane(*lane, value as i16)),
- I32x4ReplaceLane(lane) => exec_op!(binary_mixed i32, Value128 => Value128, |value, vec| vec.i32x4_replace_lane(*lane, value)),
- I64x2ReplaceLane(lane) => exec_op!(binary_mixed i64, Value128 => Value128, |value, vec| vec.i64x2_replace_lane(*lane, value)),
- F32x4ReplaceLane(lane) => exec_op!(binary_mixed f32, Value128 => Value128, |value, vec| vec.f32x4_replace_lane(*lane, value)),
- F64x2ReplaceLane(lane) => exec_op!(binary_mixed f64, Value128 => Value128, |value, vec| vec.f64x2_replace_lane(*lane, value)),
+ I8x16ReplaceLane(lane) => self.exec_simd_replace_lane::<i32>(*lane, |value, vector, lane| vector.i8x16_replace_lane(lane, value as i8))?,
+ I16x8ReplaceLane(lane) => self.exec_simd_replace_lane::<i32>(*lane, |value, vector, lane| vector.i16x8_replace_lane(lane, value as i16))?,
+ I32x4ReplaceLane(lane) => self.exec_simd_replace_lane::<i32>(*lane, |value, vector, lane| vector.i32x4_replace_lane(lane, value))?,
+ I64x2ReplaceLane(lane) => self.exec_simd_replace_lane::<i64>(*lane, |value, vector, lane| vector.i64x2_replace_lane(lane, value))?,
+ F32x4ReplaceLane(lane) => self.exec_simd_replace_lane::<f32>(*lane, |value, vector, lane| vector.f32x4_replace_lane(lane, value))?,
+ F64x2ReplaceLane(lane) => self.exec_simd_replace_lane::<f64>(*lane, |value, vector, lane| vector.f64x2_replace_lane(lane, value))?,
I8x16Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i8(v as i8)),
I16x8Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i16(v as i16)),
I32x4Splat => exec_op!(unary i32 => Value128, |v| Value128::splat_i32(v)),
@@ -745,18 +608,18 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
I16x8Bitmask => exec_op!(unary Value128 => i32, |v| v.i16x8_bitmask() as i32),
I32x4Bitmask => exec_op!(unary Value128 => i32, |v| v.i32x4_bitmask() as i32),
I64x2Bitmask => exec_op!(unary Value128 => i32, |v| v.i64x2_bitmask() as i32),
- I8x16Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i8x16_shl(a as u32)),
- I16x8Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i16x8_shl(a as u32)),
- I32x4Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i32x4_shl(a as u32)),
- I64x2Shl => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i64x2_shl(a as u32)),
- I8x16ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i8x16_shr_s(a as u32)),
- I16x8ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i16x8_shr_s(a as u32)),
- I32x4ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i32x4_shr_s(a as u32)),
- I64x2ShrS => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i64x2_shr_s(a as u32)),
- I8x16ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i8x16_shr_u(a as u32)),
- I16x8ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i16x8_shr_u(a as u32)),
- I32x4ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i32x4_shr_u(a as u32)),
- I64x2ShrU => exec_op!(binary_mixed i32, Value128 => Value128, |a, b| b.i64x2_shr_u(a as u32)),
+ I8x16Shl => exec_op!(binary i32, Value128 => Value128, |a, b| b.i8x16_shl(a as u32)),
+ I16x8Shl => exec_op!(binary i32, Value128 => Value128, |a, b| b.i16x8_shl(a as u32)),
+ I32x4Shl => exec_op!(binary i32, Value128 => Value128, |a, b| b.i32x4_shl(a as u32)),
+ I64x2Shl => exec_op!(binary i32, Value128 => Value128, |a, b| b.i64x2_shl(a as u32)),
+ I8x16ShrS => exec_op!(binary i32, Value128 => Value128, |a, b| b.i8x16_shr_s(a as u32)),
+ I16x8ShrS => exec_op!(binary i32, Value128 => Value128, |a, b| b.i16x8_shr_s(a as u32)),
+ I32x4ShrS => exec_op!(binary i32, Value128 => Value128, |a, b| b.i32x4_shr_s(a as u32)),
+ I64x2ShrS => exec_op!(binary i32, Value128 => Value128, |a, b| b.i64x2_shr_s(a as u32)),
+ I8x16ShrU => exec_op!(binary i32, Value128 => Value128, |a, b| b.i8x16_shr_u(a as u32)),
+ I16x8ShrU => exec_op!(binary i32, Value128 => Value128, |a, b| b.i16x8_shr_u(a as u32)),
+ I32x4ShrU => exec_op!(binary i32, Value128 => Value128, |a, b| b.i32x4_shr_u(a as u32)),
+ I64x2ShrU => exec_op!(binary i32, Value128 => Value128, |a, b| b.i64x2_shr_u(a as u32)),
I8x16Add => exec_op!(binary Value128 => Value128, |a, b| a.i8x16_add(b)),
I16x8Add => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_add(b)),
I32x4Add => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_add(b)),
@@ -823,7 +686,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
I64x2ExtendHighI32x4S => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_s()),
I64x2ExtendHighI32x4U => exec_op!(unary Value128 => Value128, |a| a.i64x2_extend_high_i32x4_u()),
I8x16Popcnt => exec_op!(unary Value128 => Value128, |v| v.i8x16_popcnt()),
- I8x16Shuffle(idx) => exec_op!(binary Value128 => Value128, |a, b| Value128::i8x16_shuffle(a, b, Value128(idx.get(&self.func.data).value))),
+ I8x16Shuffle(idx) => self.exec_simd_shuffle(Value128(idx.resolve(&self.func.data).value()))?,
I16x8Q15MulrSatS => exec_op!(binary Value128 => Value128, |a, b| a.i16x8_q15mulr_sat_s(b)),
I32x4DotI16x8S => exec_op!(binary Value128 => Value128, |a, b| a.i32x4_dot_i16x8_s(b)),
I8x16RelaxedLaneselect => exec_op!(ternary Value128 => Value128, |a, b, c| Value128::i8x16_relaxed_laneselect(a, b, c)),
@@ -891,17 +754,424 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
}
#[inline(always)]
- fn exec_jump_if(cf: &CallFrame, condition: impl FnOnce(&CallFrame) -> bool) -> bool {
- condition(cf)
+ fn exec_jump_if_ref<const ON_NULL: bool>(&mut self) -> bool {
+ let is_null = ValueRef::stack_peek(&self.store.value_stack).is_null();
+ if is_null {
+ ValueRef::stack_pop(&mut self.store.value_stack);
+ }
+ is_null == ON_NULL
+ }
+
+ #[inline(always)]
+ fn exec_br_on_cast<const ON_MATCH: bool>(&self, index: Operand64Idx<(u32, u32)>) -> Option<usize> {
+ let operand = index.resolve(&self.func.data);
+ let ty = unwrap_or_unreachable!(RefType::from_bits(operand.b()));
+ (self.exec_ref_matches(ty) == ON_MATCH).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_jump_if_local<T: InternalValue + Default + PartialEq, const ON_ZERO: bool>(
+ &self,
+ local: LocalAddr,
+ ) -> bool {
+ (T::local_get(&self.store.value_stack, &self.cf, local) == T::default()) == ON_ZERO
+ }
+
+ #[inline(always)]
+ fn exec_jump_cmp_stack_const32(&mut self, packed: PackedOp64<CmpOp, (u32, i32)>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ packed.op.cmp(i32::stack_pop(&mut self.store.value_stack), operand.b()).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_jump_cmp_stack_const64(&mut self, packed: PackedOp128<CmpOp, (u32, i64)>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ packed.op.cmp(i64::stack_pop(&mut self.store.value_stack), operand.b()).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_jump_cmp_stack_local32(&mut self, packed: PackedOp64<CmpOp, (u32, u16)>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let lhs = i32::stack_pop(&mut self.store.value_stack);
+ let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.b());
+ packed.op.cmp(lhs, rhs).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_jump_cmp_stack_local64(&mut self, packed: PackedOp64<CmpOp, (u32, u16)>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let lhs = i64::stack_pop(&mut self.store.value_stack);
+ let rhs = i64::local_get(&self.store.value_stack, &self.cf, operand.b());
+ packed.op.cmp(lhs, rhs).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_binop_local_const_jump(&mut self, packed: PackedOp128<BinOp, LocalUpdateOperand>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let value = i32::local_update(
+ &mut self.store.value_stack,
+ &self.cf,
+ operand.local(),
+ #[inline(always)]
+ |value| packed.op.exec(value as u32, operand.value() as u32) as i32,
+ );
+ ((value == 0) == operand.on_zero()).then_some(operand.target() as usize)
}
- fn exec_branch_table(&mut self, index: OperandIdx<BranchTableArg>) -> usize {
- let v = index.get(&self.func.data);
+ #[inline(always)]
+ fn exec_binop_local_const_jump_cmp_local(
+ &mut self,
+ packed: PackedOp128<(BinOp, CmpOp), LocalUpdateCmpOperand>,
+ ) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let lhs = i32::local_update(
+ &mut self.store.value_stack,
+ &self.cf,
+ operand.local(),
+ #[inline(always)]
+ |value| packed.op.0.exec(value as u32, operand.value() as u32) as i32,
+ );
+ let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.right());
+ packed.op.1.cmp(lhs, rhs).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_binop_stack_const_tee_local_jump(
+ &mut self,
+ packed: PackedOp128<BinOp, LocalUpdateOperand>,
+ ) -> Result<Option<usize>, Trap> {
+ let operand = packed.index.resolve(&self.func.data);
+ let lhs = i32::stack_pop(&mut self.store.value_stack);
+ let value = packed.op.exec(lhs as u32, operand.value() as u32) as i32;
+ i32::local_set(&mut self.store.value_stack, &self.cf, operand.local(), value);
+ i32::stack_push(&mut self.store.value_stack, value)?;
+ Ok(((value == 0) == operand.on_zero()).then_some(operand.target() as usize))
+ }
+
+ #[inline(always)]
+ fn exec_binop_global_const_jump(&mut self, packed: PackedOp128<BinOp, GlobalUpdateOperand>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let global = self.module.resolve_global_addr(operand.global());
+ let value = i32::global_update(
+ &mut self.store.state.globals,
+ global,
+ #[inline(always)]
+ |value| packed.op.exec(value as u32, operand.value() as u32) as i32,
+ );
+ ((value == 0) == operand.on_zero()).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_inc_local_jump(&mut self, index: Operand128Idx<LocalUpdateOperand>) -> Option<usize> {
+ let operand = index.resolve(&self.func.data);
+ let value = i32::local_update(
+ &mut self.store.value_stack,
+ &self.cf,
+ operand.local(),
+ #[inline(always)]
+ |value| value.wrapping_add(operand.value()),
+ );
+ ((value == 0) == operand.on_zero()).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_inc_stack_tee_local_jump(
+ &mut self,
+ index: Operand128Idx<LocalUpdateOperand>,
+ ) -> Result<Option<usize>, Trap> {
+ let operand = index.resolve(&self.func.data);
+ let value = i32::stack_pop(&mut self.store.value_stack).wrapping_add(operand.value());
+ i32::local_set(&mut self.store.value_stack, &self.cf, operand.local(), value);
+ i32::stack_push(&mut self.store.value_stack, value)?;
+ Ok(((value == 0) == operand.on_zero()).then_some(operand.target() as usize))
+ }
+
+ #[inline(always)]
+ fn exec_inc_global_jump(&mut self, index: Operand128Idx<GlobalUpdateOperand>) -> Option<usize> {
+ let operand = index.resolve(&self.func.data);
+ let global = self.module.resolve_global_addr(operand.global());
+ let value = i32::global_update(
+ &mut self.store.state.globals,
+ global,
+ #[inline(always)]
+ |value| value.wrapping_add(operand.value()),
+ );
+ ((value == 0) == operand.on_zero()).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_inc_local_jump_cmp_local(&mut self, packed: PackedOp128<CmpOp, LocalUpdateCmpOperand>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let lhs = i32::local_update(
+ &mut self.store.value_stack,
+ &self.cf,
+ operand.local(),
+ #[inline(always)]
+ |value| value.wrapping_add(operand.value()),
+ );
+ let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.right());
+ packed.op.cmp(lhs, rhs).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_jump_cmp_local_const32(&self, packed: PackedOp128<CmpOp, (u32, i32, u16)>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let lhs = i32::local_get(&self.store.value_stack, &self.cf, operand.c());
+ packed.op.cmp(lhs, operand.b()).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_jump_cmp_local_const64(&self, packed: PackedOp128<CmpOp, (u32, i32, u16)>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let lhs = i64::local_get(&self.store.value_stack, &self.cf, operand.c());
+ packed.op.cmp(lhs, i64::from(operand.b())).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_jump_cmp_local_local32(&self, packed: PackedOp64<CmpOp, (u32, u16, u16)>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let lhs = i32::local_get(&self.store.value_stack, &self.cf, operand.b());
+ let rhs = i32::local_get(&self.store.value_stack, &self.cf, operand.c());
+ packed.op.cmp(lhs, rhs).then_some(operand.target() as usize)
+ }
+
+ #[inline(always)]
+ fn exec_jump_cmp_local_local64(&self, packed: PackedOp64<CmpOp, (u32, u16, u16)>) -> Option<usize> {
+ let operand = packed.index.resolve(&self.func.data);
+ let lhs = i64::local_get(&self.store.value_stack, &self.cf, operand.b());
+ let rhs = i64::local_get(&self.store.value_stack, &self.cf, operand.c());
+ packed.op.cmp(lhs, rhs).then_some(operand.target() as usize)
+ }
+
+ fn exec_i64_add128(&mut self) -> Result<(), Trap> {
+ let b_hi = i64::stack_pop(&mut self.store.value_stack);
+ let b_lo = i64::stack_pop(&mut self.store.value_stack);
+ let a_hi = i64::stack_pop(&mut self.store.value_stack);
+ let a_lo = i64::stack_pop(&mut self.store.value_stack);
+ let lo = a_lo.wrapping_add(b_lo);
+ let carry = u64::from((lo as u64) < (a_lo as u64));
+ let hi = a_hi.wrapping_add(b_hi).wrapping_add(carry as i64);
+ i64::stack_push(&mut self.store.value_stack, lo)?;
+ i64::stack_push(&mut self.store.value_stack, hi)
+ }
+
+ fn exec_i64_sub128(&mut self) -> Result<(), Trap> {
+ let b_hi = i64::stack_pop(&mut self.store.value_stack);
+ let b_lo = i64::stack_pop(&mut self.store.value_stack);
+ let a_hi = i64::stack_pop(&mut self.store.value_stack);
+ let a_lo = i64::stack_pop(&mut self.store.value_stack);
+ let lo = a_lo.wrapping_sub(b_lo);
+ let borrow = u64::from((a_lo as u64) < (b_lo as u64));
+ let hi = a_hi.wrapping_sub(b_hi).wrapping_sub(borrow as i64);
+ i64::stack_push(&mut self.store.value_stack, lo)?;
+ i64::stack_push(&mut self.store.value_stack, hi)
+ }
+
+ fn exec_i64_mul_wide_s(&mut self) -> Result<(), Trap> {
+ let rhs = i64::stack_pop(&mut self.store.value_stack);
+ let lhs = i64::stack_pop(&mut self.store.value_stack);
+ let product = (lhs as i128).wrapping_mul(rhs as i128);
+ i64::stack_push(&mut self.store.value_stack, product as i64)?;
+ i64::stack_push(&mut self.store.value_stack, (product >> 64) as i64)
+ }
+
+ fn exec_i64_mul_wide_u(&mut self) -> Result<(), Trap> {
+ let rhs = i64::stack_pop(&mut self.store.value_stack);
+ let lhs = i64::stack_pop(&mut self.store.value_stack);
+ let product = (lhs as u64 as u128).wrapping_mul(rhs as u64 as u128);
+ i64::stack_push(&mut self.store.value_stack, product as u64 as i64)?;
+ i64::stack_push(&mut self.store.value_stack, (product >> 64) as u64 as i64)
+ }
+
+ fn exec_simd_extract_lane<TO: InternalValue>(
+ &mut self,
+ lane: u8,
+ operation: impl FnOnce(Value128, u8) -> TO,
+ ) -> Result<(), Trap> {
+ let vector = Value128::stack_pop(&mut self.store.value_stack);
+ TO::stack_push(&mut self.store.value_stack, operation(vector, lane))
+ }
+
+ fn exec_simd_replace_lane<VALUE: InternalValue>(
+ &mut self,
+ lane: u8,
+ operation: impl FnOnce(VALUE, Value128, u8) -> Value128,
+ ) -> Result<(), Trap> {
+ let vector = Value128::stack_pop(&mut self.store.value_stack);
+ let value = VALUE::stack_pop(&mut self.store.value_stack);
+ Value128::stack_push(&mut self.store.value_stack, operation(value, vector, lane))
+ }
+
+ fn exec_simd_shuffle(&mut self, lanes: Value128) -> Result<(), Trap> {
+ let rhs = Value128::stack_pop(&mut self.store.value_stack);
+ let lhs = Value128::stack_pop(&mut self.store.value_stack);
+ Value128::stack_push(&mut self.store.value_stack, Value128::i8x16_shuffle(lhs, rhs, lanes))
+ }
+
+ #[inline(always)]
+ fn exec_local_set_pop<T: InternalValue>(&mut self, local: LocalAddr) {
+ let value = T::stack_pop(&mut self.store.value_stack);
+ T::local_set(&mut self.store.value_stack, &self.cf, local, value);
+ }
+
+ #[inline(always)]
+ fn exec_local_tee<T: InternalValue>(&mut self, local: LocalAddr) {
+ let value = T::stack_peek(&self.store.value_stack);
+ T::local_set(&mut self.store.value_stack, &self.cf, local, value);
+ }
+
+ #[inline(always)]
+ fn exec_global_get<T: InternalValue>(&mut self, global: GlobalAddr) -> Result<(), Trap> {
+ let addr = self.module.resolve_global_addr(global);
+ let value = T::global_get(&self.store.state.globals, addr);
+ T::stack_push(&mut self.store.value_stack, value)
+ }
+
+ #[inline(always)]
+ fn exec_global_set<T: InternalValue>(&mut self, global: GlobalAddr) {
+ let addr = self.module.resolve_global_addr(global);
+ let value = T::stack_pop(&mut self.store.value_stack);
+ T::global_set(&mut self.store.state.globals, addr, value);
+ }
+
+ #[inline(always)]
+ fn exec_global_tee<T: InternalValue>(&mut self, global: GlobalAddr) {
+ let addr = self.module.resolve_global_addr(global);
+ let value = T::stack_peek(&self.store.value_stack);
+ T::global_set(&mut self.store.state.globals, addr, value);
+ }
+
+ #[inline(always)]
+ fn exec_binop_result<T: InternalValue, const PUSH: bool>(
+ &mut self,
+ dst: Option<LocalAddr>,
+ val: T,
+ ) -> Result<(), Trap> {
+ if let Some(dst) = dst {
+ T::local_set(&mut self.store.value_stack, &self.cf, dst, val);
+ }
+ if PUSH { T::stack_push(&mut self.store.value_stack, val) } else { Ok(()) }
+ }
+
+ #[inline(always)]
+ fn exec_binop_local_local<T: InternalValue, const PUSH: bool>(
+ &mut self,
+ lhs: LocalAddr,
+ rhs: LocalAddr,
+ destination: Option<LocalAddr>,
+ op: impl BinOpExt<T>,
+ ) -> Result<(), Trap> {
+ let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs);
+ let rhs = T::local_get(&self.store.value_stack, &self.cf, rhs);
+ self.exec_binop_result::<T, PUSH>(destination, op.exec(lhs, rhs))
+ }
+
+ #[inline(always)]
+ fn exec_binop_local_local_indexed<T: InternalValue, const PUSH: bool>(
+ &mut self,
+ index: Operand64Idx<(u16, u16, u16)>,
+ op: impl BinOpExt<T>,
+ ) -> Result<(), Trap> {
+ let operands = index.resolve(&self.func.data);
+ self.exec_binop_local_local::<T, PUSH>(operands.a(), operands.b(), Some(operands.c()), op)
+ }
+
+ #[inline(always)]
+ fn exec_binop_local_const<T: InternalValue, const PUSH: bool>(
+ &mut self,
+ lhs: LocalAddr,
+ rhs: T,
+ destination: Option<LocalAddr>,
+ op: impl BinOpExt<T>,
+ ) -> Result<(), Trap> {
+ let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs);
+ self.exec_binop_result::<T, PUSH>(destination, op.exec(lhs, rhs))
+ }
+
+ #[inline(always)]
+ fn exec_binop_global_const<T: InternalValue>(
+ &mut self,
+ lhs: GlobalAddr,
+ rhs: T,
+ op: impl BinOpExt<T>,
+ ) -> Result<(), Trap> {
+ let lhs = T::global_get(&self.store.state.globals, self.module.resolve_global_addr(lhs));
+ T::stack_push(&mut self.store.value_stack, op.exec(lhs, rhs))
+ }
+
+ #[inline(always)]
+ fn exec_cmp_local_local<T>(&mut self, lhs: LocalAddr, rhs: LocalAddr, op: CmpOp) -> Result<(), Trap>
+ where
+ T: InternalValue,
+ CmpOp: CmpOpExt<T>,
+ {
+ let lhs = T::local_get(&self.store.value_stack, &self.cf, lhs);
+ let rhs = T::local_get(&self.store.value_stack, &self.cf, rhs);
+ i32::stack_push(&mut self.store.value_stack, i32::from(op.cmp(lhs, rhs)))
+ }
+
+ #[inline(always)]
+ fn exec_binop_stack_global<T: InternalValue>(
+ &mut self,
+ global: GlobalAddr,
+ op: impl BinOpExt<T>,
+ ) -> Result<(), Trap> {
+ let addr = self.module.resolve_global_addr(global);
+ let rhs = T::global_get(&self.store.state.globals, addr);
+ let lhs = T::stack_pop(&mut self.store.value_stack);
+ T::stack_push(&mut self.store.value_stack, op.exec(lhs, rhs))
+ }
+
+ #[inline(always)]
+ fn exec_binop_stack_local<T: InternalValue, const PUSH: bool>(
+ &mut self,
+ local: LocalAddr,
+ destination: Option<LocalAddr>,
+ op: impl BinOpExt<T>,
+ ) -> Result<(), Trap> {
+ let rhs = T::local_get(&self.store.value_stack, &self.cf, local);
+ let lhs = T::stack_pop(&mut self.store.value_stack);
+ self.exec_binop_result::<T, PUSH>(destination, op.exec(lhs, rhs))
+ }
+
+ #[inline(always)]
+ fn exec_binop_const_tee<T: InternalValue>(
+ &mut self,
+ rhs: T,
+ destination: LocalAddr,
+ op: impl BinOpExt<T>,
+ ) -> Result<(), Trap> {
+ let value = T::stack_update(&mut self.store.value_stack, |lhs| op.exec(lhs, rhs))?;
+ T::local_set(&mut self.store.value_stack, &self.cf, destination, value);
+ Ok(())
+ }
+
+ #[inline(always)]
+ fn exec_mul_acc_local<T: InternalValue>(
+ &mut self,
+ accumulator: LocalAddr,
+ multiply: fn(T, T) -> T,
+ add: fn(T, T) -> T,
+ ) {
+ let rhs = T::stack_pop(&mut self.store.value_stack);
+ let lhs = T::stack_pop(&mut self.store.value_stack);
+ let product = multiply(lhs, rhs);
+ T::local_update(
+ &mut self.store.value_stack,
+ &self.cf,
+ accumulator,
+ #[inline(always)]
+ |value| add(product, value),
+ );
+ }
+
+ fn exec_branch_table(&mut self, index: Operand128Idx<BranchTableOperand>) -> usize {
+ let v = index.resolve(&self.func.data);
let idx = <i32>::stack_pop(&mut self.store.value_stack);
- let target_ip = if idx >= 0 && (idx as u32) < v.len {
- self.func.data.branch_table_targets.get((v.start + idx as u32) as usize).copied().unwrap_or(v.target)
+ let target_ip = if idx >= 0 && (idx as u32) < v.size() {
+ self.func.data.branch_table_targets.get((v.start() + idx as u32) as usize).copied().unwrap_or(v.target())
} else {
- v.target
+ v.target()
};
target_ip as usize
@@ -929,12 +1199,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
self.store.state.alloc_exception(tag_addr, payload, roots)
}
- fn exec_throw(&mut self, tag_index: TagAddr, instr_ptr: usize) -> Result<usize> {
+ fn exec_throw(&mut self, tag_index: TagAddr, instr_ptr: usize) -> Result<ControlFlow<(), usize>> {
let exception = self.create_exception(tag_index)?;
self.throw_exception(exception, instr_ptr)
}
- fn exec_throw_ref(&mut self, instr_ptr: usize) -> Result<usize> {
+ fn exec_throw_ref(&mut self, instr_ptr: usize) -> Result<ControlFlow<(), usize>> {
let exception = ValueRef::stack_pop(&mut self.store.value_stack);
if exception.is_null() {
return Err(Trap::NullReference.into());
@@ -942,11 +1212,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
self.throw_exception(exception, instr_ptr)
}
- fn throw_exception(&mut self, exception: ValueRef, protected_ip: usize) -> Result<usize> {
- match self.dispatch_exception(exception, protected_ip) {
- Ok(Some(landing_pad)) => Ok(landing_pad),
- Ok(None) => self.store.root_exception(exception).and_then(|exception| Err(Error::Exception(exception))),
- Err(trap) => Err(trap.into()),
+ fn throw_exception(&mut self, exception: ValueRef, protected_ip: usize) -> Result<ControlFlow<(), usize>> {
+ match self.dispatch_exception(exception, protected_ip)? {
+ Some(landing_pad) => Ok(ControlFlow::Continue(landing_pad)),
+ None => self.store.root_exception(exception).and_then(|exception| Err(Error::Exception(exception))),
}
}
@@ -964,6 +1233,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
})
}
+ #[inline(always)]
fn switch_to_frame(&mut self, frame: CallFrame) {
let previous = core::mem::replace(&mut self.cf, frame);
if previous.func_addr == self.cf.func_addr {
@@ -1013,7 +1283,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
return Ok(None);
};
self.switch_to_frame(caller);
- protected_ip = self.cf.instr_ptr.checked_sub(1).unwrap_or_else(|| unreachable!("invalid caller IP"));
+ protected_ip = unwrap_or_unreachable!(self.cf.instr_ptr.checked_sub(1), "invalid caller IP");
}
}
@@ -1066,7 +1336,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
host_func: HostFunction,
type_addr: TypeAddr,
return_instr_ptr: usize,
- ) -> Result<ControlFlow<(), usize>, Trap> {
+ ) -> Result<ControlFlow<(), usize>> {
if let Some(host_func) = host_func.typed_callback() {
cold_err!(host_func.call_stack(self.store, self.module.id(), type_addr))
.map_err(|error| Trap::HostFunction(Box::new(error)))?;
@@ -1101,7 +1371,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
if TAIL { Ok(self.exec_return()) } else { Ok(ControlFlow::Continue(return_instr_ptr)) }
}
- fn exec_call_direct(&mut self, v: u32, return_instr_ptr: usize) -> Result<ControlFlow<(), usize>, Trap> {
+ fn exec_call_direct(&mut self, v: u32, return_instr_ptr: usize) -> Result<ControlFlow<(), usize>> {
self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
let addr = self.module.resolve_func_addr(v);
let func = self.store.state.get_func(addr);
@@ -1116,7 +1386,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
}
}
- fn exec_return_call_direct(&mut self, v: u32) -> Result<ControlFlow<(), usize>, Trap> {
+ fn exec_return_call_direct(&mut self, v: u32) -> Result<ControlFlow<(), usize>> {
self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
let addr = self.module.resolve_func_addr(v);
let func = self.store.state.get_func(addr);
@@ -1131,34 +1401,36 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
}
}
- fn exec_call_self(&mut self, return_instr_ptr: usize) -> Result<(), Trap> {
+ fn exec_call_self(&mut self, return_instr_ptr: usize) -> Result<ControlFlow<(), usize>> {
self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
let Ok(locals_base) = self.store.value_stack.enter_locals(&self.func.params, &self.func.locals) else {
- return cold!(Err(Trap::CallStackOverflow));
+ return cold!(Err(Trap::CallStackOverflow.into()));
};
let new = CallFrame::new(self.cf.func_addr, locals_base, self.func.locals);
self.store.call_stack.push(core::mem::replace(&mut self.cf, new), return_instr_ptr)?;
- Ok(())
+ Ok(ControlFlow::Continue(0))
}
- fn exec_return_call_self(&mut self) -> Result<(), Trap> {
+ fn exec_return_call_self(&mut self) -> Result<ControlFlow<(), usize>> {
self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
self.store.value_stack.truncate_keep_counts(self.cf.locals_base, self.func.params);
let Ok(locals_base) = self.store.value_stack.enter_locals(&self.func.params, &self.func.locals) else {
- return cold!(Err(Trap::CallStackOverflow));
+ return cold!(Err(Trap::CallStackOverflow.into()));
};
self.cf = CallFrame::new(self.cf.func_addr, locals_base, self.func.locals);
- Ok(())
+ Ok(ControlFlow::Continue(0))
}
fn exec_call_indirect<const IS_RETURN_CALL: bool>(
&mut self,
- index: OperandIdx<TwoU32>,
+ index: Operand64Idx<(u32, u32)>,
return_instr_ptr: usize,
- ) -> Result<ControlFlow<(), usize>, Trap> {
- let TwoU32 { first: type_addr, second: table_addr } = index.get(&self.func.data);
+ ) -> Result<ControlFlow<(), usize>> {
+ let operand = index.resolve(&self.func.data);
+ let type_addr = operand.a();
+ let table_addr = operand.b();
self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
// verify that the table is of the right type, this should be validated by the parser already
let table_addr = self.module.resolve_table_addr(table_addr);
@@ -1166,11 +1438,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
let table = self.store.state.get_table(table_addr);
let Ok(table) = table.get(table_idx) else {
- return cold!(Err(Trap::UndefinedElement { index: table_idx }));
+ return cold!(Err(Trap::UndefinedElement { index: table_idx }.into()));
};
let Some(func_ref) = table.addr() else {
- return cold!(Err(Trap::UninitializedElement { index: table_idx }));
+ return cold!(Err(Trap::UninitializedElement { index: table_idx }.into()));
};
self.exec_typed_call::<IS_RETURN_CALL>(func_ref, self.module.resolve_type_addr(type_addr), return_instr_ptr)
@@ -1181,13 +1453,14 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
func_addr: FuncAddr,
expected_type_addr: TypeAddr,
return_instr_ptr: usize,
- ) -> Result<ControlFlow<(), usize>, Trap> {
+ ) -> Result<ControlFlow<(), usize>> {
let func = self.store.state.get_func(func_addr);
if !self.store.state.type_addr_is_subtype(func.type_addr, expected_type_addr) {
return cold!(Err(Trap::IndirectCallTypeMismatch {
actual: Box::new(self.store.state.get_canonical_func_type(func.type_addr).clone()),
expected: Box::new(self.store.state.get_canonical_func_type(expected_type_addr).clone()),
- }));
+ }
+ .into()));
}
match &func.inner {
crate::store::FunctionInstanceInner::Wasm(wasm_func) => match IS_RETURN_CALL {
@@ -1205,11 +1478,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
&mut self,
type_addr: u32,
return_instr_ptr: usize,
- ) -> Result<ControlFlow<(), usize>, Trap> {
+ ) -> Result<ControlFlow<(), usize>> {
self.charge_call_fuel(FUEL_COST_CALL_TOTAL);
let func_ref = ValueRef::stack_pop(&mut self.store.value_stack);
let Some(func_addr) = func_ref.addr() else {
- return cold!(Err(Trap::NullFunctionReference));
+ return cold!(Err(Trap::NullFunctionReference.into()));
};
self.exec_typed_call::<IS_RETURN_CALL>(func_addr, self.module.resolve_type_addr(type_addr), return_instr_ptr)
@@ -1234,13 +1507,11 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
ControlFlow::Continue(instr_ptr)
}
- #[inline(always)]
fn exec_return_void(&mut self) -> ControlFlow<(), usize> {
self.store.value_stack.truncate_to_base(self.cf.locals_base);
self.finish_return()
}
- #[inline(always)]
fn exec_return_32(&mut self) -> ControlFlow<(), usize> {
self.store.value_stack.stack_32.truncate_to_one_tail(self.cf.locals_base.s32 as usize);
self.store.value_stack.stack_64.truncate_to(self.cf.locals_base.s64 as usize);
@@ -1248,7 +1519,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
self.finish_return()
}
- #[inline(always)]
fn exec_return_64(&mut self) -> ControlFlow<(), usize> {
self.store.value_stack.stack_32.truncate_to(self.cf.locals_base.s32 as usize);
self.store.value_stack.stack_64.truncate_to_one_tail(self.cf.locals_base.s64 as usize);
@@ -1256,7 +1526,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
self.finish_return()
}
- #[inline(always)]
fn exec_return_128(&mut self) -> ControlFlow<(), usize> {
self.store.value_stack.stack_32.truncate_to(self.cf.locals_base.s32 as usize);
self.store.value_stack.stack_64.truncate_to(self.cf.locals_base.s64 as usize);
@@ -1264,15 +1533,15 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
self.finish_return()
}
- #[inline(always)]
fn exec_store_local_local<T: InternalValue + MemValue<N>, const N: usize>(
&mut self,
- memarg: CompactMemoryArg,
+ index: Operand64Idx<CompactMemoryOperand>,
addr_local: u8,
value_local: u8,
) -> Result<(), Trap> {
+ let memarg = index.resolve(&self.func.data);
let value = T::local_get(&self.store.value_stack, &self.cf, u16::from(value_local));
- let mem_addr = self.mem_addr(memarg.mem_addr());
+ let mem_addr = self.mem_addr(MemAddr::from(memarg.memory()));
let mem = self.store.state.get_mem_mut(mem_addr);
let addr = if mem.is_64bit() {
let base = u64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local));
@@ -1281,22 +1550,22 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
len: N,
max: mem.inner.len(),
}))?;
- mem.effective_addr::<N>(base, memarg.offset())?
+ cold_err!(mem.effective_addr::<N>(base, u64::from(memarg.offset())))?
} else {
let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local));
- mem.effective_addr::<N>(base as usize, memarg.offset())?
+ cold_err!(mem.effective_addr::<N>(base as usize, u64::from(memarg.offset())))?
};
value.store_at(&mut mem.inner, addr)
}
- #[inline(always)]
fn exec_inc_memory_local<T: MemValue<N>, const N: usize>(
&mut self,
- memarg: CompactMemoryArg,
+ index: Operand64Idx<CompactMemoryOperand>,
addr_local: u8,
increment: impl FnOnce(T) -> T,
) -> Result<(), Trap> {
- let mem_addr = self.mem_addr(memarg.mem_addr());
+ let memarg = index.resolve(&self.func.data);
+ let mem_addr = self.mem_addr(MemAddr::from(memarg.memory()));
let mem = self.store.state.get_mem_mut(mem_addr);
let addr = if mem.is_64bit() {
let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64;
@@ -1305,17 +1574,16 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
len: N,
max: mem.inner.len(),
}))?;
- mem.effective_addr::<N>(base, memarg.offset())?
+ cold_err!(mem.effective_addr::<N>(base, u64::from(memarg.offset())))?
} else {
let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local));
- mem.effective_addr::<N>(base as usize, memarg.offset())?
+ cold_err!(mem.effective_addr::<N>(base as usize, u64::from(memarg.offset())))?
};
let value = cold_err!(T::load_at(&mem.inner, addr))?;
increment(value).store_at(&mut mem.inner, addr)
}
- #[inline(always)]
fn exec_fma_store<
T: InternalValue + MemValue<N> + core::ops::Add<Output = T> + core::ops::Mul<Output = T>,
const N: usize,
@@ -1330,18 +1598,16 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
let mem_addr = self.mem_addr(m.mem_addr());
let mem = self.store.state.get_mem_mut(mem_addr);
let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?;
- let addr = mem.effective_addr::<N>(base, m.offset())?;
- fma.store_at(&mut mem.inner, addr)?;
- Ok(())
+ let addr = cold_err!(mem.effective_addr::<N>(base, m.offset()))?;
+ cold_err!(fma.store_at(&mut mem.inner, addr))
}
- #[inline(always)]
fn exec_load_local_value<T: MemValue<N>, const N: usize>(
&self,
- memarg: CompactMemoryArg,
+ memarg: Operand64<CompactMemoryOperand>,
addr_local: u8,
) -> Result<T, Trap> {
- let mem = self.store.state.get_mem(self.mem_addr(memarg.mem_addr()));
+ let mem = self.store.state.get_mem(self.mem_addr(MemAddr::from(memarg.memory())));
let addr = if mem.is_64bit() {
let base = i64::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local)) as u64;
let base = cold_err!(usize::try_from(base).map_err(|_| Trap::MemoryOutOfBounds {
@@ -1349,15 +1615,14 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
len: N,
max: mem.inner.len(),
}))?;
- mem.effective_addr::<N>(base, memarg.offset())?
+ cold_err!(mem.effective_addr::<N>(base, u64::from(memarg.offset())))?
} else {
let base = u32::local_get(&self.store.value_stack, &self.cf, u16::from(addr_local));
- mem.effective_addr::<N>(base as usize, memarg.offset())?
+ cold_err!(mem.effective_addr::<N>(base as usize, u64::from(memarg.offset())))?
};
cold_err!(T::load_at(&mem.inner, addr))
}
- #[inline(always)]
fn exec_load_local<
LOAD: MemValue<N>,
const N: usize,
@@ -1366,11 +1631,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
const TEE: bool,
>(
&mut self,
- memarg: CompactMemoryArg,
+ index: Operand64Idx<CompactMemoryOperand>,
addr_local: u8,
dst_local: u8,
cast: impl Fn(LOAD) -> TARGET,
) -> Result<(), Trap> {
+ let memarg = index.resolve(&self.func.data);
let value = cast(self.exec_load_local_value::<LOAD, N>(memarg, addr_local)?);
if SET_LOCAL {
TARGET::local_set(&mut self.store.value_stack, &self.cf, u16::from(dst_local), value);
@@ -1382,7 +1648,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
}
fn exec_ref_is_null(&mut self) -> Result<(), Trap> {
- let is_null = i32::from(<ValueRef>::stack_pop(&mut self.store.value_stack).is_null());
+ let is_null = i32::from(ValueRef::stack_pop(&mut self.store.value_stack).is_null());
self.store.value_stack.push::<i32>(is_null)
}
@@ -1463,8 +1729,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
self.push_gc_object(type_addr, values)
}
- fn exec_struct_get(&mut self, index: OperandIdx<TwoU32>, signed: Option<bool>) -> Result<(), Trap> {
- let TwoU32 { first: type_index, second: field_index } = index.get(&self.func.data);
+ fn exec_struct_get(&mut self, index: Operand64Idx<(u32, u32)>, signed: Option<bool>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let type_index = operand.a();
+ let field_index = operand.b();
let reference = ValueRef::stack_pop(&mut self.store.value_stack);
let type_addr = self.module.resolve_type_addr(type_index);
let storage = self.store.state.get_type(type_addr).as_struct().expect("validated struct.get type").fields
@@ -1476,8 +1744,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
push_value(&mut self.store.value_stack, value, storage, signed)
}
- fn exec_struct_set(&mut self, index: OperandIdx<TwoU32>) -> Result<(), Trap> {
- let TwoU32 { first: type_index, second: field_index } = index.get(&self.func.data);
+ fn exec_struct_set(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let type_index = operand.a();
+ let field_index = operand.b();
let type_addr = self.module.resolve_type_addr(type_index);
let storage = self.store.state.get_type(type_addr).as_struct().expect("validated struct.set type").fields
[field_index as usize]
@@ -1501,8 +1771,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
self.push_gc_object(type_addr, values)
}
- fn exec_array_new_fixed(&mut self, index: OperandIdx<TwoU32>) -> Result<(), Trap> {
- let TwoU32 { first: type_index, second: len } = index.get(&self.func.data);
+ fn exec_array_new_fixed(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let type_index = operand.a();
+ let len = operand.b();
let type_addr = self.module.resolve_type_addr(type_index);
let storage =
self.store.state.get_type(type_addr).as_array().expect("validated array.new_fixed type").field.storage;
@@ -1567,8 +1839,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
Ok(())
}
- fn exec_array_copy(&mut self, index: OperandIdx<TwoU32>) -> Result<(), Trap> {
- let TwoU32 { first: dst_type, second: src_type } = index.get(&self.func.data);
+ fn exec_array_copy(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let dst_type = operand.a();
+ let src_type = operand.b();
let len = u32::stack_pop(&mut self.store.value_stack) as usize;
let src_index = u32::stack_pop(&mut self.store.value_stack) as usize;
let src = ValueRef::stack_pop(&mut self.store.value_stack);
@@ -1595,8 +1869,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
Ok(())
}
- fn exec_array_new_data(&mut self, index: OperandIdx<TwoU32>) -> Result<(), Trap> {
- let TwoU32 { first: type_index, second: data_index } = index.get(&self.func.data);
+ fn exec_array_new_data(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let type_index = operand.a();
+ let data_index = operand.b();
let len = u32::stack_pop(&mut self.store.value_stack) as usize;
let src = u32::stack_pop(&mut self.store.value_stack) as usize;
let type_addr = self.module.resolve_type_addr(type_index);
@@ -1609,8 +1885,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
self.push_gc_object(type_addr, values)
}
- fn exec_array_new_elem(&mut self, index: OperandIdx<TwoU32>) -> Result<(), Trap> {
- let TwoU32 { first: type_index, second: elem_index } = index.get(&self.func.data);
+ fn exec_array_new_elem(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let type_index = operand.a();
+ let elem_index = operand.b();
let len = u32::stack_pop(&mut self.store.value_stack) as usize;
let src = u32::stack_pop(&mut self.store.value_stack) as usize;
let type_addr = self.module.resolve_type_addr(type_index);
@@ -1623,8 +1901,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
self.push_gc_object(type_addr, values)
}
- fn exec_array_init_data(&mut self, index: OperandIdx<TwoU32>) -> Result<(), Trap> {
- let TwoU32 { first: type_index, second: data_index } = index.get(&self.func.data);
+ fn exec_array_init_data(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let type_index = operand.a();
+ let data_index = operand.b();
let len = u32::stack_pop(&mut self.store.value_stack) as usize;
let src = u32::stack_pop(&mut self.store.value_stack) as usize;
let dst = u32::stack_pop(&mut self.store.value_stack) as usize;
@@ -1641,8 +1921,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
Ok(())
}
- fn exec_array_init_elem(&mut self, index: OperandIdx<TwoU32>) -> Result<(), Trap> {
- let TwoU32 { first: type_index, second: elem_index } = index.get(&self.func.data);
+ fn exec_array_init_elem(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let type_index = operand.a();
+ let elem_index = operand.b();
let len = u32::stack_pop(&mut self.store.value_stack) as usize;
let src = u32::stack_pop(&mut self.store.value_stack) as usize;
let dst = u32::stack_pop(&mut self.store.value_stack) as usize;
@@ -1674,21 +1956,23 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
let mem = self.store.state.get_mem_mut(mem_addr);
let is_64bit = mem.is_64bit();
let pages_delta = match is_64bit {
- true => <i64>::stack_pop(&mut self.store.value_stack),
- false => i64::from(<i32>::stack_pop(&mut self.store.value_stack)),
+ true => i64::stack_pop(&mut self.store.value_stack),
+ false => i64::from(i32::stack_pop(&mut self.store.value_stack)),
};
let size = mem.grow(pages_delta, limiter)?.unwrap_or(-1);
match is_64bit {
- true => self.store.value_stack.push::<i64>(size)?,
- false => self.store.value_stack.push::<i32>(size as i32)?,
+ true => i64::stack_push(&mut self.store.value_stack, size)?,
+ false => i32::stack_push(&mut self.store.value_stack, size as i32)?,
};
Ok(())
}
- fn exec_memory_copy(&mut self, index: OperandIdx<TwoU32>) -> Result<(), Trap> {
- let TwoU32 { first: dst_mem, second: src_mem } = index.get(&self.func.data);
+ fn exec_memory_copy(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let dst_mem = operand.a();
+ let src_mem = operand.b();
let dst_mem_addr = self.mem_addr(dst_mem);
let src_mem_addr = self.mem_addr(src_mem);
let dst_arch = self.store.state.get_mem(dst_mem_addr).kind.arch();
@@ -1720,12 +2004,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
self.exec_memory_fill_impl(mem_addr, dst, val as u8, size)
}
- fn exec_memory_fill_const(&mut self, index: OperandIdx<MemoryFillConstOp>) -> Result<(), Trap> {
- let MemoryFillConstOp { memory: addr, byte: val, value: size } = index.get(&self.func.data);
- let mem_addr = self.mem_addr(addr);
+ fn exec_memory_fill_const(&mut self, index: Operand128Idx<MemoryFillOperand>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let mem_addr = self.mem_addr(operand.memory());
let arch = self.store.state.get_mem(mem_addr).kind.arch();
let dst = self.store.value_stack.pop_memory_operand(arch)?;
- self.exec_memory_fill_impl(mem_addr, dst, val, size as u32 as usize)
+ self.exec_memory_fill_impl(mem_addr, dst, operand.byte(), operand.value() as u32 as usize)
}
fn exec_memory_fill_impl(&mut self, mem_addr: MemAddr, dst: usize, val: u8, size: usize) -> Result<(), Trap> {
@@ -1737,8 +2021,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
Ok(())
}
- fn exec_memory_init(&mut self, index: OperandIdx<TwoU32>) -> Result<(), Trap> {
- let TwoU32 { first: data_index, second: mem_index } = index.get(&self.func.data);
+ fn exec_memory_init(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let data_index = operand.a();
+ let mem_index = operand.b();
let size = u32::stack_pop(&mut self.store.value_stack) as usize;
let offset = u32::stack_pop(&mut self.store.value_stack) as usize;
let mem_addr = self.mem_addr(mem_index);
@@ -1770,8 +2056,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
Ok(())
}
- fn exec_table_copy(&mut self, index: OperandIdx<TwoU32>) -> Result<(), Trap> {
- let TwoU32 { first: dst_table, second: src_table } = index.get(&self.func.data);
+ fn exec_table_copy(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let dst_table = operand.a();
+ let src_table = operand.b();
let dst_table_addr = self.module.resolve_table_addr(dst_table);
let src_table_addr = self.module.resolve_table_addr(src_table);
let dst_arch = self.store.state.get_table(dst_table_addr).kind.arch();
@@ -1796,13 +2084,13 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
&mut self,
arg: MemoryLaneArg,
) -> Result<(), Trap> {
- let m = arg.memory_arg_idx.get(&self.func.data);
- let mem = self.store.state.get_mem(self.mem_addr(m.mem_addr()));
+ let m = arg.memory_arg_idx.resolve(&self.func.data);
+ let mem = self.store.state.get_mem(self.mem_addr(m.memory()));
let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?;
- let addr = mem.effective_addr::<LOAD_SIZE>(base, m.offset())?;
+ let addr = cold_err!(mem.effective_addr::<LOAD_SIZE>(base, m.offset()))?;
let val = cold_err!(LOAD::load_at(&mem.inner, addr))?;
let offset = arg.lane as usize * LOAD_SIZE;
- let mut imm = <Value128>::stack_pop(&mut self.store.value_stack).to_mem_bytes();
+ let mut imm = Value128::stack_pop(&mut self.store.value_stack).to_mem_bytes();
imm[offset..offset + LOAD_SIZE].copy_from_slice(&val.to_mem_bytes());
self.store.value_stack.push(Value128(imm))?;
Ok(())
@@ -1811,47 +2099,65 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
#[inline(always)]
fn exec_mem_load<LOAD: MemValue<LOAD_SIZE>, const LOAD_SIZE: usize, TARGET: InternalValue>(
&mut self,
- index: OperandIdx<MemoryArg>,
+ m: Operand128<MemoryOperand>,
cast: impl Fn(LOAD) -> TARGET,
) -> Result<(), Trap> {
- let m = index.get(&self.func.data);
- let mem = self.store.state.get_mem(self.mem_addr(m.mem_addr()));
+ let mem = self.store.state.get_mem(self.mem_addr(m.memory()));
let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?;
- let addr = mem.effective_addr::<LOAD_SIZE>(base, m.offset())?;
+ let addr = cold_err!(mem.effective_addr::<LOAD_SIZE>(base, m.offset()))?;
let value = cold_err!(LOAD::load_at(&mem.inner, addr))?;
self.store.value_stack.push(cast(value))
}
+ #[inline(always)]
fn exec_mem_store_lane<U: MemValue<N> + Copy, const N: usize>(&mut self, arg: MemoryLaneArg) -> Result<(), Trap> {
- let bytes = <Value128>::stack_pop(&mut self.store.value_stack).to_mem_bytes();
+ let bytes = Value128::stack_pop(&mut self.store.value_stack).to_mem_bytes();
let lane_offset = arg.lane as usize * N;
let mut val_bytes = [0u8; N];
val_bytes.copy_from_slice(&bytes[lane_offset..lane_offset + N]);
let val = U::from_mem_bytes(val_bytes);
- let m = arg.memory_arg_idx.get(&self.func.data);
- let mem_addr = self.mem_addr(m.mem_addr());
+ let m = arg.memory_arg_idx.resolve(&self.func.data);
+ let mem_addr = self.mem_addr(m.memory());
let mem = self.store.state.get_mem_mut(mem_addr);
let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?;
- let addr = mem.effective_addr::<N>(base, m.offset())?;
+ let addr = cold_err!(mem.effective_addr::<N>(base, m.offset()))?;
cold_err!(val.store_at(&mut mem.inner, addr))?;
Ok(())
}
+ #[inline(always)]
fn exec_mem_store<T: InternalValue, U: MemValue<N>, const N: usize>(
&mut self,
- index: OperandIdx<MemoryArg>,
+ memory: Operand128<MemoryOperand>,
cast: impl Fn(T) -> U,
) -> Result<(), Trap> {
- let val = <T>::stack_pop(&mut self.store.value_stack);
- let val = cast(val);
+ let val = cast(<T>::stack_pop(&mut self.store.value_stack));
+ self.exec_mem_store_value(self.mem_addr(memory.memory()), memory.offset(), val)
+ }
- let m = index.get(&self.func.data);
- let mem_addr = self.mem_addr(m.mem_addr());
- let mem = self.store.state.get_mem_mut(mem_addr);
+ #[inline(always)]
+ fn exec_select_store<T: InternalValue + MemValue<N>, const N: usize>(
+ &mut self,
+ memory: Operand128<MemoryOperand>,
+ ) -> Result<(), Trap> {
+ let condition = Value32::stack_pop(&mut self.store.value_stack);
+ let false_value = T::stack_pop(&mut self.store.value_stack);
+ let true_value = T::stack_pop(&mut self.store.value_stack);
+ let value = if condition == 0 { false_value } else { true_value };
+ self.exec_mem_store_value(self.mem_addr(memory.memory()), memory.offset(), value)
+ }
+
+ #[inline(always)]
+ fn exec_mem_store_value<U: MemValue<N>, const N: usize>(
+ &mut self,
+ memory_addr: MemAddr,
+ offset: u64,
+ val: U,
+ ) -> Result<(), Trap> {
+ let mem = self.store.state.get_mem_mut(memory_addr);
let base = self.store.value_stack.pop_memory_operand(mem.kind.arch())?;
- let addr = mem.effective_addr::<N>(base, m.offset())?;
- cold_err!(val.store_at(&mut mem.inner, addr))?;
- Ok(())
+ let addr = cold_err!(mem.effective_addr::<N>(base, offset))?;
+ cold_err!(val.store_at(&mut mem.inner, addr))
}
fn exec_table_get(&mut self, table_index: u32) -> Result<(), Trap> {
@@ -1862,7 +2168,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
}
fn exec_table_set(&mut self, table_index: u32) -> Result<(), Trap> {
- let val = <ValueRef>::stack_pop(&mut self.store.value_stack);
+ let val = ValueRef::stack_pop(&mut self.store.value_stack);
let table_addr = self.module.resolve_table_addr(table_index);
let idx = self.pop_table_operand(self.store.state.get_table(table_addr).kind.arch())?;
let table = self.store.state.get_table_mut(table_addr);
@@ -1877,8 +2183,10 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
}
}
- fn exec_table_init(&mut self, index: OperandIdx<TwoU32>) -> Result<(), Trap> {
- let TwoU32 { first: elem_index, second: table_index } = index.get(&self.func.data);
+ fn exec_table_init(&mut self, index: Operand64Idx<(u32, u32)>) -> Result<(), Trap> {
+ let operand = index.resolve(&self.func.data);
+ let elem_index = operand.a();
+ let table_index = operand.b();
let size = self.pop_table_operand(MemoryArch::I32)?; // n
let offset = self.pop_table_operand(MemoryArch::I32)?; // s
let table_addr = self.module.resolve_table_addr(table_index);
@@ -1896,7 +2204,7 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
let table_addr = self.module.resolve_table_addr(table_index);
let arch = self.store.state.get_table(table_addr).kind.arch();
let n = self.pop_table_operand(arch)?;
- let val = <ValueRef>::stack_pop(&mut self.store.value_stack);
+ let val = ValueRef::stack_pop(&mut self.store.value_stack);
let limiter = self.store.engine.config().resource_limiter.as_deref();
let table = self.store.state.get_table_mut(table_addr);
let sz = table.size();
@@ -1913,15 +2221,15 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> {
let table_addr = self.module.resolve_table_addr(table_index);
let arch = self.store.state.get_table(table_addr).kind.arch();
let n = self.pop_table_operand(arch)?;
- let val = <ValueRef>::stack_pop(&mut self.store.value_stack);
+ let val = ValueRef::stack_pop(&mut self.store.value_stack);
let i = self.pop_table_operand(arch)?;
self.store.state.get_table_mut(table_addr).fill(i, n, val)
}
fn pop_table_operand(&mut self, arch: MemoryArch) -> Result<usize, Trap> {
let value = match arch {
- MemoryArch::I32 => <i32>::stack_pop(&mut self.store.value_stack) as u32 as u64,
- MemoryArch::I64 => <i64>::stack_pop(&mut self.store.value_stack) as u64,
+ MemoryArch::I32 => i32::stack_pop(&mut self.store.value_stack) as u32 as u64,
+ MemoryArch::I64 => i64::stack_pop(&mut self.store.value_stack) as u64,
};
cold_err!(usize::try_from(value).map_err(|_| Trap::TableOutOfBounds {
offset: usize::MAX,
@@ -1994,92 +2302,3 @@ impl<'store> Executor<'store, true> {
}
}
}
-
-#[inline(always)]
-fn cmp_i32(lhs: i32, rhs: i32, op: CmpOp) -> bool {
- match op {
- CmpOp::Eq => lhs == rhs,
- CmpOp::Ne => lhs != rhs,
- CmpOp::LtS => lhs < rhs,
- CmpOp::LtU => (lhs as u32) < (rhs as u32),
- CmpOp::GtS => lhs > rhs,
- CmpOp::GtU => (lhs as u32) > (rhs as u32),
- CmpOp::LeS => lhs <= rhs,
- CmpOp::LeU => (lhs as u32) <= (rhs as u32),
- CmpOp::GeS => lhs >= rhs,
- CmpOp::GeU => (lhs as u32) >= (rhs as u32),
- }
-}
-
-#[inline(always)]
-fn cmp_i64(lhs: i64, rhs: i64, op: CmpOp) -> bool {
- match op {
- CmpOp::Eq => lhs == rhs,
- CmpOp::Ne => lhs != rhs,
- CmpOp::LtS => lhs < rhs,
- CmpOp::LtU => (lhs as u64) < (rhs as u64),
- CmpOp::GtS => lhs > rhs,
- CmpOp::GtU => (lhs as u64) > (rhs as u64),
- CmpOp::LeS => lhs <= rhs,
- CmpOp::LeU => (lhs as u64) <= (rhs as u64),
- CmpOp::GeS => lhs >= rhs,
- CmpOp::GeU => (lhs as u64) >= (rhs as u64),
- }
-}
-
-fn exec_binop_32(op: BinOp, lhs: u32, rhs: u32) -> u32 {
- match op {
- BinOp::IAdd => lhs.wrapping_add(rhs),
- BinOp::ISub => lhs.wrapping_sub(rhs),
- BinOp::IMul => lhs.wrapping_mul(rhs),
- BinOp::IAnd => lhs & rhs,
- BinOp::IOr => lhs | rhs,
- BinOp::IXor => lhs ^ rhs,
- BinOp::IShl => (lhs as i32).wrapping_shl(rhs) as u32,
- BinOp::IShrS => (lhs as i32).wrapping_shr(rhs) as u32,
- BinOp::IShrU => lhs.wrapping_shr(rhs),
- BinOp::IRotl => (lhs as i32).rotate_left(rhs) as u32,
- BinOp::IRotr => (lhs as i32).rotate_right(rhs) as u32,
- BinOp::FAdd => (f32::from_bits(lhs) + f32::from_bits(rhs)).to_bits(),
- BinOp::FSub => (f32::from_bits(lhs) - f32::from_bits(rhs)).to_bits(),
- BinOp::FMul => (f32::from_bits(lhs) * f32::from_bits(rhs)).to_bits(),
- BinOp::FDiv => (f32::from_bits(lhs) / f32::from_bits(rhs)).to_bits(),
- BinOp::FMin => f32::from_bits(lhs).tw_minimum(f32::from_bits(rhs)).to_bits(),
- BinOp::FMax => f32::from_bits(lhs).tw_maximum(f32::from_bits(rhs)).to_bits(),
- BinOp::FCopysign => f32::from_bits(lhs).copysign(f32::from_bits(rhs)).to_bits(),
- }
-}
-
-fn exec_binop_64(op: BinOp, lhs: u64, rhs: u64) -> u64 {
- match op {
- BinOp::IAdd => lhs.wrapping_add(rhs),
- BinOp::ISub => lhs.wrapping_sub(rhs),
- BinOp::IMul => lhs.wrapping_mul(rhs),
- BinOp::IAnd => lhs & rhs,
- BinOp::IOr => lhs | rhs,
- BinOp::IXor => lhs ^ rhs,
- BinOp::IShl => (lhs as i64).wrapping_shl(rhs as u32) as u64,
- BinOp::IShrS => (lhs as i64).wrapping_shr(rhs as u32) as u64,
- BinOp::IShrU => lhs.wrapping_shr(rhs as u32),
- BinOp::IRotl => (lhs as i64).rotate_left(rhs as u32) as u64,
- BinOp::IRotr => (lhs as i64).rotate_right(rhs as u32) as u64,
- BinOp::FAdd => (f64::from_bits(lhs) + f64::from_bits(rhs)).to_bits(),
- BinOp::FSub => (f64::from_bits(lhs) - f64::from_bits(rhs)).to_bits(),
- BinOp::FMul => (f64::from_bits(lhs) * f64::from_bits(rhs)).to_bits(),
- BinOp::FDiv => (f64::from_bits(lhs) / f64::from_bits(rhs)).to_bits(),
- BinOp::FMin => f64::from_bits(lhs).tw_minimum(f64::from_bits(rhs)).to_bits(),
- BinOp::FMax => f64::from_bits(lhs).tw_maximum(f64::from_bits(rhs)).to_bits(),
- BinOp::FCopysign => f64::from_bits(lhs).copysign(f64::from_bits(rhs)).to_bits(),
- }
-}
-
-fn exec_binop_128(op: BinOp128, lhs: Value128, rhs: Value128) -> Value128 {
- match op {
- BinOp128::And => lhs.v128_and(rhs),
- BinOp128::AndNot => lhs.v128_andnot(rhs),
- BinOp128::Or => lhs.v128_or(rhs),
- BinOp128::Xor => lhs.v128_xor(rhs),
- BinOp128::I64x2Add => lhs.i64x2_add(rhs),
- BinOp128::I64x2Mul => lhs.i64x2_mul(rhs),
- }
-}
diff --git a/crates/tinywasm/src/interpreter/num_helpers.rs b/crates/tinywasm/src/interpreter/num_helpers.rs
index 783b10b..d35b217 100644
--- a/crates/tinywasm/src/interpreter/num_helpers.rs
+++ b/crates/tinywasm/src/interpreter/num_helpers.rs
@@ -7,25 +7,22 @@ pub(crate) trait TinywasmIntExt: Sized {
/// we need to check for overflow. This macro generates the min/max values
/// for a specific conversion, which are then used in the actual conversion.
/// Rust sadly doesn't have wrapping casts for floats yet.
-#[rustfmt::skip]
macro_rules! float_min_max {
- (f32, i32) => {(i32::MIN as f32 - (1 << 8) as f32, i32::MAX as f32 + 1.0)}; // 2^8: f32 precision margin
- (f64, i32) => {(i32::MIN as f64 - 1.0, i32::MAX as f64 + 1.0)};
- (f32, u32) => {(-1.0_f32, u32::MAX as f32 + 1.0)};
- (f64, u32) => {(-1.0_f64, u32::MAX as f64 + 1.0)};
- (f32, i64) => {(i64::MIN as f32 - (1i64 << 40) as f32, i64::MAX as f32 + 1.0)}; // 2^40: f32 has 23 mantissa bits
- (f64, i64) => {(i64::MIN as f64 - (1i64 << 11) as f64, i64::MAX as f64 + 1.0)}; // 2^11: f64 precision margin
- (f32, u64) => {(-1.0_f32, u64::MAX as f32 + 1.0)};
- (f64, u64) => {(-1.0_f64, u64::MAX as f64 + 1.0)};
- ($from:ty, $to:ty) => {compile_error!("invalid float conversion")};
+ (f32, i32) => {{ (i32::MIN as f32 - (1 << 8) as f32, i32::MAX as f32 + 1.0) }}; // 2^8: f32 precision margin
+ (f64, i32) => {{ (i32::MIN as f64 - 1.0, i32::MAX as f64 + 1.0) }};
+ (f32, u32) => {{ (-1.0_f32, u32::MAX as f32 + 1.0) }};
+ (f64, u32) => {{ (-1.0_f64, u32::MAX as f64 + 1.0) }};
+ (f32, i64) => {{ (i64::MIN as f32 - (1i64 << 40) as f32, i64::MAX as f32 + 1.0) }}; // 2^40: f32 has 23 mantissa bits
+ (f64, i64) => {{ (i64::MIN as f64 - (1i64 << 11) as f64, i64::MAX as f64 + 1.0) }}; // 2^11: f64 precision margin
+ (f32, u64) => {{ (-1.0_f32, u64::MAX as f32 + 1.0) }};
+ (f64, u64) => {{ (-1.0_f64, u64::MAX as f64 + 1.0) }};
+ ($from:ty, $to:ty) => {{ compile_error!("invalid float conversion") }};
}
/// Convert a value on the stack with error checking
macro_rules! checked_conv_float {
// Direct conversion with error checking (two types)
- ($from:tt, $to:tt, $self:expr) => {
- checked_conv_float!($from, $to, $to, $self)
- };
+ ($from:tt, $to:tt, $self:expr) => {{ checked_conv_float!($from, $to, $to, $self) }};
// Conversion with an intermediate unsigned type and error checking (three types)
($from:tt, $intermediate:tt, $to:tt, $self:expr) => {{
let v = <$from>::stack_pop(&mut $self.store.value_stack);
diff --git a/crates/tinywasm/src/interpreter/simd/macros.rs b/crates/tinywasm/src/interpreter/simd/macros.rs
index bc7b805..9306d8f 100644
--- a/crates/tinywasm/src/interpreter/simd/macros.rs
+++ b/crates/tinywasm/src/interpreter/simd/macros.rs
@@ -183,18 +183,17 @@ macro_rules! lane_read {
(f64, $bytes:expr, $offset:expr) => { f64::from_bits(u64::from_le_bytes([$bytes[$offset], $bytes[$offset + 1], $bytes[$offset + 2], $bytes[$offset + 3], $bytes[$offset + 4], $bytes[$offset + 5], $bytes[$offset + 6], $bytes[$offset + 7]])) };
}
-#[rustfmt::skip]
macro_rules! lane_write {
- (i8, $value:expr) => { [$value as u8] };
- (u8, $value:expr) => { [$value] };
- (i16, $value:expr) => { $value.to_le_bytes() };
- (u16, $value:expr) => { $value.to_le_bytes() };
- (i32, $value:expr) => { $value.to_le_bytes() };
- (u32, $value:expr) => { $value.to_le_bytes() };
- (i64, $value:expr) => { $value.to_le_bytes() };
- (u64, $value:expr) => { $value.to_le_bytes() };
- (f32, $value:expr) => { $value.to_bits().to_le_bytes() };
- (f64, $value:expr) => { $value.to_bits().to_le_bytes() };
+ (i8, $value:expr) => {{ [$value as u8] }};
+ (u8, $value:expr) => {{ [$value] }};
+ (i16, $value:expr) => {{ $value.to_le_bytes() }};
+ (u16, $value:expr) => {{ $value.to_le_bytes() }};
+ (i32, $value:expr) => {{ $value.to_le_bytes() }};
+ (u32, $value:expr) => {{ $value.to_le_bytes() }};
+ (i64, $value:expr) => {{ $value.to_le_bytes() }};
+ (u64, $value:expr) => {{ $value.to_le_bytes() }};
+ (f32, $value:expr) => {{ $value.to_bits().to_le_bytes() }};
+ (f64, $value:expr) => {{ $value.to_bits().to_le_bytes() }};
}
macro_rules! impl_lane_accessors {
diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs
index e123a41..3748ef9 100644
--- a/crates/tinywasm/src/interpreter/stack/value_stack.rs
+++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs
@@ -62,12 +62,12 @@ impl<T: Copy + Default> Stack<T> {
#[inline(always)]
pub(crate) fn pop(&mut self) -> T {
- self.data.pop().unwrap_or_else(|| unreachable!("ValueStack underflow, this is a bug"))
+ unwrap_or_unreachable!(self.data.pop(), "ValueStack underflow, this is a bug")
}
#[inline(always)]
pub(crate) fn last(&self) -> &T {
- self.data.last().unwrap_or_else(|| unreachable!("ValueStack underflow, this is a bug"))
+ unwrap_or_unreachable!(self.data.last(), "ValueStack underflow, this is a bug")
}
#[inline(always)]
@@ -107,7 +107,7 @@ impl<T: Copy + Default> Stack<T> {
#[inline(always)]
pub(crate) fn truncate_to_one_tail(&mut self, n: usize) {
debug_assert!(n < self.data.len());
- let last = self.data.pop().unwrap_or_else(|| unreachable!("ValueStack underflow, this is a bug"));
+ let last = unwrap_or_unreachable!(self.data.pop(), "ValueStack underflow, this is a bug");
self.data.truncate(n);
self.data.push(last);
}
@@ -164,7 +164,7 @@ impl<T: Copy + Default> Stack<T> {
}
let len = self.data.len();
- let needed = count.checked_mul(2).unwrap_or_else(|| unreachable!("Stack underflow, this is a bug"));
+ let needed = unwrap_or_unreachable!(count.checked_mul(2), "Stack underflow, this is a bug");
if len < needed {
unreachable!("Stack underflow, this is a bug");
diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs
index 22f20b7..83b520b 100644
--- a/crates/tinywasm/src/interpreter/values.rs
+++ b/crates/tinywasm/src/interpreter/values.rs
@@ -1,7 +1,8 @@
+use super::num_helpers::TinywasmFloatExt;
use super::stack::{CallFrame, ValueStack};
use crate::store::Globals;
use crate::{Error, Result, Store, WasmValue, interpreter::simd::Value128};
-use tinywasm_types::{GlobalAddr, LocalAddr, WasmType};
+use tinywasm_types::{BinOp, BinOp128, CmpOp, GlobalAddr, LocalAddr, WasmType};
pub(crate) type Value32 = u32;
pub(crate) type Value64 = u64;
@@ -114,14 +115,24 @@ pub(crate) trait InternalValue: sealed::Sealed + Copy + Default {
fn stack_push(stack: &mut ValueStack, value: Self) -> Result<(), crate::Trap>;
fn stack_pop(stack: &mut ValueStack) -> Self;
fn stack_peek(stack: &ValueStack) -> Self;
+ fn stack_update(stack: &mut ValueStack, f: impl FnOnce(Self) -> Self) -> Result<Self, crate::Trap> {
+ let value = f(Self::stack_pop(stack));
+ Self::stack_push(stack, value)?;
+ Ok(value)
+ }
fn stack_select(stack: &mut ValueStack);
fn local_get(stack: &ValueStack, frame: &CallFrame, index: LocalAddr) -> Self;
fn local_push(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr) -> Result<(), crate::Trap>;
fn local_set(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, value: Self);
- fn local_update(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, f: impl FnOnce(Self) -> Self);
+ fn local_update(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, f: impl FnOnce(Self) -> Self) -> Self;
fn local_copy(stack: &mut ValueStack, frame: &CallFrame, from: LocalAddr, to: LocalAddr);
fn global_get(globals: &Globals, addr: GlobalAddr) -> Self;
fn global_set(globals: &mut Globals, addr: GlobalAddr, value: Self);
+ fn global_update(globals: &mut Globals, addr: GlobalAddr, f: impl FnOnce(Self) -> Self) -> Self {
+ let value = f(Self::global_get(globals, addr));
+ Self::global_set(globals, addr, value);
+ value
+ }
}
macro_rules! impl_internalvalue {
@@ -137,13 +148,6 @@ macro_rules! impl_internalvalue {
impl InternalValue for $outer {
#[inline(always)]
- fn stack_push(stack: &mut ValueStack, value: Self) -> Result<(), crate::Trap> {
- let $to_stack_v = value;
- cold_err!(stack.$stack.push($to_stack))?;
- Ok(())
- }
-
- #[inline(always)]
fn local_get(stack: &ValueStack, frame: &CallFrame, index: LocalAddr) -> Self {
let $from_stack_v =
*stack.$stack.get(frame.locals_base.$stack_base.wrapping_add(u32::from(index)) as usize);
@@ -168,11 +172,13 @@ macro_rules! impl_internalvalue {
frame: &CallFrame,
index: LocalAddr,
f: impl FnOnce(Self) -> Self,
- ) {
+ ) -> Self {
let abs_index = frame.locals_base.$stack_base.wrapping_add(u32::from(index)) as usize;
let $from_stack_v = *stack.$stack.get(abs_index);
- let $to_stack_v = f($from_stack);
+ let value = f($from_stack);
+ let $to_stack_v = value;
stack.$stack.set(abs_index, $to_stack);
+ value
}
#[inline(always)]
@@ -195,6 +201,13 @@ macro_rules! impl_internalvalue {
}
#[inline(always)]
+ fn stack_push(stack: &mut ValueStack, value: Self) -> Result<(), crate::Trap> {
+ let $to_stack_v = value;
+ cold_err!(stack.$stack.push($to_stack))?;
+ Ok(())
+ }
+
+ #[inline(always)]
fn stack_pop(stack: &mut ValueStack) -> Self {
let $from_stack_v = stack.$stack.pop();
$from_stack
@@ -232,6 +245,105 @@ impl_internalvalue! {
stack_128, s128, get_128, set_128, Value128, |v| v, |v| v
}
+pub(crate) trait BinOpExt<T>: Copy {
+ fn exec(self, lhs: T, rhs: T) -> T;
+}
+
+impl BinOpExt<Value32> for BinOp {
+ #[inline(always)]
+ fn exec(self, lhs: Value32, rhs: Value32) -> Value32 {
+ match self {
+ BinOp::IAdd => lhs.wrapping_add(rhs),
+ BinOp::ISub => lhs.wrapping_sub(rhs),
+ BinOp::IMul => lhs.wrapping_mul(rhs),
+ BinOp::IAnd => lhs & rhs,
+ BinOp::IOr => lhs | rhs,
+ BinOp::IXor => lhs ^ rhs,
+ BinOp::IShl => (lhs as i32).wrapping_shl(rhs) as u32,
+ BinOp::IShrS => (lhs as i32).wrapping_shr(rhs) as u32,
+ BinOp::IShrU => lhs.wrapping_shr(rhs),
+ BinOp::IRotl => (lhs as i32).rotate_left(rhs) as u32,
+ BinOp::IRotr => (lhs as i32).rotate_right(rhs) as u32,
+ BinOp::FAdd => (f32::from_bits(lhs) + f32::from_bits(rhs)).to_bits(),
+ BinOp::FSub => (f32::from_bits(lhs) - f32::from_bits(rhs)).to_bits(),
+ BinOp::FMul => (f32::from_bits(lhs) * f32::from_bits(rhs)).to_bits(),
+ BinOp::FDiv => (f32::from_bits(lhs) / f32::from_bits(rhs)).to_bits(),
+ BinOp::FMin => f32::from_bits(lhs).tw_minimum(f32::from_bits(rhs)).to_bits(),
+ BinOp::FMax => f32::from_bits(lhs).tw_maximum(f32::from_bits(rhs)).to_bits(),
+ BinOp::FCopysign => f32::from_bits(lhs).copysign(f32::from_bits(rhs)).to_bits(),
+ }
+ }
+}
+
+impl BinOpExt<Value64> for BinOp {
+ #[inline(always)]
+ fn exec(self, lhs: Value64, rhs: Value64) -> Value64 {
+ match self {
+ BinOp::IAdd => lhs.wrapping_add(rhs),
+ BinOp::ISub => lhs.wrapping_sub(rhs),
+ BinOp::IMul => lhs.wrapping_mul(rhs),
+ BinOp::IAnd => lhs & rhs,
+ BinOp::IOr => lhs | rhs,
+ BinOp::IXor => lhs ^ rhs,
+ BinOp::IShl => (lhs as i64).wrapping_shl(rhs as u32) as u64,
+ BinOp::IShrS => (lhs as i64).wrapping_shr(rhs as u32) as u64,
+ BinOp::IShrU => lhs.wrapping_shr(rhs as u32),
+ BinOp::IRotl => (lhs as i64).rotate_left(rhs as u32) as u64,
+ BinOp::IRotr => (lhs as i64).rotate_right(rhs as u32) as u64,
+ BinOp::FAdd => (f64::from_bits(lhs) + f64::from_bits(rhs)).to_bits(),
+ BinOp::FSub => (f64::from_bits(lhs) - f64::from_bits(rhs)).to_bits(),
+ BinOp::FMul => (f64::from_bits(lhs) * f64::from_bits(rhs)).to_bits(),
+ BinOp::FDiv => (f64::from_bits(lhs) / f64::from_bits(rhs)).to_bits(),
+ BinOp::FMin => f64::from_bits(lhs).tw_minimum(f64::from_bits(rhs)).to_bits(),
+ BinOp::FMax => f64::from_bits(lhs).tw_maximum(f64::from_bits(rhs)).to_bits(),
+ BinOp::FCopysign => f64::from_bits(lhs).copysign(f64::from_bits(rhs)).to_bits(),
+ }
+ }
+}
+
+impl BinOpExt<Value128> for BinOp128 {
+ #[inline(always)]
+ fn exec(self, lhs: Value128, rhs: Value128) -> Value128 {
+ match self {
+ BinOp128::And => lhs.v128_and(rhs),
+ BinOp128::AndNot => lhs.v128_andnot(rhs),
+ BinOp128::Or => lhs.v128_or(rhs),
+ BinOp128::Xor => lhs.v128_xor(rhs),
+ BinOp128::I64x2Add => lhs.i64x2_add(rhs),
+ BinOp128::I64x2Mul => lhs.i64x2_mul(rhs),
+ }
+ }
+}
+
+pub(crate) trait CmpOpExt<T>: Copy {
+ fn cmp(self, lhs: T, rhs: T) -> bool;
+}
+
+macro_rules! impl_cmp_value {
+ ($ty:ty, $unsigned:ty) => {
+ impl CmpOpExt<$ty> for CmpOp {
+ #[inline(always)]
+ fn cmp(self, lhs: $ty, rhs: $ty) -> bool {
+ match self {
+ CmpOp::Eq => lhs == rhs,
+ CmpOp::Ne => lhs != rhs,
+ CmpOp::LtS => lhs < rhs,
+ CmpOp::LtU => (lhs as $unsigned) < (rhs as $unsigned),
+ CmpOp::GtS => lhs > rhs,
+ CmpOp::GtU => (lhs as $unsigned) > (rhs as $unsigned),
+ CmpOp::LeS => lhs <= rhs,
+ CmpOp::LeU => (lhs as $unsigned) <= (rhs as $unsigned),
+ CmpOp::GeS => lhs >= rhs,
+ CmpOp::GeU => (lhs as $unsigned) >= (rhs as $unsigned),
+ }
+ }
+ }
+ };
+}
+
+impl_cmp_value!(i32, u32);
+impl_cmp_value!(i64, u64);
+
#[cfg(test)]
mod tests {
use super::ValueRef;
diff --git a/crates/tinywasm/src/macros.rs b/crates/tinywasm/src/macros.rs
index 351ae88..b071259 100644
--- a/crates/tinywasm/src/macros.rs
+++ b/crates/tinywasm/src/macros.rs
@@ -16,3 +16,21 @@ macro_rules! cold_err {
}
};
}
+
+macro_rules! unwrap_or_unreachable {
+ ($value:expr) => {{
+ unwrap_or_unreachable!($value, "entered unreachable code")
+ }};
+ ($value:expr, $($message:tt)+) => {{
+ match $value {
+ Some(value) => value,
+ None => $crate::macros::unwrap_unreachable(format_args!($($message)+)),
+ }
+ }};
+}
+
+#[cold]
+#[inline(never)]
+pub(crate) fn unwrap_unreachable(message: core::fmt::Arguments<'_>) -> ! {
+ unreachable!("{message}")
+}
diff --git a/crates/tinywasm/src/store/global.rs b/crates/tinywasm/src/store/global.rs
index 4052eb8..42a2acf 100644
--- a/crates/tinywasm/src/store/global.rs
+++ b/crates/tinywasm/src/store/global.rs
@@ -30,16 +30,16 @@ impl<T: Copy> GlobalLane<T> {
#[inline(always)]
fn get(&self, index: usize, addr: GlobalAddr) -> T {
- *self.values.get(index).unwrap_or_else(|| unreachable!("invalid global address: {addr}"))
+ *unwrap_or_unreachable!(self.values.get(index), "invalid global address: {addr}")
}
#[inline(always)]
fn set(&mut self, index: usize, addr: GlobalAddr, value: T) {
- *self.values.get_mut(index).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) = value;
+ *unwrap_or_unreachable!(self.values.get_mut(index), "invalid global address: {addr}") = value;
}
fn ty(&self, index: usize, addr: GlobalAddr) -> GlobalType {
- *self.types.get(index).unwrap_or_else(|| unreachable!("invalid global address: {addr}"))
+ *unwrap_or_unreachable!(self.types.get(index), "invalid global address: {addr}")
}
}
diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs
index 93e62a5..d4c8b15 100644
--- a/crates/tinywasm/src/store/mod.rs
+++ b/crates/tinywasm/src/store/mod.rs
@@ -489,15 +489,14 @@ impl Store {
}
/// Reads typed results from the value stack and restores its previous base.
+ #[inline]
pub(crate) fn take_typed_results<R: FromWasmValues>(
&mut self,
type_addr: TypeAddr,
stack_base: StackBase,
) -> Result<R> {
- let result = {
- let mut values = self.stack_value_iter(type_addr, FuncValueTypes::Results, stack_base)?;
- R::from_wasm_values_exact(&mut values)
- };
+ let mut values = cold_err!(self.stack_value_iter(type_addr, FuncValueTypes::Results, stack_base))?;
+ let result = cold_err!(R::from_wasm_values_exact(&mut values));
self.value_stack.truncate_to_base(stack_base);
result
}
diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs
index 769fc8b..49efcdc 100644
--- a/crates/tinywasm/src/store/state.rs
+++ b/crates/tinywasm/src/store/state.rs
@@ -284,11 +284,11 @@ impl State {
}
pub(super) fn get<'a, T>(items: &'a [T], addr: Addr, kind: &str) -> &'a T {
- items.get(addr as usize).unwrap_or_else(|| unreachable!("invalid {kind} address: {addr}"))
+ unwrap_or_unreachable!(items.get(addr as usize), "invalid {kind} address: {addr}")
}
fn get_mut<'a, T>(items: &'a mut [T], addr: Addr, kind: &str) -> &'a mut T {
- items.get_mut(addr as usize).unwrap_or_else(|| unreachable!("invalid {kind} address: {addr}"))
+ unwrap_or_unreachable!(items.get_mut(addr as usize), "invalid {kind} address: {addr}")
}
fn get_disjoint_mut<'a, T>(items: &'a mut [T], addr: Addr, addr2: Addr, kind: &str) -> (&'a mut T, &'a mut T) {
diff --git a/crates/types/src/archive.rs b/crates/types/src/archive.rs
index db13ab0..bdce379 100644
--- a/crates/types/src/archive.rs
+++ b/crates/types/src/archive.rs
@@ -64,11 +64,11 @@ impl Module {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::Operand128Idx;
use crate::{
- AbstractHeapType, ConstInstruction, Global, GlobalType, Instruction, ModuleFuncIdx, ModuleInner, RefType,
- Shared, V128Operand, WasmFunction, WasmType,
+ AbstractHeapType, ConstInstruction, Global, GlobalType, Instruction, ModuleFuncIdx, ModuleInner, Operand128,
+ RefType, Shared, WasmFunction, WasmType,
};
- use crate::{OperandIdx, OperandType};
use alloc::boxed::Box;
#[test]
@@ -91,8 +91,8 @@ mod tests {
fn v128_operands_round_trip_archive() {
let bytes = [0x00, 0x01, 0x02, 0x03, 0x7f, 0x80, 0xfe, 0xff, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x90];
let mut function = WasmFunction::default();
- let constant = OperandIdx::new(0);
- function.data.operands128 = Box::new([V128Operand { value: bytes }.encode()]);
+ let constant = Operand128Idx::new(0);
+ function.data.operands128 = Box::new([Operand128::<[u8; 16]>::new(bytes).cast()]);
function.instructions = Box::new([Instruction::Const128(constant), Instruction::I8x16Shuffle(constant)]);
let module = Module::from(ModuleInner { funcs: Box::new([Shared::new(function)]), ..ModuleInner::default() });
@@ -106,7 +106,7 @@ mod tests {
Instruction::Const128(index) | Instruction::I8x16Shuffle(index) => *index,
_ => panic!("unexpected instruction"),
};
- assert_eq!(index.get(&function.data).value, bytes);
+ assert_eq!(index.resolve(&function.data).value(), bytes);
}
}
diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs
index 7e0cd28..9330af6 100644
--- a/crates/types/src/instructions.rs
+++ b/crates/types/src/instructions.rs
@@ -1,18 +1,31 @@
use alloc::boxed::Box;
use super::{FuncAddr, GlobalAddr, LocalAddr, TableAddr, TagAddr, TypeAddr, ValueCounts};
-use crate::operands::sealed;
-use crate::{DataAddr, ElemAddr, MemAddr, ModuleFuncIdx, Operand64, Operand128, OperandIdx, OperandType, RefType};
+use crate::operands::read_field;
+use crate::{
+ DataAddr, ElemAddr, MemAddr, ModuleFuncIdx, Operand64, Operand64Idx, Operand128, Operand128Idx, OperandIdx, RefType,
+};
-/// Represents a memory immediate in a WebAssembly memory instruction.
-#[derive(Copy, Clone, PartialEq, Eq)]
-#[cfg_attr(feature = "debug", derive(Debug))]
-#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
-#[repr(Rust, packed)]
-pub struct MemoryArg {
- offset: u64,
- mem_addr: MemAddr,
-}
+/// Identifies the packed full-width memory operand layout.
+pub enum MemoryOperand {}
+
+/// Identifies the packed compact memory operand layout.
+pub enum CompactMemoryOperand {}
+
+/// Identifies a packed branch-table operand.
+pub enum BranchTableOperand {}
+
+/// Identifies a packed constant memory-fill operand.
+pub enum MemoryFillOperand {}
+
+/// Identifies a packed local update and branch operand.
+pub enum LocalUpdateOperand {}
+
+/// Identifies a packed global update and branch operand.
+pub enum GlobalUpdateOperand {}
+
+/// Identifies a packed local update, comparison, and branch operand.
+pub enum LocalUpdateCmpOperand {}
/// A compact memory immediate used by optimized instructions.
///
@@ -33,7 +46,7 @@ pub struct CompactMemoryArg {
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
#[repr(Rust, packed)]
pub struct MemoryLocalArg {
- pub memory_arg_idx: OperandIdx<CompactMemoryArg>,
+ pub memory_arg_idx: Operand64Idx<CompactMemoryOperand>,
pub local1: u8,
pub local2: u8,
}
@@ -44,7 +57,7 @@ pub struct MemoryLocalArg {
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
#[repr(Rust, packed)]
pub struct MemoryLaneArg {
- pub memory_arg_idx: OperandIdx<MemoryArg>,
+ pub memory_arg_idx: Operand128Idx<MemoryOperand>,
pub lane: u8,
}
@@ -68,22 +81,6 @@ pub struct LocalTripleArg {
pub dst: LocalAddr,
}
-impl sealed::Sealed for LocalTripleArg {}
-
-impl OperandType for LocalTripleArg {
- type Raw = Operand64;
-
- #[inline(always)]
- fn decode(raw: Self::Raw) -> Self {
- Self { left: raw.u16::<0>(), right: raw.u16::<2>(), dst: raw.u16::<4>() }
- }
-
- #[inline]
- fn encode(self) -> Self::Raw {
- Operand64::default().with_u16::<0>(self.left).with_u16::<2>(self.right).with_u16::<4>(self.dst)
- }
-}
-
/// A branch target and local operand that fit in an instruction payload.
#[derive(Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "debug", derive(Debug))]
@@ -94,194 +91,55 @@ pub struct TargetLocalArg {
pub local: LocalAddr,
}
-macro_rules! operand_view {
- ($name:ident, $lane:ident, $raw:ty, { $($field:ident : $ty:ty = $read:ident / $write:ident ($offset:expr)),+ $(,)? }) => {
- #[derive(Copy, Clone, PartialEq, Eq)]
- #[cfg_attr(feature = "debug", derive(Debug))]
- pub struct $name {
- $(pub $field: $ty),+
- }
-
- impl sealed::Sealed for $name {}
-
- impl OperandType for $name {
- type Raw = $raw;
-
- #[inline(always)]
- fn decode(raw: Self::Raw) -> Self {
- Self { $($field: raw.$read::<$offset>() as $ty),+ }
- }
-
- #[inline]
- fn encode(self) -> Self::Raw {
- <$raw>::default()$(.$write::<$offset>(self.$field as _))+
- }
- }
- };
-}
-
-operand_view!(I64Operand, operands64, Operand64, { value: i64 = u64 / with_u64(0) });
-operand_view!(TwoU32, operands64, Operand64, {
- first: u32 = u32 / with_u32(0), second: u32 = u32 / with_u32(4)
-});
-operand_view!(LocalU32, operands64, Operand64, {
- local: u16 = u16 / with_u16(0), value: u32 = u32 / with_u32(2)
-});
-operand_view!(TargetLocal, operands64, Operand64, {
- target: u32 = u32 / with_u32(0), local: u16 = u16 / with_u16(4)
-});
-
-operand_view!(LocalConst64, operands128, Operand128, {
- local: u16 = u16 / with_u16(0), value: u64 = u64 / with_u64(2)
-});
-operand_view!(GlobalConst32, operands64, Operand64, {
- global: u32 = u32 / with_u32(0), value: u32 = u32 / with_u32(4)
-});
-operand_view!(GlobalConst64, operands128, Operand128, {
- global: u32 = u32 / with_u32(0), value: u64 = u64 / with_u64(4)
-});
-operand_view!(LocalConstSet32, operands64, Operand64, {
- local: u16 = u16 / with_u16(0), dst: u16 = u16 / with_u16(2), value: u32 = u32 / with_u32(4)
-});
-operand_view!(LocalConstSet64, operands128, Operand128, {
- local: u16 = u16 / with_u16(0), dst: u16 = u16 / with_u16(2), value: u64 = u64 / with_u64(4)
-});
-operand_view!(MemoryFillConstOp, operands128, Operand128, {
- memory: u32 = u32 / with_u32(0), byte: u8 = u8 / with_u8(4), value: i32 = u32 / with_u32(5)
-});
-operand_view!(CastBranch, operands64, Operand64, {
- target: u32 = u32 / with_u32(0), ref_type_bits: u32 = u32 / with_u32(4)
-});
-operand_view!(BranchTableArg, operands128, Operand128, {
- target: u32 = u32 / with_u32(0), start: u32 = u32 / with_u32(4), len: u32 = u32 / with_u32(8)
-});
-operand_view!(StackConst32, operands64, Operand64, {
- target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4)
-});
-operand_view!(StackConst64, operands128, Operand128, {
- target: u32 = u32 / with_u32(0), value: i64 = u64 / with_u64(4)
-});
-operand_view!(LocalConstCmp, operands128, Operand128, {
- target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8)
-});
-operand_view!(LocalLocalCmp, operands64, Operand64, {
- target: u32 = u32 / with_u32(0), left: u16 = u16 / with_u16(4), right: u16 = u16 / with_u16(6)
-});
-operand_view!(LocalUpdate, operands128, Operand128, {
- target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8), on_zero: u8 = u8 / with_u8(10)
-});
-operand_view!(GlobalUpdate, operands128, Operand128, {
- target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), global: u32 = u32 / with_u32(8), on_zero: u8 = u8 / with_u8(12)
-});
-operand_view!(LocalUpdateCmp, operands128, Operand128, {
- target: u32 = u32 / with_u32(0), value: i32 = u32 / with_u32(4), local: u16 = u16 / with_u16(8), right: u16 = u16 / with_u16(10)
-});
-
/// An operation packed inline with an indexed operand.
-#[derive(Copy, Clone, PartialEq, Eq)]
-#[cfg_attr(feature = "debug", derive(Debug))]
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "archive",
serde(bound(serialize = "Op: Copy + serde::Serialize", deserialize = "Op: Copy + serde::de::DeserializeOwned",))
)]
#[repr(Rust, packed)]
-pub struct PackedOp<Op, T> {
+pub struct PackedOp<Op, T, const WIDTH: usize> {
pub op: Op,
- pub index: OperandIdx<T>,
+ pub index: OperandIdx<T, WIDTH>,
}
-impl<Op, T> PackedOp<Op, T> {
- /// Creates a packed operation from an operator and operand index.
- #[inline]
- pub const fn new(op: Op, index: OperandIdx<T>) -> Self {
- Self { op, index }
- }
-}
+/// An operation packed with an index into the 64-bit operand lane.
+pub type PackedOp64<Op, T> = PackedOp<Op, T, 8>;
-/// A SIMD value stored in the 128-bit operand lane.
-#[derive(Copy, Clone, PartialEq, Eq)]
-#[cfg_attr(feature = "debug", derive(Debug))]
-pub struct V128Operand {
- pub value: [u8; 16],
-}
+/// An operation packed with an index into the 128-bit operand lane.
+pub type PackedOp128<Op, T> = PackedOp<Op, T, 16>;
-/// A local SIMD operation with an indexed constant.
-#[derive(Copy, Clone, PartialEq, Eq)]
-#[cfg_attr(feature = "debug", derive(Debug))]
-pub struct LocalV128 {
- pub local: u16,
- pub value: OperandIdx<V128Operand>,
-}
+impl<Op: Copy, T, const WIDTH: usize> Copy for PackedOp<Op, T, WIDTH> {}
-/// A global SIMD operation with an indexed constant.
-#[derive(Copy, Clone, PartialEq, Eq)]
-#[cfg_attr(feature = "debug", derive(Debug))]
-pub struct GlobalV128 {
- pub global: u32,
- pub value: OperandIdx<V128Operand>,
+impl<Op: Copy, T, const WIDTH: usize> Clone for PackedOp<Op, T, WIDTH> {
+ fn clone(&self) -> Self {
+ *self
+ }
}
-/// A local SIMD operation, indexed constant, and destination local.
-#[derive(Copy, Clone, PartialEq, Eq)]
-#[cfg_attr(feature = "debug", derive(Debug))]
-pub struct LocalConstSetV128 {
- pub local: u16,
- pub dst: u16,
- pub value: OperandIdx<V128Operand>,
+impl<Op: Copy + PartialEq, T, const WIDTH: usize> PartialEq for PackedOp<Op, T, WIDTH> {
+ fn eq(&self, other: &Self) -> bool {
+ let (op, index) = (self.op, self.index);
+ let (other_op, other_index) = (other.op, other.index);
+ op == other_op && index == other_index
+ }
}
-macro_rules! operand_raw_view {
- ($name:ident, $raw:ty, $decode:expr, $encode:expr) => {
- impl sealed::Sealed for $name {}
-
- impl OperandType for $name {
- type Raw = $raw;
-
- #[inline(always)]
- fn decode(raw: Self::Raw) -> Self {
- $decode(raw)
- }
-
- #[inline]
- fn encode(self) -> Self::Raw {
- $encode(self)
- }
- }
- };
-}
+impl<Op: Copy + Eq, T, const WIDTH: usize> Eq for PackedOp<Op, T, WIDTH> {}
-operand_raw_view!(V128Operand, Operand128, |raw: Operand128| Self { value: raw.to_le_bytes() }, |value: Self| {
- Operand128::from_le_bytes(value.value)
-});
-operand_raw_view!(
- LocalV128,
- Operand64,
- |raw: Operand64| Self { local: raw.u16::<0>(), value: OperandIdx::new(raw.u32::<2>()) },
- |value: Self| { Operand64::default().with_u16::<0>(value.local).with_u32::<2>(value.value.index()) }
-);
-operand_raw_view!(
- GlobalV128,
- Operand64,
- |raw: Operand64| Self { global: raw.u32::<0>(), value: OperandIdx::new(raw.u32::<4>()) },
- |value: Self| { Operand64::default().with_u32::<0>(value.global).with_u32::<4>(value.value.index()) }
-);
-operand_raw_view!(
- LocalConstSetV128,
- Operand64,
- |raw: Operand64| Self { local: raw.u16::<0>(), dst: raw.u16::<2>(), value: OperandIdx::new(raw.u32::<4>()) },
- |value: Self| {
- Operand64::default().with_u16::<0>(value.local).with_u16::<2>(value.dst).with_u32::<4>(value.value.index())
+#[cfg(feature = "debug")]
+impl<Op: Copy + core::fmt::Debug, T, const WIDTH: usize> core::fmt::Debug for PackedOp<Op, T, WIDTH> {
+ fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ let (op, index) = (self.op, self.index);
+ formatter.debug_struct("PackedOp").field("op", &op).field("index", &index).finish()
}
-);
+}
-impl CastBranch {
+impl<Op, T, const WIDTH: usize> PackedOp<Op, T, WIDTH> {
+ /// Creates a packed operation from an operator and operand index.
#[inline]
- pub const fn ref_type(self) -> RefType {
- match RefType::from_bits(self.ref_type_bits) {
- Some(value) => value,
- None => unreachable!(),
- }
+ pub const fn new(op: Op, index: OperandIdx<T, WIDTH>) -> Self {
+ Self { op, index }
}
}
@@ -325,36 +183,163 @@ pub struct ExceptionHandler {
pub catches: Box<[ExceptionCatch]>,
}
-impl MemoryArg {
+impl Operand128<MemoryOperand> {
+ /// Creates a full-width memory operand.
#[inline]
- pub const fn new(offset: u64, mem_addr: MemAddr) -> Self {
- Self { offset, mem_addr }
+ pub fn new(offset: u64, memory: MemAddr) -> Self {
+ let mut operand = Self::default();
+ operand.write_u64::<0>(offset);
+ operand.write_u32::<8>(memory);
+ operand
+ }
+
+ /// Returns the static byte offset.
+ #[inline(always)]
+ pub fn offset(&self) -> u64 {
+ read_field!(self, u64, 0)
}
+ /// Returns the module-local memory index.
+ #[inline(always)]
+ pub fn memory(&self) -> MemAddr {
+ read_field!(self, u32, 8)
+ }
+}
+
+impl Operand64<CompactMemoryOperand> {
+ /// Creates a compact memory operand.
#[inline]
- pub const fn offset(self) -> u64 {
- self.offset
+ pub fn new(offset: u32, memory: u16) -> Self {
+ let mut operand = Self::default();
+ operand.write_u32::<0>(offset);
+ operand.write_u16::<4>(memory);
+ operand
+ }
+
+ /// Returns the static byte offset.
+ #[inline(always)]
+ pub fn offset(&self) -> u32 {
+ read_field!(self, u32, 0)
}
+ /// Returns the module-local memory index.
+ #[inline(always)]
+ pub fn memory(&self) -> u16 {
+ read_field!(self, u16, 4)
+ }
+}
+
+impl Operand128<BranchTableOperand> {
#[inline]
- pub const fn mem_addr(self) -> MemAddr {
- self.mem_addr
+ pub fn new(target: u32, start: u32, len: u32) -> Self {
+ let mut operand = Self::default();
+ operand.write_u32::<0>(target);
+ operand.write_u32::<4>(start);
+ operand.write_u32::<8>(len);
+ operand
+ }
+ #[inline(always)]
+ pub fn start(&self) -> u32 {
+ read_field!(self, u32, 4)
+ }
+ #[inline(always)]
+ pub fn size(&self) -> u32 {
+ read_field!(self, u32, 8)
}
}
-impl sealed::Sealed for MemoryArg {}
+impl Operand128<MemoryFillOperand> {
+ #[inline]
+ pub fn new(memory: MemAddr, byte: u8, value: i32) -> Self {
+ let mut operand = Self::default();
+ operand.write_u32::<0>(memory);
+ operand.write_u8::<4>(byte);
+ operand.write_u32::<5>(value as u32);
+ operand
+ }
+ #[inline(always)]
+ pub fn memory(&self) -> MemAddr {
+ read_field!(self, u32, 0)
+ }
+ #[inline(always)]
+ pub fn byte(&self) -> u8 {
+ read_field!(self, u8, 4)
+ }
+ #[inline(always)]
+ pub fn value(&self) -> i32 {
+ read_field!(self, i32, 5)
+ }
+}
-impl OperandType for MemoryArg {
- type Raw = Operand128;
+impl Operand128<LocalUpdateOperand> {
+ #[inline]
+ pub fn new(target: u32, value: i32, local: LocalAddr, on_zero: bool) -> Self {
+ let mut operand = Self::default();
+ operand.write_u32::<0>(target);
+ operand.write_u32::<4>(value as u32);
+ operand.write_u16::<8>(local);
+ operand.write_u8::<10>(u8::from(on_zero));
+ operand
+ }
+ #[inline(always)]
+ pub fn value(&self) -> i32 {
+ read_field!(self, i32, 4)
+ }
+ #[inline(always)]
+ pub fn local(&self) -> LocalAddr {
+ read_field!(self, u16, 8)
+ }
+ #[inline(always)]
+ pub fn on_zero(&self) -> bool {
+ read_field!(self, u8, 10) != 0
+ }
+}
+impl Operand128<GlobalUpdateOperand> {
+ #[inline]
+ pub fn new(target: u32, value: i32, global: GlobalAddr, on_zero: bool) -> Self {
+ let mut operand = Self::default();
+ operand.write_u32::<0>(target);
+ operand.write_u32::<4>(value as u32);
+ operand.write_u32::<8>(global);
+ operand.write_u8::<12>(u8::from(on_zero));
+ operand
+ }
+ #[inline(always)]
+ pub fn value(&self) -> i32 {
+ read_field!(self, i32, 4)
+ }
#[inline(always)]
- fn decode(raw: Self::Raw) -> Self {
- Self::new(raw.u64::<0>(), raw.u32::<8>())
+ pub fn global(&self) -> GlobalAddr {
+ read_field!(self, u32, 8)
}
+ #[inline(always)]
+ pub fn on_zero(&self) -> bool {
+ read_field!(self, u8, 12) != 0
+ }
+}
+impl Operand128<LocalUpdateCmpOperand> {
#[inline]
- fn encode(self) -> Self::Raw {
- Operand128::default().with_u64::<0>(self.offset).with_u32::<8>(self.mem_addr)
+ pub fn new(target: u32, value: i32, local: LocalAddr, right: LocalAddr) -> Self {
+ let mut operand = Self::default();
+ operand.write_u32::<0>(target);
+ operand.write_u32::<4>(value as u32);
+ operand.write_u16::<8>(local);
+ operand.write_u16::<10>(right);
+ operand
+ }
+ #[inline(always)]
+ pub fn value(&self) -> i32 {
+ read_field!(self, i32, 4)
+ }
+ #[inline(always)]
+ pub fn local(&self) -> LocalAddr {
+ read_field!(self, u16, 8)
+ }
+ #[inline(always)]
+ pub fn right(&self) -> LocalAddr {
+ read_field!(self, u16, 10)
}
}
@@ -372,43 +357,27 @@ impl CompactMemoryArg {
}
}
-impl sealed::Sealed for CompactMemoryArg {}
-
-impl OperandType for CompactMemoryArg {
- type Raw = Operand64;
-
- #[inline(always)]
- fn decode(raw: Self::Raw) -> Self {
- Self { offset: raw.u32::<0>(), mem_addr: raw.u16::<4>() }
- }
-
- #[inline]
- fn encode(self) -> Self::Raw {
- Operand64::default().with_u32::<0>(self.offset).with_u16::<4>(self.mem_addr)
- }
-}
-
-impl TryFrom<MemoryArg> for CompactMemoryArg {
+impl TryFrom<Operand128<MemoryOperand>> for CompactMemoryArg {
type Error = ();
#[inline]
- fn try_from(arg: MemoryArg) -> Result<Self, Self::Error> {
+ fn try_from(arg: Operand128<MemoryOperand>) -> Result<Self, Self::Error> {
Ok(Self {
offset: u32::try_from(arg.offset()).map_err(|_| ())?,
- mem_addr: u16::try_from(arg.mem_addr()).map_err(|_| ())?,
+ mem_addr: u16::try_from(arg.memory()).map_err(|_| ())?,
})
}
}
-impl From<CompactMemoryArg> for MemoryArg {
+impl From<CompactMemoryArg> for Operand64<CompactMemoryOperand> {
#[inline]
fn from(arg: CompactMemoryArg) -> Self {
- Self::new(arg.offset(), arg.mem_addr())
+ Self::new(arg.offset, arg.mem_addr)
}
}
const _: () = {
- assert!(core::mem::size_of::<OperandIdx<I64Operand>>() == 4);
+ assert!(core::mem::size_of::<Operand64Idx<i64>>() == 4);
assert!(core::mem::size_of::<Operand64>() == 8);
assert!(core::mem::size_of::<Operand128>() == 16);
assert!(core::mem::size_of::<CompactMemoryArg>() == 6);
@@ -542,28 +511,28 @@ pub enum BinOp128 {
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
pub enum Instruction {
LocalCopy32(LocalAddr, LocalAddr), LocalCopy64(LocalAddr, LocalAddr), LocalCopy128(LocalAddr, LocalAddr),
- AddConst32(i32), AddConst64(OperandIdx<I64Operand>),
- IncLocal32(I32LocalArg), IncLocal64(PackedOp<LocalAddr, I64Operand>),
+ AddConst32(i32), AddConst64(Operand64Idx<i64>),
+ IncLocal32(I32LocalArg), IncLocal64(PackedOp64<LocalAddr, i64>),
// The 32/64 suffix describes the operand width. Future compare-style ops may still yield i32 results.
BinOpLocalLocal32(BinOp, LocalAddr, LocalAddr), BinOpLocalLocal64(BinOp, LocalAddr, LocalAddr),
BinOpLocalLocal128(BinOp128, LocalAddr, LocalAddr),
CmpLocalLocal32(CmpOp, LocalAddr, LocalAddr), CmpLocalLocal64(CmpOp, LocalAddr, LocalAddr),
AddLocalLocalSet32(LocalTripleArg), AddLocalLocalTee32(LocalTripleArg),
- BinOpLocalLocalSet32(PackedOp<BinOp, LocalTripleArg>), BinOpLocalLocalSet64(PackedOp<BinOp, LocalTripleArg>), BinOpLocalLocalSet128(PackedOp<BinOp128, LocalTripleArg>),
- BinOpLocalLocalTee32(PackedOp<BinOp, LocalTripleArg>), BinOpLocalLocalTee64(PackedOp<BinOp, LocalTripleArg>), BinOpLocalLocalTee128(PackedOp<BinOp128, LocalTripleArg>),
+ BinOpLocalLocalSet32(PackedOp64<BinOp, (u16, u16, u16)>), BinOpLocalLocalSet64(PackedOp64<BinOp, (u16, u16, u16)>), BinOpLocalLocalSet128(PackedOp64<BinOp128, (u16, u16, u16)>),
+ BinOpLocalLocalTee32(PackedOp64<BinOp, (u16, u16, u16)>), BinOpLocalLocalTee64(PackedOp64<BinOp, (u16, u16, u16)>), BinOpLocalLocalTee128(PackedOp64<BinOp128, (u16, u16, u16)>),
AddLocalConst32(I32LocalArg), SubLocalConst32(I32LocalArg), MulLocalConst32(I32LocalArg),
- BinOpLocalConst32(PackedOp<BinOp, LocalU32>), BinOpLocalConst64(PackedOp<BinOp, LocalConst64>),
- BinOpGlobalConst32(PackedOp<BinOp, GlobalConst32>), BinOpGlobalConst64(PackedOp<BinOp, GlobalConst64>),
- BinOpGlobalConst128(PackedOp<BinOp128, GlobalV128>), BinOpLocalConst128(PackedOp<BinOp128, LocalV128>),
- BinOpLocalConstSet32(PackedOp<BinOp, LocalConstSet32>), BinOpLocalConstSet64(PackedOp<BinOp, LocalConstSet64>), BinOpLocalConstSet128(PackedOp<BinOp128, LocalConstSetV128>),
- BinOpLocalConstTee32(PackedOp<BinOp, LocalConstSet32>), BinOpLocalConstTee64(PackedOp<BinOp, LocalConstSet64>), BinOpLocalConstTee128(PackedOp<BinOp128, LocalConstSetV128>),
+ BinOpLocalConst32(PackedOp64<BinOp, (u16, u32)>), BinOpLocalConst64(PackedOp128<BinOp, (u16, u64)>),
+ BinOpGlobalConst32(PackedOp64<BinOp, (u32, u32)>), BinOpGlobalConst64(PackedOp128<BinOp, (u32, u64)>),
+ BinOpGlobalConst128(PackedOp64<BinOp128, (u32, Operand128Idx<[u8; 16]>)>), BinOpLocalConst128(PackedOp64<BinOp128, (u16, Operand128Idx<[u8; 16]>)>),
+ BinOpLocalConstSet32(PackedOp64<BinOp, (u16, u16, u32)>), BinOpLocalConstSet64(PackedOp128<BinOp, (u16, u16, u64)>), BinOpLocalConstSet128(PackedOp64<BinOp128, (u16, u16, Operand128Idx<[u8; 16]>)>),
+ BinOpLocalConstTee32(PackedOp64<BinOp, (u16, u16, u32)>), BinOpLocalConstTee64(PackedOp128<BinOp, (u16, u16, u64)>), BinOpLocalConstTee128(PackedOp64<BinOp128, (u16, u16, Operand128Idx<[u8; 16]>)>),
BinOpStackLocal32(BinOp, LocalAddr),
BinOpStackLocalSet32(BinOp, LocalAddr, LocalAddr),
BinOpStackLocalTee32(BinOp, LocalAddr, LocalAddr),
BinOpStackLocal128(BinOp128, LocalAddr),
BinOpStackGlobal32(BinOp, u32),
BinOpStackGlobal64(BinOp, u32),
- SetLocalConst32(I32LocalArg), SetLocalConst64(PackedOp<LocalAddr, I64Operand>), SetLocalConst128(PackedOp<LocalAddr, V128Operand>),
+ SetLocalConst32(I32LocalArg), SetLocalConst64(PackedOp64<LocalAddr, i64>), SetLocalConst128(PackedOp128<LocalAddr, [u8; 16]>),
IncMemoryLocal32(MemoryLocalArg), IncMemoryLocal64(MemoryLocalArg),
StoreLocalLocal32(MemoryLocalArg), StoreLocalLocal64(MemoryLocalArg), StoreLocalLocal128(MemoryLocalArg),
LoadLocal32(MemoryLocalArg), LoadLocal64(MemoryLocalArg),
@@ -576,7 +545,7 @@ pub enum Instruction {
LoadLocalSet16S32(MemoryLocalArg), LoadLocalSet16U32(MemoryLocalArg),
LoadLocalTee128(MemoryLocalArg), LoadLocalSet128(MemoryLocalArg),
AndConstTee32(I32LocalArg), SubConstTee32(I32LocalArg),
- AndConstTee64(PackedOp<LocalAddr, I64Operand>), SubConstTee64(PackedOp<LocalAddr, I64Operand>),
+ AndConstTee64(PackedOp64<LocalAddr, i64>), SubConstTee64(PackedOp64<LocalAddr, i64>),
MulAccLocal32(LocalAddr), MulAccLocal64(LocalAddr),
FMulAccLocal32(LocalAddr), FMulAccLocal64(LocalAddr),
I32Add3,
@@ -596,14 +565,14 @@ pub enum Instruction {
JumpIfRefNonNull(u32),
JumpIfLocalZero32(TargetLocalArg), JumpIfLocalNonZero32(TargetLocalArg),
JumpIfLocalZero64(TargetLocalArg), JumpIfLocalNonZero64(TargetLocalArg),
- JumpCmpStackConst32(PackedOp<CmpOp, StackConst32>), JumpCmpStackConst64(PackedOp<CmpOp, StackConst64>),
- JumpCmpStackLocal32(PackedOp<CmpOp, TargetLocal>), JumpCmpStackLocal64(PackedOp<CmpOp, TargetLocal>),
- BinOpLocalConstJump32(PackedOp<BinOp, LocalUpdate>), BinOpLocalConstJumpCmpLocal32(PackedOp<(BinOp, CmpOp), LocalUpdateCmp>),
- BinOpStackConstTeeLocalJump32(PackedOp<BinOp, LocalUpdate>), BinOpGlobalConstJump32(PackedOp<BinOp, GlobalUpdate>),
- IncLocalJump32(OperandIdx<LocalUpdate>), IncStackTeeLocalJump32(OperandIdx<LocalUpdate>), IncGlobalJump32(OperandIdx<GlobalUpdate>),
- IncLocalJumpCmpLocal32(PackedOp<CmpOp, LocalUpdateCmp>), JumpCmpLocalConst32(PackedOp<CmpOp, LocalConstCmp>), JumpCmpLocalConst64(PackedOp<CmpOp, LocalConstCmp>),
- JumpCmpLocalLocal32(PackedOp<CmpOp, LocalLocalCmp>), JumpCmpLocalLocal64(PackedOp<CmpOp, LocalLocalCmp>),
- DropKeep32 { base: u16, keep: u16 }, DropKeep64 { base: u16, keep: u16 }, DropKeep128 { base: u16, keep: u16 }, BranchTable(OperandIdx<BranchTableArg>),
+ JumpCmpStackConst32(PackedOp64<CmpOp, (u32, i32)>), JumpCmpStackConst64(PackedOp128<CmpOp, (u32, i64)>),
+ JumpCmpStackLocal32(PackedOp64<CmpOp, (u32, u16)>), JumpCmpStackLocal64(PackedOp64<CmpOp, (u32, u16)>),
+ BinOpLocalConstJump32(PackedOp128<BinOp, LocalUpdateOperand>), BinOpLocalConstJumpCmpLocal32(PackedOp128<(BinOp, CmpOp), LocalUpdateCmpOperand>),
+ BinOpStackConstTeeLocalJump32(PackedOp128<BinOp, LocalUpdateOperand>), BinOpGlobalConstJump32(PackedOp128<BinOp, GlobalUpdateOperand>),
+ IncLocalJump32(Operand128Idx<LocalUpdateOperand>), IncStackTeeLocalJump32(Operand128Idx<LocalUpdateOperand>), IncGlobalJump32(Operand128Idx<GlobalUpdateOperand>),
+ IncLocalJumpCmpLocal32(PackedOp128<CmpOp, LocalUpdateCmpOperand>), JumpCmpLocalConst32(PackedOp128<CmpOp, (u32, i32, u16)>), JumpCmpLocalConst64(PackedOp128<CmpOp, (u32, i32, u16)>),
+ JumpCmpLocalLocal32(PackedOp64<CmpOp, (u32, u16, u16)>), JumpCmpLocalLocal64(PackedOp64<CmpOp, (u32, u16, u16)>),
+ DropKeep32 { base: u16, keep: u16 }, DropKeep64 { base: u16, keep: u16 }, DropKeep128 { base: u16, keep: u16 }, BranchTable(Operand128Idx<BranchTableOperand>),
Return,
ReturnVoid,
Return32,
@@ -611,11 +580,11 @@ pub enum Instruction {
Return128,
Call(FuncAddr),
CallSelf,
- CallIndirect(OperandIdx<TwoU32>),
+ CallIndirect(Operand64Idx<(u32, u32)>),
CallRef(TypeAddr),
ReturnCall(FuncAddr),
ReturnCallSelf,
- ReturnCallIndirect(OperandIdx<TwoU32>),
+ ReturnCallIndirect(Operand64Idx<(u32, u32)>),
ReturnCallRef(TypeAddr),
Throw(TagAddr),
ThrowRef,
@@ -634,18 +603,18 @@ pub enum Instruction {
GlobalGet128(GlobalAddr), GlobalSet128(GlobalAddr), GlobalTee128(GlobalAddr), LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr),
// > Memory Instructions
- I32Load(OperandIdx<MemoryArg>), I64Load(OperandIdx<MemoryArg>), F32Load(OperandIdx<MemoryArg>), F64Load(OperandIdx<MemoryArg>),
- I32Load8S(OperandIdx<MemoryArg>), I32Load8U(OperandIdx<MemoryArg>), I32Load16S(OperandIdx<MemoryArg>), I32Load16U(OperandIdx<MemoryArg>),
- I64Load8S(OperandIdx<MemoryArg>), I64Load8U(OperandIdx<MemoryArg>), I64Load16S(OperandIdx<MemoryArg>), I64Load16U(OperandIdx<MemoryArg>), I64Load32S(OperandIdx<MemoryArg>), I64Load32U(OperandIdx<MemoryArg>),
- I32Store(OperandIdx<MemoryArg>), I64Store(OperandIdx<MemoryArg>), F32Store(OperandIdx<MemoryArg>), F64Store(OperandIdx<MemoryArg>),
- I32Store8(OperandIdx<MemoryArg>), I32Store16(OperandIdx<MemoryArg>), I64Store8(OperandIdx<MemoryArg>), I64Store16(OperandIdx<MemoryArg>), I64Store32(OperandIdx<MemoryArg>),
+ I32Load(Operand128Idx<MemoryOperand>), I64Load(Operand128Idx<MemoryOperand>), F32Load(Operand128Idx<MemoryOperand>), F64Load(Operand128Idx<MemoryOperand>),
+ I32Load8S(Operand128Idx<MemoryOperand>), I32Load8U(Operand128Idx<MemoryOperand>), I32Load16S(Operand128Idx<MemoryOperand>), I32Load16U(Operand128Idx<MemoryOperand>),
+ I64Load8S(Operand128Idx<MemoryOperand>), I64Load8U(Operand128Idx<MemoryOperand>), I64Load16S(Operand128Idx<MemoryOperand>), I64Load16U(Operand128Idx<MemoryOperand>), I64Load32S(Operand128Idx<MemoryOperand>), I64Load32U(Operand128Idx<MemoryOperand>),
+ I32Store(Operand128Idx<MemoryOperand>), I64Store(Operand128Idx<MemoryOperand>), F32Store(Operand128Idx<MemoryOperand>), F64Store(Operand128Idx<MemoryOperand>),
+ I32Store8(Operand128Idx<MemoryOperand>), I32Store16(Operand128Idx<MemoryOperand>), I64Store8(Operand128Idx<MemoryOperand>), I64Store16(Operand128Idx<MemoryOperand>), I64Store32(Operand128Idx<MemoryOperand>),
MemorySize(MemAddr),
MemoryGrow(MemAddr),
// > Constants
Const32(i32),
Const64Imm(i32),
- Const64(OperandIdx<I64Operand>),
+ Const64(Operand64Idx<i64>),
// > Reference Types
RefNull(RefType),
@@ -658,24 +627,24 @@ pub enum Instruction {
RefEq,
RefTest(RefType),
RefCast(RefType),
- BrOnCast(OperandIdx<CastBranch>),
- BrOnCastFail(OperandIdx<CastBranch>),
+ BrOnCast(Operand64Idx<(u32, u32)>),
+ BrOnCastFail(Operand64Idx<(u32, u32)>),
// > GC Objects
StructNew(TypeAddr),
StructNewDefault(TypeAddr),
- StructGet(OperandIdx<TwoU32>), StructGetS(OperandIdx<TwoU32>), StructGetU(OperandIdx<TwoU32>), StructSet(OperandIdx<TwoU32>),
+ StructGet(Operand64Idx<(u32, u32)>), StructGetS(Operand64Idx<(u32, u32)>), StructGetU(Operand64Idx<(u32, u32)>), StructSet(Operand64Idx<(u32, u32)>),
ArrayNew(TypeAddr),
ArrayNewDefault(TypeAddr),
- ArrayNewFixed(OperandIdx<TwoU32>),
- ArrayNewData(OperandIdx<TwoU32>), ArrayNewElem(OperandIdx<TwoU32>),
+ ArrayNewFixed(Operand64Idx<(u32, u32)>),
+ ArrayNewData(Operand64Idx<(u32, u32)>), ArrayNewElem(Operand64Idx<(u32, u32)>),
ArrayGet(TypeAddr),
ArrayGetS(TypeAddr),
ArrayGetU(TypeAddr),
ArraySet(TypeAddr),
ArrayLen,
ArrayFill(TypeAddr),
- ArrayCopy(OperandIdx<TwoU32>), ArrayInitData(OperandIdx<TwoU32>), ArrayInitElem(OperandIdx<TwoU32>),
+ ArrayCopy(Operand64Idx<(u32, u32)>), ArrayInitData(Operand64Idx<(u32, u32)>), ArrayInitElem(Operand64Idx<(u32, u32)>),
// > Numeric Instructions
// See <https://webassembly.github.io/spec/core/binary/instructions.html#numeric-instructions>
@@ -705,18 +674,18 @@ pub enum Instruction {
I64TruncSatF32S, I64TruncSatF32U, I64TruncSatF64S, I64TruncSatF64U,
// > Table Instructions
- TableInit(OperandIdx<TwoU32>),
+ TableInit(Operand64Idx<(u32, u32)>),
TableGet(TableAddr),
TableSet(TableAddr),
- TableCopy(OperandIdx<TwoU32>),
+ TableCopy(Operand64Idx<(u32, u32)>),
TableGrow(TableAddr),
TableSize(TableAddr),
TableFill(TableAddr),
// > Bulk Memory Instructions
- MemoryInit(OperandIdx<TwoU32>), MemoryCopy(OperandIdx<TwoU32>),
+ MemoryInit(Operand64Idx<(u32, u32)>), MemoryCopy(Operand64Idx<(u32, u32)>),
MemoryFill(MemAddr),
- MemoryFillConst(OperandIdx<MemoryFillConstOp>),
+ MemoryFillConst(Operand128Idx<MemoryFillOperand>),
DataDrop(DataAddr),
ElemDrop(ElemAddr),
@@ -724,18 +693,18 @@ pub enum Instruction {
I64Add128, I64Sub128, I64MulWideS, I64MulWideU,
// > SIMD
- V128Load(OperandIdx<MemoryArg>), V128Load8x8S(OperandIdx<MemoryArg>), V128Load8x8U(OperandIdx<MemoryArg>),
- V128Load16x4S(OperandIdx<MemoryArg>), V128Load16x4U(OperandIdx<MemoryArg>), V128Load32x2S(OperandIdx<MemoryArg>), V128Load32x2U(OperandIdx<MemoryArg>),
+ V128Load(Operand128Idx<MemoryOperand>), V128Load8x8S(Operand128Idx<MemoryOperand>), V128Load8x8U(Operand128Idx<MemoryOperand>),
+ V128Load16x4S(Operand128Idx<MemoryOperand>), V128Load16x4U(Operand128Idx<MemoryOperand>), V128Load32x2S(Operand128Idx<MemoryOperand>), V128Load32x2U(Operand128Idx<MemoryOperand>),
- V128Load8Splat(OperandIdx<MemoryArg>), V128Load16Splat(OperandIdx<MemoryArg>), V128Load32Splat(OperandIdx<MemoryArg>), V128Load64Splat(OperandIdx<MemoryArg>),
+ V128Load8Splat(Operand128Idx<MemoryOperand>), V128Load16Splat(Operand128Idx<MemoryOperand>), V128Load32Splat(Operand128Idx<MemoryOperand>), V128Load64Splat(Operand128Idx<MemoryOperand>),
V128Load8Lane(MemoryLaneArg), V128Load16Lane(MemoryLaneArg), V128Load32Lane(MemoryLaneArg), V128Load64Lane(MemoryLaneArg),
- V128Load32Zero(OperandIdx<MemoryArg>), V128Load64Zero(OperandIdx<MemoryArg>),
+ V128Load32Zero(Operand128Idx<MemoryOperand>), V128Load64Zero(Operand128Idx<MemoryOperand>),
- V128Store(OperandIdx<MemoryArg>), V128Store8Lane(MemoryLaneArg), V128Store16Lane(MemoryLaneArg), V128Store32Lane(MemoryLaneArg), V128Store64Lane(MemoryLaneArg),
+ V128Store(Operand128Idx<MemoryOperand>), V128Store8Lane(MemoryLaneArg), V128Store16Lane(MemoryLaneArg), V128Store32Lane(MemoryLaneArg), V128Store64Lane(MemoryLaneArg),
- I8x16Shuffle(OperandIdx<V128Operand>),
- Const128Imm(u32), Const128(OperandIdx<V128Operand>),
+ I8x16Shuffle(Operand128Idx<[u8; 16]>),
+ Const128Imm(u32), Const128(Operand128Idx<[u8; 16]>),
I8x16ExtractLaneS(u8), I8x16ExtractLaneU(u8), I8x16ReplaceLane(u8),
I16x8ExtractLaneS(u8), I16x8ExtractLaneU(u8), I16x8ReplaceLane(u8),
@@ -794,6 +763,8 @@ pub enum Instruction {
I16x8RelaxedQ15mulrS,
I16x8RelaxedDotI8x16I7x16S,
I32x4RelaxedDotI8x16I7x16AddS,
+
+ SelectStore32(Operand128Idx<MemoryOperand>), SelectStore64(Operand128Idx<MemoryOperand>),
}
const _: () = assert!(core::mem::size_of::<Instruction>() == 8);
@@ -814,43 +785,40 @@ mod tests {
#[test]
fn operand_lanes_round_trip_max_values() {
- let memory = MemoryArg::new(u64::MAX, u32::MAX);
- assert_eq!(MemoryArg::decode(memory.encode()), memory);
-
- let value = Operand128::default()
- .with_u8::<0>(u8::MAX)
- .with_u16::<1>(u16::MAX)
- .with_u32::<3>(u32::MAX)
- .with_u64::<7>(u64::MAX);
- assert_eq!(
- (value.u8::<0>(), value.u16::<1>(), value.u32::<3>(), value.u64::<7>()),
- (u8::MAX, u16::MAX, u32::MAX, u64::MAX)
- );
+ let memory = Operand128::<MemoryOperand>::new(u64::MAX, u32::MAX);
+ assert_eq!(memory.offset(), u64::MAX);
+ assert_eq!(memory.memory(), u32::MAX);
- let bytes = [u8::MAX; 16];
- assert_eq!(Operand128::from_le_bytes(bytes).to_le_bytes(), bytes);
+ let value = Operand128::<LocalUpdateOperand>::new(u32::MAX, i32::MIN, u16::MAX, true);
+ assert_eq!(value.target(), u32::MAX);
+ assert_eq!(value.value(), i32::MIN);
+ assert_eq!(value.local(), u16::MAX);
+ assert!(value.on_zero());
}
#[test]
fn v128_operand_views_round_trip_max_bytes() {
- let value = OperandIdx::<V128Operand>::new(0);
- let local = OperandIdx::<LocalV128>::new(0);
- let global = OperandIdx::<GlobalV128>::new(1);
- let set = OperandIdx::<LocalConstSetV128>::new(2);
+ let value = Operand128Idx::<[u8; 16]>::new(0);
+ let local = Operand64Idx::<(u16, Operand128Idx<[u8; 16]>)>::new(0);
+ let global = Operand64Idx::<(u32, Operand128Idx<[u8; 16]>)>::new(1);
+ let set = Operand64Idx::<(u16, u16, Operand128Idx<[u8; 16]>)>::new(2);
let data = super::super::WasmFunctionData {
- operands128: vec![V128Operand { value: [u8::MAX; 16] }.encode()].into_boxed_slice(),
+ operands128: vec![Operand128::<[u8; 16]>::new([u8::MAX; 16]).cast()].into_boxed_slice(),
operands64: vec![
- LocalV128 { local: u16::MAX, value }.encode(),
- GlobalV128 { global: u32::MAX, value }.encode(),
- LocalConstSetV128 { local: u16::MAX, dst: u16::MAX, value }.encode(),
+ Operand64::<(u16, Operand128Idx<[u8; 16]>)>::new(u16::MAX, value).cast(),
+ Operand64::<(u32, Operand128Idx<[u8; 16]>)>::new(u32::MAX, value).cast(),
+ Operand64::<(u16, u16, Operand128Idx<[u8; 16]>)>::new(u16::MAX, u16::MAX, value).cast(),
]
.into_boxed_slice(),
..Default::default()
};
- assert_eq!(value.get(&data).value, [u8::MAX; 16]);
- assert_eq!(local.get(&data), LocalV128 { local: u16::MAX, value });
- assert_eq!(global.get(&data), GlobalV128 { global: u32::MAX, value });
- assert_eq!(set.get(&data), LocalConstSetV128 { local: u16::MAX, dst: u16::MAX, value });
+ assert_eq!(value.resolve(&data).value(), [u8::MAX; 16]);
+ assert_eq!((local.resolve(&data).a(), local.resolve(&data).b()), (u16::MAX, value));
+ assert_eq!((global.resolve(&data).a(), global.resolve(&data).b()), (u32::MAX, value));
+ assert_eq!(
+ (set.resolve(&data).a(), set.resolve(&data).b(), set.resolve(&data).c()),
+ (u16::MAX, u16::MAX, value)
+ );
}
}
diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs
index f9f85fa..a3f26f2 100644
--- a/crates/types/src/lib.rs
+++ b/crates/types/src/lib.rs
@@ -133,6 +133,9 @@ pub struct ModuleInner {
/// Corresponds to the `memory` section of the original WebAssembly module.
pub memory_types: Box<[MemoryType]>,
+ /// Whether instantiation should omit unexported local memories that guest code cannot access.
+ pub skip_local_memory_allocation: bool,
+
/// Tag components of the WebAssembly module.
///
/// Corresponds to the `tag` section of the original WebAssembly module.
diff --git a/crates/types/src/operands.rs b/crates/types/src/operands.rs
index 3cc311c..1bc4a28 100644
--- a/crates/types/src/operands.rs
+++ b/crates/types/src/operands.rs
@@ -1,18 +1,22 @@
use core::marker::PhantomData;
-use crate::WasmFunctionData;
-
/// An index into the operand lane used by `T`.
#[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "archive", serde(transparent))]
#[repr(transparent)]
-pub struct OperandIdx<T> {
+pub struct OperandIdx<T, const WIDTH: usize> {
index: u32,
#[cfg_attr(feature = "archive", serde(skip))]
marker: PhantomData<T>,
}
-impl<T> OperandIdx<T> {
+/// An index into the 64-bit operand lane.
+pub type Operand64Idx<T> = OperandIdx<T, 8>;
+
+/// An index into the 128-bit operand lane.
+pub type Operand128Idx<T> = OperandIdx<T, 16>;
+
+impl<T, const WIDTH: usize> OperandIdx<T, WIDTH> {
#[inline]
#[doc(hidden)]
pub const fn new(index: u32) -> Self {
@@ -21,157 +25,329 @@ impl<T> OperandIdx<T> {
/// Returns the underlying lane index.
#[inline]
- pub const fn index(self) -> u32 {
- self.index
- }
-}
-
-impl<T: OperandType> OperandIdx<T> {
- /// Returns the typed operand at this index.
- ///
- /// Panics if the index is outside its statically selected operand lane.
- #[inline(always)]
- pub fn get(self, data: &WasmFunctionData) -> T {
- T::decode(T::Raw::get(data, self.index))
+ pub const fn index(self) -> usize {
+ self.index as usize
}
}
-impl<T> Copy for OperandIdx<T> {}
-
-impl<T> Clone for OperandIdx<T> {
+impl<T, const WIDTH: usize> Copy for OperandIdx<T, WIDTH> {}
+impl<T, const WIDTH: usize> Clone for OperandIdx<T, WIDTH> {
fn clone(&self) -> Self {
*self
}
}
-
-impl<T> PartialEq for OperandIdx<T> {
+impl<T, const WIDTH: usize> PartialEq for OperandIdx<T, WIDTH> {
fn eq(&self, other: &Self) -> bool {
self.index == other.index
}
}
-
-impl<T> Eq for OperandIdx<T> {}
+impl<T, const WIDTH: usize> Eq for OperandIdx<T, WIDTH> {}
#[cfg(feature = "debug")]
-impl<T> core::fmt::Debug for OperandIdx<T> {
+impl<T, const WIDTH: usize> core::fmt::Debug for OperandIdx<T, WIDTH> {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
self.index.fmt(formatter)
}
}
-pub(crate) mod sealed {
- pub trait Sealed {}
-}
-
-/// A typed view stored in one of the per-function operand lanes.
-pub trait OperandType: sealed::Sealed + Copy {
- #[doc(hidden)]
- type Raw: RawOperand;
-
- #[doc(hidden)]
- fn decode(raw: Self::Raw) -> Self;
- #[doc(hidden)]
- fn encode(self) -> Self::Raw;
-}
-
-#[doc(hidden)]
-pub trait RawOperand: sealed::Sealed + Copy {
- fn get(data: &WasmFunctionData, index: u32) -> Self;
-}
-
macro_rules! define_operand {
- ($name:ident, $len:literal, $lane:ident) => {
- #[doc = concat!("Raw fields stored in a per-function ", $len, "-byte operand lane.")]
- #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default)]
- #[cfg_attr(feature = "debug", derive(Debug))]
- #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))]
- #[repr(transparent)]
- pub struct $name([u8; $len]);
-
- impl sealed::Sealed for $name {}
-
- impl RawOperand for $name {
- #[inline(always)]
- fn get(data: &WasmFunctionData, index: u32) -> Self {
- *data.$lane.get(index as usize).unwrap_or_else(|| unreachable!("invalid operand index"))
- }
+ ($name:ident, $len:literal) => {
+ #[doc = concat!("A typed packed ", $len, "-byte operand value.")]
+ #[repr(C)]
+ pub struct $name<T = ()> {
+ pub(crate) bytes: [u8; $len],
+ marker: PhantomData<T>,
}
- impl $name {
- /// Returns the byte at `OFFSET`.
+ #[allow(dead_code)]
+ impl<T> $name<T> {
#[inline]
- pub fn u8<const OFFSET: usize>(self) -> u8 {
+ pub(crate) fn write_u8<const OFFSET: usize>(&mut self, value: u8) {
const { assert!(OFFSET < $len) };
- self.0[OFFSET]
+ self.bytes[OFFSET] = value;
}
- /// Returns the little-endian `u16` at `OFFSET`.
#[inline]
- pub fn u16<const OFFSET: usize>(self) -> u16 {
+ pub(crate) fn write_u16<const OFFSET: usize>(&mut self, value: u16) {
const { assert!(OFFSET + 2 <= $len) };
- u16::from_le_bytes(self.0[OFFSET..OFFSET + 2].try_into().unwrap_or_else(|_| unreachable!()))
+ self.bytes[OFFSET..OFFSET + 2].copy_from_slice(&value.to_le_bytes());
}
- /// Returns the little-endian `u32` at `OFFSET`.
#[inline]
- pub fn u32<const OFFSET: usize>(self) -> u32 {
+ pub(crate) fn write_u32<const OFFSET: usize>(&mut self, value: u32) {
const { assert!(OFFSET + 4 <= $len) };
- u32::from_le_bytes(self.0[OFFSET..OFFSET + 4].try_into().unwrap_or_else(|_| unreachable!()))
+ self.bytes[OFFSET..OFFSET + 4].copy_from_slice(&value.to_le_bytes());
}
- /// Returns the little-endian `u64` at `OFFSET`.
#[inline]
- pub fn u64<const OFFSET: usize>(self) -> u64 {
+ pub(crate) fn write_u64<const OFFSET: usize>(&mut self, value: u64) {
const { assert!(OFFSET + 8 <= $len) };
- u64::from_le_bytes(self.0[OFFSET..OFFSET + 8].try_into().unwrap_or_else(|_| unreachable!()))
+ self.bytes[OFFSET..OFFSET + 8].copy_from_slice(&value.to_le_bytes());
}
- /// Builds an operand from its raw little-endian bytes.
- #[inline]
- pub fn from_le_bytes(value: [u8; $len]) -> Self {
- Self(value)
+ #[inline(always)]
+ #[doc(hidden)]
+ pub fn cast<U>(self) -> $name<U> {
+ $name { bytes: self.bytes, marker: PhantomData }
}
+ }
- /// Returns the raw little-endian bytes.
- #[inline]
- pub fn to_le_bytes(self) -> [u8; $len] {
- self.0
+ impl<T> Copy for $name<T> {}
+ impl<T> Clone for $name<T> {
+ fn clone(&self) -> Self {
+ *self
}
+ }
+ impl<T> PartialEq for $name<T> {
+ fn eq(&self, other: &Self) -> bool {
+ self.bytes == other.bytes
+ }
+ }
+ impl<T> Eq for $name<T> {}
+ impl<T> PartialOrd for $name<T> {
+ fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
+ Some(self.cmp(other))
+ }
+ }
+ impl<T> Ord for $name<T> {
+ fn cmp(&self, other: &Self) -> core::cmp::Ordering {
+ self.bytes.cmp(&other.bytes)
+ }
+ }
+ impl<T> Default for $name<T> {
+ fn default() -> Self {
+ Self { bytes: [0; $len], marker: PhantomData }
+ }
+ }
- /// Writes `value` at `OFFSET` and returns the updated operand.
- #[inline]
- pub fn with_u8<const OFFSET: usize>(mut self, value: u8) -> Self {
- const { assert!(OFFSET < $len) };
- self.0[OFFSET] = value;
- self
+ #[cfg(feature = "debug")]
+ impl<T> core::fmt::Debug for $name<T> {
+ fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ self.bytes.fmt(formatter)
}
+ }
- /// Writes `value` at `OFFSET` and returns the updated operand.
- #[inline]
- pub fn with_u16<const OFFSET: usize>(mut self, value: u16) -> Self {
- const { assert!(OFFSET + 2 <= $len) };
- self.0[OFFSET..OFFSET + 2].copy_from_slice(&value.to_le_bytes());
- self
+ #[cfg(feature = "archive")]
+ impl<T> serde::Serialize for $name<T> {
+ fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
+ where
+ S: serde::Serializer,
+ {
+ self.bytes.serialize(serializer)
}
+ }
- /// Writes `value` at `OFFSET` and returns the updated operand.
- #[inline]
- pub fn with_u32<const OFFSET: usize>(mut self, value: u32) -> Self {
- const { assert!(OFFSET + 4 <= $len) };
- self.0[OFFSET..OFFSET + 4].copy_from_slice(&value.to_le_bytes());
- self
+ #[cfg(feature = "archive")]
+ impl<'de, T> serde::Deserialize<'de> for $name<T> {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ Ok(Self { bytes: <[u8; $len]>::deserialize(deserializer)?, marker: PhantomData })
}
+ }
+ };
+}
+
+define_operand!(Operand64, 8);
+define_operand!(Operand128, 16);
+
+macro_rules! unwrap_or_unreachable {
+ ($value:expr) => {{ unwrap_or_unreachable!($value, "entered unreachable code") }};
+ ($value:expr, $message:literal) => {{
+ match $value {
+ Some(value) => value,
+ None => operand_unreachable($message),
+ }
+ }};
+}
+
+#[cold]
+#[inline(never)]
+pub(crate) fn operand_unreachable(message: &'static str) -> ! {
+ unreachable!("{message}")
+}
- /// Writes `value` at `OFFSET` and returns the updated operand.
+impl<T> Operand64Idx<T> {
+ /// Resolves this index to a copied 64-bit packed operand.
+ #[inline(always)]
+ pub fn resolve(self, data: &crate::WasmFunctionData) -> Operand64<T> {
+ (*unwrap_or_unreachable!(data.operands64.get(self.index()), "invalid 64-bit operand index")).cast()
+ }
+}
+
+impl<T> Operand128Idx<T> {
+ /// Resolves this index to a copied 128-bit packed operand.
+ #[inline(always)]
+ pub fn resolve(self, data: &crate::WasmFunctionData) -> Operand128<T> {
+ (*unwrap_or_unreachable!(data.operands128.get(self.index()), "invalid 128-bit operand index")).cast()
+ }
+}
+
+macro_rules! field_ty {
+ (u8) => { u8 }; (u16) => { u16 }; (u32) => { u32 }; (u64) => { u64 };
+ (i32) => { i32 }; (i64) => { i64 }; (idx128) => { Operand128Idx<[u8; 16]> };
+}
+macro_rules! field_size {
+ (u8) => {{ 1 }};
+ (u16) => {{ 2 }};
+ (u32) => {{ 4 }};
+ (u64) => {{ 8 }};
+ (i32) => {{ 4 }};
+ (i64) => {{ 8 }};
+ (idx128) => {{ 4 }};
+}
+
+macro_rules! read_field {
+ ($self:ident, u8, $offset:expr) => {{ $self.bytes[$offset] }};
+ ($self:ident, u16, $offset:expr) => {{ u16::from_le_bytes($crate::operands::read_bytes!($self, $offset, 2)) }};
+ ($self:ident, u32, $offset:expr) => {{ u32::from_le_bytes($crate::operands::read_bytes!($self, $offset, 4)) }};
+ ($self:ident, u64, $offset:expr) => {{ u64::from_le_bytes($crate::operands::read_bytes!($self, $offset, 8)) }};
+ ($self:ident, i32, $offset:expr) => {{ read_field!($self, u32, $offset) as i32 }};
+ ($self:ident, i64, $offset:expr) => {{ read_field!($self, u64, $offset) as i64 }};
+ ($self:ident, idx128, $offset:expr) => {{ Operand128Idx::new(read_field!($self, u32, $offset)) }};
+}
+pub(crate) use read_field;
+
+macro_rules! read_bytes {
+ ($self:ident, $offset:expr, $len:literal) => {{
+ match <[u8; $len]>::try_from(&$self.bytes[$offset..$offset + $len]) {
+ Ok(bytes) => bytes,
+ Err(_) => $crate::operands::operand_unreachable("invalid operand field"),
+ }
+ }};
+}
+pub(crate) use read_bytes;
+macro_rules! write_field {
+ ($self:ident, u8, $offset:expr, $value:expr) => {{ $self.write_u8::<{ $offset }>($value) }};
+ ($self:ident, u16, $offset:expr, $value:expr) => {{ $self.write_u16::<{ $offset }>($value) }};
+ ($self:ident, u32, $offset:expr, $value:expr) => {{ $self.write_u32::<{ $offset }>($value) }};
+ ($self:ident, u64, $offset:expr, $value:expr) => {{ $self.write_u64::<{ $offset }>($value) }};
+ ($self:ident, i32, $offset:expr, $value:expr) => {{ $self.write_u32::<{ $offset }>($value as u32) }};
+ ($self:ident, i64, $offset:expr, $value:expr) => {{ $self.write_u64::<{ $offset }>($value as u64) }};
+ ($self:ident, idx128, $offset:expr, $value:expr) => {{ $self.write_u32::<{ $offset }>($value.index) }};
+}
+
+impl<T> Operand64<T> {
+ /// Returns the jump target stored at the start of a retargetable operand.
+ #[inline(always)]
+ pub fn target(&self) -> u32 {
+ read_field!(self, u32, 0)
+ }
+
+ /// Replaces the jump target stored at the start of a retargetable operand.
+ #[inline]
+ pub fn with_target(mut self, target: u32) -> Self {
+ self.write_u32::<0>(target);
+ self
+ }
+}
+
+impl<T> Operand128<T> {
+ /// Returns the jump target stored at the start of a retargetable operand.
+ #[inline(always)]
+ pub fn target(&self) -> u32 {
+ read_field!(self, u32, 0)
+ }
+
+ /// Replaces the jump target stored at the start of a retargetable operand.
+ #[inline]
+ pub fn with_target(mut self, target: u32) -> Self {
+ self.write_u32::<0>(target);
+ self
+ }
+}
+
+macro_rules! packed_layout {
+ ($operand:ident, $lane:ident, $field:tt) => {
+ impl $operand<field_ty!($field)> {
#[inline]
- pub fn with_u64<const OFFSET: usize>(mut self, value: u64) -> Self {
- const { assert!(OFFSET + 8 <= $len) };
- self.0[OFFSET..OFFSET + 8].copy_from_slice(&value.to_le_bytes());
- self
+ pub fn new(value: field_ty!($field)) -> Self {
+ let mut operand = Self::default();
+ write_field!(operand, $field, 0, value);
+ operand
+ }
+ #[inline(always)]
+ pub fn value(&self) -> field_ty!($field) {
+ read_field!(self, $field, 0)
+ }
+ }
+ };
+ ($operand:ident, $lane:ident, $a:tt, $b:tt) => {
+ impl $operand<(field_ty!($a), field_ty!($b))> {
+ #[inline]
+ pub fn new(a: field_ty!($a), b: field_ty!($b)) -> Self {
+ let mut operand = Self::default();
+ write_field!(operand, $a, 0, a);
+ write_field!(operand, $b, field_size!($a), b);
+ operand
+ }
+ #[inline(always)]
+ pub fn a(&self) -> field_ty!($a) {
+ read_field!(self, $a, 0)
+ }
+ #[inline(always)]
+ pub fn b(&self) -> field_ty!($b) {
+ read_field!(self, $b, field_size!($a))
+ }
+ }
+ };
+ ($operand:ident, $lane:ident, $a:tt, $b:tt, $c:tt) => {
+ impl $operand<(field_ty!($a), field_ty!($b), field_ty!($c))> {
+ #[inline]
+ pub fn new(a: field_ty!($a), b: field_ty!($b), c: field_ty!($c)) -> Self {
+ let mut operand = Self::default();
+ write_field!(operand, $a, 0, a);
+ write_field!(operand, $b, field_size!($a), b);
+ write_field!(operand, $c, field_size!($a) + field_size!($b), c);
+ operand
+ }
+ #[inline(always)]
+ pub fn a(&self) -> field_ty!($a) {
+ read_field!(self, $a, 0)
+ }
+ #[inline(always)]
+ pub fn b(&self) -> field_ty!($b) {
+ read_field!(self, $b, field_size!($a))
+ }
+ #[inline(always)]
+ pub fn c(&self) -> field_ty!($c) {
+ read_field!(self, $c, field_size!($a) + field_size!($b))
}
}
};
}
-define_operand!(Operand64, 8, operands64);
-define_operand!(Operand128, 16, operands128);
+packed_layout!(Operand64, operands64, i64);
+packed_layout!(Operand64, operands64, u32, u32);
+packed_layout!(Operand64, operands64, u16, u32);
+packed_layout!(Operand64, operands64, u32, u16);
+packed_layout!(Operand64, operands64, u16, u16, u16);
+packed_layout!(Operand64, operands64, u16, u16, u32);
+packed_layout!(Operand64, operands64, u32, i32);
+packed_layout!(Operand64, operands64, u32, u16, u16);
+packed_layout!(Operand64, operands64, u16, idx128);
+packed_layout!(Operand64, operands64, u32, idx128);
+packed_layout!(Operand64, operands64, u16, u16, idx128);
+
+packed_layout!(Operand128, operands128, u16, u64);
+packed_layout!(Operand128, operands128, u32, u64);
+packed_layout!(Operand128, operands128, u16, u16, u64);
+packed_layout!(Operand128, operands128, u32, i64);
+packed_layout!(Operand128, operands128, u32, i32, u16);
+
+impl Operand128<[u8; 16]> {
+ #[inline]
+ pub fn new(value: [u8; 16]) -> Self {
+ Self { bytes: value, marker: PhantomData }
+ }
+ #[inline(always)]
+ pub fn value(&self) -> [u8; 16] {
+ self.bytes
+ }
+}
+const _: () = {
+ assert!(core::mem::size_of::<Operand64Idx<i64>>() == 4);
+ assert!(core::mem::size_of::<Operand64>() == 8);
+ assert!(core::mem::size_of::<Operand128>() == 16);
+};
diff --git a/crates/types/src/reference.rs b/crates/types/src/reference.rs
index 2d725ca..d195a81 100644
--- a/crates/types/src/reference.rs
+++ b/crates/types/src/reference.rs
@@ -69,7 +69,8 @@ impl RefType {
}
#[inline]
- pub(crate) const fn from_bits(bits: u32) -> Option<Self> {
+ #[doc(hidden)]
+ pub const fn from_bits(bits: u32) -> Option<Self> {
let ty = Self(bits);
if ty.is_concrete() || ty.abstract_heap_type().is_some() { Some(ty) } else { None }
}
diff --git a/examples/rust/build.sh b/examples/rust/build.sh
index cbd3b27..873028f 100755
--- a/examples/rust/build.sh
+++ b/examples/rust/build.sh
@@ -12,6 +12,10 @@ wasmopt_features="--enable-simd --enable-relaxed-simd --enable-tail-call --enabl
# ensure out dir exists
mkdir -p "$dest_dir"
+# Keep the embedded archive synchronized with the current archive version and instruction layout.
+cargo run --quiet --manifest-path "../../Cargo.toml" --package tinywasm-cli -- \
+ compile "src/print.wasm" --output "src/print.twasm" --force || exit
+
# build no_std
RUSTFLAGS="-Zlocation-detail=none -Zfmt-debug=none -C target-feature=$rust_features -C panic=abort" cargo build -Z build-std=core,alloc,panic_abort -Z build-std-features="optimize_for_size" --target wasm32-unknown-unknown --package rust-wasm-examples --profile=wasm --bin tinywasm_no_std --no-default-features
cp "$out_dir/tinywasm_no_std.wasm" "$dest_dir/"
diff --git a/examples/rust/src/print.twasm b/examples/rust/src/print.twasm
index 7841329..0fb3f39 100644
--- a/examples/rust/src/print.twasm
+++ b/examples/rust/src/print.twasm
Binary files differ