A shift count is negative or not less than the width of the value

tx0/c:shift-rangedefaultwarningbug

What it finds

1 << 32, x >> -1: shifting by a negative count, or by at least the width of the promoted left operand, is undefined behavior, and on common processors gives the value unchanged or zero rather than what was meant.

The count must be an integer literal. The width is taken where it is certain: 32 bits for an int literal and for any declared type up to int, which is promoted to int, 64 bits for long and long long, the widest they are anywhere, and for size_t and the 64-bit types of stdint.h. A negative count is reported whatever the left operand.

From the rule's source, shift_range.rs.

Example from the rule's tests
#include <stdint.h> typedef unsigned long long u64_t; long shifts(int i, unsigned char c, long l, uint64_t w, u64_t v, mystery_t m, __int128 big){  long r = 0;  r += 1 << 32;tx0 reports: 1 has 32 bits, so shifting it by 32 is undefined  r += i << 40;tx0 reports: i has 32 bits, so shifting it by 40 is undefined  r += c >> 32;tx0 reports: c has 32 bits, so shifting it by 32 is undefined  r += l << 64;tx0 reports: l has 64 bits, so shifting it by 64 is undefined  r += w >> 64;tx0 reports: w has 64 bits, so shifting it by 64 is undefined  r += v << 70;tx0 reports: v has 64 bits, so shifting it by 70 is undefined  r += i >> -1;tx0 reports: the shift count -1 is negative  r += m << -2;tx0 reports: the shift count -2 is negative  i <<= 33;tx0 reports: i has 32 bits, so shifting it by 33 is undefined  r += 1 << 31;  r += 1UL << 40;  r += 1ULL << 63;  r += 0x100000000 << 8;  r += c << 24;  r += l << 40;  r += w << 63;  r += m << 40;  r += big << 64;  r += (long)i << 40;  return r;}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs in every tier. To turn it off for a project, set its level in tx0.toml:

tx0.toml
[rules]
"tx0/c:shift-range" = "off"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/c:shift-range] reason="..."

tx0 explain tx0/c:shift-range shows the same in the terminal. Found a false positive? Report it.