On Sun, 2018-07-08 at 13:38 +0300, Leon Romanovsky wrote: > +/* > + * Compute *d = (a << s) > + * > + * Returns true if '*d' cannot hold the result or 'a << s' doesn't make sense. > + * - 'a << s' causes bits to be lost when stored in d > + * - 's' is garbage (eg negative) or so large that a << s is guaranteed to be 0 If s >= sizeof(a) * 8 then a << s triggers undefined behavior. There is no guarantee that the result will be 0. See also http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_21.html. > + * - 'a' is negative What is wrong with using (a << s) if a < 0? > + * - 'a << s' sets the sign bit, if any, in '*d' Setting the highest bit is fine if a is unsigned. > + * *d is not defined if false is returned. > + */ > +#define check_shift_overflow(a, s, d) ({ \ > + typeof(a) _a = a; \ > + typeof(s) _s = s; \ > + typeof(d) _d = d; \ > + u64 _a_full = _a; \ > + unsigned int _to_shift = \ > + _s >= 0 && _s < 8 * sizeof(*d) ? _s : 0; \ > + *_d = (_a_full << _to_shift); \ > + *d = *_d; \ > + (_to_shift != _s || *_d < 0 || _a < 0 || \ > + (*_d >> _to_shift) != _a); \ > +}) I think the fact that the above macro stores the result in a pointer passed as argument will reduce readability. How about the macro below, which addresses all the shortcomings mentioned above? /* * Test whether the result of a shift-left operation would be larger than * what fits in a variable with the type of @a. Both signed and unsigned * types are supported for @a. */ #define shift_left_overflows(a, b) \ ({ \ typeof(a) _minus_one = -1LL; \ typeof(a) _plus_one = 1; \ bool _a_is_signed = _minus_one < 0; \ int _shift = sizeof(a) * 8 - ((b) + _a_is_signed); \ _shift < 0 || ((a) & ~((_plus_one << _shift) - 1)) != 0;\ }) Thanks, Bart. ��.n��������+%������w��{.n�����{���fk��ܨ}���Ơz�j:+v�����w����ޙ��&�)ߡ�a����z�ޗ���ݢj��w�f