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",
308 "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
309 "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
314 break // treat like any other node, that is, cost of 1
320 if ir.IsIntrinsicCall(n) {
321 // Treat like any other node.
325 if fn := inlCallee(n.X); fn != nil && typecheck.HaveInlineBody(fn) {
326 v.budget -= fn.Inl.Cost
330 // Call cost for non-leaf inlining.
331 v.budget -= v.extraCallCost
334 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
336 // Things that are too hairy, irrespective of the budget
337 case ir.OCALL, ir.OCALLINTER:
338 // Call cost for non-leaf inlining.
339 v.budget -= v.extraCallCost
342 n := n.(*ir.UnaryExpr)
343 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
344 // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
345 // Before CL 284412, these conversions were introduced later in the
346 // compiler, so they didn't count against inlining budget.
349 v.budget -= inlineExtraPanicCost
352 // recover matches the argument frame pointer to find
353 // the right panic value, so it needs an argument frame.
354 v.reason = "call to recover"
358 if base.Debug.InlFuncsWithClosures == 0 {
359 v.reason = "not inlining functions with closures"
363 // TODO(danscales): Maybe make budget proportional to number of closure
365 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
367 // Scan body of closure (which DoChildren doesn't automatically
368 // do) to check for disallowed ops in the body and include the
369 // body in the budget.
370 if doList(n.(*ir.ClosureExpr).Func.Body, v.do) {
376 ir.ODCLTYPE, // can't print yet
378 v.reason = "unhandled op " + n.Op().String()
382 v.budget -= inlineExtraAppendCost
385 // *(*X)(unsafe.Pointer(&x)) is low-cost
386 n := n.(*ir.StarExpr)
389 for ptr.Op() == ir.OCONVNOP {
390 ptr = ptr.(*ir.ConvExpr).X
392 if ptr.Op() == ir.OADDR {
393 v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
397 // This doesn't produce code, but the children might.
398 v.budget++ // undo default cost
400 case ir.ODCLCONST, ir.OFALL:
401 // These nodes don't produce code; omit from inlining budget.
406 if ir.IsConst(n.Cond, constant.Bool) {
407 // This if and the condition cost nothing.
408 if doList(n.Init(), v.do) {
411 if ir.BoolVal(n.Cond) {
412 return doList(n.Body, v.do)
414 return doList(n.Else, v.do)
420 if n.Class == ir.PAUTO {
425 // The only OBLOCK we should see at this point is an empty one.
426 // In any event, let the visitList(n.List()) below take care of the statements,
427 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
430 case ir.OMETHVALUE, ir.OSLICELIT:
431 v.budget-- // Hack for toolstash -cmp.
434 v.budget++ // Hack for toolstash -cmp.
437 n := n.(*ir.AssignListStmt)
439 // Unified IR unconditionally rewrites:
450 // so that it can insert implicit conversions as necessary. To
451 // minimize impact to the existing inlining heuristics (in
452 // particular, to avoid breaking the existing inlinability regress
453 // tests), we need to compensate for this here.
454 if base.Debug.Unified != 0 {
455 if init := n.Rhs[0].Init(); len(init) == 1 {
456 if _, ok := init[0].(*ir.AssignListStmt); ok {
457 // 4 for each value, because each temporary variable now
458 // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
460 // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
461 v.budget += 4*int32(len(n.Lhs)) + 1
469 // When debugging, don't stop early, to get full cost of inlining this function
470 if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
471 v.reason = "too expensive"
475 return ir.DoChildren(n, v.do)
478 func isBigFunc(fn *ir.Func) bool {
479 budget := inlineBigFunctionNodes
480 return ir.Any(fn, func(n ir.Node) bool {
486 // inlcopylist (together with inlcopy) recursively copies a list of nodes, except
487 // that it keeps the same ONAME, OTYPE, and OLITERAL nodes. It is used for copying
488 // the body and dcls of an inlineable function.
489 func inlcopylist(ll []ir.Node) []ir.Node {
490 s := make([]ir.Node, len(ll))
491 for i, n := range ll {
497 // inlcopy is like DeepCopy(), but does extra work to copy closures.
498 func inlcopy(n ir.Node) ir.Node {
499 var edit func(ir.Node) ir.Node
500 edit = func(x ir.Node) ir.Node {
502 case ir.ONAME, ir.OTYPE, ir.OLITERAL, ir.ONIL:
506 ir.EditChildren(m, edit)
507 if x.Op() == ir.OCLOSURE {
508 x := x.(*ir.ClosureExpr)
509 // Need to save/duplicate x.Func.Nname,
510 // x.Func.Nname.Ntype, x.Func.Dcl, x.Func.ClosureVars, and
511 // x.Func.Body for iexport and local inlining.
513 newfn := ir.NewFunc(oldfn.Pos())
514 m.(*ir.ClosureExpr).Func = newfn
515 newfn.Nname = ir.NewNameAt(oldfn.Nname.Pos(), oldfn.Nname.Sym())
516 // XXX OK to share fn.Type() ??
517 newfn.Nname.SetType(oldfn.Nname.Type())
518 newfn.Body = inlcopylist(oldfn.Body)
519 // Make shallow copy of the Dcl and ClosureVar slices
520 newfn.Dcl = append([]*ir.Name(nil), oldfn.Dcl...)
521 newfn.ClosureVars = append([]*ir.Name(nil), oldfn.ClosureVars...)
528 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
529 // calls made to inlineable functions. This is the external entry point.
530 func InlineCalls(fn *ir.Func) {
533 maxCost := int32(inlineMaxBudget)
535 maxCost = inlineBigFunctionMaxCost
537 var inlCalls []*ir.InlinedCallExpr
538 var edit func(ir.Node) ir.Node
539 edit = func(n ir.Node) ir.Node {
540 return inlnode(n, maxCost, &inlCalls, edit)
542 ir.EditChildren(fn, edit)
544 // If we inlined any calls, we want to recursively visit their
545 // bodies for further inlining. However, we need to wait until
546 // *after* the original function body has been expanded, or else
547 // inlCallee can have false positives (e.g., #54632).
548 for len(inlCalls) > 0 {
550 inlCalls = inlCalls[1:]
551 ir.EditChildren(call, edit)
557 // inlnode recurses over the tree to find inlineable calls, which will
558 // be turned into OINLCALLs by mkinlcall. When the recursion comes
559 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
560 // nbody and nelse and use one of the 4 inlconv/glue functions above
561 // to turn the OINLCALL into an expression, a statement, or patch it
562 // in to this nodes list or rlist as appropriate.
563 // NOTE it makes no sense to pass the glue functions down the
564 // recursion to the level where the OINLCALL gets created because they
565 // have to edit /this/ n, so you'd have to push that one down as well,
566 // but then you may as well do it here. so this is cleaner and
567 // shorter and less complicated.
568 // The result of inlnode MUST be assigned back to n, e.g.
570 // n.Left = inlnode(n.Left)
571 func inlnode(n ir.Node, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node) ir.Node {
577 case ir.ODEFER, ir.OGO:
578 n := n.(*ir.GoDeferStmt)
579 switch call := n.Call; call.Op() {
581 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
583 call := call.(*ir.CallExpr)
587 n := n.(*ir.TailCallStmt)
588 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
590 // TODO do them here (or earlier),
591 // so escape analysis can avoid more heapmoves.
595 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
597 n := n.(*ir.CallExpr)
598 if n.X.Op() == ir.OMETHEXPR {
599 // Prevent inlining some reflect.Value methods when using checkptr,
600 // even when package reflect was compiled without it (#35073).
601 if meth := ir.MethodExprName(n.X); meth != nil {
603 if base.Debug.Checkptr != 0 && types.IsReflectPkg(s.Pkg) && (s.Name == "Value.UnsafeAddr" || s.Name == "Value.Pointer") {
612 ir.EditChildren(n, edit)
614 // with all the branches out of the way, it is now time to
615 // transmogrify this node itself unless inhibited by the
616 // switch at the top of this function.
619 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
622 call := n.(*ir.CallExpr)
626 if base.Flag.LowerM > 3 {
627 fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.X)
629 if ir.IsIntrinsicCall(call) {
632 if fn := inlCallee(call.X); fn != nil && typecheck.HaveInlineBody(fn) {
633 n = mkinlcall(call, fn, maxCost, inlCalls, edit)
642 // inlCallee takes a function-typed expression and returns the underlying function ONAME
643 // that it refers to if statically known. Otherwise, it returns nil.
644 func inlCallee(fn ir.Node) *ir.Func {
645 fn = ir.StaticValue(fn)
648 fn := fn.(*ir.SelectorExpr)
649 n := ir.MethodExprName(fn)
650 // Check that receiver type matches fn.X.
651 // TODO(mdempsky): Handle implicit dereference
652 // of pointer receiver argument?
653 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
659 if fn.Class == ir.PFUNC {
663 fn := fn.(*ir.ClosureExpr)
671 func inlParam(t *types.Field, as ir.InitNode, inlvars map[*ir.Name]*ir.Name) ir.Node {
675 n := t.Nname.(*ir.Name)
681 base.Fatalf("missing inlvar for %v", n)
683 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, inlvar))
684 inlvar.Name().Defn = as
690 // SSADumpInline gives the SSA back end a chance to dump the function
691 // when producing output for debugging the compiler itself.
692 var SSADumpInline = func(*ir.Func) {}
694 // InlineCall allows the inliner implementation to be overridden.
695 // If it returns nil, the function will not be inlined.
696 var InlineCall = oldInlineCall
698 // If n is a OCALLFUNC node, and fn is an ONAME node for a
699 // function with an inlinable body, return an OINLCALL node that can replace n.
700 // The returned node's Ninit has the parameter assignments, the Nbody is the
701 // inlined function body, and (List, Rlist) contain the (input, output)
703 // The result of mkinlcall MUST be assigned back to n, e.g.
705 // n.Left = mkinlcall(n.Left, fn, isddd)
706 func mkinlcall(n *ir.CallExpr, fn *ir.Func, maxCost int32, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node) ir.Node {
708 if logopt.Enabled() {
709 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
710 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(fn)))
714 if fn.Inl.Cost > maxCost {
715 // The inlined function body is too big. Typically we use this check to restrict
716 // inlining into very big functions. See issue 26546 and 17566.
717 if logopt.Enabled() {
718 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
719 fmt.Sprintf("cost %d of %s exceeds max large caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), maxCost))
724 if fn == ir.CurFunc {
725 // Can't recursively inline a function into itself.
726 if logopt.Enabled() {
727 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(ir.CurFunc)))
732 // The non-unified frontend has issues with inlining and shape parameters.
733 if base.Debug.Unified == 0 {
734 // Don't inline a function fn that has no shape parameters, but is passed at
735 // least one shape arg. This means we must be inlining a non-generic function
736 // fn that was passed into a generic function, and can be called with a shape
737 // arg because it matches an appropriate type parameters. But fn may include
738 // an interface conversion (that may be applied to a shape arg) that was not
739 // apparent when we first created the instantiation of the generic function.
740 // We can't handle this if we actually do the inlining, since we want to know
741 // all interface conversions immediately after stenciling. So, we avoid
742 // inlining in this case, see issue #49309. (1)
744 // See discussion on go.dev/cl/406475 for more background.
745 if !fn.Type().Params().HasShape() {
746 for _, arg := range n.Args {
747 if arg.Type().HasShape() {
748 if logopt.Enabled() {
749 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
750 fmt.Sprintf("inlining function %v has no-shape params with shape args", ir.FuncName(fn)))
756 // Don't inline a function fn that has shape parameters, but is passed no shape arg.
757 // See comments (1) above, and issue #51909.
758 inlineable := len(n.Args) == 0 // Function has shape in type, with no arguments can always be inlined.
759 for _, arg := range n.Args {
760 if arg.Type().HasShape() {
766 if logopt.Enabled() {
767 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
768 fmt.Sprintf("inlining function %v has shape params with no-shape args", ir.FuncName(fn)))
775 if base.Flag.Cfg.Instrumenting && types.IsRuntimePkg(fn.Sym().Pkg) {
776 // Runtime package must not be instrumented.
777 // Instrument skips runtime package. However, some runtime code can be
778 // inlined into other packages and instrumented there. To avoid this,
779 // we disable inlining of runtime functions when instrumenting.
780 // The example that we observed is inlining of LockOSThread,
781 // which lead to false race reports on m contents.
785 parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
788 // Check if we've already inlined this function at this particular
789 // call site, in order to stop inlining when we reach the beginning
790 // of a recursion cycle again. We don't inline immediately recursive
791 // functions, but allow inlining if there is a recursion cycle of
792 // many functions. Most likely, the inlining will stop before we
793 // even hit the beginning of the cycle again, but this catches the
795 for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
796 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
797 if base.Flag.LowerM > 1 {
798 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), fn, ir.FuncName(ir.CurFunc))
804 typecheck.FixVariadicCall(n)
806 inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym)
808 if base.Flag.GenDwarfInl > 0 {
809 if !sym.WasInlined() {
810 base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
811 sym.Set(obj.AttrWasInlined, true)
815 if base.Flag.LowerM != 0 {
816 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
818 if base.Flag.LowerM > 2 {
819 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
822 res := InlineCall(n, fn, inlIndex)
824 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
827 if base.Flag.LowerM > 2 {
828 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
831 *inlCalls = append(*inlCalls, res)
836 // CalleeEffects appends any side effects from evaluating callee to init.
837 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
839 init.Append(ir.TakeInit(callee)...)
842 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
846 conv := callee.(*ir.ConvExpr)
850 ic := callee.(*ir.InlinedCallExpr)
851 init.Append(ic.Body.Take()...)
852 callee = ic.SingleResult()
855 base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
860 // oldInlineCall creates an InlinedCallExpr to replace the given call
861 // expression. fn is the callee function to be inlined. inlIndex is
862 // the inlining tree position index, for use with src.NewInliningBase
863 // when rewriting positions.
864 func oldInlineCall(call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
865 if base.Debug.TypecheckInl == 0 {
866 typecheck.ImportedBody(fn)
873 // For normal function calls, the function callee expression
874 // may contain side effects. Make sure to preserve these,
875 // if necessary (#42703).
876 if call.Op() == ir.OCALLFUNC {
877 CalleeEffects(&ninit, call.X)
880 // Make temp names to use instead of the originals.
881 inlvars := make(map[*ir.Name]*ir.Name)
883 // record formals/locals for later post-processing
884 var inlfvars []*ir.Name
886 for _, ln := range fn.Inl.Dcl {
887 if ln.Op() != ir.ONAME {
890 if ln.Class == ir.PPARAMOUT { // return values handled below.
893 inlf := typecheck.Expr(inlvar(ln)).(*ir.Name)
895 if base.Flag.GenDwarfInl > 0 {
896 if ln.Class == ir.PPARAM {
897 inlf.Name().SetInlFormal(true)
899 inlf.Name().SetInlLocal(true)
901 inlf.SetPos(ln.Pos())
902 inlfvars = append(inlfvars, inlf)
906 // We can delay declaring+initializing result parameters if:
907 // temporaries for return values.
908 var retvars []ir.Node
909 for i, t := range fn.Type().Results().Fields().Slice() {
911 if nn := t.Nname; nn != nil && !ir.IsBlank(nn.(*ir.Name)) && !strings.HasPrefix(nn.Sym().Name, "~r") {
914 m = typecheck.Expr(m).(*ir.Name)
917 // anonymous return values, synthesize names for use in assignment that replaces return
921 if base.Flag.GenDwarfInl > 0 {
922 // Don't update the src.Pos on a return variable if it
923 // was manufactured by the inliner (e.g. "~R2"); such vars
924 // were not part of the original callee.
925 if !strings.HasPrefix(m.Sym().Name, "~R") {
926 m.Name().SetInlFormal(true)
928 inlfvars = append(inlfvars, m)
932 retvars = append(retvars, m)
935 // Assign arguments to the parameters' temp names.
936 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
938 if call.Op() == ir.OCALLMETH {
939 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
941 as.Rhs.Append(call.Args...)
943 if recv := fn.Type().Recv(); recv != nil {
944 as.Lhs.Append(inlParam(recv, as, inlvars))
946 for _, param := range fn.Type().Params().Fields().Slice() {
947 as.Lhs.Append(inlParam(param, as, inlvars))
950 if len(as.Rhs) != 0 {
951 ninit.Append(typecheck.Stmt(as))
954 if !fn.Inl.CanDelayResults {
955 // Zero the return parameters.
956 for _, n := range retvars {
957 ninit.Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
958 ras := ir.NewAssignStmt(base.Pos, n, nil)
959 ninit.Append(typecheck.Stmt(ras))
963 retlabel := typecheck.AutoLabel(".i")
967 // Add an inline mark just before the inlined body.
968 // This mark is inline in the code so that it's a reasonable spot
969 // to put a breakpoint. Not sure if that's really necessary or not
970 // (in which case it could go at the end of the function instead).
972 ninit.Append(ir.NewInlineMarkStmt(call.Pos().WithIsStmt(), int64(inlIndex)))
978 defnMarker: ir.NilExpr{},
979 bases: make(map[*src.PosBase]*src.PosBase),
980 newInlIndex: inlIndex,
983 subst.edit = subst.node
985 body := subst.list(ir.Nodes(fn.Inl.Body))
987 lab := ir.NewLabelStmt(base.Pos, retlabel)
988 body = append(body, lab)
990 if base.Flag.GenDwarfInl > 0 {
991 for _, v := range inlfvars {
992 v.SetPos(subst.updatedPos(v.Pos()))
996 //dumplist("ninit post", ninit);
998 res := ir.NewInlinedCallExpr(base.Pos, body, retvars)
1000 res.SetType(call.Type())
1005 // Every time we expand a function we generate a new set of tmpnames,
1006 // PAUTO's in the calling functions, and link them off of the
1007 // PPARAM's, PAUTOS and PPARAMOUTs of the called function.
1008 func inlvar(var_ *ir.Name) *ir.Name {
1009 if base.Flag.LowerM > 3 {
1010 fmt.Printf("inlvar %+v\n", var_)
1013 n := typecheck.NewName(var_.Sym())
1014 n.SetType(var_.Type())
1018 n.SetAutoTemp(var_.AutoTemp())
1019 n.Curfn = ir.CurFunc // the calling function, not the called one
1020 n.SetAddrtaken(var_.Addrtaken())
1022 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1026 // Synthesize a variable to store the inlined function's results in.
1027 func retvar(t *types.Field, i int) *ir.Name {
1028 n := typecheck.NewName(typecheck.LookupNum("~R", i))
1033 n.Curfn = ir.CurFunc // the calling function, not the called one
1034 ir.CurFunc.Dcl = append(ir.CurFunc.Dcl, n)
1038 // The inlsubst type implements the actual inlining of a single
1040 type inlsubst struct {
1041 // Target of the goto substituted in place of a return.
1044 // Temporary result variables.
1047 inlvars map[*ir.Name]*ir.Name
1048 // defnMarker is used to mark a Node for reassignment.
1049 // inlsubst.clovar set this during creating new ONAME.
1050 // inlsubst.node will set the correct Defn for inlvar.
1051 defnMarker ir.NilExpr
1053 // bases maps from original PosBase to PosBase with an extra
1054 // inlined call frame.
1055 bases map[*src.PosBase]*src.PosBase
1057 // newInlIndex is the index of the inlined call frame to
1058 // insert for inlined nodes.
1061 edit func(ir.Node) ir.Node // cached copy of subst.node method value closure
1063 // If non-nil, we are inside a closure inside the inlined function, and
1064 // newclofn is the Func of the new inlined closure.
1067 fn *ir.Func // For debug -- the func that is being inlined
1069 // If true, then don't update source positions during substitution
1070 // (retain old source positions).
1074 // list inlines a list of nodes.
1075 func (subst *inlsubst) list(ll ir.Nodes) []ir.Node {
1076 s := make([]ir.Node, 0, len(ll))
1077 for _, n := range ll {
1078 s = append(s, subst.node(n))
1083 // fields returns a list of the fields of a struct type representing receiver,
1084 // params, or results, after duplicating the field nodes and substituting the
1085 // Nname nodes inside the field nodes.
1086 func (subst *inlsubst) fields(oldt *types.Type) []*types.Field {
1087 oldfields := oldt.FieldSlice()
1088 newfields := make([]*types.Field, len(oldfields))
1089 for i := range oldfields {
1090 newfields[i] = oldfields[i].Copy()
1091 if oldfields[i].Nname != nil {
1092 newfields[i].Nname = subst.node(oldfields[i].Nname.(*ir.Name))
1098 // clovar creates a new ONAME node for a local variable or param of a closure
1099 // inside a function being inlined.
1100 func (subst *inlsubst) clovar(n *ir.Name) *ir.Name {
1101 m := ir.NewNameAt(n.Pos(), n.Sym())
1105 if n.IsClosureVar() {
1106 m.SetIsClosureVar(true)
1109 m.SetAddrtaken(true)
1116 m.Curfn = subst.newclofn
1118 switch defn := n.Defn.(type) {
1122 if !n.IsClosureVar() {
1123 base.FatalfAt(n.Pos(), "want closure variable, got: %+v", n)
1125 if n.Sym().Pkg != types.LocalPkg {
1126 // If the closure came from inlining a function from
1127 // another package, must change package of captured
1128 // variable to localpkg, so that the fields of the closure
1129 // struct are local package and can be accessed even if
1130 // name is not exported. If you disable this code, you can
1131 // reproduce the problem by running 'go test
1132 // go/internal/srcimporter'. TODO(mdempsky) - maybe change
1133 // how we create closure structs?
1134 m.SetSym(types.LocalPkg.Lookup(n.Sym().Name))
1136 // Make sure any inlvar which is the Defn
1137 // of an ONAME closure var is rewritten
1138 // during inlining. Don't substitute
1139 // if Defn node is outside inlined function.
1140 if subst.inlvars[n.Defn.(*ir.Name)] != nil {
1141 m.Defn = subst.node(n.Defn)
1143 case *ir.AssignStmt, *ir.AssignListStmt:
1144 // Mark node for reassignment at the end of inlsubst.node.
1145 m.Defn = &subst.defnMarker
1146 case *ir.TypeSwitchGuard:
1147 // TODO(mdempsky): Set m.Defn properly. See discussion on #45743.
1149 // TODO: Set m.Defn properly if we support inlining range statement in the future.
1151 base.FatalfAt(n.Pos(), "unexpected Defn: %+v", defn)
1155 // Either the outer variable is defined in function being inlined,
1156 // and we will replace it with the substituted variable, or it is
1157 // defined outside the function being inlined, and we should just
1158 // skip the outer variable (the closure variable of the function
1160 s := subst.node(n.Outer).(*ir.Name)
1169 // closure does the necessary substitions for a ClosureExpr n and returns the new
1171 func (subst *inlsubst) closure(n *ir.ClosureExpr) ir.Node {
1172 // Prior to the subst edit, set a flag in the inlsubst to indicate
1173 // that we don't want to update the source positions in the new
1174 // closure function. If we do this, it will appear that the
1175 // closure itself has things inlined into it, which is not the
1176 // case. See issue #46234 for more details. At the same time, we
1177 // do want to update the position in the new ClosureExpr (which is
1178 // part of the function we're working on). See #49171 for an
1179 // example of what happens if we miss that update.
1180 newClosurePos := subst.updatedPos(n.Pos())
1181 defer func(prev bool) { subst.noPosUpdate = prev }(subst.noPosUpdate)
1182 subst.noPosUpdate = true
1184 //fmt.Printf("Inlining func %v with closure into %v\n", subst.fn, ir.FuncName(ir.CurFunc))
1187 newfn := ir.NewClosureFunc(oldfn.Pos(), true)
1189 if subst.newclofn != nil {
1190 //fmt.Printf("Inlining a closure with a nested closure\n")
1192 prevxfunc := subst.newclofn
1194 // Mark that we are now substituting within a closure (within the
1195 // inlined function), and create new nodes for all the local
1196 // vars/params inside this closure.
1197 subst.newclofn = newfn
1199 newfn.ClosureVars = nil
1200 for _, oldv := range oldfn.Dcl {
1201 newv := subst.clovar(oldv)
1202 subst.inlvars[oldv] = newv
1203 newfn.Dcl = append(newfn.Dcl, newv)
1205 for _, oldv := range oldfn.ClosureVars {
1206 newv := subst.clovar(oldv)
1207 subst.inlvars[oldv] = newv
1208 newfn.ClosureVars = append(newfn.ClosureVars, newv)
1211 // Need to replace ONAME nodes in
1212 // newfn.Type().FuncType().Receiver/Params/Results.FieldSlice().Nname
1213 oldt := oldfn.Type()
1214 newrecvs := subst.fields(oldt.Recvs())
1215 var newrecv *types.Field
1216 if len(newrecvs) > 0 {
1217 newrecv = newrecvs[0]
1219 newt := types.NewSignature(oldt.Pkg(), newrecv,
1220 nil, subst.fields(oldt.Params()), subst.fields(oldt.Results()))
1222 newfn.Nname.SetType(newt)
1223 newfn.Body = subst.list(oldfn.Body)
1225 // Remove the nodes for the current closure from subst.inlvars
1226 for _, oldv := range oldfn.Dcl {
1227 delete(subst.inlvars, oldv)
1229 for _, oldv := range oldfn.ClosureVars {
1230 delete(subst.inlvars, oldv)
1232 // Go back to previous closure func
1233 subst.newclofn = prevxfunc
1235 // Actually create the named function for the closure, now that
1236 // the closure is inlined in a specific function.
1237 newclo := newfn.OClosure
1238 newclo.SetPos(newClosurePos)
1239 newclo.SetInit(subst.list(n.Init()))
1240 return typecheck.Expr(newclo)
1243 // node recursively copies a node from the saved pristine body of the
1244 // inlined function, substituting references to input/output
1245 // parameters with ones to the tmpnames, and substituting returns with
1246 // assignments to the output.
1247 func (subst *inlsubst) node(n ir.Node) ir.Node {
1256 // Handle captured variables when inlining closures.
1257 if n.IsClosureVar() && subst.newclofn == nil {
1260 // Deal with case where sequence of closures are inlined.
1261 // TODO(danscales) - write test case to see if we need to
1262 // go up multiple levels.
1263 if o.Curfn != ir.CurFunc {
1267 // make sure the outer param matches the inlining location
1268 if o == nil || o.Curfn != ir.CurFunc {
1269 base.Fatalf("%v: unresolvable capture %v\n", ir.Line(n), n)
1272 if base.Flag.LowerM > 2 {
1273 fmt.Printf("substituting captured name %+v -> %+v\n", n, o)
1278 if inlvar := subst.inlvars[n]; inlvar != nil { // These will be set during inlnode
1279 if base.Flag.LowerM > 2 {
1280 fmt.Printf("substituting name %+v -> %+v\n", n, inlvar)
1285 if base.Flag.LowerM > 2 {
1286 fmt.Printf("not substituting name %+v\n", n)
1291 n := n.(*ir.SelectorExpr)
1294 case ir.OLITERAL, ir.ONIL, ir.OTYPE:
1295 // If n is a named constant or type, we can continue
1296 // using it in the inline copy. Otherwise, make a copy
1297 // so we can update the line number.
1303 if subst.newclofn != nil {
1304 // Don't do special substitutions if inside a closure
1307 // Because of the above test for subst.newclofn,
1308 // this return is guaranteed to belong to the current inlined function.
1309 n := n.(*ir.ReturnStmt)
1310 init := subst.list(n.Init())
1311 if len(subst.retvars) != 0 && len(n.Results) != 0 {
1312 as := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, nil)
1314 // Make a shallow copy of retvars.
1315 // Otherwise OINLCALL.Rlist will be the same list,
1316 // and later walk and typecheck may clobber it.
1317 for _, n := range subst.retvars {
1320 as.Rhs = subst.list(n.Results)
1322 if subst.fn.Inl.CanDelayResults {
1323 for _, n := range as.Lhs {
1324 as.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, n.(*ir.Name)))
1329 init = append(init, typecheck.Stmt(as))
1331 init = append(init, ir.NewBranchStmt(base.Pos, ir.OGOTO, subst.retlabel))
1332 typecheck.Stmts(init)
1333 return ir.NewBlockStmt(base.Pos, init)
1335 case ir.OGOTO, ir.OBREAK, ir.OCONTINUE:
1336 if subst.newclofn != nil {
1337 // Don't do special substitutions if inside a closure
1340 n := n.(*ir.BranchStmt)
1341 m := ir.Copy(n).(*ir.BranchStmt)
1342 m.SetPos(subst.updatedPos(m.Pos()))
1344 m.Label = translateLabel(n.Label)
1348 if subst.newclofn != nil {
1349 // Don't do special substitutions if inside a closure
1352 n := n.(*ir.LabelStmt)
1353 m := ir.Copy(n).(*ir.LabelStmt)
1354 m.SetPos(subst.updatedPos(m.Pos()))
1356 m.Label = translateLabel(n.Label)
1360 return subst.closure(n.(*ir.ClosureExpr))
1365 m.SetPos(subst.updatedPos(m.Pos()))
1366 ir.EditChildren(m, subst.edit)
1368 if subst.newclofn == nil {
1369 // Translate any label on FOR, RANGE loops, SWITCH or SELECT
1372 m := m.(*ir.ForStmt)
1373 m.Label = translateLabel(m.Label)
1377 m := m.(*ir.RangeStmt)
1378 m.Label = translateLabel(m.Label)
1382 m := m.(*ir.SwitchStmt)
1383 m.Label = translateLabel(m.Label)
1387 m := m.(*ir.SelectStmt)
1388 m.Label = translateLabel(m.Label)
1393 switch m := m.(type) {
1394 case *ir.AssignStmt:
1395 if lhs, ok := m.X.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1398 case *ir.AssignListStmt:
1399 for _, lhs := range m.Lhs {
1400 if lhs, ok := lhs.(*ir.Name); ok && lhs.Defn == &subst.defnMarker {
1409 // translateLabel makes a label from an inlined function (if non-nil) be unique by
1410 // adding "·inlgen".
1411 func translateLabel(l *types.Sym) *types.Sym {
1415 p := fmt.Sprintf("%s·%d", l.Name, inlgen)
1416 return typecheck.Lookup(p)
1419 func (subst *inlsubst) updatedPos(xpos src.XPos) src.XPos {
1420 if subst.noPosUpdate {
1423 pos := base.Ctxt.PosTable.Pos(xpos)
1424 oldbase := pos.Base() // can be nil
1425 newbase := subst.bases[oldbase]
1427 newbase = src.NewInliningBase(oldbase, subst.newInlIndex)
1428 subst.bases[oldbase] = newbase
1430 pos.SetBase(newbase)
1431 return base.Ctxt.PosTable.XPos(pos)
1434 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1435 s := make([]*ir.Name, 0, len(ll))
1436 for _, n := range ll {
1437 if n.Class == ir.PAUTO {
1438 if !vis.usedLocals.Has(n) {
1447 // numNonClosures returns the number of functions in list which are not closures.
1448 func numNonClosures(list []*ir.Func) int {
1450 for _, fn := range list {
1451 if fn.OClosure == nil {
1458 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1459 for _, x := range list {