You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
cmd/compile: right shifting may cause extra bounds checks compared to division #76332
// Result: No panicBounds sectionsfuncissue57077Div(s []int) (left, right []int) {
middle:=len(s) /2// ERROR "Proved Div64 is unsigned$"left=s[:middle] // ERROR "Proved IsSliceInBounds$"right=s[middle:] // ERROR "Proved IsSliceInBounds$"return
}
// Result: Two panicBounds sections!funcissue57077Shift(s []int) (left, right []int) {
middle:=len(s) >>1// no such proof here or belowleft=s[:middle]
right=s[middle:]
return
}
What did you see happen?
issue57077Shift contains two extra bounds checks.
What did you expect to see?
The above functions should compile to the same result, namely without extra bounds checks.
This appears to be due to right shifts not given optimizations that this recent CL by @rsc and this older CL by @Jorropo gave division for provably non-negative signed values.
The below are simple cases demonstrating how the compiler treats right shifts differently:
// Result: SHRQ $1, BXfunctestLenDiv(s []int) int {
returnlen(s) /2
}
// Result: SARQ $1, BX <--- Could be SHRQ as BX >= 0functestLenShift(s []int) int {
returnlen(s) >>1
}
// Result: SHRQ $1, AX (was SHRQ+SARQ in Go 1.24)functestIfDiv(sint) int {
ifs<0 {
return0
}
returns/2
}
// Result: SARQ $1, AX <--- Could be SHRQ as AX >= 0functestIfShift(sint) int {
ifs<0 {
return0
}
returns>>1
}
changed the title [-]cmd/compile: Right shifting may cause extra bounds checks compared to division[/-][+]cmd/compile: right shifting may cause extra bounds checks compared to division[/+]on Nov 18, 2025
Activity
randall77 commentedon Nov 17, 2025
@Jorropo
gopherbot commentedon Nov 18, 2025
Change https://go.dev/cl/721205 mentions this issue:
cmd/compile: propagate unsigned relations for Div and Rsh if arguments are positivegopherbot commentedon Nov 18, 2025
Change https://go.dev/cl/721206 mentions this issue:
cmd/compile: rewrite Rsh to RshU if arguments are proved positive[-]cmd/compile: Right shifting may cause extra bounds checks compared to division[/-][+]cmd/compile: right shifting may cause extra bounds checks compared to division[/+]cmd/compile: propagate unsigned relations for Rsh if arguments are po…
cmd/compile: rewrite Rsh to RshU if arguments are proved positive