perf(relinker): collect code instructions into sorted vectors #12154

Merged
JJenkx merged 2 commits from upstream-pr/12154 into main 2026-11-02 12:29:28 +00:00
JJenkx commented 2026-10-27 23:53:52 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by JJenkx on 2026-10-27T23:53:52Z.


What

A Windows conversion spends most of its time in CodeInstructionCollector::Collect, called by WindowsTlsBuilder::Build. Within that, a large share goes to std::set<std::uint64_t> insertions. Every decoded instruction address and every static branch target was inserted into a red-black tree, millions of insertions for a 35 MB eboot.

Stack samples of relinker --windows on PPSA28311's eboot (gdb attached every 150 ms, 40 samples, main thread) showed this. 34 samples were inside Collect. In 14 of them the frame directly below Collect was std::_Rb_tree::_M_insert_unique, and a few more were the matching node allocation and free. The conversion runs on one thread: 9.5 s of CPU in 9.8 s of wall time.

Two commits:

  1. Sorted vectors. Both collections are now vectors:
  • staticTargets is sorted and deduplicated before the check against skipped ranges, so it is walked in the same order as before.
  • instructions collects into a vector during the linear decode and the graph passes. It is sorted and deduplicated once, and the std::set that Collect returns is built from that sorted list, which is linear time.
  1. Per-section bitmaps. The graph pass recorded every reachable instruction in an unordered_set<VirtualAddress>, one node allocation each. In a profile of commit 1, its insertions and the matching heap allocations were 6 of 40 samples, and removing it gave more than its sample share suggested. Each code section now has a vector<bool> over its bytes, sized on first use. An address outside its section, for which the decode below would have read past the section, is now reported as an error.

The overlap check, the return type and all callers are unchanged.

Tested

Current-main refresh (2026-11-01): linear head 0e8027852cf4e9c9473ff75f9857123fda3fc89b on main 93dbd0f82aea. Main's incremental ExtendControlFlowGraph and byte-per-offset reached state are retained. The decoded-address bitmap and sorted/deduplicated vector collection are adapted to that API. Linux x86-64, GCC 16.2.1, Ninja Release, ANYPS5_RELINKER_ONLY=ON, BUILD_TESTING=ON: rebuilt relinker and all registered tests, 557/557 CTests pass; conventions and whitespace pass. Historical platform and performance reports below remain pinned to their stated commits; no new conversion timing or runtime gain is claimed.

Windows 11 Enterprise 10.0.22621, Ryzen 9 5950X, WinLibs GCC 15.2.0 UCRT r7, Ninja, Release, -DANYPS5_RELINKER_ONLY=ON -DBUILD_TESTING=ON. Two builds:

  • base: main 6e9b9134f6;
  • candidate: this head ad732ce0ec, two commits on that base.

Output is identical. Four title executables (unwrapped eboot.bin) were converted with --windows --skip-sce-module --registry, alternating base and candidate, three times each. Every run produced a byte-identical app.exe and app.registry.json on both builds, and every run exited 0.

Wall time, min/median/max over 3 runs each, in ms:

title base candidate median change
PPSA28311 (35.9 MB) 9353/9441/9568 6615/6680/6785 −29.2%
PPSA27616 (34.3 MB) 10272/10400/10513 6898/6990/7045 −32.8%
PPSA20423 8416/8436/8469 5676/5825/5826 −31.0%
PPSA13934 8826/8897/8899 6166/6182/6190 −30.5%

With commit 1 alone, the median changes were −15% to −17% (same titles and method).

Tests: all 372 relinker CTests pass in each of 3 runs on the candidate (both commits), and on the base. python tools/check_conventions.py --base origin/main and git diff --check pass.

Overlap: Felipebmaitan's open #10861 rewrites the same graph-pass loop, including the decodedInstructions and instructions.insert(address) lines changed here. Whichever lands second needs a small rebase.

Not tested: Linux and macOS conversion times. The code is host-independent, and macOS conversion calls the same Collect.

Current refresh source proofs and unedited test logs, SHA-256 b4491a56de7e9655af33b7a34afbce236ceb43ebd4e44c11b42454b282648563.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source: none
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes

AI-assisted (Claude Code).

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5042891517 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12154). Originally posted by [JJenkx](https://github.com/JJenkx) on 2026-10-27T23:53:52Z. --- ### What A Windows conversion spends most of its time in `CodeInstructionCollector::Collect`, called by `WindowsTlsBuilder::Build`. Within that, a large share goes to `std::set<std::uint64_t>` insertions. Every decoded instruction address and every static branch target was inserted into a red-black tree, millions of insertions for a 35 MB `eboot`. Stack samples of `relinker --windows` on PPSA28311's `eboot` (gdb attached every 150 ms, 40 samples, main thread) showed this. 34 samples were inside `Collect`. In 14 of them the frame directly below `Collect` was `std::_Rb_tree::_M_insert_unique`, and a few more were the matching node allocation and `free`. The conversion runs on one thread: 9.5 s of CPU in 9.8 s of wall time. Two commits: 1. **Sorted vectors.** Both collections are now vectors: - `staticTargets` is sorted and deduplicated before the check against skipped ranges, so it is walked in the same order as before. - `instructions` collects into a vector during the linear decode and the graph passes. It is sorted and deduplicated once, and the `std::set` that `Collect` returns is built from that sorted list, which is linear time. 2. **Per-section bitmaps.** The graph pass recorded every reachable instruction in an `unordered_set<VirtualAddress>`, one node allocation each. In a profile of commit 1, its insertions and the matching heap allocations were 6 of 40 samples, and removing it gave more than its sample share suggested. Each code section now has a `vector<bool>` over its bytes, sized on first use. An address outside its section, for which the decode below would have read past the section, is now reported as an error. The overlap check, the return type and all callers are unchanged. ### Tested **Current-main refresh (2026-11-01):** linear head `0e8027852cf4e9c9473ff75f9857123fda3fc89b` on main `93dbd0f82aea`. Main's incremental `ExtendControlFlowGraph` and byte-per-offset reached state are retained. The decoded-address bitmap and sorted/deduplicated vector collection are adapted to that API. Linux x86-64, GCC 16.2.1, Ninja Release, `ANYPS5_RELINKER_ONLY=ON`, `BUILD_TESTING=ON`: rebuilt relinker and all registered tests, **557/557 CTests pass**; conventions and whitespace pass. Historical platform and performance reports below remain pinned to their stated commits; no new conversion timing or runtime gain is claimed. Windows 11 Enterprise 10.0.22621, Ryzen 9 5950X, WinLibs GCC 15.2.0 UCRT r7, Ninja, Release, `-DANYPS5_RELINKER_ONLY=ON -DBUILD_TESTING=ON`. Two builds: - **base:** `main` `6e9b9134f6`; - **candidate:** this head `ad732ce0ec`, two commits on that base. **Output is identical.** Four title executables (unwrapped `eboot.bin`) were converted with `--windows --skip-sce-module --registry`, alternating base and candidate, three times each. Every run produced a byte-identical `app.exe` and `app.registry.json` on both builds, and every run exited 0. **Wall time**, min/median/max over 3 runs each, in ms: | title | base | candidate | median change | |---|---|---|---| | PPSA28311 (35.9 MB) | 9353/9441/9568 | 6615/6680/6785 | −29.2% | | PPSA27616 (34.3 MB) | 10272/10400/10513 | 6898/6990/7045 | −32.8% | | PPSA20423 | 8416/8436/8469 | 5676/5825/5826 | −31.0% | | PPSA13934 | 8826/8897/8899 | 6166/6182/6190 | −30.5% | With commit 1 alone, the median changes were −15% to −17% (same titles and method). **Tests:** all 372 relinker CTests pass in each of 3 runs on the candidate (both commits), and on the base. `python tools/check_conventions.py --base origin/main` and `git diff --check` pass. **Overlap:** Felipebmaitan's open #10861 rewrites the same graph-pass loop, including the `decodedInstructions` and `instructions.insert(address)` lines changed here. Whichever lands second needs a small rebase. **Not tested:** Linux and macOS conversion times. The code is host-independent, and macOS conversion calls the same `Collect`. [Current refresh source proofs and unedited test logs](https://github.com/JJenkx/AnyPS5/releases/download/linux-validation-20261023/pr12154-0e802785-rebase-linux-20261101.tar.gz), SHA-256 `b4491a56de7e9655af33b7a34afbce236ceb43ebd4e44c11b42454b282648563`. ### Checklist - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source: none - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes AI-assisted (Claude Code).
rooklz commented 2026-10-28 00:07:56 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by rooklz on 2026-10-28T00:07:56Z.

Review: APPROVED


Verified on macOS (relinker-only build): full audit of the set→vector conversion, build 266/266, ctest 362/362 at head a3e2c71bec.

Equivalence audit (the risk of deferring dedup): I checked every use of both containers in Collect() on the base tree:

  • instructions — only two writes exist before the deferred sort (phase-1 emplace_hint site → push_back, phase-2 insert site → push_back). Every read that needs set semantics comes after the new sort/unique/set-construction block that follows report(8500): the scan loop, instructions.size() in the progress callback, the lower_bound(address) lookback, and the return value. Cross-phase duplicates that the old set collapsed at insert time are collapsed by the final unique instead — same resulting set, and it's still constructed from a sorted range.
  • staticTargets — sort + unique land directly above its single consumer (the branch-into-skipped-range-tail check), which iterated ascending under the old std::set too, so iteration order, the throw condition and the throw order are unchanged.
  • instructionList = {} after the set construction is memory hygiene only; the old emplace_hint(end, …) hint has no observable effect either way.

Drift check: git diff <base>..upstream/main on CodeInstructionCollector.cpp is empty, so the audit holds against current main (the branch's base 6e9b9134f6 predates today's merges but the file is untouched since).

Gates: fresh ANYPS5_RELINKER_ONLY build 266/266; full ctest 362/362 — the end-to-end conversion fixtures exercise both collection phases (function walk + BuildControlFlowGraph reachability), covering the dedup path being moved.

Perf rationale checks out: both hot containers allocate one red-black-tree node per address on real modules today; replacing them with push_back + one sort each removes the per-address allocation and keeps the addresses contiguous for the scan loop.

Merge-order note (non-blocking): the only open PR sharing this file is #10861, and its hunks do overlap this region — but #10861 already conflicts with the base branch, so it needs a rebase regardless of ordering; this change is small and orthogonal enough to rebase either way.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5676154381 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12154#pullrequestreview-5676154381). Originally posted by [rooklz](https://github.com/rooklz) on 2026-10-28T00:07:56Z. **Review:** APPROVED --- Verified on macOS (relinker-only build): full audit of the set→vector conversion, build 266/266, ctest 362/362 at head `a3e2c71bec`. **Equivalence audit (the risk of deferring dedup):** I checked every use of both containers in `Collect()` on the base tree: - `instructions` — only two writes exist before the deferred sort (phase-1 `emplace_hint` site → `push_back`, phase-2 insert site → `push_back`). Every read that needs set semantics comes *after* the new `sort`/`unique`/set-construction block that follows `report(8500)`: the scan loop, `instructions.size()` in the progress callback, the `lower_bound(address)` lookback, and the return value. Cross-phase duplicates that the old set collapsed at insert time are collapsed by the final `unique` instead — same resulting set, and it's still constructed from a sorted range. - `staticTargets` — `sort` + `unique` land directly above its single consumer (the branch-into-skipped-range-tail check), which iterated ascending under the old `std::set` too, so iteration order, the throw condition and the throw order are unchanged. - `instructionList = {}` after the set construction is memory hygiene only; the old `emplace_hint(end, …)` hint has no observable effect either way. **Drift check:** `git diff <base>..upstream/main` on `CodeInstructionCollector.cpp` is empty, so the audit holds against current main (the branch's base `6e9b9134f6` predates today's merges but the file is untouched since). **Gates:** fresh `ANYPS5_RELINKER_ONLY` build 266/266; full ctest 362/362 — the end-to-end conversion fixtures exercise both collection phases (function walk + `BuildControlFlowGraph` reachability), covering the dedup path being moved. **Perf rationale checks out:** both hot containers allocate one red-black-tree node per address on real modules today; replacing them with `push_back` + one sort each removes the per-address allocation and keeps the addresses contiguous for the scan loop. **Merge-order note (non-blocking):** the only open PR sharing this file is #10861, and its hunks do overlap this region — but #10861 already conflicts with the base branch, so it needs a rebase regardless of ordering; this change is small and orthogonal enough to rebase either way.
rooklz commented 2026-10-28 02:50:52 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by rooklz on 2026-10-28T02:50:52Z.

Review: APPROVED


Re-review after ad732ce0ec (per-section bitmaps). My earlier approval covered only a3e2c71bec.

What I checked in the new commit:

  • The new throw can't fire. ControlFlowGraph.cpp only adds va to reachable when va - textVaddr < text.size(). Here text.size() == header.FileSize == decoded.size(), and sectionReachable[i] is only ever filled by that section's graph. So the offset >= decoded.size() check guards against a bad read and doesn't change behaviour. Before this commit, the same case would have read past text.
  • Global set → per-section bitmap gives the same result. The two only differ if one address is reachable through two code headers. Then the second section decodes it again, but everything that happens on a repeat changes nothing: instructionList is sorted and deduped before the std::set is built, and addRoot/addPointerRoot only insert into roots/dataTargets, which are sets. The final instruction set and roots fixpoint are unchanged.
  • instructions isn't read anywhere between its declaration and the final sort/unique, so building it later is still safe (same check as for commit 1).
  • Memory goes from one hash node per reachable instruction to FileSize bits per code section, about 4.4 MB for a 35 MB text.

Evidence (macOS arm64, relinker-only, Release):

  • PR merged onto main a3ac94774e: build 266/266, ctest 366/366
  • check_conventions --base upstream/main passed; git merge-tree against main is clean
  • pr_overlap: only #10861 (CodeInstructionCollector.cpp, couldn't be compared). That's a merge-order question, not a conflict in this diff.

Still missing: the bot's perf form asks for the two aps5-summary.jsonl lines (main vs. change). The gdb sampling in the description explains the change but isn't a substitute for those lines.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5677176128 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12154#pullrequestreview-5677176128). Originally posted by [rooklz](https://github.com/rooklz) on 2026-10-28T02:50:52Z. **Review:** APPROVED --- Re-review after `ad732ce0ec` (per-section bitmaps). My earlier approval covered only `a3e2c71bec`. What I checked in the new commit: - **The new throw can't fire.** `ControlFlowGraph.cpp` only adds `va` to `reachable` when `va - textVaddr < text.size()`. Here `text.size() == header.FileSize == decoded.size()`, and `sectionReachable[i]` is only ever filled by that section's graph. So the `offset >= decoded.size()` check guards against a bad read and doesn't change behaviour. Before this commit, the same case would have read past `text`. - **Global set → per-section bitmap gives the same result.** The two only differ if one address is reachable through two code headers. Then the second section decodes it again, but everything that happens on a repeat changes nothing: `instructionList` is sorted and deduped before the `std::set` is built, and `addRoot`/`addPointerRoot` only insert into `roots`/`dataTargets`, which are sets. The final instruction set and roots fixpoint are unchanged. - `instructions` isn't read anywhere between its declaration and the final sort/unique, so building it later is still safe (same check as for commit 1). - Memory goes from one hash node per reachable instruction to `FileSize` bits per code section, about 4.4 MB for a 35 MB text. Evidence (macOS arm64, relinker-only, Release): - PR merged onto main `a3ac94774e`: build 266/266, `ctest` **366/366** - `check_conventions --base upstream/main` passed; `git merge-tree` against main is clean - `pr_overlap`: only #10861 (`CodeInstructionCollector.cpp`, couldn't be compared). That's a merge-order question, not a conflict in this diff. Still missing: the bot's `perf` form asks for the two `aps5-summary.jsonl` lines (main vs. change). The gdb sampling in the description explains the change but isn't a substitute for those lines.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!12154
No description provided.