Oxeon / Examples / WebAssembly instructions

WebAssembly instructions

WebAssembly instructions in Oxeon through Rust’s primitive methods (count_ones, sqrt, rotate_left, to_bits) and core::arch::wasm32.

Partly works today

Every function here compiles today except add4: core::arch::wasm32 and SIMD are planned.

Oxeon reaches WebAssembly instructions the way Rust does, so the code stays valid Rust and the type and borrow checkers cover it. Methods on the primitive types compile to one instruction each: count_ones is i32.popcnt, sqrt is f32.sqrt, to_bits is i32.reinterpret_f32.

Where Rust’s method and the instruction disagree, Rust wins. f32::min ignores a NaN argument, while f32.min returns NaN, so min checks for NaN first. round rounds halves away from zero, while f32.nearest rounds them to even, which is round_ties_even. mul_add must round once, and WebAssembly has no instruction for that, so multiply_add here is a multiply and an add, rounded twice.

The rest, such as SIMD, is planned through core::arch::wasm32, with Rust’s names and signatures.

14_wasm_instructions.ox

examples/syntax/14_wasm_instructions.ox
// WebAssembly instructions, the way Rust exposes them: methods on the
// primitive types that compile to one instruction each, and
// `core::arch::wasm32` for the rest, such as SIMD. It's all plain Rust, so
// this file compiles with `rustc` for wasm32 too.

/// `i32.popcnt`.
fn popcount(x: u32) -> u32 {
    x.count_ones()
}

/// `31 - i32.clz`: the position of the highest set bit.
fn log2(x: u32) -> u32 {
    31 - x.leading_zeros()
}

/// `i32.rotl`, in a small hash.
fn mix(seed: u32, value: u32) -> u32 {
    (seed ^ value).wrapping_mul(0x9E37_79B9).rotate_left(5)
}

/// `f32.sqrt`.
fn length(x: f32, y: f32) -> f32 {
    (x * x + y * y).sqrt()
}

/// `f32.floor`.
fn snap(x: f32, grid: f32) -> f32 {
    (x / grid).floor() * grid
}

/// `f32.mul` then `f32.add`: rounded after each. Rust's `f32::mul_add`
/// rounds once, and WebAssembly has no instruction for that, so Oxeon
/// doesn't offer `mul_add` yet.
fn multiply_add(a: f32, b: f32, c: f32) -> f32 {
    a * b + c
}

/// `i32.reinterpret_f32` and back: the next float after a positive `x`.
fn next_up(x: f32) -> f32 {
    f32::from_bits(x.to_bits() + 1)
}

/// SIMD (planned): four `f32` additions in one `f32x4.add`.
fn add4(a: core::arch::wasm32::v128, b: core::arch::wasm32::v128) -> core::arch::wasm32::v128 {
    core::arch::wasm32::f32x4_add(a, b)
}