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.
435 n := n.(*ir.AssignListStmt)
437 // Unified IR unconditionally rewrites:
448 // so that it can insert implicit conversions as necessary. To
449 // minimize impact to the existing inlining heuristics (in
450 // particular, to avoid breaking the existing inlinability regress
451 // tests), we need to compensate for this here.
452 if base.Debug.Unified != 0 {
453 if init := n.Rhs[0].Init(); len(init) == 1 {
454 if _, ok := init[0].(*ir.AssignListStmt); ok {
455 // 4 for each value, because each temporary variable now
456 // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
458 // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
459 v.budget += 4*int32(len(n.Lhs)) + 1
467 // When debugging, don't stop early, to get full cost of inlining this function
468 if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
469 v.reason = "too expensive"
473 return ir.DoChildren(n, v.do)
476 func isBigFunc(fn *ir.Func) bool {
477 budget := inlineBigFunctionNodes
478 return ir.Any(fn, func(n ir.Node) bool {
484 // inlcopylist (together with inlcopy) recursively copies a list of nodes, except
485 // that it keeps the same ONAME, OTYPE, and OLITERAL nodes. It is used for copying
486 // the body and dcls of an inlineable function.
487 func inlcopylist(ll []ir.Node) []ir.Node {
488 s := make([]ir.Node, len(ll))
489 for i, n := range ll {
495 // inlcopy is like DeepCopy(), but does extra work to copy closures.
496 func inlcopy(n ir.Node) ir.Node {
497 var edit func(ir.Node) ir.Node
498 edit = func(x ir.Node) ir.Node {
500 case ir.ONAME, ir.OTYPE, ir.OLITERAL, ir.ONIL:
504 ir.EditChildren(m, edit)
505 if x.Op() == ir.OCLOSURE {
506 x := x.(*ir.ClosureExpr)
507 // Need to save/duplicate x.Func.Nname,
508 // x.Func.Nname.Ntype, x.Func.Dcl, x.Func.ClosureVars, and
509 // x.Func.Body for iexport and local inlining.
511 newfn := ir.NewFunc(oldfn.Pos())
512 m.(*ir.ClosureExpr).Func = newfn
513 newfn.Nname = ir.NewNameAt(oldfn.Nname.Pos(), oldfn.Nname.Sym())
514 // XXX OK to share fn.Type() ??
515 newfn.Nname.SetType(oldfn.Nname.Type())
516 newfn.Body = inlcopylist(oldfn.Body)
517 // Make shallow copy of the Dcl and ClosureVar slices
518 newfn.Dcl = append([]*ir.Name(nil), oldfn.Dcl...)
519 newfn.ClosureVars = append([]*ir.Name(nil), oldfn.ClosureVars...)
526 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
527 // calls made to inlineable functions. This is the external entry point.
528 func InlineCalls(fn *ir.Func) {
531 maxCost := int32(inlineMaxBudget)
533 maxCost = inlineBigFunctionMaxCost
535 // Map to keep track of functions that have been inlined at a particular
536 // call site, in order to stop inlining when we reach the beginning of a
537 // recursion cycle again. We don't inline immediately recursive functions,
538 // but allow inlining if there is a recursion cycle of many functions.
539 // Most likely, the inlining will stop before we even hit the beginning of
540 // the cycle again, but the map catches the unusual case.
541 inlMap := make(map[*ir.Func]bool)
542 var edit func(ir.Node) ir.Node
543 edit = func(n ir.Node) ir.Node {
544 return inlnode(n, maxCost, inlMap, edit)
546 ir.EditChildren(fn, edit)
550 // inlnode recurses over the tree to find inlineable calls, which will
551 // be turned into OINLCALLs by mkinlcall. When the recursion comes
552 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
553 // nbody and nelse and use one of the 4 inlconv/glue functions above
554 // to turn the OINLCALL into an expression, a statement, or patch it
555 // in to this nodes list or rlist as appropriate.
556 // NOTE it makes no sense to pass the glue functions down the
557 // recursion to the level where the OINLCALL gets created because they
558 // have to edit /this/ n, so you'd have to push that one down as well,
559 // but then you may as well do it here. so this is cleaner and
560 // shorter and less complicated.
561 // The result of inlnode MUST be assigned back to n, e.g.
563 // n.Left = inlnode(n.Left)
564 func inlnode(n ir.Node, maxCost int32, inlMap map[*ir.Func]bool, edit func(ir.Node) ir.Node) ir.Node {
570 case ir.ODEFER, ir.OGO:
571 n := n.(*ir.GoDeferStmt)
572 switch call := n.Call; call.Op() {
574 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
576 call := call.(*ir.CallExpr)
580 n := n.(*ir.TailCallStmt)
581 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
583 // TODO do them here (or earlier),
584 // so escape analysis can avoid more heapmoves.
588 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
590 n := n.(*ir.CallExpr)
591 if n.X.Op() == ir.OMETHEXPR {
592 // Prevent inlining some reflect.Value methods when using checkptr,
593 // even when package reflect was compiled without it (#35073).
594 if meth := ir.MethodExprName(n.X); meth != nil {
596 if base.Debug.Checkptr != 0 && types.IsReflectPkg(s.Pkg) && (s.Name == "Value.UnsafeAddr" || s.Name == "Value.Pointer") {
605 ir.EditChildren(n, edit)
607 // with all the branches out of the way, it is now time to
608 // transmogrify this node itself unless inhibited by the
609 // switch at the top of this function.
612 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
615 call := n.(*ir.CallExpr)
619 if base.Flag.LowerM > 3 {
620 fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.X)
622 if ir.IsIntrinsicCall(call) {
625 if fn := inlCallee(call.X); fn != nil && typecheck.HaveInlineBody(fn) {
626 n = mkinlcall(call, fn, maxCost, inlMap, edit)
635 // inlCallee takes a function-typed expression and returns the underlying function ONAME
636 // that it refers to if statically known. Otherwise, it returns nil.
637 func inlCallee(fn ir.Node) *ir.Func {
638 fn = ir.StaticValue(fn)
641 fn := fn.(*ir.SelectorExpr)
642 n := ir.MethodExprName(fn)
643 // Check that receiver type matches fn.X.
644 // TODO(mdempsky): Handle implicit dereference
645 // of pointer receiver argument?
646 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
652 if fn.Class == ir.PFUNC {
656 fn := fn.(*ir.ClosureExpr)
664 func inlParam(t *types.Field, as ir.InitNode, inlvars map[*ir.Name]*ir.Name) ir.Node {
668 n := t.Nname.(*ir.Name)
674 base.Fatalf("missing inlvar for %v", n)
676 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, inlvar))
677 inlvar.Name().Defn = as
683 // SSADumpInline gives the SSA back end a chance to dump the function
684 // when producing output for debugging the compiler itself.
685 var SSADumpInline = func(*ir.Func) {}
687 // NewInline allows the inliner implementation to be overridden.
688 // If it returns nil, the function will not be inlined.
689 var NewInline = oldInline
691 // If n is a OCALLFUNC node, and fn is an ONAME node for a
692 // function with an inlinable body, return an OINLCALL node that can replace n.
693 // The returned node's Ninit has the parameter assignments, the Nbody is the
694 // inlined function body, and (List, Rlist) contain the (input, output)
696 // The result of mkinlcall MUST be assigned back to n, e.g.
698 // n.Left = mkinlcall(n.Left, fn, isddd)
699 func mkinlcall(n *ir.CallExpr, fn *ir.Func, maxCost int32, inlMap map[*ir.Func]bool, edit func(ir.Node) ir.Node) ir.Node {
701 if logopt.Enabled() {
702 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
703 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(fn)))
707 if fn.Inl.Cost > maxCost {
708 // The inlined function body is too big. Typically we use this check to restrict
709 // inlining into very big functions. See issue 26546 and 17566.
710 if logopt.Enabled() {
711 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
712 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), maxCost))
717 if fn == ir.CurFunc {
718 // Can't recursively inline a function into itself.
719 if logopt.Enabled() {
720 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(ir.CurFunc)))
725 // Don't inline a function fn that has no shape parameters, but is passed at
726 // least one shape arg. This means we must be inlining a non-generic function
727 // fn that was passed into a generic function, and can be called with a shape
728 // arg because it matches an appropriate type parameters. But fn may include
729 // an interface conversion (that may be applied to a shape arg) that was not
730 // apparent when we first created the instantiation of the generic function.
731 // We can't handle this if we actually do the inlining, since we want to know
732 // all interface conversions immediately after stenciling. So, we avoid
733 // inlining in this case, see issue #49309. (1)
735 // See discussion on go.dev/cl/406475 for more background.
736 if !fn.Type().Params().HasShape() {
737 for _, arg := range n.Args {
738 if arg.Type().HasShape() {
739 if logopt.Enabled() {
740 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
741 fmt.Sprintf("inlining function %v has no-shape params with shape args", ir.FuncName(fn)))
747 // Don't inline a function fn that has shape parameters, but is passed no shape arg.
748 // See comments (1) above, and issue #51909.
749 inlineable := len(n.Args) == 0 // Function has shape in type, with no arguments can always be inlined.
750 for _, arg := range n.Args {
751 if arg.Type().HasShape() {
757 if logopt.Enabled() {
758 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
759 fmt.Sprintf("inlining function %v has shape params with no-shape args", ir.FuncName(fn)))
765 if base.Flag.Cfg.Instrumenting && types.IsRuntimePkg(fn.Sym().Pkg) {
766 // Runtime package must not be instrumented.
767 // Instrument skips runtime package. However, some runtime code can be
768 // inlined into other packages and instrumented there. To avoid this,
769 // we disable inlining of runtime functions when instrumenting.
770 // The example that we observed is inlining of LockOSThread,
771 // which lead to false race reports on m contents.
776 if base.Flag.LowerM > 1 {
777 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), fn, ir.FuncName(ir.CurFunc))
786 typecheck.FixVariadicCall(n)
788 parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
791 inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym)
793 if base.Flag.GenDwarfInl > 0 {
794 if !sym.WasInlined() {
795 base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
796 sym.Set(obj.AttrWasInlined, true)
800 if base.Flag.LowerM != 0 {
801 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
803 if base.Flag.LowerM > 2 {
804 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
807 res := NewInline(n, fn, inlIndex)
812 // transitive inlining
813 // might be nice to do this before exporting the body,
814 // but can't emit the body with inlining expanded.
815 // instead we emit the things that the body needs
816 // and each use must redo the inlining.
817 // luckily these are small.
818 ir.EditChildren(res, edit)
820 if base.Flag.LowerM > 2 {
821 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
827 // CalleeEffects appends any side effects from evaluating callee to init.
828 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
831 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
835 conv := callee.(*ir.ConvExpr)
836 init.Append(ir.TakeInit(conv)...)
840 ic := callee.(*ir.InlinedCallExpr)
841 init.Append(ir.TakeInit(ic)...)
842 init.Append(ic.Body.Take()...)
843 callee = ic.SingleResult()
846 base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
851 // oldInline creates an InlinedCallExpr to replace the given call
852 // expression. fn is the callee function to be inlined. inlIndex is
853 // the inlining tree position index, for use with src.NewInliningBase
854 // when rewriting positions.
855 func oldInline(call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
856 if base.Debug.TypecheckInl == 0 {
857 typecheck.ImportedBody(fn)
864 // For normal function calls, the function callee expression
865 // may contain side effects. Make sure to preserve these,
866 // if necessary (#42703).
867 if call.Op() == ir.OCALLFUNC {
868 CalleeEffects(&ninit, call.X)
871 // Make temp names to use instead of the originals.
872 inlvars := make(map[*ir.Name]*ir.Name)
874 // record formals/locals for later post-processing
875 var inlfvars []*ir.Name
877 for _, ln := range fn.Inl.Dcl {
878 if ln.Op() != ir.ONAME {
881 if ln.Class == ir.PPARAMOUT { // return values handled below.
884 inlf := typecheck.Expr(inlvar(ln)).(*ir.Name)
886 if base.Flag.GenDwarfInl > 0 {
887 if ln.Class == ir.PPARAM {
888 inlf.Name().SetInlFormal(true)
890 inlf.Name().SetInlLocal(true)
892 inlf.SetPos(ln.Pos())
893 inlfvars = append(inlfvars, inlf)
897 // We can delay declaring+initializing result parameters if:
898 // temporaries for return values.
899 var retvars []ir.Node
900 for i, t := range fn.Type().Results().Fields().Slice() {
902 if nn := t.Nname; nn != nil && !ir.IsBlank(nn.(*ir.Name)) && !strings.HasPrefix(nn.Sym().Name, "~r") {
905 m = typecheck.Expr(m).(*ir.Name)
908 // anonymous return values, synthesize names for use in assignment that replaces return
912 if base.Flag.GenDwarfInl > 0 {
913 // Don't update the src.Pos on a return variable if it
914 // was manufactured by the inliner (e.g. "~R2"); such vars
915 // were not part of the original callee.
916 if !strings.HasPrefix(m.Sym().Name, "~R") {
917 m.Name().SetInlFormal(true)
919 inlfvars = append(inlfvars, m)
923 retvars = append(retvars, m)
926 // Assign arguments to the parameters' temp names.
927 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
929 if call.Op() == ir.OCALLMETH {
930 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
932 as.Rhs.Append(call.Args...)
934 if recv := fn.Type().Recv(); recv != nil {
935 as.Lhs.Append(inlParam(recv, as, inlvars))
937 for _, param := range fn.Type().Params().Fields().Slice() {
938 as.Lhs.Append(inlParam(param, as, inlvars))
941 if len(as.Rhs) != 0 {
942 ninit.Append(typecheck.Stmt(as))
945 if !fn.Inl.CanDelayResults {
946 // Zero the return parameters.
947 for _, n := range retvars {
948 ninit.Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
949 ras := ir.NewAssignStmt(base.Pos, n, nil)
950 ninit.Append(typecheck.Stmt(ras))
954 retlabel := typecheck.AutoLabel(".i")
958 // Add an inline mark just before the inlined body.
959 // This mark is inline in the code so that it's a reasonable spot
960 // to put a breakpoint. Not sure if that's really necessary or not
961 // (in which case it could go at the end of the function instead).
963 ninit.Append(ir.NewInlineMarkStmt(call.Pos().WithIsStmt(), int64(inlIndex)))
969 defnMarker: ir.NilExpr{},
970 bases: make(map[*src.PosBase]*src.PosBase),
971 newInlIndex: inlIndex,
974 subst.edit = subst.node
976 body := subst.list(ir.Nodes(fn.Inl.Body))
978 lab := ir.NewLabelStmt(base.Pos, retlabel)
979 body = append(body, lab)
981 if base.Flag.GenDwarfInl > 0 {
982 for _, v := range inlfvars {
983 v.SetPos(subst.updatedPos(v.Pos()))
987 //dumplist("ninit post", ninit);
989 res := ir.NewInlinedCallExpr(base.Pos, body, retvars)
991 res.SetType(call.Type())
996 // Every time we expand a function we generate a new set of tmpnames,
997 // PAUTO's in the calling functions, and link them off of the
998 // PPARAM's, PAUTOS and PPARAMOUTs of the called function.
999 func inlvar(var_ *ir.Name) *ir.Name {
1000 if base.Flag.LowerM > 3 {
1001 fmt.Printf("inlvar %+v\n", var_)
1004 n := typecheck.NewName(var_.Sym())
1005 n.SetType(var_.Type())
1009 n.SetAutoTemp(var_.AutoTemp())
1010 n.Curfn = ir.CurFunc // the calling function, not the called one
1011 n.SetAddrtaken(var_.Addrtaken())
1013 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1017 // Synthesize a variable to store the inlined function's results in.
1018 func retvar(t *types.Field, i int) *ir.Name {
1019 n := typecheck.NewName(typecheck.LookupNum("~R", i))
1024 n.Curfn = ir.CurFunc // the calling function, not the called one
1025 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1029 // The inlsubst type implements the actual inlining of a single
1031 type inlsubst struct {
1032 // Target of the goto substituted in place of a return.
1035 // Temporary result variables.
1038 inlvars map[*ir.Name]*ir.Name
1039 // defnMarker is used to mark a Node for reassignment.
1040 // inlsubst.clovar set this during creating new ONAME.
1041 // inlsubst.node will set the correct Defn for inlvar.
1042 defnMarker ir.NilExpr
1044 // bases maps from original PosBase to PosBase with an extra
1045 // inlined call frame.
1046 bases map[*src.PosBase]*src.PosBase
1048 // newInlIndex is the index of the inlined call frame to
1049 // insert for inlined nodes.
1052 edit func(ir.Node) ir.Node // cached copy of subst.node method value closure
1054 // If non-nil, we are inside a closure inside the inlined function, and
1055 // newclofn is the Func of the new inlined closure.
1058 fn *ir.Func // For debug -- the func that is being inlined
1060 // If true, then don't update source positions during substitution
1061 // (retain old source positions).
1065 // list inlines a list of nodes.
1066 func (subst *inlsubst) list(ll ir.Nodes) []ir.Node {
1067 s := make([]ir.Node, 0, len(ll))
1068 for _, n := range ll {
1069 s = append(s, subst.node(n))
1074 // fields returns a list of the fields of a struct type representing receiver,
1075 // params, or results, after duplicating the field nodes and substituting the
1076 // Nname nodes inside the field nodes.
1077 func (subst *inlsubst) fields(oldt *types.Type) []*types.Field {
1078 oldfields := oldt.FieldSlice()
1079 newfields := make([]*types.Field, len(oldfields))
1080 for i := range oldfields {
1081 newfields[i] = oldfields[i].Copy()
1082 if oldfields[i].Nname != nil {
1083 newfields[i].Nname = subst.node(oldfields[i].Nname.(*ir.Name))
1089 // clovar creates a new ONAME node for a local variable or param of a closure
1090 // inside a function being inlined.
1091 func (subst *inlsubst) clovar(n *ir.Name) *ir.Name {
1092 m := ir.NewNameAt(n.Pos(), n.Sym())
1096 if n.IsClosureVar() {
1097 m.SetIsClosureVar(true)
1100 m.SetAddrtaken(true)
1107 m.Curfn = subst.newclofn
1109 switch defn := n.Defn.(type) {
1113 if !n.IsClosureVar() {
1114 base.FatalfAt(n.Pos(), "want closure variable, got: %+v", n)
1116 if n.Sym().Pkg != types.LocalPkg {
1117 // If the closure came from inlining a function from
1118 // another package, must change package of captured
1119 // variable to localpkg, so that the fields of the closure
1120 // struct are local package and can be accessed even if
1121 // name is not exported. If you disable this code, you can
1122 // reproduce the problem by running 'go test
1123 // go/internal/srcimporter'. TODO(mdempsky) - maybe change
1124 // how we create closure structs?
1125 m.SetSym(types.LocalPkg.Lookup(n.Sym().Name))
1127 // Make sure any inlvar which is the Defn
1128 // of an ONAME closure var is rewritten
1129 // during inlining. Don't substitute
1130 // if Defn node is outside inlined function.
1131 if subst.inlvars[n.Defn.(*ir.Name)] != nil {
1132 m.Defn = subst.node(n.Defn)
1134 case *ir.AssignStmt, *ir.AssignListStmt:
1135 // Mark node for reassignment at the end of inlsubst.node.
1136 m.Defn = &subst.defnMarker
1137 case *ir.TypeSwitchGuard:
1138 // TODO(mdempsky): Set m.Defn properly. See discussion on #45743.
1140 // TODO: Set m.Defn properly if we support inlining range statement in the future.
1142 base.FatalfAt(n.Pos(), "unexpected Defn: %+v", defn)
1146 // Either the outer variable is defined in function being inlined,
1147 // and we will replace it with the substituted variable, or it is
1148 // defined outside the function being inlined, and we should just
1149 // skip the outer variable (the closure variable of the function
1151 s := subst.node(n.Outer).(*ir.Name)
1160 // closure does the necessary substitions for a ClosureExpr n and returns the new
1162 func (subst *inlsubst) closure(n *ir.ClosureExpr) ir.Node {
1163 // Prior to the subst edit, set a flag in the inlsubst to indicate
1164 // that we don't want to update the source positions in the new
1165 // closure function. If we do this, it will appear that the
1166 // closure itself has things inlined into it, which is not the
1167 // case. See issue #46234 for more details. At the same time, we
1168 // do want to update the position in the new ClosureExpr (which is
1169 // part of the function we're working on). See #49171 for an
1170 // example of what happens if we miss that update.
1171 newClosurePos := subst.updatedPos(n.Pos())
1172 defer func(prev bool) { subst.noPosUpdate = prev }(subst.noPosUpdate)
1173 subst.noPosUpdate = true
1175 //fmt.Printf("Inlining func %v with closure into %v\n", subst.fn, ir.FuncName(ir.CurFunc))
1178 newfn := ir.NewClosureFunc(oldfn.Pos(), true)
1180 if subst.newclofn != nil {
1181 //fmt.Printf("Inlining a closure with a nested closure\n")
1183 prevxfunc := subst.newclofn
1185 // Mark that we are now substituting within a closure (within the
1186 // inlined function), and create new nodes for all the local
1187 // vars/params inside this closure.
1188 subst.newclofn = newfn
1190 newfn.ClosureVars = nil
1191 for _, oldv := range oldfn.Dcl {
1192 newv := subst.clovar(oldv)
1193 subst.inlvars[oldv] = newv
1194 newfn.Dcl = append(newfn.Dcl, newv)
1196 for _, oldv := range oldfn.ClosureVars {
1197 newv := subst.clovar(oldv)
1198 subst.inlvars[oldv] = newv
1199 newfn.ClosureVars = append(newfn.ClosureVars, newv)
1202 // Need to replace ONAME nodes in
1203 // newfn.Type().FuncType().Receiver/Params/Results.FieldSlice().Nname
1204 oldt := oldfn.Type()
1205 newrecvs := subst.fields(oldt.Recvs())
1206 var newrecv *types.Field
1207 if len(newrecvs) > 0 {
1208 newrecv = newrecvs[0]
1210 newt := types.NewSignature(oldt.Pkg(), newrecv,
1211 nil, subst.fields(oldt.Params()), subst.fields(oldt.Results()))
1213 newfn.Nname.SetType(newt)
1214 newfn.Body = subst.list(oldfn.Body)
1216 // Remove the nodes for the current closure from subst.inlvars
1217 for _, oldv := range oldfn.Dcl {
1218 delete(subst.inlvars, oldv)
1220 for _, oldv := range oldfn.ClosureVars {
1221 delete(subst.inlvars, oldv)
1223 // Go back to previous closure func
1224 subst.newclofn = prevxfunc
1226 // Actually create the named function for the closure, now that
1227 // the closure is inlined in a specific function.
1228 newclo := newfn.OClosure
1229 newclo.SetPos(newClosurePos)
1230 newclo.SetInit(subst.list(n.Init()))
1231 return typecheck.Expr(newclo)
1234 // node recursively copies a node from the saved pristine body of the
1235 // inlined function, substituting references to input/output
1236 // parameters with ones to the tmpnames, and substituting returns with
1237 // assignments to the output.
1238 func (subst *inlsubst) node(n ir.Node) ir.Node {
1247 // Handle captured variables when inlining closures.
1248 if n.IsClosureVar() && subst.newclofn == nil {
1251 // Deal with case where sequence of closures are inlined.
1252 // TODO(danscales) - write test case to see if we need to
1253 // go up multiple levels.
1254 if o.Curfn != ir.CurFunc {
1258 // make sure the outer param matches the inlining location
1259 if o == nil || o.Curfn != ir.CurFunc {
1260 base.Fatalf("%v: unresolvable capture %v\n", ir.Line(n), n)
1263 if base.Flag.LowerM > 2 {
1264 fmt.Printf("substituting captured name %+v -> %+v\n", n, o)
1269 if inlvar := subst.inlvars[n]; inlvar != nil { // These will be set during inlnode
1270 if base.Flag.LowerM > 2 {
1271 fmt.Printf("substituting name %+v -> %+v\n", n, inlvar)
1276 if base.Flag.LowerM > 2 {
1277 fmt.Printf("not substituting name %+v\n", n)
1282 n := n.(*ir.SelectorExpr)
1285 case ir.OLITERAL, ir.ONIL, ir.OTYPE:
1286 // If n is a named constant or type, we can continue
1287 // using it in the inline copy. Otherwise, make a copy
1288 // so we can update the line number.
1294 if subst.newclofn != nil {
1295 // Don't do special substitutions if inside a closure
1298 // Because of the above test for subst.newclofn,
1299 // this return is guaranteed to belong to the current inlined function.
1300 n := n.(*ir.ReturnStmt)
1301 init := subst.list(n.Init())
1302 if len(subst.retvars) != 0 && len(n.Results) != 0 {
1303 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1305 // Make a shallow copy of retvars.
1306 // Otherwise OINLCALL.Rlist will be the same list,
1307 // and later walk and typecheck may clobber it.
1308 for _, n := range subst.retvars {
1311 as.Rhs = subst.list(n.Results)
1313 if subst.fn.Inl.CanDelayResults {
1314 for _, n := range as.Lhs {
1315 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1320 init = append(init, typecheck.Stmt(as))
1322 init = append(init, ir.NewBranchStmt(base.Pos, ir.OGOTO, subst.retlabel))
1323 typecheck.Stmts(init)
1324 return ir.NewBlockStmt(base.Pos, init)
1326 case ir.OGOTO, ir.OBREAK, ir.OCONTINUE:
1327 if subst.newclofn != nil {
1328 // Don't do special substitutions if inside a closure
1331 n := n.(*ir.BranchStmt)
1332 m := ir.Copy(n).(*ir.BranchStmt)
1333 m.SetPos(subst.updatedPos(m.Pos()))
1335 m.Label = translateLabel(n.Label)
1339 if subst.newclofn != nil {
1340 // Don't do special substitutions if inside a closure
1343 n := n.(*ir.LabelStmt)
1344 m := ir.Copy(n).(*ir.LabelStmt)
1345 m.SetPos(subst.updatedPos(m.Pos()))
1347 m.Label = translateLabel(n.Label)
1351 return subst.closure(n.(*ir.ClosureExpr))
1356 m.SetPos(subst.updatedPos(m.Pos()))
1357 ir.EditChildren(m, subst.edit)
1359 if subst.newclofn == nil {
1360 // Translate any label on FOR, RANGE loops, SWITCH or SELECT
1363 m := m.(*ir.ForStmt)
1364 m.Label = translateLabel(m.Label)
1368 m := m.(*ir.RangeStmt)
1369 m.Label = translateLabel(m.Label)
1373 m := m.(*ir.SwitchStmt)
1374 m.Label = translateLabel(m.Label)
1378 m := m.(*ir.SelectStmt)
1379 m.Label = translateLabel(m.Label)
1384 switch m := m.(type) {
1385 case *ir.AssignStmt:
1386 if lhs, ok := m.X.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1389 case *ir.AssignListStmt:
1390 for _, lhs := range m.Lhs {
1391 if lhs, ok := lhs.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1400 // translateLabel makes a label from an inlined function (if non-nil) be unique by
1401 // adding "·inlgen".
1402 func translateLabel(l *types.Sym) *types.Sym {
1406 p := fmt.Sprintf("%s·%d", l.Name, inlgen)
1407 return typecheck.Lookup(p)
1410 func (subst *inlsubst) updatedPos(xpos src.XPos) src.XPos {
1411 if subst.noPosUpdate {
1414 pos := base.Ctxt.PosTable.Pos(xpos)
1415 oldbase := pos.Base() // can be nil
1416 newbase := subst.bases[oldbase]
1418 newbase = src.NewInliningBase(oldbase, subst.newInlIndex)
1419 subst.bases[oldbase] = newbase
1421 pos.SetBase(newbase)
1422 return base.Ctxt.PosTable.XPos(pos)
1425 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1426 s := make([]*ir.Name, 0, len(ll))
1427 for _, n := range ll {
1428 if n.Class == ir.PAUTO {
1429 if !vis.usedLocals.Has(n) {
1438 // numNonClosures returns the number of functions in list which are not closures.
1439 func numNonClosures(list []*ir.Func) int {
1441 for _, fn := range list {
1442 if fn.OClosure == nil {
1449 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1450 for _, x := range list {