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: backing a local slice with an array in a loop causes the array to escape #24730

Closed
mundaym opened this issue Apr 6, 2018 · 4 comments

Comments

@mundaym
Copy link
Member

mundaym commented Apr 6, 2018

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

go version devel +68c7cb25a7 Wed Apr 4 12:18:29 2018 +0100 darwin/amd64

Does this issue reproduce with the latest release?

Yes (go version go1.10.1 darwin/amd64)

What did you do?

Compile the following code with '-m -m' to print escape information:

package main

type T struct {
	x [64]byte
}

func (t *T) f() {
	y := t.x[:]
	for i := range t.x[:] {
		y[i] = 1
	}
}

func (t *T) g() {
	y := t.x[:]
	for i := range t.x[:] {
		y = t.x[:] // <--- causes t.x to escape 
		y[i] = 1
	}
}

func main() { }

What did you expect to see?

t.x not to escape in f() or g() (it is only referenced by local variables).

What did you see instead?

t.x escapes in g() due to the second assignment.

./esc.go:7:10: (*T).f t does not escape
./esc.go:8:10: (*T).f t.x does not escape
./esc.go:17:10: t.x escapes to heap
./esc.go:17:10: 	from y (assigned) at ./esc.go:17:5
./esc.go:14:10: (*T).g t does not escape
./esc.go:15:10: (*T).g t.x does not escape
./esc.go:16:20: (*T).g t.x does not escape
@mvdan
Copy link
Member

mvdan commented Apr 6, 2018

Smaller repro:

$ cat f.go
package p

var arr [64]byte

func f() {
        var y []byte
        for i := 0; i < 2; i++ {
                y = arr[:]
                y[i] = 1
        }
}
$ go build -gcflags=-m f.go
# command-line-arguments
./f.go:8:10: arr escapes to heap

@josharian
Copy link
Contributor

cc @dr2chase

@cherrymui
Copy link
Member

This is not specific to slice and array.

package p

type T struct { x int }

func f(t *T) {
        var y *int
        for i := 0; i < 2; i++ {
                y = &t.x
                *y = 1
        }
}
e2.go:8:21: &t.x escapes to heap

The escape analysis models "loop depth". If the address of t.x to is passed to something defined at a lower (outer) loop depth, the escape analysis decides it escape. The problem is that it uses the loop depth of the address operator (or [:] which is implicitly address operator) instead of where the RHS is defined.

@gopherbot
Copy link

Change https://golang.org/cl/105257 mentions this issue: cmd/compile: in escape analysis, propagate loop depth to field

@golang golang locked and limited conversation to collaborators Apr 13, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

5 participants