[ub] Signed shifting

Hubert Tong hubert.reinterpretcast at gmail.com
Tue Nov 18 14:36:35 CET 2014


UB for signed integer overflow is often relied on by optimizers to either
increment 32-bit ints in 64-bit registers on RISC systems without enforcing
exact wraparound or to perform loop optimizations:

for (int x = y; x < y + 32; ++x) f[x] += x;

to (possibly)

f[y] += y;
f[y + 1] += y + 1;
...
f[y + 31] += y + 31;

where the original loop might not have performed a single iteration if
wraparound is to reliably occur.

-- HT


On Tue, Nov 18, 2014 at 4:04 AM, Jens Maurer <Jens.Maurer at gmx.net> wrote:

> On 11/18/2014 12:14 AM, Howard Hinnant wrote:
> > int
> > sign(int x)
> > {
> >     constexpr int n = std::numeric_limits<int>::digits;
> >     return (x >> n) | (static_cast<unsigned>(-x) >> n);
> > }
>
> That "-x" in there seems to cause undefined behavior on
> two's complement machines if "x" is std::numeric_limits<int>::min(),
> according to 5p4, it seems:
>
> "If during the evaluation of an expression, the result is [...] not
> in the range of representable values for its type, the behavior is
> undefined."
>
>
> Can we make the world a simpler and better place by prescribing two's
> complement for all signed integer operations in C++, thereby enshrining
> what everybody expects, anyway?
>
> Jens
>
> _______________________________________________
> ub mailing list
> ub at isocpp.open-std.org
> http://www.open-std.org/mailman/listinfo/ub
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.open-std.org/pipermail/ub/attachments/20141118/e245db4c/attachment.html 


More information about the ub mailing list