带符号的64位整数饱和加法?
我正在寻找一些带符号的饱和64位加法使用的C代码,这些代码可使用gcc优化器编译为有效的x86-64代码.可移植的代码将是理想的选择,尽管必要时可以使用asm解决方案.
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.
static const int64 kint64max = 0x7fffffffffffffffll;
static const int64 kint64min = 0x8000000000000000ll;
int64 signed_saturated_add(int64 x, int64 y) {
bool x_is_negative = (x & kint64min) != 0;
bool y_is_negative = (y & kint64min) != 0;
int64 sum = x+y;
bool sum_is_negative = (sum & kint64min) != 0;
if (x_is_negative != y_is_negative) return sum; // can't overflow
if (x_is_negative && !sum_is_negative) return kint64min;
if (!x_is_negative && sum_is_negative) return kint64max;
return sum;
}
编写的函数产生带有多个分支的相当长的汇编输出.关于优化的任何提示吗?似乎它应该只用带有几个CMOV
指令的ADD
即可实现,但是我对此东西有点生锈.
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 ADD
with a few CMOV
instructions but I'm a little bit rusty with this stuff.
可以对此进行进一步优化,但这是一个可移植的解决方案.它不会调用未定义的行为,并且会在整数溢出发生之前对其进行检查.
This may be optimized further but here is a portable solution. It does not invoked undefined behavior and it checks for integer overflow before it could occur.
#include <stdint.h>
int64_t sadd64(int64_t a, int64_t b)
{
if (a > 0) {
if (b > INT64_MAX - a) {
return INT64_MAX;
}
} else if (b < INT64_MIN - a) {
return INT64_MIN;
}
return a + b;
}