Efficient detection of signed overflow?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I've just found myself looking at a piece of C code like the
snippet given below.  It's supposed to be adding two longs
and doing something special when the sum overflows.
Here a and b could have any value, but are likely to be small
in the common case.  The snippet occurs in a fairly performance-
critical section of code.

long a, b, x;
...
x = a + b;
if ((x^a) < 0 && (x^b) < 0)
    goto deal_with_overflow;
...

This code is wrong, I think, because it depends on undefined
behaviour.  I'm wondering how best to rewrite it so that (a)
the replacement code is correct and portable C89, and (b)
there's a reasonable chance of gcc compiling it to efficient
assembler on common platforms.

A bullet-proof solution (valid even in the presence of ones'
complement machines, trap representations, etc.) is
something like:

if ((a >= 0 && 0UL + a > (unsigned long)LONG_MAX - b) ||
    (a < 0 && 0UL - a > b - (unsigned long)LONG_MIN))
    goto deal_with_overflow;
x = a + b;

but, not surprisingly, this generates rather inefficient assembler
(with gcc-4.4 -O3).

Any suggestions for improvements over this?

On x86 or x86-64, the optimal generated code would
presumably consist of just two instructions:  an addition
followed by a jump-on-overflow.  Unfortunately, using
inline assembly isn't really an option here.  Are there
any common C code constructs that gcc would compile
to a jump-on-overflow instruction on x86?

Mark

[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux