golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123.29k stars 17.58k forks source link

cmd/compile: negative types are allowed, but will not be negative during program execution, with boundary checking #64895

Open qiulaidongfeng opened 9 months ago

qiulaidongfeng commented 9 months ago

Go version

go version devel go1.22-78b42a5338a Fri Dec 8 03:28:17 2023 +0000 linux/amd64

What operating system and processor architecture are you using (go env)?

set GO111MODULE=auto
set GOARCH=amd64
set GOBIN=
set GOCACHE=C:\Users\26454\AppData\Local\go-build
set GOENV=C:\Users\26454\AppData\Roaming\go\env
set GOEXE=.exe
set GOEXPERIMENT=
set GOFLAGS=
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOINSECURE=
set GOMODCACHE=D:\file\gofile\pkg\mod
set GONOPROXY=
set GONOSUMDB=
set GOOS=windows
set GOPATH=D:\file\gofile
set GOPRIVATE=
set GOPROXY=https://goproxy.cn,direct
set GOROOT=C:\Users\26454\.go\current
set GOSUMDB=sum.golang.org
set GOTMPDIR=
set GOTOOLCHAIN=local
set GOTOOLDIR=C:\Users\26454\.go\current\pkg\tool\windows_amd64
set GOVCS=
set GOVERSION=devel go1.22-f6509cf Thu Dec 21 00:15:58 2023 +0000
set GCCGO=gccgo
set GOAMD64=v3
set AR=ar
set CC=gcc
set CXX=g++
set CGO_ENABLED=1
set GOMOD=
set GOWORK=
set CGO_CFLAGS=-O2 -g
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-O2 -g
set CGO_FFLAGS=-O2 -g
set CGO_LDFLAGS=-O2 -g
set PKG_CONFIG=pkg-config
set GOGCCFLAGS=-m64 -mthreads -Wl,--no-gc-sections -fmessage-length=0 -ffile-prefix-map=D:\tmp\go-build1429133840=/tmp/go-build -gno-record-gcc-switches

What did you do?

package main

type s struct {
    str string
    i   int
}

func main() {
    var l s
    l.str = "100"
    for l.i < len(l.str) {
        switch l.str[l.i] {
        case '1':
            l.i++
        case '0':
            for i := l.i + 1; i < len(l.str); i++ {
                _ = l.str[l.i]
            }
        }
    }
}

What did you expect to see?

No Boundary check.

What did you see instead?

Have Boundary check.

qiulaidongfeng commented 9 months ago

l.str[l.i] memory is not accessed out of bounds, and this boundary check can be eliminated.

zigo101 commented 9 months ago

l.i might be negative in theory. That is the cause of the bound check. Though, for this specified case, the compiler can be smarter. (But worthy it?).

qiulaidongfeng commented 9 months ago

l.i might be negative in theory. That is the cause of the bound check. Though, for this specified case, the compiler can be smarter. (But worthy it?).

This issue was discovered in the lexer of a real open source project : https://gitee.com/u-language/u-language/blob/master/ucom/lex2/lex.go

If you have a way to make the code linked above have no boundary check without using unsafe. Can prove not worth the compiler can be more smarter.