Debian Codegraph @

src/cmd/compile/internal/devirtualize/devirtualize.go

raw
1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package devirtualize implements two "devirtualization" optimization passes:
6 //
7 // - "Static" devirtualization which replaces interface method calls with
8 // direct concrete-type method calls where possible.
9 // - "Profile-guided" devirtualization which replaces indirect calls with a
10 // conditional direct call to the hottest concrete callee from a profile, as
11 // well as a fallback using the original indirect call.
12 package devirtualize
13
14 import (
15 "cmd/compile/internal/base"
16 "cmd/compile/internal/ir"
17 "cmd/compile/internal/typecheck"
18 "cmd/compile/internal/types"
19 )
20
21 const go126ImprovedConcreteTypeAnalysis = true
22
23 // StaticCall devirtualizes the given call if possible when the concrete callee
24 // is available statically.
25 func StaticCall(s *State, call *ir.CallExpr) {
26 // For promoted methods (including value-receiver methods promoted
27 // to pointer-receivers), the interface method wrapper may contain
28 // expressions that can panic (e.g., ODEREF, ODOTPTR,
29 // ODOTINTER). Devirtualization involves inlining these expressions
30 // (and possible panics) to the call site. This normally isn't a
31 // problem, but for go/defer statements it can move the panic from
32 // when/where the call executes to the go/defer statement itself,
33 // which is a visible change in semantics (e.g., #52072). To prevent
34 // this, we skip devirtualizing calls within go/defer statements
35 // altogether.
36 if call.GoDefer {
37 return
38 }
39
40 if call.Op() != ir.OCALLINTER {
41 return
42 }
43
44 sel := call.Fun.(*ir.SelectorExpr)
45 var typ *types.Type
46 if go126ImprovedConcreteTypeAnalysis {
47 typ = concreteType(s, sel.X)
48 if typ == nil {
49 return
50 }
51
52 // Don't create type-assertions that would be impossible at compile-time.
53 // This can happen in such case: any(0).(interface {A()}).A(), this typechecks without
54 // any errors, but will cause a runtime panic. We statically know that int(0) does not
55 // implement that interface, thus we skip the devirtualization, as it is not possible
56 // to make an assertion: any(0).(interface{A()}).(int) (int does not implement interface{A()}).
57 if !typecheck.Implements(typ, sel.X.Type()) {
58 return
59 }
60 } else {
61 r := ir.StaticValue(sel.X)
62 if r.Op() != ir.OCONVIFACE {
63 return
64 }
65 recv := r.(*ir.ConvExpr)
66 typ = recv.X.Type()
67 if typ.IsInterface() {
68 return
69 }
70 }
71
72 // If typ is a shape type, then it was a type argument originally
73 // and we'd need an indirect call through the dictionary anyway.
74 // We're unable to devirtualize this call.
75 if typ.IsShape() {
76 return
77 }
78
79 // If typ *has* a shape type, then it's a shaped, instantiated
80 // type like T[go.shape.int], and its methods (may) have an extra
81 // dictionary parameter. We could devirtualize this call if we
82 // could derive an appropriate dictionary argument.
83 //
84 // TODO(mdempsky): If typ has a promoted non-generic method,
85 // then that method won't require a dictionary argument. We could
86 // still devirtualize those calls.
87 //
88 // TODO(mdempsky): We have the *runtime.itab in recv.TypeWord. It
89 // should be possible to compute the represented type's runtime
90 // dictionary from this (e.g., by adding a pointer from T[int]'s
91 // *runtime._type to .dict.T[int]; or by recognizing static
92 // references to go:itab.T[int],iface and constructing a direct
93 // reference to .dict.T[int]).
94 if typ.HasShape() {
95 if base.Flag.LowerM != 0 {
96 base.WarnfAt(call.Pos(), "cannot devirtualize %v: shaped receiver %v", call, typ)
97 }
98 return
99 }
100
101 // Further, if sel.X's type has a shape type, then it's a shaped
102 // interface type. In this case, the (non-dynamic) TypeAssertExpr
103 // we construct below would attempt to create an itab
104 // corresponding to this shaped interface type; but the actual
105 // itab pointer in the interface value will correspond to the
106 // original (non-shaped) interface type instead. These are
107 // functionally equivalent, but they have distinct pointer
108 // identities, which leads to the type assertion failing.
109 //
110 // TODO(mdempsky): We know the type assertion here is safe, so we
111 // could instead set a flag so that walk skips the itab check. For
112 // now, punting is easy and safe.
113 if sel.X.Type().HasShape() {
114 if base.Flag.LowerM != 0 {
115 base.WarnfAt(call.Pos(), "cannot devirtualize %v: shaped interface %v", call, sel.X.Type())
116 }
117 return
118 }
119
120 dt := ir.NewTypeAssertExpr(sel.Pos(), sel.X, typ)
121
122 if go126ImprovedConcreteTypeAnalysis {
123 // Consider:
124 //
125 // var v Iface
126 // v.A()
127 // v = &Impl{}
128 //
129 // Here in the devirtualizer, we determine the concrete type of v as being an *Impl,
130 // but it can still be a nil interface, we have not detected that. The v.(*Impl)
131 // type assertion that we make here would also have failed, but with a different
132 // panic "pkg.Iface is nil, not *pkg.Impl", where previously we would get a nil panic.
133 // We fix this, by introducing an additional nilcheck on the itab.
134 // Calling a method on a nil interface (in most cases) is a bug in a program, so it is fine
135 // to devirtualize and further (possibly) inline them, even though we would never reach
136 // the called function.
137 dt.UseNilPanic = true
138 dt.SetPos(call.Pos())
139 }
140
141 x := typecheck.XDotMethod(sel.Pos(), dt, sel.Sel, true)
142 switch x.Op() {
143 case ir.ODOTMETH:
144 if base.Flag.LowerM != 0 {
145 base.WarnfAt(call.Pos(), "devirtualizing %v to %v", sel, typ)
146 }
147 call.SetOp(ir.OCALLMETH)
148 call.Fun = x
149 case ir.ODOTINTER:
150 // Promoted method from embedded interface-typed field (#42279).
151 if base.Flag.LowerM != 0 {
152 base.WarnfAt(call.Pos(), "partially devirtualizing %v to %v", sel, typ)
153 }
154 call.SetOp(ir.OCALLINTER)
155 call.Fun = x
156 default:
157 base.FatalfAt(call.Pos(), "failed to devirtualize %v (%v)", x, x.Op())
158 }
159
160 // Duplicated logic from typecheck for function call return
161 // value types.
162 //
163 // Receiver parameter size may have changed; need to update
164 // call.Type to get correct stack offsets for result
165 // parameters.
166 types.CheckSize(x.Type())
167 switch ft := x.Type(); ft.NumResults() {
168 case 0:
169 case 1:
170 call.SetType(ft.Result(0).Type)
171 default:
172 call.SetType(ft.ResultsTuple())
173 }
174
175 // Desugar OCALLMETH, if we created one (#57309).
176 typecheck.FixMethodCall(call)
177 }
178
179 const concreteTypeDebug = false
180
181 // concreteType determines the concrete type of n, following OCONVIFACEs and type asserts.
182 // Returns nil when the concrete type could not be determined, or when there are multiple
183 // (different) types assigned to an interface.
184 func concreteType(s *State, n ir.Node) (typ *types.Type) {
185 typ = concreteType1(s, n, make(map[*ir.Name]struct{}))
186 if typ == &noType {
187 return nil
188 }
189 if typ != nil && typ.IsInterface() {
190 base.FatalfAt(n.Pos(), "typ.IsInterface() = true; want = false; typ = %v", typ)
191 }
192 return typ
193 }
194
195 // noType is a sentinel value returned by [concreteType1].
196 var noType types.Type
197
198 // concreteType1 analyzes the node n and returns its concrete type if it is statically known.
199 // Otherwise, it returns a nil Type, indicating that a concrete type was not determined.
200 // When n is known to be statically nil or a self-assignment is detected, it returns a sentinel [noType] type instead.
201 func concreteType1(s *State, n ir.Node, seen map[*ir.Name]struct{}) (outT *types.Type) {
202 nn := n // for debug messages
203
204 if concreteTypeDebug {
205 defer func() {
206 t := "&noType"
207 if outT != &noType {
208 t = outT.String()
209 }
210 base.Warn("concreteType1(%v) -> %v", nn, t)
211 }()
212 }
213
214 for {
215 if concreteTypeDebug {
216 base.Warn("concreteType1(%v): analyzing %v", nn, n)
217 }
218
219 if !n.Type().IsInterface() {
220 return n.Type()
221 }
222
223 switch n1 := n.(type) {
224 case *ir.ConvExpr:
225 if n1.Op() == ir.OCONVNOP {
226 if !n1.Type().IsInterface() || !types.Identical(n1.Type().Underlying(), n1.X.Type().Underlying()) {
227 // As we check (directly before this switch) whether n is an interface, thus we should only reach
228 // here for iface conversions where both operands are the same.
229 base.FatalfAt(n1.Pos(), "not identical/interface types found n1.Type = %v; n1.X.Type = %v", n1.Type(), n1.X.Type())
230 }
231 n = n1.X
232 continue
233 }
234 if n1.Op() == ir.OCONVIFACE {
235 n = n1.X
236 continue
237 }
238 case *ir.InlinedCallExpr:
239 if n1.Op() == ir.OINLCALL {
240 n = n1.SingleResult()
241 continue
242 }
243 case *ir.ParenExpr:
244 n = n1.X
245 continue
246 case *ir.TypeAssertExpr:
247 n = n1.X
248 continue
249 }
250 break
251 }
252
253 if n.Op() != ir.ONAME {
254 return nil
255 }
256
257 name := n.(*ir.Name).Canonical()
258 if name.Class != ir.PAUTO {
259 return nil
260 }
261
262 if name.Op() != ir.ONAME {
263 base.FatalfAt(name.Pos(), "name.Op = %v; want = ONAME", n.Op())
264 }
265
266 // name.Curfn must be set, as we checked name.Class != ir.PAUTO before.
267 if name.Curfn == nil {
268 base.FatalfAt(name.Pos(), "name.Curfn = nil; want not nil")
269 }
270
271 if name.Addrtaken() {
272 return nil // conservatively assume it's reassigned with a different type indirectly
273 }
274
275 if _, ok := seen[name]; ok {
276 return &noType // Already analyzed assignments to name, no need to do that twice.
277 }
278 seen[name] = struct{}{}
279
280 if concreteTypeDebug {
281 base.Warn("concreteType1(%v): analyzing assignments to %v", nn, name)
282 }
283
284 var typ *types.Type
285 for _, v := range s.assignments(name) {
286 var t *types.Type
287 switch v := v.(type) {
288 case *types.Type:
289 t = v
290 case ir.Node:
291 t = concreteType1(s, v, seen)
292 if t == &noType {
293 continue
294 }
295 }
296 if t == nil {
297 return nil // unknown concrete type
298 }
299
300 // Methods are only declared on named types, and each named type
301 // is represented by a unique [*types.Type], thus pointer comparison
302 // is fine here.
303 //
304 // The only scenario where [types.IdenticalStrict] could help here is with
305 // unnamed struct types that embed another type (e.g. foo = struct { Impl }{}).
306 // However, such patterns are uncommon and not worth the additional complexity
307 // in the devirtualizer.
308 if typ != nil && typ != t {
309 return nil // assigned with a different type
310 }
311
312 typ = t
313 }
314
315 if typ == nil {
316 // Variable either declared with zero value, or only assigned with nil.
317 return &noType
318 }
319
320 return typ
321 }
322
323 // assignment can be one of:
324 // - nil - assignment from an interface type.
325 // - *types.Type - assignment from a concrete type (non-interface).
326 // - ir.Node - assignment from an ir.Node.
327 //
328 // In most cases assignment should be an [ir.Node], but in cases where we
329 // do not follow the data-flow, we return either a concrete type (*types.Type) or a nil.
330 // For example in range over a slice, if the slice elem is of an interface type, then we return
331 // a nil, otherwise the elem's concrete type (We do so because we do not analyze assignment to the
332 // slice being ranged-over).
333 type assignment any
334
335 // State holds precomputed state for use in [StaticCall].
336 type State struct {
337 // ifaceAssignments maps interface variables to all their assignments
338 // defined inside functions stored in the analyzedFuncs set.
339 // Note: it does not include direct assignments to nil.
340 ifaceAssignments map[*ir.Name][]assignment
341
342 // ifaceCallExprAssigns stores every [*ir.CallExpr], which has an interface
343 // result, that is assigned to a variable.
344 ifaceCallExprAssigns map[*ir.CallExpr][]ifaceAssignRef
345
346 // analyzedFuncs is a set of Funcs that were analyzed for iface assignments.
347 analyzedFuncs map[*ir.Func]struct{}
348 }
349
350 type ifaceAssignRef struct {
351 name *ir.Name // ifaceAssignments[name]
352 assignmentIndex int // ifaceAssignments[name][assignmentIndex]
353 returnIndex int // (*ir.CallExpr).Result(returnIndex)
354 }
355
356 // InlinedCall updates the [State] to take into account a newly inlined call.
357 func (s *State) InlinedCall(fun *ir.Func, origCall *ir.CallExpr, inlinedCall *ir.InlinedCallExpr) {
358 if _, ok := s.analyzedFuncs[fun]; !ok {
359 // Full analyze has not been yet executed for the provided function, so we can skip it for now.
360 // When no devirtualization happens in a function, it is unnecessary to analyze it.
361 return
362 }
363
364 // Analyze assignments in the newly inlined function.
365 s.analyze(inlinedCall.Init())
366 s.analyze(inlinedCall.Body)
367
368 refs, ok := s.ifaceCallExprAssigns[origCall]
369 if !ok {
370 return
371 }
372 delete(s.ifaceCallExprAssigns, origCall)
373
374 // Update assignments to reference the new ReturnVars of the inlined call.
375 for _, ref := range refs {
376 vt := &s.ifaceAssignments[ref.name][ref.assignmentIndex]
377 if *vt != nil {
378 base.Fatalf("unexpected non-nil assignment")
379 }
380 if concreteTypeDebug {
381 base.Warn(
382 "InlinedCall(%v, %v): replacing interface node in (%v,%v) to %v (typ %v)",
383 origCall, inlinedCall, ref.name, ref.assignmentIndex,
384 inlinedCall.ReturnVars[ref.returnIndex],
385 inlinedCall.ReturnVars[ref.returnIndex].Type(),
386 )
387 }
388
389 // Update ifaceAssignments with an ir.Node from the inlined function’s ReturnVars.
390 // This may enable future devirtualization of calls that reference ref.name.
391 // We will get calls to [StaticCall] from the interleaved package,
392 // to try devirtualize such calls afterwards.
393 *vt = inlinedCall.ReturnVars[ref.returnIndex]
394 }
395 }
396
397 // assignments returns all assignments to n.
398 func (s *State) assignments(n *ir.Name) []assignment {
399 fun := n.Curfn
400 if fun == nil {
401 base.FatalfAt(n.Pos(), "n.Curfn = <nil>")
402 }
403 if n.Class != ir.PAUTO {
404 base.FatalfAt(n.Pos(), "n.Class = %v; want = PAUTO", n.Class)
405 }
406
407 if !n.Type().IsInterface() {
408 base.FatalfAt(n.Pos(), "name passed to assignments is not of an interface type: %v", n.Type())
409 }
410
411 // Analyze assignments in func, if not analyzed before.
412 if _, ok := s.analyzedFuncs[fun]; !ok {
413 if concreteTypeDebug {
414 base.Warn("assignments(): analyzing assignments in %v func", fun)
415 }
416 if s.analyzedFuncs == nil {
417 s.ifaceAssignments = make(map[*ir.Name][]assignment)
418 s.ifaceCallExprAssigns = make(map[*ir.CallExpr][]ifaceAssignRef)
419 s.analyzedFuncs = make(map[*ir.Func]struct{})
420 }
421 s.analyzedFuncs[fun] = struct{}{}
422 s.analyze(fun.Init())
423 s.analyze(fun.Body)
424 }
425
426 return s.ifaceAssignments[n]
427 }
428
429 // analyze analyzes every assignment to interface variables in nodes, updating [State].
430 func (s *State) analyze(nodes ir.Nodes) {
431 assign := func(name ir.Node, assignment assignment) (*ir.Name, int) {
432 if name == nil || name.Op() != ir.ONAME || ir.IsBlank(name) {
433 return nil, -1
434 }
435
436 n, ok := ir.OuterValue(name).(*ir.Name)
437 if !ok || n.Curfn == nil {
438 return nil, -1
439 }
440
441 // Do not track variables that are not of interface types.
442 // For devirtualization they are unnecessary, we will not even look them up.
443 if !n.Type().IsInterface() {
444 return nil, -1
445 }
446
447 n = n.Canonical()
448 if n.Op() != ir.ONAME {
449 base.FatalfAt(n.Pos(), "n.Op = %v; want = ONAME", n.Op())
450 }
451 if n.Class != ir.PAUTO {
452 return nil, -1
453 }
454
455 switch a := assignment.(type) {
456 case nil:
457 case *types.Type:
458 if a != nil && a.IsInterface() {
459 assignment = nil // non-concrete type
460 }
461 case ir.Node:
462 // nil assignment, we can safely ignore them, see [StaticCall].
463 if ir.IsNil(a) {
464 return nil, -1
465 }
466 default:
467 base.Fatalf("unexpected type: %v", assignment)
468 }
469
470 if concreteTypeDebug {
471 base.Warn("analyze(): assignment found %v = %v", name, assignment)
472 }
473
474 s.ifaceAssignments[n] = append(s.ifaceAssignments[n], assignment)
475 return n, len(s.ifaceAssignments[n]) - 1
476 }
477
478 var do func(n ir.Node)
479 do = func(n ir.Node) {
480 switch n.Op() {
481 case ir.OAS:
482 n := n.(*ir.AssignStmt)
483 if rhs := n.Y; rhs != nil {
484 for {
485 if r, ok := rhs.(*ir.ParenExpr); ok {
486 rhs = r.X
487 continue
488 }
489 break
490 }
491 if call, ok := rhs.(*ir.CallExpr); ok && call.Fun != nil {
492 retTyp := call.Fun.Type().Results()[0].Type
493 n, idx := assign(n.X, retTyp)
494 if n != nil && retTyp.IsInterface() {
495 // We have a call expression, that returns an interface, store it for later evaluation.
496 // In case this func gets inlined later, we will update the assignment (added before)
497 // with a reference to ReturnVars, see [State.InlinedCall], which might allow for future devirtualizing of n.X.
498 s.ifaceCallExprAssigns[call] = append(s.ifaceCallExprAssigns[call], ifaceAssignRef{n, idx, 0})
499 }
500 } else {
501 assign(n.X, rhs)
502 }
503 }
504 case ir.OAS2:
505 n := n.(*ir.AssignListStmt)
506 for i, p := range n.Lhs {
507 if n.Rhs[i] != nil {
508 assign(p, n.Rhs[i])
509 }
510 }
511 case ir.OAS2DOTTYPE:
512 n := n.(*ir.AssignListStmt)
513 if n.Rhs[0] == nil {
514 base.FatalfAt(n.Pos(), "n.Rhs[0] == nil; n = %v", n)
515 }
516 assign(n.Lhs[0], n.Rhs[0])
517 assign(n.Lhs[1], nil) // boolean does not have methods to devirtualize
518 case ir.OAS2MAPR, ir.OAS2RECV, ir.OSELRECV2:
519 n := n.(*ir.AssignListStmt)
520 if n.Rhs[0] == nil {
521 base.FatalfAt(n.Pos(), "n.Rhs[0] == nil; n = %v", n)
522 }
523 assign(n.Lhs[0], n.Rhs[0].Type())
524 assign(n.Lhs[1], nil) // boolean does not have methods to devirtualize
525 case ir.OAS2FUNC:
526 n := n.(*ir.AssignListStmt)
527 rhs := n.Rhs[0]
528 for {
529 if r, ok := rhs.(*ir.ParenExpr); ok {
530 rhs = r.X
531 continue
532 }
533 break
534 }
535 if call, ok := rhs.(*ir.CallExpr); ok {
536 for i, p := range n.Lhs {
537 retTyp := call.Fun.Type().Results()[i].Type
538 n, idx := assign(p, retTyp)
539 if n != nil && retTyp.IsInterface() {
540 // We have a call expression, that returns an interface, store it for later evaluation.
541 // In case this func gets inlined later, we will update the assignment (added before)
542 // with a reference to ReturnVars, see [State.InlinedCall], which might allow for future devirtualizing of n.X.
543 s.ifaceCallExprAssigns[call] = append(s.ifaceCallExprAssigns[call], ifaceAssignRef{n, idx, i})
544 }
545 }
546 } else if call, ok := rhs.(*ir.InlinedCallExpr); ok {
547 for i, p := range n.Lhs {
548 assign(p, call.ReturnVars[i])
549 }
550 } else {
551 base.FatalfAt(n.Pos(), "unexpected type %T in OAS2FUNC Rhs[0]", call)
552 }
553 case ir.ORANGE:
554 n := n.(*ir.RangeStmt)
555 xTyp := n.X.Type()
556
557 // Range over an array pointer.
558 if xTyp.IsPtr() && xTyp.Elem().IsArray() {
559 xTyp = xTyp.Elem()
560 }
561
562 if xTyp.IsArray() || xTyp.IsSlice() {
563 assign(n.Key, nil) // integer does not have methods to devirtualize
564 assign(n.Value, xTyp.Elem())
565 } else if xTyp.IsChan() {
566 assign(n.Key, xTyp.Elem())
567 base.AssertfAt(n.Value == nil, n.Pos(), "n.Value != nil in range over chan")
568 } else if xTyp.IsMap() {
569 assign(n.Key, xTyp.Key())
570 assign(n.Value, xTyp.Elem())
571 } else if xTyp.IsInteger() || xTyp.IsString() {
572 // Range over int/string, results do not have methods, so nothing to devirtualize.
573 assign(n.Key, nil)
574 assign(n.Value, nil)
575 } else {
576 // We will not reach here in case of a range-over-func, as it is
577 // rewritten to function calls in the noder package.
578 base.FatalfAt(n.Pos(), "range over unexpected type %v", n.X.Type())
579 }
580 case ir.OSWITCH:
581 n := n.(*ir.SwitchStmt)
582 if guard, ok := n.Tag.(*ir.TypeSwitchGuard); ok {
583 for _, v := range n.Cases {
584 if v.Var == nil {
585 base.Assert(guard.Tag == nil)
586 continue
587 }
588 assign(v.Var, guard.X)
589 }
590 }
591 case ir.OCLOSURE:
592 n := n.(*ir.ClosureExpr)
593 if _, ok := s.analyzedFuncs[n.Func]; !ok {
594 s.analyzedFuncs[n.Func] = struct{}{}
595 ir.Visit(n.Func, do)
596 }
597 }
598 }
599 ir.VisitList(nodes, do)
600 }