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

            Bug ID: 129035
           Summary: Missed optimization opportunity with std::signbit
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: lakshayg.xyz at gmail dot com
  Target Milestone: ---

https://godbolt.org/z/jW79TqP9K

```
#include <cmath>

using T = ...; // integral types only

bool signbit1(T x) {
    return std::signbit(x);
}

bool signbit2(T x) {
    return x < 0;
}
```

I looked at the assembly for the above code snippet on Compiler Explorer and
noticed that the std::signbit emits an extra `and` instructions in certain
cases. Ideally the two implementations above should be identical for all
integral types. I checked Clang and it produces a single right shift
instruction in all cases.

+-----------------+---------------------+---------------------+
|                 | aarch64             | x86_64              |
|-----------------|----------+----------|----------+----------|
|                 | T = int  | T = long | T = int  | T = long |
|-----------------|----------|----------|----------|----------|
| std::signbit(x) | lsr      | asr, and | sar, and | sar, and |
|                 |          | ^^^^^^^^ | ^^^^^^^^ | ^^^^^^^^ | 
|           x < 0 | lsr      | lsr      | shr      | shr      |
+-----------------+----------+----------+----------+----------+

^^^^^ indicates unexpected output.

Somewhat more surprising is that if I replace std::signbit(x) with (x < 0 ?
true : false), we still get the extra `and` instruction in all those cases. I
would have expected `cond` and `cond ? true : false` to produce identical
assembly (assuming no UB).

----------------------------------

I am unfamiliar with GCC internals but I attempted some LLM driven analysis of
this problem, full details (mostly slop) are available here:
https://github.com/bot-lakshayg/gcc/issues/3 but my understanding is that
there's an optimization in GCC that transforms (A < 0 ? C : 0). It acts on this
expression before (cond ? 1 : 0) has had a chance to act on it. This leaves the
extra `and` instruction.

I also came up with a few different ways of addressing this problem (linked to
that github issue) but I am not sure any of those are the _right_ fix.

Reply via email to