[RFC] Implementing detection of saturation and rounding arithmetic
Liu Hao
lh_mouse@126.com
Wed May 12 13:06:16 GMT 2021
在 5/12/21 5:13 PM, Tamar Christina via Gcc 写道:
>
> int f (int a, int b)
> {
> int res;
> if (__builtin_add_overflow (a, b, &res))
> {
> if (res >= 0)
> return INT_MAX;
> else
> return INT_MIN;
> }
> return res;
> }
>
> Should be recognized as saturating as well. But yeah, following the same approach we
> would rewrite the sequence to something like res = .ADD_SAT (a, b);
>
Is this a correct saturating addition implementation?
If the addition has overflowed, you get a positive result or zero for the sum of two negative
numbers (or a negative one for two positive numbers); and it is not straightforward to write it this
way.
This should be
int f (int a, int b)
{
int res;
if (__builtin_add_overflow (a, b, &res))
{
if (a >= 0) /* changed from `res` to `a` */
return INT_MAX;
else
return INT_MIN;
}
return res;
}
which can be optimized further as
int f (int a, int b)
{
int res;
if (__builtin_add_overflow (a, b, &res))
res = (a >> sizeof(int) * CHAR_BIT - 1) ^ INT_MAX;
return res;
}
--
Best regards,
Liu Hao
-------------- next part --------------
A non-text attachment was scrubbed...
Name: OpenPGP_signature
Type: application/pgp-signature
Size: 840 bytes
Desc: OpenPGP digital signature
URL: <https://gcc.gnu.org/pipermail/gcc/attachments/20210512/489cafc6/attachment.sig>
More information about the Gcc
mailing list