Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions src/backend/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,12 @@ impl<'a> WasmFuncBackend<'a> {
let from_ty = self.body.values[self.body.resolve_alias(from)]
.ty(&self.body.type_pool)
.unwrap();
assert_eq!(from_ty, to_ty);
assert!(
from_ty.is_subtype_of(to_ty),
"block argument type {} is not a subtype of {}",
from_ty,
to_ty
);
if ctx.locals.values[from].len() == 1 {
assert_eq!(from_ty, ctx.locals.locals[ctx.locals.values[from][0]]);
}
Expand Down Expand Up @@ -1006,8 +1011,8 @@ impl<'a> WasmFuncBackend<'a> {
Some(wasm_encoder::Instruction::CallRef(sig_index.index() as u32))
}
Operator::RefIsNull => Some(wasm_encoder::Instruction::RefIsNull),
Operator::RefNull { sig_index } => Some(wasm_encoder::Instruction::RefNull(
wasm_encoder::HeapType::Concrete(sig_index.index() as u32),
Operator::RefNull { ty } => Some(wasm_encoder::Instruction::RefNull(
wasm_encoder::RefType::from(*ty).heap_type,
)),
Operator::RefFunc { func_index } => {
Some(wasm_encoder::Instruction::RefFunc(func_index.index() as u32))
Expand Down Expand Up @@ -1643,9 +1648,8 @@ fn const_init(ty: Type, value: Option<u64>) -> wasm_encoder::ConstExpr {
Type::I64 => wasm_encoder::ConstExpr::i64_const(bits as i64),
Type::F32 => wasm_encoder::ConstExpr::f32_const(f32::from_bits(bits as u32).into()),
Type::F64 => wasm_encoder::ConstExpr::f64_const(f64::from_bits(bits as u64).into()),
Type::TypedFuncRef(true, sig) if bits == 0 => {
let hty = wasm_encoder::HeapType::Concrete(sig);
wasm_encoder::ConstExpr::ref_null(hty)
Type::FuncRef | Type::ExternRef | Type::TypedFuncRef(true, _) if bits == 0 => {
wasm_encoder::ConstExpr::ref_null(wasm_encoder::RefType::from(ty).heap_type)
}
_ => unimplemented!(),
}
Expand Down
55 changes: 36 additions & 19 deletions src/frontend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use addr2line::gimli;
use anyhow::{bail, Result};
use fxhash::{FxHashMap, FxHashSet};
use log::trace;
use std::convert::TryFrom;
use std::convert::{TryFrom, TryInto};
use wasmparser::{BlockType, DataKind, ExternalKind, KnownCustom, Name, Parser, Payload, TypeRef};

/// Options to control the Wasm-to-bytecode translation process.
Expand Down Expand Up @@ -98,7 +98,7 @@ fn element_type(items: &wasmparser::ElementItems) -> Result<Type> {
wasmparser::ElementItems::Expressions(ty, _)
if *ty == wasmparser::RefType::FUNCREF || ty.type_index().is_some() =>
{
Ok((*ty).into())
Ok((*ty).try_into()?)
}
wasmparser::ElementItems::Expressions(ty, _) => bail!(FrontendError::UnsupportedFeature(
format!("Unsupported element segment type: {:?}", ty)
Expand Down Expand Up @@ -164,13 +164,14 @@ fn memory_data(ty: &wasmparser::MemoryType) -> Result<MemoryData> {
}

/// Converts a table type to a `TableData` with no elements. Returns
/// `FrontendError::UnsupportedFeature` for a 64-bit table.
/// `FrontendError::UnsupportedFeature` for a 64-bit table and for an
/// element type that `Type` cannot represent.
fn table_data(ty: &wasmparser::TableType) -> Result<TableData> {
if ty.table64 {
bail!(FrontendError::UnsupportedFeature("64-bit table".into()));
}
Ok(TableData {
ty: ty.element_type.into(),
ty: ty.element_type.try_into()?,
initial: ty.initial,
max: ty.maximum,
initializer: None,
Expand Down Expand Up @@ -238,9 +239,14 @@ fn handle_payload<'a>(
Payload::TypeSection(reader) => {
for rec_group in reader {
for ty in rec_group?.into_types() {
if ty.composite_type.shared {
bail!(FrontendError::UnsupportedFeature(
"shared type in type section".into()
));
}
match &ty.composite_type.inner {
wasmparser::CompositeInnerType::Func(fty) => {
module.signatures.push(fty.into());
module.signatures.push(fty.try_into()?);
}
_ => bail!(FrontendError::UnsupportedFeature(
"non-function type in type section".into()
Expand All @@ -265,7 +271,7 @@ fn handle_payload<'a>(
}
TypeRef::Global(ty) => {
let mutable = ty.mutable;
let ty = ty.content_type.into();
let ty = ty.content_type.try_into()?;
let global = module.globals.push(GlobalData {
ty,
value: None,
Expand Down Expand Up @@ -322,7 +328,7 @@ fn handle_payload<'a>(
for global in reader {
let global = global?;
let mutable = global.ty.mutable;
let ty = global.ty.content_type.into();
let ty = global.ty.content_type.try_into()?;
let init_expr = parse_init_expr(&global.init_expr)?;
module.globals.push(GlobalData {
ty,
Expand Down Expand Up @@ -549,7 +555,7 @@ fn handle_payload<'a>(
let table = Table::from(table_index.unwrap_or(0));
let ty = match &element.items {
wasmparser::ElementItems::Functions(_) => Type::FuncRef,
wasmparser::ElementItems::Expressions(ty, _) => (*ty).into(),
wasmparser::ElementItems::Expressions(ty, _) => (*ty).try_into()?,
};
module.active_element_segments.push(ActiveElementSegment {
index,
Expand Down Expand Up @@ -671,7 +677,7 @@ pub(crate) fn parse_body<'a>(
for _ in 0..locals.get_count() {
let (count, ty) = locals.read()?;
for _ in 0..count {
ret.locals.push(ty.into());
ret.locals.push(ty.try_into()?);
}
}
let locals = ret.locals.clone();
Expand Down Expand Up @@ -900,7 +906,10 @@ impl LocalTracker {
Type::F32 => body.add_op(at_block, Operator::F32Const { value: 0 }, &[], &[ty]),
Type::F64 => body.add_op(at_block, Operator::F64Const { value: 0 }, &[], &[ty]),
Type::V128 => body.add_op(at_block, Operator::V128Const { value: 0 }, &[], &[ty]),
_ => todo!("unsupported type: {:?}", ty),
Type::FuncRef | Type::ExternRef | Type::TypedFuncRef(true, _) => {
body.add_op(at_block, Operator::RefNull { ty }, &[], &[ty])
}
Type::TypedFuncRef(false, _) => todo!("unsupported type: {:?}", ty),
};
log::trace!(
"created default value {} of type {} at block {}",
Expand Down Expand Up @@ -1618,7 +1627,10 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> {
| wasmparser::Operator::RefFunc { .. }
| wasmparser::Operator::MemoryFill { .. }
| wasmparser::Operator::MemoryCopy { .. } => {
self.emit(Operator::try_from(&op).unwrap(), loc)?
let op = Operator::try_from(&op).map_err(|()| {
FrontendError::UnsupportedFeature(format!("Unsupported operator: {:?}", op))
})?;
self.emit(op, loc)?
}

wasmparser::Operator::Nop => {}
Expand Down Expand Up @@ -1851,7 +1863,7 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> {
}

wasmparser::Operator::Block { blockty } => {
let (params, results) = self.block_params_and_results(*blockty);
let (params, results) = self.block_params_and_results(*blockty)?;
let out = self.body.add_block();
self.add_block_params(out, &results[..]);
let start_depth = if self.reachable {
Expand All @@ -1869,7 +1881,7 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> {
}

wasmparser::Operator::Loop { blockty } => {
let (params, results) = self.block_params_and_results(*blockty);
let (params, results) = self.block_params_and_results(*blockty)?;
let header = self.body.add_block();
self.add_block_params(header, &params[..]);
let initial_args = if self.reachable {
Expand All @@ -1895,7 +1907,7 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> {
}

wasmparser::Operator::If { blockty } => {
let (params, results) = self.block_params_and_results(*blockty);
let (params, results) = self.block_params_and_results(*blockty)?;
let if_true = self.body.add_block();
let if_false = self.body.add_block();
let join = self.body.add_block();
Expand Down Expand Up @@ -1983,18 +1995,18 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> {
}
}

fn block_params_and_results(&self, ty: BlockType) -> (Vec<Type>, Vec<Type>) {
match ty {
fn block_params_and_results(&self, ty: BlockType) -> Result<(Vec<Type>, Vec<Type>)> {
Ok(match ty {
BlockType::Empty => (vec![], vec![]),
BlockType::Type(ret_ty) => (vec![], vec![ret_ty.into()]),
BlockType::Type(ret_ty) => (vec![], vec![ret_ty.try_into()?]),
BlockType::FuncType(sig_idx) => {
let sig = &self.module.signatures[Signature::from(sig_idx)];
(
Vec::from(sig.params.clone()),
Vec::from(sig.returns.clone()),
)
}
}
})
}

fn relative_frame(&mut self, relative_depth: u32) -> &mut Frame {
Expand Down Expand Up @@ -2156,7 +2168,12 @@ impl<'a, 'b> FunctionBodyBuilder<'a, 'b> {
let args = &mut self.body.arg_pool[input_operands];
for (i, &input) in inputs.into_iter().enumerate().rev() {
let (stack_top_ty, stack_top) = self.op_stack.pop().unwrap();
assert_eq!(stack_top_ty, input);
assert!(
stack_top_ty.is_subtype_of(input),
"operand type {} is not a subtype of {}",
stack_top_ty,
input
);
args[i] = stack_top;
}
log::trace!(" -> operands: {:?}", input_operands);
Expand Down
90 changes: 72 additions & 18 deletions src/ir.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
//! Intermediate representation for Wasm.

use crate::declare_entity;
use crate::FrontendError;
use std::convert::{TryFrom, TryInto};

/// Types in waffle's IR.
///
/// These types correspond to (a subset of) the primitive Wasm value
/// types: integers, floats, SIMD vectors, and function references
/// (optionally typed).
/// types: integers, floats, SIMD vectors, function references
/// (optionally typed), and external references.
///
/// Every SSA value in a function body has a `Type`, unless it is a
/// tuple (multi-value or zero-value result).
Expand All @@ -32,31 +34,61 @@ pub enum Type {
V128,
/// A function reference.
FuncRef,
/// A nullable external reference (`externref`).
ExternRef,
/// A typed function reference, optionally nullable, and with type
/// specified by a signature index in the module's signature
/// index-space.
TypedFuncRef(bool, u32),
}
impl From<wasmparser::ValType> for Type {
fn from(ty: wasmparser::ValType) -> Self {
impl TryFrom<wasmparser::ValType> for Type {
type Error = FrontendError;

fn try_from(ty: wasmparser::ValType) -> Result<Self, FrontendError> {
match ty {
wasmparser::ValType::I32 => Type::I32,
wasmparser::ValType::I64 => Type::I64,
wasmparser::ValType::F32 => Type::F32,
wasmparser::ValType::F64 => Type::F64,
wasmparser::ValType::V128 => Type::V128,
wasmparser::ValType::Ref(r) => r.into(),
wasmparser::ValType::I32 => Ok(Type::I32),
wasmparser::ValType::I64 => Ok(Type::I64),
wasmparser::ValType::F32 => Ok(Type::F32),
wasmparser::ValType::F64 => Ok(Type::F64),
wasmparser::ValType::V128 => Ok(Type::V128),
wasmparser::ValType::Ref(r) => r.try_into(),
}
}
}
impl From<wasmparser::RefType> for Type {
fn from(ty: wasmparser::RefType) -> Self {
match ty.type_index() {
Some(idx) => {
let nullable = ty.is_nullable();
Type::TypedFuncRef(nullable, idx.as_module_index().unwrap())
/// Converts a reference type to a `Type`. Nullable `func` and `extern`
/// references convert to `FuncRef` and `ExternRef`, and references to a
/// module type index convert to `TypedFuncRef`. Every other reference
/// type returns `FrontendError::UnsupportedFeature`: non-nullable
/// abstract references, shared abstract references, exact references,
/// references to a rec-group type index, and abstract heap types other
/// than `func` and `extern`.
impl TryFrom<wasmparser::RefType> for Type {
type Error = FrontendError;

fn try_from(ty: wasmparser::RefType) -> Result<Self, FrontendError> {
use wasmparser::{AbstractHeapType, HeapType, UnpackedIndex};
match (ty.heap_type(), ty.is_nullable()) {
(HeapType::Concrete(UnpackedIndex::Module(idx)), nullable) => {
Ok(Type::TypedFuncRef(nullable, idx))
}
None => Type::FuncRef,
(
HeapType::Abstract {
shared: false,
ty: AbstractHeapType::Func,
},
true,
) => Ok(Type::FuncRef),
(
HeapType::Abstract {
shared: false,
ty: AbstractHeapType::Extern,
},
true,
) => Ok(Type::ExternRef),
_ => Err(FrontendError::UnsupportedFeature(format!(
"Unsupported reference type: {}",
ty
))),
}
}
}
Expand All @@ -70,6 +102,7 @@ impl std::fmt::Display for Type {
Type::F64 => write!(f, "f64"),
Type::V128 => write!(f, "v128"),
Type::FuncRef => write!(f, "funcref"),
Type::ExternRef => write!(f, "externref"),
Type::TypedFuncRef(nullable, idx) => write!(
f,
"funcref({}, {})",
Expand All @@ -88,7 +121,9 @@ impl From<Type> for wasm_encoder::ValType {
Type::F32 => wasm_encoder::ValType::F32,
Type::F64 => wasm_encoder::ValType::F64,
Type::V128 => wasm_encoder::ValType::V128,
Type::FuncRef | Type::TypedFuncRef(..) => wasm_encoder::ValType::Ref(ty.into()),
Type::FuncRef | Type::ExternRef | Type::TypedFuncRef(..) => {
wasm_encoder::ValType::Ref(ty.into())
}
}
}
}
Expand All @@ -97,6 +132,7 @@ impl From<Type> for wasm_encoder::RefType {
fn from(ty: Type) -> wasm_encoder::RefType {
match ty {
Type::FuncRef => wasm_encoder::RefType::FUNCREF,
Type::ExternRef => wasm_encoder::RefType::EXTERNREF,
Type::TypedFuncRef(nullable, idx) => wasm_encoder::RefType {
nullable,
heap_type: wasm_encoder::HeapType::Concrete(idx),
Expand All @@ -106,6 +142,24 @@ impl From<Type> for wasm_encoder::RefType {
}
}

impl Type {
/// Returns `true` if a value of type `self` is valid where a value of
/// type `other` is expected: the types are equal, `self` is a typed
/// function reference and `other` is `FuncRef`, or both are typed
/// function references with the same signature index and `other` is
/// nullable or `self` is not. Signature indices are compared by
/// index, not by the signatures they refer to.
pub(crate) fn is_subtype_of(self, other: Type) -> bool {
match (self, other) {
(Type::TypedFuncRef(..), Type::FuncRef) => true,
(Type::TypedFuncRef(sub_nullable, sub_sig), Type::TypedFuncRef(nullable, sig)) => {
sub_sig == sig && (nullable || !sub_nullable)
}
_ => self == other,
}
}
}

// Per-module index spaces:

// A signature (list of parameter types and list of return types) in
Expand Down
Loading
Loading