1 // Copyright 2011 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.
5 // The inlining facility makes 2 passes: first caninl determines which
6 // functions are suitable for inlining, and for those that are it
7 // saves a copy of the body. Then InlineCalls walks each function body to
8 // expand calls to inlinable functions.
10 // The Debug.l flag controls the aggressiveness. Note that main() swaps level 0 and 1,
11 // making 1 the default and -l disable. Additional levels (beyond -l) may be buggy and
14 // 1: 80-nodes leaf functions, oneliners, panic, lazy typechecking (default)
17 // 4: allow non-leaf functions
19 // At some point this may get another default and become switch-offable with -N.
21 // The -d typcheckinl flag enables early typechecking of all imported bodies,
22 // which is useful to flush out bugs.
24 // The Debug.m flag enables diagnostic output. a single -m is useful for verifying
25 // which calls get inlined or not, more is for debugging, and may go away at any point.
34 "cmd/compile/internal/base"
35 "cmd/compile/internal/ir"
36 "cmd/compile/internal/logopt"
37 "cmd/compile/internal/typecheck"
38 "cmd/compile/internal/types"
43 // Inlining budget parameters, gathered in one place
46 inlineExtraAppendCost = 0
47 // default is to inline if there's at most one call. -l=4 overrides this by using 1 instead.
48 inlineExtraCallCost = 57 // 57 was benchmarked to provided most benefit with no bad surprises; see https://github.com/golang/go/issues/19348#issuecomment-439370742
49 inlineExtraPanicCost = 1 // do not penalize inlining panics.
50 inlineExtraThrowCost = inlineMaxBudget // with current (2018-05/1.11) code, inlining runtime.throw does not help.
52 inlineBigFunctionNodes = 5000 // Functions with this many nodes are considered "big".
53 inlineBigFunctionMaxCost = 20 // Max cost of inlinee when inlining into a "big" function.
56 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
57 func InlinePackage() {
58 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
59 numfns := numNonClosures(list)
60 for _, n := range list {
61 if !recursive || numfns > 1 {
62 // We allow inlining if there is no
63 // recursion, or the recursion cycle is
64 // across more than one function.
67 if base.Flag.LowerM > 1 {
68 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
76 // CanInline determines whether fn is inlineable.
77 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
78 // fn and fn.Body will already have been typechecked.
79 func CanInline(fn *ir.Func) {
81 base.Fatalf("CanInline no nname %+v", fn)
84 var reason string // reason, if any, that the function was not inlined
85 if base.Flag.LowerM > 1 || logopt.Enabled() {
88 if base.Flag.LowerM > 1 {
89 fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
92 logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
98 // If marked "go:noinline", don't inline
99 if fn.Pragma&ir.Noinline != 0 {
100 reason = "marked go:noinline"
104 // If marked "go:norace" and -race compilation, don't inline.
105 if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
106 reason = "marked go:norace with -race compilation"
110 // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
111 if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
112 reason = "marked go:nocheckptr"
116 // If marked "go:cgo_unsafe_args", don't inline, since the
117 // function makes assumptions about its argument frame layout.
118 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
119 reason = "marked go:cgo_unsafe_args"
123 // If marked as "go:uintptrkeepalive", don't inline, since the
124 // keep alive information is lost during inlining.
126 // TODO(prattmic): This is handled on calls during escape analysis,
127 // which is after inlining. Move prior to inlining so the keep-alive is
128 // maintained after inlining.
129 if fn.Pragma&ir.UintptrKeepAlive != 0 {
130 reason = "marked as having a keep-alive uintptr argument"
134 // If marked as "go:uintptrescapes", don't inline, since the
135 // escape information is lost during inlining.
136 if fn.Pragma&ir.UintptrEscapes != 0 {
137 reason = "marked as having an escaping uintptr argument"
141 // The nowritebarrierrec checker currently works at function
142 // granularity, so inlining yeswritebarrierrec functions can
143 // confuse it (#22342). As a workaround, disallow inlining
145 if fn.Pragma&ir.Yeswritebarrierrec != 0 {
146 reason = "marked go:yeswritebarrierrec"
150 // If fn has no body (is defined outside of Go), cannot inline it.
151 if len(fn.Body) == 0 {
152 reason = "no function body"
156 if fn.Typecheck() == 0 {
157 base.Fatalf("CanInline on non-typechecked function %v", fn)
161 if n.Func.InlinabilityChecked() {
164 defer n.Func.SetInlinabilityChecked(true)
166 cc := int32(inlineExtraCallCost)
167 if base.Flag.LowerL == 4 {
168 cc = 1 // this appears to yield better performance than 0.
171 // At this point in the game the function we're looking at may
172 // have "stale" autos, vars that still appear in the Dcl list, but
173 // which no longer have any uses in the function body (due to
174 // elimination by deadcode). We'd like to exclude these dead vars
175 // when creating the "Inline.Dcl" field below; to accomplish this,
176 // the hairyVisitor below builds up a map of used/referenced
177 // locals, and we use this map to produce a pruned Inline.Dcl
178 // list. See issue 25249 for more context.
180 visitor := hairyVisitor{
181 budget: inlineMaxBudget,
184 if visitor.tooHairy(fn) {
185 reason = visitor.reason
189 n.Func.Inl = &ir.Inline{
190 Cost: inlineMaxBudget - visitor.budget,
191 Dcl: pruneUnusedAutos(n.Defn.(*ir.Func).Dcl, &visitor),
192 Body: inlcopylist(fn.Body),
194 CanDelayResults: canDelayResults(fn),
197 if base.Flag.LowerM > 1 {
198 fmt.Printf("%v: can inline %v with cost %d as: %v { %v }\n", ir.Line(fn), n, inlineMaxBudget-visitor.budget, fn.Type(), ir.Nodes(n.Func.Inl.Body))
199 } else if base.Flag.LowerM != 0 {
200 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
202 if logopt.Enabled() {
203 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", inlineMaxBudget-visitor.budget))
207 // canDelayResults reports whether inlined calls to fn can delay
208 // declaring the result parameter until the "return" statement.
209 func canDelayResults(fn *ir.Func) bool {
210 // We can delay declaring+initializing result parameters if:
211 // (1) there's exactly one "return" statement in the inlined function;
212 // (2) it's not an empty return statement (#44355); and
213 // (3) the result parameters aren't named.
216 ir.VisitList(fn.Body, func(n ir.Node) {
217 if n, ok := n.(*ir.ReturnStmt); ok {
219 if len(n.Results) == 0 {
220 nreturns++ // empty return statement (case 2)
226 return false // not exactly one return statement (case 1)
229 // temporaries for return values.
230 for _, param := range fn.Type().Results().FieldSlice() {
231 if sym := types.OrigSym(param.Sym); sym != nil && !sym.IsBlank() {
232 return false // found a named result parameter (case 3)
239 // hairyVisitor visits a function body to determine its inlining
240 // hairiness and whether or not it can be inlined.
241 type hairyVisitor struct {
245 usedLocals ir.NameSet
246 do func(ir.Node) bool
249 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
250 v.do = v.doNode // cache closure
251 if ir.DoChildren(fn, v.do) {
255 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", inlineMaxBudget-v.budget, inlineMaxBudget)
261 func (v *hairyVisitor) doNode(n ir.Node) bool {
266 // Call is okay if inlinable and we have the budget for the body.
268 n := n.(*ir.CallExpr)
269 // Functions that call runtime.getcaller{pc,sp} can not be inlined
270 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
272 // runtime.throw is a "cheap call" like panic in normal code.
273 if n.X.Op() == ir.ONAME {
274 name := n.X.(*ir.Name)
275 if name.Class == ir.PFUNC && types.IsRuntimePkg(name.Sym().Pkg) {
276 fn := name.Sym().Name
277 if fn == "getcallerpc" || fn == "getcallersp" {
278 v.reason = "call to " + fn
282 v.budget -= inlineExtraThrowCost
287 if n.X.Op() == ir.OMETHEXPR {
288 if meth := ir.MethodExprName(n.X); meth != nil {
289 if fn := meth.Func; fn != nil {
292 if types.IsRuntimePkg(s.Pkg) && s.Name == "heapBits.nextArena" {
293 // Special case: explicitly allow mid-stack inlining of
294 // runtime.heapBits.next even though it calls slow-path
295 // runtime.heapBits.nextArena.
298 // Special case: on architectures that can do unaligned loads,
299 // explicitly mark encoding/binary methods as cheap,
300 // because in practice they are, even though our inlining
301 // budgeting system does not see that. See issue 42958.
302 if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
304 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
305 "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
306 "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
307 "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16":
312 break // treat like any other node, that is, cost of 1
318 if ir.IsIntrinsicCall(n) {
319 // Treat like any other node.
323 if fn := inlCallee(n.X); fn != nil && typecheck.HaveInlineBody(fn) {
324 v.budget -= fn.Inl.Cost
328 // Call cost for non-leaf inlining.
329 v.budget -= v.extraCallCost
332 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
334 // Things that are too hairy, irrespective of the budget
335 case ir.OCALL, ir.OCALLINTER:
336 // Call cost for non-leaf inlining.
337 v.budget -= v.extraCallCost
340 n := n.(*ir.UnaryExpr)
341 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
342 // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
343 // Before CL 284412, these conversions were introduced later in the
344 // compiler, so they didn't count against inlining budget.
347 v.budget -= inlineExtraPanicCost
350 // recover matches the argument frame pointer to find
351 // the right panic value, so it needs an argument frame.
352 v.reason = "call to recover"
356 if base.Debug.InlFuncsWithClosures == 0 {
357 v.reason = "not inlining functions with closures"
361 // TODO(danscales): Maybe make budget proportional to number of closure
363 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
365 // Scan body of closure (which DoChildren doesn't automatically
366 // do) to check for disallowed ops in the body and include the
367 // body in the budget.
368 if doList(n.(*ir.ClosureExpr).Func.Body, v.do) {
374 ir.ODCLTYPE, // can't print yet
376 v.reason = "unhandled op " + n.Op().String()
380 v.budget -= inlineExtraAppendCost
383 // *(*X)(unsafe.Pointer(&x)) is low-cost
384 n := n.(*ir.StarExpr)
387 for ptr.Op() == ir.OCONVNOP {
388 ptr = ptr.(*ir.ConvExpr).X
390 if ptr.Op() == ir.OADDR {
391 v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
395 // This doesn't produce code, but the children might.
396 v.budget++ // undo default cost
398 case ir.ODCLCONST, ir.OFALL:
399 // These nodes don't produce code; omit from inlining budget.
404 if ir.IsConst(n.Cond, constant.Bool) {
405 // This if and the condition cost nothing.
406 if doList(n.Init(), v.do) {
409 if ir.BoolVal(n.Cond) {
410 return doList(n.Body, v.do)
412 return doList(n.Else, v.do)
418 if n.Class == ir.PAUTO {
423 // The only OBLOCK we should see at this point is an empty one.
424 // In any event, let the visitList(n.List()) below take care of the statements,
425 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
428 case ir.OMETHVALUE, ir.OSLICELIT:
429 v.budget-- // Hack for toolstash -cmp.
432 v.budget++ // Hack for toolstash -cmp.
437 // When debugging, don't stop early, to get full cost of inlining this function
438 if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
439 v.reason = "too expensive"
443 return ir.DoChildren(n, v.do)
446 func isBigFunc(fn *ir.Func) bool {
447 budget := inlineBigFunctionNodes
448 return ir.Any(fn, func(n ir.Node) bool {
454 // inlcopylist (together with inlcopy) recursively copies a list of nodes, except
455 // that it keeps the same ONAME, OTYPE, and OLITERAL nodes. It is used for copying
456 // the body and dcls of an inlineable function.
457 func inlcopylist(ll []ir.Node) []ir.Node {
458 s := make([]ir.Node, len(ll))
459 for i, n := range ll {
465 // inlcopy is like DeepCopy(), but does extra work to copy closures.
466 func inlcopy(n ir.Node) ir.Node {
467 var edit func(ir.Node) ir.Node
468 edit = func(x ir.Node) ir.Node {
470 case ir.ONAME, ir.OTYPE, ir.OLITERAL, ir.ONIL:
474 ir.EditChildren(m, edit)
475 if x.Op() == ir.OCLOSURE {
476 x := x.(*ir.ClosureExpr)
477 // Need to save/duplicate x.Func.Nname,
478 // x.Func.Nname.Ntype, x.Func.Dcl, x.Func.ClosureVars, and
479 // x.Func.Body for iexport and local inlining.
481 newfn := ir.NewFunc(oldfn.Pos())
482 m.(*ir.ClosureExpr).Func = newfn
483 newfn.Nname = ir.NewNameAt(oldfn.Nname.Pos(), oldfn.Nname.Sym())
484 // XXX OK to share fn.Type() ??
485 newfn.Nname.SetType(oldfn.Nname.Type())
486 newfn.Body = inlcopylist(oldfn.Body)
487 // Make shallow copy of the Dcl and ClosureVar slices
488 newfn.Dcl = append([]*ir.Name(nil), oldfn.Dcl...)
489 newfn.ClosureVars = append([]*ir.Name(nil), oldfn.ClosureVars...)
496 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
497 // calls made to inlineable functions. This is the external entry point.
498 func InlineCalls(fn *ir.Func) {
501 maxCost := int32(inlineMaxBudget)
503 maxCost = inlineBigFunctionMaxCost
505 // Map to keep track of functions that have been inlined at a particular
506 // call site, in order to stop inlining when we reach the beginning of a
507 // recursion cycle again. We don't inline immediately recursive functions,
508 // but allow inlining if there is a recursion cycle of many functions.
509 // Most likely, the inlining will stop before we even hit the beginning of
510 // the cycle again, but the map catches the unusual case.
511 inlMap := make(map[*ir.Func]bool)
512 var edit func(ir.Node) ir.Node
513 edit = func(n ir.Node) ir.Node {
514 return inlnode(n, maxCost, inlMap, edit)
516 ir.EditChildren(fn, edit)
520 // inlnode recurses over the tree to find inlineable calls, which will
521 // be turned into OINLCALLs by mkinlcall. When the recursion comes
522 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
523 // nbody and nelse and use one of the 4 inlconv/glue functions above
524 // to turn the OINLCALL into an expression, a statement, or patch it
525 // in to this nodes list or rlist as appropriate.
526 // NOTE it makes no sense to pass the glue functions down the
527 // recursion to the level where the OINLCALL gets created because they
528 // have to edit /this/ n, so you'd have to push that one down as well,
529 // but then you may as well do it here. so this is cleaner and
530 // shorter and less complicated.
531 // The result of inlnode MUST be assigned back to n, e.g.
533 // n.Left = inlnode(n.Left)
534 func inlnode(n ir.Node, maxCost int32, inlMap map[*ir.Func]bool, edit func(ir.Node) ir.Node) ir.Node {
540 case ir.ODEFER, ir.OGO:
541 n := n.(*ir.GoDeferStmt)
542 switch call := n.Call; call.Op() {
544 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
546 call := call.(*ir.CallExpr)
550 n := n.(*ir.TailCallStmt)
551 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
553 // TODO do them here (or earlier),
554 // so escape analysis can avoid more heapmoves.
558 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
560 n := n.(*ir.CallExpr)
561 if n.X.Op() == ir.OMETHEXPR {
562 // Prevent inlining some reflect.Value methods when using checkptr,
563 // even when package reflect was compiled without it (#35073).
564 if meth := ir.MethodExprName(n.X); meth != nil {
566 if base.Debug.Checkptr != 0 && types.IsReflectPkg(s.Pkg) && (s.Name == "Value.UnsafeAddr" || s.Name == "Value.Pointer") {
575 ir.EditChildren(n, edit)
577 // with all the branches out of the way, it is now time to
578 // transmogrify this node itself unless inhibited by the
579 // switch at the top of this function.
582 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
585 call := n.(*ir.CallExpr)
589 if base.Flag.LowerM > 3 {
590 fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.X)
592 if ir.IsIntrinsicCall(call) {
595 if fn := inlCallee(call.X); fn != nil && typecheck.HaveInlineBody(fn) {
596 n = mkinlcall(call, fn, maxCost, inlMap, edit)
605 // inlCallee takes a function-typed expression and returns the underlying function ONAME
606 // that it refers to if statically known. Otherwise, it returns nil.
607 func inlCallee(fn ir.Node) *ir.Func {
608 fn = ir.StaticValue(fn)
611 fn := fn.(*ir.SelectorExpr)
612 n := ir.MethodExprName(fn)
613 // Check that receiver type matches fn.X.
614 // TODO(mdempsky): Handle implicit dereference
615 // of pointer receiver argument?
616 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
622 if fn.Class == ir.PFUNC {
626 fn := fn.(*ir.ClosureExpr)
634 func inlParam(t *types.Field, as ir.InitNode, inlvars map[*ir.Name]*ir.Name) ir.Node {
638 n := t.Nname.(*ir.Name)
644 base.Fatalf("missing inlvar for %v", n)
646 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, inlvar))
647 inlvar.Name().Defn = as
653 // SSADumpInline gives the SSA back end a chance to dump the function
654 // when producing output for debugging the compiler itself.
655 var SSADumpInline = func(*ir.Func) {}
657 // NewInline allows the inliner implementation to be overridden.
658 // If it returns nil, the legacy inliner will handle this call
660 var NewInline = func(call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr { return nil }
662 // If n is a OCALLFUNC node, and fn is an ONAME node for a
663 // function with an inlinable body, return an OINLCALL node that can replace n.
664 // The returned node's Ninit has the parameter assignments, the Nbody is the
665 // inlined function body, and (List, Rlist) contain the (input, output)
667 // The result of mkinlcall MUST be assigned back to n, e.g.
669 // n.Left = mkinlcall(n.Left, fn, isddd)
670 func mkinlcall(n *ir.CallExpr, fn *ir.Func, maxCost int32, inlMap map[*ir.Func]bool, edit func(ir.Node) ir.Node) ir.Node {
672 if logopt.Enabled() {
673 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
674 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(fn)))
678 if fn.Inl.Cost > maxCost {
679 // The inlined function body is too big. Typically we use this check to restrict
680 // inlining into very big functions. See issue 26546 and 17566.
681 if logopt.Enabled() {
682 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
683 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), maxCost))
688 if fn == ir.CurFunc {
689 // Can't recursively inline a function into itself.
690 if logopt.Enabled() {
691 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(ir.CurFunc)))
696 // Don't inline a function fn that has no shape parameters, but is passed at
697 // least one shape arg. This means we must be inlining a non-generic function
698 // fn that was passed into a generic function, and can be called with a shape
699 // arg because it matches an appropriate type parameters. But fn may include
700 // an interface conversion (that may be applied to a shape arg) that was not
701 // apparent when we first created the instantiation of the generic function.
702 // We can't handle this if we actually do the inlining, since we want to know
703 // all interface conversions immediately after stenciling. So, we avoid
704 // inlining in this case, see issue #49309. (1)
706 // See discussion on go.dev/cl/406475 for more background.
707 if !fn.Type().Params().HasShape() {
708 for _, arg := range n.Args {
709 if arg.Type().HasShape() {
710 if logopt.Enabled() {
711 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
712 fmt.Sprintf("inlining function %v has no-shape params with shape args", ir.FuncName(fn)))
718 // Don't inline a function fn that has shape parameters, but is passed no shape arg.
719 // See comments (1) above, and issue #51909.
720 inlineable := len(n.Args) == 0 // Function has shape in type, with no arguments can always be inlined.
721 for _, arg := range n.Args {
722 if arg.Type().HasShape() {
728 if logopt.Enabled() {
729 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
730 fmt.Sprintf("inlining function %v has shape params with no-shape args", ir.FuncName(fn)))
736 if base.Flag.Cfg.Instrumenting && types.IsRuntimePkg(fn.Sym().Pkg) {
737 // Runtime package must not be instrumented.
738 // Instrument skips runtime package. However, some runtime code can be
739 // inlined into other packages and instrumented there. To avoid this,
740 // we disable inlining of runtime functions when instrumenting.
741 // The example that we observed is inlining of LockOSThread,
742 // which lead to false race reports on m contents.
747 if base.Flag.LowerM > 1 {
748 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), fn, ir.FuncName(ir.CurFunc))
757 typecheck.FixVariadicCall(n)
759 parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
762 inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym)
764 if base.Flag.GenDwarfInl > 0 {
765 if !sym.WasInlined() {
766 base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
767 sym.Set(obj.AttrWasInlined, true)
771 if base.Flag.LowerM != 0 {
772 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
774 if base.Flag.LowerM > 2 {
775 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
778 res := NewInline(n, fn, inlIndex)
780 res = oldInline(n, fn, inlIndex)
783 // transitive inlining
784 // might be nice to do this before exporting the body,
785 // but can't emit the body with inlining expanded.
786 // instead we emit the things that the body needs
787 // and each use must redo the inlining.
788 // luckily these are small.
789 ir.EditChildren(res, edit)
791 if base.Flag.LowerM > 2 {
792 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
798 // CalleeEffects appends any side effects from evaluating callee to init.
799 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
802 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
806 conv := callee.(*ir.ConvExpr)
807 init.Append(ir.TakeInit(conv)...)
811 ic := callee.(*ir.InlinedCallExpr)
812 init.Append(ir.TakeInit(ic)...)
813 init.Append(ic.Body.Take()...)
814 callee = ic.SingleResult()
817 base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
822 // oldInline creates an InlinedCallExpr to replace the given call
823 // expression. fn is the callee function to be inlined. inlIndex is
824 // the inlining tree position index, for use with src.NewInliningBase
825 // when rewriting positions.
826 func oldInline(call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
827 if base.Debug.TypecheckInl == 0 {
828 typecheck.ImportedBody(fn)
835 // For normal function calls, the function callee expression
836 // may contain side effects. Make sure to preserve these,
837 // if necessary (#42703).
838 if call.Op() == ir.OCALLFUNC {
839 CalleeEffects(&ninit, call.X)
842 // Make temp names to use instead of the originals.
843 inlvars := make(map[*ir.Name]*ir.Name)
845 // record formals/locals for later post-processing
846 var inlfvars []*ir.Name
848 for _, ln := range fn.Inl.Dcl {
849 if ln.Op() != ir.ONAME {
852 if ln.Class == ir.PPARAMOUT { // return values handled below.
855 inlf := typecheck.Expr(inlvar(ln)).(*ir.Name)
857 if base.Flag.GenDwarfInl > 0 {
858 if ln.Class == ir.PPARAM {
859 inlf.Name().SetInlFormal(true)
861 inlf.Name().SetInlLocal(true)
863 inlf.SetPos(ln.Pos())
864 inlfvars = append(inlfvars, inlf)
868 // We can delay declaring+initializing result parameters if:
869 // temporaries for return values.
870 var retvars []ir.Node
871 for i, t := range fn.Type().Results().Fields().Slice() {
873 if nn := t.Nname; nn != nil && !ir.IsBlank(nn.(*ir.Name)) && !strings.HasPrefix(nn.Sym().Name, "~r") {
876 m = typecheck.Expr(m).(*ir.Name)
879 // anonymous return values, synthesize names for use in assignment that replaces return
883 if base.Flag.GenDwarfInl > 0 {
884 // Don't update the src.Pos on a return variable if it
885 // was manufactured by the inliner (e.g. "~R2"); such vars
886 // were not part of the original callee.
887 if !strings.HasPrefix(m.Sym().Name, "~R") {
888 m.Name().SetInlFormal(true)
890 inlfvars = append(inlfvars, m)
894 retvars = append(retvars, m)
897 // Assign arguments to the parameters' temp names.
898 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
900 if call.Op() == ir.OCALLMETH {
901 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
903 as.Rhs.Append(call.Args...)
905 if recv := fn.Type().Recv(); recv != nil {
906 as.Lhs.Append(inlParam(recv, as, inlvars))
908 for _, param := range fn.Type().Params().Fields().Slice() {
909 as.Lhs.Append(inlParam(param, as, inlvars))
912 if len(as.Rhs) != 0 {
913 ninit.Append(typecheck.Stmt(as))
916 if !fn.Inl.CanDelayResults {
917 // Zero the return parameters.
918 for _, n := range retvars {
919 ninit.Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
920 ras := ir.NewAssignStmt(base.Pos, n, nil)
921 ninit.Append(typecheck.Stmt(ras))
925 retlabel := typecheck.AutoLabel(".i")
929 // Add an inline mark just before the inlined body.
930 // This mark is inline in the code so that it's a reasonable spot
931 // to put a breakpoint. Not sure if that's really necessary or not
932 // (in which case it could go at the end of the function instead).
934 ninit.Append(ir.NewInlineMarkStmt(call.Pos().WithIsStmt(), int64(inlIndex)))
940 defnMarker: ir.NilExpr{},
941 bases: make(map[*src.PosBase]*src.PosBase),
942 newInlIndex: inlIndex,
945 subst.edit = subst.node
947 body := subst.list(ir.Nodes(fn.Inl.Body))
949 lab := ir.NewLabelStmt(base.Pos, retlabel)
950 body = append(body, lab)
952 if base.Flag.GenDwarfInl > 0 {
953 for _, v := range inlfvars {
954 v.SetPos(subst.updatedPos(v.Pos()))
958 //dumplist("ninit post", ninit);
960 res := ir.NewInlinedCallExpr(base.Pos, body, retvars)
962 res.SetType(call.Type())
967 // Every time we expand a function we generate a new set of tmpnames,
968 // PAUTO's in the calling functions, and link them off of the
969 // PPARAM's, PAUTOS and PPARAMOUTs of the called function.
970 func inlvar(var_ *ir.Name) *ir.Name {
971 if base.Flag.LowerM > 3 {
972 fmt.Printf("inlvar %+v\n", var_)
975 n := typecheck.NewName(var_.Sym())
976 n.SetType(var_.Type())
980 n.SetAutoTemp(var_.AutoTemp())
981 n.Curfn = ir.CurFunc // the calling function, not the called one
982 n.SetAddrtaken(var_.Addrtaken())
984 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
988 // Synthesize a variable to store the inlined function's results in.
989 func retvar(t *types.Field, i int) *ir.Name {
990 n := typecheck.NewName(typecheck.LookupNum("~R", i))
995 n.Curfn = ir.CurFunc // the calling function, not the called one
996 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1000 // The inlsubst type implements the actual inlining of a single
1002 type inlsubst struct {
1003 // Target of the goto substituted in place of a return.
1006 // Temporary result variables.
1009 inlvars map[*ir.Name]*ir.Name
1010 // defnMarker is used to mark a Node for reassignment.
1011 // inlsubst.clovar set this during creating new ONAME.
1012 // inlsubst.node will set the correct Defn for inlvar.
1013 defnMarker ir.NilExpr
1015 // bases maps from original PosBase to PosBase with an extra
1016 // inlined call frame.
1017 bases map[*src.PosBase]*src.PosBase
1019 // newInlIndex is the index of the inlined call frame to
1020 // insert for inlined nodes.
1023 edit func(ir.Node) ir.Node // cached copy of subst.node method value closure
1025 // If non-nil, we are inside a closure inside the inlined function, and
1026 // newclofn is the Func of the new inlined closure.
1029 fn *ir.Func // For debug -- the func that is being inlined
1031 // If true, then don't update source positions during substitution
1032 // (retain old source positions).
1036 // list inlines a list of nodes.
1037 func (subst *inlsubst) list(ll ir.Nodes) []ir.Node {
1038 s := make([]ir.Node, 0, len(ll))
1039 for _, n := range ll {
1040 s = append(s, subst.node(n))
1045 // fields returns a list of the fields of a struct type representing receiver,
1046 // params, or results, after duplicating the field nodes and substituting the
1047 // Nname nodes inside the field nodes.
1048 func (subst *inlsubst) fields(oldt *types.Type) []*types.Field {
1049 oldfields := oldt.FieldSlice()
1050 newfields := make([]*types.Field, len(oldfields))
1051 for i := range oldfields {
1052 newfields[i] = oldfields[i].Copy()
1053 if oldfields[i].Nname != nil {
1054 newfields[i].Nname = subst.node(oldfields[i].Nname.(*ir.Name))
1060 // clovar creates a new ONAME node for a local variable or param of a closure
1061 // inside a function being inlined.
1062 func (subst *inlsubst) clovar(n *ir.Name) *ir.Name {
1063 m := ir.NewNameAt(n.Pos(), n.Sym())
1067 if n.IsClosureVar() {
1068 m.SetIsClosureVar(true)
1071 m.SetAddrtaken(true)
1078 m.Curfn = subst.newclofn
1080 switch defn := n.Defn.(type) {
1084 if !n.IsClosureVar() {
1085 base.FatalfAt(n.Pos(), "want closure variable, got: %+v", n)
1087 if n.Sym().Pkg != types.LocalPkg {
1088 // If the closure came from inlining a function from
1089 // another package, must change package of captured
1090 // variable to localpkg, so that the fields of the closure
1091 // struct are local package and can be accessed even if
1092 // name is not exported. If you disable this code, you can
1093 // reproduce the problem by running 'go test
1094 // go/internal/srcimporter'. TODO(mdempsky) - maybe change
1095 // how we create closure structs?
1096 m.SetSym(types.LocalPkg.Lookup(n.Sym().Name))
1098 // Make sure any inlvar which is the Defn
1099 // of an ONAME closure var is rewritten
1100 // during inlining. Don't substitute
1101 // if Defn node is outside inlined function.
1102 if subst.inlvars[n.Defn.(*ir.Name)] != nil {
1103 m.Defn = subst.node(n.Defn)
1105 case *ir.AssignStmt, *ir.AssignListStmt:
1106 // Mark node for reassignment at the end of inlsubst.node.
1107 m.Defn = &subst.defnMarker
1108 case *ir.TypeSwitchGuard:
1109 // TODO(mdempsky): Set m.Defn properly. See discussion on #45743.
1111 // TODO: Set m.Defn properly if we support inlining range statement in the future.
1113 base.FatalfAt(n.Pos(), "unexpected Defn: %+v", defn)
1117 // Either the outer variable is defined in function being inlined,
1118 // and we will replace it with the substituted variable, or it is
1119 // defined outside the function being inlined, and we should just
1120 // skip the outer variable (the closure variable of the function
1122 s := subst.node(n.Outer).(*ir.Name)
1131 // closure does the necessary substitions for a ClosureExpr n and returns the new
1133 func (subst *inlsubst) closure(n *ir.ClosureExpr) ir.Node {
1134 // Prior to the subst edit, set a flag in the inlsubst to indicate
1135 // that we don't want to update the source positions in the new
1136 // closure function. If we do this, it will appear that the
1137 // closure itself has things inlined into it, which is not the
1138 // case. See issue #46234 for more details. At the same time, we
1139 // do want to update the position in the new ClosureExpr (which is
1140 // part of the function we're working on). See #49171 for an
1141 // example of what happens if we miss that update.
1142 newClosurePos := subst.updatedPos(n.Pos())
1143 defer func(prev bool) { subst.noPosUpdate = prev }(subst.noPosUpdate)
1144 subst.noPosUpdate = true
1146 //fmt.Printf("Inlining func %v with closure into %v\n", subst.fn, ir.FuncName(ir.CurFunc))
1149 newfn := ir.NewClosureFunc(oldfn.Pos(), true)
1151 if subst.newclofn != nil {
1152 //fmt.Printf("Inlining a closure with a nested closure\n")
1154 prevxfunc := subst.newclofn
1156 // Mark that we are now substituting within a closure (within the
1157 // inlined function), and create new nodes for all the local
1158 // vars/params inside this closure.
1159 subst.newclofn = newfn
1161 newfn.ClosureVars = nil
1162 for _, oldv := range oldfn.Dcl {
1163 newv := subst.clovar(oldv)
1164 subst.inlvars[oldv] = newv
1165 newfn.Dcl = append(newfn.Dcl, newv)
1167 for _, oldv := range oldfn.ClosureVars {
1168 newv := subst.clovar(oldv)
1169 subst.inlvars[oldv] = newv
1170 newfn.ClosureVars = append(newfn.ClosureVars, newv)
1173 // Need to replace ONAME nodes in
1174 // newfn.Type().FuncType().Receiver/Params/Results.FieldSlice().Nname
1175 oldt := oldfn.Type()
1176 newrecvs := subst.fields(oldt.Recvs())
1177 var newrecv *types.Field
1178 if len(newrecvs) > 0 {
1179 newrecv = newrecvs[0]
1181 newt := types.NewSignature(oldt.Pkg(), newrecv,
1182 nil, subst.fields(oldt.Params()), subst.fields(oldt.Results()))
1184 newfn.Nname.SetType(newt)
1185 newfn.Body = subst.list(oldfn.Body)
1187 // Remove the nodes for the current closure from subst.inlvars
1188 for _, oldv := range oldfn.Dcl {
1189 delete(subst.inlvars, oldv)
1191 for _, oldv := range oldfn.ClosureVars {
1192 delete(subst.inlvars, oldv)
1194 // Go back to previous closure func
1195 subst.newclofn = prevxfunc
1197 // Actually create the named function for the closure, now that
1198 // the closure is inlined in a specific function.
1199 newclo := newfn.OClosure
1200 newclo.SetPos(newClosurePos)
1201 newclo.SetInit(subst.list(n.Init()))
1202 return typecheck.Expr(newclo)
1205 // node recursively copies a node from the saved pristine body of the
1206 // inlined function, substituting references to input/output
1207 // parameters with ones to the tmpnames, and substituting returns with
1208 // assignments to the output.
1209 func (subst *inlsubst) node(n ir.Node) ir.Node {
1218 // Handle captured variables when inlining closures.
1219 if n.IsClosureVar() && subst.newclofn == nil {
1222 // Deal with case where sequence of closures are inlined.
1223 // TODO(danscales) - write test case to see if we need to
1224 // go up multiple levels.
1225 if o.Curfn != ir.CurFunc {
1229 // make sure the outer param matches the inlining location
1230 if o == nil || o.Curfn != ir.CurFunc {
1231 base.Fatalf("%v: unresolvable capture %v\n", ir.Line(n), n)
1234 if base.Flag.LowerM > 2 {
1235 fmt.Printf("substituting captured name %+v -> %+v\n", n, o)
1240 if inlvar := subst.inlvars[n]; inlvar != nil { // These will be set during inlnode
1241 if base.Flag.LowerM > 2 {
1242 fmt.Printf("substituting name %+v -> %+v\n", n, inlvar)
1247 if base.Flag.LowerM > 2 {
1248 fmt.Printf("not substituting name %+v\n", n)
1253 n := n.(*ir.SelectorExpr)
1256 case ir.OLITERAL, ir.ONIL, ir.OTYPE:
1257 // If n is a named constant or type, we can continue
1258 // using it in the inline copy. Otherwise, make a copy
1259 // so we can update the line number.
1265 if subst.newclofn != nil {
1266 // Don't do special substitutions if inside a closure
1269 // Because of the above test for subst.newclofn,
1270 // this return is guaranteed to belong to the current inlined function.
1271 n := n.(*ir.ReturnStmt)
1272 init := subst.list(n.Init())
1273 if len(subst.retvars) != 0 && len(n.Results) != 0 {
1274 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1276 // Make a shallow copy of retvars.
1277 // Otherwise OINLCALL.Rlist will be the same list,
1278 // and later walk and typecheck may clobber it.
1279 for _, n := range subst.retvars {
1282 as.Rhs = subst.list(n.Results)
1284 if subst.fn.Inl.CanDelayResults {
1285 for _, n := range as.Lhs {
1286 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1291 init = append(init, typecheck.Stmt(as))
1293 init = append(init, ir.NewBranchStmt(base.Pos, ir.OGOTO, subst.retlabel))
1294 typecheck.Stmts(init)
1295 return ir.NewBlockStmt(base.Pos, init)
1297 case ir.OGOTO, ir.OBREAK, ir.OCONTINUE:
1298 if subst.newclofn != nil {
1299 // Don't do special substitutions if inside a closure
1302 n := n.(*ir.BranchStmt)
1303 m := ir.Copy(n).(*ir.BranchStmt)
1304 m.SetPos(subst.updatedPos(m.Pos()))
1306 m.Label = translateLabel(n.Label)
1310 if subst.newclofn != nil {
1311 // Don't do special substitutions if inside a closure
1314 n := n.(*ir.LabelStmt)
1315 m := ir.Copy(n).(*ir.LabelStmt)
1316 m.SetPos(subst.updatedPos(m.Pos()))
1318 m.Label = translateLabel(n.Label)
1322 return subst.closure(n.(*ir.ClosureExpr))
1327 m.SetPos(subst.updatedPos(m.Pos()))
1328 ir.EditChildren(m, subst.edit)
1330 if subst.newclofn == nil {
1331 // Translate any label on FOR, RANGE loops, SWITCH or SELECT
1334 m := m.(*ir.ForStmt)
1335 m.Label = translateLabel(m.Label)
1339 m := m.(*ir.RangeStmt)
1340 m.Label = translateLabel(m.Label)
1344 m := m.(*ir.SwitchStmt)
1345 m.Label = translateLabel(m.Label)
1349 m := m.(*ir.SelectStmt)
1350 m.Label = translateLabel(m.Label)
1355 switch m := m.(type) {
1356 case *ir.AssignStmt:
1357 if lhs, ok := m.X.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1360 case *ir.AssignListStmt:
1361 for _, lhs := range m.Lhs {
1362 if lhs, ok := lhs.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1371 // translateLabel makes a label from an inlined function (if non-nil) be unique by
1372 // adding "·inlgen".
1373 func translateLabel(l *types.Sym) *types.Sym {
1377 p := fmt.Sprintf("%s·%d", l.Name, inlgen)
1378 return typecheck.Lookup(p)
1381 func (subst *inlsubst) updatedPos(xpos src.XPos) src.XPos {
1382 if subst.noPosUpdate {
1385 pos := base.Ctxt.PosTable.Pos(xpos)
1386 oldbase := pos.Base() // can be nil
1387 newbase := subst.bases[oldbase]
1389 newbase = src.NewInliningBase(oldbase, subst.newInlIndex)
1390 subst.bases[oldbase] = newbase
1392 pos.SetBase(newbase)
1393 return base.Ctxt.PosTable.XPos(pos)
1396 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1397 s := make([]*ir.Name, 0, len(ll))
1398 for _, n := range ll {
1399 if n.Class == ir.PAUTO {
1400 if !vis.usedLocals.Has(n) {
1409 // numNonClosures returns the number of functions in list which are not closures.
1410 func numNonClosures(list []*ir.Func) int {
1412 for _, fn := range list {
1413 if fn.OClosure == nil {
1420 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1421 for _, x := range list {