From f81d73e8d57c99d32744e61940dad08c4ec07111 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Martin=20M=C3=B6hrmann?= Date: Sun, 6 May 2018 12:19:25 +0200 Subject: [PATCH] strconv: add comment explaining bounded shift in formatBits MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit The compiler can generate better code for shifts bounded to be less than 32 and thereby known to be less than any register width. See https://golang.org/cl/109776. Change-Id: I0c4c9f0faafa065fce3c10fd328830deb92f9e38 Reviewed-on: https://go-review.googlesource.com/c/111735 Run-TryBot: Martin Möhrmann TryBot-Result: Gobot Gobot Reviewed-by: Robert Griesemer Reviewed-by: Brad Fitzpatrick --- src/strconv/itoa.go | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/strconv/itoa.go b/src/strconv/itoa.go index 8afe7af251..4aaf57830c 100644 --- a/src/strconv/itoa.go +++ b/src/strconv/itoa.go @@ -152,10 +152,14 @@ func formatBits(dst []byte, u uint64, base int, neg, append_ bool) (d []byte, s } } else if isPowerOfTwo(base) { - // It is known that base is a power of two and - // 2 <= base <= len(digits). // Use shifts and masks instead of / and %. - shift := uint(bits.TrailingZeros(uint(base))) & 31 + // Base is a power of 2 and 2 <= base <= len(digits) where len(digits) is 36. + // The largest power of 2 below or equal to 36 is 32, which is 1 << 5; + // i.e., the largest possible shift count is 5. By &-ind that value with + // the constant 7 we tell the compiler that the shift count is always + // less than 8 which is smaller than any register width. This allows + // the compiler to generate better code for the shift operation. + shift := uint(bits.TrailingZeros(uint(base))) & 7 b := uint64(base) m := uint(base) - 1 // == 1<= b { -- 2.50.0