[all-commits] [llvm/llvm-project] 69780b: [AggressiveInstCombine] Recognize table based log2...

Craig Topper via All-commits all-commits at lists.llvm.org
Sat Mar 14 17:39:17 PDT 2026


  Branch: refs/heads/main
  Home:   https://github.com/llvm/llvm-project
  Commit: 69780be1d42a5fd218e36e854e72a5532ac7b502
      https://github.com/llvm/llvm-project/commit/69780be1d42a5fd218e36e854e72a5532ac7b502
  Author: Craig Topper <craig.topper at sifive.com>
  Date:   2026-03-14 (Sat, 14 Mar 2026)

  Changed paths:
    M llvm/lib/Transforms/AggressiveInstCombine/AggressiveInstCombine.cpp
    A llvm/test/Transforms/AggressiveInstCombine/AArch64/lower-table-based-log2-basics.ll
    A llvm/test/Transforms/AggressiveInstCombine/X86/lower-table-based-log2-basics.ll
    A llvm/test/Transforms/AggressiveInstCombine/X86/lower-table-based-log2-negative.ll

  Log Message:
  -----------
  [AggressiveInstCombine] Recognize table based log2 and replace with ctlz+sub. (#185160)

Recognize table based log2 implementations like

```
unsigned log2(unsigned v) {
  static const unsigned char table[] = {
    0,  9,  1, 10, 13, 21,  2, 29, 11, 14, 16, 18, 22, 25,  3, 30,
    8, 12, 20, 28, 15, 17, 24,  7, 19, 27, 23,  6, 26,  5,  4, 31
  };

  v |= v >> 1;
  v |= v >> 2;
  v |= v >> 4;
  v |= v >> 8;
  v |= v >> 16;

  return table[(unsigned)(v * 0x07C4ACDDU) >> 27];
}
```

and replaces with 31 - llvm.ctlz(v).

Similar for i64 log2. Other sizes can be supported with correct multiply
constant and table values, but I have not found examples yet.

This code is based on the existing tryToRecognizeTableBasedCttz. Like
that function, we support
any combination of multiply constant and table values that produce the
correct result.

It handles the same pattern as #177110, but does not match the outer
subtract from that patch. It is assumed that InstCombine or other
optimizations can combine (sub 31 (sub 31, cttz V)) later.

I have limited this to targets that have a fast ctlz. The backend does
not yet have a table based lowering for ctlz so this reduces the chance
of regressions.



To unsubscribe from these emails, change your notification settings at https://github.com/llvm/llvm-project/settings/notifications


More information about the All-commits mailing list