Skip to content

cmd/compile: fallthrough prevents the elimination of some bounds checks #78390

Description

@jub0bs

Go version

go version go1.27-devel_c173b531 Wed Mar 25

Output of go env in your module/workspace:

N/A

What did you do?

While working on CL 759100, I noticed a bounds check that should be eliminated but isn't. Below is a simple reproducer:

package p

func f(s []byte) {
	switch len(s) {
	case 2:
		_ = s[1]
		fallthrough
	case 1:
		_ = s[0]
	}
}

What did you see happen?

Running go build -gcflags='-d=ssa/check_bce/debug=1 reveals one bounds checks (for 0) remains:

package p

func f(s []byte) {
	switch len(s) {
	case 2:
		_ = s[1]
		fallthrough
	case 1:
		_ = s[0] // Found IsInBounds
	}
}

(Godbolt link)

What did you expect to see?

I expected no bounds checks, since the indexing expression s[0] is evaluated only when len(s) is equal to either 2 or 1.

Apparently, the fallthrough statement is to blame. If I remove it, all bounds checks are gone (Godbolt link).

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugReportIssues describing a possible bug in the Go implementation.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

    Fields

    No fields configured for issues without a type.

    Projects

    Status
    Todo

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions