Skip to content

Commit 3452d80

Browse files
randall77gopherbot
authored andcommitted
cmd/compile: add cast in range loop final value computation
When replacing a loop where the iteration variable has a named type, we need to compute the last iteration value as i = T(len(a)-1), not just i = len(a)-1. Fixes #73491 Change-Id: Ic1cc3bdf8571a40c10060f929a9db8a888de2b70 Reviewed-on: https://go-review.googlesource.com/c/go/+/667815 Reviewed-by: Cuong Manh Le <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]> Auto-Submit: Keith Randall <[email protected]> Reviewed-by: Junyang Shao <[email protected]> Reviewed-by: Keith Randall <[email protected]>
1 parent 3009566 commit 3452d80

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/cmd/compile/internal/walk/range.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -605,7 +605,7 @@ func arrayClear(wbPos src.XPos, a ir.Node, nrange *ir.RangeStmt) ir.Node {
605605

606606
// For array range clear, also set "i = len(a) - 1"
607607
if nrange != nil {
608-
idx := ir.NewAssignStmt(base.Pos, nrange.Key, ir.NewBinaryExpr(base.Pos, ir.OSUB, ir.NewUnaryExpr(base.Pos, ir.OLEN, a), ir.NewInt(base.Pos, 1)))
608+
idx := ir.NewAssignStmt(base.Pos, nrange.Key, typecheck.Conv(ir.NewBinaryExpr(base.Pos, ir.OSUB, ir.NewUnaryExpr(base.Pos, ir.OLEN, a), ir.NewInt(base.Pos, 1)), nrange.Key.Type()))
609609
n.Body.Append(idx)
610610
}
611611

test/fixedbugs/issue73491.go

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// build
2+
3+
// Copyright 2025 The Go Authors. All rights reserved.
4+
// Use of this source code is governed by a BSD-style
5+
// license that can be found in the LICENSE file.
6+
7+
package main
8+
9+
type T int
10+
11+
const K T = 5
12+
13+
type P struct {
14+
a [K]*byte
15+
}
16+
17+
//go:noinline
18+
func f(p *P) {
19+
for i := range K {
20+
p.a[i] = nil
21+
}
22+
}
23+
func main() {
24+
f(nil)
25+
}

0 commit comments

Comments
 (0)