llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[X86][AArch64] backend didn't revert early exit for native popcnt

Open Andarwinux opened this issue 7 months ago • 21 comments

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.

Andarwinux avatar Apr 26 '26 06:04 Andarwinux

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

sai18022001 avatar Apr 26 '26 10:04 sai18022001

I don’t have permission to assign issues, so feel free to work on this.

Andarwinux avatar Apr 26 '26 11:04 Andarwinux

Looks like this optimization could also be applied to vector popcnt, but the situation here is more specific:

  1. The target lacks native vector popcount and predicate.
  2. The target lacks native vector popcount but has predicate.
  3. 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 avatar Apr 26 '26 12:04 Andarwinux

@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

sai18022001 avatar Apr 26 '26 12:04 sai18022001

@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:

  1. Scalar case (x86_64 -mattr=+popcnt): successfully folds to a single popcntq.

     # Output for i64 
     popcntq %rdi, %rax
     retq
    
  2. 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.

  3. 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 ?

sai18022001 avatar Apr 29 '26 11:04 sai18022001

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?

Andarwinux avatar Apr 29 '26 12:04 Andarwinux

Why does this need to be done in DAG and not InstCombine?

RKSimon avatar Apr 29 '26 19:04 RKSimon

I thought InstCombine was target-independent? For scalar cases, this optimization indeed depends on target.

Andarwinux avatar Apr 30 '26 06:04 Andarwinux

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

sai18022001 avatar Apr 30 '26 08:04 sai18022001

TTI has getPopcntSupport and actual cost functions which can do this much better int the middle-end

RKSimon avatar Apr 30 '26 11:04 RKSimon

@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 ?

sai18022001 avatar Apr 30 '26 11:04 sai18022001

Maybe a mixture of InstCombine / SimplfiyCFG?

RKSimon avatar Apr 30 '26 13:04 RKSimon

@RKSimon Thanks for the direction.

The pattern can appear in two IR forms:

  1. Select form — select (icmp ule X, 1), X, ctpop(X) → handled in InstCombine, folding to just ctpop(X) when TTI::getPopcntSupport returns PSK_FastHardware.
  2. Branch form — actual if/else blocks → SimplifyCFG converts these to selects first, which InstCombine then folds.

So the plan is:

  • Add a fold in InstCombineSelect.cpp gated on TTI::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?

sai18022001 avatar Apr 30 '26 15:04 sai18022001

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 avatar Apr 30 '26 16:04 Andarwinux

@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?

sai18022001 avatar May 01 '26 07:05 sai18022001

I think you could open a PR even if it's just a draft, so that InstCombine team can review it.

Andarwinux avatar May 01 '26 11:05 Andarwinux

@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?

sai18022001 avatar May 02 '26 11:05 sai18022001

@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

sai18022001 avatar May 02 '26 19:05 sai18022001

@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?

Andarwinux avatar May 03 '26 06:05 Andarwinux

@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?

sai18022001 avatar May 03 '26 09:05 sai18022001