Inspect bounds-check elimination and folding
Inspect bounds-check elimination and folding
Go requires valid array and slice indices; an out-of-range access panics. The compiler can eliminate a runtime bounds check when it proves the access safe along that path. Constant folding evaluates eligible constant computations before execution; Go also has exact language-level constant arithmetic before conversion to a concrete type. Optimizations preserve defined behavior, including required panics, and their presence depends on the compiler.
package main
import ( "fmt")
//go:noinlinefunc first(b []byte) byte { return b[0] }
//go:noinlinefunc pair(b []byte) int { if len(b) < 2 { return 0 } return int(b[0]) + int(b[1])}func main() { fmt.Println(first([]byte{7}), pair([]byte{3, 4}), pair(nil))}Compile with go build -gcflags=-d=ssa/check_bce/debug=1 -o demo main.go. In Go 1.23 a Found IsInBounds message at first identifies a check still present at that pass. The guarded pair accesses are proved safe. This is not a complete census of every check in the final binary. Prefer clear guard conditions; do not introduce dummy accesses solely to manipulate the optimizer.
Expected output:
7 7 0Constant arithmetic and target conversion
package main
import ( "fmt" "go/constant" "go/token")
const big = 1 << 80const small = big >> 77
func main() { fmt.Println(int(small), 3*7+2) fmt.Println(constant.BinaryOp(constant.MakeInt64(3), token.MUL, constant.MakeInt64(7)))}The untyped constant big exceeds int64 but small fits int. Conversion to int is legal only when representable. go/constant offers exact constant operations for analysis tools; it does not inspect the compiler optimizer. A runtime variable computation can also be folded when values are known, but a function cannot assume arbitrary inputs are constant. Invalid constant indices may be rejected at compile time instead of panicking.
Expected output:
8 2321Try it locally
Write a guarded function returning the sum of the first three slice elements and a boolean. Return false for short inputs; try [1,2,3] and [1]. Inspect the BCE diagnostic.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Compiler pipeline 06: Inspect bounds-check elimination and folding
Check the lesson objective before moving on.
When may a bounds check be removed?
What does Found IsInBounds in check_bce typically report?