diff options
| author | Henry <mail@henrygressmann.de> | 2026-08-08 18:30:29 +0200 |
|---|---|---|
| committer | Henry <mail@henrygressmann.de> | 2026-08-08 18:30:29 +0200 |
| commit | 676be92cde66d7c20bfe11d64bfc3f5762c4c46e (patch) | |
| tree | 537702525e0b7d04ca8007c7a53aab8fcfca7050 | |
| parent | d0c74255f9d6c57a243cf34037af0e8f371504b3 (diff) | |
chore: store globals in different lanes based on size
Signed-off-by: Henry <mail@henrygressmann.de>
| -rw-r--r-- | CHANGELOG.md | 5 | ||||
| -rw-r--r-- | crates/parser/src/conversion.rs | 22 | ||||
| -rw-r--r-- | crates/parser/src/macros.rs | 2 | ||||
| -rw-r--r-- | crates/parser/src/optimize.rs | 8 | ||||
| -rw-r--r-- | crates/parser/src/visit.rs | 248 | ||||
| -rw-r--r-- | crates/tinywasm/src/imports.rs | 23 | ||||
| -rw-r--r-- | crates/tinywasm/src/interpreter/executor.rs | 50 | ||||
| -rw-r--r-- | crates/tinywasm/src/interpreter/stack/value_stack.rs | 4 | ||||
| -rw-r--r-- | crates/tinywasm/src/interpreter/values.rs | 40 | ||||
| -rw-r--r-- | crates/tinywasm/src/reference.rs | 34 | ||||
| -rw-r--r-- | crates/tinywasm/src/store/global.rs | 165 | ||||
| -rw-r--r-- | crates/tinywasm/src/store/mod.rs | 18 | ||||
| -rw-r--r-- | crates/tinywasm/src/store/state.rs | 64 | ||||
| -rw-r--r-- | crates/tinywasm/tests/store_ownership.rs | 18 | ||||
| -rw-r--r-- | crates/tinywasm/tests/typed_globals.rs | 93 | ||||
| -rw-r--r-- | crates/types/src/instructions.rs | 7 | ||||
| -rw-r--r-- | crates/types/src/lib.rs | 41 |
17 files changed, 564 insertions, 278 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index 38d4dd8..7ef6fb5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,16 +10,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Added support for the WebAssembly function-references proposal -- Added support for the WebAssembly garbage-collection proposal +- Added basic support for the WebAssembly garbage-collection proposal - Added `WasmValue::ty` and `WasmValue::matches_type` +- Added `ValueLane` for mapping WebAssembly value types to their physical 32-bit, 64-bit, or 128-bit storage lane. - Added a `validate` feature to `tinywasm` and `tinywasm-parser` (enabled by default) to optionally skip wasmparser validation for faster parsing of trusted modules. ### Changed - Module types now use one dense recursive type space, while function types are resolved through `Function::ty(&Store)`. +- Globals are stored in separate 32-bit, 64-bit, and 128-bit value lanes, avoiding tagged value conversion during guest execution. ### Fixed +- Directly defined imports now reject handles from a different `Store`. - Tail calls to host functions now return directly to the caller frame. ### Breaking Changes diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 8bc7df1..4073a8e 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -6,6 +6,14 @@ use alloc::{boxed::Box, format, vec::Vec}; use tinywasm_types::*; use wasmparser::{CompositeInnerType, OperatorsReader, OperatorsReaderAllocations, UnpackedIndex}; +pub(crate) fn value_lane(ty: wasmparser::ValType) -> ValueLane { + match ty { + wasmparser::ValType::I32 | wasmparser::ValType::F32 | wasmparser::ValType::Ref(_) => ValueLane::S32, + wasmparser::ValType::I64 | wasmparser::ValType::F64 => ValueLane::S64, + wasmparser::ValType::V128 => ValueLane::S128, + } +} + pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result<tinywasm_types::Element> { let kind = match element.kind { wasmparser::ElementKind::Active { table_index, offset_expr } => tinywasm_types::ElementKind::Active { @@ -116,12 +124,8 @@ pub(crate) fn convert_module_export(export: wasmparser::Export<'_>) -> Result<Ex Ok(Export { index: export.index, name: Box::from(export.name), kind }) } -fn extend_local_types( - local_types: &mut Vec<crate::visit::OperandSize>, - count: u32, - ty: wasmparser::ValType, -) -> Result<()> { - let size = crate::visit::OperandSize::from(ty); +fn extend_local_types(local_types: &mut Vec<ValueLane>, count: u32, ty: wasmparser::ValType) -> Result<()> { + let size = value_lane(ty); let count = usize::try_from(count).map_err(|_| crate::ParseError::Other("local declaration count is too large".into()))?; local_types.reserve(count); @@ -166,9 +170,9 @@ pub(crate) fn convert_module_code( for ty in &local_types { let (count, error) = match ty { - crate::visit::OperandSize::S32 => (&mut local_counts.c32, "too many 32-bit locals"), - crate::visit::OperandSize::S64 => (&mut local_counts.c64, "too many 64-bit locals"), - crate::visit::OperandSize::S128 => (&mut local_counts.c128, "too many 128-bit locals"), + ValueLane::S32 => (&mut local_counts.c32, "too many 32-bit locals"), + ValueLane::S64 => (&mut local_counts.c64, "too many 64-bit locals"), + ValueLane::S128 => (&mut local_counts.c128, "too many 128-bit locals"), }; local_addr_map.push(*count); *count = count.checked_add(1).ok_or_else(|| crate::ParseError::Other(error.into()))?; diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs index 553f439..db1402d 100644 --- a/crates/parser/src/macros.rs +++ b/crates/parser/src/macros.rs @@ -141,7 +141,7 @@ pub(crate) mod visit { (@size Addr, $address:ident) => { $address }; (@size Field, $address:ident) => { $address }; - (@size $size:ident $(, $address:ident)?) => { OperandSize::$size }; + (@size $size:ident $(, $address:ident)?) => { ValueLane::$size }; } macro_rules! impl_visit_operator { diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs index 5c2d7d5..74a9fc0 100644 --- a/crates/parser/src/optimize.rs +++ b/crates/parser/src/optimize.rs @@ -93,7 +93,7 @@ fn rewrite( rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); rewrite!(instrs, i, [Const32(c), LocalGet32(local)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [GlobalGet(global)] => BinOpStackGlobal32(op, global)); + rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); if matches!(op, BinOp::IAdd) { rewrite!(instrs, i, [Const32(c)] => AddConst32(c)); rewrite!(instrs, i, [I32Add] => I32Add3); @@ -103,7 +103,7 @@ fn rewrite( let Some(op) = int_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet32(a), LocalGet32(b)] => BinOpLocalLocal32(op, a, b)); rewrite!(instrs, i, [LocalGet32(local), Const32(c)] => BinOpLocalConst32(op, local, c)); - rewrite!(instrs, i, [GlobalGet(global)] => BinOpStackGlobal32(op, global)); + rewrite!(instrs, i, [GlobalGet32(global)] => BinOpStackGlobal32(op, global)); if matches!(op, BinOp::IShrS) { rewrite!(instrs, i, [BinOpLocalConst32(BinOp::IShl, local, 8), Const32(8)] => [LocalGet32(local), I32Extend8S]); rewrite!(instrs, i, [BinOpLocalConst32(BinOp::IShl, local, 16), Const32(16)] => [LocalGet32(local), I32Extend16S]); @@ -114,7 +114,7 @@ fn rewrite( rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); rewrite!(instrs, i, [Const64(c), LocalGet64(local)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [GlobalGet(global)] => BinOpStackGlobal64(op, global)); + rewrite!(instrs, i, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); if matches!(op, BinOp::IAdd) { rewrite!(instrs, i, [Const64(c)] => AddConst64(c)); rewrite!(instrs, i, [I64Add] => I64Add3); @@ -124,7 +124,7 @@ fn rewrite( let Some(op) = int_bin_op(instr) else { unreachable!() }; rewrite!(instrs, i, [LocalGet64(a), LocalGet64(b)] => BinOpLocalLocal64(op, a, b)); rewrite!(instrs, i, [LocalGet64(local), Const64(c)] => BinOpLocalConst64(op, local, c)); - rewrite!(instrs, i, [GlobalGet(global)] => BinOpStackGlobal64(op, global)); + rewrite!(instrs, i, [GlobalGet64(global)] => BinOpStackGlobal64(op, global)); if matches!(op, BinOp::IShrS) { rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 8), Const64(8)] => [LocalGet64(local), I64Extend8S]); rewrite!(instrs, i, [BinOpLocalConst64(BinOp::IShl, local, 16), Const64(16)] => [LocalGet64(local), I64Extend16S]); diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index 4437242..46d1f9f 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -1,9 +1,13 @@ -use crate::{Result, conversion::convert_heap_type, macros::visit::*}; +use crate::{ + Result, + conversion::{convert_heap_type, value_lane}, + macros::visit::*, +}; use alloc::string::ToString; use alloc::vec::Vec; use tinywasm_types::{ - Global, Import, ImportKind, Instruction, MemoryArch, MemoryArg, MemoryType, StorageType, SubType, TableDefinition, - TypeSection, ValueCounts, WasmFunctionData, WasmType, + Global, Import, ImportKind, Instruction, MemoryArg, MemoryType, StorageType, SubType, TableDefinition, TypeSection, + ValueCounts, ValueLane, WasmFunctionData, }; use wasmparser::{FunctionBody, OperatorsReader, OperatorsReaderAllocations, VisitSimdOperator}; @@ -18,52 +22,6 @@ enum BlockKind { If, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum OperandSize { - S32, - S64, - S128, -} - -impl OperandSize { - fn choose<T>(self, s32: T, s64: T, s128: T) -> T { - match self { - Self::S32 => s32, - Self::S64 => s64, - Self::S128 => s128, - } - } -} - -impl From<wasmparser::ValType> for OperandSize { - fn from(ty: wasmparser::ValType) -> Self { - match ty { - wasmparser::ValType::I32 | wasmparser::ValType::F32 | wasmparser::ValType::Ref(_) => Self::S32, - wasmparser::ValType::I64 | wasmparser::ValType::F64 => Self::S64, - wasmparser::ValType::V128 => Self::S128, - } - } -} - -impl From<&WasmType> for OperandSize { - fn from(ty: &WasmType) -> Self { - match ty { - WasmType::I32 | WasmType::F32 | WasmType::Ref(_) => Self::S32, - WasmType::I64 | WasmType::F64 => Self::S64, - WasmType::V128 => Self::S128, - } - } -} - -impl From<MemoryArch> for OperandSize { - fn from(arch: MemoryArch) -> Self { - match arch { - MemoryArch::I32 => Self::S32, - MemoryArch::I64 => Self::S64, - } - } -} - struct ControlFrame { kind: BlockKind, has_else: bool, @@ -71,8 +29,8 @@ struct ControlFrame { branch_jumps: Vec<usize>, height: usize, base: ValueCounts, - params: Vec<OperandSize>, - results: Vec<OperandSize>, + params: Vec<ValueLane>, + results: Vec<ValueLane>, unreachable: bool, entry_unreachable: bool, end_reachable: bool, @@ -80,16 +38,16 @@ struct ControlFrame { #[derive(Clone)] pub(crate) struct Signature { - pub params: Vec<OperandSize>, - results: Vec<OperandSize>, + pub params: Vec<ValueLane>, + results: Vec<ValueLane>, } pub(crate) struct ModuleMetadata { signatures: Vec<Option<Signature>>, functions: Vec<u32>, - globals: Vec<OperandSize>, - memories: Vec<OperandSize>, - tables: Vec<OperandSize>, + globals: Vec<ValueLane>, + memories: Vec<ValueLane>, + tables: Vec<ValueLane>, types: Vec<SubType>, } @@ -103,10 +61,10 @@ pub(crate) struct FunctionBuilder<'a> { instructions: Vec<Instruction>, data: FunctionDataBuilder, control_stack: Vec<ControlFrame>, - operand_stack: Vec<OperandSize>, + operand_stack: Vec<ValueLane>, lane_counts: ValueCounts, metadata: &'a ModuleMetadata, - local_types: Vec<OperandSize>, + local_types: Vec<ValueLane>, local_addr_map: Vec<u16>, } @@ -114,7 +72,7 @@ impl<'a> FunctionBuilder<'a> { pub(crate) fn new( metadata: &'a ModuleMetadata, signature: Signature, - local_types: Vec<OperandSize>, + local_types: Vec<ValueLane>, local_addr_map: Vec<u16>, body_size: usize, ) -> Self { @@ -149,7 +107,7 @@ impl<'a> FunctionBuilder<'a> { instruction: fn(u32, u32) -> Instruction, ) -> Result<()> { let size = ModuleMetadata::storage_size(self.metadata.struct_field(type_index, field_index)?.storage); - self.emit(&[OperandSize::S32], &[size], instruction(type_index, field_index)) + self.emit(&[ValueLane::S32], &[size], instruction(type_index, field_index)) } } @@ -161,6 +119,13 @@ struct ValidateThenVisit<'a, 'm> { } impl ModuleMetadata { + fn address_lane(arch: tinywasm_types::MemoryArch) -> ValueLane { + match arch { + tinywasm_types::MemoryArch::I32 => ValueLane::S32, + tinywasm_types::MemoryArch::I64 => ValueLane::S64, + } + } + pub(crate) fn new( types: &TypeSection, code_type_addrs: &[u32], @@ -177,24 +142,24 @@ impl ModuleMetadata { for import in imports { match &import.kind { ImportKind::Function(ty) => functions.push(*ty), - ImportKind::Global(ty) => global_sizes.push(OperandSize::from(&ty.ty)), - ImportKind::Memory(ty) => memory_sizes.push(OperandSize::from(ty.arch())), - ImportKind::Table(ty) => table_sizes.push(OperandSize::from(ty.arch())), + ImportKind::Global(ty) => global_sizes.push(ValueLane::from(&ty.ty)), + ImportKind::Memory(ty) => memory_sizes.push(Self::address_lane(ty.arch())), + ImportKind::Table(ty) => table_sizes.push(Self::address_lane(ty.arch())), } } functions.extend_from_slice(code_type_addrs); - global_sizes.extend(globals.iter().map(|global| OperandSize::from(&global.ty.ty))); - memory_sizes.extend(memories.iter().map(|ty| OperandSize::from(ty.arch()))); - table_sizes.extend(tables.iter().map(|table| OperandSize::from(table.ty.arch()))); + global_sizes.extend(globals.iter().map(|global| ValueLane::from(&global.ty.ty))); + memory_sizes.extend(memories.iter().map(|ty| Self::address_lane(ty.arch()))); + table_sizes.extend(tables.iter().map(|table| Self::address_lane(table.ty.arch()))); let signatures = types .types .iter() .map(|ty| { ty.as_func().map(|ty| Signature { - params: ty.params().iter().map(OperandSize::from).collect(), - results: ty.results().iter().map(OperandSize::from).collect(), + params: ty.params().iter().map(ValueLane::from).collect(), + results: ty.results().iter().map(ValueLane::from).collect(), }) }) .collect(); @@ -223,29 +188,29 @@ impl ModuleMetadata { self.signature(ty) } - fn global_size(&self, idx: u32) -> Result<OperandSize> { + fn global_size(&self, idx: u32) -> Result<ValueLane> { Self::indexed_size(&self.globals, "global", idx) } - fn memory_size(&self, idx: u32) -> Result<OperandSize> { + fn memory_size(&self, idx: u32) -> Result<ValueLane> { Self::indexed_size(&self.memories, "memory", idx) } - fn table_size(&self, idx: u32) -> Result<OperandSize> { + fn table_size(&self, idx: u32) -> Result<ValueLane> { Self::indexed_size(&self.tables, "table", idx) } - fn indexed_size(sizes: &[OperandSize], entity: &str, idx: u32) -> Result<OperandSize> { + fn indexed_size(sizes: &[ValueLane], entity: &str, idx: u32) -> Result<ValueLane> { sizes .get(idx as usize) .copied() .ok_or_else(|| crate::ParseError::Other(alloc::format!("{entity} index out of bounds: {idx}"))) } - fn storage_size(storage: StorageType) -> OperandSize { + fn storage_size(storage: StorageType) -> ValueLane { match storage { - StorageType::I8 | StorageType::I16 => OperandSize::S32, - StorageType::Value(ref ty) => OperandSize::from(ty), + StorageType::I8 | StorageType::I16 => ValueLane::S32, + StorageType::Value(ref ty) => ValueLane::from(ty), } } @@ -291,7 +256,7 @@ impl VisitSimdOperator<'_> for ValidateThenVisit<'_, '_> { pub(crate) fn process_operators( body: FunctionBody<'_>, - local_types: Vec<OperandSize>, + local_types: Vec<ValueLane>, local_addr_map: Vec<u16>, metadata: &ModuleMetadata, ty_idx: u32, @@ -327,7 +292,7 @@ pub(crate) fn process_operators( pub(crate) fn process_operators_and_validate( mut validator: FuncValidator<ValidatorResources>, body: FunctionBody<'_>, - local_types: Vec<OperandSize>, + local_types: Vec<ValueLane>, local_addr_map: Vec<u16>, metadata: &ModuleMetadata, ty_idx: u32, @@ -470,7 +435,6 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { effect [S32] => [S32] { visit_f32_reinterpret_i32, visit_i32_reinterpret_f32 } effect [S64] => [S64] { visit_f64_reinterpret_i64, visit_i64_reinterpret_f64 } terminating [] => [] { visit_unreachable => Unreachable, visit_return => Return } - global [] => [Addr] { visit_global_get(global_index: u32) => GlobalGet } memory_index [] => [Addr] { visit_memory_size(memory: u32) => MemorySize } memory_index [Addr] => [Addr] { visit_memory_grow(memory: u32) => MemoryGrow } memory_index [Addr, S32, Addr] => [] { @@ -514,7 +478,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { .iter() .map(|field| ModuleMetadata::storage_size(field.storage)) .collect::<Vec<_>>(); - self.emit(&inputs, &[OperandSize::S32], Instruction::StructNew(type_index)) + self.emit(&inputs, &[ValueLane::S32], Instruction::StructNew(type_index)) } fn visit_struct_get(&mut self, type_index: u32, field_index: u32) -> Self::Output { @@ -531,7 +495,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_struct_set(&mut self, type_index: u32, field_index: u32) -> Self::Output { let size = ModuleMetadata::storage_size(self.metadata.struct_field(type_index, field_index)?.storage); - self.emit(&[OperandSize::S32, size], &[], Instruction::StructSet(type_index, field_index)) + self.emit(&[ValueLane::S32, size], &[], Instruction::StructSet(type_index, field_index)) } fn visit_array_new_fixed(&mut self, type_index: u32, array_size: u32) -> Self::Output { @@ -539,7 +503,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { for _ in 0..array_size { self.pop_expect(size)?; } - self.push_sizes(&[OperandSize::S32])?; + self.push_sizes(&[ValueLane::S32])?; self.instructions.push(Instruction::ArrayNewFixed(type_index, array_size)); Ok(()) } @@ -559,7 +523,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_call_ref(&mut self, type_index: u32) -> Self::Output { let signature = self.metadata.signature(type_index)?.clone(); let mut inputs = signature.params; - inputs.push(OperandSize::S32); + inputs.push(ValueLane::S32); self.emit(&inputs, &signature.results, Instruction::CallRef(type_index)) } @@ -584,7 +548,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_return_call_ref(&mut self, type_index: u32) -> Self::Output { let signature = self.metadata.signature(type_index)?.clone(); let mut inputs = signature.params; - inputs.push(OperandSize::S32); + inputs.push(ValueLane::S32); self.apply_effect(&inputs, &[])?; self.mark_unreachable(); self.instructions.push(Instruction::ReturnCallRef(type_index)); @@ -593,7 +557,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_global_set(&mut self, global_index: u32) -> Self::Output { let size = self.metadata.global_size(global_index)?; - let instruction = size.choose( + let instruction = size.select( Instruction::GlobalSet32(global_index), Instruction::GlobalSet64(global_index), Instruction::GlobalSet128(global_index), @@ -601,21 +565,31 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { self.emit(&[size], &[], instruction) } + fn visit_global_get(&mut self, global_index: u32) -> Self::Output { + let size = self.metadata.global_size(global_index)?; + let instruction = size.select( + Instruction::GlobalGet32(global_index), + Instruction::GlobalGet64(global_index), + Instruction::GlobalGet128(global_index), + ); + self.emit(&[], &[size], instruction) + } + fn visit_drop(&mut self) -> Self::Output { - let size = self.operand_stack.last().copied().unwrap_or(OperandSize::S32); - let instruction = size.choose(Instruction::Drop32, Instruction::Drop64, Instruction::Drop128); + let size = self.operand_stack.last().copied().unwrap_or(ValueLane::S32); + let instruction = size.select(Instruction::Drop32, Instruction::Drop64, Instruction::Drop128); self.emit(&[size], &[], instruction) } fn visit_select(&mut self) -> Self::Output { - let size = self.operand_stack.iter().rev().nth(1).copied().unwrap_or(OperandSize::S32); - let instruction = size.choose(Instruction::Select32, Instruction::Select64, Instruction::Select128); - self.emit(&[size, size, OperandSize::S32], &[size], instruction) + let size = self.operand_stack.iter().rev().nth(1).copied().unwrap_or(ValueLane::S32); + let instruction = size.select(Instruction::Select32, Instruction::Select64, Instruction::Select128); + self.emit(&[size, size, ValueLane::S32], &[size], instruction) } fn visit_local_get(&mut self, idx: u32) -> Self::Output { let (size, local_idx) = self.local(idx)?; - let instruction = size.choose( + let instruction = size.select( Instruction::LocalGet32(local_idx), Instruction::LocalGet64(local_idx), Instruction::LocalGet128(local_idx), @@ -625,7 +599,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_local_set(&mut self, idx: u32) -> Self::Output { let (size, local_idx) = self.local(idx)?; - let instruction = size.choose( + let instruction = size.select( Instruction::LocalSet32(local_idx), Instruction::LocalSet64(local_idx), Instruction::LocalSet128(local_idx), @@ -637,21 +611,21 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { let (size, local_idx) = self.local(idx)?; self.apply_effect(&[size], &[size])?; let src = match (size, self.instructions.last()) { - (OperandSize::S32, Some(Instruction::LocalGet32(src))) => Some(*src), - (OperandSize::S64, Some(Instruction::LocalGet64(src))) => Some(*src), - (OperandSize::S128, Some(Instruction::LocalGet128(src))) => Some(*src), + (ValueLane::S32, Some(Instruction::LocalGet32(src))) => Some(*src), + (ValueLane::S64, Some(Instruction::LocalGet64(src))) => Some(*src), + (ValueLane::S128, Some(Instruction::LocalGet128(src))) => Some(*src), _ => None, }; if let Some(src) = src { self.instructions.pop(); let instructions = match size { - OperandSize::S32 => [Instruction::LocalCopy32(src, local_idx), Instruction::LocalGet32(local_idx)], - OperandSize::S64 => [Instruction::LocalCopy64(src, local_idx), Instruction::LocalGet64(local_idx)], - OperandSize::S128 => [Instruction::LocalCopy128(src, local_idx), Instruction::LocalGet128(local_idx)], + ValueLane::S32 => [Instruction::LocalCopy32(src, local_idx), Instruction::LocalGet32(local_idx)], + ValueLane::S64 => [Instruction::LocalCopy64(src, local_idx), Instruction::LocalGet64(local_idx)], + ValueLane::S128 => [Instruction::LocalCopy128(src, local_idx), Instruction::LocalGet128(local_idx)], }; self.instructions.extend(instructions); } else { - self.instructions.push(size.choose( + self.instructions.push(size.select( Instruction::LocalTee32(local_idx), Instruction::LocalTee64(local_idx), Instruction::LocalTee128(local_idx), @@ -669,7 +643,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_if(&mut self, ty: wasmparser::BlockType) -> Self::Output { - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; self.instructions.push(Instruction::JumpIfZero32(0)); self.push_control(BlockKind::If, ty, Some(self.instructions.len() - 1)) } @@ -721,7 +695,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_br_if(&mut self, depth: u32) -> Self::Output { - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; let cond_jump_ip = self.instructions.len(); self.instructions.push(Instruction::JumpIfZero32(0)); @@ -745,7 +719,7 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { fn visit_br_table(&mut self, targets: wasmparser::BrTable<'_>) -> Self::Output { let ts = targets.targets().collect::<Result<Vec<_>, wasmparser::Error>>()?; - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; let default_depth = targets.default(); let len = ts.len() as u32; @@ -819,24 +793,24 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_f32_const(&mut self, val: wasmparser::Ieee32) -> Self::Output { - self.emit(&[], &[OperandSize::S32], Instruction::Const32(val.bits() as i32)) + self.emit(&[], &[ValueLane::S32], Instruction::Const32(val.bits() as i32)) } fn visit_f64_const(&mut self, val: wasmparser::Ieee64) -> Self::Output { - self.emit(&[], &[OperandSize::S64], Instruction::Const64(val.bits() as i64)) + self.emit(&[], &[ValueLane::S64], Instruction::Const64(val.bits() as i64)) } fn visit_table_copy(&mut self, dst_table: u32, src_table: u32) -> Self::Output { let dst = self.metadata.table_size(dst_table)?; let src = self.metadata.table_size(src_table)?; - let len = if dst == OperandSize::S32 || src == OperandSize::S32 { OperandSize::S32 } else { OperandSize::S64 }; + let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; self.emit(&[dst, src, len], &[], Instruction::TableCopy { dst_table, src_table }) } fn visit_memory_copy(&mut self, dst_mem: u32, src_mem: u32) -> Self::Output { let dst = self.metadata.memory_size(dst_mem)?; let src = self.metadata.memory_size(src_mem)?; - let len = if dst == OperandSize::S32 || src == OperandSize::S32 { OperandSize::S32 } else { OperandSize::S64 }; + let len = if dst == ValueLane::S32 || src == ValueLane::S32 { ValueLane::S32 } else { ValueLane::S64 }; self.emit(&[dst, src, len], &[], Instruction::MemoryCopy { dst_mem, src_mem }) } @@ -859,41 +833,41 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { } fn visit_br_on_null(&mut self, relative_depth: u32) -> Self::Output { - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; let fallthrough_jump = self.instructions.len(); self.instructions.push(Instruction::JumpIfRefNonNull(0)); self.emit_dropkeep_to_label(relative_depth)?; self.emit_branch_jump_or_return(relative_depth)?; self.patch_jump(fallthrough_jump, self.instructions.len()); - self.push_sizes(&[OperandSize::S32]) + self.push_sizes(&[ValueLane::S32]) } fn visit_br_on_non_null(&mut self, relative_depth: u32) -> Self::Output { - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; let fallthrough_jump = self.instructions.len(); self.instructions.push(Instruction::JumpIfRefNull(0)); - self.push_sizes(&[OperandSize::S32])?; + self.push_sizes(&[ValueLane::S32])?; self.emit_dropkeep_to_label(relative_depth)?; - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; self.emit_branch_jump_or_return(relative_depth)?; self.patch_jump(fallthrough_jump, self.instructions.len()); Ok(()) } fn visit_typed_select_multi(&mut self, tys: Vec<wasmparser::ValType>) -> Self::Output { - let sizes: Vec<_> = tys.into_iter().map(OperandSize::from).collect(); + let sizes: Vec<_> = tys.into_iter().map(value_lane).collect(); let counts = Self::value_counts(&sizes); self.emit( - &[sizes.as_slice(), sizes.as_slice(), &[OperandSize::S32]].concat(), + &[sizes.as_slice(), sizes.as_slice(), &[ValueLane::S32]].concat(), &sizes, Instruction::SelectMulti(counts), ) } fn visit_typed_select(&mut self, ty: wasmparser::ValType) -> Self::Output { - let size = OperandSize::from(ty); - let instruction = size.choose(Instruction::Select32, Instruction::Select64, Instruction::Select128); - self.emit(&[size, size, OperandSize::S32], &[size], instruction) + let size = value_lane(ty); + let instruction = size.select(Instruction::Select32, Instruction::Select64, Instruction::Select128); + self.emit(&[size, size, ValueLane::S32], &[size], instruction) } } @@ -1085,8 +1059,8 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { fn visit_i8x16_shuffle(&mut self, lanes: [u8; 16]) -> Self::Output { self.emit( - &[OperandSize::S128, OperandSize::S128], - &[OperandSize::S128], + &[ValueLane::S128, ValueLane::S128], + &[ValueLane::S128], Instruction::I8x16Shuffle(self.data.v128_constants.len() as u32), )?; self.data.v128_constants.push(lanes); @@ -1094,7 +1068,7 @@ impl wasmparser::VisitSimdOperator<'_> for FunctionBuilder<'_> { } fn visit_v128_const(&mut self, value: wasmparser::V128) -> Self::Output { - self.emit(&[], &[OperandSize::S128], Instruction::Const128(self.data.v128_constants.len() as u32))?; + self.emit(&[], &[ValueLane::S128], Instruction::Const128(self.data.v128_constants.len() as u32))?; self.data.v128_constants.push(*value.bytes()); Ok(()) } @@ -1107,11 +1081,11 @@ impl FunctionBuilder<'_> { target: wasmparser::RefType, branch_on_fail: bool, ) -> Result<()> { - self.pop_expect(OperandSize::S32)?; + self.pop_expect(ValueLane::S32)?; let target = convert_heap_type(target.heap_type(), target.is_nullable())?; let conditional_ip = self.instructions.len(); self.instructions.push(Instruction::BrOnCast(0, target, branch_on_fail)); - self.push_sizes(&[OperandSize::S32])?; + self.push_sizes(&[ValueLane::S32])?; self.emit_dropkeep_to_label(relative_depth)?; self.emit_branch_jump_or_return(relative_depth)?; self.patch_jump(conditional_ip, self.instructions.len()); @@ -1129,7 +1103,7 @@ impl FunctionBuilder<'_> { .ok_or_else(|| crate::ParseError::Other(alloc::format!("branch depth out of bounds: {depth}"))) } - fn local(&self, idx: u32) -> Result<(OperandSize, u16)> { + fn local(&self, idx: u32) -> Result<(ValueLane, u16)> { let size = *self .local_types .get(idx as usize) @@ -1142,12 +1116,12 @@ impl FunctionBuilder<'_> { } /// Pushes logical operands while maintaining the lane counts used by `DropKeep`. - fn push_sizes(&mut self, sizes: &[OperandSize]) -> Result<()> { + fn push_sizes(&mut self, sizes: &[ValueLane]) -> Result<()> { for &size in sizes { let count = match size { - OperandSize::S32 => &mut self.lane_counts.c32, - OperandSize::S64 => &mut self.lane_counts.c64, - OperandSize::S128 => &mut self.lane_counts.c128, + ValueLane::S32 => &mut self.lane_counts.c32, + ValueLane::S64 => &mut self.lane_counts.c64, + ValueLane::S128 => &mut self.lane_counts.c128, }; *count = count .checked_add(1) @@ -1158,7 +1132,7 @@ impl FunctionBuilder<'_> { } /// Pops an operand, allowing a polymorphic value at an unreachable frame base. - fn pop_expect(&mut self, expected: OperandSize) -> Result<()> { + fn pop_expect(&mut self, expected: ValueLane) -> Result<()> { let frame_height = self.control_stack.last().map_or(0, |frame| frame.height); if self.operand_stack.len() == frame_height && self.is_unreachable() { return Ok(()); @@ -1171,22 +1145,22 @@ impl FunctionBuilder<'_> { return Err(crate::ParseError::Other("logical operand width mismatch".into())); } match actual { - OperandSize::S32 => self.lane_counts.c32 -= 1, - OperandSize::S64 => self.lane_counts.c64 -= 1, - OperandSize::S128 => self.lane_counts.c128 -= 1, + ValueLane::S32 => self.lane_counts.c32 -= 1, + ValueLane::S64 => self.lane_counts.c64 -= 1, + ValueLane::S128 => self.lane_counts.c128 -= 1, } Ok(()) } /// Applies a declared logical stack effect in WebAssembly operand order. - fn apply_effect(&mut self, inputs: &[OperandSize], outputs: &[OperandSize]) -> Result<()> { + fn apply_effect(&mut self, inputs: &[ValueLane], outputs: &[ValueLane]) -> Result<()> { inputs.iter().rev().try_for_each(|&size| self.pop_expect(size))?; self.push_sizes(outputs)?; Ok(()) } /// Applies an instruction's stack effect before adding it to the bytecode. - fn emit(&mut self, inputs: &[OperandSize], outputs: &[OperandSize], instruction: Instruction) -> Result<()> { + fn emit(&mut self, inputs: &[ValueLane], outputs: &[ValueLane], instruction: Instruction) -> Result<()> { self.apply_effect(inputs, outputs)?; self.instructions.push(instruction); Ok(()) @@ -1212,9 +1186,7 @@ impl FunctionBuilder<'_> { fn push_control(&mut self, kind: BlockKind, ty: wasmparser::BlockType, initial_jump: Option<usize>) -> Result<()> { let signature = match ty { wasmparser::BlockType::Empty => Signature { params: Vec::new(), results: Vec::new() }, - wasmparser::BlockType::Type(ty) => { - Signature { params: Vec::new(), results: alloc::vec![OperandSize::from(ty)] } - } + wasmparser::BlockType::Type(ty) => Signature { params: Vec::new(), results: alloc::vec![value_lane(ty)] }, wasmparser::BlockType::FuncType(idx) => self.metadata.signature(idx)?.clone(), }; for &size in signature.params.iter().rev() { @@ -1263,13 +1235,13 @@ impl FunctionBuilder<'_> { } } - fn value_counts(sizes: &[OperandSize]) -> ValueCounts { + fn value_counts(sizes: &[ValueLane]) -> ValueCounts { let mut counts = ValueCounts::default(); for size in sizes { match size { - OperandSize::S32 => counts.c32 += 1, - OperandSize::S64 => counts.c64 += 1, - OperandSize::S128 => counts.c128 += 1, + ValueLane::S32 => counts.c32 += 1, + ValueLane::S64 => counts.c64 += 1, + ValueLane::S128 => counts.c128 += 1, } } counts diff --git a/crates/tinywasm/src/imports.rs b/crates/tinywasm/src/imports.rs index 3a7c06d..6a399ee 100644 --- a/crates/tinywasm/src/imports.rs +++ b/crates/tinywasm/src/imports.rs @@ -224,9 +224,18 @@ impl Imports { for import in &*module.imports { let (val, func_handle) = if let Some(defined) = self.take_defined(import) { match defined { - Extern::Global(global) => (ExternVal::Global(global.0.addr), None), - Extern::Table(table) => (ExternVal::Table(table.0.addr), None), - Extern::Memory(memory) => (ExternVal::Memory(memory.0.addr), None), + Extern::Global(global) => { + global.0.validate_store(store)?; + (ExternVal::Global(global.0.addr), None) + } + Extern::Table(table) => { + table.0.validate_store(store)?; + (ExternVal::Table(table.0.addr), None) + } + Extern::Memory(memory) => { + memory.0.validate_store(store)?; + (ExternVal::Memory(memory.0.addr), None) + } Extern::Function(func) => (ExternVal::Func(func.addr()), Some(func)), } } else { @@ -246,11 +255,11 @@ impl Imports { match (val, &import.kind) { (ExternVal::Global(global_addr), ImportKind::Global(ty)) => { - let global = store.state.get_global(global_addr); + let global_ty = store.state.globals.ty(global_addr); let expected = ty.with_ty(crate::store::canonicalize_value_type(ty.ty, type_addrs)); - let compatible = global.ty.mutable == ty.mutable - && store.state.value_type_is_subtype(global.ty.ty, expected.ty) - && (!ty.mutable || store.state.value_type_is_subtype(expected.ty, global.ty.ty)); + let compatible = global_ty.mutable == ty.mutable + && store.state.value_type_is_subtype(global_ty.ty, expected.ty) + && (!ty.mutable || store.state.value_type_is_subtype(expected.ty, global_ty.ty)); if !compatible { cold_path(); return Err(LinkingError::incompatible_import_type(import).into()); diff --git a/crates/tinywasm/src/interpreter/executor.rs b/crates/tinywasm/src/interpreter/executor.rs index fb8fdec..f864972 100644 --- a/crates/tinywasm/src/interpreter/executor.rs +++ b/crates/tinywasm/src/interpreter/executor.rs @@ -123,6 +123,16 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { let val = <$ty>::stack_peek(&self.store.value_stack); <$ty>::local_set(&mut self.store.value_stack, &self.cf, *$local_index, val); }}; + (global_get $ty:ty, $global_index:expr) => {{ + let addr = self.module.resolve_global_addr(*$global_index); + let value = <$ty>::global_get(&self.store.state.globals, addr); + <$ty>::stack_push(&mut self.store.value_stack, value)?; + }}; + (global_set $ty:ty, $global_index:expr) => {{ + let addr = self.module.resolve_global_addr(*$global_index); + let value = <$ty>::stack_pop(&mut self.store.value_stack); + <$ty>::global_set(&mut self.store.state.globals, addr, value); + }}; } macro_rules! exec_binop { @@ -200,12 +210,9 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { <$vt>::local_set(&mut self.store.value_stack, &self.cf, *$dst, value); self.store.value_stack.push(value)?; }}; - (stack_global $vt:ident, $width:tt, $op:ident, $global:ident) => {{ - let TinyWasmValue::$vt(global_val) = - self.store.state.get_global_val(self.module.resolve_global_addr(*$global)) - else { - unreachable!("expected global to be Value32") - }; + (stack_global $vt:ty, $width:tt, $op:ident, $global:ident) => {{ + let global_val = + <$vt>::global_get(&self.store.state.globals, self.module.resolve_global_addr(*$global)); let stack_val = <$vt>::stack_pop(&mut self.store.value_stack); self.store.value_stack.push(exec_binop!($width, *$op, stack_val, global_val))?; }}; @@ -339,10 +346,12 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { LocalTee32(local_index) => stack_op!(local_tee Value32, local_index), LocalTee64(local_index) => stack_op!(local_tee Value64, local_index), LocalTee128(local_index) => stack_op!(local_tee Value128, local_index), - GlobalGet(global_index) => self.exec_global_get(*global_index)?, - GlobalSet32(global_index) => self.exec_global_set_32(*global_index), - GlobalSet64(global_index) => self.exec_global_set::<Value64>(*global_index), - GlobalSet128(global_index) => self.exec_global_set::<Value128>(*global_index), + GlobalGet32(global_index) => stack_op!(global_get Value32, global_index), + GlobalGet64(global_index) => stack_op!(global_get Value64, global_index), + GlobalGet128(global_index) => stack_op!(global_get Value128, global_index), + GlobalSet32(global_index) => stack_op!(global_set Value32, global_index), + GlobalSet64(global_index) => stack_op!(global_set Value64, global_index), + GlobalSet128(global_index) => stack_op!(global_set Value128, global_index), Const32(val) => self.exec_const(*val)?, Const64(val) => self.exec_const(*val)?, I64Eqz => stack_op!(unary i64 => i32, |v| i32::from(v == 0)), @@ -1336,27 +1345,6 @@ impl<'store, const BUDGETED: bool> Executor<'store, BUDGETED> { Ok(()) } - fn exec_global_get(&mut self, global_index: u32) -> Result<(), Trap> { - self.store.value_stack.push_dyn(self.store.state.get_global_val(self.module.resolve_global_addr(global_index))) - } - - fn exec_global_set<T: InternalValue>(&mut self, global_index: u32) { - let global_addr = self.module.resolve_global_addr(global_index); - let value = <T>::stack_pop(&mut self.store.value_stack).into(); - self.store.state.set_global_val(global_addr, value); - } - - fn exec_global_set_32(&mut self, global_index: u32) { - let global_addr = self.module.resolve_global_addr(global_index); - let raw = <Value32>::stack_pop(&mut self.store.value_stack); - let value = match self.store.state.get_global(global_addr).ty.ty { - WasmType::I32 | WasmType::F32 => TinyWasmValue::Value32(raw), - WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::from_raw(raw)), - WasmType::I64 | WasmType::F64 | WasmType::V128 => unreachable!("invalid global.set.32 target type"), - }; - self.store.state.set_global_val(global_addr, value); - } - fn exec_const<T: InternalValue>(&mut self, val: T) -> Result<(), Trap> { self.store.value_stack.push(val) } diff --git a/crates/tinywasm/src/interpreter/stack/value_stack.rs b/crates/tinywasm/src/interpreter/stack/value_stack.rs index 378dc7f..3b5dfe2 100644 --- a/crates/tinywasm/src/interpreter/stack/value_stack.rs +++ b/crates/tinywasm/src/interpreter/stack/value_stack.rs @@ -8,6 +8,10 @@ use crate::interpreter::*; use crate::{Result, Trap}; #[cfg_attr(feature = "debug", derive(Debug))] +/// Physical value lanes used by the interpreter. +/// +/// Guest values should normally be accessed through +/// [`InternalValue`] so their stack and global representation stays consistent. pub(crate) struct ValueStack { pub(crate) stack_32: Stack<Value32>, pub(crate) stack_64: Stack<Value64>, diff --git a/crates/tinywasm/src/interpreter/values.rs b/crates/tinywasm/src/interpreter/values.rs index f034906..fae7876 100644 --- a/crates/tinywasm/src/interpreter/values.rs +++ b/crates/tinywasm/src/interpreter/values.rs @@ -1,6 +1,7 @@ use super::stack::{CallFrame, ValueStack}; +use crate::store::Globals; use crate::{Result, interpreter::simd::Value128}; -use tinywasm_types::{AnyRef, ExnRef, ExternRef, FuncRef, LocalAddr, RefValue, WasmType, WasmValue}; +use tinywasm_types::{AnyRef, ExnRef, ExternRef, FuncRef, GlobalAddr, LocalAddr, RefValue, WasmType, WasmValue}; pub(crate) type Value32 = u32; pub(crate) type Value64 = u64; @@ -179,7 +180,8 @@ mod sealed { pub trait Sealed {} } -pub(crate) trait InternalValue: sealed::Sealed + Into<TinyWasmValue> + Copy + Default { +/// Typed access to values in their physical [`ValueStack`] and [`Globals`] lanes. +pub(crate) trait InternalValue: sealed::Sealed + Copy + Default { fn stack_push(stack: &mut ValueStack, value: Self) -> Result<(), crate::Trap>; fn stack_pop(stack: &mut ValueStack) -> Self; fn stack_peek(stack: &ValueStack) -> Self; @@ -188,12 +190,16 @@ pub(crate) trait InternalValue: sealed::Sealed + Into<TinyWasmValue> + Copy + De fn local_set(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, value: Self); fn local_update(stack: &mut ValueStack, frame: &CallFrame, index: LocalAddr, f: impl FnOnce(Self) -> Self); fn local_copy(stack: &mut ValueStack, frame: &CallFrame, from: LocalAddr, to: LocalAddr); + /// Gets a value from its physical global lane. + fn global_get(globals: &Globals, addr: GlobalAddr) -> Self; + /// Sets a value in its physical global lane. + fn global_set(globals: &mut Globals, addr: GlobalAddr, value: Self); } macro_rules! impl_internalvalue { ( $( - $variant:ident, $stack:ident, $stack_base:ident, $outer:ty, + $variant:ident, $stack:ident, $stack_base:ident, $global_get:ident, $global_set:ident, $outer:ty, |$to_value_v:ident| $to_value:expr, |$to_stack_v:ident| $to_stack:expr, |$from_stack_v:ident| $from_stack:expr @@ -249,6 +255,18 @@ macro_rules! impl_internalvalue { } #[inline(always)] + fn global_get(globals: &Globals, addr: GlobalAddr) -> Self { + let $from_stack_v = globals.$global_get(addr); + $from_stack + } + + #[inline(always)] + fn global_set(globals: &mut Globals, addr: GlobalAddr, value: Self) { + let $to_stack_v = value; + globals.$global_set(addr, $to_stack); + } + + #[inline(always)] fn stack_pop(stack: &mut ValueStack) -> Self { let $from_stack_v = stack.$stack.pop(); $from_stack @@ -278,12 +296,12 @@ macro_rules! impl_internalvalue { } impl_internalvalue! { - Value32, stack_32, s32, u32, |v| v, |v| v, |v| v - Value64, stack_64, s64, u64, |v| v, |v| v, |v| v - Value32, stack_32, s32, i32, |v| v as u32, |v| v as u32, |v| v as i32 - Value64, stack_64, s64, i64, |v| v as u64, |v| v as u64, |v| v as i64 - Value32, stack_32, s32, f32, |v| f32::to_bits(v), |v| f32::to_bits(v), |v| f32::from_bits(v) - Value64, stack_64, s64, f64, |v| f64::to_bits(v), |v| f64::to_bits(v), |v| f64::from_bits(v) - ValueRef, stack_32, s32, ValueRef, |v| v, |v| v.raw(), |v| ValueRef(v) - Value128, stack_128, s128, Value128, |v| v, |v| v, |v| v + Value32, stack_32, s32, get_32, set_32, u32, |v| v, |v| v, |v| v + Value64, stack_64, s64, get_64, set_64, u64, |v| v, |v| v, |v| v + Value32, stack_32, s32, get_32, set_32, i32, |v| v as u32, |v| v as u32, |v| v as i32 + Value64, stack_64, s64, get_64, set_64, i64, |v| v as u64, |v| v as u64, |v| v as i64 + Value32, stack_32, s32, get_32, set_32, f32, |v| f32::to_bits(v), |v| f32::to_bits(v), |v| f32::from_bits(v) + Value64, stack_64, s64, get_64, set_64, f64, |v| f64::to_bits(v), |v| f64::to_bits(v), |v| f64::from_bits(v) + ValueRef, stack_32, s32, get_32, set_32, ValueRef, |v| v, |v| v.raw(), |v| ValueRef(v) + Value128, stack_128, s128, get_128, set_128, Value128, |v| v, |v| v, |v| v } diff --git a/crates/tinywasm/src/reference.rs b/crates/tinywasm/src/reference.rs index d8f9669..ad9cfd9 100644 --- a/crates/tinywasm/src/reference.rs +++ b/crates/tinywasm/src/reference.rs @@ -6,9 +6,9 @@ use alloc::string::{String, ToString}; use alloc::vec::Vec; use crate::interpreter::TinyWasmValue; -use crate::store::{GlobalInstance, TableInstance}; +use crate::store::TableInstance; use crate::{Error, MemoryInstance, Result, Store, Trap}; -use tinywasm_types::{Addr, GlobalAddr, GlobalType, MemAddr, MemoryType, TableAddr, TableType, WasmType, WasmValue}; +use tinywasm_types::{Addr, GlobalType, MemAddr, MemoryType, TableAddr, TableType, WasmType, WasmValue}; #[derive(Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "debug", derive(Debug))] @@ -460,28 +460,20 @@ impl Global { cold_path(); return Err(Error::Other("invalid global value type".to_string())); } - let addr = store.state.globals.len() as GlobalAddr; - store.state.globals.push(GlobalInstance::new(ty, value.into())); + let addr = store.state.globals.push(ty, value.into()); Ok(Self(StoreItem::new(store.id(), addr))) } - #[inline] - fn instance<'a>(&self, store: &'a Store) -> Result<&'a GlobalInstance> { - self.0.validate_store(store)?; - Ok(store.state.get_global(self.0.addr)) - } - /// Get the type of the global. pub fn ty(&self, store: &Store) -> Result<GlobalType> { - Ok(self.instance(store)?.ty) + self.0.validate_store(store)?; + Ok(store.state.globals.ty(self.0.addr)) } /// Get the current value of the global. pub fn get(&self, store: &Store) -> Result<WasmValue> { - let global = self.instance(store)?; - let value = store.state.attach_value(global.value, global.ty.ty); - let value = - value.unwrap_or_else(|| unreachable!("Global value type does not match global type, this is a bug")); + self.0.validate_store(store)?; + let value = store.state.global_wasm_value(self.0.addr); if let WasmValue::Ref(value) = value { store.state.pin_host_ref(value); } @@ -491,16 +483,6 @@ impl Global { /// Set the current value of the global. pub fn set(&self, store: &mut Store, value: WasmValue) -> Result<()> { self.0.validate_store(store)?; - let global = store.state.get_global(self.0.addr); - if !global.ty.mutable { - cold_path(); - return Err(Error::Other("global is immutable".to_string())); - } - if !store.state.value_matches_type(value, global.ty.ty) { - cold_path(); - return Err(Error::Other("invalid global value type".to_string())); - } - store.state.get_global_mut(self.0.addr).value = value.into(); - Ok(()) + store.state.set_global_wasm_value(self.0.addr, value) } } diff --git a/crates/tinywasm/src/store/global.rs b/crates/tinywasm/src/store/global.rs index 9280494..c685d89 100644 --- a/crates/tinywasm/src/store/global.rs +++ b/crates/tinywasm/src/store/global.rs @@ -1,17 +1,162 @@ -use crate::interpreter::TinyWasmValue; +use alloc::vec::Vec; use tinywasm_types::*; -/// A WebAssembly Global Instance +use crate::interpreter::{TinyWasmValue, Value32, Value64, Value128, ValueRef}; + +struct GlobalLane<T> { + values: Vec<T>, + types: Vec<GlobalType>, +} + +impl<T> Default for GlobalLane<T> { + fn default() -> Self { + Self { values: Vec::new(), types: Vec::new() } + } +} + +impl<T: Copy> GlobalLane<T> { + fn push(&mut self, ty: GlobalType, value: T) -> usize { + debug_assert_eq!(self.values.len(), self.types.len()); + let index = self.values.len(); + self.values.push(value); + self.types.push(ty); + index + } + + #[inline(always)] + fn get(&self, index: usize, addr: GlobalAddr) -> T { + *self.values.get(index).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) + } + + #[inline(always)] + fn set(&mut self, index: usize, addr: GlobalAddr, value: T) { + *self.values.get_mut(index).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) = value; + } + + fn ty(&self, index: usize, addr: GlobalAddr) -> GlobalType { + *self.types.get(index).unwrap_or_else(|| unreachable!("invalid global address: {addr}")) + } +} + +/// Global instances split into their physical value lanes. /// -/// See <https://webassembly.github.io/spec/core/exec/runtime.html#global-instances> -#[cfg_attr(feature = "debug", derive(Debug))] -pub(crate) struct GlobalInstance { - pub(crate) value: TinyWasmValue, - pub(crate) ty: GlobalType, +/// Guest values should normally be accessed through +/// [`InternalValue`](crate::interpreter::InternalValue). Dynamic access is +/// reserved for initialization and host boundaries. +#[derive(Default)] +pub(crate) struct Globals { + globals_32: GlobalLane<Value32>, + globals_64: GlobalLane<Value64>, + globals_128: GlobalLane<Value128>, } -impl GlobalInstance { - pub(crate) fn new(ty: GlobalType, value: TinyWasmValue) -> Self { - Self { ty, value } +impl Globals { + const LANE_SHIFT: u32 = 30; + const INDEX_MASK: u32 = (1 << Self::LANE_SHIFT) - 1; + const LANE_32: u32 = 0; + const LANE_64: u32 = 1 << Self::LANE_SHIFT; + const LANE_128: u32 = 2 << Self::LANE_SHIFT; + + fn addr(lane: u32, index: usize) -> GlobalAddr { + assert!(index <= Self::INDEX_MASK as usize, "too many globals in one value lane"); + lane | index as u32 + } + + #[inline(always)] + fn index(addr: GlobalAddr, lane: u32) -> usize { + debug_assert_eq!(addr & !Self::INDEX_MASK, lane, "global address has the wrong value lane"); + (addr & Self::INDEX_MASK) as usize + } + + /// Returns a global's logical type and mutability. + pub(crate) fn ty(&self, addr: GlobalAddr) -> GlobalType { + match addr & !Self::INDEX_MASK { + Self::LANE_32 => self.globals_32.ty(Self::index(addr, Self::LANE_32), addr), + Self::LANE_64 => self.globals_64.ty(Self::index(addr, Self::LANE_64), addr), + Self::LANE_128 => self.globals_128.ty(Self::index(addr, Self::LANE_128), addr), + _ => unreachable!("invalid global address: {addr}"), + } + } + + /// Adds a global and returns its packed store address. + pub(crate) fn push(&mut self, ty: GlobalType, value: TinyWasmValue) -> GlobalAddr { + match (ty.ty, value) { + (WasmType::I32 | WasmType::F32, TinyWasmValue::Value32(value)) => { + Self::addr(Self::LANE_32, self.globals_32.push(ty, value)) + } + (WasmType::Ref(_), TinyWasmValue::ValueRef(value)) => { + Self::addr(Self::LANE_32, self.globals_32.push(ty, value.raw())) + } + (WasmType::I64 | WasmType::F64, TinyWasmValue::Value64(value)) => { + Self::addr(Self::LANE_64, self.globals_64.push(ty, value)) + } + (WasmType::V128, TinyWasmValue::Value128(value)) => { + Self::addr(Self::LANE_128, self.globals_128.push(ty, value)) + } + _ => unreachable!("global value does not match its declared type"), + } + } + + /// Returns a dynamically represented global value. + pub(crate) fn get(&self, addr: GlobalAddr) -> TinyWasmValue { + let ty = self.ty(addr); + match ty.ty { + WasmType::I32 | WasmType::F32 => TinyWasmValue::Value32(self.get_32(addr)), + WasmType::I64 | WasmType::F64 => TinyWasmValue::Value64(self.get_64(addr)), + WasmType::Ref(_) => TinyWasmValue::ValueRef(ValueRef::from_raw(self.get_32(addr))), + WasmType::V128 => TinyWasmValue::Value128(self.get_128(addr)), + } + } + + /// Sets a global from a dynamically represented value. + pub(crate) fn set(&mut self, addr: GlobalAddr, value: TinyWasmValue) { + match (self.ty(addr).ty, value) { + (WasmType::I32 | WasmType::F32, TinyWasmValue::Value32(value)) => self.set_32(addr, value), + (WasmType::Ref(_), TinyWasmValue::ValueRef(value)) => self.set_32(addr, value.raw()), + (WasmType::I64 | WasmType::F64, TinyWasmValue::Value64(value)) => self.set_64(addr, value), + (WasmType::V128, TinyWasmValue::Value128(value)) => self.set_128(addr, value), + _ => unreachable!("global value does not match its declared type"), + } + } + + /// Returns a raw value from the 32-bit lane. + #[inline(always)] + pub(crate) fn get_32(&self, addr: GlobalAddr) -> Value32 { + self.globals_32.get(Self::index(addr, Self::LANE_32), addr) + } + + /// Returns a raw value from the 64-bit lane. + #[inline(always)] + pub(crate) fn get_64(&self, addr: GlobalAddr) -> Value64 { + self.globals_64.get(Self::index(addr, Self::LANE_64), addr) + } + + /// Returns a raw value from the 128-bit lane. + #[inline(always)] + pub(crate) fn get_128(&self, addr: GlobalAddr) -> Value128 { + self.globals_128.get(Self::index(addr, Self::LANE_128), addr) + } + + /// Sets a raw value in the 32-bit lane. + #[inline(always)] + pub(crate) fn set_32(&mut self, addr: GlobalAddr, value: Value32) { + self.globals_32.set(Self::index(addr, Self::LANE_32), addr, value); + } + + /// Sets a raw value in the 64-bit lane. + #[inline(always)] + pub(crate) fn set_64(&mut self, addr: GlobalAddr, value: Value64) { + self.globals_64.set(Self::index(addr, Self::LANE_64), addr, value); + } + + /// Sets a raw value in the 128-bit lane. + #[inline(always)] + pub(crate) fn set_128(&mut self, addr: GlobalAddr, value: Value128) { + self.globals_128.set(Self::index(addr, Self::LANE_128), addr, value); + } + + /// Iterates over globals in the 32-bit lane for root tracing. + pub(crate) fn globals_32(&self) -> impl Iterator<Item = (Value32, GlobalType)> + '_ { + self.globals_32.values.iter().copied().zip(self.globals_32.types.iter().copied()) } } diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index 84c4033..3c80e91 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -72,7 +72,8 @@ impl Store { /// Create a new store pub fn new(engine: Engine) -> Self { let id = STORE_ID.fetch_add(1, Ordering::Relaxed); - let state = State { gc: gc::GcHeap::new(engine.config().gc_collection_threshold), ..State::default() }; + let state = + State { gc: Box::new(gc::GcHeap::new(engine.config().gc_collection_threshold)), ..State::default() }; Self { id, module_instances: Vec::new(), @@ -138,16 +139,16 @@ impl Store { self.module_instances.push(instance); } - /// Get the global at the actual index in the store + /// Gets a global by its opaque store address. #[doc(hidden)] pub fn get_global_val(&self, addr: GlobalAddr) -> TinyWasmValue { - self.state.get_global_val(addr) + self.state.globals.get(addr) } - /// Set the global at the actual index in the store + /// Sets a global by its opaque store address. #[doc(hidden)] pub fn set_global_val(&mut self, addr: GlobalAddr, value: TinyWasmValue) { - self.state.set_global_val(addr, value); + self.state.globals.set(addr, value); } /// Returns whether a public value has the requested runtime type. @@ -232,9 +233,6 @@ impl Store { func_addrs: &[FuncAddr], type_addrs: &[TypeAddr], ) -> Result<()> { - let start = self.state.globals.len() as Addr; - out.extend(start..start + globals.len() as Addr); - for global in globals { let value = match self.eval_const(&global.init, out, func_addrs, type_addrs) { Ok(val) => val, @@ -244,7 +242,7 @@ impl Store { } }; let ty = global.ty.with_ty(canonicalize_value_type(global.ty.ty, type_addrs)); - self.state.globals.push(GlobalInstance::new(ty, value)); + out.push(self.state.globals.push(ty, value)); } Ok(()) @@ -439,7 +437,7 @@ impl Store { let addr = *module_global_addrs .get(index as usize) .ok_or_else(|| Error::Other(format!("global {index} not found")))?; - Ok(state.globals.get(addr as usize).ok_or_else(|| Error::Other(format!("global {addr} not found")))?.value) + Ok(state.globals.get(addr)) }; let func_ref = |index: u32| -> Result<ValueRef> { let addr = *module_func_addrs diff --git a/crates/tinywasm/src/store/state.rs b/crates/tinywasm/src/store/state.rs index 125cc30..392035f 100644 --- a/crates/tinywasm/src/store/state.rs +++ b/crates/tinywasm/src/store/state.rs @@ -14,10 +14,10 @@ pub(crate) struct State { pub(crate) funcs: Vec<FunctionInstance>, pub(crate) tables: Vec<TableInstance>, pub(crate) memories: Vec<MemoryInstance>, - pub(crate) globals: Vec<GlobalInstance>, + pub(crate) globals: Globals, pub(crate) elements: Vec<ElementInstance>, pub(crate) data: Vec<DataInstance>, - pub(crate) gc: gc::GcHeap, + pub(crate) gc: Box<gc::GcHeap>, } impl State { @@ -73,9 +73,9 @@ impl State { .map(ValueRef::from_raw) .chain( self.globals - .iter() - .filter(|global| Self::type_may_contain_gc_in(canonical_types, global.ty.ty)) - .filter_map(|global| global.value.as_ref()), + .globals_32() + .filter(|(_, ty)| Self::type_may_contain_gc_in(canonical_types, ty.ty)) + .map(|(value, _)| ValueRef::from_raw(value)), ) .chain( self.tables @@ -363,23 +363,45 @@ impl State { Self::get_mut(&mut self.elements, addr, "element") } - /// Get the global at the actual index in the store - pub(crate) fn get_global(&self, addr: GlobalAddr) -> &GlobalInstance { - Self::get(&self.globals, addr, "global") - } - - /// Get the global at the actual index in the store - pub(crate) fn get_global_mut(&mut self, addr: GlobalAddr) -> &mut GlobalInstance { - Self::get_mut(&mut self.globals, addr, "global") - } - - /// Get the global at the actual index in the store - pub(crate) fn get_global_val(&self, addr: GlobalAddr) -> TinyWasmValue { - self.get_global(addr).value + /// Converts a global directly to its public value representation. + pub(crate) fn global_wasm_value(&self, addr: GlobalAddr) -> WasmValue { + let ty = self.globals.ty(addr).ty; + match ty { + WasmType::I32 => WasmValue::I32(self.globals.get_32(addr) as i32), + WasmType::I64 => WasmValue::I64(self.globals.get_64(addr) as i64), + WasmType::F32 => WasmValue::F32(f32::from_bits(self.globals.get_32(addr))), + WasmType::F64 => WasmValue::F64(f64::from_bits(self.globals.get_64(addr))), + WasmType::Ref(_) => self + .attach_value(TinyWasmValue::ValueRef(ValueRef::from_raw(self.globals.get_32(addr))), ty) + .unwrap_or_else(|| unreachable!("global value does not match its type")), + WasmType::V128 => WasmValue::V128(self.globals.get_128(addr).to_le_bytes()), + } } - /// Set the global at the actual index in the store - pub(crate) fn set_global_val(&mut self, addr: GlobalAddr, value: TinyWasmValue) { - self.get_global_mut(addr).value = value; + /// Validates and sets a global from its public value representation. + pub(crate) fn set_global_wasm_value(&mut self, addr: GlobalAddr, value: WasmValue) -> Result<()> { + let ty = self.globals.ty(addr); + if !ty.mutable { + cold_path(); + return Err(Error::other("global is immutable")); + } + if !self.value_matches_type(value, ty.ty) { + cold_path(); + return Err(Error::other("invalid global value type")); + } + match value { + WasmValue::I32(value) => self.globals.set_32(addr, value as u32), + WasmValue::I64(value) => self.globals.set_64(addr, value as u64), + WasmValue::F32(value) => self.globals.set_32(addr, value.to_bits()), + WasmValue::F64(value) => self.globals.set_64(addr, value.to_bits()), + WasmValue::Ref(value) => { + let TinyWasmValue::ValueRef(value) = TinyWasmValue::from(WasmValue::Ref(value)) else { + unreachable!("reference value did not convert to an internal reference") + }; + self.globals.set_32(addr, value.raw()); + } + WasmValue::V128(value) => self.globals.set_128(addr, value.into()), + } + Ok(()) } } diff --git a/crates/tinywasm/tests/store_ownership.rs b/crates/tinywasm/tests/store_ownership.rs index 8577d73..6cae984 100644 --- a/crates/tinywasm/tests/store_ownership.rs +++ b/crates/tinywasm/tests/store_ownership.rs @@ -1,5 +1,6 @@ use eyre::Result; -use tinywasm::{ModuleInstance, Store}; +use tinywasm::types::{GlobalType, WasmType}; +use tinywasm::{Global, Imports, ModuleInstance, Store}; const MODULE_WAT: &str = r#" (module @@ -86,3 +87,18 @@ fn table_grow_rejects_wrong_store_with_invalid_store_error() -> Result<()> { Ok(()) } + +#[test] +fn global_import_rejects_wrong_store() -> Result<()> { + let wasm = wat::parse_str(r#"(module (import "env" "g" (global i32)))"#)?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut owner_store = Store::default(); + let global = Global::new(&mut owner_store, GlobalType::new(WasmType::I32, false), 1.into())?; + let mut imports = Imports::default(); + imports.define("env", "g", global); + + let mut other_store = Store::default(); + let err = ModuleInstance::instantiate(&mut other_store, &module, Some(imports)).unwrap_err(); + assert_eq!(err, tinywasm::Error::Trap(tinywasm::Trap::InvalidStore)); + Ok(()) +} diff --git a/crates/tinywasm/tests/typed_globals.rs b/crates/tinywasm/tests/typed_globals.rs new file mode 100644 index 0000000..80494e0 --- /dev/null +++ b/crates/tinywasm/tests/typed_globals.rs @@ -0,0 +1,93 @@ +use eyre::Result; +use tinywasm::types::{GlobalType, Instruction, RefValue, WasmType, WasmValue}; +use tinywasm::{Global, Imports, ModuleInstance, Store}; + +#[test] +fn globals_use_typed_instructions_and_roundtrip_values() -> Result<()> { + let wasm = wat::parse_str( + r#" + (module + (global (mut i32) (i32.const 1)) + (global (mut f32) (f32.const 2)) + (global (mut i64) (i64.const 3)) + (global (mut f64) (f64.const 4)) + (global (mut v128) (v128.const i32x4 1 2 3 4)) + (global (mut funcref) (ref.null func)) + + (func (export "i32") (param i32) (result i32) + local.get 0 global.set 0 global.get 0) + (func (export "f32") (param f32) (result f32) + local.get 0 global.set 1 global.get 1) + (func (export "i64") (param i64) (result i64) + local.get 0 global.set 2 global.get 2) + (func (export "f64") (param f64) (result f64) + local.get 0 global.set 3 global.get 3) + (func (export "v128") (param v128) (result v128) + local.get 0 global.set 4 global.get 4) + (func (export "ref") (param funcref) (result funcref) + local.get 0 global.set 5 global.get 5) + (func (export "add-i32") (param i32) (result i32) + local.get 0 global.get 0 i32.add) + (func (export "add-i64") (param i64) (result i64) + local.get 0 global.get 2 i64.add) + ) + "#, + )?; + + let module = tinywasm::parse_bytes(&wasm)?; + let instructions = module.funcs.iter().flat_map(|func| func.instructions.iter()); + let (mut get32, mut get64, mut get128, mut fused32, mut fused64) = (0, 0, 0, 0, 0); + for instruction in instructions { + match instruction { + Instruction::GlobalGet32(_) => get32 += 1, + Instruction::GlobalGet64(_) => get64 += 1, + Instruction::GlobalGet128(_) => get128 += 1, + Instruction::BinOpStackGlobal32(..) => fused32 += 1, + Instruction::BinOpStackGlobal64(..) => fused64 += 1, + _ => {} + } + } + assert_eq!((get32, get64, get128), (3, 2, 1)); + assert_eq!((fused32, fused64), (1, 1)); + + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let cases = [ + ("i32", WasmValue::I32(11)), + ("f32", WasmValue::F32(12.5)), + ("i64", WasmValue::I64(13)), + ("f64", WasmValue::F64(14.5)), + ("v128", WasmValue::V128([15; 16])), + ("ref", WasmValue::Ref(RefValue::Null)), + ]; + for (name, value) in cases { + assert_eq!(instance.func_untyped(&store, name)?.call(&mut store, &[value])?, vec![value]); + } + assert_eq!(instance.func::<i32, i32>(&store, "add-i32")?.call(&mut store, 2)?, 13); + assert_eq!(instance.func::<i64, i64>(&store, "add-i64")?.call(&mut store, 2)?, 15); + + Ok(()) +} + +#[test] +fn imported_global_keeps_its_typed_store_address() -> Result<()> { + let wasm = wat::parse_str( + r#" + (module + (import "env" "g" (global (mut i64))) + (func (export "roundtrip") (param i64) (result i64) + local.get 0 global.set 0 global.get 0) + ) + "#, + )?; + let module = tinywasm::parse_bytes(&wasm)?; + let mut store = Store::default(); + let global = Global::new(&mut store, GlobalType::new(WasmType::I64, true), WasmValue::I64(1))?; + let mut imports = Imports::default(); + imports.define("env", "g", global); + let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + + assert_eq!(instance.func::<i64, i64>(&store, "roundtrip")?.call(&mut store, 42)?, 42); + assert_eq!(global.get(&store)?, WasmValue::I64(42)); + Ok(()) +} diff --git a/crates/types/src/instructions.rs b/crates/types/src/instructions.rs index 1160fa5..b920ac7 100644 --- a/crates/types/src/instructions.rs +++ b/crates/types/src/instructions.rs @@ -239,10 +239,9 @@ pub enum Instruction { // > Variable Instructions // See <https://webassembly.github.io/spec/core/binary/instructions.html#variable-instructions> - GlobalGet(GlobalAddr), - LocalGet32(LocalAddr), LocalSet32(LocalAddr), LocalTee32(LocalAddr), GlobalSet32(GlobalAddr), - LocalGet64(LocalAddr), LocalSet64(LocalAddr), LocalTee64(LocalAddr), GlobalSet64(GlobalAddr), - LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr), GlobalSet128(GlobalAddr), + GlobalGet32(GlobalAddr), LocalGet32(LocalAddr), LocalSet32(LocalAddr), LocalTee32(LocalAddr), GlobalSet32(GlobalAddr), + GlobalGet64(GlobalAddr), LocalGet64(LocalAddr), LocalSet64(LocalAddr), LocalTee64(LocalAddr), GlobalSet64(GlobalAddr), + GlobalGet128(GlobalAddr), LocalGet128(LocalAddr), LocalSet128(LocalAddr), LocalTee128(LocalAddr), GlobalSet128(GlobalAddr), // > Memory Instructions I32Load(MemoryArg), diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index c461296..0fd4e81 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -362,6 +362,39 @@ impl ExternVal { } } +/// The physical storage lane used by a [`WasmType`]. +#[derive(Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "debug", derive(Debug))] +pub enum ValueLane { + /// A 32-bit value or reference. + S32, + /// A 64-bit value. + S64, + /// A 128-bit SIMD value. + S128, +} + +impl ValueLane { + /// Selects one of three values based on this lane. + pub fn select<T>(self, s32: T, s64: T, s128: T) -> T { + match self { + Self::S32 => s32, + Self::S64 => s64, + Self::S128 => s128, + } + } +} + +impl From<&WasmType> for ValueLane { + fn from(ty: &WasmType) -> Self { + match ty { + WasmType::I32 | WasmType::F32 | WasmType::Ref(_) => Self::S32, + WasmType::I64 | WasmType::F64 => Self::S64, + WasmType::V128 => Self::S128, + } + } +} + #[derive(Default, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "debug", derive(Debug))] #[cfg_attr(feature = "archive", derive(serde::Serialize, serde::Deserialize))] @@ -384,10 +417,10 @@ impl<'a> FromIterator<&'a WasmType> for ValueCounts { let mut counts = Self::default(); for ty in iter { - match ty { - WasmType::I32 | WasmType::F32 | WasmType::Ref(_) => counts.c32 += 1, - WasmType::I64 | WasmType::F64 => counts.c64 += 1, - WasmType::V128 => counts.c128 += 1, + match ValueLane::from(ty) { + ValueLane::S32 => counts.c32 += 1, + ValueLane::S64 => counts.c64 += 1, + ValueLane::S128 => counts.c128 += 1, } } counts |
