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
277 changes: 153 additions & 124 deletions AstSemantics.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,35 +32,62 @@ Callstack space is limited by unspecified and dynamically varying constraints.
If program callstack usage exceeds the available callstack space at any time,
a trap occurs.

## Local and Memory types

Individual storage locations in WebAssembly are typed, including global
variables, local variables, and parameters. The main storage of a wasm module,
called the *Linear memory*, is a contiguous, byte-addressable range of memory
spanning from offset `0` to `memory_size`. The linear memory can be considered
to be a untyped array of bytes which is stored separately from the global variables.
The linear memory is sandboxed; it does not alias the execution engine's internal
data structures, the execution stack, or other process memory.
All accesses to memory are annotated with a type. The legal types for
global variables and memory accesses are called *Memory types*.
## Types

* `int8`: 8-bit integer
* `int16`: 16-bit integer
* `int32`: 32-bit integer
* `int64`: 64-bit integer
* `float32`: 32-bit floating point
* `float64`: 64-bit floating point
### Local Types

The legal types for parameters and local variables, called *Local types*
are a subset of the Memory types:
The following types are called the *local types*:

* `int32`: 32-bit integer
* `int64`: 64-bit integer
* `float32`: 32-bit floating point
* `float64`: 64-bit floating point

All operations except loads and stores deal with local types. Loads convert
Memory types to Local types according to the following rules:
Note that the local types `int32` and `int64` are not inherently signed or
unsigned. The interpretation of these types is determined by individual
operations.

Parameters and local variables use local types.

### Expression Types

*Expression types* include all the local types, and also:

* `void`: no value

AST expression nodes use expression types.

### Memory Types

*Memory types* are a different superset of the local types, adding the
following:

* `int8`: 8-bit integer
* `int16`: 16-bit integer

Global variables and linear memory accesses use memory types.

## Linear Memory

The main storage of a wasm module, called the *linear memory*, is a contiguous,
byte-addressable range of memory spanning from offset `0` and extending for
`memory_size` bytes. The linear memory can be considered to be a untyped array
of bytes. The linear memory is sandboxed; it does not alias the execution
engine's internal data structures, the execution stack, local variables, global
variables, or other process memory.

In the MVP, linear memory is not shared between threads. When
[threads](PostMVP.md#threads) are added as a feature, regular load and store
nodes will have the most relaxed semantics specified in the memory model and new
memory-access nodes will be added with atomic and ordering guarantees.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regular loads and stores won't have relaxed semantics: they're instead bound by happens-before with atomics in the same thread of execution, which themselves synchronize-with atomics in other threads.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is text that was already present, and is just being moved in this patch. I can attempt to clarify this text though and avoid the ambiguous word "relaxed" in this context.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ha, I didn't notice it the first time around. I can also do a separate PR following yours, if that's cleaner.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, if you don't mind, that'd be simpler.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will do. Filed #248 to do this once this PR is checked in.


### Linear Memory Operations

Linear memory operations are annotated with a memory type and perform a
conversion between that memory type and a local type.

Loads read data from linear memory, convert from their memory type to a basic

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We've been using the term local type in other places.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I grepped the design repo and didn't see any other references. Do you prefer "local" over "basic" here? These types do get used outside of "local" contexts.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I recall using "local type" in AstSemantics. Maybe those references have
been refactored away. "Local" is nice because it relates to local variables.

On Tue, Jul 7, 2015 at 2:52 PM, Dan Gohman [email protected] wrote:

In AstSemantics.md
#245 (comment):

+memory_size bytes. The linear memory can be considered to be a untyped array
+of bytes. The linear memory is sandboxed; it does not alias the execution
+engine's internal data structures, the execution stack, local variables, global
+variables, or other process memory.
+
+In the MVP, linear memory is not shared between threads. When
+threads are added as a feature, regular load and store
+nodes will have the most relaxed semantics specified in the memory model and new
+memory-access nodes will be added with atomic and ordering guarantees.
+
+### Linear Memory Operations
+
+Linear memory operations are annotated with a memory type and perform a
+conversion between that memory type and a basic type.
+
+Loads read data from linear memory, convert from their memory type to a basic

I grepped the design repo and didn't see any other references. Do you
prefer "local" over "basic" here? These types do get used outside of
"local" contexts.

—
Reply to this email directly or view it on GitHub
https://github.com/WebAssembly/design/pull/245/files#r34035409.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I had found and replaced them all :-). But I don't feel strongly about this right now, so I've now added another patch to revert back to "local types".

type, and return the result:

* `int32.load_sx[int8]`: sign-extend to int32
* `int32.load_sx[int16]`: sign-extend to int32
Expand All @@ -77,11 +104,8 @@ Memory types to Local types according to the following rules:
* `float32.load[float32]`: (no conversion)
* `float64.load[float64]`: (no conversion)

Note that the local types `int32` and `int64` don't technically have a sign; the
sign bit is interpreted differently by the operations below.

Similar to loads, stores convert Local types to Memory types according to the
following rules:
Stores have an operand providing a value to store. They convert from the value's
local type to their memory type, and write the resulting value to linear memory:

* `int32.store[int8]`: wrap int32 to int8
* `int32.store[int16]`: wrap int32 to int16
Expand All @@ -96,107 +120,61 @@ following rules:
Wrapping of integers simply discards any upper bits; i.e. wrapping does not
perform saturation, trap on overflow, etc.

## Addressing local variables
In addition to storing a value to linear memory, store instructions also
reproduce their value operand, with no conversion applied.

Each function has a fixed, pre-declared number of local variables which occupy a single
index space local to the function. Parameters are addressed as local variables. Local
variables do not have addresses and are not aliased in the globals or memory. Local
variables have *Local types* and are initialized to the appropriate zero value for their
type at the beginning of the function, except parameters which are initialized to the values
of the arguments passed to the function.
### Addressing

* `get_local`: read the current value of a local variable
* `set_local`: set the current value of a local variable

The details of index space for local variables and their types will be further clarified,
e.g. whether locals with type `int32` and `int64` must be contiguous and separate from
others, etc.
Each linear memory access operation also has an address operand and an immediate
integer byte offset attribute. The infinite-precision sum of the address
operand's value with the byte offset attribute's value is called the
*effective address*, which is interpreted as an unsigned byte index.

## Control flow structures
Linear memory accesses access the bytes starting at the location in the linear
memory storage indexed by the effective address, and extending for the number
of bytes implied by the memory type attribute of the access.

WebAssembly offers basic structured control flow. All control flow structures
are statements.
If any of the accessed bytes are beyond `memory_size`, the access is considered
*out-of-bounds*. A module may optionally define that out-of-bounds includes
small effective addresses close to `0`
(see [discussion](https://github.com/WebAssembly/design/issues/204)).
The semantics of out-of-bounds accesses are discussed
[below](AstSemantics.md#out-of-bounds).

* `block`: a fixed-length sequence of statements
* `if`: if statement
* `do_while`: do while statement, basically a loop with a conditional branch
(back to the top of the loop)
* `forever`: infinite loop statement (like `while (1)`), basically an
unconditional branch (back to the top of the loop)
* `continue`: continue to start of nested loop
* `break`: break to end from nested loop or block
* `return`: return zero or more values from this function
* `switch`: switch statement with fallthrough
The use of infinite-precision in the effective address computation means that
the addition of the offset to the address does is never wrapped, so if the
address for an access is out-of-bounds, the effective address will always also
be out-of-bounds. This is intended to simplify folding of offsets into complex
address modes in hardware, and to simplify bounds checking optimizations.

Break and continue statements can only target blocks or loops in which they are
nested. This guarantees that all resulting control flow graphs are well-structured.
In the MVP, address operands and offset attributes have type `int32`, and linear
memory sizes are limited to 4 GiB (of course, actual sizes are further limited
by [available resources](Nondeterminism.md)). In the future, to support
[>4GiB linear memory](FutureFeatures.md#heaps-bigger-than-4gib), support for
indices with type `int64` will be added.

* Simple and size-efficient binary encoding and compilation.
* Any control flow—even irreducible—can be transformed into structured control
flow with the
[Relooper](https://github.com/kripken/emscripten/raw/master/docs/paper.pdf)
[algorithm](http://dl.acm.org/citation.cfm?id=2048224&CFID=670868333&CFTOKEN=46181900),
with guaranteed low code size overhead, and typically minimal throughput
overhead (except for pathological cases of irreducible control
flow). Alternative approaches can generate reducible control flow via node
splitting, which can reduce throughput overhead, at the cost of increasing
code size (potentially very significantly in pathological cases).
* The
[signature-restricted proper tail-call](PostMVP.md#signature-restricted-proper-tail-calls)
feature would allow efficient compilation of arbitrary irreducible control
flow.

## Accessing Linear Memory

Programs address memory by using integers that are interpreted as unsigned byte indexes
starting at `0`.
Accesses to memory at indices larger than the size of memory are considered out-of-bounds,
and a module may optionally define that out-of-bounds includes small indices close to `0` (see [discussion] (https://github.com/WebAssembly/design/issues/204)).
Out-of-bounds access is considered a program error, and the semantics are discussed below.
Each memory access is annotated with a *Memory type* and the presumed alignment of the index.

* `load_mem`: load a value from memory at a given index with given
alignment
* `store_mem`: store a given value to memory at a given index with given
alignment

To enable more aggressive hoisting of bounds checks, memory accesses may also
include an offset:

* `load_mem_with_offset`: load a value from memory at a given index plus a
given immediate offset
* `store_mem_with_offset`: store a given value to memory at a given index
plus a given immediate offset

The addition of the offset and index is specified to use infinite precision such
that an out-of-bounds access never wraps around to an in-bounds access. Bounds
checking before the final offset addition allows the offset addition to easily
be folded into the hardware load instruction *and* for groups of loads with the
same base and different offsets to easily share a single bounds check.
### Alignment

In the MVP, the indices are 32-bit unsigned integers. With
[64-bit integers](PostMVP.md#64-bit-integers) and
[>4GiB memory](FutureFeatures.md#heaps-bigger-than-4gib), these nodes would also
accept 64-bit unsigned integers.
Each linear memory access operation also has an immediate positive integer power
of 2 alignment attribute. An alignment value which is the same as the memory
attribute size is considered to be a *natural* alignment.

In the MVP, linear memory is not shared between threads. When
[threads](PostMVP.md#threads) are added as a feature, the basic
`load_mem`/`store_mem` nodes will have the most relaxed semantics specified in
the memory model and new memory-access nodes will be added with atomic and
ordering guarantees.
If the effective address of a memory access is a multiple of the alignment
attribute value of the memory access, the memory access is considered *aligned*,
otherwise it is considered *misaligned*. Aligned and misaligned accesses have
the same behavior. Alignment affects performance as follows:

Two important semantic cases are **misaligned** and **out-of-bounds** accesses:
* Aligned accesses with at least natural alignment are fast.
* Aligned accesses with less than natural alignment may be somewhat slower
(think: implementation makes multiple accesses, either in software or
in hardware).
* Misaligned access of any kind may be *massively* slower
(think: implementation takes a signal and fixes things up)

### Alignment

If the incoming index argument to a memory access is misaligned with respect to
the alignment operand of the memory access, the memory access must still work
correctly (as if the alignment operand was `1`). However, on some platforms,
such misaligned accesses may incur a *massive* performance penalty (due to trap
handling). Thus, it is highly recommend that every WebAssembly producer provide
accurate alignment. Note: on platforms without unaligned accesses,
smaller-than-natural alignment may result in slower code generation (due to the
whole access being broken into smaller aligned accesses).
Thus, it is recommend that WebAssembly producers align frequently-used data
to permit the use of natural alignment access, and use loads and stores with
the grestest alignment values practical, while always avoiding misaligned
accesses.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you also mention that a misaligned access which is partly out-of-bounds traps?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm rewording the out-of-bounds discussion per your comments above, and that will hopefully clarify this.


Either tooling or an explicit opt-in "debug mode" in the spec should allow
execution of a module in a mode that threw exceptions on misaligned access.
Expand All @@ -205,11 +183,12 @@ is why it isn't the specified default.)

### Out of bounds

The ideal semantics is for out-of-bounds accesses to trap, but the
implications are not yet fully clear.
The ideal semantics is for out-of-bounds accesses to trap, but the implications
are not yet fully clear.

There are several possible variations on this design being discussed and
experimented with. More measurement is required to understand the associated tradeoffs.
experimented with. More measurement is required to understand the associated
tradeoffs.

* After an out-of-bounds access, the module can no longer execute code and any
outstanding JS ArrayBuffers aliasing the linear memory are detached.
Expand All @@ -229,10 +208,26 @@ experimented with. More measurement is required to understand the associated tra
execution of a module in a mode that threw exceptions on out-of-bounds
access.

## Accessing globals
## Local variables

Each function has a fixed, pre-declared number of local variables which occupy a single
index space local to the function. Parameters are addressed as local variables. Local
variables do not have addresses and are not aliased in the globals or memory. Local
variables have local types and are initialized to the appropriate zero value for their
type at the beginning of the function, except parameters which are initialized to the values
of the arguments passed to the function.

* `get_local`: read the current value of a local variable
* `set_local`: set the current value of a local variable

The details of index space for local variables and their types will be further clarified,
e.g. whether locals with type `int32` and `int64` must be contiguous and separate from
others, etc.

## Global variables

Global variables are storage locations outside the linear memory.
Every global has exactly one Memory type.
Every global has exactly one memory type.
Accesses to global variables specify the index as an integer literal.

* `load_global`: load the value of a given global variable
Expand All @@ -241,14 +236,48 @@ Accesses to global variables specify the index as an integer literal.
The specification will add atomicity annotations in the future. Currently
all global accesses can be considered "non-atomic".

## Control flow structures

WebAssembly offers basic structured control flow. All control flow structures
are statements.

* `block`: a fixed-length sequence of statements
* `if`: if statement
* `do_while`: do while statement, basically a loop with a conditional branch
(back to the top of the loop)
* `forever`: infinite loop statement (like `while (1)`), basically an
unconditional branch (back to the top of the loop)
* `continue`: continue to start of nested loop
* `break`: break to end from nested loop or block
* `return`: return zero or more values from this function
* `switch`: switch statement with fallthrough

Break and continue statements can only target blocks or loops in which they are
nested. This guarantees that all resulting control flow graphs are well-structured.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

switch doesn't allow Duff's device, even though it supports fallthrough, because the AST structure prevents nesting a loop which straddles switch statement blocks.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is also pre-existing text. I'll submit a followup PR for this.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SGTM


* Simple and size-efficient binary encoding and compilation.
* Any control flow—even irreducible—can be transformed into structured control
flow with the
[Relooper](https://github.com/kripken/emscripten/raw/master/docs/paper.pdf)
[algorithm](http://dl.acm.org/citation.cfm?id=2048224&CFID=670868333&CFTOKEN=46181900),
with guaranteed low code size overhead, and typically minimal throughput
overhead (except for pathological cases of irreducible control
flow). Alternative approaches can generate reducible control flow via node
splitting, which can reduce throughput overhead, at the cost of increasing
code size (potentially very significantly in pathological cases).
* The
[signature-restricted proper tail-call](PostMVP.md#signature-restricted-proper-tail-calls)
feature would allow efficient compilation of arbitrary irreducible control
flow.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This list is missing a paragraph that explains it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is more pre-existing text :-). I agree that there's a lot of clarification needed. Let's handle this in follow-up PRs.


## Calls

Direct calls to a function specify the callee by index into a function table.

* `call_direct`: call function directly

Each function has a signature in terms of local types, and calls must match the
function signature
Each function has a signature in terms of expression types, and calls must match
the function signature
exactly. [Imported functions](MVP.md#code-loading-and-imports) also have
signatures and are added to the same function table and are thus also callable
via `call_direct`.
Expand Down Expand Up @@ -279,7 +308,7 @@ values.

## Literals

Each Local type allows literal values directly in the AST. See the
Each local type allows literal values directly in the AST. See the
[binary encoding section](BinaryEncoding.md#constant-pool).

## Expressions with control flow
Expand Down
4 changes: 2 additions & 2 deletions BinaryEncoding.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ Yes:
* A `definitions` section contains (in this order):
- The generic section header
- A table (sorted by offset) containing, for each type which has opcodes:
+ A standardized string literal [type name](AstSemantics.md#local-and-memory-types).
+ A standardized string literal [type name](AstSemantics.md#expression-types).
The index of a type name in this table is referred to as a type ID
+ 64-bit offset of its opcode table within the section
- A sequence of opcode tables
Expand All @@ -94,7 +94,7 @@ Yes:
+ 64-bit offset within the section
- A sequence of functions
- A function contains:
+ A table containing, for each type ID that has [locals](AstSemantics.md#addressing-local-variables):
+ A table containing, for each type ID that has [locals](AstSemantics.md#local-variables):
* Type ID
* Count of locals
+ The serialized AST
Expand Down
4 changes: 2 additions & 2 deletions MVP.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ isomorphic to the [binary format](BinaryEncoding.md).
* JavaScript sees the exported memory as an `ArrayBuffer`.
* To keep an `ArrayBuffer`'s length immutable, resizing a module's memory
detaches any existent `ArrayBuffer`.
* See the [AST Semantics memory section](AstSemantics.md#accessing-linear-memory) for
more details.
* See the [AST Semantics linear memory section](AstSemantics.md#linear-memory)
for more details.

## Security

Expand Down