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 CanInline 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.
35 "cmd/compile/internal/base"
36 "cmd/compile/internal/ir"
37 "cmd/compile/internal/logopt"
38 "cmd/compile/internal/pgo"
39 "cmd/compile/internal/typecheck"
40 "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.
58 // List of all hot callee nodes.
59 // TODO(prattmic): Make this non-global.
60 candHotCalleeMap = make(map[*pgo.IRNode]struct{})
62 // List of all hot call sites. CallSiteInfo.Callee is always nil.
63 // TODO(prattmic): Make this non-global.
64 candHotEdgeMap = make(map[pgo.CallSiteInfo]struct{})
66 // Threshold in percentage for hot callsite inlining.
67 inlineHotCallSiteThresholdPercent float64
69 // Threshold in CDF percentage for hot callsite inlining,
70 // that is, for a threshold of X the hottest callsites that
71 // make up the top X% of total edge weight will be
72 // considered hot for inlining candidates.
73 inlineCDFHotCallSiteThresholdPercent = float64(99)
75 // Budget increased due to hotness.
76 inlineHotMaxBudget int32 = 2000
79 // pgoInlinePrologue records the hot callsites from ir-graph.
80 func pgoInlinePrologue(p *pgo.Profile, decls []ir.Node) {
81 if base.Debug.PGOInlineCDFThreshold != "" {
82 if s, err := strconv.ParseFloat(base.Debug.PGOInlineCDFThreshold, 64); err == nil && s >= 0 && s <= 100 {
83 inlineCDFHotCallSiteThresholdPercent = s
85 base.Fatalf("invalid PGOInlineCDFThreshold, must be between 0 and 100")
88 var hotCallsites []pgo.NodeMapKey
89 inlineHotCallSiteThresholdPercent, hotCallsites = hotNodesFromCDF(p)
90 if base.Debug.PGOInline > 0 {
91 fmt.Printf("hot-callsite-thres-from-CDF=%v\n", inlineHotCallSiteThresholdPercent)
94 if x := base.Debug.PGOInlineBudget; x != 0 {
95 inlineHotMaxBudget = int32(x)
98 for _, n := range hotCallsites {
99 // mark inlineable callees from hot edges
100 if callee := p.WeightedCG.IRNodes[n.CalleeName]; callee != nil {
101 candHotCalleeMap[callee] = struct{}{}
103 // mark hot call sites
104 if caller := p.WeightedCG.IRNodes[n.CallerName]; caller != nil {
105 csi := pgo.CallSiteInfo{LineOffset: n.CallSiteOffset, Caller: caller.AST}
106 candHotEdgeMap[csi] = struct{}{}
110 if base.Debug.PGOInline >= 2 {
111 fmt.Printf("hot-cg before inline in dot format:")
112 p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
116 // hotNodesFromCDF computes an edge weight threshold and the list of hot
117 // nodes that make up the given percentage of the CDF. The threshold, as
118 // a percent, is the lower bound of weight for nodes to be considered hot
119 // (currently only used in debug prints) (in case of equal weights,
120 // comparing with the threshold may not accurately reflect which nodes are
122 func hotNodesFromCDF(p *pgo.Profile) (float64, []pgo.NodeMapKey) {
123 nodes := make([]pgo.NodeMapKey, len(p.NodeMap))
125 for n := range p.NodeMap {
129 sort.Slice(nodes, func(i, j int) bool {
130 ni, nj := nodes[i], nodes[j]
131 if wi, wj := p.NodeMap[ni].EWeight, p.NodeMap[nj].EWeight; wi != wj {
132 return wi > wj // want larger weight first
134 // same weight, order by name/line number
135 if ni.CallerName != nj.CallerName {
136 return ni.CallerName < nj.CallerName
138 if ni.CalleeName != nj.CalleeName {
139 return ni.CalleeName < nj.CalleeName
141 return ni.CallSiteOffset < nj.CallSiteOffset
144 for i, n := range nodes {
145 w := p.NodeMap[n].EWeight
147 if pgo.WeightInPercentage(cum, p.TotalEdgeWeight) > inlineCDFHotCallSiteThresholdPercent {
148 // nodes[:i+1] to include the very last node that makes it to go over the threshold.
149 // (Say, if the CDF threshold is 50% and one hot node takes 60% of weight, we want to
150 // include that node instead of excluding it.)
151 return pgo.WeightInPercentage(w, p.TotalEdgeWeight), nodes[:i+1]
157 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
158 func InlinePackage(p *pgo.Profile) {
159 InlineDecls(p, typecheck.Target.Decls, true)
161 // Perform a garbage collection of hidden closures functions that
162 // are no longer reachable from top-level functions following
163 // inlining. See #59404 and #59638 for more context.
164 garbageCollectUnreferencedHiddenClosures()
167 // InlineDecls applies inlining to the given batch of declarations.
168 func InlineDecls(p *pgo.Profile, decls []ir.Node, doInline bool) {
170 pgoInlinePrologue(p, decls)
173 doCanInline := func(n *ir.Func, recursive bool, numfns int) {
174 if !recursive || numfns > 1 {
175 // We allow inlining if there is no
176 // recursion, or the recursion cycle is
177 // across more than one function.
180 if base.Flag.LowerM > 1 && n.OClosure == nil {
181 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
186 ir.VisitFuncsBottomUp(decls, func(list []*ir.Func, recursive bool) {
187 numfns := numNonClosures(list)
188 // We visit functions within an SCC in fairly arbitrary order,
189 // so by computing inlinability for all functions in the SCC
190 // before performing any inlining, the results are less
191 // sensitive to the order within the SCC (see #58905 for an
194 // First compute inlinability for all functions in the SCC ...
195 for _, n := range list {
196 doCanInline(n, recursive, numfns)
198 // ... then make a second pass to do inlining of calls.
200 for _, n := range list {
207 // garbageCollectUnreferencedHiddenClosures makes a pass over all the
208 // top-level (non-hidden-closure) functions looking for nested closure
209 // functions that are reachable, then sweeps through the Target.Decls
210 // list and marks any non-reachable hidden closure function as dead.
211 // See issues #59404 and #59638 for more context.
212 func garbageCollectUnreferencedHiddenClosures() {
214 liveFuncs := make(map[*ir.Func]bool)
216 var markLiveFuncs func(fn *ir.Func)
217 markLiveFuncs = func(fn *ir.Func) {
222 ir.Visit(fn, func(n ir.Node) {
223 if clo, ok := n.(*ir.ClosureExpr); ok {
224 markLiveFuncs(clo.Func)
229 for i := 0; i < len(typecheck.Target.Decls); i++ {
230 if fn, ok := typecheck.Target.Decls[i].(*ir.Func); ok {
231 if fn.IsHiddenClosure() {
238 for i := 0; i < len(typecheck.Target.Decls); i++ {
239 if fn, ok := typecheck.Target.Decls[i].(*ir.Func); ok {
240 if !fn.IsHiddenClosure() {
243 if fn.IsDeadcodeClosure() {
249 fn.SetIsDeadcodeClosure(true)
250 if base.Flag.LowerM > 2 {
251 fmt.Printf("%v: unreferenced closure %v marked as dead\n", ir.Line(fn), fn)
253 if fn.Inl != nil && fn.LSym == nil {
254 ir.InitLSym(fn, true)
260 // CanInline determines whether fn is inlineable.
261 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
262 // fn and fn.Body will already have been typechecked.
263 func CanInline(fn *ir.Func, profile *pgo.Profile) {
265 base.Fatalf("CanInline no nname %+v", fn)
268 var reason string // reason, if any, that the function was not inlined
269 if base.Flag.LowerM > 1 || logopt.Enabled() {
272 if base.Flag.LowerM > 1 {
273 fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
275 if logopt.Enabled() {
276 logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
282 // If marked "go:noinline", don't inline
283 if fn.Pragma&ir.Noinline != 0 {
284 reason = "marked go:noinline"
288 // If marked "go:norace" and -race compilation, don't inline.
289 if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
290 reason = "marked go:norace with -race compilation"
294 // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
295 if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
296 reason = "marked go:nocheckptr"
300 // If marked "go:cgo_unsafe_args", don't inline, since the
301 // function makes assumptions about its argument frame layout.
302 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
303 reason = "marked go:cgo_unsafe_args"
307 // If marked as "go:uintptrkeepalive", don't inline, since the
308 // keep alive information is lost during inlining.
310 // TODO(prattmic): This is handled on calls during escape analysis,
311 // which is after inlining. Move prior to inlining so the keep-alive is
312 // maintained after inlining.
313 if fn.Pragma&ir.UintptrKeepAlive != 0 {
314 reason = "marked as having a keep-alive uintptr argument"
318 // If marked as "go:uintptrescapes", don't inline, since the
319 // escape information is lost during inlining.
320 if fn.Pragma&ir.UintptrEscapes != 0 {
321 reason = "marked as having an escaping uintptr argument"
325 // The nowritebarrierrec checker currently works at function
326 // granularity, so inlining yeswritebarrierrec functions can
327 // confuse it (#22342). As a workaround, disallow inlining
329 if fn.Pragma&ir.Yeswritebarrierrec != 0 {
330 reason = "marked go:yeswritebarrierrec"
334 // If fn has no body (is defined outside of Go), cannot inline it.
335 if len(fn.Body) == 0 {
336 reason = "no function body"
340 // If fn is synthetic hash or eq function, cannot inline it.
341 // The function is not generated in Unified IR frontend at this moment.
342 if ir.IsEqOrHashFunc(fn) {
343 reason = "type eq/hash function"
347 if fn.Typecheck() == 0 {
348 base.Fatalf("CanInline on non-typechecked function %v", fn)
352 if n.Func.InlinabilityChecked() {
355 defer n.Func.SetInlinabilityChecked(true)
357 cc := int32(inlineExtraCallCost)
358 if base.Flag.LowerL == 4 {
359 cc = 1 // this appears to yield better performance than 0.
362 // Update the budget for profile-guided inlining.
363 budget := int32(inlineMaxBudget)
365 if n, ok := profile.WeightedCG.IRNodes[ir.LinkFuncName(fn)]; ok {
366 if _, ok := candHotCalleeMap[n]; ok {
367 budget = int32(inlineHotMaxBudget)
368 if base.Debug.PGOInline > 0 {
369 fmt.Printf("hot-node enabled increased budget=%v for func=%v\n", budget, ir.PkgFuncName(fn))
375 // At this point in the game the function we're looking at may
376 // have "stale" autos, vars that still appear in the Dcl list, but
377 // which no longer have any uses in the function body (due to
378 // elimination by deadcode). We'd like to exclude these dead vars
379 // when creating the "Inline.Dcl" field below; to accomplish this,
380 // the hairyVisitor below builds up a map of used/referenced
381 // locals, and we use this map to produce a pruned Inline.Dcl
382 // list. See issue 25249 for more context.
384 visitor := hairyVisitor{
391 if visitor.tooHairy(fn) {
392 reason = visitor.reason
396 n.Func.Inl = &ir.Inline{
397 Cost: budget - visitor.budget,
398 Dcl: pruneUnusedAutos(n.Defn.(*ir.Func).Dcl, &visitor),
399 Body: inlcopylist(fn.Body),
401 CanDelayResults: canDelayResults(fn),
404 if base.Flag.LowerM > 1 {
405 fmt.Printf("%v: can inline %v with cost %d as: %v { %v }\n", ir.Line(fn), n, budget-visitor.budget, fn.Type(), ir.Nodes(n.Func.Inl.Body))
406 } else if base.Flag.LowerM != 0 {
407 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
409 if logopt.Enabled() {
410 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", budget-visitor.budget))
414 // canDelayResults reports whether inlined calls to fn can delay
415 // declaring the result parameter until the "return" statement.
416 func canDelayResults(fn *ir.Func) bool {
417 // We can delay declaring+initializing result parameters if:
418 // (1) there's exactly one "return" statement in the inlined function;
419 // (2) it's not an empty return statement (#44355); and
420 // (3) the result parameters aren't named.
423 ir.VisitList(fn.Body, func(n ir.Node) {
424 if n, ok := n.(*ir.ReturnStmt); ok {
426 if len(n.Results) == 0 {
427 nreturns++ // empty return statement (case 2)
433 return false // not exactly one return statement (case 1)
436 // temporaries for return values.
437 for _, param := range fn.Type().Results().FieldSlice() {
438 if sym := types.OrigSym(param.Sym); sym != nil && !sym.IsBlank() {
439 return false // found a named result parameter (case 3)
446 // hairyVisitor visits a function body to determine its inlining
447 // hairiness and whether or not it can be inlined.
448 type hairyVisitor struct {
449 // This is needed to access the current caller in the doNode function.
455 usedLocals ir.NameSet
456 do func(ir.Node) bool
460 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
461 v.do = v.doNode // cache closure
462 if ir.DoChildren(fn, v.do) {
466 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", v.maxBudget-v.budget, v.maxBudget)
472 // doNode visits n and its children, updates the state in v, and returns true if
473 // n makes the current function too hairy for inlining.
474 func (v *hairyVisitor) doNode(n ir.Node) bool {
479 // Call is okay if inlinable and we have the budget for the body.
481 n := n.(*ir.CallExpr)
482 // Functions that call runtime.getcaller{pc,sp} can not be inlined
483 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
485 // runtime.throw is a "cheap call" like panic in normal code.
487 if n.X.Op() == ir.ONAME {
488 name := n.X.(*ir.Name)
489 if name.Class == ir.PFUNC && types.IsRuntimePkg(name.Sym().Pkg) {
490 fn := name.Sym().Name
491 if fn == "getcallerpc" || fn == "getcallersp" {
492 v.reason = "call to " + fn
496 v.budget -= inlineExtraThrowCost
500 // Special case for reflect.noescpae. It does just type
501 // conversions to appease the escape analysis, and doesn't
503 if name.Class == ir.PFUNC && types.IsReflectPkg(name.Sym().Pkg) {
504 if name.Sym().Name == "noescape" {
508 // Special case for coverage counter updates; although
509 // these correspond to real operations, we treat them as
510 // zero cost for the moment. This is due to the existence
511 // of tests that are sensitive to inlining-- if the
512 // insertion of coverage instrumentation happens to tip a
513 // given function over the threshold and move it from
514 // "inlinable" to "not-inlinable", this can cause changes
515 // in allocation behavior, which can then result in test
516 // failures (a good example is the TestAllocations in
518 if isAtomicCoverageCounterUpdate(n) {
522 if n.X.Op() == ir.OMETHEXPR {
523 if meth := ir.MethodExprName(n.X); meth != nil {
524 if fn := meth.Func; fn != nil {
526 if types.IsRuntimePkg(s.Pkg) && s.Name == "heapBits.nextArena" {
527 // Special case: explicitly allow mid-stack inlining of
528 // runtime.heapBits.next even though it calls slow-path
529 // runtime.heapBits.nextArena.
532 // Special case: on architectures that can do unaligned loads,
533 // explicitly mark encoding/binary methods as cheap,
534 // because in practice they are, even though our inlining
535 // budgeting system does not see that. See issue 42958.
536 if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
538 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
539 "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
540 "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
541 "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
542 "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
543 "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
551 break // treat like any other node, that is, cost of 1
554 // Determine if the callee edge is for an inlinable hot callee or not.
555 if v.profile != nil && v.curFunc != nil {
556 if fn := inlCallee(n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
557 lineOffset := pgo.NodeLineOffset(n, fn)
558 csi := pgo.CallSiteInfo{LineOffset: lineOffset, Caller: v.curFunc}
559 if _, o := candHotEdgeMap[csi]; o {
560 if base.Debug.PGOInline > 0 {
561 fmt.Printf("hot-callsite identified at line=%v for func=%v\n", ir.Line(n), ir.PkgFuncName(v.curFunc))
567 if ir.IsIntrinsicCall(n) {
568 // Treat like any other node.
572 if fn := inlCallee(n.X, v.profile); fn != nil && typecheck.HaveInlineBody(fn) {
573 v.budget -= fn.Inl.Cost
577 // Call cost for non-leaf inlining.
578 v.budget -= v.extraCallCost
581 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
583 // Things that are too hairy, irrespective of the budget
584 case ir.OCALL, ir.OCALLINTER:
585 // Call cost for non-leaf inlining.
586 v.budget -= v.extraCallCost
589 n := n.(*ir.UnaryExpr)
590 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
591 // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
592 // Before CL 284412, these conversions were introduced later in the
593 // compiler, so they didn't count against inlining budget.
596 v.budget -= inlineExtraPanicCost
599 // recover matches the argument frame pointer to find
600 // the right panic value, so it needs an argument frame.
601 v.reason = "call to recover"
605 if base.Debug.InlFuncsWithClosures == 0 {
606 v.reason = "not inlining functions with closures"
610 // TODO(danscales): Maybe make budget proportional to number of closure
612 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
613 // TODO(austin): However, if we're able to inline this closure into
614 // v.curFunc, then we actually pay nothing for the closure captures. We
615 // should try to account for that if we're going to account for captures.
620 ir.ODCLTYPE, // can't print yet
622 v.reason = "unhandled op " + n.Op().String()
626 v.budget -= inlineExtraAppendCost
629 n := n.(*ir.AddrExpr)
630 // Make "&s.f" cost 0 when f's offset is zero.
631 if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
632 if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
633 v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
638 // *(*X)(unsafe.Pointer(&x)) is low-cost
639 n := n.(*ir.StarExpr)
642 for ptr.Op() == ir.OCONVNOP {
643 ptr = ptr.(*ir.ConvExpr).X
645 if ptr.Op() == ir.OADDR {
646 v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
650 // This doesn't produce code, but the children might.
651 v.budget++ // undo default cost
653 case ir.ODCLCONST, ir.OFALL, ir.OTYPE:
654 // These nodes don't produce code; omit from inlining budget.
659 if ir.IsConst(n.Cond, constant.Bool) {
660 // This if and the condition cost nothing.
661 if doList(n.Init(), v.do) {
664 if ir.BoolVal(n.Cond) {
665 return doList(n.Body, v.do)
667 return doList(n.Else, v.do)
673 if n.Class == ir.PAUTO {
678 // The only OBLOCK we should see at this point is an empty one.
679 // In any event, let the visitList(n.List()) below take care of the statements,
680 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
683 case ir.OMETHVALUE, ir.OSLICELIT:
684 v.budget-- // Hack for toolstash -cmp.
687 v.budget++ // Hack for toolstash -cmp.
690 n := n.(*ir.AssignListStmt)
692 // Unified IR unconditionally rewrites:
703 // so that it can insert implicit conversions as necessary. To
704 // minimize impact to the existing inlining heuristics (in
705 // particular, to avoid breaking the existing inlinability regress
706 // tests), we need to compensate for this here.
708 // See also identical logic in isBigFunc.
709 if init := n.Rhs[0].Init(); len(init) == 1 {
710 if _, ok := init[0].(*ir.AssignListStmt); ok {
711 // 4 for each value, because each temporary variable now
712 // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
714 // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
715 v.budget += 4*int32(len(n.Lhs)) + 1
720 // Special case for coverage counter updates and coverage
721 // function registrations. Although these correspond to real
722 // operations, we treat them as zero cost for the moment. This
723 // is primarily due to the existence of tests that are
724 // sensitive to inlining-- if the insertion of coverage
725 // instrumentation happens to tip a given function over the
726 // threshold and move it from "inlinable" to "not-inlinable",
727 // this can cause changes in allocation behavior, which can
728 // then result in test failures (a good example is the
729 // TestAllocations in crypto/ed25519).
730 n := n.(*ir.AssignStmt)
731 if n.X.Op() == ir.OINDEX && isIndexingCoverageCounter(n.X) {
738 // When debugging, don't stop early, to get full cost of inlining this function
739 if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
740 v.reason = "too expensive"
744 return ir.DoChildren(n, v.do)
747 func isBigFunc(fn *ir.Func) bool {
748 budget := inlineBigFunctionNodes
749 return ir.Any(fn, func(n ir.Node) bool {
750 // See logic in hairyVisitor.doNode, explaining unified IR's
751 // handling of "a, b = f()" assignments.
752 if n, ok := n.(*ir.AssignListStmt); ok && n.Op() == ir.OAS2 {
753 if init := n.Rhs[0].Init(); len(init) == 1 {
754 if _, ok := init[0].(*ir.AssignListStmt); ok {
755 budget += 4*len(n.Lhs) + 1
765 // inlcopylist (together with inlcopy) recursively copies a list of nodes, except
766 // that it keeps the same ONAME, OTYPE, and OLITERAL nodes. It is used for copying
767 // the body and dcls of an inlineable function.
768 func inlcopylist(ll []ir.Node) []ir.Node {
769 s := make([]ir.Node, len(ll))
770 for i, n := range ll {
776 // inlcopy is like DeepCopy(), but does extra work to copy closures.
777 func inlcopy(n ir.Node) ir.Node {
778 var edit func(ir.Node) ir.Node
779 edit = func(x ir.Node) ir.Node {
781 case ir.ONAME, ir.OTYPE, ir.OLITERAL, ir.ONIL:
785 ir.EditChildren(m, edit)
786 if x.Op() == ir.OCLOSURE {
787 x := x.(*ir.ClosureExpr)
788 // Need to save/duplicate x.Func.Nname,
789 // x.Func.Nname.Ntype, x.Func.Dcl, x.Func.ClosureVars, and
790 // x.Func.Body for iexport and local inlining.
792 newfn := ir.NewFunc(oldfn.Pos())
793 m.(*ir.ClosureExpr).Func = newfn
794 newfn.Nname = ir.NewNameAt(oldfn.Nname.Pos(), oldfn.Nname.Sym())
795 // XXX OK to share fn.Type() ??
796 newfn.Nname.SetType(oldfn.Nname.Type())
797 newfn.Body = inlcopylist(oldfn.Body)
798 // Make shallow copy of the Dcl and ClosureVar slices
799 newfn.Dcl = append([]*ir.Name(nil), oldfn.Dcl...)
800 newfn.ClosureVars = append([]*ir.Name(nil), oldfn.ClosureVars...)
807 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
808 // calls made to inlineable functions. This is the external entry point.
809 func InlineCalls(fn *ir.Func, profile *pgo.Profile) {
812 bigCaller := isBigFunc(fn)
813 if bigCaller && base.Flag.LowerM > 1 {
814 fmt.Printf("%v: function %v considered 'big'; reducing max cost of inlinees\n", ir.Line(fn), fn)
816 var inlCalls []*ir.InlinedCallExpr
817 var edit func(ir.Node) ir.Node
818 edit = func(n ir.Node) ir.Node {
819 return inlnode(n, bigCaller, &inlCalls, edit, profile)
821 ir.EditChildren(fn, edit)
823 // If we inlined any calls, we want to recursively visit their
824 // bodies for further inlining. However, we need to wait until
825 // *after* the original function body has been expanded, or else
826 // inlCallee can have false positives (e.g., #54632).
827 for len(inlCalls) > 0 {
829 inlCalls = inlCalls[1:]
830 ir.EditChildren(call, edit)
836 // inlnode recurses over the tree to find inlineable calls, which will
837 // be turned into OINLCALLs by mkinlcall. When the recursion comes
838 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
839 // nbody and nelse and use one of the 4 inlconv/glue functions above
840 // to turn the OINLCALL into an expression, a statement, or patch it
841 // in to this nodes list or rlist as appropriate.
842 // NOTE it makes no sense to pass the glue functions down the
843 // recursion to the level where the OINLCALL gets created because they
844 // have to edit /this/ n, so you'd have to push that one down as well,
845 // but then you may as well do it here. so this is cleaner and
846 // shorter and less complicated.
847 // The result of inlnode MUST be assigned back to n, e.g.
849 // n.Left = inlnode(n.Left)
850 func inlnode(n ir.Node, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node, profile *pgo.Profile) ir.Node {
856 case ir.ODEFER, ir.OGO:
857 n := n.(*ir.GoDeferStmt)
858 switch call := n.Call; call.Op() {
860 base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
862 call := call.(*ir.CallExpr)
866 n := n.(*ir.TailCallStmt)
867 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
869 // TODO do them here (or earlier),
870 // so escape analysis can avoid more heapmoves.
874 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
876 n := n.(*ir.CallExpr)
877 if n.X.Op() == ir.OMETHEXPR {
878 // Prevent inlining some reflect.Value methods when using checkptr,
879 // even when package reflect was compiled without it (#35073).
880 if meth := ir.MethodExprName(n.X); meth != nil {
882 if base.Debug.Checkptr != 0 && types.IsReflectPkg(s.Pkg) && (s.Name == "Value.UnsafeAddr" || s.Name == "Value.Pointer") {
891 ir.EditChildren(n, edit)
893 // with all the branches out of the way, it is now time to
894 // transmogrify this node itself unless inhibited by the
895 // switch at the top of this function.
898 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
901 call := n.(*ir.CallExpr)
905 if base.Flag.LowerM > 3 {
906 fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.X)
908 if ir.IsIntrinsicCall(call) {
911 if fn := inlCallee(call.X, profile); fn != nil && typecheck.HaveInlineBody(fn) {
912 n = mkinlcall(call, fn, bigCaller, inlCalls)
921 // inlCallee takes a function-typed expression and returns the underlying function ONAME
922 // that it refers to if statically known. Otherwise, it returns nil.
923 func inlCallee(fn ir.Node, profile *pgo.Profile) *ir.Func {
924 fn = ir.StaticValue(fn)
927 fn := fn.(*ir.SelectorExpr)
928 n := ir.MethodExprName(fn)
929 // Check that receiver type matches fn.X.
930 // TODO(mdempsky): Handle implicit dereference
931 // of pointer receiver argument?
932 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
938 if fn.Class == ir.PFUNC {
942 fn := fn.(*ir.ClosureExpr)
944 CanInline(c, profile)
952 // SSADumpInline gives the SSA back end a chance to dump the function
953 // when producing output for debugging the compiler itself.
954 var SSADumpInline = func(*ir.Func) {}
956 // InlineCall allows the inliner implementation to be overridden.
957 // If it returns nil, the function will not be inlined.
958 var InlineCall = func(call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
959 base.Fatalf("inline.InlineCall not overridden")
963 // inlineCostOK returns true if call n from caller to callee is cheap enough to
964 // inline. bigCaller indicates that caller is a big function.
966 // If inlineCostOK returns false, it also returns the max cost that the callee
968 func inlineCostOK(n *ir.CallExpr, caller, callee *ir.Func, bigCaller bool) (bool, int32) {
969 maxCost := int32(inlineMaxBudget)
971 // We use this to restrict inlining into very big functions.
972 // See issue 26546 and 17566.
973 maxCost = inlineBigFunctionMaxCost
976 if callee.Inl.Cost <= maxCost {
977 // Simple case. Function is already cheap enough.
981 // We'll also allow inlining of hot functions below inlineHotMaxBudget,
982 // but only in small functions.
984 lineOffset := pgo.NodeLineOffset(n, caller)
985 csi := pgo.CallSiteInfo{LineOffset: lineOffset, Caller: caller}
986 if _, ok := candHotEdgeMap[csi]; !ok {
988 return false, maxCost
994 if base.Debug.PGOInline > 0 {
995 fmt.Printf("hot-big check disallows inlining for call %s (cost %d) at %v in big function %s\n", ir.PkgFuncName(callee), callee.Inl.Cost, ir.Line(n), ir.PkgFuncName(caller))
997 return false, maxCost
1000 if callee.Inl.Cost > inlineHotMaxBudget {
1001 return false, inlineHotMaxBudget
1004 if base.Debug.PGOInline > 0 {
1005 fmt.Printf("hot-budget check allows inlining for call %s (cost %d) at %v in function %s\n", ir.PkgFuncName(callee), callee.Inl.Cost, ir.Line(n), ir.PkgFuncName(caller))
1011 // If n is a OCALLFUNC node, and fn is an ONAME node for a
1012 // function with an inlinable body, return an OINLCALL node that can replace n.
1013 // The returned node's Ninit has the parameter assignments, the Nbody is the
1014 // inlined function body, and (List, Rlist) contain the (input, output)
1016 // The result of mkinlcall MUST be assigned back to n, e.g.
1018 // n.Left = mkinlcall(n.Left, fn, isddd)
1019 func mkinlcall(n *ir.CallExpr, fn *ir.Func, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr) ir.Node {
1021 if logopt.Enabled() {
1022 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
1023 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(fn)))
1028 if ok, maxCost := inlineCostOK(n, ir.CurFunc, fn, bigCaller); !ok {
1029 if logopt.Enabled() {
1030 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(ir.CurFunc),
1031 fmt.Sprintf("cost %d of %s exceeds max caller cost %d", fn.Inl.Cost, ir.PkgFuncName(fn), maxCost))
1036 if fn == ir.CurFunc {
1037 // Can't recursively inline a function into itself.
1038 if logopt.Enabled() {
1039 logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(ir.CurFunc)))
1044 if base.Flag.Cfg.Instrumenting && types.IsNoInstrumentPkg(fn.Sym().Pkg) {
1045 // Runtime package must not be instrumented.
1046 // Instrument skips runtime package. However, some runtime code can be
1047 // inlined into other packages and instrumented there. To avoid this,
1048 // we disable inlining of runtime functions when instrumenting.
1049 // The example that we observed is inlining of LockOSThread,
1050 // which lead to false race reports on m contents.
1053 if base.Flag.Race && types.IsNoRacePkg(fn.Sym().Pkg) {
1057 parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
1060 // Check if we've already inlined this function at this particular
1061 // call site, in order to stop inlining when we reach the beginning
1062 // of a recursion cycle again. We don't inline immediately recursive
1063 // functions, but allow inlining if there is a recursion cycle of
1064 // many functions. Most likely, the inlining will stop before we
1065 // even hit the beginning of the cycle again, but this catches the
1067 for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
1068 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
1069 if base.Flag.LowerM > 1 {
1070 fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), fn, ir.FuncName(ir.CurFunc))
1076 typecheck.AssertFixedCall(n)
1078 inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym)
1080 closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
1081 // The linker needs FuncInfo metadata for all inlined
1082 // functions. This is typically handled by gc.enqueueFunc
1083 // calling ir.InitLSym for all function declarations in
1084 // typecheck.Target.Decls (ir.UseClosure adds all closures to
1087 // However, non-trivial closures in Decls are ignored, and are
1088 // insteaded enqueued when walk of the calling function
1091 // This presents a problem for direct calls to closures.
1092 // Inlining will replace the entire closure definition with its
1093 // body, which hides the closure from walk and thus suppresses
1096 // Explicitly create a symbol early in this edge case to ensure
1097 // we keep this metadata.
1099 // TODO: Refactor to keep a reference so this can all be done
1102 if n.Op() != ir.OCALLFUNC {
1103 // Not a standard call.
1106 if n.X.Op() != ir.OCLOSURE {
1107 // Not a direct closure call.
1111 clo := n.X.(*ir.ClosureExpr)
1112 if ir.IsTrivialClosure(clo) {
1113 // enqueueFunc will handle trivial closures anyways.
1117 ir.InitLSym(fn, true)
1120 closureInitLSym(n, fn)
1122 if base.Flag.GenDwarfInl > 0 {
1123 if !sym.WasInlined() {
1124 base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
1125 sym.Set(obj.AttrWasInlined, true)
1129 if base.Flag.LowerM != 0 {
1130 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
1132 if base.Flag.LowerM > 2 {
1133 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
1136 res := InlineCall(n, fn, inlIndex)
1139 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
1142 if base.Flag.LowerM > 2 {
1143 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
1146 *inlCalls = append(*inlCalls, res)
1151 // CalleeEffects appends any side effects from evaluating callee to init.
1152 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
1154 init.Append(ir.TakeInit(callee)...)
1156 switch callee.Op() {
1157 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
1161 conv := callee.(*ir.ConvExpr)
1165 ic := callee.(*ir.InlinedCallExpr)
1166 init.Append(ic.Body.Take()...)
1167 callee = ic.SingleResult()
1170 base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
1175 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1176 s := make([]*ir.Name, 0, len(ll))
1177 for _, n := range ll {
1178 if n.Class == ir.PAUTO {
1179 if !vis.usedLocals.Has(n) {
1188 // numNonClosures returns the number of functions in list which are not closures.
1189 func numNonClosures(list []*ir.Func) int {
1191 for _, fn := range list {
1192 if fn.OClosure == nil {
1199 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1200 for _, x := range list {
1210 // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
1211 // into a coverage counter array.
1212 func isIndexingCoverageCounter(n ir.Node) bool {
1213 if n.Op() != ir.OINDEX {
1216 ixn := n.(*ir.IndexExpr)
1217 if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
1220 nn := ixn.X.(*ir.Name)
1221 return nn.CoverageCounter()
1224 // isAtomicCoverageCounterUpdate examines the specified node to
1225 // determine whether it represents a call to sync/atomic.AddUint32 to
1226 // increment a coverage counter.
1227 func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
1228 if cn.X.Op() != ir.ONAME {
1231 name := cn.X.(*ir.Name)
1232 if name.Class != ir.PFUNC {
1235 fn := name.Sym().Name
1236 if name.Sym().Pkg.Path != "sync/atomic" ||
1237 (fn != "AddUint32" && fn != "StoreUint32") {
1240 if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
1243 adn := cn.Args[0].(*ir.AddrExpr)
1244 v := isIndexingCoverageCounter(adn.X)