Re: [PATCH v5 bpf-next 06/23] bpf: add special smin32/smax32 derivation from 64-bit bounds

Alexei Starovoitov
2023-10-31T18:41:41Z

On Tue, Oct 31, 2023 at 10:39 AM Andrii Nakryiko
<andrii.nakryiko@gmail.com> wrote:
> > fwiw, an alternative explanation might be arithmetic based.
> > Suppose:
> > . there are numbers a, b, c
> > . 2**31 <= b < 2**32
> > . 0 <= c < 2**31
> > . umin = 2**32 * a + b
> > . umax = 2**32 * (a + 1) + c
> >
> > The number of values in the range represented by [umin; umax] is:
> > . N = umax - umin + 1 = 2**32 + c - b + 1
> > . min(N) = 2**32 + 0 - (2**32-1) + 1 = 2
> > . max(N) = 2**32 + (2**31 - 1) - 2**31 + 1 = 2**32
> > Hence [(s32)b; (s32)c] form a valid range.
> >
> > At-least that's how I convinced myself.
>
> So the logic here follows the (visual) intuition how s64 and u64 (and
> also u32 and s32) correlate. That's how I saw it. TBH, the above
> mathematical way seems scary and not so straightforward to follow, so
> I'm hesitant to add it to comments to not scare anyone away :)

Actually Ed's math carried me across the line.
Could you add it to the commit log at least?

> I did try to visually represent it, but I'm not creative enough ASCII
> artist to pull this off, apparently. I'll just leave it as it is for
> now.

Your comment is also good, keep it as-is,
but it's harder to see that it's correct without the math part.

> > > + * upper 32 bits. As a random example, s64 range
> > > + * [0xfffffff0ffffff00; 0xfffffff100000010], forms a valid s32 range
> > > + * [-16, 16] ([0xffffff00; 0x00000010]) in its 32 bit subregister.
> > > + */

typo. It's [-256, 16]