Bug ID: 93742
           Summary: Optimization request: pattern-match typical addition
                    overflow checks
           Product: gcc
           Version: 10.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: middle-end
          Assignee: unassigned at gcc dot
          Reporter: tavianator at gmail dot com
  Target Milestone: ---

It would be nice if GCC could pattern-match the typical pattern for
overflow-safe addition and optimize it to just branch on the overflow flag. 
Right now, this:

_Bool add_overflow(int a, int b, int *res) {
    if ((a > 0 && b > INT_MAX - a) || (a < 0 && b < INT_MIN - a)) {
        return 1;
    } else {
        *res = a + b;
        return 0;

compiles to this:

        testl   %edi, %edi
        jle     .L2
        movl    $2147483647, %ecx
        movl    $1, %eax
        subl    %edi, %ecx
        cmpl    %esi, %ecx
        jl      .L12
        addl    %esi, %edi
        xorl    %eax, %eax
        movl    %edi, (%rdx)
        je      .L4
        movl    $-2147483648, %ecx
        movl    $1, %eax
        subl    %edi, %ecx
        cmpl    %esi, %ecx
        jle     .L4

#48580 is similar but about multiplication, for which the overflow-safe pattern
is a lot more complicated.  But the addition one above is a lot simpler and
pretty widespread I think.  For example, it's what CERT recommends:

Reply via email to