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

Missed combining shr and shrx in collatz_f1()

Open BreadTom opened this issue 1 year ago • 2 comments

See godbolt and GCC bug.

#include <stdint.h>
#include <stdbool.h>

uint64_t
collatz_onlyoddstep (uint64_t oddnum){
  return (3 * oddnum + 1);
}

uint64_t
collatz_oddstep (uint64_t oddnum)
{
  return (3 * oddnum + 1) / 2;
}

uint64_t
collatz_div2tillodd (uint64_t num)
{
  num >>= __builtin_ctzg (num);
  return num;
}

uint64_t
collatz_f0 (uint64_t oddnum)
{
  oddnum = collatz_onlyoddstep (oddnum);
  return collatz_div2tillodd (oddnum);
}

uint64_t
collatz_f1 (uint64_t oddnum)
{
  oddnum = collatz_oddstep (oddnum);
  return collatz_div2tillodd (oddnum);
}

collatz_f1() uses shr then tzcnt then shrx. collatz_f0() uses only tzcnt then shrx.

collatz_f0() speeds up by 10% when I tested it.

BreadTom avatar Apr 30 '25 16:04 BreadTom

@llvm/issue-subscribers-backend-x86

Author: None (BreadTom)

See [godbolt](https://godbolt.org/z/5Wh8sG958) and [GCC bug](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120038). ``` #include <stdint.h> #include <stdbool.h>

uint64_t collatz_onlyoddstep (uint64_t oddnum){ return (3 * oddnum + 1); }

uint64_t collatz_oddstep (uint64_t oddnum) { return (3 * oddnum + 1) / 2; }

uint64_t collatz_div2tillodd (uint64_t num) { num >>= __builtin_ctzg (num); return num; }

uint64_t collatz_f0 (uint64_t oddnum) { oddnum = collatz_onlyoddstep (oddnum); return collatz_div2tillodd (oddnum); }

uint64_t collatz_f1 (uint64_t oddnum) { oddnum = collatz_oddstep (oddnum); return collatz_div2tillodd (oddnum); }

collatz_f1() uses shr then tzcnt then shrx.
collatz_f0() uses only tzcnt then shrx.

collatz_f0() speeds up by 10% when I tested it.
</details>

llvmbot avatar Apr 30 '25 16:04 llvmbot

btver2 (BMI1) vs icelake (BMI1+2): https://godbolt.org/z/baaG6Mo6E

shrx had been used to allow for a separate dst reg (and maybe to not touch eflags?) but we don't attempt to relax this back to regular shr - probably because of the dependency on the ECX reg for the shift amount that we might not be able to fold away in regalloc

RKSimon avatar May 02 '25 14:05 RKSimon