Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

cmd/compile: Compiler doesn't know bits.Len and friends return non-negative integers #51963

greatroar opened this issue Mar 26, 2022 · 1 comment


Copy link

@greatroar greatroar commented Mar 26, 2022

What version of Go are you using (go version)?

$ go version
go version go1.18 linux/amd64

Does this issue reproduce with the latest release?

Reproduces with

$ gotip version
go version devel go1.19-ab0f7611d73 Mon Mar 14 09:19:01 2022 +0000 linux/amd64

What did you do?

func nextpow2(x uint) uint {
	return 1 << bits.Len(x)

What did you expect to see?

The same code as for

func nextpow2(x uint) uint {
	return 1 << uint(bits.Len(x))

What did you see instead?

The compiler generates a check that boils down to

if bits.Len(x) < 0 {

This happens because bits.Len (and LeadingZeros, TrailingZeros, OnesCount) have return type int instead of uint. In the example given, this doesn't matter much because I can add the cast. But that's clutter and also adds to the inlining cost, despite the generated code being smaller.

It looks like the compiler knows that cap and len never return negative integers, so perhaps the math/bits functions could be dealt with in the same way?

Copy link

@gopherbot gopherbot commented Mar 26, 2022

Change mentions this issue: cmd/compile: upgrade prove pass to know results of math/bits ops are nonnegative

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
None yet

No branches or pull requests

2 participants