On Tue, Feb 19, 2013 at 8:52 PM, Ian Lance Taylor <i...@google.com> wrote: > On Tue, Feb 19, 2013 at 4:19 PM, Jeffrey Walton <noloa...@gmail.com> wrote: >> >> I've been using John Regehr's Integer Overflow Checker (IOC) on a few >> libraries. It is a Clang plug-in and can be found at >> http://embed.cs.utah.edu/ioc/. >> >> The checker has flagged two libraries I use for performing undefined >> right shifts: >> >> CLANG ARITHMETIC UNDEFINED at <./xxx, (595:22)> : Op: >>, Reason : >> Unsigned Right Shift: Right operand is negative or is greater than or >> equal to the width of the promoted left operand, BINARY OPERATION: >> left (uint32): 2196358166 right (uint32): 32 >> >> The fix seems easy enough on the surface: simply validate the >> parameters before performing the shift. However, that could introduce >> a timing difference in the function. >> >> How could one fix the issue without introducing timing differences? > > As the saying goes, I can write code that runs as fast as you like, if > it doesn't have to be correct. Jon Bentley :)
> If you care about the result of the shift, you need to ensure that the > right operand is within bounds, one way or another. It looks like they have to use AND rather than MOD: template <class T> inline T rotlMod(T x, unsigned int y) { y &= sizeof(T)*8 - 1; return T((x<<y) | (x>>y)); } Jeff