Skip to content

Commit adc0cae

Browse files
committed
compiler: add //go:linkname support for globals
We previously used our own //go:extern but //go:linkname is probably the better choice since it's used in the math/bits package.
1 parent 38e3d55 commit adc0cae

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

compiler/symbol.go

+7-2
Original file line numberDiff line numberDiff line change
@@ -688,20 +688,25 @@ func (c *compilerContext) getGlobalInfo(g *ssa.Global) globalInfo {
688688
// Check for //go: pragmas, which may change the link name (among others).
689689
doc := c.astComments[info.linkName]
690690
if doc != nil {
691-
info.parsePragmas(doc)
691+
info.parsePragmas(doc, g)
692692
}
693693
return info
694694
}
695695

696696
// Parse //go: pragma comments from the source. In particular, it parses the
697697
// //go:extern pragma on globals.
698-
func (info *globalInfo) parsePragmas(doc *ast.CommentGroup) {
698+
func (info *globalInfo) parsePragmas(doc *ast.CommentGroup, g *ssa.Global) {
699699
for _, comment := range doc.List {
700700
if !strings.HasPrefix(comment.Text, "//go:") {
701701
continue
702702
}
703703
parts := strings.Fields(comment.Text)
704704
switch parts[0] {
705+
case "//go:linkname":
706+
if len(parts) == 3 && g.Name() == parts[1] {
707+
info.linkName = parts[2]
708+
info.extern = true
709+
}
705710
case "//go:extern":
706711
info.extern = true
707712
if len(parts) == 2 {

compiler/testdata/pragma.go

+6
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@ package main
22

33
import _ "unsafe"
44

5+
// Use the go:linkname mechanism to link this global to a different package.
6+
// This is used in math/bits.
7+
//
8+
//go:linkname linknamedGlobal runtime.testLinknamedGlobal
9+
var linknamedGlobal int
10+
511
// Creates an external global with name extern_global.
612
//
713
//go:extern extern_global

compiler/testdata/pragma.ll

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ source_filename = "pragma.go"
33
target datalayout = "e-m:e-p:32:32-p10:8:8-p20:8:8-i64:64-n32:64-S128-ni:1:10:20"
44
target triple = "wasm32-unknown-wasi"
55

6+
@runtime.testLinknamedGlobal = external global i32, align 4
67
@extern_global = external global [0 x i8], align 1
78
@main.alignedGlobal = hidden global [4 x i32] zeroinitializer, align 32
89
@main.alignedGlobal16 = hidden global [4 x i32] zeroinitializer, align 16

0 commit comments

Comments
 (0)