diff options
Diffstat (limited to 'crates/parser/src')
| -rw-r--r-- | crates/parser/src/conversion.rs | 78 | ||||
| -rw-r--r-- | crates/parser/src/macros.rs | 1 | ||||
| -rw-r--r-- | crates/parser/src/module.rs | 41 | ||||
| -rw-r--r-- | crates/parser/src/optimize.rs | 3 | ||||
| -rw-r--r-- | crates/parser/src/visit.rs | 64 |
5 files changed, 127 insertions, 60 deletions
diff --git a/crates/parser/src/conversion.rs b/crates/parser/src/conversion.rs index 586cac5..db8d2aa 100644 --- a/crates/parser/src/conversion.rs +++ b/crates/parser/src/conversion.rs @@ -1,5 +1,3 @@ -use alloc::sync::Arc; - use crate::{Result, module::FunctionCode, visit::process_operators_and_validate}; use alloc::{boxed::Box, format, string::ToString, vec::Vec}; use tinywasm_types::*; @@ -26,7 +24,7 @@ pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result .collect::<Result<Vec<_>>>()? .into_boxed_slice(); - Ok(tinywasm_types::Element { kind, items, ty: WasmType::RefFunc, range: element.range }) + Ok(tinywasm_types::Element { kind, items, ty: RefType::FUNCREF, range: element.range }) } wasmparser::ElementItems::Expressions(ty, exprs) => { @@ -36,7 +34,7 @@ pub(crate) fn convert_module_element(element: wasmparser::Element<'_>) -> Result .collect::<Result<Vec<_>>>()? .into_boxed_slice(); - Ok(tinywasm_types::Element { kind, items, ty: convert_reftype(ty)?, range: element.range }) + Ok(tinywasm_types::Element { kind, items, ty: convert_ref_type(ty)?, range: element.range }) } } } @@ -59,7 +57,7 @@ pub(crate) fn convert_module_import(import: wasmparser::Import<'_>) -> Result<Im let kind = match import.ty { wasmparser::TypeRef::Func(ty) => ImportKind::Function(ty), wasmparser::TypeRef::Table(ty) => { - let element_type = convert_reftype(ty.element_type)?; + let element_type = convert_ref_type(ty.element_type)?; ImportKind::Table(if ty.table64 { TableType::new64(element_type, ty.initial, ty.maximum) } else { @@ -165,8 +163,9 @@ pub(crate) fn convert_module_code( )) } -pub(crate) fn convert_module_type(ty: wasmparser::RecGroup) -> Result<Arc<FuncType>> { +pub(crate) fn convert_module_type(ty: wasmparser::RecGroup) -> Result<FuncType> { let mut types = ty.types(); + // TODO(wasm3): Preserve recursive groups and non-function composite types instead of flattening singleton funcs. if types.len() != 1 { return Err(crate::ParseError::UnsupportedOperator( "Expected exactly one type in the type section".to_string(), @@ -182,18 +181,11 @@ pub(crate) fn convert_module_type(ty: wasmparser::RecGroup) -> Result<Arc<FuncTy }; let params = ty.params().iter().map(convert_valtype).collect::<Result<Vec<_>>>()?; let results = ty.results().iter().map(convert_valtype).collect::<Result<Vec<_>>>()?; - Ok(FuncType::new(¶ms, &results).into()) + Ok(FuncType::new(¶ms, &results)) } -pub(crate) fn convert_reftype(reftype: wasmparser::RefType) -> Result<WasmType> { - match reftype { - _ if reftype.is_func_ref() => Ok(WasmType::RefFunc), - _ if reftype.is_extern_ref() => Ok(WasmType::RefExtern), - _ => Err(crate::ParseError::UnsupportedOperator(format!( - "Unsupported reference type: {reftype:?}, {:?}", - reftype.heap_type() - ))), - } +pub(crate) fn convert_ref_type(ty: wasmparser::RefType) -> Result<RefType> { + convert_heap_type(ty.heap_type(), ty.is_nullable()) } pub(crate) fn convert_valtype(valtype: &wasmparser::ValType) -> Result<WasmType> { @@ -203,7 +195,7 @@ pub(crate) fn convert_valtype(valtype: &wasmparser::ValType) -> Result<WasmType> wasmparser::ValType::F32 => Ok(WasmType::F32), wasmparser::ValType::F64 => Ok(WasmType::F64), wasmparser::ValType::V128 => Ok(WasmType::V128), - wasmparser::ValType::Ref(r) => convert_reftype(*r), + wasmparser::ValType::Ref(r) => Ok(WasmType::Ref(convert_ref_type(*r)?)), } } @@ -221,16 +213,13 @@ pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<Box<[C } let instr = match op { - wasmparser::Operator::RefNull { hty } => match convert_heaptype(hty)? { - WasmType::RefFunc => ConstInstruction::RefFunc(None), - WasmType::RefExtern => ConstInstruction::RefExtern(None), - other => { - return Err(crate::ParseError::UnsupportedOperator(format!( - "Unsupported ref.null heap type lowered to {other:?}" - ))); - } - }, - wasmparser::Operator::RefFunc { function_index } => ConstInstruction::RefFunc(Some(function_index)), + wasmparser::Operator::RefNull { hty } => { + convert_heap_type(hty, false)?; + ConstInstruction::Ref(RefValue::Null) + } + wasmparser::Operator::RefFunc { function_index } => { + ConstInstruction::Ref(RefValue::Func(FuncRef::new(function_index))) + } wasmparser::Operator::I32Const { value } => ConstInstruction::I32Const(value), wasmparser::Operator::I64Const { value } => ConstInstruction::I64Const(value), wasmparser::Operator::F32Const { value } => ConstInstruction::F32Const(f32::from_bits(value.bits())), @@ -259,14 +248,37 @@ pub(crate) fn process_const_operators(ops: OperatorsReader<'_>) -> Result<Box<[C Ok(out.into_boxed_slice()) } -pub(crate) fn convert_heaptype(heap: wasmparser::HeapType) -> Result<WasmType> { +pub(crate) fn convert_heap_type(heap: wasmparser::HeapType, nullable: bool) -> Result<RefType> { match heap { - wasmparser::HeapType::Abstract { shared: false, ty: wasmparser::AbstractHeapType::Func } => { - Ok(WasmType::RefFunc) + wasmparser::HeapType::Abstract { shared: false, ty } => Ok(RefType::new_abstract( + nullable, + match ty { + wasmparser::AbstractHeapType::Any => AbstractHeapType::Any, + wasmparser::AbstractHeapType::Eq => AbstractHeapType::Eq, + wasmparser::AbstractHeapType::I31 => AbstractHeapType::I31, + wasmparser::AbstractHeapType::Struct => AbstractHeapType::Struct, + wasmparser::AbstractHeapType::Array => AbstractHeapType::Array, + wasmparser::AbstractHeapType::None => AbstractHeapType::None, + wasmparser::AbstractHeapType::Func => AbstractHeapType::Func, + wasmparser::AbstractHeapType::NoFunc => AbstractHeapType::NoFunc, + wasmparser::AbstractHeapType::Exn => AbstractHeapType::Exn, + wasmparser::AbstractHeapType::NoExn => AbstractHeapType::NoExn, + wasmparser::AbstractHeapType::Extern => AbstractHeapType::Extern, + wasmparser::AbstractHeapType::NoExtern => AbstractHeapType::NoExtern, + wasmparser::AbstractHeapType::Cont | wasmparser::AbstractHeapType::NoCont => { + return Err(crate::ParseError::UnsupportedOperator(format!("Unsupported heap type: {heap:?}"))); + } + }, + )), + wasmparser::HeapType::Concrete(index) => { + let index = index.as_module_index().ok_or_else(|| { + crate::ParseError::UnsupportedOperator(format!("Unsupported non-module heap type index: {index:?}")) + })?; + RefType::new_concrete(nullable, index) + .ok_or_else(|| crate::ParseError::Other(format!("heap type index is too large: {index}"))) } - wasmparser::HeapType::Abstract { shared: false, ty: wasmparser::AbstractHeapType::Extern } => { - Ok(WasmType::RefExtern) + wasmparser::HeapType::Abstract { shared: true, .. } | wasmparser::HeapType::Exact(_) => { + Err(crate::ParseError::UnsupportedOperator(format!("Unsupported heap type: {heap:?}"))) } - _ => Err(crate::ParseError::UnsupportedOperator(format!("Unsupported heap type: {heap:?}"))), } } diff --git a/crates/parser/src/macros.rs b/crates/parser/src/macros.rs index ff216a5..723f691 100644 --- a/crates/parser/src/macros.rs +++ b/crates/parser/src/macros.rs @@ -129,6 +129,7 @@ pub(crate) mod visit { (@@wide_arithmetic $($rest:tt)* ) => {}; (@@relaxed_simd $($rest:tt)* ) => {}; (@@tail_call $($rest:tt)* ) => {}; + (@@function_references $($rest:tt)* ) => {}; (@@$proposal:ident $op:ident $({ $($arg:ident: $argty:ty),* })? => $visit:ident ($($ann:tt)*)) => { fn $visit(&mut self $($(,_: $argty)*)?) -> Self::Output { diff --git a/crates/parser/src/module.rs b/crates/parser/src/module.rs index 05811ec..c2199f3 100644 --- a/crates/parser/src/module.rs +++ b/crates/parser/src/module.rs @@ -45,13 +45,13 @@ pub(crate) struct ModuleReader<'a> { pub(crate) version: Option<u16>, pub(crate) start_func: Option<u32>, - pub(crate) func_types: Arc<[Arc<FuncType>]>, + pub(crate) func_types: Box<[FuncType]>, pub(crate) code_type_addrs: Box<[u32]>, code_results: Box<[ValueCounts]>, pub(crate) exports: Arc<[Export]>, pub(crate) code: Vec<FunctionCode>, pub(crate) globals: Box<[Global]>, - pub(crate) table_types: Box<[TableType]>, + pub(crate) tables: Box<[TableDefinition]>, pub(crate) memory_types: Box<[MemoryType]>, pub(crate) imports: Box<[Import]>, pub(crate) data: Box<[Data]>, @@ -73,7 +73,7 @@ impl<'a> ModuleReader<'a> { &self.imports, &self.globals, &self.memory_types, - &self.table_types, + &self.tables, ))); } self.translation_metadata.as_deref().unwrap() @@ -124,22 +124,28 @@ impl<'a> ModuleReader<'a> { self.globals = convert_module_globals(reader)?; } Payload::TableSection(reader) => { - check_section("table", !self.table_types.is_empty())?; + check_section("table", !self.tables.is_empty())?; if let Some(validator) = validator.as_mut() { validator.table_section(&reader)?; } - self.table_types = reader - .into_iter() - .map(|table| { - let table = table?; - let element_type = convert_reftype(table.ty.element_type)?; - Ok(if table.ty.table64 { - TableType::new64(element_type, table.ty.initial, table.ty.maximum) - } else { - TableType::new(element_type, table.ty.initial, table.ty.maximum) - }) - }) - .collect::<Result<_>>()?; + let mut tables = Vec::with_capacity(reader.count() as usize); + for table in reader { + let table = table?; + let element_type = convert_ref_type(table.ty.element_type)?; + let ty = if table.ty.table64 { + TableType::new64(element_type, table.ty.initial, table.ty.maximum) + } else { + TableType::new(element_type, table.ty.initial, table.ty.maximum) + }; + let init = match table.init { + wasmparser::TableInit::RefNull => None, + wasmparser::TableInit::Expr(expr) => { + Some(process_const_operators(expr.get_operators_reader())?) + } + }; + tables.push(TableDefinition { ty, init }); + } + self.tables = tables.into_boxed_slice(); } Payload::MemorySection(reader) => { check_section("memory", !self.memory_types.is_empty())?; @@ -466,7 +472,6 @@ impl<'a> ModuleReader<'a> { locals: code.locals, params, results, - ty, }) }) .collect(); @@ -476,7 +481,7 @@ impl<'a> ModuleReader<'a> { func_types: self.func_types, func_type_idxs, globals: self.globals, - table_types: self.table_types, + tables: self.tables, imports: self.imports, start_func: self.start_func, data: self.data, diff --git a/crates/parser/src/optimize.rs b/crates/parser/src/optimize.rs index 80dfa0d..dcb7568 100644 --- a/crates/parser/src/optimize.rs +++ b/crates/parser/src/optimize.rs @@ -856,6 +856,8 @@ fn instruction_target_mut(instr: &mut Instruction) -> Option<&mut u32> { | Instruction::JumpIfNonZero32(ip) | Instruction::JumpIfZero64(ip) | Instruction::JumpIfNonZero64(ip) + | Instruction::JumpIfRefNull(ip) + | Instruction::JumpIfRefNonNull(ip) | Instruction::JumpCmpStackConst32 { target_ip: ip, .. } | Instruction::JumpCmpStackConst64 { target_ip: ip, .. } | Instruction::JumpIfLocalZero32 { target_ip: ip, .. } @@ -906,6 +908,7 @@ fn is_unconditional_terminator(instr: Instruction) -> bool { | Instruction::ReturnCall(_) | Instruction::ReturnCallSelf | Instruction::ReturnCallIndirect(..) + | Instruction::ReturnCallRef(_) ) } diff --git a/crates/parser/src/visit.rs b/crates/parser/src/visit.rs index dae9ff2..d0e970b 100644 --- a/crates/parser/src/visit.rs +++ b/crates/parser/src/visit.rs @@ -1,9 +1,8 @@ -use crate::{Result, conversion::convert_heaptype, macros::visit::*}; +use crate::{Result, conversion::convert_heap_type, macros::visit::*}; use alloc::string::ToString; -use alloc::sync::Arc; use alloc::vec::Vec; use tinywasm_types::{ - FuncType, Global, Import, ImportKind, Instruction, MemoryArch, MemoryArg, MemoryType, TableType, ValueCounts, + FuncType, Global, Import, ImportKind, Instruction, MemoryArch, MemoryArg, MemoryType, TableDefinition, ValueCounts, WasmFunctionData, WasmType, }; use wasmparser::{ @@ -49,7 +48,7 @@ impl From<wasmparser::ValType> for OperandSize { impl From<&WasmType> for OperandSize { fn from(ty: &WasmType) -> Self { match ty { - WasmType::I32 | WasmType::F32 | WasmType::RefFunc | WasmType::RefExtern => Self::S32, + WasmType::I32 | WasmType::F32 | WasmType::Ref(_) => Self::S32, WasmType::I64 | WasmType::F64 => Self::S64, WasmType::V128 => Self::S128, } @@ -151,12 +150,12 @@ struct ValidateThenVisit<'a, 'm> { impl ModuleMetadata { pub(crate) fn new( - types: &[Arc<FuncType>], + types: &[FuncType], code_type_addrs: &[u32], imports: &[Import], globals: &[Global], memories: &[MemoryType], - tables: &[TableType], + tables: &[TableDefinition], ) -> Self { let mut functions = Vec::with_capacity(imports.len() + code_type_addrs.len()); let mut global_sizes = Vec::with_capacity(imports.len() + globals.len()); @@ -175,7 +174,7 @@ impl ModuleMetadata { 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(|ty| OperandSize::from(ty.arch()))); + table_sizes.extend(tables.iter().map(|table| OperandSize::from(table.ty.arch()))); let signatures = types .iter() @@ -399,6 +398,13 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { self.emit(&inputs, &signature.results, Instruction::CallIndirect(type_index, table_index)) } + fn visit_call_ref(&mut self, type_index: u32) -> Self::Output { + let signature = self.metadata.signature(type_index)?.clone(); + let mut inputs = signature.params; + inputs.push(OperandSize::S32); + self.emit(&inputs, &signature.results, Instruction::CallRef(type_index)) + } + fn visit_return_call(&mut self, function_index: u32) -> Self::Output { let signature = self.metadata.function_signature(function_index)?.clone(); self.apply_effect(&signature.params, &[])?; @@ -417,6 +423,16 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { Ok(()) } + fn visit_return_call_ref(&mut self, type_index: u32) -> Self::Output { + let signature = self.metadata.signature(type_index)?.clone(); + let mut inputs = signature.params; + inputs.push(OperandSize::S32); + self.apply_effect(&inputs, &[])?; + self.mark_unreachable(); + self.instructions.push(Instruction::ReturnCallRef(type_index)); + Ok(()) + } + fn visit_global_set(&mut self, global_index: u32) -> Self::Output { let size = self.metadata.global_size(global_index)?; let instruction = size.choose( @@ -668,10 +684,36 @@ impl<'a> wasmparser::VisitOperator<'a> for FunctionBuilder<'_> { // Reference Types fn visit_ref_null(&mut self, ty: wasmparser::HeapType) -> Self::Output { - let instruction = Instruction::RefNull(convert_heaptype(ty)?); + let instruction = Instruction::RefNull(convert_heap_type(ty, false)?); self.emit(&[], &[OperandSize::S32], instruction) } + fn visit_ref_as_non_null(&mut self) -> Self::Output { + self.emit(&[OperandSize::S32], &[OperandSize::S32], Instruction::RefAsNonNull) + } + + fn visit_br_on_null(&mut self, relative_depth: u32) -> Self::Output { + self.pop_expect(OperandSize::S32)?; + let fallthrough_jump = self.instructions.len(); + self.instructions.push(Instruction::JumpIfRefNonNull(0)); + 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]) + } + + fn visit_br_on_non_null(&mut self, relative_depth: u32) -> Self::Output { + self.pop_expect(OperandSize::S32)?; + let fallthrough_jump = self.instructions.len(); + self.instructions.push(Instruction::JumpIfRefNull(0)); + self.push_sizes(&[OperandSize::S32])?; + self.emit_dropkeep_to_label(relative_depth)?; + self.pop_expect(OperandSize::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 counts = Self::value_counts(&sizes); @@ -1026,7 +1068,11 @@ impl FunctionBuilder<'_> { fn patch_jump(&mut self, jump_ip: usize, target: usize) { match &mut self.instructions[jump_ip] { - Instruction::Jump(ip) | Instruction::JumpIfZero32(ip) | Instruction::JumpIfNonZero32(ip) => { + Instruction::Jump(ip) + | Instruction::JumpIfZero32(ip) + | Instruction::JumpIfNonZero32(ip) + | Instruction::JumpIfRefNull(ip) + | Instruction::JumpIfRefNonNull(ip) => { *ip = target as u32; } _ => {} |
