Skip to content

ext/mbstring: Faster UTF-8 validation following simdutf - #25473

Closed
lemire wants to merge 6 commits into
php:masterfrom
lemire:mbstring-utf8-lookup
Closed

lemire wants to merge 6 commits into
php:masterfrom
lemire:mbstring-utf8-lookup

Conversation

@lemire

@lemire lemire commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

This PR updates the SIMD UTF-8 validation behind mb_check_encoding(), and behind the functions that validate UTF-8 before taking a fast path (mb_strlen(), mb_substr(), ...). It uses the "lookup" algorithm from

John Keiser and Daniel Lemire, Validating UTF-8 In Less Than One Instruction Per Byte, Software: Practice and Experience 51 (5), 2021. https://doi.org/10.1002/spe.2940

as implemented in simdutf. The simdutf library is used by mainstream browsers and major JavaScript runtimes. It is thus quite solid (used in production for many years).

Changes

  • AVX2: the existing kernel used part of this algorithm, but checked byte structure separately and tested for errors every 32 bytes. It now uses the full algorithm (three nibble lookups plus the check of the 2nd and 3rd previous bytes) and accumulates errors over blocks. There is also an ASCII fast path for 64-byte blocks. The tail and short strings use overlapping loads instead of a copy. Short strings may read up to 16 bytes of the zend_string header before the content, which the old code already did, and those bytes are cleared.
  • AVX-512 (new): a 64-byte kernel (AVX-512 F/BW/VL/DQ/CD) with a masked load for the tail. It is selected at runtime, via ifunc or a function pointer, like the AVX2 kernel. It is enabled on x86-64 only, and only when the AVX2 kernel is also selected at runtime, which follows ext/standard/base64.c. For long strings it checks one unaligned block, then continues from the next 64-byte boundary. The three bytes of context for that boundary are read from inside the string.
  • ARM64: a NEON implementation of the same algorithm (vqtbl1q_u8) replaces the SSE2 code emulated through zend_simd.h.
  • SSE2 and scalar fallbacks: unchanged.

Performance

mb_check_encoding($s, 'UTF-8'), ns per call; the string is modified before each call so the cached validity flag is cleared.

Intel Xeon Gold 6338 (Ice Lake), GCC 16:

input master AVX2 AVX-512
ASCII, 16 B 37.6 23.9 23.7
ASCII, 1 KiB 55.7 34.3 33.2
ASCII, 1 MiB 30,970 20,862 12,151
UTF-8 (CJK), 258 B 60.1 45.1 38.0
UTF-8 (CJK), 1 KiB 170 104 81
UTF-8 (CJK), 1 MiB 150,212 81,897 59,083

Apple M4 Max, Apple clang:

input master NEON
ASCII, 16 B 14.4 14.1
ASCII, 1 KiB 43.2 19.9
ASCII, 1 MiB 32,410 9,820
UTF-8 (CJK), 258 B 38.3 23.6
UTF-8 (CJK), 1 KiB 143 76
UTF-8 (CJK), 1 MiB 143,200 75,802

None of the measured sizes (16 B to 1 MiB, ASCII, Latin, CJK, emoji) got slower.

Testing

  • New test ext/mbstring/tests/mb_check_encoding_utf8_blocks.phpt. It puts valid, invalid and truncated sequences at every offset of strings up to 140 bytes, and compares against PCRE's UTF-8 validation. The string passed to mb_check_encoding() is a pack() copy, so the UTF-8 flag set by preg_match('//u') is clear and the SIMD path actually runs. It also checks strings of 2048 bytes and longer, which is when the AVX-512 kernel aligns its loads.
  • Differential fuzzing of each kernel against a scalar reference and simdutf. Strings were placed against inaccessible pages to catch out-of-bounds reads.
  • Random strings compared against preg_match('//u', ...).
  • mbstring test suite with:
    • AVX-512 via ifunc
    • AVX2 only
    • clang + ASan with function-pointer dispatch
    • aarch64 Linux under qemu
    • macOS arm64

#24362 also changes the AVX2 dispatch code in mbstring.c, for i386 clang; whichever lands second will need a small rebase.

Use the "lookup" algorithm of Keiser and Lemire, "Validating UTF-8 In
Less Than One Instruction Per Byte", Software: Practice and Experience
51 (5), 2021, as implemented in the simdutf library, for
mb_check_encoding() and the other functions which validate UTF-8:

- AVX2: full lookup algorithm (the previous version only adopted part of
  it), errors accumulated over blocks, 64-byte ASCII fast path, and no
  copying for the tail of the string or for short strings.
- AVX-512 (new): selected at runtime when available, on x86-64.
- ARM64: NEON implementation of the same algorithm, replacing the
  emulated SSE2 code.

Long strings are validated about twice as fast (UTF-8 text) to three
times as fast (ASCII); short strings are not slower.
The new test called preg_match('//u') before mb_check_encoding().
That sets IS_STR_VALID_UTF8, and str_repeat($s, 1) returns the same
string, so valid input never reached the new kernels. Copy the
bytes with pack() first, and cover strings longer than 2048 bytes.

The AVX-512 alignment prologue loaded context through a pointer
before the zend_string. Read the three bytes from inside the string.
OR the NEON continuation checks, matching AVX2.

Record the speedup in NEWS.
@lemire

lemire commented Nov 15, 2026

Copy link
Copy Markdown
Contributor Author

Opened by mistake. Closing.

@lemire lemire closed this Nov 15, 2026
_mm512_setr_epi8 does not exist in GCC or clang. Go back to the
_mm512_setr_epi64 constant, which has the same bytes.
@lemire lemire reopened this Nov 15, 2026
@lemire

lemire commented Nov 15, 2026

Copy link
Copy Markdown
Contributor Author

reopening, as it is now ready for review

@alexdowad

Copy link
Copy Markdown
Contributor

@lemire It is awesome to get a PR coming in from "the man" himself!

If you've fuzzed this code thoroughly, I don't foresee a lot of issues coming up in review. But I do need to do my due diligence, and because of time constraints, that won't happen for at least several days.

So, if you can hold tight for a while, I'll be happy to review this before long. Hopefully shouldn't hold things up too much.

Comment thread ext/mbstring/mbstring.c
* (This will also confirm that the previous block didn't end with a bad byte like 0xFF) */
__m256i bad_mask = _mm256_set_epi8(0xB, 0xD, 0xE, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127);
__m256i bad = _mm256_cmpgt_epi8(last_hi_nibbles, bad_mask);
if (_mm256_movemask_epi8(bad)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lemire Thank you for your pull request. I have a question. In my understand, _mm256_moveask_epi8(bad) is check bad mask in every loop, But your pull request, seems check every 1KiB. I think lost performance when bad UTF-8 sequence, right?

If I am wrong, I'm sorry.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, you are right. The loop accumulates errors and only tests them every 1 KiB, so with invalid input it may read up to about 1 KiB past the error before returning false. It is the same tradeoff as in simdutf, which offers an optimistic validator (assume the input is valid, test at the end) and one that stops at the first error. Since mb_check_encoding() returns only a boolean and inputs are usually valid, I went with the optimistic approach, but bounded it: the extra work is at most about 1 KiB, whatever the string length.

Measured with one invalid byte near the start (ns per call, mb_check_encoding($s, 'UTF-8')):

input master this PR (AVX2) this PR (AVX-512) master (M4) this PR (M4, NEON)
CJK, 1 KiB, valid 141 89 70 145 79
CJK, 1 KiB, error at byte 0 24 79 65 18 73
CJK, 64 KiB, valid 8,296 4,545 3,419 9,060 4,796
CJK, 64 KiB, error at byte 0 24 85 70 18 77
ASCII, 64 KiB, error at byte 0 27 35 32 21 26

So an early error costs about 50–60 ns more per call in the worst case, while valid input of the same size runs 1.6–2.7× faster.

It is a trade-off.

In practice, most strings are going to be valid, I believe.

@lemire

lemire commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

@alexdowad Thanks! It was fuzzed for many hours two days ago. But it is actually still fuzzing. I'll report back.

The CI failure seems unrelated.

@lemire

lemire commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

Ok. Done. So beyond the new phpt, each kernel (AVX2, AVX-512, NEON) was fuzzed against a scalar reference, about 12 billion checks in all, with GCC, clang, ASan and UBSan. Two parts got targeted fuzzing:

  • Short strings, which may read up to 16 bytes of the zend_string header before the content (as the old code already did). The header bytes were filled with adversarial values, and the strings were placed against guard pages on both sides.
  • The AVX-512 path for long strings, which checks one unaligned block and then continues with aligned loads, using three bytes of context from inside the string. Every misalignment from 0 to 63 was tested, with errors and multi-byte characters placed around the alignment point, the block boundaries and the end.

No mismatches.

I can share the fuzzer if it is useful.

lemire added a commit to simdutf/simdutf that referenced this pull request Nov 17, 2026
* validate_utf8: stop early on invalid input

validate_utf8 accumulated errors over the whole input and tested them
once at the end, so an invalid string cost as much as a valid one of the
same length. We now test the error vector when a non-ASCII block is
reached and at least 1 KiB has been processed since the last test, as
in php/php-src#25473. The ASCII path is unchanged. An ASCII block can
only be in error when it follows a truncated character, and that error
is still caught by the next test or at the end.
The test is marked unlikely so that the compiler keeps the ASCII path as
the fall-through; without it, clang gave the icelake ASCII loop a second
taken branch per block.

* icelake: rename check_when_left to left_at_next_check
@alexdowad

Copy link
Copy Markdown
Contributor

@lemire Just did some testing. This looks good!

I found that some operations on pure-ASCII strings seem slower with this patch than before. However, when EXPECTED() is used to let the compiler know that the ASCII path is the expected one, we recover the lost performance and more.

The new tests also look good. It would be better if a bit more test coverage can be added:

  • The upper part tests strings 140 chars long, the lower part tests 2048, 2112, and 4095. It would be good to try lengths slightly less than 1024, 1024, and slightly more than 1024 as well, since "1024 bytes" is a meaningful number for the rewritten functions.
  • The lower part only tries mutating $s[64]. However other offsets, like 63, 1023, 1024, 1025? Also, how about the last few bytes of the string?

…ation

Mark the all-ASCII branch as expected in the NEON and AVX-512 block
loops, and the periodic error checks as unexpected in all three kernels.
The AVX2 ASCII branch is left without a hint: with GCC 16 it makes
the compiler spill registers in the non-ASCII path, and UTF-8 text gets
about 12% slower, for a gain of about 1% on ASCII.

Test lengths around 1024 and 1088 bytes, where the kernels check the
accumulated errors, as well as 2047-4097 bytes. Corrupt bytes at
offsets around 64, 1024, 1088 and 2048, and in the last 6 bytes.
The content of a long zend_string starts 24 bytes past a 64-byte
boundary, so half of the 32-byte loads crossed a cache line. As in the
AVX-512 kernel, check one unaligned 64-byte block, then continue from
the next 64-byte boundary with the 3 preceding bytes as context.

On an Ice Lake server, long ASCII strings were about 7% slower than with
the old AVX2 code; they are now about 20% faster.
As in the AVX2 and AVX-512 kernels, check one unaligned 64-byte block,
then continue from the next 64-byte boundary with the 3 preceding bytes
as context.

On Graviton 5 (Neoverse V3), long ASCII strings are validated 5% (64 KiB)
to 14% (1 MiB) faster; Apple M4 shows no difference.
@lemire

lemire commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

@alexdowad Thanks for testing!

Tests: done. The test now covers lengths just below, at and above 1024 (and 2048, 4096), and puts invalid bytes at many offsets, including 63, 64, 1023, 1024, 1025 and the last few bytes of the string.

ASCII slowdown: I found the cause. Long strings start 24 bytes past a cache-line boundary, so many loads crossed cache lines. The AVX2 and NEON kernels now align their loads, as the AVX-512 kernel already did. Long ASCII strings are now about 20% faster than master with AVX2 (they were 7% slower before).

EXPECTED(): with GCC 16 on AVX2, it made UTF-8 text about 12% slower, with almost no gain on ASCII, so I left it out there. I added it to the NEON and AVX-512 kernels, where it does no harm.

I also tested on Graviton 5. On all the machines I tried (Intel Emerald Rapids, Apple M4, Graviton 5), nothing is slower than master, from 16 bytes to 1 MiB.

@alexdowad

Copy link
Copy Markdown
Contributor

I think we can go ahead and merge this. @youkidearitai, do you have any other questions or concerns before I go ahead?

@youkidearitai youkidearitai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@alexdowad Nothing, LGTM! Thanks @lemire !

@alexdowad

alexdowad commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Merged into master. @lemire, thank you for this very nice contribution! I hope this gets some attention in the announcement of the next PHP release! @DanielEScherzer @svpernova09 @mbeccati

@lemire, this GH thread may not be the best place to start a separate discussion, but I am very interested if you have any thoughts on the possibility of using SIMD to speed up Unicode case conversions. Our ASCII case conversions use SIMD instructions when available, and it's unfortunate that Unicode case conversion can't benefit as well.

A while ago, one of our core contributors wanted to merge a patch which made mbstring's case conversion first check if a string was all-ASCII, and then use the SIMD fast path if so. I didn't like the patch myself, because it forces a full scan of every string, which is wasted work if it turns out the string is non-ASCII.

Another option is to convert long runs of ASCII characters using SIMD, and fall back to scalar code for runs of non-ASCII characters. But I wonder how much that will help in real-world usage.

Yet another idea is to optimistically try converting an ASCII prefix of the string using SIMD, and fall back to the current code for any non-ASCII suffix. That would avoid the possibility of a wasted full scan.

If you have any thoughts, I'd love to hear them.

@youkidearitai

Copy link
Copy Markdown
Contributor

@alexdowad I comfirmed commit in 0fb074d (and more) but perhaps your Git author's name is T. T is you, right?

@lemire

lemire commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

@alexdowad I will send an email at the email address your show on your GH profile.

@alexdowad

alexdowad commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

@alexdowad I comfirmed commit in 0fb074d (and more) but perhaps your Git author's name is T. T is you, right?

Oh my. It looks like I didn't have git properly configured on the machine where I applied the patches.

@alexdowad

Copy link
Copy Markdown
Contributor

@alexdowad I comfirmed commit in 0fb074d (and more) but perhaps your Git author's name is T. T is you, right?

Oh my. It looks like I didn't have git properly configured on the machine where I applied the patches.

I checked the git history for php-src:master and there was one other earlier patch which I applied with the same mixed-up git configuration (it was 49b9884).

@alexdowad

Copy link
Copy Markdown
Contributor

Hmm. The master branch is protected against force-pushes (which it should be), so I can't fix up the incorrect committer. 😅 Thanks to @youkidearitai for noticing the problem.

@youkidearitai

Copy link
Copy Markdown
Contributor

@alexdowad This PR was already merge, So I close.

@mbeccati

mbeccati commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

I hope this gets some attention in the announcement of the next PHP release!

This has been merged to master: 8.6.0 has been released last week, so this will take about a year to be end up in a stable release, I'm afraid

@TimWolla

TimWolla commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

This has been merged to master: 8.6.0 has been released last week, so this will take about a year to be end up in a stable release, I'm afraid

With an appropriate description in UPGRADING (

php-src/UPGRADING

Lines 247 to 249 in e6707b5

- MBString:
. Improved performance of mb_strlen for UTF-8 strings.
. Improved performance of mb_substr and mb_strpos for UTF-8 strings.
) - currently there is none - I'm confident it will get its mention on the release page, though.

@alexdowad

Copy link
Copy Markdown
Contributor

Hmm!
@lemire Do you want to add an entry to UPGRADING as suggested by @TimWolla? Up to you.

@lemire

lemire commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

@alexdowad

Something of the sort maybe?

- MBString:
  . Improved performance of UTF-8 validation (mb_check_encoding() and the fast paths used by mb_strlen(), mb_substr(), etc.).

If I need to do something, please tell me.

@youkidearitai

Copy link
Copy Markdown
Contributor

@lemire @alexdowad I have an idea. Could you create follow-up pull request that about write UPGRADING?

@lemire

lemire commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @youkidearitai. I opened #25795 with an UPGRADING entry.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants