perf(libc): scan wide strings sixteen bytes at a time #17326

Merged
rocklouis055 merged 1 commit from upstream-pr/17326 into main 2026-11-11 12:57:14 +00:00
rocklouis055 commented 2026-11-08 17:57:59 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by rocklouis055 on 2026-11-08T17:57:59Z.


What

wcslen, wcsnlen_s, wmemchr, wcschr and wcsrchr looked at one UTF-16 unit per step. They now compare eight units per SSE2 step.

  • Loads are 16-byte aligned, so a load never crosses a page and never faults past the string. Lanes before the start are masked off, and bounded scans mask lanes past n. The helpers that load are marked no_sanitize("address"), as in GuestAllocations.cpp.
  • wcschr stops at the first match or terminator. wcsrchr keeps the last match in each block up to the terminator.
  • wmemchr and wcsnlen_s share one bounded scan. A count past the end of the address space is clamped, so SIZE_MAX still works when the unit is present.
  • Odd addresses, and builds without __SSE2__ (the Emscripten test build compiles this file), keep main's loops.

The results are unchanged, and no exported functions or NIDs are added or changed.

Tested

Ubuntu 26.04, GCC 15.2, Release, -DBUILD_TESTING=ON. All 18 guest_wide*, guest_wcs*, guest_wmemchr* and guest_string* tests pass. These include the guard-page tests guest_wide_char_boundary, guest_wmemchr_boundary, guest_wcslen_boundary and guest_wide_length_protected.

The new guest_wide_scan_blocks test runs 20000 random cases against naive references:

  • start offsets 0–32 bytes from a 32-byte boundary, odd ones included;
  • lengths 0–540 units;
  • matching units placed before the start and after the terminator;
  • targets that include 0;
  • wmemchr/wcsnlen_s limits below, at and past the terminator, plus SIZE_MAX and a null pointer with n == 0.

Mutation check. Each change below makes the test suite fail:

  • not masking lanes before the start (in the unbounded and the bounded scan);
  • an off-by-one in the end mask;
  • keeping wcsrchr matches past the terminator;
  • not masking wcsrchr lanes before the start;
  • the wrong unit from the last match bit;
  • wcschr returning the terminator;
  • wcsnlen_s returning 0 when no terminator is found;
  • dropping the SIZE_MAX clamp.

Ending the bounded loop at < 16 instead of <= 16 passes the new test, because it only reads one extra aligned block. The guard-page tests fail on it.

Windows: Strings.cpp and the new test pass a syntax-only build for x86_64-windows-gnu (zig/clang), where __SSE2__ is defined. Not built with MinGW or run on Windows.

Performance: I have no title capture. I can't run a title, so there are no main/PR summary lines.

Micro-benchmark through the built libc.prx, at 1393eea62d against main bfdb58119e. Medians of 31 samples, in ns per call, on a string of a with the target absent (wcsrchr searches for a):

units wcslen wcsnlen_s wmemchr wcschr wcsrchr
7 2.7 → 1.8 3.2 → 3.3 2.8 → 4.5 5.2 → 4.2 7.0 → 3.6
31 14.2 → 2.3 15.0 → 3.8 15.4 → 3.7 15.0 → 3.4 15.0 → 5.5
255 70 → 15 85 → 16 109 → 15 83 → 19 101 → 27
4095 791 → 227 1060 → 217 1536 → 216 1047 → 312 1531 → 434
65535 12648 → 3380 16700 → 3352 24386 → 3354 16499 → 4730 24379 → 6778

wmemchr over 7 units costs about +1.7 ns. Every other case is equal or faster.

Order with other open PRs

pr_overlap lists #15807, #16210, #8965 and #5021 on Strings.cpp, and others on libc/CMakeLists.txt. None of them change these functions. For every listed PR, git merge-tree shows the same conflicting files against this branch as against main, so this branch adds no conflict in either order.

Sibling PRs from me in the same area: #17336 (wide compares), #17345 (memrchr/memccpy), #17354 (strnlen/stpncpy) and #17394 (strcasecmp). All of them merge with this branch and each other cleanly in any order (git merge-tree).

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. This PR adds no unimplemented paths.
  • No notes, investigation .md files or images added to the repository
  • New third-party code is a submodule built from source. This PR adds no third-party code.
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes (Claude Code)

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5213704638 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/17326). Originally posted by [rocklouis055](https://github.com/rocklouis055) on 2026-11-08T17:57:59Z. --- ### What `wcslen`, `wcsnlen_s`, `wmemchr`, `wcschr` and `wcsrchr` looked at one UTF-16 unit per step. They now compare eight units per SSE2 step. - Loads are 16-byte aligned, so a load never crosses a page and never faults past the string. Lanes before the start are masked off, and bounded scans mask lanes past `n`. The helpers that load are marked `no_sanitize("address")`, as in `GuestAllocations.cpp`. - `wcschr` stops at the first match or terminator. `wcsrchr` keeps the last match in each block up to the terminator. - `wmemchr` and `wcsnlen_s` share one bounded scan. A count past the end of the address space is clamped, so `SIZE_MAX` still works when the unit is present. - Odd addresses, and builds without `__SSE2__` (the Emscripten test build compiles this file), keep main's loops. The results are unchanged, and no exported functions or NIDs are added or changed. ### Tested Ubuntu 26.04, GCC 15.2, Release, `-DBUILD_TESTING=ON`. All 18 `guest_wide*`, `guest_wcs*`, `guest_wmemchr*` and `guest_string*` tests pass. These include the guard-page tests `guest_wide_char_boundary`, `guest_wmemchr_boundary`, `guest_wcslen_boundary` and `guest_wide_length_protected`. The new `guest_wide_scan_blocks` test runs 20000 random cases against naive references: - start offsets 0–32 bytes from a 32-byte boundary, odd ones included; - lengths 0–540 units; - matching units placed before the start and after the terminator; - targets that include 0; - `wmemchr`/`wcsnlen_s` limits below, at and past the terminator, plus `SIZE_MAX` and a null pointer with `n == 0`. Mutation check. Each change below makes the test suite fail: - not masking lanes before the start (in the unbounded and the bounded scan); - an off-by-one in the end mask; - keeping `wcsrchr` matches past the terminator; - not masking `wcsrchr` lanes before the start; - the wrong unit from the last match bit; - `wcschr` returning the terminator; - `wcsnlen_s` returning 0 when no terminator is found; - dropping the `SIZE_MAX` clamp. Ending the bounded loop at `< 16` instead of `<= 16` passes the new test, because it only reads one extra aligned block. The guard-page tests fail on it. Windows: `Strings.cpp` and the new test pass a syntax-only build for `x86_64-windows-gnu` (zig/clang), where `__SSE2__` is defined. Not built with MinGW or run on Windows. **Performance:** I have no title capture. I can't run a title, so there are no `main`/PR summary lines. Micro-benchmark through the built `libc.prx`, at `1393eea62d` against main `bfdb58119e`. Medians of 31 samples, in ns per call, on a string of `a` with the target absent (`wcsrchr` searches for `a`): | units | wcslen | wcsnlen_s | wmemchr | wcschr | wcsrchr | |---|---|---|---|---|---| | 7 | 2.7 → 1.8 | 3.2 → 3.3 | 2.8 → 4.5 | 5.2 → 4.2 | 7.0 → 3.6 | | 31 | 14.2 → 2.3 | 15.0 → 3.8 | 15.4 → 3.7 | 15.0 → 3.4 | 15.0 → 5.5 | | 255 | 70 → 15 | 85 → 16 | 109 → 15 | 83 → 19 | 101 → 27 | | 4095 | 791 → 227 | 1060 → 217 | 1536 → 216 | 1047 → 312 | 1531 → 434 | | 65535 | 12648 → 3380 | 16700 → 3352 | 24386 → 3354 | 16499 → 4730 | 24379 → 6778 | `wmemchr` over 7 units costs about +1.7 ns. Every other case is equal or faster. ### Order with other open PRs `pr_overlap` lists #15807, #16210, #8965 and #5021 on `Strings.cpp`, and others on `libc/CMakeLists.txt`. None of them change these functions. For every listed PR, `git merge-tree` shows the same conflicting files against this branch as against `main`, so this branch adds no conflict in either order. Sibling PRs from me in the same area: #17336 (wide compares), #17345 (`memrchr`/`memccpy`), #17354 (`strnlen`/`stpncpy`) and #17394 (`strcasecmp`). All of them merge with this branch and each other cleanly in any order (`git merge-tree`). ### 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 - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's technical debt file. This PR adds no unimplemented paths. - [x] No notes, investigation `.md` files or images added to the repository - [x] New third-party code is a submodule built from source. This PR adds no third-party code. - [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 (Claude Code) 🤖 Generated with [Claude Code](https://claude.com/claude-code)
gabichuuuuu commented 2026-11-08 19:17:34 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by gabichuuuuu on 2026-11-08T19:17:34Z.

Review: COMMENTED


Windows run of head 1393eea62d, merged onto main 9fabd4aa7e. To save builds, this ran in one tree together with 11 other open PRs that touch different code (four libc string speed-ups and eight test-only PRs); all merged cleanly. Setup: Windows 11, WinLibs GCC 15.2 (x86_64-ucrt-posix-seh), Release, BUILD_TESTING=ON, i7-12800H.

  • guest_wide_scan_blocks with --repeat until-fail:5: 5 / 5 pass.
  • Extra differential check, not part of this PR. I wrote a fuzz test that compares strnlen, stpncpy, memrchr, memccpy, wcslen, wcschr, wcsrchr, wmemchr, wcsnlen_s, wcscmp, wcsncmp and wmemcmp with byte-by-byte reference loops. It runs 400,000 rounds with random lengths, alphabets and odd or even alignments. Half of the strings end right before a PAGE_NOACCESS page, and memrchr also starts right after one, so any read past the bounds faults. With this PR's code (all four speed-ups together), 5,600,000 checks agree and nothing faults.
  • With main's Strings.cpp and StringExtensions.cpp, the same tests and the fuzz pass too, so the new test pins the result of wcslen, wcschr, wcsrchr, wmemchr and wcsnlen_s, not the speed-up. That's expected for a speed change, but it means the new code paths are covered only by the equivalence checks.

I didn't measure the speed.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5819285683 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/17326#pullrequestreview-5819285683). Originally posted by [gabichuuuuu](https://github.com/gabichuuuuu) on 2026-11-08T19:17:34Z. **Review:** COMMENTED --- Windows run of head `1393eea62d`, merged onto `main` `9fabd4aa7e`. To save builds, this ran in one tree together with 11 other open PRs that touch different code (four libc string speed-ups and eight test-only PRs); all merged cleanly. Setup: Windows 11, WinLibs GCC 15.2 (`x86_64-ucrt-posix-seh`), Release, `BUILD_TESTING=ON`, i7-12800H. - `guest_wide_scan_blocks` with `--repeat until-fail:5`: 5 / 5 pass. - **Extra differential check, not part of this PR.** I wrote a fuzz test that compares `strnlen`, `stpncpy`, `memrchr`, `memccpy`, `wcslen`, `wcschr`, `wcsrchr`, `wmemchr`, `wcsnlen_s`, `wcscmp`, `wcsncmp` and `wmemcmp` with byte-by-byte reference loops. It runs 400,000 rounds with random lengths, alphabets and odd or even alignments. Half of the strings end right before a `PAGE_NOACCESS` page, and `memrchr` also starts right after one, so any read past the bounds faults. With this PR's code (all four speed-ups together), 5,600,000 checks agree and nothing faults. - With `main`'s `Strings.cpp` and `StringExtensions.cpp`, the same tests and the fuzz pass too, so the new test pins the result of `wcslen`, `wcschr`, `wcsrchr`, `wmemchr` and `wcsnlen_s`, not the speed-up. That's expected for a speed change, but it means the new code paths are covered only by the equivalence checks. I didn't measure the speed.
PrivacyOnion commented 2026-11-08 19:51:54 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by PrivacyOnion on 2026-11-08T19:51:54Z.

Review: DISMISSED


Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 1393eea62d:

  • Conventions: tools/check_conventions.py passed; git diff --check clean.
  • Build: guest_wide_scan_blocks_tests built cleanly.
  • CTest (guest_wide_scan_blocks):
    1/1 Test #1100: guest_wide_scan_blocks ...........   Passed    0.08 sec
    100% tests passed, 0 tests failed out of 1
    
  • Negative control: the tests still pass with the change reverted, so they do not cover it
  • Code reading:
    • Verified 16-byte aligned vector loads in MatchUnits, MatchUnitsOrZero, and FindLastUnit never cross 4KB page boundaries and are properly annotated with gnu::no_sanitize("address")
    • Checked bitmask indexing and endian arithmetic in UnitAt (std::countr_zero) and FindLastUnit (std::countl_zero with unsigned 32-bit movemasks) across all 8 char16_t lane positions and null-terminator locations
    • Validated boundary clamping against address space wrap-around in FindUnit using (UINTPTR_MAX - address) / sizeof(char16_t) with SIZE_MAX limits
    • Audited wcschr, wcsrchr, and wcslen behavior with target c == 0 to confirm conforming handling of the terminating null wide character
    • Checked AGENTS.md compliance regarding code comments, Conventional Commits formatting, export definitions, and third-party dependencies
  • Concerns:
    • AGENTS.md:16: AGENTS.md strictly mandates that 'A speed claim shows tools/trace_digest.py summaries of main and of the change from the same machine and scene.' The PR description for this perf commit explicitly admits omitting tools/trace_digest.py summaries ('I have no title capture. I can't run a title, so there are no main/PR summary lines.') and substitutes micro-benchmarks instead of the required trace digest comparison.
    • core/libs/tests/GuestWideScanBlocks.cpp:1: The mechanical negative gate failed (negative.ok: false). The newly added test guest_wide_scan_blocks still passes when core/libs/prx/libc/src/Strings.cpp is reverted to main, failing the project's gate requirement that newly added tests demonstrate coverage by failing against the unpatched implementation.

Requesting changes for the points above.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5819411447 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/17326#pullrequestreview-5819411447). Originally posted by [PrivacyOnion](https://github.com/PrivacyOnion) on 2026-11-08T19:51:54Z. **Review:** DISMISSED --- Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against `1393eea62d`: - **Conventions**: `tools/check_conventions.py` passed; `git diff --check` clean. - **Build**: `guest_wide_scan_blocks_tests` built cleanly. - **CTest** (`guest_wide_scan_blocks`): ``` 1/1 Test #1100: guest_wide_scan_blocks ........... Passed 0.08 sec 100% tests passed, 0 tests failed out of 1 ``` - **Negative control**: the tests still pass with the change reverted, so they do not cover it - **Code reading**: - Verified 16-byte aligned vector loads in MatchUnits, MatchUnitsOrZero, and FindLastUnit never cross 4KB page boundaries and are properly annotated with [[gnu::no_sanitize("address")]] - Checked bitmask indexing and endian arithmetic in UnitAt (std::countr_zero) and FindLastUnit (std::countl_zero with unsigned 32-bit movemasks) across all 8 char16_t lane positions and null-terminator locations - Validated boundary clamping against address space wrap-around in FindUnit using (UINTPTR_MAX - address) / sizeof(char16_t) with SIZE_MAX limits - Audited wcschr, wcsrchr, and wcslen behavior with target c == 0 to confirm conforming handling of the terminating null wide character - Checked AGENTS.md compliance regarding code comments, Conventional Commits formatting, export definitions, and third-party dependencies - **Concerns**: - AGENTS.md:16: AGENTS.md strictly mandates that 'A speed claim shows tools/trace_digest.py summaries of main and of the change from the same machine and scene.' The PR description for this perf commit explicitly admits omitting tools/trace_digest.py summaries ('I have no title capture. I can't run a title, so there are no main/PR summary lines.') and substitutes micro-benchmarks instead of the required trace digest comparison. - core/libs/tests/GuestWideScanBlocks.cpp:1: The mechanical negative gate failed (negative.ok: false). The newly added test guest_wide_scan_blocks still passes when core/libs/prx/libc/src/Strings.cpp is reverted to main, failing the project's gate requirement that newly added tests demonstrate coverage by failing against the unpatched implementation. Requesting changes for the points above.
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!17326
No description provided.