Skip to content

ext/mbstring: Convert the case of leading ASCII characters with SIMD - #25812

Closed
lemire wants to merge 2 commits into
php:masterfrom
lemire:mbstring-ascii-case
Closed

lemire wants to merge 2 commits into
php:masterfrom
lemire:mbstring-ascii-case

Conversation

@lemire

@lemire lemire commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Follow-up to the discussion in #25473 about using SIMD in mbstring's case conversion.

When both the input and output encodings are UTF-8, php_unicode_convert_case() now converts the leading ASCII characters 16 bytes at a time (SSE2 on x86-64, NEON on arm64, with a scalar loop elsewhere and for the tail). We use the fact that all x64 processors support SSE2. It stops at the first non-ASCII byte, and the existing loop handles the rest of the string.

The string is not scanned first: the fast loop converts as it goes. On a non-ASCII string, the existing loop redoes at most 63 bytes of that work.

Final sigma. The existing loop converts 64 codepoints at a time, and the special casing of the final Greek sigma looks back into the previous block's output (converted_buf). So the fast loop hands over at a multiple of 64 bytes, with the last 64 converted characters copied into converted_buf. The output is therefore exactly what the existing loop alone produces, including for long runs of case-ignorable characters.

Scope. Upper, lower and fold, both full and simple. Title case still goes through the existing loop. This covers mb_strtolower(), mb_strtoupper(), mb_convert_case() and the case-insensitive searches (mb_stripos(), mb_stristr(), ...) when the string is UTF-8.

Benchmarks

Best of 5 runs, ns per call, UTF-8 input.

input Apple M4 (NEON) before → after Xeon 6548N (SSE2) before → after
ASCII, 8 B, lower 45 → 34 69 → 45
ASCII, 32 B, lower 78 → 32 131 → 42
ASCII, 1 KB, lower 1498 → 56 (27x) 3152 → 81 (39x)
ASCII, 1 KB, upper 1265 → 56 (23x) 2757 → 82 (34x)
ASCII, 64 KB, lower 92406 → 1618 (57x) 196568 → 2626 (75x)
é at 50%, 1 KB, lower 1546 → 897 3086 → 1756
Latin-1 text, 1 KB, upper 1729 → 1642 3085 → 3130
é first, 1 KB, upper 1375 → 1381 2765 → 2800
Greek, 1 KB, upper 1682 → 1711 2649 → 2658
"Café", upper 42 → 44 60 → 63

The worst case is a short string with a non-ASCII character near the start, such as "Café": about 2–3 ns slower, from the function call and the discarded prefix work. The fast loop is kept out of line (zend_never_inline). Inlining it changed GCC's code generation for the existing loop and slowed non-ASCII uppercase by about 15% on x86.

Testing

  • New test mb_convert_case_ascii_prefix.phpt. It puts the first non-ASCII character at every offset from 0 to 200, for every mode, including final-sigma cases around the 64-byte handover.
  • Differential fuzzing against an unpatched build, on arm64 and x86-64: random mixes of ASCII, case-ignorable runs, sigma, special-casing characters and invalid bytes, in all 8 case modes plus mb_stripos(). About 100,000 strings, identical output.
  • ext/mbstring tests pass on arm64 (macOS) and x86-64 (Linux).

When both the input and output encodings are UTF-8, php_unicode_convert_case()
now converts the leading ASCII characters 16 bytes at a time (SSE2 or NEON,
with a scalar fallback), and stops at the first non-ASCII byte. The general
loop handles the rest of the string. Title case is left to the general loop.

There is no separate scan of the whole string: the fast loop does the
conversion as it goes, and a non-ASCII string costs at most 63 bytes of work
that the general loop redoes.

The general loop converts 64 codepoints at a time, and the special casing of
the final Greek sigma looks back into the previous block. So the handover
happens at a multiple of 64 bytes, with the last 64 converted characters
already in converted_buf, and the output is the same as before.

This speeds up mb_strtolower(), mb_strtoupper(), mb_convert_case() and the
case-insensitive searches (mb_stripos() and co.) on ASCII and mostly-ASCII
UTF-8 strings.
@alexdowad

Copy link
Copy Markdown
Contributor

Very nice work, @lemire. Thank you! We have been wanting something like this for a long time. (@mvorisek, do you remember that quite some time ago, I respectfully declined one of your patches which aimed to speed up case-conversion via SIMD? This new patch is exactly the kind of thing I was hoping to see at that time.)

Now, about the use of __SSE2__, I believe this is not defined by MSVC. So if PHP is compiled with MSVC, I believe that the scalar branch of convert_case_ascii_prefix will be used. (I don't normally work on a Windows box and haven't tried compiling this patch on Windows, so this is just what I expect should be the case.)

In zend_simd.h, we define XSSE2, which detects SSE2 support on all common compilers. XSSE2 is also defined when compiling for ARM64/NEON, in which case all the SSE2 intrinsics are shims which compile to the corresponding NEON instructions.

Your ARM64/NEON branch may be slightly more efficient than the code we would get from your SSE2 branch using the shims. So if you want to retain that small bit of efficiency, you could put the ARM64/NEON branch first, so it takes priority over the XSSE2 branch. Or, if performance is too close either way to even care about the difference, you could delete your ARM64/NEON branch and just rely on XSSE2.

Any other thoughts?

@lemire

lemire commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review.

I think it is a nice little change worth doing.

Now, about the use of __SSE2__, I believe this is not defined by MSVC. So if PHP is compiled with MSVC, I believe that the scalar branch of convert_case_ascii_prefix will be used. (I don't normally work on a Windows box and haven't tried compiling this patch on Windows, so this is just what I expect should be the case.)

Is this true? On Windows, PHP's build system seems to define __SSE2__ itself: toolset_setup_intrinsic_cflags() in win32/build/confutils.js enables SSE2 by default and, for MSVC, adds __SSE__/__SSE2__ to config.w32.h, which every file includes through php.h.

  1. SSE2 is the default: default_enabled = "sse2", and "sse2" maps to "SSE2":
    function toolset_setup_intrinsic_cflags()
    {
    var default_enabled = "sse2";
    var avail = WScript.CreateObject("Scripting.Dictionary");
    avail.Add("sse", "__SSE__");
    avail.Add("sse2", "__SSE2__");
  2. That default is used when --enable-native-intrinsics isn't given:
    // if --enable-native-intrisics is not specified, it's "no" - enable default
    if ("no" == PHP_NATIVE_INTRINSICS || "yes" == PHP_NATIVE_INTRINSICS) {
    PHP_NATIVE_INTRINSICS = default_enabled;
    }
  3. With MSVC, the macros are defined explicitly ("The declared macros won't affect code generation, but will enable the guarded code parts"), via AC_DEFINE(avail.Item(it), 1):
    if (VS_TOOLSET) {
    /* MSVC has no explicit way to enable intrinsics between SSE3 and SSE4.2.
    The declared macros won't affect code generation, but will enable
    the guarded code parts. */
    for (var i = 0; i <= j; i++) {
    var it = scale[i];
    AC_DEFINE(avail.Item(it), 1);
    }
  4. The documented option says so too ("SSE and SSE2 are enabled by default"), and config.w32 calls the function:
    ARG_ENABLE("native-intrinsics", "Comma separated list of intrinsic optimizations to enable. \
    Available instruction set names are sse, sse2, sse3, ssse3, sse4.1, sse4.2, avx, avx2, avx512. \
    SSE and SSE2 are enabled by default. The best instruction set specified will \
    automatically enable all the older instruction sets. Note, that the produced binary \
    might not work properly, if the chosen instruction sets are not available on the target \
    processor.", "no");
    toolset_setup_intrinsic_cflags();
  5. The defines reach C code: AC_DEFINE values are written to main/config.w32.h, which Zend/zend_config.w32.h includes:
    STDOUT.WriteLine("Generating main/config.w32.h");
    infile = FSO.OpenTextFile("win32/build/config.w32.h.in", 1);
    indata = infile.ReadAll();
    infile.Close();
    outfile = FSO.CreateTextFile("main/config.w32.h", true);

    #include <../main/config.w32.h>

In zend_simd.h, we define XSSE2, which detects SSE2 support on all common compilers. XSSE2 is also defined when compiling for ARM64/NEON, in which case all the SSE2 intrinsics are shims which compile to the corresponding NEON instructions.

I tried it. On my macBook, it is measurably slower.

@alexdowad

Copy link
Copy Markdown
Contributor

@lemire Thanks very much for correcting my misconception. In that case, no objection to merging the patch as written.
@youkidearitai If you have any comments, please feel free to add. If you don't wish to comment, that's also fine; if some time passes and it seems no other comments are forthcoming, then I'll go ahead and merge.

@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 comment. LGTM

@alexdowad

Copy link
Copy Markdown
Contributor

Merged into master. @lemire, we really appreciate this valuable contribution.

Personally, I'm a fan of your work and hope to see more interesting research from you and your colleagues in the future.

@alexdowad alexdowad closed this Nov 27, 2026
@lemire

lemire commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

@alexdowad Thanks for the good words.

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.

3 participants