Go interface devirtualization — when the compiler skips convT64

Dig101: dig more, simplify more, know more.

This follows the Dig101 piece on Go interface layout.

For interface Stringer and concrete type Binary, why does conversion call convT64 while devirt does not?

1
2
3
4
5
6
7
8
9
10
11
func conversion() {
var b Stringer
var i Binary = 1
b = i // convT64
_=b.String()
}

func devirt() {
var b Stringer = Binary(1)
_ = b.String() // static call Binary.String
}

SSA dumps make the compiler steps obvious.
Example: GOSSAFUNC=main go1.14 build types/interface/interface.go produces ssa.html
SSA HTML output for interface conversion vs devirtualization

When the concrete type behind an interface is known at compile time, the optimizer can rewrite the call. See issue #19361 and CL 37751.

The original motivation included reducing GC pressure from interface calls during escape analysis (receiver and arguments escaping to the heap). That part is still open; see issue #33160. What ships today is mainly skipping convXXX and turning dynamic calls into static ones — smaller code and a small speed win.

Main compiler touchpoints:

1
2
3
4
5
6
7
8
9
10
11
12
// Record itab for pointer-shaped concrete types assigned to iface,
// so later SSA can eliminate OCONVIFACE
cmd/compile/internal/gc/subr.go:implements
if isdirectiface(t0) && !iface.IsEmptyInterface() {
itabname(t0, iface)
}
cmd/compile/internal/gc/reflect.go:itabname
itabs = append(itabs, itabEntry{t: t, itype: itype, lsym: s.Linksym()})
// Load itabs before compile
cmd/compile/internal/gc/reflect.go:peekitabs
// SSA rewrite: inline + itabs → static call, no convXXX
cmd/compile/internal/ssa/rewrite.go:devirt

Compiler pipeline overview: Go compiler README.

This helps common constructors that return an interface:

1
func New() Interface { return &impl{...} }

The concrete value must be pointer-shaped for the optimization to apply. You can rely on that when designing APIs.

More tests: devirt.go

Source: NewbMiao/Dig101-Go

Questions? Leave a comment below or email: newbvirgil@gmail.com