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"
44 // Inlining budget parameters, gathered in one place
47 inlineExtraAppendCost = 0
48 // default is to inline if there's at most one call. -l=4 overrides this by using 1 instead.
49 inlineExtraCallCost = 57 // 57 was benchmarked to provided most benefit with no bad surprises; see https://github.com/golang/go/issues/19348#issuecomment-439370742
50 inlineExtraPanicCost = 1 // do not penalize inlining panics.
51 inlineExtraThrowCost = inlineMaxBudget // with current (2018-05/1.11) code, inlining runtime.throw does not help.
53 inlineBigFunctionNodes = 5000 // Functions with this many nodes are considered "big".
54 inlineBigFunctionMaxCost = 20 // Max cost of inlinee when inlining into a "big" function.
57 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
58 func InlinePackage() {
59 ir.VisitFuncsBottomUp(typecheck.Target.Decls, func(list []*ir.Func, recursive bool) {
60 numfns := numNonClosures(list)
61 for _, n := range list {
62 if !recursive || numfns > 1 {
63 // We allow inlining if there is no
64 // recursion, or the recursion cycle is
65 // across more than one function.
68 if base.Flag.LowerM > 1 {
69 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
77 // CanInline determines whether fn is inlineable.
78 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
79 // fn and fn.Body will already have been typechecked.
80 func CanInline(fn *ir.Func) {
82 base.Fatalf("CanInline no nname %+v", fn)
85 var reason string // reason, if any, that the function was not inlined
86 if base.Flag.LowerM > 1 || logopt.Enabled() {
89 if base.Flag.LowerM > 1 {
90 fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
93 logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
99 // If marked "go:noinline", don't inline
100 if fn.Pragma&ir.Noinline != 0 {
101 reason = "marked go:noinline"
105 // If marked "go:norace" and -race compilation, don't inline.
106 if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
107 reason = "marked go:norace with -race compilation"
111 // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
112 if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
113 reason = "marked go:nocheckptr"
117 // If marked "go:cgo_unsafe_args", don't inline, since the
118 // function makes assumptions about its argument frame layout.
119 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
120 reason = "marked go:cgo_unsafe_args"
124 // If marked as "go:uintptrkeepalive", don't inline, since the
125 // keep alive information is lost during inlining.
127 // TODO(prattmic): This is handled on calls during escape analysis,
128 // which is after inlining. Move prior to inlining so the keep-alive is
129 // maintained after inlining.
130 if fn.Pragma&ir.UintptrKeepAlive != 0 {
131 reason = "marked as having a keep-alive uintptr argument"
135 // If marked as "go:uintptrescapes", don't inline, since the
136 // escape information is lost during inlining.
137 if fn.Pragma&ir.UintptrEscapes != 0 {
138 reason = "marked as having an escaping uintptr argument"
142 // The nowritebarrierrec checker currently works at function
143 // granularity, so inlining yeswritebarrierrec functions can
144 // confuse it (#22342). As a workaround, disallow inlining
146 if fn.Pragma&ir.Yeswritebarrierrec != 0 {
147 reason = "marked go:yeswritebarrierrec"
151 // If fn has no body (is defined outside of Go), cannot inline it.
152 if len(fn.Body) == 0 {
153 reason = "no function body"
157 if fn.Typecheck() == 0 {
158 base.Fatalf("CanInline on non-typechecked function %v", fn)
162 if n.Func.InlinabilityChecked() {
165 defer n.Func.SetInlinabilityChecked(true)
167 cc := int32(inlineExtraCallCost)
168 if base.Flag.LowerL == 4 {
169 cc = 1 // this appears to yield better performance than 0.
172 // At this point in the game the function we're looking at may
173 // have "stale" autos, vars that still appear in the Dcl list, but
174 // which no longer have any uses in the function body (due to
175 // elimination by deadcode). We'd like to exclude these dead vars
176 // when creating the "Inline.Dcl" field below; to accomplish this,
177 // the hairyVisitor below builds up a map of used/referenced
178 // locals, and we use this map to produce a pruned Inline.Dcl
179 // list. See issue 25249 for more context.
181 visitor := hairyVisitor{
182 budget: inlineMaxBudget,
185 if visitor.tooHairy(fn) {
186 reason = visitor.reason
190 n.Func.Inl = &ir.Inline{
191 Cost: inlineMaxBudget - visitor.budget,
192 Dcl: pruneUnusedAutos(n.Defn.(*ir.Func).Dcl, &visitor),
193 Body: inlcopylist(fn.Body),
195 CanDelayResults: canDelayResults(fn),
198 if base.Flag.LowerM > 1 {
199 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))
200 } else if base.Flag.LowerM != 0 {
201 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
203 if logopt.Enabled() {
204 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", inlineMaxBudget-visitor.budget))
208 // canDelayResults reports whether inlined calls to fn can delay
209 // declaring the result parameter until the "return" statement.
210 func canDelayResults(fn *ir.Func) bool {
211 // We can delay declaring+initializing result parameters if:
212 // (1) there's exactly one "return" statement in the inlined function;
213 // (2) it's not an empty return statement (#44355); and
214 // (3) the result parameters aren't named.
217 ir.VisitList(fn.Body, func(n ir.Node) {
218 if n, ok := n.(*ir.ReturnStmt); ok {
220 if len(n.Results) == 0 {
221 nreturns++ // empty return statement (case 2)
227 return false // not exactly one return statement (case 1)
230 // temporaries for return values.
231 for _, param := range fn.Type().Results().FieldSlice() {
232 if sym := types.OrigSym(param.Sym); sym != nil && !sym.IsBlank() {
233 return false // found a named result parameter (case 3)
240 // hairyVisitor visits a function body to determine its inlining
241 // hairiness and whether or not it can be inlined.
242 type hairyVisitor struct {
246 usedLocals ir.NameSet
247 do func(ir.Node) bool
250 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
251 v.do = v.doNode // cache closure
252 if ir.DoChildren(fn, v.do) {
256 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", inlineMaxBudget-v.budget, inlineMaxBudget)
262 func (v *hairyVisitor) doNode(n ir.Node) bool {
267 // Call is okay if inlinable and we have the budget for the body.
269 n := n.(*ir.CallExpr)
270 // Functions that call runtime.getcaller{pc,sp} can not be inlined
271 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
273 // runtime.throw is a "cheap call" like panic in normal code.
274 if n.X.Op() == ir.ONAME {
275 name := n.X.(*ir.Name)
276 if name.Class == ir.PFUNC && types.IsRuntimePkg(name.Sym().Pkg) {
277 fn := name.Sym().Name
278 if fn == "getcallerpc" || fn == "getcallersp" {
279 v.reason = "call to " + fn
283 v.budget -= inlineExtraThrowCost
288 if n.X.Op() == ir.OMETHEXPR {
289 if meth := ir.MethodExprName(n.X); meth != nil {
290 if fn := meth.Func; fn != nil {
293 if types.IsRuntimePkg(s.Pkg) && s.Name == "heapBits.nextArena" {
294 // Special case: explicitly allow mid-stack inlining of
295 // runtime.heapBits.next even though it calls slow-path
296 // runtime.heapBits.nextArena.
299 // Special case: on architectures that can do unaligned loads,
300 // explicitly mark encoding/binary methods as cheap,
301 // because in practice they are, even though our inlining
302 // budgeting system does not see that. See issue 42958.
303 if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
305 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
306 "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
307 "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
308 "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
309 "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
310 "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
315 break // treat like any other node, that is, cost of 1
321 if ir.IsIntrinsicCall(n) {
322 // Treat like any other node.
326 if fn := inlCallee(n.X); fn != nil && typecheck.HaveInlineBody(fn) {
327 v.budget -= fn.Inl.Cost
331 // Call cost for non-leaf inlining.
332 v.budget -= v.extraCallCost
335 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
337 // Things that are too hairy, irrespective of the budget
338 case ir.OCALL, ir.OCALLINTER:
339 // Call cost for non-leaf inlining.
340 v.budget -= v.extraCallCost
343 n := n.(*ir.UnaryExpr)
344 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
345 // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
346 // Before CL 284412, these conversions were introduced later in the
347 // compiler, so they didn't count against inlining budget.
350 v.budget -= inlineExtraPanicCost
353 // recover matches the argument frame pointer to find
354 // the right panic value, so it needs an argument frame.
355 v.reason = "call to recover"
359 if base.Debug.InlFuncsWithClosures == 0 {
360 v.reason = "not inlining functions with closures"
364 // TODO(danscales): Maybe make budget proportional to number of closure
366 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
368 // Scan body of closure (which DoChildren doesn't automatically
369 // do) to check for disallowed ops in the body and include the
370 // body in the budget.
371 if doList(n.(*ir.ClosureExpr).Func.Body, v.do) {
377 ir.ODCLTYPE, // can't print yet
379 v.reason = "unhandled op " + n.Op().String()
383 v.budget -= inlineExtraAppendCost
386 n := n.(*ir.AddrExpr)
387 // Make "&s.f" cost 0 when f's offset is zero.
388 if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
389 if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
390 v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
395 // *(*X)(unsafe.Pointer(&x)) is low-cost
396 n := n.(*ir.StarExpr)
399 for ptr.Op() == ir.OCONVNOP {
400 ptr = ptr.(*ir.ConvExpr).X
402 if ptr.Op() == ir.OADDR {
403 v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
407 // This doesn't produce code, but the children might.
408 v.budget++ // undo default cost
410 case ir.ODCLCONST, ir.OFALL:
411 // These nodes don't produce code; omit from inlining budget.
416 if ir.IsConst(n.Cond, constant.Bool) {
417 // This if and the condition cost nothing.
418 if doList(n.Init(), v.do) {
421 if ir.BoolVal(n.Cond) {
422 return doList(n.Body, v.do)
424 return doList(n.Else, v.do)
430 if n.Class == ir.PAUTO {
435 // The only OBLOCK we should see at this point is an empty one.
436 // In any event, let the visitList(n.List()) below take care of the statements,
437 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
440 case ir.OMETHVALUE, ir.OSLICELIT:
441 v.budget-- // Hack for toolstash -cmp.
444 v.budget++ // Hack for toolstash -cmp.
447 n := n.(*ir.AssignListStmt)
449 // Unified IR unconditionally rewrites:
460 // so that it can insert implicit conversions as necessary. To
461 // minimize impact to the existing inlining heuristics (in
462 // particular, to avoid breaking the existing inlinability regress
463 // tests), we need to compensate for this here.
464 if base.Debug.Unified != 0 {
465 if init := n.Rhs[0].Init(); len(init) == 1 {
466 if _, ok := init[0].(*ir.AssignListStmt); ok {
467 // 4 for each value, because each temporary variable now
468 // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
470 // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
471 v.budget += 4*int32(len(n.Lhs)) + 1
477 // Special case for coverage counter updates and coverage
478 // function registrations. Although these correspond to real
479 // operations, we treat them as zero cost for the moment. This
480 // is primarily due to the existence of tests that are
481 // sensitive to inlining-- if the insertion of coverage
482 // instrumentation happens to tip a given function over the
483 // threshold and move it from "inlinable" to "not-inlinable",
484 // this can cause changes in allocation behavior, which can
485 // then result in test failures (a good example is the
486 // TestAllocations in crypto/ed25519).
487 n := n.(*ir.AssignStmt)
488 if n.X.Op() == ir.OINDEX {
489 n := n.X.(*ir.IndexExpr)
490 if n.X.Op() == ir.ONAME && n.X.Type().IsArray() {
492 if n.Linksym().Type == objabi.SCOVERAGE_COUNTER {
501 // When debugging, don't stop early, to get full cost of inlining this function
502 if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
503 v.reason = "too expensive"
507 return ir.DoChildren(n, v.do)
510 func isBigFunc(fn *ir.Func) bool {
511 budget := inlineBigFunctionNodes
512 return ir.Any(fn, func(n ir.Node) bool {
518 // inlcopylist (together with inlcopy) recursively copies a list of nodes, except
519 // that it keeps the same ONAME, OTYPE, and OLITERAL nodes. It is used for copying
520 // the body and dcls of an inlineable function.
521 func inlcopylist(ll []ir.Node) []ir.Node {
522 s := make([]ir.Node, len(ll))
523 for i, n := range ll {
529 // inlcopy is like DeepCopy(), but does extra work to copy closures.
530 func inlcopy(n ir.Node) ir.Node {
531 var edit func(ir.Node) ir.Node
532 edit = func(x ir.Node) ir.Node {
534 case ir.ONAME, ir.OTYPE, ir.OLITERAL, ir.ONIL:
538 ir.EditChildren(m, edit)
539 if x.Op() == ir.OCLOSURE {
540 x := x.(*ir.ClosureExpr)
541 // Need to save/duplicate x.Func.Nname,
542 // x.Func.Nname.Ntype, x.Func.Dcl, x.Func.ClosureVars, and
543 // x.Func.Body for iexport and local inlining.
545 newfn := ir.NewFunc(oldfn.Pos())
546 m.(*ir.ClosureExpr).Func = newfn
547 newfn.Nname = ir.NewNameAt(oldfn.Nname.Pos(), oldfn.Nname.Sym())
548 // XXX OK to share fn.Type() ??
549 newfn.Nname.SetType(oldfn.Nname.Type())
550 newfn.Body = inlcopylist(oldfn.Body)
551 // Make shallow copy of the Dcl and ClosureVar slices
552 newfn.Dcl = append([]*ir.Name(nil), oldfn.Dcl...)
553 newfn.ClosureVars = append([]*ir.Name(nil), oldfn.ClosureVars...)
560 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
561 // calls made to inlineable functions. This is the external entry point.
562 func InlineCalls(fn *ir.Func) {
565 maxCost := int32(inlineMaxBudget)
567 maxCost = inlineBigFunctionMaxCost
569 var inlCalls []*ir.InlinedCallExpr
570 var edit func(ir.Node) ir.Node
571 edit = func(n ir.Node) ir.Node {
572 return inlnode(n, maxCost, &inlCalls, edit)
574 ir.EditChildren(fn, edit)
576 // If we inlined any calls, we want to recursively visit their
577 // bodies for further inlining. However, we need to wait until
578 // *after* the original function body has been expanded, or else
579 // inlCallee can have false positives (e.g., #54632).
580 for len(inlCalls) > 0 {
582 inlCalls = inlCalls[1:]
583 ir.EditChildren(call, edit)
589 // inlnode recurses over the tree to find inlineable calls, which will
590 // be turned into OINLCALLs by mkinlcall. When the recursion comes
591 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
592 // nbody and nelse and use one of the 4 inlconv/glue functions above
593 // to turn the OINLCALL into an expression, a statement, or patch it
594 // in to this nodes list or rlist as appropriate.
595 // NOTE it makes no sense to pass the glue functions down the
596 // recursion to the level where the OINLCALL gets created because they
597 // have to edit /this/ n, so you'd have to push that one down as well,
598 // but then you may as well do it here. so this is cleaner and
599 // shorter and less complicated.
600 // The result of inlnode MUST be assigned back to n, e.g.
602 // n.Left = inlnode(n.Left)
603 func inlnode(n ir.Node, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node) ir.Node {
609 case ir.ODEFER, ir.OGO:
610 n := n.(*ir.GoDeferStmt)
611 switch call := n.Call; call.Op() {
613 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
615 call := call.(*ir.CallExpr)
619 n := n.(*ir.TailCallStmt)
620 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
622 // TODO do them here (or earlier),
623 // so escape analysis can avoid more heapmoves.
627 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
629 n := n.(*ir.CallExpr)
630 if n.X.Op() == ir.OMETHEXPR {
631 // Prevent inlining some reflect.Value methods when using checkptr,
632 // even when package reflect was compiled without it (#35073).
633 if meth := ir.MethodExprName(n.X); meth != nil {
635 if base.Debug.Checkptr != 0 && types.IsReflectPkg(s.Pkg) && (s.Name == "Value.UnsafeAddr" || s.Name == "Value.Pointer") {
644 ir.EditChildren(n, edit)
646 // with all the branches out of the way, it is now time to
647 // transmogrify this node itself unless inhibited by the
648 // switch at the top of this function.
651 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
654 call := n.(*ir.CallExpr)
658 if base.Flag.LowerM > 3 {
659 fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.X)
661 if ir.IsIntrinsicCall(call) {
664 if fn := inlCallee(call.X); fn != nil && typecheck.HaveInlineBody(fn) {
665 n = mkinlcall(call, fn, maxCost, inlCalls, edit)
674 // inlCallee takes a function-typed expression and returns the underlying function ONAME
675 // that it refers to if statically known. Otherwise, it returns nil.
676 func inlCallee(fn ir.Node) *ir.Func {
677 fn = ir.StaticValue(fn)
680 fn := fn.(*ir.SelectorExpr)
681 n := ir.MethodExprName(fn)
682 // Check that receiver type matches fn.X.
683 // TODO(mdempsky): Handle implicit dereference
684 // of pointer receiver argument?
685 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
691 if fn.Class == ir.PFUNC {
695 fn := fn.(*ir.ClosureExpr)
703 func inlParam(t *types.Field, as ir.InitNode, inlvars map[*ir.Name]*ir.Name) ir.Node {
707 n := t.Nname.(*ir.Name)
713 base.Fatalf("missing inlvar for %v", n)
715 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, inlvar))
716 inlvar.Name().Defn = as
722 // SSADumpInline gives the SSA back end a chance to dump the function
723 // when producing output for debugging the compiler itself.
724 var SSADumpInline = func(*ir.Func) {}
726 // InlineCall allows the inliner implementation to be overridden.
727 // If it returns nil, the function will not be inlined.
728 var InlineCall = oldInlineCall
730 // If n is a OCALLFUNC node, and fn is an ONAME node for a
731 // function with an inlinable body, return an OINLCALL node that can replace n.
732 // The returned node's Ninit has the parameter assignments, the Nbody is the
733 // inlined function body, and (List, Rlist) contain the (input, output)
735 // The result of mkinlcall MUST be assigned back to n, e.g.
737 // n.Left = mkinlcall(n.Left, fn, isddd)
738 func mkinlcall(n *ir.CallExpr, fn *ir.Func, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node) ir.Node {
740 if logopt.Enabled() {
741 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
742 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(fn)))
746 if fn.Inl.Cost > maxCost {
747 // The inlined function body is too big. Typically we use this check to restrict
748 // inlining into very big functions. See issue 26546 and 17566.
749 if logopt.Enabled() {
750 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
751 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), maxCost))
756 if fn == ir.CurFunc {
757 // Can't recursively inline a function into itself.
758 if logopt.Enabled() {
759 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(ir.CurFunc)))
764 // The non-unified frontend has issues with inlining and shape parameters.
765 if base.Debug.Unified == 0 {
766 // Don't inline a function fn that has no shape parameters, but is passed at
767 // least one shape arg. This means we must be inlining a non-generic function
768 // fn that was passed into a generic function, and can be called with a shape
769 // arg because it matches an appropriate type parameters. But fn may include
770 // an interface conversion (that may be applied to a shape arg) that was not
771 // apparent when we first created the instantiation of the generic function.
772 // We can't handle this if we actually do the inlining, since we want to know
773 // all interface conversions immediately after stenciling. So, we avoid
774 // inlining in this case, see issue #49309. (1)
776 // See discussion on go.dev/cl/406475 for more background.
777 if !fn.Type().Params().HasShape() {
778 for _, arg := range n.Args {
779 if arg.Type().HasShape() {
780 if logopt.Enabled() {
781 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
782 fmt.Sprintf("inlining function %v has no-shape params with shape args", ir.FuncName(fn)))
788 // Don't inline a function fn that has shape parameters, but is passed no shape arg.
789 // See comments (1) above, and issue #51909.
790 inlineable := len(n.Args) == 0 // Function has shape in type, with no arguments can always be inlined.
791 for _, arg := range n.Args {
792 if arg.Type().HasShape() {
798 if logopt.Enabled() {
799 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
800 fmt.Sprintf("inlining function %v has shape params with no-shape args", ir.FuncName(fn)))
807 if base.Flag.Cfg.Instrumenting && types.IsRuntimePkg(fn.Sym().Pkg) {
808 // Runtime package must not be instrumented.
809 // Instrument skips runtime package. However, some runtime code can be
810 // inlined into other packages and instrumented there. To avoid this,
811 // we disable inlining of runtime functions when instrumenting.
812 // The example that we observed is inlining of LockOSThread,
813 // which lead to false race reports on m contents.
817 parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
820 // Check if we've already inlined this function at this particular
821 // call site, in order to stop inlining when we reach the beginning
822 // of a recursion cycle again. We don't inline immediately recursive
823 // functions, but allow inlining if there is a recursion cycle of
824 // many functions. Most likely, the inlining will stop before we
825 // even hit the beginning of the cycle again, but this catches the
827 for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
828 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
829 if base.Flag.LowerM > 1 {
830 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), fn, ir.FuncName(ir.CurFunc))
836 typecheck.FixVariadicCall(n)
838 inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym)
840 closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
841 // The linker needs FuncInfo metadata for all inlined
842 // functions. This is typically handled by gc.enqueueFunc
843 // calling ir.InitLSym for all function declarations in
844 // typecheck.Target.Decls (ir.UseClosure adds all closures to
847 // However, non-trivial closures in Decls are ignored, and are
848 // insteaded enqueued when walk of the calling function
851 // This presents a problem for direct calls to closures.
852 // Inlining will replace the entire closure definition with its
853 // body, which hides the closure from walk and thus suppresses
856 // Explicitly create a symbol early in this edge case to ensure
857 // we keep this metadata.
859 // TODO: Refactor to keep a reference so this can all be done
862 if n.Op() != ir.OCALLFUNC {
863 // Not a standard call.
866 if n.X.Op() != ir.OCLOSURE {
867 // Not a direct closure call.
871 clo := n.X.(*ir.ClosureExpr)
872 if ir.IsTrivialClosure(clo) {
873 // enqueueFunc will handle trivial closures anyways.
877 ir.InitLSym(fn, true)
880 closureInitLSym(n, fn)
882 if base.Flag.GenDwarfInl > 0 {
883 if !sym.WasInlined() {
884 base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
885 sym.Set(obj.AttrWasInlined, true)
889 if base.Flag.LowerM != 0 {
890 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
892 if base.Flag.LowerM > 2 {
893 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
896 res := InlineCall(n, fn, inlIndex)
898 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
901 if base.Flag.LowerM > 2 {
902 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
905 *inlCalls = append(*inlCalls, res)
910 // CalleeEffects appends any side effects from evaluating callee to init.
911 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
913 init.Append(ir.TakeInit(callee)...)
916 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
920 conv := callee.(*ir.ConvExpr)
924 ic := callee.(*ir.InlinedCallExpr)
925 init.Append(ic.Body.Take()...)
926 callee = ic.SingleResult()
929 base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
934 // oldInlineCall creates an InlinedCallExpr to replace the given call
935 // expression. fn is the callee function to be inlined. inlIndex is
936 // the inlining tree position index, for use with src.NewInliningBase
937 // when rewriting positions.
938 func oldInlineCall(call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
939 if base.Debug.TypecheckInl == 0 {
940 typecheck.ImportedBody(fn)
947 // For normal function calls, the function callee expression
948 // may contain side effects. Make sure to preserve these,
949 // if necessary (#42703).
950 if call.Op() == ir.OCALLFUNC {
951 CalleeEffects(&ninit, call.X)
954 // Make temp names to use instead of the originals.
955 inlvars := make(map[*ir.Name]*ir.Name)
957 // record formals/locals for later post-processing
958 var inlfvars []*ir.Name
960 for _, ln := range fn.Inl.Dcl {
961 if ln.Op() != ir.ONAME {
964 if ln.Class == ir.PPARAMOUT { // return values handled below.
967 inlf := typecheck.Expr(inlvar(ln)).(*ir.Name)
969 if base.Flag.GenDwarfInl > 0 {
970 if ln.Class == ir.PPARAM {
971 inlf.Name().SetInlFormal(true)
973 inlf.Name().SetInlLocal(true)
975 inlf.SetPos(ln.Pos())
976 inlfvars = append(inlfvars, inlf)
980 // We can delay declaring+initializing result parameters if:
981 // temporaries for return values.
982 var retvars []ir.Node
983 for i, t := range fn.Type().Results().Fields().Slice() {
985 if nn := t.Nname; nn != nil && !ir.IsBlank(nn.(*ir.Name)) && !strings.HasPrefix(nn.Sym().Name, "~r") {
988 m = typecheck.Expr(m).(*ir.Name)
991 // anonymous return values, synthesize names for use in assignment that replaces return
995 if base.Flag.GenDwarfInl > 0 {
996 // Don't update the src.Pos on a return variable if it
997 // was manufactured by the inliner (e.g. "~R2"); such vars
998 // were not part of the original callee.
999 if !strings.HasPrefix(m.Sym().Name, "~R") {
1000 m.Name().SetInlFormal(true)
1002 inlfvars = append(inlfvars, m)
1006 retvars = append(retvars, m)
1009 // Assign arguments to the parameters' temp names.
1010 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1012 if call.Op() == ir.OCALLMETH {
1013 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
1015 as.Rhs.Append(call.Args...)
1017 if recv := fn.Type().Recv(); recv != nil {
1018 as.Lhs.Append(inlParam(recv, as, inlvars))
1020 for _, param := range fn.Type().Params().Fields().Slice() {
1021 as.Lhs.Append(inlParam(param, as, inlvars))
1024 if len(as.Rhs) != 0 {
1025 ninit.Append(typecheck.Stmt(as))
1028 if !fn.Inl.CanDelayResults {
1029 // Zero the return parameters.
1030 for _, n := range retvars {
1031 ninit.Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1032 ras := ir.NewAssignStmt(base.Pos, n, nil)
1033 ninit.Append(typecheck.Stmt(ras))
1037 retlabel := typecheck.AutoLabel(".i")
1041 // Add an inline mark just before the inlined body.
1042 // This mark is inline in the code so that it's a reasonable spot
1043 // to put a breakpoint. Not sure if that's really necessary or not
1044 // (in which case it could go at the end of the function instead).
1045 // Note issue 28603.
1046 ninit.Append(ir.NewInlineMarkStmt(call.Pos().WithIsStmt(), int64(inlIndex)))
1052 defnMarker: ir.NilExpr{},
1053 bases: make(map[*src.PosBase]*src.PosBase),
1054 newInlIndex: inlIndex,
1057 subst.edit = subst.node
1059 body := subst.list(ir.Nodes(fn.Inl.Body))
1061 lab := ir.NewLabelStmt(base.Pos, retlabel)
1062 body = append(body, lab)
1064 if base.Flag.GenDwarfInl > 0 {
1065 for _, v := range inlfvars {
1066 v.SetPos(subst.updatedPos(v.Pos()))
1070 //dumplist("ninit post", ninit);
1072 res := ir.NewInlinedCallExpr(base.Pos, body, retvars)
1074 res.SetType(call.Type())
1079 // Every time we expand a function we generate a new set of tmpnames,
1080 // PAUTO's in the calling functions, and link them off of the
1081 // PPARAM's, PAUTOS and PPARAMOUTs of the called function.
1082 func inlvar(var_ *ir.Name) *ir.Name {
1083 if base.Flag.LowerM > 3 {
1084 fmt.Printf("inlvar %+v\n", var_)
1087 n := typecheck.NewName(var_.Sym())
1088 n.SetType(var_.Type())
1092 n.SetAutoTemp(var_.AutoTemp())
1093 n.Curfn = ir.CurFunc // the calling function, not the called one
1094 n.SetAddrtaken(var_.Addrtaken())
1096 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1100 // Synthesize a variable to store the inlined function's results in.
1101 func retvar(t *types.Field, i int) *ir.Name {
1102 n := typecheck.NewName(typecheck.LookupNum("~R", i))
1107 n.Curfn = ir.CurFunc // the calling function, not the called one
1108 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1112 // The inlsubst type implements the actual inlining of a single
1114 type inlsubst struct {
1115 // Target of the goto substituted in place of a return.
1118 // Temporary result variables.
1121 inlvars map[*ir.Name]*ir.Name
1122 // defnMarker is used to mark a Node for reassignment.
1123 // inlsubst.clovar set this during creating new ONAME.
1124 // inlsubst.node will set the correct Defn for inlvar.
1125 defnMarker ir.NilExpr
1127 // bases maps from original PosBase to PosBase with an extra
1128 // inlined call frame.
1129 bases map[*src.PosBase]*src.PosBase
1131 // newInlIndex is the index of the inlined call frame to
1132 // insert for inlined nodes.
1135 edit func(ir.Node) ir.Node // cached copy of subst.node method value closure
1137 // If non-nil, we are inside a closure inside the inlined function, and
1138 // newclofn is the Func of the new inlined closure.
1141 fn *ir.Func // For debug -- the func that is being inlined
1143 // If true, then don't update source positions during substitution
1144 // (retain old source positions).
1148 // list inlines a list of nodes.
1149 func (subst *inlsubst) list(ll ir.Nodes) []ir.Node {
1150 s := make([]ir.Node, 0, len(ll))
1151 for _, n := range ll {
1152 s = append(s, subst.node(n))
1157 // fields returns a list of the fields of a struct type representing receiver,
1158 // params, or results, after duplicating the field nodes and substituting the
1159 // Nname nodes inside the field nodes.
1160 func (subst *inlsubst) fields(oldt *types.Type) []*types.Field {
1161 oldfields := oldt.FieldSlice()
1162 newfields := make([]*types.Field, len(oldfields))
1163 for i := range oldfields {
1164 newfields[i] = oldfields[i].Copy()
1165 if oldfields[i].Nname != nil {
1166 newfields[i].Nname = subst.node(oldfields[i].Nname.(*ir.Name))
1172 // clovar creates a new ONAME node for a local variable or param of a closure
1173 // inside a function being inlined.
1174 func (subst *inlsubst) clovar(n *ir.Name) *ir.Name {
1175 m := ir.NewNameAt(n.Pos(), n.Sym())
1179 if n.IsClosureVar() {
1180 m.SetIsClosureVar(true)
1183 m.SetAddrtaken(true)
1190 m.Curfn = subst.newclofn
1192 switch defn := n.Defn.(type) {
1196 if !n.IsClosureVar() {
1197 base.FatalfAt(n.Pos(), "want closure variable, got: %+v", n)
1199 if n.Sym().Pkg != types.LocalPkg {
1200 // If the closure came from inlining a function from
1201 // another package, must change package of captured
1202 // variable to localpkg, so that the fields of the closure
1203 // struct are local package and can be accessed even if
1204 // name is not exported. If you disable this code, you can
1205 // reproduce the problem by running 'go test
1206 // go/internal/srcimporter'. TODO(mdempsky) - maybe change
1207 // how we create closure structs?
1208 m.SetSym(types.LocalPkg.Lookup(n.Sym().Name))
1210 // Make sure any inlvar which is the Defn
1211 // of an ONAME closure var is rewritten
1212 // during inlining. Don't substitute
1213 // if Defn node is outside inlined function.
1214 if subst.inlvars[n.Defn.(*ir.Name)] != nil {
1215 m.Defn = subst.node(n.Defn)
1217 case *ir.AssignStmt, *ir.AssignListStmt:
1218 // Mark node for reassignment at the end of inlsubst.node.
1219 m.Defn = &subst.defnMarker
1220 case *ir.TypeSwitchGuard:
1221 // TODO(mdempsky): Set m.Defn properly. See discussion on #45743.
1223 // TODO: Set m.Defn properly if we support inlining range statement in the future.
1225 base.FatalfAt(n.Pos(), "unexpected Defn: %+v", defn)
1229 // Either the outer variable is defined in function being inlined,
1230 // and we will replace it with the substituted variable, or it is
1231 // defined outside the function being inlined, and we should just
1232 // skip the outer variable (the closure variable of the function
1234 s := subst.node(n.Outer).(*ir.Name)
1243 // closure does the necessary substitions for a ClosureExpr n and returns the new
1245 func (subst *inlsubst) closure(n *ir.ClosureExpr) ir.Node {
1246 // Prior to the subst edit, set a flag in the inlsubst to indicate
1247 // that we don't want to update the source positions in the new
1248 // closure function. If we do this, it will appear that the
1249 // closure itself has things inlined into it, which is not the
1250 // case. See issue #46234 for more details. At the same time, we
1251 // do want to update the position in the new ClosureExpr (which is
1252 // part of the function we're working on). See #49171 for an
1253 // example of what happens if we miss that update.
1254 newClosurePos := subst.updatedPos(n.Pos())
1255 defer func(prev bool) { subst.noPosUpdate = prev }(subst.noPosUpdate)
1256 subst.noPosUpdate = true
1258 //fmt.Printf("Inlining func %v with closure into %v\n", subst.fn, ir.FuncName(ir.CurFunc))
1261 newfn := ir.NewClosureFunc(oldfn.Pos(), true)
1263 if subst.newclofn != nil {
1264 //fmt.Printf("Inlining a closure with a nested closure\n")
1266 prevxfunc := subst.newclofn
1268 // Mark that we are now substituting within a closure (within the
1269 // inlined function), and create new nodes for all the local
1270 // vars/params inside this closure.
1271 subst.newclofn = newfn
1273 newfn.ClosureVars = nil
1274 for _, oldv := range oldfn.Dcl {
1275 newv := subst.clovar(oldv)
1276 subst.inlvars[oldv] = newv
1277 newfn.Dcl = append(newfn.Dcl, newv)
1279 for _, oldv := range oldfn.ClosureVars {
1280 newv := subst.clovar(oldv)
1281 subst.inlvars[oldv] = newv
1282 newfn.ClosureVars = append(newfn.ClosureVars, newv)
1285 // Need to replace ONAME nodes in
1286 // newfn.Type().FuncType().Receiver/Params/Results.FieldSlice().Nname
1287 oldt := oldfn.Type()
1288 newrecvs := subst.fields(oldt.Recvs())
1289 var newrecv *types.Field
1290 if len(newrecvs) > 0 {
1291 newrecv = newrecvs[0]
1293 newt := types.NewSignature(oldt.Pkg(), newrecv,
1294 nil, subst.fields(oldt.Params()), subst.fields(oldt.Results()))
1296 newfn.Nname.SetType(newt)
1297 newfn.Body = subst.list(oldfn.Body)
1299 // Remove the nodes for the current closure from subst.inlvars
1300 for _, oldv := range oldfn.Dcl {
1301 delete(subst.inlvars, oldv)
1303 for _, oldv := range oldfn.ClosureVars {
1304 delete(subst.inlvars, oldv)
1306 // Go back to previous closure func
1307 subst.newclofn = prevxfunc
1309 // Actually create the named function for the closure, now that
1310 // the closure is inlined in a specific function.
1311 newclo := newfn.OClosure
1312 newclo.SetPos(newClosurePos)
1313 newclo.SetInit(subst.list(n.Init()))
1314 return typecheck.Expr(newclo)
1317 // node recursively copies a node from the saved pristine body of the
1318 // inlined function, substituting references to input/output
1319 // parameters with ones to the tmpnames, and substituting returns with
1320 // assignments to the output.
1321 func (subst *inlsubst) node(n ir.Node) ir.Node {
1330 // Handle captured variables when inlining closures.
1331 if n.IsClosureVar() && subst.newclofn == nil {
1334 // Deal with case where sequence of closures are inlined.
1335 // TODO(danscales) - write test case to see if we need to
1336 // go up multiple levels.
1337 if o.Curfn != ir.CurFunc {
1341 // make sure the outer param matches the inlining location
1342 if o == nil || o.Curfn != ir.CurFunc {
1343 base.Fatalf("%v: unresolvable capture %v\n", ir.Line(n), n)
1346 if base.Flag.LowerM > 2 {
1347 fmt.Printf("substituting captured name %+v -> %+v\n", n, o)
1352 if inlvar := subst.inlvars[n]; inlvar != nil { // These will be set during inlnode
1353 if base.Flag.LowerM > 2 {
1354 fmt.Printf("substituting name %+v -> %+v\n", n, inlvar)
1359 if base.Flag.LowerM > 2 {
1360 fmt.Printf("not substituting name %+v\n", n)
1365 n := n.(*ir.SelectorExpr)
1368 case ir.OLITERAL, ir.ONIL, ir.OTYPE:
1369 // If n is a named constant or type, we can continue
1370 // using it in the inline copy. Otherwise, make a copy
1371 // so we can update the line number.
1377 if subst.newclofn != nil {
1378 // Don't do special substitutions if inside a closure
1381 // Because of the above test for subst.newclofn,
1382 // this return is guaranteed to belong to the current inlined function.
1383 n := n.(*ir.ReturnStmt)
1384 init := subst.list(n.Init())
1385 if len(subst.retvars) != 0 && len(n.Results) != 0 {
1386 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1388 // Make a shallow copy of retvars.
1389 // Otherwise OINLCALL.Rlist will be the same list,
1390 // and later walk and typecheck may clobber it.
1391 for _, n := range subst.retvars {
1394 as.Rhs = subst.list(n.Results)
1396 if subst.fn.Inl.CanDelayResults {
1397 for _, n := range as.Lhs {
1398 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1403 init = append(init, typecheck.Stmt(as))
1405 init = append(init, ir.NewBranchStmt(base.Pos, ir.OGOTO, subst.retlabel))
1406 typecheck.Stmts(init)
1407 return ir.NewBlockStmt(base.Pos, init)
1409 case ir.OGOTO, ir.OBREAK, ir.OCONTINUE:
1410 if subst.newclofn != nil {
1411 // Don't do special substitutions if inside a closure
1414 n := n.(*ir.BranchStmt)
1415 m := ir.Copy(n).(*ir.BranchStmt)
1416 m.SetPos(subst.updatedPos(m.Pos()))
1418 m.Label = translateLabel(n.Label)
1422 if subst.newclofn != nil {
1423 // Don't do special substitutions if inside a closure
1426 n := n.(*ir.LabelStmt)
1427 m := ir.Copy(n).(*ir.LabelStmt)
1428 m.SetPos(subst.updatedPos(m.Pos()))
1430 m.Label = translateLabel(n.Label)
1434 return subst.closure(n.(*ir.ClosureExpr))
1439 m.SetPos(subst.updatedPos(m.Pos()))
1440 ir.EditChildren(m, subst.edit)
1442 if subst.newclofn == nil {
1443 // Translate any label on FOR, RANGE loops, SWITCH or SELECT
1446 m := m.(*ir.ForStmt)
1447 m.Label = translateLabel(m.Label)
1451 m := m.(*ir.RangeStmt)
1452 m.Label = translateLabel(m.Label)
1456 m := m.(*ir.SwitchStmt)
1457 m.Label = translateLabel(m.Label)
1461 m := m.(*ir.SelectStmt)
1462 m.Label = translateLabel(m.Label)
1467 switch m := m.(type) {
1468 case *ir.AssignStmt:
1469 if lhs, ok := m.X.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1472 case *ir.AssignListStmt:
1473 for _, lhs := range m.Lhs {
1474 if lhs, ok := lhs.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1483 // translateLabel makes a label from an inlined function (if non-nil) be unique by
1484 // adding "·inlgen".
1485 func translateLabel(l *types.Sym) *types.Sym {
1489 p := fmt.Sprintf("%s·%d", l.Name, inlgen)
1490 return typecheck.Lookup(p)
1493 func (subst *inlsubst) updatedPos(xpos src.XPos) src.XPos {
1494 if subst.noPosUpdate {
1497 pos := base.Ctxt.PosTable.Pos(xpos)
1498 oldbase := pos.Base() // can be nil
1499 newbase := subst.bases[oldbase]
1501 newbase = src.NewInliningBase(oldbase, subst.newInlIndex)
1502 subst.bases[oldbase] = newbase
1504 pos.SetBase(newbase)
1505 return base.Ctxt.PosTable.XPos(pos)
1508 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1509 s := make([]*ir.Name, 0, len(ll))
1510 for _, n := range ll {
1511 if n.Class == ir.PAUTO {
1512 if !vis.usedLocals.Has(n) {
1521 // numNonClosures returns the number of functions in list which are not closures.
1522 func numNonClosures(list []*ir.Func) int {
1524 for _, fn := range list {
1525 if fn.OClosure == nil {
1532 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1533 for _, x := range list {