binaryen.js


Creating WebAssembly
from JavaScript


Alon Zakai

Background


WebAssembly (wasm) is a new binary executable format for the web.

It's compact and fast.

Binaryen


A compiler library for WebAssembly, providing a bunch of useful things.

For example, an optimizer: shrinks optimized LLVM wasm binaries by ~5% (C++ or Rust) by just doing


  wasm-opt -Os input.wasm -o output.wasm
            

(like a JavaScript minifier, but for WebAssembly)

You can also write a compiler
with Binaryen


binaryen.js


API lets you:

  • Create Binaryen IR
  • Optimize it, etc.
  • Generate wasm from that

binaryen.js is used by AssemblyScript, a subset of TypeScript that compiles to WebAssembly:

Creating IR



// Example from a Mandlebrot computation

// if we ran enough iterations, return 0
var code = module.if(
  module.i32.ge_u(                        // >= (unsigned)
    module.get_local(6, Binaryen.i32),    // the counter
    module.i32.const(MAX_ITERS_PER_PIXEL) // the limit
  ),
  module.return(
    module.i32.const(0)
  )
);
          

Creating wasm



// Create a module
var module = new Binaryen.Module();

// [..create module contents, examples on last slide..]

// Optionally, optimize the module
module.optimize();

// Get a wasm binary (in typed array form)
var binary = module.emitBinary();
          

Running the wasm



// Compile the binary
WebAssembly.instantiate(binary, {}).then(function(output) {
  var wasm = output.instance;

  // Call it!
  wasm.exports.function_name();
});
          


The end, thanks for listening!