https://gcc.gnu.org/bugzilla/show_bug.cgi?id=124009
--- Comment #5 from GCC Commits <cvs-commit at gcc dot gnu.org> --- The master branch has been updated by Jeff Law <[email protected]>: https://gcc.gnu.org/g:57797c6404d81fdfa798c21b88ae6d8e19b23fd8 commit r17-285-g57797c6404d81fdfa798c21b88ae6d8e19b23fd8 Author: Jeff Law <[email protected]> Date: Sun May 3 06:45:19 2026 -0600 [RISC-V][PR target/124009] Improve select between 2^n and 0 on RISC-V So this was something I noticed a while back, I'm pretty sure while throwing hot blocks into an LLM to see what the LLM thought might be optimizable. In this case it was mcf from spec2017. So the basic idea is for code like this: int foo(int x, int y) { return (y < x) ? 1 : -1; } We get something like this for rv64gcbv_zicond: slt a1,a1,a0 # 27 [c=4 l=4] slt_didi3 li a5,2 # 28 [c=4 l=4] *movdi_64bit/1 czero.eqz a0,a5,a1 # 29 [c=4 l=4] *czero.eqz.didi addi a0,a0,-1 # 17 [c=4 l=4] *adddi3/1 That's not bad, in particular it avoids a likely tough to predict conditional branch. But we can do better. Essentially the code is selecting between 1 and -1. So if we take the output of the SLT (0/1) shift it left by one position (0/2), then subtract one we get a select for -1, 1. After this patch we get the expected: slt a1,a1,a0 # 28 [c=4 l=4] slt_didi3 slli a0,a1,1 # 29 [c=4 l=4] ashldi3 addi a0,a0,-1 # 17 [c=4 l=4] *adddi3/1 It's probably not any faster on a modern design, but it will encode more efficiently, saving either 2 or 4 bytes (potentially improving performance by getting more ops per fetch block). There's some very obvious generalizations. We can select between 2^n and 0, we can select between 2^n-1 and -1. But we can also do things like select between 3, 5 or 9 and 0 (think using shNadd where both source operands are the output of the slt). There's all kinds of interesting possibilities here. The key is to implement a splitter which handles 2^n and 0. Once that is in place pre-existing code will handle the 2^n-1 and -1 case automatically. While cases like selecting between 9 and 0 aren't yet handled, it would be a fairly simple extension to these new splitters with the basic framework in place. Anyway, while working on this I realized the scc_0 iterator didn't include any_lt, which seems like a dreadful oversight on my part. So I fixed that as well. Given the high degree of non-orthogonality in the sCC capabilities of the RISC-V ISA, this is actually several splitters to deal with the different cases of sCC we can handle in a single instruction. Tested on riscv32-elf and riscv64-elf. Will wait for pre-commit CI before moving forward. PR target/124009 gcc/ * config/riscv/iterators.md (scc_0): Add any_lt. * config/riscv/zicond.md: Add splitters to select between 2^n and 0. gcc/testsuite/ * gcc.target/riscv/pr124009.c: New test.
