From 417d5e6627dbef2e6a309957b4f932eb91ce1e4d Mon Sep 17 00:00:00 2001 From: Jorropo Date: Sun, 7 Dec 2025 03:07:46 +0100 Subject: [PATCH] cmd/compile: add limits bruteforce tests for bitlen This ensure BitLen is perfect within the limitations limits can represent. Change-Id: I5c1770b4a9f6408fd68fe77b4ef2b2cdd52e26cb Reviewed-on: https://go-review.googlesource.com/c/go/+/727781 Reviewed-by: Keith Randall LUCI-TryBot-Result: Go LUCI Auto-Submit: Jorropo Reviewed-by: Keith Randall Reviewed-by: Carlos Amedee --- src/cmd/compile/internal/ssa/prove.go | 32 ++++++++-------------- src/cmd/compile/internal/ssa/prove_test.go | 4 +++ 2 files changed, 16 insertions(+), 20 deletions(-) diff --git a/src/cmd/compile/internal/ssa/prove.go b/src/cmd/compile/internal/ssa/prove.go index 22de2dc7a55..233d0b30d14 100644 --- a/src/cmd/compile/internal/ssa/prove.go +++ b/src/cmd/compile/internal/ssa/prove.go @@ -428,6 +428,14 @@ func (l limit) ctz(b uint) limit { return noLimit.unsignedMax(uint64(min(uint(bits.TrailingZeros64(fixed)), b))) } +// Similar to add, but computes the Len of the limit for bitsize b. +func (l limit) bitlen(b uint) limit { + return noLimit.unsignedMinMax( + uint64(bits.Len64(l.umin)), + uint64(bits.Len64(l.umax)), + ) +} + var noLimit = limit{math.MinInt64, math.MaxInt64, 0, math.MaxUint64} // a limitFact is a limit known for a particular value. @@ -1941,26 +1949,10 @@ func (ft *factsTable) flowLimit(v *Value) { min := uint64(bits.OnesCount64(fixedBits)) ft.unsignedMinMax(v, min, min+changingBitsCount) - case OpBitLen64: - a := ft.limits[v.Args[0].ID] - ft.unsignedMinMax(v, - uint64(bits.Len64(a.umin)), - uint64(bits.Len64(a.umax))) - case OpBitLen32: - a := ft.limits[v.Args[0].ID] - ft.unsignedMinMax(v, - uint64(bits.Len32(uint32(a.umin))), - uint64(bits.Len32(uint32(a.umax)))) - case OpBitLen16: - a := ft.limits[v.Args[0].ID] - ft.unsignedMinMax(v, - uint64(bits.Len16(uint16(a.umin))), - uint64(bits.Len16(uint16(a.umax)))) - case OpBitLen8: - a := ft.limits[v.Args[0].ID] - ft.unsignedMinMax(v, - uint64(bits.Len8(uint8(a.umin))), - uint64(bits.Len8(uint8(a.umax)))) + case OpBitLen64, OpBitLen32, OpBitLen16, OpBitLen8: + a := v.Args[0] + al := ft.limits[a.ID] + ft.newLimit(v, al.bitlen(uint(a.Type.Size())*8)) // Masks. diff --git a/src/cmd/compile/internal/ssa/prove_test.go b/src/cmd/compile/internal/ssa/prove_test.go index 1d91736ff00..969e68fee4f 100644 --- a/src/cmd/compile/internal/ssa/prove_test.go +++ b/src/cmd/compile/internal/ssa/prove_test.go @@ -77,3 +77,7 @@ func TestLimitComUnsigned(t *testing.T) { func TestLimitCtzUnsigned(t *testing.T) { testLimitUnaryOpUnsigned8(t, "ctz", limit{-128, 127, 0, 8}, limit.ctz, func(x uint8) uint8 { return uint8(bits.TrailingZeros8(x)) }) } + +func TestLimitBitlenUnsigned(t *testing.T) { + testLimitUnaryOpUnsigned8(t, "bitlen", limit{-128, 127, 0, 8}, limit.bitlen, func(x uint8) uint8 { return uint8(bits.Len8(x)) }) +}