Skip to content

[JSC] Bytecode cache: linear-time encoding, deterministic output - #433

Open
dylan-conway wants to merge 2 commits into
mainfrom
claude/bytecode-cache-encoder-perf
Open

dylan-conway wants to merge 2 commits into
mainfrom
claude/bytecode-cache-encoder-perf

Conversation

@dylan-conway

@dylan-conway dylan-conway commented Aug 14, 2026 •

Copy link
Copy Markdown
Member

Two commits, both in JSC's bytecode cache (CachedTypes.cpp and what feeds it). Best reviewed separately.

1. Encoder: grow pages geometrically so encoding is not quadratic in cache size

bun build --bytecode spent almost all of its time in the bytecode-cache Encoder, growing quadratically with bundle size.

Encoder allocates its output in Pages and Encoder::offsetOf() maps a pointer into one of those pages back to an offset in the final buffer by walking m_pages. offsetOf() runs for every CachedPtr / VariableLengthObject encoded — millions of times for a large program. Pages were pageSize() (4 KB Linux / 16 KB macOS) unless a single allocation was larger, so a cache of a few hundred MB was tens of thousands of pages, and since the walk started at the first page while the address being looked up is nearly always in the last one, each lookup was O(pages) and encoding was O(pointers × pages). Upstream only drives this encoder from the jsc shell's disk cache on individual files, so it never mattered there.

  • Size each new page to at least the total encoded so far (still rounded to pageSize(), still ≥ the requested allocation), so the number of pages is logarithmic in the cache size instead of linear.
  • Walk pages from the most recently allocated one in offsetOf(), which is where a depth-first encoder's addresses almost always are. Each Page records its base offset instead of Encoder keeping a running m_baseOffset for the current page only.

Output bytes are unchanged by this commit: release()/releaseMapped() still copy exactly page.size() bytes per page and offsetOf() returns the same values. The extra capacity in the last page is never touched.

macOS arm64 release, bun build --target=bun --format=cjs --minify --bytecode:

input before after .jsc size
synthetic 3 MB / 15.6k functions 0.59 s 0.19 s 44.7 MB (identical)
synthetic 6 MB / 31k functions 1.95 s 0.38 s 88.8 MB (identical)
synthetic 12 MB / 61k functions 7.27 s 0.75 s 176 MB (identical)
synthetic 24 MB / 122k functions 26.97 s 1.56 s 353 MB (identical)
[email protected] + [email protected], 7.5 MB 978 ms 457 ms (410 ms after commit 2) 51.1 MB (identical)

(Without --bytecode the 24 MB case is 0.09 s and ts+prettier is 95 ms.) On Linux x64 "before" is ~4× worse because pages are 4 KB. Measured separately: geometric growth alone gives the same times; the reverse walk alone is ~17× faster than before at 24 MB but still slightly superlinear (a large CachedArray whose elements each encode a subtree looks its early page up once per element). Peak footprint for the 24 MB case: 2857 MB → 2923 MB.

2. Make the bytecode cache deterministic for a given source

Serializing the same program twice produced different bytes every time (none of it changes behaviour after decoding, but bun build --bytecode output was unreproducible). Six independent causes — details in the commit message:

  1. Encoder padding — alignment gaps and struct padding/bit-field slack were never written; Page::malloc()/alignEnd() now zero what they hand out.
  2. String switch jump tables — m_offsetTable is a RobinHood table seeded with its own address, so serialization order followed ASLR; now written in m_indexInTable order.
  3. CompactTDZEnvironment — names are kept sorted by pointer; now serialized ordered by contents (decode re-sorts by pointer as before).
  4. HandlerInfoBase::typeBits : 2 left 30 indeterminate bits in every serialized UnlinkedHandlerInfo; now a whole word.
  5. SourceProviderCache not transparent (and cleared on every full GC, so which variant a function got depended on GC timing): the uncached path took an expression-bodied arrow function's endColumn from the token after the body while the cache path uses the body's last token (uncached now matches); and NoEvalCacheFeature was lost for tagged templates inside skipped functions (now recorded in SourceProviderCacheItem::containsTaggedTemplate and replayed).
  6. GC timing still chose between equivalent-but-different parser states (e.g. closed-variable propagation order). recursivelyGenerateUnlinkedCodeBlock() now holds the provider's SourceProviderCache for its duration and VM::clearSourceProviderCaches() only drops caches nothing else references; idle caches are freed on full GC exactly as before. Side effect: nested reparses always hit, ~10% faster on ts+prettier.

Testing

  • bun build --bytecode on typescript+prettier, three+lodash+zod+react-dom+@babel/standalone, and synthetic bundles, minified and not, repeated runs including JSC_collectContinuously=1 and gcMaxHeapSize=1MB: all byte-identical (before: every run differed, e.g. 356k differing bytes in a 44 MB cache). New bun test (bundler_bun.test.ts "bytecode output is deterministic") fails 8/8 on current bun, passes 12/12 with this.
  • Bun test/bundler/bundler_compile.test.ts -t bytecode (27 tests), test/js/node/vm/vm.test.ts, test/regression/issue/26298.test.ts pass; built outputs run with [Disk Cache] Cache hit.
  • jsc shell disk cache (JSC_diskCachePath, then JSC_forceDiskCache=1 which asserts a hit) over ~100 JSTests/stress files (1-in-97 sample plus arrow/tagged-template/try-catch/switch-string tests) and a 3.8 MB / 20k-function script (46 MB cache via releaseMapped() + function updates); that cache file is also identical with and without collectContinuously.

… not quadratic in cache size

Encoder allocates its output in Pages and Encoder::offsetOf() maps a pointer
into one of those pages back to an offset in the final buffer by walking
m_pages. offsetOf() runs for every CachedPtr / VariableLengthObject that is
encoded, i.e. millions of times for a large program. Pages were pageSize()
(4 KB on Linux, 16 KB on macOS) unless a single allocation was larger, so a
cache of a few hundred MB was tens of thousands of pages, and since the walk
started at the first page while the address being looked up is nearly always
in the last one, every lookup was O(pages): encoding was O(pointers x pages),
quadratic in the size of the program. Upstream only drives this encoder from
the jsc shell's disk cache on individual files; Bun's `bun build --bytecode`
runs it over whole application bundles, where serialization took ~95% of the
build and doubling the input roughly quadrupled the time (a 24 MB bundle ->
353 MB cache took 27 s, of which <1 s is parsing and bytecode generation).

Size each new page to at least the total encoded so far (still rounded to
pageSize() and still at least the requested allocation), so the page count is
logarithmic in the cache size instead of linear, and walk the pages from the
most recently allocated one, which is where a depth-first encoder's addresses
almost always are. Each Page now records its base offset instead of Encoder
keeping a running m_baseOffset for the current page only.

The bytes produced are unchanged: release()/releaseMapped() still copy exactly
page.size() bytes per page, and offsetOf() returns the same values. The extra
capacity in the last page is never touched. With this, the 24 MB bundle above
encodes in 1.6 s and time is linear in input size (3/6/12/24 MB: 0.19/0.38/
0.75/1.56 s, previously 0.59/1.95/7.27/26.97 s); typescript+prettier
(7.5 MB -> 51 MB cache) goes from 978 ms to 457 ms. Geometric growth alone
accounts for essentially all of it; the reverse walk just makes the common
lookup hit on the first iteration.
@coderabbitai

coderabbitai Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 842ca16c-7a8c-4b15-a201-86d8ca35100c

📥 Commits

Reviewing files that changed from the base of the PR and between e2f13c6 and bc6e107.

📒 Files selected for processing (6)
  • Source/JavaScriptCore/bytecode/HandlerInfo.h
  • Source/JavaScriptCore/parser/Parser.cpp
  • Source/JavaScriptCore/parser/SourceProviderCacheItem.h
  • Source/JavaScriptCore/runtime/CachedTypes.cpp
  • Source/JavaScriptCore/runtime/CodeCache.cpp
  • Source/JavaScriptCore/runtime/VM.cpp

Walkthrough

JavaScriptCore updates cache serialization, parser metadata, and source-provider cache lifetime. Serialized fields are initialized, encoded data uses stable ordering, tagged-template state is preserved across parsing and cache loading, and active caches remain retained during recursive code generation.

Changes

JavaScriptCore cache consistency

Layer / File(s) Summary
Cache metadata and serialized representation
Source/JavaScriptCore/bytecode/HandlerInfo.h, Source/JavaScriptCore/parser/SourceProviderCacheItem.h
HandlerInfoBase::typeBits is now a full initialized uint32_t. Source-provider cache items now store containsTaggedTemplate.
Deterministic cache encoding
Source/JavaScriptCore/runtime/CachedTypes.cpp
Encoding now uses per-page offsets, zero-initialized storage, stable string jump-table ordering, and normalized compact TDZ environment names.
Tagged-template parser state
Source/JavaScriptCore/parser/Parser.cpp
Function parsing isolates and restores tagged-template state, restores it from cached functions, and records it in new cache entries. Arrow expression bodies use the last parsed token for endColumn.
Source-provider cache lifetime
Source/JavaScriptCore/runtime/CodeCache.cpp, Source/JavaScriptCore/runtime/VM.cpp
Recursive code generation retains the source-provider cache. Cache clearing removes only entries without external references.

Suggested reviewers: constellation, geoffreygaren

🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed and on-topic, but it omits the required Bugzilla link, review line, and changed-file/function list from the repository template. Add the Bugzilla bug URL, the “Reviewed by” line, and a template-style explanation with changed paths and relevant functions.
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly summarizes the two main changes: linear-time bytecode-cache encoding and deterministic output.

Comment @coderabbitai help to get the list of available commands.

@claude claude Bot left a comment

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 reviewed this PR and didn't find any bugs. Because it changes the allocation strategy inside JSC's bytecode-cache encoder (a critical path for bun build --bytecode) and trades some peak memory for the O(pages) → O(log) fix, a human look would still be worthwhile.

Checked that each Page's stored baseOffset equals the old running m_baseOffset (set after alignEnd() on the prior page), so offsetOf(), malloc(), release(), and releaseMapped() return the same values as before.
Checked that release()/releaseMapped() still copy only page.size() bytes per page, so the unused tail of the geometrically-grown last page never reaches the output — consistent with the byte-identical .jsc files reported.
Checked that m_currentPage is re-taken from &m_pages.last() immediately after every append, so the reverse walk and the read-before-append in allocateNewPage() don't touch a stale pointer.

Extended reasoning...

Overview

The PR changes ~30 lines inside Encoder in Source/JavaScriptCore/runtime/CachedTypes.cpp. It replaces the encoder-level m_baseOffset with a per-Page m_baseOffset, walks m_pages in reverse in offsetOf(), and sizes each new page to at least the total bytes encoded so far (still pageSize()-aligned and still ≥ the requested allocation). malloc(), release(), and releaseMapped() are updated to read the base offset from the current page instead of the removed member.

I traced the invariant: previously m_baseOffset was updated to += m_currentPage->size() after alignEnd() when allocating a new page. Now baseOffset = m_currentPage->baseOffset() + m_currentPage->size() is computed at the same point and stored in the new page — inductively identical. offsetOf() used to sum page.size() while walking forward; now it reads the stored baseOffset() while walking backward, which is the same sum since prior pages' size() is frozen after alignEnd(). The total-size computation in release()/releaseMapped() is the same expression as before, just sourced from the page. page.span() is still first(size()), so only the used portion is copied and the RELEASE_ASSERT(bufferSpan.empty()) still holds.

Security risks

None identified. This is the write side of the bytecode cache — it serializes trusted in-memory JSC structures at build time and does not parse untrusted input. The change does not touch the Decoder, bounds checks, or any auth/crypto/permissions path. The reverse loop uses unsigned i = m_pages.size(); i--; which is safe for an empty vector, though m_pages is never empty after the constructor's allocateNewPage().

Level of scrutiny

Moderate-to-high. CachedTypes.cpp is core JSC runtime and directly backs bun build --bytecode; a wrong offset here would corrupt every cached bytecode blob. The change is small and self-contained, and the author reports byte-identical outputs across several inputs plus passing bytecode tests, but a JSC-familiar human should sign off on the memory tradeoff: the last page can now be up to the size of everything before it (author reports 2857 MB → 2923 MB peak on the 24 MB / 353 MB-cache case, so the practical delta is small, but it is a behaviour change worth a maintainer's ack).

Other factors

No prior human or bot reviews with substantive content (CodeRabbit was rate-limited). No outstanding comments to address. The PR description is thorough with before/after benchmarks, separate measurements of each half of the change, and testing on both the Bun bytecode path and the upstream jsc shell disk-cache path (releaseMapped()). Given it's a JSC-runtime allocation-strategy change rather than a mechanical fix, I'm deferring rather than approving.

@github-actions

github-actions Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

Preview Builds

Commit Release Date
bc6e107a autobuild-preview-pr-433-bc6e107a 2026-08-14 10:09:23 UTC
4e33c298 autobuild-preview-pr-433-4e33c298 2026-08-14 09:35:04 UTC

Serializing the same program twice (e.g. `bun build --bytecode` run twice on
the same bundle, or the jsc shell's disk cache) produced different bytes each
time. None of the differences changed behaviour after decoding, but they make
the output unreproducible. There were six independent causes:

1. Encoder never wrote the alignment gaps between allocations, and the cached
   objects placement-new'd into its pages are default-initialized structs
   with padding and bit-fields, so heap garbage ended up in the file.
   Page::malloc()/alignEnd() now zero what they hand out.

2. UnlinkedStringJumpTable::m_offsetTable is a RobinHoodHashTable, whose hash
   is seeded with the table's address, so its iteration order - and the order
   CachedHashMap serialized it in - varied with ASLR. CachedStringJumpTable
   now writes the entries in m_indexInTable order (and the otherwise unused
   CachedMemoryCompactLookupOnlyRobinHoodHashMap alias is gone).

3. CompactTDZEnvironment keeps its names sorted by pointer (or in a hash set);
   CachedCompactTDZEnvironment now serializes them ordered by contents.
   decode() already re-sorts by pointer.

4. HandlerInfoBase::typeBits was a 2-bit bit-field in its own word, leaving 30
   indeterminate bits in every UnlinkedHandlerInfo, which is serialized
   as-is. It is a whole uint32_t now.

5. The parser's SourceProviderCache is supposed to be transparent, but two
   things it reconstructs for a skipped function differed from a real parse,
   and VM::clearSourceProviderCaches() runs on every full collection, so
   which variant a function got depended on GC timing:
   - For an arrow function with an expression body, parseFunctionBody() took
     endColumn from the token *after* the body (which is not part of the
     function and may be on another line), while the cache path uses the
     body's last token, as both do for the '}' of a block body. The uncached
     path now uses the last token too.
   - m_seenTaggedTemplateInNonReparsingFunctionMode (-> NoEvalCacheFeature on
     the enclosing code block) was never set for tagged templates inside a
     skipped function. The flag is now tracked per function, stored in
     SourceProviderCacheItem::containsTaggedTemplate and replayed on a hit.

6. Even with those fixed, a cache hit legitimately produces different (but
   equivalent) parser state than a full parse - e.g. the order closed-over
   variables are propagated to the parent scope - so output still depended
   on whether a collection had emptied the cache between two reparses.
   recursivelyGenerateUnlinkedCodeBlock(), which reparses every function in
   the program back to back precisely to build a cache, now holds a Ref to
   the provider's SourceProviderCache for its duration, and
   VM::clearSourceProviderCaches() only drops caches nothing else references
   (an idle cache is still freed on full GC exactly as before). As a side
   effect the nested reparses always hit, which makes typescript+prettier
   `bun build --bytecode` another ~10% faster.

Verified with `bun build --bytecode` on typescript+prettier, three+lodash+zod+
react-dom+@babel/standalone and synthetic bundles, minified and not, across
repeated runs including JSC_collectContinuously=1 and a 1 MB gcMaxHeapSize:
all byte-identical (previously every run differed). jsc shell disk cache for a
20k-function script is likewise identical with and without
collectContinuously. JSTests/stress sample plus arrow/tagged-template/
try-catch/switch-string tests pass normally and under JSC_forceDiskCache.
@dylan-conway dylan-conway changed the title [JSC] Bytecode cache Encoder: grow pages geometrically so encoding is not quadratic in cache size [JSC] Bytecode cache: linear-time encoding, deterministic output Aug 14, 2026

@claude claude Bot left a comment

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 reviewed this PR and didn't find any bugs. Because it touches the parser (arrow-function endColumn, per-function tagged-template tracking) and GC-time cache lifetime alongside the encoder changes, a human look would still be worthwhile.

What was reviewed:

  • Encoder page growth / reverse walk: release()/releaseMapped() still copy page.size() per page and baseOffset bookkeeping matches the old running m_baseOffset.
  • CachedStringJumpTable: confirmed m_indexInTable is a dense 0..N-1 assigned only on new entries, so the vector indexing is in bounds.
  • m_seenTaggedTemplateInNonReparsingFunctionMode save/restore via std::exchange + makeScopeExit — cache-hit and uncached paths both leave the enclosing flag OR'd correctly.
  • clearSourceProviderCaches() hasOneRef() guard vs. the new Ref in recursivelyGenerateUnlinkedCodeBlock — idle caches still drop on full GC.
Extended reasoning...

Overview

Two commits across six files. Commit 1 reworks the bytecode-cache Encoder in CachedTypes.cpp to grow pages geometrically and store a per-page baseOffset, walking m_pages backwards in offsetOf(). Commit 2 makes the serialized bytes deterministic: zeroing padding in Page::malloc/alignEnd, serializing UnlinkedStringJumpTable in m_indexInTable order, sorting CompactTDZEnvironment names by content, widening HandlerInfoBase::typeBits to a full word, fixing two SourceProviderCache transparency issues in Parser.cpp (arrow-expression endColumn, tagged-template propagation via a new containsTaggedTemplate field on SourceProviderCacheItem), and pinning the SourceProviderCache for the duration of recursivelyGenerateUnlinkedCodeBlock while making VM::clearSourceProviderCaches() skip caches with an outstanding ref.

Security risks

None apparent. The zeroing of encoder padding is a mild hardening (previously heap garbage was written into on-disk cache files). No new external input parsing, no auth/permissions surfaces. entries[entry.value.m_indexInTable] was checked against BytecodeGenerator::endSwitch, which assigns size() - 1 only on new entries, so the index is always in [0, m_offsetTable.size()).

Level of scrutiny

High. The encoder half is largely mechanical and output-byte-preserving, but the determinism half changes parser semantics that feed CodeFeatures (NoEvalCacheFeature) and the recorded endColumn for expression-bodied arrows, and it alters what happens to sourceProviderCacheMap during a full GC. These are subtle, cross-cutting invariants in core JSC — exactly the kind of change a JSC-familiar reviewer should sign off on rather than an automated approval.

Other factors

The PR description documents extensive testing (bun bytecode tests, jsc shell disk cache with forceDiskCache assertions, collectContinuously/gcMaxHeapSize stress). The two commits are already on main per the recent-commits log, so this PR appears to be the review vehicle for already-landed work. No prior human review comments to address; CodeRabbit was rate-limited and did not review.

dylan-conway added a commit that referenced this pull request Aug 24, 2026
…SourceProviderCache transparent to what gets encoded

Records: everything enters the Encoder through malloc<T> / mallocArray<T> /
mallocCopy<T>, which static_assert isPortableRecord<T>() -- fixed-width
scalars, no padding, no bit-field slack (has_unique_object_representations) --
so every byte in the payload is a named, initialized field and a record's
layout follows from its declaration alone. The records that had holes get
fields reordered/widened or explicit zeroed m_padding; VariableEnvironmentEntry,
PrivateNameEntry and SymbolTableEntry go through Cached* records.

Parser (from #433, plus one more case): whether a nested function's body was
skipped through the SourceProviderCache changed what the parser recorded for it
and for what follows it, and a full collection part-way through generation
could drop that cache, so the payload depended on GC timing:
- an expression-bodied arrow function's end line/column came from the token
  after the body when parsed but from the body's last token when skipped;
  both now use the last token;
- NoEvalCacheFeature for a tagged template inside a skipped body was lost;
  the cache item records and replays it;
- after skipping a body whose last token spans lines (a template literal) the
  lexer resumed on the line that token started on, so every later function's
  line numbers were short by the lines it spanned (visible in stack traces,
  not only in the cache); the cache item records where the token ended;
- recursivelyGenerateUnlinkedCodeBlock() and the builtin-executable path hold
  the provider's cache for their duration, and VM::clearSourceProviderCaches()
  keeps caches that are in use.

The stress test also runs under --collectContinuously=1 and
--useSourceProviderCache=0.
dylan-conway added a commit that referenced this pull request Aug 27, 2026
…rce ⇒ same bytes everywhere) (#505)

* [JSC] Make the bytecode cache format independent of the encoding platform

The cache is decoded by Bun executables cross-compiled for a different OS/CPU
than the one that produced it, but two things in it depended on the encoder's
C++ ABI:

- CachedMetadataTable serialized the finalized metadata offset table, whose
  entries are byte offsets computed from sizeof(Op::Metadata). Those sizes
  differ between ABIs (everything embedding CallLinkInfo is 16 bytes larger
  under MSVC), so a table encoded on Linux/macOS and linked on Windows had
  LLInt indexing past each entry. Serialize per-opcode entry counts instead
  and lay the table out again on decode via the normal finalize() path.
- CachedStringSourceProvider's Bun-only m_sourceLength sat in the base
  class's tail padding under Itanium but not under MSVC. It didn't validate
  anything SourceCodeKey doesn't already (the key compares the source hash),
  so drop it and hand back the provider being decoded against.

Also make the encoder's output a pure function of its input so it can be
compared across platforms: fixed allocation alignment and page size instead
of alignof(max_align_t)/pageSize(), zeroed pages so struct padding is not
heap garbage, string switch tables encoded in index order rather than
StringImpl-pointer hash order, and UnlinkedHandlerInfo encoded field-wise
rather than copied with 30 bits of bit-field slack.

The two allocation entry points now static_assert what the compiler can
check about a type's portability (alignment, no destructor/array cookie,
and for verbatim-copied types: no padding or bit-field slack, no
long/wchar_t/long double).

* [JSC] CachedTypes: don't reject int64_t on LP64 where it is spelled long

The verbatim-copy check rejected `long` by name to catch the LP64/LLP64
size difference, but int64_t (EncodedJSValue) is `long` under glibc. Only
reject `long` where it is the 32-bit outlier.

* [JSC] Bytecode cache: a format the decoding platform's ABI cannot disagree with

Bun embeds this cache in executables it cross-compiles, so the bytes are decoded
by a build whose OS, CPU and C++ ABI differ from the encoder's. Two things in
the format depended on the encoder:

- The metadata table was stored as offsets (lately as offset deltas), which are
  sums of this build's sizeof(Op::Metadata); anything embedding CallLinkInfo is
  16 bytes larger under MSVC, so a table written on Linux/macOS and linked on
  Windows had LLInt index past every entry. The cache now stores per-opcode
  entry counts and UnlinkedMetadataTable::layOut() -- the one function that
  turns counts into offsets, shared with finalize() -- runs on the decoding
  side (at link() for a persistent payload, as before).

- Records are placed in the payload as C++ objects, so any byte the ABI is free
  to place (tail padding Itanium reuses and MSVC does not, bit-field units MSVC
  restarts on a type change, holes after a bool/uint8_t/uint16_t member) can
  land differently. Every type now enters the Encoder through malloc<T> /
  mallocArray<T> / mallocCopy<T>, which static_assert isPortableRecord<T>():
  trivially destructible, alignment <= 8, no long/wchar_t/pointers, and
  has_unique_object_representations -- i.e. no padding and no bit-field slack,
  so the layout is fully determined by the declared field sizes. The dozen
  records that had holes get their fields reordered/widened or an explicit
  zeroed m_padding; UnlinkedHandlerInfo, VariableEnvironmentEntry,
  PrivateNameEntry and SymbolTableEntry are encoded through Cached* records
  instead of copied; CachedStringSourceProvider's Bun-only m_sourceLength is
  gone (SourceCodeKey already compares hash and length).

And the output is made a pure function of the source so that platforms can be
compared byte for byte: allocation alignment and encoder page size are
constants instead of max_align_t/pageSize(), and hash maps/sets and TDZ
environments are written in key order instead of table order (which follows
SymbolImpl's per-process hash counter, or a robin-hood table's own address).

* UnlinkedMetadataTable::layOut: Layout::end includes the 32-bit table displacement, as the table's last entry does

totalSize() of a table backed by persistent entry counts used it as-is and
under-allocated the linked buffer by s_offset32TableSize for functions large
enough to need 32-bit offsets (ASAN: heap-buffer-overflow writing
OpPutToScope::Metadata in CodeBlock::finishCreation).

* CachedStringSourceProvider: keep comparing the source length before standing in the runtime provider

Now a plain uint32_t after a base without tail padding, so both ABIs place it
at the same offset (the reason the earlier revision dropped it).

* jsc shell: bytecodeCacheFor(source, kind); stress test that two encodings of one source are identical

* layOut(): 64-bit running offset with a bound, so entry counts out of a payload cannot wrap it; EncodingOrder: order equal-content keys by symbol kind

* BytecodeGenerator: allocate an instruction's value profile indices in operand order, not argument-evaluation order

op_iterator_open, op_iterator_next, op_async_iterator_open and op_instanceof
took their two or three value-profile indices as nextValueProfileIndex()
calls in one emit() argument list, so which operand got which index was up
to the compiler's argument evaluation order: left-to-right under clang for
SysV targets, right-to-left under the MSVC ABI. The bytecode was equivalent
either way, but not byte-identical across platforms, which the bytecode
cache now promises.

* Bytecode cache: make the payload a function of the source alone

Two encodings of the same source could differ:

- hash maps/sets and TDZ environments were written in table order, which for
  SymbolImpl keys follows a per-process hash counter and for robin-hood tables
  (string switch jump tables) the table's own address; they are now written in
  key order (EncodingOrder);
- UnlinkedHandlerInfo was copied with the 30 unspecified bits next to its
  2-bit HandlerType; it is encoded field by field (CachedHandlerInfo);
- allocation alignment was alignof(std::max_align_t) and encoder pages were
  pageSize(), both of which vary by platform and show up as padding; they are
  constants;
- op_iterator_open/op_iterator_next/op_async_iterator_open/op_instanceof took
  their value-profile indices as several nextValueProfileIndex() calls in one
  argument list, so which operand got which index followed the compiler's
  argument evaluation order (reversed under the MSVC ABI); they are sequenced.

jsc shell: bytecodeCacheFor(source, kind) returns the payload as a Uint8Array;
JSTests/stress/bytecode-cache-deterministic.js encodes a corpus twice and
compares.

* Bytecode cache: no ABI-placed or unwritten bytes in records; parser: SourceProviderCache transparent to what gets encoded

Records: everything enters the Encoder through malloc<T> / mallocArray<T> /
mallocCopy<T>, which static_assert isPortableRecord<T>() -- fixed-width
scalars, no padding, no bit-field slack (has_unique_object_representations) --
so every byte in the payload is a named, initialized field and a record's
layout follows from its declaration alone. The records that had holes get
fields reordered/widened or explicit zeroed m_padding; VariableEnvironmentEntry,
PrivateNameEntry and SymbolTableEntry go through Cached* records.

Parser (from #433, plus one more case): whether a nested function's body was
skipped through the SourceProviderCache changed what the parser recorded for it
and for what follows it, and a full collection part-way through generation
could drop that cache, so the payload depended on GC timing:
- an expression-bodied arrow function's end line/column came from the token
  after the body when parsed but from the body's last token when skipped;
  both now use the last token;
- NoEvalCacheFeature for a tagged template inside a skipped body was lost;
  the cache item records and replays it;
- after skipping a body whose last token spans lines (a template literal) the
  lexer resumed on the line that token started on, so every later function's
  line numbers were short by the lines it spanned (visible in stack traces,
  not only in the cache); the cache item records where the token ended;
- recursivelyGenerateUnlinkedCodeBlock() and the builtin-executable path hold
  the provider's cache for their duration, and VM::clearSourceProviderCaches()
  keeps caches that are in use.

The stress test also runs under --collectContinuously=1 and
--useSourceProviderCache=0.

* Parser: keep m_lastTokenEndPosition out of the hot-field cache lines (verifyLayout() on ARM64 release)

* Process state that reached generated bytecode: Annex B hoisting order, registry-symbol hashes, atom width; and ** folding through libm

- Parser: sloppy-mode block function hoisting candidates were a HashMap keyed
  by FunctionMetadataNode* and iterated to declare the hoisted vars, so their
  registers / scope offsets followed arena addresses (ASLR): two runs of
  '{ function a(){} function b(){} }' inside any sloppy function encoded
  differently. Kept in declaration order now.
- SymbolImpl: registered and private symbols hashed by a process-global
  counter, so a VariableEnvironment holding computed-class-field keys (or
  builtin @NAMEs) past its inline capacity iterated -- and the generator
  assigned scope offsets -- in an order set by how many symbols the process had
  made. They hash by contents (as StaticSymbolImpl already does); plain
  Symbol() keeps the counter.
- Encoder: a Latin-1 string is written 8-bit even when this thread's atom for
  it is 16-bit because an equal 16-bit string was atomized first; and
  CachedImmutableButterfly stores indexingMode(), not the cell-lock bits that
  share its byte.
- ASTBuilder folds 'a ** b' only on operationMathPow's exact integer-exponent
  path; the other cases call the C library's pow(), which rounds differently
  across platforms, and left unfolded they get the pow() of where the code runs.
- Parser::restoreLexerState restores the last token's end line too.

Stress-test corpus gains block functions, >9 computed class fields and pow
folds; on main it encodes differently on every run.

* Scope: keep the hoisting-candidate vector out of the hot cache line (verifyLayout() on ARM64 release)

* SourceProviderCacheItem: pair the new end-position fields flag:1/value:31 like the rest of the struct

* Cache entry records the encoder's reserved callee-save locals; a decoder whose CPU reserves a different number treats the payload as foreign

BytecodeGenerator numbers a code block's locals after the LLInt/baseline
callee-save area, whose size comes from the encoding CPU's register set. It is
4 registers on x86-64 and arm64 alike, which is what makes payloads
interchangeable between them; this makes that dependency explicit instead of
coincidental.

* Reduce this branch to the portability change alone

Cross-decoding needs exactly two things, and this branch is now only those:

- records placed in the payload have one layout under every ABI: everything
  enters the Encoder through malloc<T>/mallocArray<T>/mallocCopy<T>, which
  static_assert isPortableRecord<T>() (fixed-width scalars, no padding, no
  bit-field slack), and the records that had holes are corrected;
- the metadata table is stored as per-opcode entry counts, and
  UnlinkedMetadataTable::layOut() computes offsets on the decoding side,
  because sizeof(Op::Metadata) belongs to the decoder.

Plus the cache entry recording the encoder's reserved callee-save locals.

The determinism work (hash-table order, encoder constants, parser /
SourceProviderCache, symbol hashing, Annex B order, ** folding, the jsc test)
moves out to #505; none of it is required for a payload to decode correctly on
another platform.

* Metadata portability as the smallest change to main's steps: a step carries an entry count

Keep UnlinkedMetadataTable and CachedMetadataSteps exactly as on main except:
- a step is (opcode << 24 | entry count) instead of (index << 24 | offset delta);
- expandSteps() lays counts out with this build's metadataSize()/metadataAlignment(),
  the same loop finalize() runs, and returns the end offset (so totalSize() and
  the 16/32-bit decision come from it instead of from the encoder);
- CachedMetadataSteps::compute() is finalize()'s inverse, checked against the
  original table in debug builds.
finalize() itself is untouched.

* Rework on top of the WebKit upgrade as the additive form

CachedTypes.cpp starts again from main and only adds: isPortableRecord<T>() and a
static_assert of it in each of main's existing typed entry points into the
payload (Encoder::malloc<T>/mallocFor<T>, VariableLengthObject::allocate<T>/
allocateFor<T>, the trivially-copyable CachedArray/CachedVector paths,
encodeArrayForTail<T>); the padding/widening those asserts demand in the
records that fail them; CachedMetadataSteps as (opcode, count); the callee-save
check in GenericCacheEntry. Encoder's allocation API is main's, unchanged.

* CachedHashMap::encode: sort entries by reference now that values may be move-only (merge with main's encodeRange)

* CachedPair spells out its own padding, so the entry wrapper records (and the VariableEnvironment.h friend) go away

CachedPair<First, Second> gets explicit, zero-cost-when-empty padding members
sized from First/Second, which makes every pair padding-free regardless of the
value type; VariableEnvironmentEntry, PrivateNameEntry and SymbolTableEntry are
stored as on main again.

* Encoder: the untyped allocation is private; records reach a page only through the checked malloc<T>/mallocFor<T>/mallocArray<T>

That check then covers the program/module code block records (allocated raw
before), whose CachedVariableEnvironment had two padding bytes after its bools.

* Route #515's two new allocations through the checked path: mallocArray<CachedJSValue> for the constant pool (kind bytes as head), mallocCopy for the packed ExpressionInfo bytes

* Restore this branch's parser/generator/SymbolImpl/test changes after merging the portability branch (whose reduction commit had reverted them here)

* Fold non-integer ** only when not generating for a bytecode cache

CodeGenerationMode::BytecodeCache is set by recursivelyGenerateUnlinkedCodeBlockFor*
(what every cache producer goes through) and now reaches the Parser/ASTBuilder
alongside the other code-generation modes; makePowNode consults it. Ordinary
parsing folds exactly as before. SourceCodeKey ignores the bit, so a block
generated for a cache serves any request for that source.

* isPortableRecord: also reject polymorphic types (a vptr is a pointer into this process)

* Review: keep CodeGenerationMode::BytecodeCache out of UnlinkedCodeBlock (Bun compares a precompiled block's mode with the global's); content-hash registered symbols only

* mallocPlaced: predict a fresh page's base with encoderMaxAlignment, which is what alignEnd() rounds to

* Reduce to the metadata table fix

Drop the layout rule (isPortableRecord, the typed allocators, the struct
padding changes): the records lay out the same on every 64-bit target we
build for today, and Bun's cross-platform golden-hash test is what catches a
future divergence. What remains is the one thing that is actually different
across ABIs -- the metadata table's offsets, computed from the encoder's
sizeof(Op::Metadata) -- now stored as per-opcode entry counts and laid out
by the decoder, plus the callee-save-locals check in the entry.

* Private-name environment sharing: hash the entries' values, not their bytes (the pairs have padding), so equal environments are always shared

* CachedMetadataSteps: refuse an entry count that does not fit the step word in release builds too

* Shape: only re-create a 16-bit string as 8-bit when it actually is all Latin-1 (no copy of genuine 16-bit strings)

* Private-name environment sharing: compare the (name, bits) pairs, not their bytes

Vector<std::pair<const UniquedStringImpl*, uint16_t>>::operator== compares
with memcmp (both halves are 'simple' types), and each pair carries six
bytes of padding whose contents depend on the allocator and on how the
compiler stores the pair. Two identical environments then compared unequal
on some machines and equal on others, so whether a nested function's
parent private-name environment was shared with the previous identical one
-- and with it the payload's size -- varied from machine to machine for
the same source. Compare with std::ranges::equal (pair::operator==).

* Build: check that the bytecode cache's records are laid out identically on every platform

A payload encoded on one platform is decoded in place on another (bun build
--compile cross-compiles), so every record CachedTypes.cpp writes must have
the same size, alignment and member offsets under the Itanium and Microsoft
C++ ABIs and on every architecture. Nothing enforced that; it happens to hold.

Tools/Scripts/dump-bytecode-cache-layout.py recompiles the translation unit
containing runtime/CachedTypes.cpp with -fdump-record-layouts and prints, in
a target-independent spelling, the layout of every record that ends up in a
payload: everything deriving from CachedObject<> / VariableLengthObjectBase,
the cache entry headers, and the value types those hold or store in their
tails (following members, bases and Cached containers' element types, but
not CachedObject<T>'s T, the in-memory source type). The linux, musl, macos
and windows images write it next to the libraries as bytecode-cache-layout.txt
(~3 s), and the release job diffs every platform's copy against linux-amd64
before publishing.

* dump-bytecode-cache-layout: TypeScript (bun where the image has it, node --experimental-strip-types elsewhere) instead of Python

* Review: keep program var declarations in source order in the payload (InlineMap is not sorted; its order is already deterministic); registered symbols hash purely by contents; Annex B candidates are a plain Vector; EncodingOrder is a bool less + std::sort; private-name environments hash with computeHash; SourceProviderCacheItem's new fields appended instead of reordering; shorter comments; <ranges> with the other system includes; static_assert against encoderMaxAlignment; stress test plans named; layout check fails on a missing dump and covers the freebsd and android images too

* Annex B candidates: KeyValuePair elements, so the two loops over them read as before

* Scope: hoisting-candidate Vector takes the old map's slot (+ m_closedVariableCandidates') so m_lexicalVariables stays at the cache line on ARM64

* SymbolImpl: content hash only for the private registry's symbols (the parser's synthetic names); Symbol.for() keeps the counter

* RegisteredSymbolImpl::createPrivate: take the hash from the registry string (already computed by the lookup) instead of rehashing; SymbolImpl's constructors are as upstream again

* ASTBuilder: for a bytecode cache, do not fold number ** number at all (MathCommon untouched)

* Drop CodeGenerationMode::BytecodeCache: number ** number folds as upstream; the cross-platform comparison simply avoids literal non-integer exponents (ParserModes.h, ASTBuilder.h, UnlinkedFunctionExecutable.cpp, UnlinkedCodeBlock.cpp back to upstream)

* Drop the SourceProviderCache pinning (VM.cpp, CodeCache.cpp back to upstream): with the parse/skip divergences fixed, dropping caches on a full GC no longer changes the output -- verified under --collectContinuously and a 32 KB max heap on the corpus and typescript.js

* dump-bytecode-cache-layout: only unescape \" and \\ inside quoted arguments

* UnlinkedMetadataTable: an explicit m_isBackedBySteps bit instead of testing m_steps for null (a value-profile-only table has zero steps)

* dump-bytecode-cache-layout: follow only a Cached container's element arguments (clang-cl lays out more records in this TU; pointer-like templates' arguments dragged GC types into the Windows dump)

* dump-bytecode-cache-layout: don't refer to the global Record<> (shadowed by the local type)

* CI: skip the cross-platform layout comparison step for now (it re-reads every tarball); the per-image dumps stay
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant