Skip to content

perf(wasm): cache memory views, slot codec, and dense dispatch for mem_call - #16007

Open
Ryan-gsq wants to merge 2 commits into
PerryTS:mainfrom
Ryan-gsq:pr/wasm-memcall-fastpath
Open

Ryan-gsq wants to merge 2 commits into
PerryTS:mainfrom
Ryan-gsq:pr/wasm-memcall-fastpath

Conversation

@Ryan-gsq

@Ryan-gsq Ryan-gsq commented Dec 3, 2026 •

Copy link
Copy Markdown

Summary

Eliminates per-call TypedArray/BigInt/argument-array allocations and string-key object lookups on the mem_call and mem_call_i32 bridge hot path in wasm_runtime.js.

Motivation

Every mem_call previously constructed two fresh BigUint64Array views over wasmMemory.buffer, decoded and encoded slots through BigInt (__bitsToJsValue/__jsValueToBits), allocated a temporary args array, spread ...args, and performed repeated property lookups on __memDispatch / __perryUiDispatch by string name.

Changes

  • Cached linear-memory views (crates/perry-codegen-wasm/src/wasm_runtime.js):
    • Cache _memBuf, _memU32, _memF64, _memDV, and _memLen in __refreshMem(), automatically refreshing before reads and after calls if a callback triggered memory.grow (detaching or resizing wasmMemory.buffer), with bounds and 8-byte alignment validation.
  • BigInt-free 64-bit NaN-box slot codec (__readSlot / __writeSlot):
    • Read and write 64-bit NaN-boxed slots directly via two 32-bit words (_memU32) / _memF64 on little-endian hosts (with DataView fallback on big-endian hosts), canonicalizing all JS NaN values to (0x7FF80000, 0) to prevent NaN-tag spoofing.
  • Fixed-arity unrolling & dense post-_start() dispatch cache:
    • Mark mem_call and mem_call_i32 with __rawBigint = true and unroll arities 0..4 without intermediate args arrays.
    • Build dense integer-indexed dispatch tables (__memFnById / __i32FnById) via __buildMemDispatchCache() after _start() populates static strings, with transparent fallback for _start()-time calls, dynamic strings, __classDispatch, direct WebAssembly.instantiate, and Workers.
  • Tests (crates/perry-codegen-wasm/src/emit/mem_call_fastpath_tests.rs):
    • Add 7 tests covering arities 0..6, signed i32 truncation, exception handling, all NaN-box types + little/big-endian paths + NaN canonicalization, memory.grow view refresh during callbacks, bounds/alignment rejections, dense vs dynamic dispatch fallback, and __classDispatch.

Verification

  • cargo test -p perry-codegen-wasm: all 7 new mem_call_fastpath tests pass (365 passed on main base).
  • RUSTFLAGS="-D warnings" cargo check -p perry-codegen-wasm --all-targets: 0 errors.
  • rustfmt --edition 2021 --check: clean.

Summary by CodeRabbit

  • Performance

    • WebAssembly calls may run more efficiently, particularly when invoking functions with a small number of arguments.
  • Bug Fixes

    • Improved reliability for calls involving UI functions, memory growth, and callbacks.
    • Invalid call addresses and argument counts now produce consistent errors, while exception handling is preserved.

@coderabbitai

coderabbitai Bot commented Dec 3, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The WASM runtime now uses cached linear-memory views and slot encoding for mem_call and mem_call_i32. It adds static-ID dispatch caches, validates call inputs, refreshes views after memory changes, and includes tests for dispatch, encoding, memory growth, exceptions, and invalid inputs.

Changes: WASM mem_call fast path

Layer / File(s) Summary
Slot codec and memory views
crates/perry-codegen-wasm/src/wasm_runtime.js, crates/perry-codegen-wasm/src/emit/mem_call_fastpath_tests.rs
The runtime adds cached linear-memory views and slot encoding and decoding. Tests cover round trips across value types and endian settings.
Dispatch cache and boot lifecycle
crates/perry-codegen-wasm/src/wasm_runtime.js, crates/perry-codegen-wasm/src/emit/mem_call_fastpath_tests.rs
WASM boot resets dispatch-cache state and builds static dispatch tables after _start or main. Tests cover cached and dynamic resolution, direct startup, minified startup, and worker bootstrap.
Validated call bridges
crates/perry-codegen-wasm/src/wasm_runtime.js, crates/perry-codegen-wasm/src/emit/mem_call_fastpath_tests.rs, crates/perry-codegen-wasm/src/emit/tests_more.rs, changelog.d/16007-wasm-memcall-fastpath.md
mem_call and mem_call_i32 validate call inputs and use slot encoding to read arguments. They dispatch calls, preserve exception handling, and handle memory changes before result writeback. Tests cover arities, memory growth, exceptions, and invalid inputs. The changelog describes the update.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant Runtime as wasm_runtime.js
  participant Memory as linear memory
  participant Cache as dispatch cache
  participant Target as target function
  Runtime->>Memory: Read argument slots
  Runtime->>Cache: Resolve static function ID
  Cache-->>Runtime: Return cached function
  Runtime->>Target: Invoke with decoded arguments
  Target-->>Runtime: Return result
  Runtime->>Memory: Refresh views and write result
Loading

Possibly related issues

Possibly related PRs

  • PerryTS/perry#16002: This PR also changes NaN canonicalization in the WASM runtime encoders, which overlaps with the slot codec’s NaN handling.

Suggested reviewers: raliclo, thehypnoo

Merge Risk: Minimal · up to f27db

This change speeds up the WASM mem_call path with cached memory views and dispatch tables. Inspection found no current regression in call behavior, and the author reports tests passing. No merge-blocking risk was identified.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title is a single, specific sentence that names the main change: a performance change to the wasm mem_call path. It names the three parts of the change (cached memory views, slot codec, dense disp…
Description check Passed The description follows the repository template. It has a Summary, Motivation, Changes, and Verification, which maps to the template's Test plan. It omits the Related issue section, the Type of change…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title is a single, specific sentence that names the main change: a performance change to the wasm mem_call path. It names the three parts of the change (cached memory views, slot codec, dense dispatch), and the description and objectives describe the same work. The title follows the perf(wasm) convention. It does not describe a different change.

Full details: Description check

Explanation

The description follows the repository template. It has a Summary, Motivation, Changes, and Verification, which maps to the template's Test plan. It omits the Related issue section, the Type of change checkboxes, the Platforms checkboxes, and the Tested on line. The Test plan has no fenced command block for the lint gate, and the checklist items are not ticked. The author gave test results and a verification list, so the description is mostly complete.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 91e648b8-3510-4f94-94cb-39c35a775c04
Commits

Reviewing files that changed from the base of the PR and between 14d049c and f27dbd1.

Files selected for processing: 4

  • changelog.d/16007-wasm-memcall-fastpath.md
  • crates/perry-codegen-wasm/src/emit/mem_call_fastpath_tests.rs
  • crates/perry-codegen-wasm/src/emit/tests_more.rs
  • crates/perry-codegen-wasm/src/wasm_runtime.js

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.

@github-actions github-actions Bot added area:compiler parser, HIR, transform, codegen, wpfacts platform:wasm Specific to wasm type:perf Runtime, compile-time, build-size, or memory performance labels Dec 3, 2026
@Ryan-gsq

Ryan-gsq commented Dec 3, 2026

Copy link
Copy Markdown
Author

Note on the overlap with #16002: this PR canonicalizes numeric NaNs in the fast-path linear-memory slot writer (__writeSlot), while #16002 covers the host-value and worker encoders used outside that path (fromJsValue, __jsValueToBits, and WORKER_BOOTSTRAP). Both paths are complementary, emit the same canonical quiet NaN bits (0x7FF8_0000_0000_0000), and merge cleanly in wasm_runtime.js.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:compiler parser, HIR, transform, codegen, wpfacts platform:wasm Specific to wasm type:perf Runtime, compile-time, build-size, or memory performance

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant