[X86][AArch64] backend didn't revert early exit for native popcnt
found form mimalloc
size_t mi_popcount(size_t x) {
if (x<=1) return x;
if (x==SIZE_MAX) return MI_SIZE_BITS;
#if (SIZE_MAX == ULONG_MAX)
return __builtin_popcountl(x);
#else
return __builtin_popcountll(x);
#endif
}
https://ddd.godbolt.org/z/5nWdfd7Pq
If the target has native popcnt, the early exit check here will only be slower, backend should be aware of this and eliminate unnecessary checks.
H @Andarwinux @hstk30-hw , I'm interested in working on this. plan is to add a rule in DAGCombiner to fold the SELECT node directly into a CTPOP node but only if architecture has a native popcount instruction
I don’t have permission to assign issues, so feel free to work on this.
Looks like this optimization could also be applied to vector popcnt, but the situation here is more specific:
- The target lacks native vector popcount and predicate.
- The target lacks native vector popcount but has predicate.
- The target has native vector popcount.
For case 3, it’s clearly profitable, but I’m not sure if this optimization should be applied to case 1/2.
https://ddd.godbolt.org/z/K34x71a9v
@Andarwinux
you;re right that we've to be careful with case 1 and case 2.
my plan is to implement fold in DAGCombiner using TLI.isCtpopFast(VT)
for case 3 : isCtpopFast will be true. We'll remove the redundant comparison/masking and let the h/w handle it in single instr.
for case 1 and 2 : if backend decides it must emulate the vector popcount, isCtpopFast will return false. The optimization won't happen and preserve the early exit check, which is more profitable in those cases.
this keeps the fold target-aware and ensures we only optimize when the h/w throughput makes the branch/masking overhead unnecessary
@Andarwinux @hstk30-hw
i have implemented suggested fold in DAGCombiner::visitSELECT and DAGCombiner::visitVSELECT.
basically the code looks for specific pattern like if x is 0 or 1, use x otherwise count the bits select (x <= 1), x, ctpop(x) and simplifies it to just count the bits ctpop(x).
it only does this if the computer's hardware is actually good at counting bits quickly.
this way it only removes if/else logic when it's sure the faster shortcut won't slow things down.
RESULTS:
-
Scalar case (x86_64 -mattr=+popcnt): successfully folds to a single
popcntq.# Output for i64 popcntq %rdi, %rax retq -
Vector case (-mattr=+avx512vpopcntdq,+avx512vl) : The logic correctly identifies the vector pattern. While it currently retains the compare/blend on X86 due to isCtpopFast returning false for vector types in the X86 backend, the implementation is target-agnostic. It is ready to trigger for any architecture (like AArch64 or future X86 updates) that overrides isCtpopFast for vectors.
-
Safety Check: Verified that on targets without native popcount (e.g., basic
x86_64), the optimization safely backs off, allowing the compiler to retain the existing branch/masking logic to avoid expensive emulated popcounts.
I’ve prepared a patch with a new test case in llvm/test/CodeGen/X86/popcnt-select-fold.ll.
Should I open the PR ?
Upon further reflection, I believe folding can be unconditionally applied to vector case, since even if elements with 0/1/max are skipped, it is still necessary to wait for trivial elements.
@RKSimon what do you think?
Why does this need to be done in DAG and not InstCombine?
I thought InstCombine was target-independent? For scalar cases, this optimization indeed depends on target.
@RKSimon @Andarwinux
What @Andarwinux said. The profitability of scalar fold is entirely target-dependent.
By placing this in DAGCombiner, we can use TLI.isCtpopFast(VT) to gracefully back off for scalars on unsupported hardware.
Vector fold can be unconditional (since SIMD lane waiting negates the branch benefit anyway), keeping both the scalar and vector logic together in the DAGCombiner keeps the implementation clean and unified.
TTI has getPopcntSupport and actual cost functions which can do this much better int the middle-end
@RKSimon
Thanks for the pointer.
I'll move this to the middle-end using TTI::getPopcntSupport. It is much cleaner.
Should this live in InstCombineSelect.cpp or is there more appropriate pass you'd recommend ?
Maybe a mixture of InstCombine / SimplfiyCFG?
@RKSimon Thanks for the direction.
The pattern can appear in two IR forms:
- Select form —
select (icmp ule X, 1), X, ctpop(X)→ handled in InstCombine, folding to justctpop(X)whenTTI::getPopcntSupportreturnsPSK_FastHardware. - Branch form — actual
if/elseblocks → SimplifyCFG converts these to selects first, which InstCombine then folds.
So the plan is:
- Add a fold in
InstCombineSelect.cppgated onTTI::getPopcntSupport - Rely on SimplifyCFG → InstCombine pipeline for the branch form
Since ctpop(X) naturally returns the correct answer for 0 and 1, the if (X <= 1) check is redundant. The only reason to keep this guard is to skip the popcount if the target has to fall back to a slow software emulation.
For the vector case, @Andarwinux suggested the fold could be unconditional — since all SIMD lanes have to wait regardless, the branch never saves work. Should we go with that, or gate it on a TTI cost check as well?
Does this overall approach sound right to you?
I think that's fine, but the case where X == size_max also need to be added.
As for vector, unless all lanes happen to be 0/1 or allmax, but I doubt that's likely to happen in reality.
@Andarwinux Good point on x == SIZE_MAX — since ctpop(SIZE_MAX) already returns MI_SIZE_BITS (64 on 64-bit targets, 32 on 32-bit targets), that guard is redundant too when hardware popcnt is available. I'll handle both patterns:
select (icmp ule X, 1), X, ctpop(X)→ctpop(X)select (icmp eq X, SIZE_MAX), MI_SIZE_BITS, ctpop(X)→ctpop(X)
For vector, agreed that in practice it's very unlikely all SIMD lanes will have values of 0, 1, or SIZE_MAX at the same time, so the branch rarely saves work.
@RKSimon what do you think about making the vector fold unconditional? And does the overall InstCombine + SimplifyCFG approach sound right to you before I open the PR?
I think you could open a PR even if it's just a draft, so that InstCombine team can review it.
@RKSimon I've opened PR #195443 for this fix. @nikic was automatically added as a reviewer, would you be able to review it as well since you guided the approach?
@RKSimon @Andarwinux PR #195443 is open with the fix in InstCombine. All CI checks pass and @dtcxzyw 's benchmark shows no regressions. Diff report: pre-commit (diff): 195443
@RKSimon @Andarwinux PR #195443 is open with the fix in InstCombine. All CI checks pass and @dtcxzyw 's benchmark shows no regressions. Diff report: pre-commit (diff): 195443
It looks like it folds scalar cases unconditionally?
@RKSimon @Andarwinux PR #195443 is open with the fix in InstCombine. All CI checks pass and @dtcxzyw 's benchmark shows no regressions. Diff report: pre-commit (diff): 195443
It looks like it folds scalar cases unconditionally?
Yes, since ctpop(0)==0 and ctpop(1)==1, the guard is always mathematically redundant regardless of target. InstCombine is target-independent, so the backend will still emit the right sequence for ctpop on targets without native support.
@RKSimon, should this fold be gated on target support, or is unconditional correct?