Skip to content

cmd/compile: unnecessary bounds check with slice offset #66691

@dsnet

Description

@dsnet

Go version

go1.22

Output of go env in your module/workspace:

GOARCH=amd64
GOOS=linux

What did you do?

Compile the following:

package main

import "encoding/binary"

var src []byte
var dst uint64

func main() {
	const offset = 1
	if len(src) < offset+8 {
		return
	}
	dst = binary.BigEndian.Uint64(src[offset:])
}

What did you see happen?

I see the following in the assembly:

	0x003f 00063 (/usr/local/go1.22.0/src/encoding/binary/binary.go:183)	MOVL	$7, AX
	0x0044 00068 (/usr/local/go1.22.0/src/encoding/binary/binary.go:183)	PCDATA	$1, $0
	0x0044 00068 (/usr/local/go1.22.0/src/encoding/binary/binary.go:183)	CALL	runtime.panicIndex(SB)
	0x0049 00073 (/usr/local/go1.22.0/src/encoding/binary/binary.go:183)	XCHGL	AX, AX

What did you expect to see?

No bounds check.

The bounds check is avoided if offset is 0, but fails once it is non-zero.

However, this provably safe so long as offset+8 does not overflow an int.

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

    Status

    No status

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions