← Back to Pull requests

fix, enh: add ability to swap std::sort with other routines, lock ISA #247

Closed
unknown closed this pull request without merging on Nov 17, 2026 07:29 UTC
View on GitHub
unknown unknown commented on Nov 16, 2026 23:48 UTC
Author

Keep the std::sort fallback's instantiations local to each ISA build

Summary

qsort_ and qselect_ fall back to std::sort(..., comparator::STDSortComparator) when quicksort stops making
progress. The comparator is passed as a function pointer, bool ()(const T &, const T &), whose type is the same in
every build of the header. So when a project compiles the header for several ISAs and links them into one binary,
which is what lib/ and NumPy do, each ISA's object file defines the same weak std:: symbols
(std::__introsort_loop<float
, ..., bool ()(const float &, const float &)> and the rest). The linker keeps one
copy for all callers, so the AVX-512 code path can run the AVX2 build of these functions, or the AVX2 path the
AVX-512 build, depending on link order. Nothing currently crashes, because the copies built for AVX-512 contain no
AVX-512 instructions, but nothing guarantees that.

This change passes the comparator through a lambda. Its type is local to qsort_<zmm_vector<float>, ...> (or
<avx2_vector<float>, ...>), so each ISA's std::sort instantiation gets its own name and local linkage, and there
is nothing for the linker to merge. As a side effect, the comparator is now inlined in the fallback, which makes it
17-32% faster for n >= 10k.

It also routes the four std::sort calls (the two fallbacks and the two in std_argsort /
std_argsort_withnan) through an XSS_STD_SORT macro that defaults to std::sort, so a project can substitute its
own sort, e.g. one templated on the ISA, as oneDAL's introSort<cpu> is.

What goes wrong

A template instantiated with the same arguments in several object files is emitted in each as a weak (COMDAT)
symbol. Under the one-definition rule the copies are interchangeable, so the linker keeps one (the first in link
order for GNU ld and gold) and drops the rest. Object files don't record which -m flags a function was compiled
with, so it has no way to tell them apart.

When this header is built once per ISA, x86simdsort-avx2.cpp and x86simdsort-skx.cpp in lib/ for example,
everything in it has internal linkage (X86_SIMD_SORT_INLINE and _FINLINE are static) or is templated on an
ISA-specific vector type, except the standard library templates it instantiates with ISA-independent arguments.
The fallback's std::sort with a function-pointer comparator is one of them.

Runtime dispatch only selects the entry point (avx512_qsort or avx2_qsort, NumPy's QSort_X86_V4 or
QSort_X86_V3). Below it, the call to the shared std:: symbol goes to whichever copy the linker kept:

QSort_X86_V4<float> (unique name)            QSort_X86_V3<float> (unique name)
 └ qsort_<zmm_vector<float>, ...> (static)    └ qsort_<avx2_vector<float>, ...> (static)
    └ std::__heap_select<float *, bool (*)(const float &, const float &)>   <- one copy, used by both

If the kept copy is the AVX-512 build and the compiler used AVX-512 instructions in it, an AVX2-only CPU gets SIGILL
the first time an input reaches the fallback.

Observed

GCC 13.3, release builds, symbols compared with check_isa_weak_symbols.sh. "Different" means the two copies
disassemble to different instructions.

| Build | Objects compared | Shared weak symbols | Different | Kept by the linker |
|---|---|---|---|---|
| lib/, main (7521047) | x86simdsort-avx2.cpp.o, -skx, -icl, -spr | 21 (avx2 vs skx) | 8 | the AVX2 copy, all 8 |
| lib/, v7.0 | same | 21 (avx2 vs skx) | 8 | the AVX2 copy, all 8 |
| NumPy main (31a42ae, x86-simd-sort fa944ef) | qsort X86_V3, X86_V4 | 12 | 2 | the X86_V3 copy |
| NumPy | 16-bit qsort AVX512_ICL, AVX512_SPR | 8 | 0 | |
| NumPy | argsort X86_V3, X86_V4 | 0 | | |

The shared symbols are std::__introsort_loop, __insertion_sort, __adjust_heap and __heap_select for every key
type, plus, in NumPy's 16-bit pair, Comparator<zmm_vector<int16_t / uint16_t>, ...>::STDSortComparator itself: taking
its address forces an out-of-line copy, and both 16-bit targets use zmm_vector. The copies that differ were
compiled from the same source with different instruction scheduling, so they are distinct code under one name. In
NumPy's _multiarray_umath.so the single remaining std::__heap_select<float
, ...> is called from both
qsort_<zmm_vector<float>, ...> and qsort_<avx2_vector<float>, ...>, and it is exported in the dynamic symbol table.

None of the copies contain AVX-512 instructions with this compiler, so no crash was observed.

Which copy is kept follows link order. With the two builds of the fallback as separate objects:

| Linker | Order | Copy in the binary |
|---|---|---|
| GNU ld 2.42 | AVX2 object first | AVX2 |
| GNU ld 2.42 | AVX-512 object first | AVX-512 |
| gold 1.16 | AVX2 object first | AVX2 |
| gold 1.16 | AVX-512 object first | AVX-512 |

NumPy gets the AVX2 copy because its build happens to put the X86_V3 object before X86_V4 in
lib_multiarray_umath_mtargets.a (members 21 and 36), even though meson.build lists X86_V4 first.

The changesrc/xss-common-qsort.h: qsort_ and qselect_ pass


[](const type_t &a, const type_t &b) { return comparator::STDSortComparator(a, b); } instead of
comparator::STDSortComparator. A lambda in a function template has a unique closure type that belongs to that
instantiation, and it has no linkage because qsort_ is static (qselect_ is X86_SIMD_SORT_INLINE, also
static). So the std::sort internals become, for example,
std::__introsort_loop<..., qsort_<zmm_vector<float>, ...>::{lambda(float const &, float const &)#1}>, a local
symbol in each object.

src/xss-common-includes.h: XSS_STD_SORT, defaulting to std::sort, used by those two calls and by std_argsort
and std_argsort_withnan (whose comparators were already lambdas). A project can define it before including the
headers to a sort taking (first, last, comp). oneDAL, for instance, could define it to
daal::algorithms::internal::introSort<DAAL_CPU>, which carries the ISA in its name at every optimization level.

+32/-9 over three files. No API or behavior change when XSS_STD_SORT is not defined.

After the change:

| Build | Shared weak symbols |
|---|---|
| lib/, main | 3, all ISA-independent: DW.ref.__gxx_personality_v0 (exception-handling data) and std::vector<size_t>::~vector() (D1/D2) from lib/'s argsort wrappers, which only null-checks and calls operator delete |
| NumPy qsort X86_V3 / X86_V4 | 0 |
| NumPy 16-bit AVX512_ICL / AVX512_SPR | 0 |
| NumPy argsort | 0 |

Performance

bench_std_sort_fallback.cpp times qsort_ with max_iters = 0, i.e. the fallback itself, on random keys, built
against main before and after the change. One core of a Xeon Platinum 8480+, -O3, best of 15-300 runs.
after/before, below 1 is faster:

| Compiler | -march | n >= 10k | n <= 1000 |
|---|---|---|---|
| GCC 13.3 | haswell | 0.68-0.76 | 0.20-0.42 |
| GCC 13.3 | skylake-avx512 | 0.68-0.76 | 0.22-0.39 |
| Clang 18.1 | haswell | 0.75-0.83 | 0.34-0.55 |
| Clang 18.1 | skylake-avx512 | 0.74-0.82 | 0.29-0.56 |

With the function pointer, neither compiler inlines the comparator into the std::sort internals: in this
benchmark's v7.0 build (-march=haswell), GCC has 7 indirect calls (call %reg) in __introsort_loop<float , ...>
and 2 each in __insertion_sort and __adjust_heap, and Clang 52 across the std:: internals. With the lambda there
are none. The fallback only runs when quicksort makes no progress, so this does
not affect typical sorts. Code size of a translation unit instantiating qsort, argsort and keyvalue_qsort for several
types changes by -0.1% to +1.0% of .text, and a linked binary keeps one copy of the fallback per ISA instead of
one in total.

<details><summary>All results (ns per sort)</summary>

See bench_results.md.
</details>

Not fixed here

  • At -O0 the standard library helpers that don't take the comparator (std::iter_swap<float , float >,

  • std::move_backward, std::reverse, std::min<float>, ...) are not inlined and are still shared between ISA builds:
    76 weak symbols in a test translation unit. With optimization they are inlined. Projects that need ISA isolation in
    unoptimized builds can define XSS_STD_SORT, but std::reverse and std::swap elsewhere in the headers would
    remain.
  • The std::vector<size_t> destructor shared by lib/'s per-ISA argsort wrappers (ISA-independent code).

  • A CI check. check_isa_weak_symbols.sh could run on lib/'s objects after the meson build; it needs nm,

  • objdump and c++filt. Left out of this change to keep it to the headers.

    Context

    Found while integrating x86-simd-sort into oneDAL, which compiles x86simdsort-static-incl.h once per ISA
    (-march=haswell and -march=skylake-avx512 translation units) and links them into one library. oneDAL only calls
    keyvalue_qsort, whose fallback is heap_sort, so it is not affected today; it would be through qsort, qselect
    or argsort. Its own kernels avoid the problem by templating every helper on the CPU type, which is what
    XSS_STD_SORT lets it do for this sort.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: r-devulap Review duration: 461m
    All Vouch review confidence checks passed
    Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    56%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #247"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 56.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 56.8% · Lower = rushed or shallow review
    56.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 22.5% · Safe to merge
    22.5%