Skip to content

Commit 9f90f31

Browse files
committed
cmd/compile: allow static init for unsafe.Pointer(&x) where x is global
This avoids both a write barrier and then dynamic initialization globals of the form var x something var xp = unsafe.Pointer(&x) Using static initialization avoids emitting a relocation for &x, which helps cgo. Fixes #9411. Change-Id: I0dbf480859cce6ab57ab805d1b8609c45b48f156 Reviewed-on: https://go-review.googlesource.com/11693 Reviewed-by: Austin Clements <[email protected]> Run-TryBot: Russ Cox <[email protected]>
1 parent d6e6baa commit 9f90f31

File tree

3 files changed

+24
-4
lines changed

3 files changed

+24
-4
lines changed

src/cmd/compile/internal/gc/sinit.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,10 @@ func staticcopy(l *Node, r *Node, out **NodeList) bool {
302302
orig := r
303303
r = r.Name.Defn.Right
304304

305+
for r.Op == OCONVNOP {
306+
r = r.Left
307+
}
308+
305309
switch r.Op {
306310
case ONAME:
307311
if staticcopy(l, r, out) {
@@ -395,6 +399,10 @@ func staticcopy(l *Node, r *Node, out **NodeList) bool {
395399
func staticassign(l *Node, r *Node, out **NodeList) bool {
396400
var n1 Node
397401

402+
for r.Op == OCONVNOP {
403+
r = r.Left
404+
}
405+
398406
switch r.Op {
399407
//dump("not static", r);
400408
default:

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

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2194,13 +2194,20 @@ func needwritebarrier(l *Node, r *Node) bool {
21942194
return false
21952195
}
21962196

2197-
// No write barrier for implicit or explicit zeroing.
2198-
if r == nil || iszero(r) {
2197+
// No write barrier for implicit zeroing.
2198+
if r == nil {
21992199
return false
22002200
}
22012201

2202-
// No write barrier for initialization to constant.
2203-
if r.Op == OLITERAL {
2202+
// Ignore no-op conversions when making decision.
2203+
// Ensures that xp = unsafe.Pointer(&x) is treated
2204+
// the same as xp = &x.
2205+
for r.Op == OCONVNOP {
2206+
r = r.Left
2207+
}
2208+
2209+
// No write barrier for zeroing or initialization to constant.
2210+
if iszero(r) || r.Op == OLITERAL {
22042211
return false
22052212
}
22062213

test/sinit.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010

1111
package p
1212

13+
import "unsafe"
14+
1315
// Should be no init func in the assembly.
1416
// All these initializations should be done at link time.
1517

@@ -284,3 +286,6 @@ type Mer interface {
284286
}
285287

286288
var _ Mer = (*T1)(nil)
289+
290+
var Byte byte
291+
var PtrByte unsafe.Pointer = unsafe.Pointer(&Byte)

0 commit comments

Comments
 (0)