title: Signed saturated add of 64-bit ints?
body: <p>I'm looking for some C code for signed saturated 64-bit addition that compiles to efficient x86-64 code with the gcc optimizer.  Portable code would be ideal, although an asm solution could be used if necessary.</p>
  
  <pre><code>static const int64 kint64max = 0x7fffffffffffffffll;
  static const int64 kint64min = 0x8000000000000000ll;
  
  int64 signed_saturated_add(int64 x, int64 y) {
    bool x_is_negative = (x &amp; kint64min) != 0;
    bool y_is_negative = (y &amp; kint64min) != 0;
    int64 sum = x+y;
    bool sum_is_negative = (sum &amp; kint64min) != 0;
    if (x_is_negative != y_is_negative) return sum;  // can't overflow
    if (x_is_negative &amp;&amp; !sum_is_negative) return kint64min;
    if (!x_is_negative &amp;&amp; sum_is_negative) return kint64max;
    return sum;
  }
  </code></pre>
  
  <p>The function as written produces a fairly lengthy assembly output with several branches.  Any tips on optimization?  Seems like it ought to be be implementable with just an <code>ADD</code> with a few <code>CMOV</code> instructions but I'm a little bit rusty with this stuff.</p>