Repository navigation
Use LLVM-libc memory functions instead of glibc ones - #107566
Conversation
Build `memcmp`, `memcpy`, `memmove`, `memset`, `bcmp` and `memmem` from LLVM-libc into the existing `libllvmlibc` target (which already supplies the math functions), replacing the previous hand-rolled `memcmp`. The wrapper TU `contrib/libllvmlibc-cmake/string/mem_functions.cpp` includes the LLVM-libc implementation files and marks each exported C symbol `weak` via the `LLVM_LIBC_FUNCTION_ATTR_<name>` hook, so sanitizer interceptors can override them and so the existing strong `memcpy` from `base/glibc-compatibility/memcpy` keeps precedence. `memmem` is a strong symbol. On x86_64, `x86_64_mem_functions.cpp` provides `memcpy`/`memmove`/`memset` with runtime AVX-512 dispatch (a lazily-resolved function pointer, the same shape as a glibc IFUNC) plus an AVX-512/AVX2/scalar `memmem`. On aarch64, `aarch64_mem_functions.cpp` adds a NEON `memmove` and `memmem`. The library is built with `-ffreestanding -fno-builtin` so clang's loop-idiom recognition does not rewrite the inner loops into calls to the very functions being defined. SIMD tiers are selected from `X86_ARCH_LEVEL` (SSE2 / v3 / v4 with `-mprefer-vector-width=512`). Ported from the `use-musl` branch (PR #97452). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [210594c] Summary: ❌
AI ReviewSummaryThis PR removes the old amd64 Findings
Tests
Final VerdictStatus: Minimum required actions: scope the new compile options to the memory-function objects (or prove the broader libm codegen change is intentional and safe), add focused correctness coverage for the interposed |
|
📊 Cloud Performance Report 🔴 AI verdict: This PR replaces the custom memcpy with llvm-libc SIMD memory functions (memcpy/memmove/memset/memcmp/memmem) behind a runtime AVX-512 dispatch, so it touches a hot path every query runs. Five queries regress consistently (ClickBench Q30 +17%, Q31 +14%; TPC-H Q4 +206%, Q7 71->711ms, Q8 +33%) and one improves (TPC-H Q16 -49%, likely faster SIMD search/compare) — all confirmed by both tests and all on the rewritten copy path, so these are real, not noise. The large TPC-H regressions (Q4/Q7/Q8) are the priority: the new large-copy dispatch appears materially slower than the old inline path on data-movement-heavy joins. Worth checking whether the benchmark hardware exposes AVX-512, since without it the new baseline path, not the tuned ZMM path, is what ran. clickbench🔴 2 regressed Flagged queries (2 of 43)
q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🔴 3 regressed · 🟢 1 improved Flagged queries (4 of 22)
q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. Debug info
|
Two follow-up fixes to the LLVM-libc memory functions port, plus comment pruning and simplification. memcpy precedence: marking `memcpy` `weak` does not by itself guarantee that the strong `base/glibc-compatibility/memcpy` keeps precedence. lld resolves a `memcpy` reference from whichever static archive it reaches first, weak or strong, and CMake places `libllvmlibc` ahead of `libmemcpy` on the link line, so the weak `memcpy` was winning. Splitting `memmem` out is not sufficient on its own because `memcpy` is referenced directly. The strong `memcpy` is now forced into every executable with `--whole-archive` (in `CMAKE_EXE_LINKER_FLAGS`, the same mechanism as `compiler_rt_link.cmake`), so it is unconditionally present and wins regardless of archive order. `memmem` is also moved to its own translation unit so that a reference to the strong, always-pulled `memmem` no longer drags the weak `memcpy` into the link. memmem worst case: the SIMD two-byte filter verifies each candidate with `memcmp`, which is O(needle) per candidate and degenerates to O(haystack*needle) on low-selectivity needles such as "aa..aba" over an all-`a` haystack. Needles of `TWO_WAY_THRESHOLD` (32) bytes or longer are now routed to a Two-Way (Crochemore-Perrin) matcher ported from musl, which is linear with no degenerate case. Below the threshold the per-candidate verification is bounded by a small constant, so the filter stays linear in the haystack. Verified by a controlled lld link experiment (strong `memcpy` wins in the exact real-world archive order with `--whole-archive`, no duplicate symbols) and by fuzzing `memmem` against a brute-force reference over 289k cases, including the degenerate low-selectivity needles and all size edge cases. The shared x86_64 runtime CPU detection now lives in `x86_cpu_dispatch.h`, included by both `x86_64_mem_functions.cpp` and `memmem.cpp`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The previous commit started forcing the strong glibc-compatibility `memcpy` into every executable with `-Wl,--whole-archive` so it wins over libllvmlibc's weak `memcpy`. Under sanitizers this collides with `compiler_rt_link.cmake`, which already force-links the sanitizer runtime's own `memcpy` interceptor with `--whole-archive`. With two `--whole-archive` definitions the custom `memcpy` defeats the interceptor, so the sanitizer's shadow-memory handling is bypassed and writes land in the shadow-gap region — a `Segmentation fault` at server start and in unit tests across all MSan jobs (the previous commit, which did not force-link `memcpy`, let the interceptor win and had no such failures). Gate the force-link on `NOT SANITIZE`. The binary's performance does not matter under sanitizers, where the interceptor must take precedence; release builds are unaffected and keep the custom `memcpy`. CI: #107566 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
| # Memory functions: mem_functions.cpp provides the weak memcmp/memcpy/memmove/ | ||
| # memset/bcmp; the strong memmem lives in memmem.cpp (added below). | ||
| set(SRCS | ||
| "${CMAKE_CURRENT_SOURCE_DIR}/string/mem_functions.cpp" |
There was a problem hiding this comment.
This target now globally interposes memcmp/memcpy/memmove/memset/bcmp and, outside sanitizers, memmem, but the PR does not add focused correctness coverage for the linked replacement symbols. Broad query tests can miss exactly the edge cases that are risky here: overlap direction and alignment around the 64/128/512-byte cutoffs, zero-length handling, and memmem short-needle SIMD vs. long-needle Two-Way paths on low-selectivity data.
Please add a small unit or fuzz-style test that calls the linked symbols and compares them with simple reference implementations across sizes, alignments, overlaps, and adversarial needles, so future changes cannot silently corrupt memory or string-search results.
Algunenano
left a comment
There was a problem hiding this comment.
A couple of questions:
- I don't see any perf changes, which is both positive (we are comparing ourselves to the runtime glibc available in the machines) and negative (don't see any improvements either). I guess that it matters most in the musl builds. Not sure if you have metrics somewhere (not critical).
- Should we consider dropping the memcpy glibc compat library in favor of this? And if not (because it's faster) then shouldn't we just discard this memcpy and use that one instead (always, move the code here)
|
Thanks for review, @Algunenano!
Correct. Changes in this branch were split from #97452, here is a relevant CI run.
That'd be nice, let me look into it. |
|
@thevar1able, there are many regressions on TPC-H. Worth checking. |
|
@alexey-milovidov please check edit history of this Cloud Performance Report. |
| @@ -15,6 +19,10 @@ if (ENABLE_LLVM_LIBC_MATH) | |||
| link_directories("${CMAKE_BINARY_DIR}/contrib/libllvmlibc-cmake") | |||
| target_link_libraries(global-libs INTERFACE libllvmlibc) | |||
There was a problem hiding this comment.
Because target_link_libraries(global-libs INTERFACE libllvmlibc) here, together with the forced -u symbols below, makes these replacements active in every non-sanitized Linux executable, this is no longer just a musl-only optimization path. The PR's own Cloud Performance Report on that default wiring is currently negative (clickbench Q30/Q31 +17%/+14%, TPC-H Q4 +206%, Q7 71->711 ms, Q8 +33%), so we would be replacing a universal hot path with a measured regression. Please either scope the interposition to the configurations where it is actually faster, or rerun with threshold/implementation changes that remove those regressions before wiring libllvmlibc into global-libs.
There was a problem hiding this comment.
Benchmark complete. Here's the picture across all four arch levels, and it fully vindicates your disbelief.
View A — CPU-bound (L2-resident): where memcpy differences are real
Single thread (GB/s):
┌───────────┬────────────┬─────────┬──────┬──────┬──────┬────────────────┬───────┐
│ chunk avg │ sse2 (old) │ llvm v1 │ v2 │ v3 │ v4 │ llvm no-AVX512 │ glibc │
├───────────┼────────────┼─────────┼──────┼──────┼──────┼────────────────┼───────┤
│ ~8 B │ 1.2 │ 1.2 │ 1.2 │ 1.2 │ 1.2 │ 1.2 │ 1.1 │
├───────────┼────────────┼─────────┼──────┼──────┼──────┼────────────────┼───────┤
│ ~32 B │ 3.6 │ 4.8 │ 4.8 │ 4.8 │ 4.9 │ 4.9 │ 3.8 │
├───────────┼────────────┼─────────┼──────┼──────┼──────┼────────────────┼───────┤
│ ~128 B │ 9.9 │ 16.3 │ 16.3 │ 16.3 │ 16.7 │ 16.7 │ 17.2 │
├───────────┼────────────┼─────────┼──────┼──────┼──────┼────────────────┼───────┤
│ ~2 KB │ 85.8 │ 95 │ 97 │ 105 │ 102 │ 98 │ 86.5 │
├───────────┼────────────┼─────────┼──────┼──────┼──────┼────────────────┼───────┤
│ ~32 KB │ 137 │ 135 │ 136 │ 141 │ 139 │ 137 │ 134 │
└───────────┴────────────┴─────────┴──────┴──────┴──────┴────────────────┴───────┘
At 32 threads (still cache-resident) the mid-size wins widen: <=256 → llvm ~350 vs sse2 232 (+50%).
LLVM-libc is faster than the old SSE2 at every level — up to +65% in the 32 B–2 KB range, tied elsewhere, never slower. v1/v2/v3/v4 are near-identical (large copies always dispatch to the AVX-512 clone; only the small tiers vary), and the no-AVX-512 baseline path tracks the AVX2 build — so even on cloud hardware without AVX-512, no regression. This directly refutes the report's hint.
View B — DRAM-resident: the bandwidth regime (production)
┌─────────────────────────┬──────┬─────────────┬───────────┬───────┐
│ │ sse2 │ llvm v1..v4 │ no-AVX512 │ glibc │
├─────────────────────────┼──────┼─────────────┼───────────┼───────┤
│ 8 threads (256 MB > L3) │ ~20 │ ~20–23 │ ~20 │ ~21 │
├─────────────────────────┼──────┼─────────────┼───────────┼───────┤
│ 32 threads (1 GB) │ 17.7 │ 17.7 │ 17.7 │ 17.7 │
└─────────────────────────┴──────┴─────────────┴───────────┴───────┘
At all-cores, every implementation, every size, every arch level pins to 17.7 GB/s — the DRAM ceiling. This is exactly Milovidov's thesis: once you saturate memory bandwidth, the memcpy implementation is irrelevant.
Verdict: the cloud regression is a false positive
TPC-H Q4/Q7/Q8 are multi-threaded, data-movement-heavy joins/aggregations — i.e. bandwidth-bound, the exact regime where the table above shows sse2, llvm-libc, and glibc are byte-for-byte identical (17.7 GB/s). A memcpy swap physically cannot change a bandwidth-bound query's runtime, let alone make Q7 go 71→711 ms (10×). Three independent lines of evidence now agree:
1. This bench: at production thread counts, all variants converge; where they diverge (CPU-bound small/mid copies) llvm-libc wins.
2. Flamegraphs (earlier): memcpy/memset were <1% of CPU in the flagged queries.
3. The presentation's own lesson: microbench/benchmark deltas don't transfer to production precisely because of this saturation — and the report is a benchmark harness, not a profile.
Honest caveats: the single-thread DRAM cells (View B1) are noisy — llvm_v3 read 25 GB/s there while v1/v2/v4 read 47–65 with the identical AVX-512 path, so that low value is measurement noise (few passes, best-of-2), not a real effect. It doesn't touch the conclusion. And this is Zen 5; on Graviton (where ClickHouse Cloud actually runs) the x86 paths don't even apply — aarch64 uses musl's memcpy, untouched by the dropped-glibc-memcpy commit.
|
|
||
| # Without -fno-builtin, clang's loop-idiom pass rewrites the mem* inner loops | ||
| # into calls to the very functions being defined (infinite recursion). | ||
| target_compile_options(libllvmlibc PRIVATE -ffreestanding -fno-builtin) |
There was a problem hiding this comment.
libllvmlibc is still the existing math library here, not a memory-only target: the SRCS list above still compiles acos, exp, log, pow, and the rest of the preexisting libm objects. Making the whole target -ffreestanding -fno-builtin here (and -mprefer-vector-width=512 in the x86-64-v4 branch below) therefore changes codegen for all of those math routines too, even though the PR contract is only "swap in mem* implementations".
That broadens the performance surface to every libllvmlibc math call without any focused evidence that those paths stayed neutral. Please either split the new mem* files into a separate target or scope these options to the memory-function sources only.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 1/1 (100.00%) · Uncovered code |
- Revert CI job changes that switched release/fast-test builds to musl and rewrote the compatibility check: that is later "musl as main build" work. - Revert LLVM-libc mem functions (split to PR #107566); keep musl's own mem*/bcmp, restoring the x86_64 asm memcpy/memmove/memset. - Remove the llvm-tblgen -march pin and protoc DEPENDS additions that are not needed for this change. - Restyle contrib/musl-cmake and cmake/musl.cmake closer to the usual contrib cmake style: drop the unused musl-Scrt1 target, banner comments and redundant arch detection; MUSL_ARCH now comes from the toolchain files. Co-Authored-By: Claude Fable 5 <[email protected]>
The x86_64 mem* dispatchers in contrib/libllvmlibc-cmake rely on `flatten`
to inline the whole LLVM-libc helper tree into the `target("arch=x86-64-v4")`
clones. At -O0 (Debug build with -DDEBUG_O_LEVEL=0) clang lowers `flatten`
as a single level of inlining, so the v4-attributed `memmove_overlap_avx512`
calls out-of-line baseline-target (x86-64-v3) helpers that pass 64-byte
vectors by value. That is an ABI mismatch - the v4 caller reads the return
value from zmm0 while the v3 callee returns it in ymm0:ymm1 - which silently
corrupts every overlapping `memmove` of more than 128 bytes on AVX-512
machines. Clang rejects this pattern with a hard error when the mismatched
call is visible in the source, but the inliner recreates it silently.
The corruption made llvm-tblgen crash (SIGSEGV in -gen-x86-fold-tables,
SmallVector `idx < size()` assertion in -gen-asm-matcher) during -O0 builds
on AVX-512 hardware. CI debug builds did not catch it: they run with the
default -Og, and CI machines have no AVX-512.
Fix it in the source so the code is correct at any optimization level:
upgrade LIBC_INLINE to `always_inline` for this TU (honored even at -O0),
and redeclare the generic `load`/`store`/`splat` - which lack LIBC_INLINE
upstream yet are exactly the functions passing vectors by value - with
`always_inline` as well. The helper tree then always collapses into the
exported functions and no cross-target call boundary survives.
Caused by: ClickHouse#107566
Co-Authored-By: Claude Fable 5 <[email protected]>
`test_implicit_index_upgrade_alter_replay` creates a second replica `node2` and asserts `SELECT count() FROM test_alter_replay` equals `10001` immediately after `wait_for_active_replica`. But `wait_for_active_replica` only waits for `is_readonly = 0`, not for the freshly-joined replica to finish fetching parts. So `node2` can observe only the small `VALUES` part (1 row, `key = 99999`) before the 10000-row part is fetched, and the assertion fails with `assert '1' == '10001'`. This raced once each on several unrelated PRs over the last 30 days (e.g. ClickHouse#108084, ClickHouse#99280, ClickHouse#107566, ClickHouse#107442). Add `SYSTEM SYNC REPLICA test_alter_replay` after the replica becomes active, which blocks until all parts are fetched, before checking the row count. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108770&sha=bb760616d54e3d8e5d20968022085506c31b5f37&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%20distributed%20plan%2C%201%2F4%29 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The previous commit started forcing the strong glibc-compatibility `memcpy` into every executable with `-Wl,--whole-archive` so it wins over libllvmlibc's weak `memcpy`. Under sanitizers this collides with `compiler_rt_link.cmake`, which already force-links the sanitizer runtime's own `memcpy` interceptor with `--whole-archive`. With two `--whole-archive` definitions the custom `memcpy` defeats the interceptor, so the sanitizer's shadow-memory handling is bypassed and writes land in the shadow-gap region — a `Segmentation fault` at server start and in unit tests across all MSan jobs (the previous commit, which did not force-link `memcpy`, let the interceptor win and had no such failures). Gate the force-link on `NOT SANITIZE`. The binary's performance does not matter under sanitizers, where the interceptor must take precedence; release builds are unaffected and keep the custom `memcpy`. CI: ClickHouse#107566 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ctions Use LLVM-libc memory functions instead of glibc ones
- Revert CI job changes that switched release/fast-test builds to musl and rewrote the compatibility check: that is later "musl as main build" work. - Revert LLVM-libc mem functions (split to PR ClickHouse#107566); keep musl's own mem*/bcmp, restoring the x86_64 asm memcpy/memmove/memset. - Remove the llvm-tblgen -march pin and protoc DEPENDS additions that are not needed for this change. - Restyle contrib/musl-cmake and cmake/musl.cmake closer to the usual contrib cmake style: drop the unused musl-Scrt1 target, banner comments and redundant arch detection; MUSL_ARCH now comes from the toolchain files. Co-Authored-By: Claude Fable 5 <[email protected]>
The x86_64 mem* dispatchers in contrib/libllvmlibc-cmake rely on `flatten`
to inline the whole LLVM-libc helper tree into the `target("arch=x86-64-v4")`
clones. At -O0 (Debug build with -DDEBUG_O_LEVEL=0) clang lowers `flatten`
as a single level of inlining, so the v4-attributed `memmove_overlap_avx512`
calls out-of-line baseline-target (x86-64-v3) helpers that pass 64-byte
vectors by value. That is an ABI mismatch - the v4 caller reads the return
value from zmm0 while the v3 callee returns it in ymm0:ymm1 - which silently
corrupts every overlapping `memmove` of more than 128 bytes on AVX-512
machines. Clang rejects this pattern with a hard error when the mismatched
call is visible in the source, but the inliner recreates it silently.
The corruption made llvm-tblgen crash (SIGSEGV in -gen-x86-fold-tables,
SmallVector `idx < size()` assertion in -gen-asm-matcher) during -O0 builds
on AVX-512 hardware. CI debug builds did not catch it: they run with the
default -Og, and CI machines have no AVX-512.
Fix it in the source so the code is correct at any optimization level:
upgrade LIBC_INLINE to `always_inline` for this TU (honored even at -O0),
and redeclare the generic `load`/`store`/`splat` - which lack LIBC_INLINE
upstream yet are exactly the functions passing vectors by value - with
`always_inline` as well. The helper tree then always collapses into the
exported functions and no cross-target call boundary survives.
Caused by: ClickHouse#107566
Co-Authored-By: Claude Fable 5 <[email protected]>
Builds
memcmp,memcpy,memmove,memset,bcmpandmemmemfrom LLVM-libc into the existinglibllvmlibctarget (which already supplies the math functions), replacing the slow libc byte-loop versions with SIMD ones competitive with glibc's IFUNC-dispatched implementations. Relevant formusl; overrides glibc's via weak symbols.The exported symbols are marked
weak(via theLLVM_LIBC_FUNCTION_ATTR_<name>hook) so the existing strongmemcpykeeps precedence and sanitizer interceptors can still override them.memmemis strong, so it is not linked under sanitizers to keep the interceptor in place. On x86_64,memcpy/memmove/memset/memmemuse runtime AVX-512/AVX2 dispatch (a lazily-resolved pointer, glibc-IFUNC shape); on aarch64, a NEONmemmoveandmemmem(memcpy/memsetcome from musl's Arm Optimized Routines). SIMD tiers are picked fromX86_ARCH_LEVEL.Split out of #97452 (
Build musl from sources), where these functions live; this PR ports them to master independently.Related: #97452
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Use SIMD
memcmp/memcpy/memmove/memset/bcmp/memmemimplementations from LLVM-libc.