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: teach prove about incrementing, len, and overflow #36346

Open
josharian opened this issue Jan 1, 2020 · 1 comment
Open

cmd/compile: teach prove about incrementing, len, and overflow #36346

josharian opened this issue Jan 1, 2020 · 1 comment

Comments

@josharian
Copy link
Contributor

@josharian josharian commented Jan 1, 2020

I have some hot code that looks approximately like this:

func f(a []int, i int) int {
	for i < len(a) && a[i] != 0 {
		i++
	}
	return i
}

The generated code has a bounds check on every iteration. This is because i might be negative. We can rule that out up front:

func f(a []int, i int) int {
	if i < 0 {
		panic("bad")
	}
	for i < len(a) && a[i] != 0 {
		i++
	}
	return i
}

This could should be able to go without a bounds check. i cannot be negative at the beginning. In order to become negative, it must overflow. However, it cannot overflow: It is being incremented, so it must reach len(a) before overflowing, in which case we exit the loop before evaluating a[i].

(I actually know a priori in my code that i is not negative; I'd be tempted to use #30582 here. I could also switch to i being a uint, which does remove the bounds check, but it makes other things in the real code a bit awkward.)

I don't know how hard it is to teach prove about this case.

cc @zdjones @rasky @randall77

@rasky
Copy link
Member

@rasky rasky commented Jan 1, 2020

It should be fixed by the patch serie finishing at CL 196680. I can't test it right now though.

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

Successfully merging a pull request may close this issue.

None yet
3 participants
You can’t perform that action at this time.