[Bug tree-optimization/71336] Suboptimal code generated for "(a & 1) ? (CST1 + CST2) : CST1"

daniel.barboza at oss dot qualcomm.com gcc-bugzilla@gcc.gnu.org
Mon Mar 9 20:31:42 GMT 2026


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

Daniel Henrique Barboza <daniel.barboza at oss dot qualcomm.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |daniel.barboza at oss dot qualcomm
                   |                            |.com

--- Comment #13 from Daniel Henrique Barboza <daniel.barboza at oss dot qualcomm.com> ---
A fix proposal was sent to the ML (currently on v2):

https://gcc.gnu.org/pipermail/gcc-patches/2026-March/710154.html

The idea is to generalize the idea Jeff gave in comment #12: for a pattern
like:

int test(int a) {
    return a & 1 ? 7 : 3;
}

We can simplify it to 

3 + (a & 1) * (7 - 3);

This will remove the conditional and targets can optimize the PLUS pattern at
their leisure.  In an armv8-a target, using current trunk, this function will
generate:

test:
.LFB0:
        .cfi_startproc
        tst     x0, 1   // 38   [c=8 l=4]  *anddi3nr_compare0_zextract
        mov     w1, 3   // 41   [c=4 l=4]  *movsi_aarch64/3
        mov     w0, 7   // 42   [c=4 l=4]  *movsi_aarch64/3
        csel    w0, w1, w0, eq  // 17   [c=4 l=4]  *cmovsi_insn/0
        ret             // 47   [c=0 l=4]  *do_return
        .cfi_endproc


With the proposed fix:

.LFB0:
        .cfi_startproc
        ubfiz   w0, w0, 2, 1    // 7    [c=4 l=4]  *andim_ashiftsi_bfiz
        add     w0, w0, 3       // 13   [c=4 l=4]  *addsi3_aarch64/0
        ret             // 21   [c=0 l=4]  *do_return
        .cfi_endproc


For RISC-V the generated .s is:

test:
.LFB0:
        .cfi_startproc
        andi    a0,a0,1 # 6     [c=4 l=4]  *anddi3/1
        slliw   a0,a0,2 # 7     [c=8 l=4]  ashlsi3_extend
        addi    a0,a0,3 # 16    [c=4 l=4]  *adddi3/1
        ret             # 29    [c=0 l=4]  simple_return
        .cfi_endproc



This idea of using a mult to re-create an immediate to eliminate a conditional
is also used in 56110 and 123967.  I'll send patches for those shortly.

design is going to be used in 56110 and 123967 as well.


More information about the Gcc-bugs mailing list