Repository navigation
Conversation
Reported in ClickHouse#116070 by egor-click, with the analysis, the ARM measurements and the patch adopted here. Both functions are FunctionUnaryArithmetic instantiations. That template has a single hot element loop, wrapped in MULTITARGET_FUNCTION_X86_V4, and vector() dispatches the wide clone under USE_MULTITARGET_CODE, which src/Common/TargetSpecific.h:110 defines only when __x86_64__ is defined. On aarch64 the dispatch block is preprocessed away and the only body that runs is the one compiled at the baseline from cmake/cpu_features.cmake:52 (-march=armv8.2-a+simd+..., 128-bit, no SVE). What that body must vectorise is a chain of data-dependent ternary selects, 15 levels deep in RoundDurationImpl and 6 in RoundAgeImpl, and clang's cost model rejects it. Neither impl is JIT-compilable, so nothing rescues them at runtime either. Both apply() bodies are rewritten as flat delta accumulation: each threshold contributes the difference between its bucket and the previous one, so the running sum telescopes to exactly what the cascade returned. The predicate is !(x < c) and not x >= c because for NaN every comparison is false, so all deltas accumulate and the result matches the cascade falling through every else branch; reversing it silently returns 0 for NaN instead of 36000 and 55. Measured by cross-compiling the two bodies for the shipped aarch64 baseline, with a positive and a negative control in every run. On the pinned clang-22 and on clang-21 the verdicts are identical: all 7 input types of the cascade report "the cost-model indicates that vectorization is not beneficial", and after the rewrite 6 of them vectorise (roundDuration at width 8, roundAge at width 16). roundDuration on Float64 vectorises in neither form. On the x86-64-v4 clone the vector width is unchanged for every roundDuration type while roundAge drops interleave 2 to 1 at the same width; on the x86-64-v3 default the rewrite strictly adds vectorisation. No aarch64 host was available, so the ARM wall-clock numbers in the issue are the reporter's and the aarch64 Performance Comparison job is the arbiter. Results are bit-identical. An equivalence harness generated from the two source bodies reports no difference over 3,049,894 cases: exhaustive over every Int8, UInt8, Int16 and UInt16 value, every value in [-100000, 100000] for the 32 and 64-bit types, Int128 and UInt128 including their min and max tails, dense Float32 and Float64 sweeps, every bucket threshold with both nextafter neighbours, and the float specials. Two mutation arms confirm the harness can fail: corrupting one delta reddens on over a million cases, and reversing all 21 predicates reddens on exactly NaN and -NaN. The UInt32 accumulator is exact, the deltas summing to 36000 and 55, and the declared ResultType of each function is unchanged. The roundAge behaviour of returning 17 for inputs 1 to 17 (ClickHouse#48640) is preserved: the first delta is 17. 00968_roundAge and 00969_roundDuration covered only exact positive integer boundaries, so nothing pinned the NaN behaviour; with the predicate reversed both of the previous test files still passed. They are extended in place with NaN, both infinities, negatives, type minimums, fractional floats, Float32, the UInt64 and Int128 extremes, Nullable and LowCardinality. Their reference files were generated from the pre-change binary, so the existing expectations are unchanged and the new lines fail on exactly the NaN row when the predicate is reversed. Closes: ClickHouse#116070
The branchless rewrite exists so that clang's loop vectoriser accepts the element loop of FunctionUnaryArithmetic at 128 bits, which is what aarch64 compiles (USE_MULTITARGET_CODE is x86-only, so ARM only ever runs the single baseline body). That trade is only profitable when there is SIMD to win back the cost of evaluating every threshold instead of exiting at the first one. FunctionUnaryArithmetic::castType also admits UInt128/UInt256/Int128/Int256. Those are software-emulated multi-limb types with no vector form, so for them the flat body is pure added work: measured at -O3 with the project's own wide::integer, the previous commit made roundDuration on zero-valued UInt128 8.22x slower and roundAge 4.74x slower. Select the body with `if constexpr (is_big_int_v<A>)`, so big integers keep the cascade and native widths keep the flat form. Being a compile-time branch, the native instantiations are unchanged: probing one object file per (body, type) pair, the emitted code for every native width is byte-identical to the flat form and for every big-int width byte-identical to the cascade. Results are unaffected in either arm: 488,100 cases over Int128/UInt128/ Int256/UInt256 plus native controls agree with the pre-rewrite cascade exactly, and both existing tests pass unmodified.
The comment on the big-integer arm asserted that the comparison chain's early exits are cheaper than evaluating every threshold. That ordering depends on the data, not on the type: on cyclic UInt256 input the flat form measured 2.75x faster than the chain, while on zero-valued input the chain wins by 8.2x. The arm's real justification is data-independent, so state that instead: wide integers have no vector form, so the flat accumulation has no vectorisation gain available to offset its extra comparisons. Comment text only, verified token-identical and reproducing the previous Build-ID bit for bit. The retained cascade was exercised by exactly one value per test file, Int128 max, which falls through to the tail and so pinned only the tail constant. Changing the value returned for x < 1800 from 1200 to 999 left that line, and 0, 7 and 20000, unchanged. One mid-bucket value per file across Int128, UInt256 and Int256 closes that: with the same perturbation applied inside the big-integer arm only, both tests now fail on exactly the new line, while the previous versions of both files still pass. Co-Authored-By: Claude Fable 5 <[email protected]>
Internal second-model review (click to expand)Reviewed over three rounds by an independent reviewer and a second model, against the
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-review-slot-8:20260824-165000 |
|
Workflow [PR], commit [c59db13] Summary: ✅
AI ReviewSummaryThis PR rewrites Missing context / blind spots
Findings❌ Blockers
|
| Metric | Baseline | Current | Δ |
|---|---|---|---|
| Lines | 87.20% | 87.20% | +0.00% |
| Functions | 91.90% | 91.90% | +0.00% |
| Branches | 79.40% | 79.30% | -0.10% |
Changed lines: Changed C/C++ lines covered: 25/25 (100.00%) · Uncovered code
|
cc @antaljanosbenjamin @rschu1ze, could you review this? Both functions are FunctionUnaryArithmetic instantiations whose only hot loop is wrapped in MULTITARGET_FUNCTION_X86_V4, so on AArch64 a single 128-bit body has to vectorise a 15-level chain of data-dependent selects and clang's cost model refuses; rewriting the chain as branchless delta accumulation gets 6 of 7 input types vectorised, with the software-emulated big integers kept on the original cascade behind if constexpr. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction. Compile time of recompiled translation units8 translation units recompiled, 11 s compile time in total, 8 of them have a recent master baseline. |
|
📊 Cloud Performance Report ✅ AI verdict: This PR rewrites roundAge and roundDuration into branch-free form to enable auto-vectorization; those are the only two functions it touches. No ClickBench query calls either function, so the four flagged deltas on Q18/Q32/Q33/Q34 (+5.9% to +8.7%) cannot be caused by this change and were correctly held as not_sure within the baseline envelope. All four are aggregation-heavy queries drifting slightly upward together, which points to run-to-run variance rather than a real regression. No action needed on these results. clickbenchFlagged queries (4 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. 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🟢 No significant changes Debug info
|
| } | ||
| else | ||
| { | ||
| /// The predicate is `!(x < c)` rather than `x >= c` so that a NaN argument, for which every |
Requested in review: the functionality is already covered by the existing tests. Both files are restored to their pre-PR contents byte for byte. The rewrite this PR makes is confined to the native-width arm, and the pre-existing values already pin every line of it: perturbing any one of the 15 roundDuration deltas or any one of the 6 roundAge deltas changes the result for at least one value the existing files already query, so all 21 line mutants are caught without the added arms. The restored references also still match the rewritten body exactly, verified by compiling the shipped apply() bodies and replaying the existing queries through them, with a perturbed delta as a negative control. Two properties are no longer pinned in tree: the NaN fall-through, where the `!(x < c)` predicate makes every comparison false so all deltas accumulate, and the retained big-integer cascade, which no existing query reaches because every existing literal is UInt8 or UInt16. Both are unchanged from master, which returns the same values for those inputs, so this removes coverage rather than changing behaviour.
Both requested in review. The `if constexpr (is_big_int_v<A>)` arm is gone, so all widths now take the flat accumulation. It existed only to keep the comparison chain for the software-emulated types, which have no vector form to pay back the extra comparisons; that is a throughput trade on those four instantiations, not a correctness one. Results are unchanged for them: over the shipped bodies compared against the previous cascade, 300,016 cases on Int128/UInt128 and 82,002 on the project's own wide::integer<256> signed and unsigned agree exactly, with a deliberately wrong delta as a negative control, and both existing tests pass. With the arm removed the two bodies are the flat form of the first commit again, delta for delta, plus the requested comment.

Closes: #116070
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Improved the performance of the
roundDurationandroundAgefunctions on AArch64 by rewriting their comparison cascades into a branchless form that the compiler can auto-vectorise. Results are unchanged.Description
Reported by @ egor-click in #116070 with the analysis, the ARM measurements and the patch adopted here, asking me to verify it.
Both are
FunctionUnaryArithmeticinstantiations, whose hot element loop is wrapped inMULTITARGET_FUNCTION_X86_V4;USE_MULTITARGET_CODEis defined only for__x86_64__(src/Common/TargetSpecific.h:110), so AArch64 runs one 128-bit baseline body. It must vectorise a data-dependent select chain, 15 levels inroundDurationand 6 inroundAge, that clang's cost model rejects; neither impl is JIT-compilable.Both
apply()bodies become flat delta accumulation: each threshold adds the difference to the previous bucket, so the sum telescopes to what the cascade returned. Portable C++, so no dispatch tier orcpu_features.cmakeentry: the shape of #101571, disjoint from #97473. The predicate is!(x < c), notx >= c: for NaN every comparison is false, so all deltas accumulate, matching the cascade falling through everyelse. Reversed, NaN returns 0.The template also admits
Int128/UInt128/Int256/UInt256, which are software-emulated, so they gain no vectorisation and pay the extra comparisons: measured onwide::integer, 11.0x onUInt128zeros, 1.21x on cyclicUInt256, 1.00x on high values, a bounded ~9.4 ns per element at worst. I had kept the cascade for them behindif constexpr (is_big_int_v<A>)and removed it on review request; results are identical either way over 382k cases.Verified on the pinned clang-22 and on clang-21 for the shipped AArch64 baseline: 6 of 7 rows go from "cost-model indicates that vectorization is not beneficial" to vectorised,
roundDurationon Float64 in neither form. No x86 width regresses. Bit-identical over 3.5M cases. The timings are his, so Performance Comparison arbitrates.No test changes, per review:
00968_roundAgeand00969_roundDurationalready pin every line of the rewritten body, so all 21 delta mutants are caught and their references still match. The NaN fall-through stays unpinned, as it is on master.Workflow [PR]
Sync PR [sync-upstream/pr/116164]
Version info
26.9.1.149(included in26.9and later)