Commit af824cc606 for golang
commit af824cc6065c68b6d66764ad1235c64c340283d1
Author: Michael Belokon <michael.belokon@icloud.com>
Date: Tue Dec 1 15:07:07 2026 +0000
go/constant: avoid int64 overflow in integer division
BinaryOp uses a normal int64 division for the integer division
(token.QUO_ASSIGN) of two int64Val values. For math.MinInt64 / -1
this overflows: the result is math.MinInt64 instead of the exact
value 1<<63. Because of this, the type checkers accept constant
expressions like -1<<63 / -1 with a negative value.
This is the only int64 division that overflows. Check for this
case and return 1<<63 directly.
Fixes #83522
Change-Id: I9e30c04758ef14a164e753909be800f37457299f
GitHub-Last-Rev: 8e71e41d28e66dfb3e6a3cda6340d8b962add140
GitHub-Pull-Request: golang/go#83523
Reviewed-on: https://go-review.googlesource.com/c/go/+/865564
Auto-Submit: Alan Donovan <adonovan@google.com>
Reviewed-by: Robert Griesemer <gri@google.com>
Auto-Submit: Robert Griesemer <gri@google.com>
Reviewed-by: Alan Donovan <adonovan@google.com>
LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
diff --git a/src/go/constant/value.go b/src/go/constant/value.go
index e6358913ce..fd68379448 100644
--- a/src/go/constant/value.go
+++ b/src/go/constant/value.go
@@ -1155,6 +1155,10 @@ func BinaryOp(x_ Value, op token.Token, y_ Value) Value {
case token.QUO:
return makeRat(big.NewRat(a, b))
case token.QUO_ASSIGN: // force integer division
+ // MinInt64 / -1 is the only int64 division that overflows.
+ if a == math.MinInt64 && b == -1 {
+ return MakeUint64(-math.MinInt64)
+ }
c = a / b
case token.REM:
c = a % b
diff --git a/src/go/constant/value_test.go b/src/go/constant/value_test.go
index 414476b470..5d85aede63 100644
--- a/src/go/constant/value_test.go
+++ b/src/go/constant/value_test.go
@@ -220,6 +220,7 @@ var opTests = []string{
`1 * 0.1 = 0.1`,
`1 * 0.1i = 0.1i`,
`1i * 1i = -1`,
+ `-9223372036854775808 * -1 = 9223372036854775808`,
`? * 0 = ?`,
`0 * ? = ?`,
`0 * 1e+1000000000 = ?`,
@@ -232,6 +233,10 @@ var opTests = []string{
`0 / ? = ?`,
`0 * 1e+1000000000i = ?`,
+ `10 /= 3 = 3`,
+ `-10 /= 3 = -3`,
+ `-9223372036854775808 /= -1 = 9223372036854775808`, // issue #83522
+
`0 % 0 = "runtime_error:_integer_divide_by_zero"`, // TODO(gri) should be the same as for /
`10 % 3 = 1`,
`? % 0 = ?`,
@@ -537,6 +542,8 @@ var optab = map[string]token.Token{
"/": token.QUO,
"%": token.REM,
+ "/=": token.QUO_ASSIGN, // integer division
+
"<<": token.SHL,
">>": token.SHR,