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

            Bug ID: 122996
           Summary: Missed optimisation for branch folding with unsigned
                    arithmetic wraparound
           Product: gcc
           Version: 16.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: rtl-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: mital at mitalashok dot co.uk
  Target Milestone: ---

This function <https://godbolt.org/z/7GeTcPqj8>:

    unsigned inc(unsigned x) {
        return x == -1u ? 0u : x + 1u;
    }

Currently produces this assembly:

    inc:
        xor     edx, edx
        lea     eax, [rdi+1]
        cmp     edi, -1
        cmove   eax, edx
        ret

When it could produce:

    inc:
        lea     eax, [rdi+1]
        ret

Because the function is equivalent to `return x + 1u;`. This optimisation is
done for `return x == 0u ? 1u : x + 1u;`.

This comes up when dealing with std::string{,_view}::npos in C++

Reply via email to