在 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