https://gcc.gnu.org/bugzilla/show_bug.cgi?id=124955

            Bug ID: 124955
           Summary: Improve code generation for leela's random number
                    generation
           Product: gcc
           Version: 16.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: rtl-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: law at gcc dot gnu.org
  Target Milestone: ---

Consider this code extracted from leela:

typedef unsigned int uint32;


uint32 random(uint32 s1) {
    const uint32 mask = 0xffffffff;
    s1 = (((s1 & 0xFFFFFFFEU) << 12) & mask);
    return s1;
}

Generates this RISC-V code:

        slli    a5,a0,44        # 25    [c=4 l=4]  ashldi3
        srai    a0,a5,44        # 26    [c=4 l=4]  ashrdi3
        andi    a0,a0,-2        # 21    [c=4 l=4]  *anddi3/1
        slli    a0,a0,12        # 22    [c=4 l=4]  ashldi3

But we can do better.  I think this is just:

srliw   a0,a0,1
slliw   a0,a0,13

This is hot in leela (Random::random()) and the two most obvious instances
would represent roughly 1% of the total dynamic instruction stream.  LLVM does
ever-so-slightly better here generating:

        andi    a0, a0, -2
        slliw   a0, a0, 12

Which encodes 2 bytes shorter and is probably realizable for GCC as well. 
Marking as RTL optimization for now, but it might be recategorized as target
once we dig into it further.

Reply via email to