Skip to content

cmd/compile: declare and assign of function literal escapes to heap #70171

@qdongxu

Description

@qdongxu

Go version

1.23.2

Output of go env in your module/workspace:

go env
GO111MODULE='on'
GOARCH='arm64'
GOBIN=''
GOCACHE='/Users/user/Library/Caches/go-build'
GOENV='/Users/user/Library/Application Support/go/env'
GOEXE=''
GOEXPERIMENT=''
GOFLAGS=''
GOHOSTARCH='arm64'
GOHOSTOS='darwin'
GOINSECURE=''
GOMODCACHE='/Users/user/go/pkg/mod'
GONOPROXY=''
GONOSUMDB=''
GOOS='darwin'
GOPATH='/Users/user/go'
GOPRIVATE=''
GOPROXY='https://goproxy.cn,direct'
GOROOT='/opt/homebrew/opt/go/libexec'
GOSUMDB='sum.golang.org'
GOTMPDIR=''
GOTOOLCHAIN='local'
GOTOOLDIR='/opt/homebrew/opt/go/libexec/pkg/tool/darwin_arm64'
GOVCS=''
GOVERSION='go1.23.2'
GODEBUG=''
GOTELEMETRY='local'
GOTELEMETRYDIR='/Users/user//Library/Application Support/go/telemetry'
GCCGO='gccgo'
GOARM64='v8.0'
AR='ar'
CC='cc'
CXX='c++'
CGO_ENABLED='1'
GOMOD='/Users/uesr/github/gorecycler/go.mod'
GOWORK=''
CGO_CFLAGS='-O2 -g'
CGO_CPPFLAGS=''
CGO_CXXFLAGS='-O2 -g'
CGO_FFLAGS='-O2 -g'
CGO_LDFLAGS='-O2 -g'
PKG_CONFIG='pkg-config'
GOGCCFLAGS='-fPIC -arch arm64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -ffile-prefix-map=/var/folders/5b/483w2_yd7wn5x962q5hvrzkc0000gn/T/go-build271930357=/tmp/go-build -gno-record-gcc-switches -fno-common'

What did you do?

when declare an closure and assign in separate lines the local variable escape:

        var someFunc func(assignF func())
	someFunc = func(assignF func()) {
		assignF()
	}
	num := testing.AllocsPerRun(1, func() {
		i := 0 // i escaped
		someFunc(func() {
			x := i
			if x < 0 {
				// do nothing, just make x valid
			}
		})

	})

but when declare the closure in one statement, it does not escape:

       var someFunc = func(assignF func()) {
		assignF()
	}
	num := testing.AllocsPerRun(1, func() {
		i := 0 // i does not escaped
		someFunc(func() {
			x := i
			if x < 0 {
				// do nothing, just make x valid
			}
		})

	})

escape : https://go.dev/play/p/r36WtbRaJtf
not escape: https://go.dev/play/p/2u-ydl00_0i

What did you see happen?

The local variable i does not escape in one code block but escaped in another code block.

What did you expect to see?

The variable i should not escape in both code blocks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.Performancecompiler/runtimeIssues related to the Go compiler and/or runtime.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions