@ 261106.1raw
current

Multiple Memories for Wasm

Summary

This proposal adds the ability to use multiple memories within a single Wasm module. In the current version of Wasm, an application can already create multiple memories, but only by splitting things up into multiple modules. A single module or function cannot refer to multiple memories at the same time. Consequently, it is not possible to e.g. efficiently transfer data from one memory to another, since that necessarily involves an individual function call into a different module per value.

Motivation

There are a number of use case scenarios for using multiple memories in a single application:

Overview

The original Wasm design already anticipated the ability to define and reference multiple memories. In particular, there already is the notion of an index space for memories (which currently can contain at most one entry), and most memory constructs already leave space in the binary encoding for it. This proposal fills in the holes accordingly.

This generalisation is fully symmetric to the extension to multiple tables in the reference typesgithub proposal.

The design of this extension is almost entirely canonical. Concretely:

Instructions

Except where noted, the following changes apply to each load and store instruction as well as to memory.size and memory.grow. Corresponding changes will be necessary for the new instructions introduced by the bulk memory proposal.instructions.

Abstract syntax:

Validation:

Execution:

Binary format:

Text format:

Modules

Data Segments and Memory Exports

The abstract syntax for data segments and memory exports already carry a memory index that is checked and used accordingly (even though it currently is known to be 0). Binary and text format also already have the corresponding index parameter (which is optional and defaults to 0 in the case of data segments).

So technically, no spec change is necessary, though implementations now need to deal with the possibility that the index is not 0.

Modules

Implementation

Engines already have to deal with multiple memories, but any given code so far can only address one. Hence, in current engines, reserving one register for the base address is a common technique. Multiple memories will typically require an extra indirection (which some engines already have).

Engines could conservatively continue to optimise access to memory index 0 via a dedicated register. Presumably, we could also eventually add a future custom section with optimisation hints, which could e.g. mark the index of the “main” memory.