WebAssembly Medium · Lesson 1 · On the house

Loads, stores, offset and align

Memory immediates, sign-extending narrow loads, and what align really promises. Lesson 1 is free — on the house.

Lessons · WebAssembly Medium · Lesson 1 of 10 · On the house

Loads, stores, offset and align

Memory immediates, sign-extending narrow loads, and what align really promises.

Illustration for WebAssembly
Lesson 1 is on the house.

Every load and store takes an address (i32) from the stack plus two immediates: offset=N is added to the address, align=N is a hint in bytes. i32.load offset=8 reads 4 bytes at addr + 8.

Narrow loads widen into a full register: i32.load8_u zero-extends one byte, i32.load8_s sign-extends it, and i32.load16_s/_u do the same for two bytes. i64.load32_s turns a 32-bit field into an i64.

Narrow stores truncate: i32.store8 keeps only the low 8 bits, i32.store16 the low 16. Memory is always little-endian, so the low byte of an i32 lives at the lowest address.

align never changes results. A wrong hint is legal but can be slower; an alignment larger than the natural size (4 for i32.load) fails validation. Out-of-bounds addr + offset + size traps.

Struct fields map to offsets: with a base pointer on the stack, i32.load offset=0 is field A and i32.load offset=4 is field B. Compilers lean on offset immediates instead of emitting extra adds.

load8_s and offset

(module
  (memory 1)
  (func (export "demo") (result i32)
    i32.const 0
    i32.const 0xFF
    i32.store8
    i32.const 0
    i32.load8_s)
  (func (export "field_b") (param $base i32) (result i32)
    local.get $base
    i32.load offset=4 align=4))
Match this when you type.

Quiz

What does demo return after storing 0xFF as one byte and reading it with i32.load8_s?

Quiz

What does offset=8 on i32.load do?

Quiz

Which byte order does WebAssembly linear memory use?

Quiz

What happens if align is larger than the access's natural size?

Check

Match the still for: Loads, stores, offset and align.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.