]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/inline/inl.go
cmd/compile: synchronize inlinability logic between hairyVisitor and mkinlcall
[gostls13.git] / src / cmd / compile / internal / inline / inl.go
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.
4 //
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.
9 //
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
12 // are not supported.
13 //      0: disabled
14 //      1: 80-nodes leaf functions, oneliners, panic, lazy typechecking (default)
15 //      2: (unassigned)
16 //      3: (unassigned)
17 //      4: allow non-leaf functions
18 //
19 // At some point this may get another default and become switch-offable with -N.
20 //
21 // The -d typcheckinl flag enables early typechecking of all imported bodies,
22 // which is useful to flush out bugs.
23 //
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.
26
27 package inline
28
29 import (
30         "fmt"
31         "go/constant"
32         "internal/goexperiment"
33         "sort"
34         "strconv"
35
36         "cmd/compile/internal/base"
37         "cmd/compile/internal/inline/inlheur"
38         "cmd/compile/internal/ir"
39         "cmd/compile/internal/logopt"
40         "cmd/compile/internal/pgo"
41         "cmd/compile/internal/typecheck"
42         "cmd/compile/internal/types"
43         "cmd/internal/obj"
44 )
45
46 // Inlining budget parameters, gathered in one place
47 const (
48         inlineMaxBudget       = 80
49         inlineExtraAppendCost = 0
50         // default is to inline if there's at most one call. -l=4 overrides this by using 1 instead.
51         inlineExtraCallCost  = 57              // 57 was benchmarked to provided most benefit with no bad surprises; see https://github.com/golang/go/issues/19348#issuecomment-439370742
52         inlineExtraPanicCost = 1               // do not penalize inlining panics.
53         inlineExtraThrowCost = inlineMaxBudget // with current (2018-05/1.11) code, inlining runtime.throw does not help.
54
55         inlineBigFunctionNodes   = 5000 // Functions with this many nodes are considered "big".
56         inlineBigFunctionMaxCost = 20   // Max cost of inlinee when inlining into a "big" function.
57 )
58
59 var (
60         // List of all hot callee nodes.
61         // TODO(prattmic): Make this non-global.
62         candHotCalleeMap = make(map[*pgo.IRNode]struct{})
63
64         // List of all hot call sites. CallSiteInfo.Callee is always nil.
65         // TODO(prattmic): Make this non-global.
66         candHotEdgeMap = make(map[pgo.CallSiteInfo]struct{})
67
68         // Threshold in percentage for hot callsite inlining.
69         inlineHotCallSiteThresholdPercent float64
70
71         // Threshold in CDF percentage for hot callsite inlining,
72         // that is, for a threshold of X the hottest callsites that
73         // make up the top X% of total edge weight will be
74         // considered hot for inlining candidates.
75         inlineCDFHotCallSiteThresholdPercent = float64(99)
76
77         // Budget increased due to hotness.
78         inlineHotMaxBudget int32 = 2000
79 )
80
81 // pgoInlinePrologue records the hot callsites from ir-graph.
82 func pgoInlinePrologue(p *pgo.Profile, funcs []*ir.Func) {
83         if base.Debug.PGOInlineCDFThreshold != "" {
84                 if s, err := strconv.ParseFloat(base.Debug.PGOInlineCDFThreshold, 64); err == nil && s >= 0 && s <= 100 {
85                         inlineCDFHotCallSiteThresholdPercent = s
86                 } else {
87                         base.Fatalf("invalid PGOInlineCDFThreshold, must be between 0 and 100")
88                 }
89         }
90         var hotCallsites []pgo.NodeMapKey
91         inlineHotCallSiteThresholdPercent, hotCallsites = hotNodesFromCDF(p)
92         if base.Debug.PGODebug > 0 {
93                 fmt.Printf("hot-callsite-thres-from-CDF=%v\n", inlineHotCallSiteThresholdPercent)
94         }
95
96         if x := base.Debug.PGOInlineBudget; x != 0 {
97                 inlineHotMaxBudget = int32(x)
98         }
99
100         for _, n := range hotCallsites {
101                 // mark inlineable callees from hot edges
102                 if callee := p.WeightedCG.IRNodes[n.CalleeName]; callee != nil {
103                         candHotCalleeMap[callee] = struct{}{}
104                 }
105                 // mark hot call sites
106                 if caller := p.WeightedCG.IRNodes[n.CallerName]; caller != nil && caller.AST != nil {
107                         csi := pgo.CallSiteInfo{LineOffset: n.CallSiteOffset, Caller: caller.AST}
108                         candHotEdgeMap[csi] = struct{}{}
109                 }
110         }
111
112         if base.Debug.PGODebug >= 3 {
113                 fmt.Printf("hot-cg before inline in dot format:")
114                 p.PrintWeightedCallGraphDOT(inlineHotCallSiteThresholdPercent)
115         }
116 }
117
118 // hotNodesFromCDF computes an edge weight threshold and the list of hot
119 // nodes that make up the given percentage of the CDF. The threshold, as
120 // a percent, is the lower bound of weight for nodes to be considered hot
121 // (currently only used in debug prints) (in case of equal weights,
122 // comparing with the threshold may not accurately reflect which nodes are
123 // considiered hot).
124 func hotNodesFromCDF(p *pgo.Profile) (float64, []pgo.NodeMapKey) {
125         nodes := make([]pgo.NodeMapKey, len(p.NodeMap))
126         i := 0
127         for n := range p.NodeMap {
128                 nodes[i] = n
129                 i++
130         }
131         sort.Slice(nodes, func(i, j int) bool {
132                 ni, nj := nodes[i], nodes[j]
133                 if wi, wj := p.NodeMap[ni].EWeight, p.NodeMap[nj].EWeight; wi != wj {
134                         return wi > wj // want larger weight first
135                 }
136                 // same weight, order by name/line number
137                 if ni.CallerName != nj.CallerName {
138                         return ni.CallerName < nj.CallerName
139                 }
140                 if ni.CalleeName != nj.CalleeName {
141                         return ni.CalleeName < nj.CalleeName
142                 }
143                 return ni.CallSiteOffset < nj.CallSiteOffset
144         })
145         cum := int64(0)
146         for i, n := range nodes {
147                 w := p.NodeMap[n].EWeight
148                 cum += w
149                 if pgo.WeightInPercentage(cum, p.TotalEdgeWeight) > inlineCDFHotCallSiteThresholdPercent {
150                         // nodes[:i+1] to include the very last node that makes it to go over the threshold.
151                         // (Say, if the CDF threshold is 50% and one hot node takes 60% of weight, we want to
152                         // include that node instead of excluding it.)
153                         return pgo.WeightInPercentage(w, p.TotalEdgeWeight), nodes[:i+1]
154                 }
155         }
156         return 0, nodes
157 }
158
159 // InlinePackage finds functions that can be inlined and clones them before walk expands them.
160 func InlinePackage(p *pgo.Profile) {
161         if base.Debug.PGOInline == 0 {
162                 p = nil
163         }
164
165         InlineDecls(p, typecheck.Target.Funcs, true)
166
167         // Perform a garbage collection of hidden closures functions that
168         // are no longer reachable from top-level functions following
169         // inlining. See #59404 and #59638 for more context.
170         garbageCollectUnreferencedHiddenClosures()
171
172         if base.Debug.DumpInlFuncProps != "" {
173                 inlheur.DumpFuncProps(nil, base.Debug.DumpInlFuncProps, nil)
174         }
175         if goexperiment.NewInliner {
176                 postProcessCallSites(p)
177         }
178 }
179
180 // InlineDecls applies inlining to the given batch of declarations.
181 func InlineDecls(p *pgo.Profile, funcs []*ir.Func, doInline bool) {
182         if p != nil {
183                 pgoInlinePrologue(p, funcs)
184         }
185
186         doCanInline := func(n *ir.Func, recursive bool, numfns int) {
187                 if !recursive || numfns > 1 {
188                         // We allow inlining if there is no
189                         // recursion, or the recursion cycle is
190                         // across more than one function.
191                         CanInline(n, p)
192                 } else {
193                         if base.Flag.LowerM > 1 && n.OClosure == nil {
194                                 fmt.Printf("%v: cannot inline %v: recursive\n", ir.Line(n), n.Nname)
195                         }
196                 }
197         }
198
199         ir.VisitFuncsBottomUp(funcs, func(list []*ir.Func, recursive bool) {
200                 numfns := numNonClosures(list)
201                 // We visit functions within an SCC in fairly arbitrary order,
202                 // so by computing inlinability for all functions in the SCC
203                 // before performing any inlining, the results are less
204                 // sensitive to the order within the SCC (see #58905 for an
205                 // example).
206
207                 // First compute inlinability for all functions in the SCC ...
208                 for _, n := range list {
209                         doCanInline(n, recursive, numfns)
210                 }
211                 // ... then make a second pass to do inlining of calls.
212                 if doInline {
213                         for _, n := range list {
214                                 InlineCalls(n, p)
215                         }
216                 }
217         })
218 }
219
220 // garbageCollectUnreferencedHiddenClosures makes a pass over all the
221 // top-level (non-hidden-closure) functions looking for nested closure
222 // functions that are reachable, then sweeps through the Target.Decls
223 // list and marks any non-reachable hidden closure function as dead.
224 // See issues #59404 and #59638 for more context.
225 func garbageCollectUnreferencedHiddenClosures() {
226
227         liveFuncs := make(map[*ir.Func]bool)
228
229         var markLiveFuncs func(fn *ir.Func)
230         markLiveFuncs = func(fn *ir.Func) {
231                 if liveFuncs[fn] {
232                         return
233                 }
234                 liveFuncs[fn] = true
235                 ir.Visit(fn, func(n ir.Node) {
236                         if clo, ok := n.(*ir.ClosureExpr); ok {
237                                 markLiveFuncs(clo.Func)
238                         }
239                 })
240         }
241
242         for i := 0; i < len(typecheck.Target.Funcs); i++ {
243                 fn := typecheck.Target.Funcs[i]
244                 if fn.IsHiddenClosure() {
245                         continue
246                 }
247                 markLiveFuncs(fn)
248         }
249
250         for i := 0; i < len(typecheck.Target.Funcs); i++ {
251                 fn := typecheck.Target.Funcs[i]
252                 if !fn.IsHiddenClosure() {
253                         continue
254                 }
255                 if fn.IsDeadcodeClosure() {
256                         continue
257                 }
258                 if liveFuncs[fn] {
259                         continue
260                 }
261                 fn.SetIsDeadcodeClosure(true)
262                 if base.Flag.LowerM > 2 {
263                         fmt.Printf("%v: unreferenced closure %v marked as dead\n", ir.Line(fn), fn)
264                 }
265                 if fn.Inl != nil && fn.LSym == nil {
266                         ir.InitLSym(fn, true)
267                 }
268         }
269 }
270
271 // inlineBudget determines the max budget for function 'fn' prior to
272 // analyzing the hairyness of the body of 'fn'. We pass in the pgo
273 // profile if available (which can change the budget), also a
274 // 'relaxed' flag, which expands the budget slightly to allow for the
275 // possibility that a call to the function might have its score
276 // adjusted downwards. If 'verbose' is set, then print a remark where
277 // we boost the budget due to PGO.
278 func inlineBudget(fn *ir.Func, profile *pgo.Profile, relaxed bool, verbose bool) int32 {
279         // Update the budget for profile-guided inlining.
280         budget := int32(inlineMaxBudget)
281         if profile != nil {
282                 if n, ok := profile.WeightedCG.IRNodes[ir.LinkFuncName(fn)]; ok {
283                         if _, ok := candHotCalleeMap[n]; ok {
284                                 budget = int32(inlineHotMaxBudget)
285                                 if verbose {
286                                         fmt.Printf("hot-node enabled increased budget=%v for func=%v\n", budget, ir.PkgFuncName(fn))
287                                 }
288                         }
289                 }
290         }
291         if relaxed {
292                 budget += inlineMaxBudget
293         }
294         return budget
295 }
296
297 // CanInline determines whether fn is inlineable.
298 // If so, CanInline saves copies of fn.Body and fn.Dcl in fn.Inl.
299 // fn and fn.Body will already have been typechecked.
300 func CanInline(fn *ir.Func, profile *pgo.Profile) {
301         if fn.Nname == nil {
302                 base.Fatalf("CanInline no nname %+v", fn)
303         }
304
305         var funcProps *inlheur.FuncProps
306         if goexperiment.NewInliner || inlheur.UnitTesting() {
307                 funcProps = inlheur.AnalyzeFunc(fn,
308                         func(fn *ir.Func) { CanInline(fn, profile) })
309         }
310
311         var reason string // reason, if any, that the function was not inlined
312         if base.Flag.LowerM > 1 || logopt.Enabled() {
313                 defer func() {
314                         if reason != "" {
315                                 if base.Flag.LowerM > 1 {
316                                         fmt.Printf("%v: cannot inline %v: %s\n", ir.Line(fn), fn.Nname, reason)
317                                 }
318                                 if logopt.Enabled() {
319                                         logopt.LogOpt(fn.Pos(), "cannotInlineFunction", "inline", ir.FuncName(fn), reason)
320                                 }
321                         }
322                 }()
323         }
324
325         reason = InlineImpossible(fn)
326         if reason != "" {
327                 return
328         }
329         if fn.Typecheck() == 0 {
330                 base.Fatalf("CanInline on non-typechecked function %v", fn)
331         }
332
333         n := fn.Nname
334         if n.Func.InlinabilityChecked() {
335                 return
336         }
337         defer n.Func.SetInlinabilityChecked(true)
338
339         cc := int32(inlineExtraCallCost)
340         if base.Flag.LowerL == 4 {
341                 cc = 1 // this appears to yield better performance than 0.
342         }
343
344         // Used a "relaxed" inline budget if goexperiment.NewInliner is in
345         // effect, or if we're producing a debugging dump.
346         relaxed := goexperiment.NewInliner ||
347                 (base.Debug.DumpInlFuncProps != "" ||
348                         base.Debug.DumpInlCallSiteScores != 0)
349
350         // Compute the inline budget for this func.
351         budget := inlineBudget(fn, profile, relaxed, base.Debug.PGODebug > 0)
352
353         // At this point in the game the function we're looking at may
354         // have "stale" autos, vars that still appear in the Dcl list, but
355         // which no longer have any uses in the function body (due to
356         // elimination by deadcode). We'd like to exclude these dead vars
357         // when creating the "Inline.Dcl" field below; to accomplish this,
358         // the hairyVisitor below builds up a map of used/referenced
359         // locals, and we use this map to produce a pruned Inline.Dcl
360         // list. See issue 25459 for more context.
361
362         visitor := hairyVisitor{
363                 curFunc:       fn,
364                 isBigFunc:     isBigFunc(fn),
365                 budget:        budget,
366                 maxBudget:     budget,
367                 extraCallCost: cc,
368                 profile:       profile,
369         }
370         if visitor.tooHairy(fn) {
371                 reason = visitor.reason
372                 return
373         }
374
375         n.Func.Inl = &ir.Inline{
376                 Cost:    budget - visitor.budget,
377                 Dcl:     pruneUnusedAutos(n.Func.Dcl, &visitor),
378                 HaveDcl: true,
379
380                 CanDelayResults: canDelayResults(fn),
381         }
382         if goexperiment.NewInliner {
383                 n.Func.Inl.Properties = funcProps.SerializeToString()
384         }
385
386         if base.Flag.LowerM > 1 {
387                 fmt.Printf("%v: can inline %v with cost %d as: %v { %v }\n", ir.Line(fn), n, budget-visitor.budget, fn.Type(), ir.Nodes(fn.Body))
388         } else if base.Flag.LowerM != 0 {
389                 fmt.Printf("%v: can inline %v\n", ir.Line(fn), n)
390         }
391         if logopt.Enabled() {
392                 logopt.LogOpt(fn.Pos(), "canInlineFunction", "inline", ir.FuncName(fn), fmt.Sprintf("cost: %d", budget-visitor.budget))
393         }
394 }
395
396 // InlineImpossible returns a non-empty reason string if fn is impossible to
397 // inline regardless of cost or contents.
398 func InlineImpossible(fn *ir.Func) string {
399         var reason string // reason, if any, that the function can not be inlined.
400         if fn.Nname == nil {
401                 reason = "no name"
402                 return reason
403         }
404
405         // If marked "go:noinline", don't inline.
406         if fn.Pragma&ir.Noinline != 0 {
407                 reason = "marked go:noinline"
408                 return reason
409         }
410
411         // If marked "go:norace" and -race compilation, don't inline.
412         if base.Flag.Race && fn.Pragma&ir.Norace != 0 {
413                 reason = "marked go:norace with -race compilation"
414                 return reason
415         }
416
417         // If marked "go:nocheckptr" and -d checkptr compilation, don't inline.
418         if base.Debug.Checkptr != 0 && fn.Pragma&ir.NoCheckPtr != 0 {
419                 reason = "marked go:nocheckptr"
420                 return reason
421         }
422
423         // If marked "go:cgo_unsafe_args", don't inline, since the function
424         // makes assumptions about its argument frame layout.
425         if fn.Pragma&ir.CgoUnsafeArgs != 0 {
426                 reason = "marked go:cgo_unsafe_args"
427                 return reason
428         }
429
430         // If marked as "go:uintptrkeepalive", don't inline, since the keep
431         // alive information is lost during inlining.
432         //
433         // TODO(prattmic): This is handled on calls during escape analysis,
434         // which is after inlining. Move prior to inlining so the keep-alive is
435         // maintained after inlining.
436         if fn.Pragma&ir.UintptrKeepAlive != 0 {
437                 reason = "marked as having a keep-alive uintptr argument"
438                 return reason
439         }
440
441         // If marked as "go:uintptrescapes", don't inline, since the escape
442         // information is lost during inlining.
443         if fn.Pragma&ir.UintptrEscapes != 0 {
444                 reason = "marked as having an escaping uintptr argument"
445                 return reason
446         }
447
448         // The nowritebarrierrec checker currently works at function
449         // granularity, so inlining yeswritebarrierrec functions can confuse it
450         // (#22342). As a workaround, disallow inlining them for now.
451         if fn.Pragma&ir.Yeswritebarrierrec != 0 {
452                 reason = "marked go:yeswritebarrierrec"
453                 return reason
454         }
455
456         // If a local function has no fn.Body (is defined outside of Go), cannot inline it.
457         // Imported functions don't have fn.Body but might have inline body in fn.Inl.
458         if len(fn.Body) == 0 && !typecheck.HaveInlineBody(fn) {
459                 reason = "no function body"
460                 return reason
461         }
462
463         return ""
464 }
465
466 // canDelayResults reports whether inlined calls to fn can delay
467 // declaring the result parameter until the "return" statement.
468 func canDelayResults(fn *ir.Func) bool {
469         // We can delay declaring+initializing result parameters if:
470         // (1) there's exactly one "return" statement in the inlined function;
471         // (2) it's not an empty return statement (#44355); and
472         // (3) the result parameters aren't named.
473
474         nreturns := 0
475         ir.VisitList(fn.Body, func(n ir.Node) {
476                 if n, ok := n.(*ir.ReturnStmt); ok {
477                         nreturns++
478                         if len(n.Results) == 0 {
479                                 nreturns++ // empty return statement (case 2)
480                         }
481                 }
482         })
483
484         if nreturns != 1 {
485                 return false // not exactly one return statement (case 1)
486         }
487
488         // temporaries for return values.
489         for _, param := range fn.Type().Results() {
490                 if sym := param.Sym; sym != nil && !sym.IsBlank() {
491                         return false // found a named result parameter (case 3)
492                 }
493         }
494
495         return true
496 }
497
498 // hairyVisitor visits a function body to determine its inlining
499 // hairiness and whether or not it can be inlined.
500 type hairyVisitor struct {
501         // This is needed to access the current caller in the doNode function.
502         curFunc       *ir.Func
503         isBigFunc     bool
504         budget        int32
505         maxBudget     int32
506         reason        string
507         extraCallCost int32
508         usedLocals    ir.NameSet
509         do            func(ir.Node) bool
510         profile       *pgo.Profile
511 }
512
513 func (v *hairyVisitor) tooHairy(fn *ir.Func) bool {
514         v.do = v.doNode // cache closure
515         if ir.DoChildren(fn, v.do) {
516                 return true
517         }
518         if v.budget < 0 {
519                 v.reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", v.maxBudget-v.budget, v.maxBudget)
520                 return true
521         }
522         return false
523 }
524
525 // doNode visits n and its children, updates the state in v, and returns true if
526 // n makes the current function too hairy for inlining.
527 func (v *hairyVisitor) doNode(n ir.Node) bool {
528         if n == nil {
529                 return false
530         }
531 opSwitch:
532         switch n.Op() {
533         // Call is okay if inlinable and we have the budget for the body.
534         case ir.OCALLFUNC:
535                 n := n.(*ir.CallExpr)
536                 // Functions that call runtime.getcaller{pc,sp} can not be inlined
537                 // because getcaller{pc,sp} expect a pointer to the caller's first argument.
538                 //
539                 // runtime.throw is a "cheap call" like panic in normal code.
540                 var cheap bool
541                 if n.Fun.Op() == ir.ONAME {
542                         name := n.Fun.(*ir.Name)
543                         if name.Class == ir.PFUNC {
544                                 switch fn := types.RuntimeSymName(name.Sym()); fn {
545                                 case "getcallerpc", "getcallersp":
546                                         v.reason = "call to " + fn
547                                         return true
548                                 case "throw":
549                                         v.budget -= inlineExtraThrowCost
550                                         break opSwitch
551                                 }
552                                 // Special case for reflect.noescape. It does just type
553                                 // conversions to appease the escape analysis, and doesn't
554                                 // generate code.
555                                 if types.ReflectSymName(name.Sym()) == "noescape" {
556                                         cheap = true
557                                 }
558                         }
559                         // Special case for coverage counter updates; although
560                         // these correspond to real operations, we treat them as
561                         // zero cost for the moment. This is due to the existence
562                         // of tests that are sensitive to inlining-- if the
563                         // insertion of coverage instrumentation happens to tip a
564                         // given function over the threshold and move it from
565                         // "inlinable" to "not-inlinable", this can cause changes
566                         // in allocation behavior, which can then result in test
567                         // failures (a good example is the TestAllocations in
568                         // crypto/ed25519).
569                         if isAtomicCoverageCounterUpdate(n) {
570                                 return false
571                         }
572                 }
573                 if n.Fun.Op() == ir.OMETHEXPR {
574                         if meth := ir.MethodExprName(n.Fun); meth != nil {
575                                 if fn := meth.Func; fn != nil {
576                                         s := fn.Sym()
577                                         if types.RuntimeSymName(s) == "heapBits.nextArena" {
578                                                 // Special case: explicitly allow mid-stack inlining of
579                                                 // runtime.heapBits.next even though it calls slow-path
580                                                 // runtime.heapBits.nextArena.
581                                                 cheap = true
582                                         }
583                                         // Special case: on architectures that can do unaligned loads,
584                                         // explicitly mark encoding/binary methods as cheap,
585                                         // because in practice they are, even though our inlining
586                                         // budgeting system does not see that. See issue 42958.
587                                         if base.Ctxt.Arch.CanMergeLoads && s.Pkg.Path == "encoding/binary" {
588                                                 switch s.Name {
589                                                 case "littleEndian.Uint64", "littleEndian.Uint32", "littleEndian.Uint16",
590                                                         "bigEndian.Uint64", "bigEndian.Uint32", "bigEndian.Uint16",
591                                                         "littleEndian.PutUint64", "littleEndian.PutUint32", "littleEndian.PutUint16",
592                                                         "bigEndian.PutUint64", "bigEndian.PutUint32", "bigEndian.PutUint16",
593                                                         "littleEndian.AppendUint64", "littleEndian.AppendUint32", "littleEndian.AppendUint16",
594                                                         "bigEndian.AppendUint64", "bigEndian.AppendUint32", "bigEndian.AppendUint16":
595                                                         cheap = true
596                                                 }
597                                         }
598                                 }
599                         }
600                 }
601                 if cheap {
602                         break // treat like any other node, that is, cost of 1
603                 }
604
605                 if ir.IsIntrinsicCall(n) {
606                         // Treat like any other node.
607                         break
608                 }
609
610                 if callee := inlCallee(v.curFunc, n.Fun, v.profile); callee != nil && typecheck.HaveInlineBody(callee) {
611                         // Check whether we'd actually inline this call. Set
612                         // log == false since we aren't actually doing inlining
613                         // yet.
614                         if canInlineCallExpr(v.curFunc, n, callee, v.isBigFunc, false) {
615                                 // mkinlcall would inline this call [1], so use
616                                 // the cost of the inline body as the cost of
617                                 // the call, as that is what will actually
618                                 // appear in the code.
619                                 //
620                                 // [1] This is almost a perfect match to the
621                                 // mkinlcall logic, except that
622                                 // canInlineCallExpr considers inlining cycles
623                                 // by looking at what has already been inlined.
624                                 // Since we haven't done any inlining yet we
625                                 // will miss those.
626                                 v.budget -= callee.Inl.Cost
627                                 break
628                         }
629                 }
630
631                 // Call cost for non-leaf inlining.
632                 v.budget -= v.extraCallCost
633
634         case ir.OCALLMETH:
635                 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
636
637         // Things that are too hairy, irrespective of the budget
638         case ir.OCALL, ir.OCALLINTER:
639                 // Call cost for non-leaf inlining.
640                 v.budget -= v.extraCallCost
641
642         case ir.OPANIC:
643                 n := n.(*ir.UnaryExpr)
644                 if n.X.Op() == ir.OCONVIFACE && n.X.(*ir.ConvExpr).Implicit() {
645                         // Hack to keep reflect.flag.mustBe inlinable for TestIntendedInlining.
646                         // Before CL 284412, these conversions were introduced later in the
647                         // compiler, so they didn't count against inlining budget.
648                         v.budget++
649                 }
650                 v.budget -= inlineExtraPanicCost
651
652         case ir.ORECOVER:
653                 base.FatalfAt(n.Pos(), "ORECOVER missed typecheck")
654         case ir.ORECOVERFP:
655                 // recover matches the argument frame pointer to find
656                 // the right panic value, so it needs an argument frame.
657                 v.reason = "call to recover"
658                 return true
659
660         case ir.OCLOSURE:
661                 if base.Debug.InlFuncsWithClosures == 0 {
662                         v.reason = "not inlining functions with closures"
663                         return true
664                 }
665
666                 // TODO(danscales): Maybe make budget proportional to number of closure
667                 // variables, e.g.:
668                 //v.budget -= int32(len(n.(*ir.ClosureExpr).Func.ClosureVars) * 3)
669                 // TODO(austin): However, if we're able to inline this closure into
670                 // v.curFunc, then we actually pay nothing for the closure captures. We
671                 // should try to account for that if we're going to account for captures.
672                 v.budget -= 15
673
674         case ir.OGO, ir.ODEFER, ir.OTAILCALL:
675                 v.reason = "unhandled op " + n.Op().String()
676                 return true
677
678         case ir.OAPPEND:
679                 v.budget -= inlineExtraAppendCost
680
681         case ir.OADDR:
682                 n := n.(*ir.AddrExpr)
683                 // Make "&s.f" cost 0 when f's offset is zero.
684                 if dot, ok := n.X.(*ir.SelectorExpr); ok && (dot.Op() == ir.ODOT || dot.Op() == ir.ODOTPTR) {
685                         if _, ok := dot.X.(*ir.Name); ok && dot.Selection.Offset == 0 {
686                                 v.budget += 2 // undo ir.OADDR+ir.ODOT/ir.ODOTPTR
687                         }
688                 }
689
690         case ir.ODEREF:
691                 // *(*X)(unsafe.Pointer(&x)) is low-cost
692                 n := n.(*ir.StarExpr)
693
694                 ptr := n.X
695                 for ptr.Op() == ir.OCONVNOP {
696                         ptr = ptr.(*ir.ConvExpr).X
697                 }
698                 if ptr.Op() == ir.OADDR {
699                         v.budget += 1 // undo half of default cost of ir.ODEREF+ir.OADDR
700                 }
701
702         case ir.OCONVNOP:
703                 // This doesn't produce code, but the children might.
704                 v.budget++ // undo default cost
705
706         case ir.OFALL, ir.OTYPE:
707                 // These nodes don't produce code; omit from inlining budget.
708                 return false
709
710         case ir.OIF:
711                 n := n.(*ir.IfStmt)
712                 if ir.IsConst(n.Cond, constant.Bool) {
713                         // This if and the condition cost nothing.
714                         if doList(n.Init(), v.do) {
715                                 return true
716                         }
717                         if ir.BoolVal(n.Cond) {
718                                 return doList(n.Body, v.do)
719                         } else {
720                                 return doList(n.Else, v.do)
721                         }
722                 }
723
724         case ir.ONAME:
725                 n := n.(*ir.Name)
726                 if n.Class == ir.PAUTO {
727                         v.usedLocals.Add(n)
728                 }
729
730         case ir.OBLOCK:
731                 // The only OBLOCK we should see at this point is an empty one.
732                 // In any event, let the visitList(n.List()) below take care of the statements,
733                 // and don't charge for the OBLOCK itself. The ++ undoes the -- below.
734                 v.budget++
735
736         case ir.OMETHVALUE, ir.OSLICELIT:
737                 v.budget-- // Hack for toolstash -cmp.
738
739         case ir.OMETHEXPR:
740                 v.budget++ // Hack for toolstash -cmp.
741
742         case ir.OAS2:
743                 n := n.(*ir.AssignListStmt)
744
745                 // Unified IR unconditionally rewrites:
746                 //
747                 //      a, b = f()
748                 //
749                 // into:
750                 //
751                 //      DCL tmp1
752                 //      DCL tmp2
753                 //      tmp1, tmp2 = f()
754                 //      a, b = tmp1, tmp2
755                 //
756                 // so that it can insert implicit conversions as necessary. To
757                 // minimize impact to the existing inlining heuristics (in
758                 // particular, to avoid breaking the existing inlinability regress
759                 // tests), we need to compensate for this here.
760                 //
761                 // See also identical logic in isBigFunc.
762                 if init := n.Rhs[0].Init(); len(init) == 1 {
763                         if _, ok := init[0].(*ir.AssignListStmt); ok {
764                                 // 4 for each value, because each temporary variable now
765                                 // appears 3 times (DCL, LHS, RHS), plus an extra DCL node.
766                                 //
767                                 // 1 for the extra "tmp1, tmp2 = f()" assignment statement.
768                                 v.budget += 4*int32(len(n.Lhs)) + 1
769                         }
770                 }
771
772         case ir.OAS:
773                 // Special case for coverage counter updates and coverage
774                 // function registrations. Although these correspond to real
775                 // operations, we treat them as zero cost for the moment. This
776                 // is primarily due to the existence of tests that are
777                 // sensitive to inlining-- if the insertion of coverage
778                 // instrumentation happens to tip a given function over the
779                 // threshold and move it from "inlinable" to "not-inlinable",
780                 // this can cause changes in allocation behavior, which can
781                 // then result in test failures (a good example is the
782                 // TestAllocations in crypto/ed25519).
783                 n := n.(*ir.AssignStmt)
784                 if n.X.Op() == ir.OINDEX && isIndexingCoverageCounter(n.X) {
785                         return false
786                 }
787         }
788
789         v.budget--
790
791         // When debugging, don't stop early, to get full cost of inlining this function
792         if v.budget < 0 && base.Flag.LowerM < 2 && !logopt.Enabled() {
793                 v.reason = "too expensive"
794                 return true
795         }
796
797         return ir.DoChildren(n, v.do)
798 }
799
800 func isBigFunc(fn *ir.Func) bool {
801         budget := inlineBigFunctionNodes
802         return ir.Any(fn, func(n ir.Node) bool {
803                 // See logic in hairyVisitor.doNode, explaining unified IR's
804                 // handling of "a, b = f()" assignments.
805                 if n, ok := n.(*ir.AssignListStmt); ok && n.Op() == ir.OAS2 {
806                         if init := n.Rhs[0].Init(); len(init) == 1 {
807                                 if _, ok := init[0].(*ir.AssignListStmt); ok {
808                                         budget += 4*len(n.Lhs) + 1
809                                 }
810                         }
811                 }
812
813                 budget--
814                 return budget <= 0
815         })
816 }
817
818 // InlineCalls/inlnode walks fn's statements and expressions and substitutes any
819 // calls made to inlineable functions. This is the external entry point.
820 func InlineCalls(fn *ir.Func, profile *pgo.Profile) {
821         if goexperiment.NewInliner && !fn.Wrapper() {
822                 inlheur.ScoreCalls(fn)
823         }
824         if base.Debug.DumpInlFuncProps != "" && !fn.Wrapper() {
825                 inlheur.DumpFuncProps(fn, base.Debug.DumpInlFuncProps,
826                         func(fn *ir.Func) { CanInline(fn, profile) })
827         }
828         savefn := ir.CurFunc
829         ir.CurFunc = fn
830         bigCaller := isBigFunc(fn)
831         if bigCaller && base.Flag.LowerM > 1 {
832                 fmt.Printf("%v: function %v considered 'big'; reducing max cost of inlinees\n", ir.Line(fn), fn)
833         }
834         var inlCalls []*ir.InlinedCallExpr
835         var edit func(ir.Node) ir.Node
836         edit = func(n ir.Node) ir.Node {
837                 return inlnode(fn, n, bigCaller, &inlCalls, edit, profile)
838         }
839         ir.EditChildren(fn, edit)
840
841         // If we inlined any calls, we want to recursively visit their
842         // bodies for further inlining. However, we need to wait until
843         // *after* the original function body has been expanded, or else
844         // inlCallee can have false positives (e.g., #54632).
845         for len(inlCalls) > 0 {
846                 call := inlCalls[0]
847                 inlCalls = inlCalls[1:]
848                 ir.EditChildren(call, edit)
849         }
850
851         ir.CurFunc = savefn
852 }
853
854 // inlnode recurses over the tree to find inlineable calls, which will
855 // be turned into OINLCALLs by mkinlcall. When the recursion comes
856 // back up will examine left, right, list, rlist, ninit, ntest, nincr,
857 // nbody and nelse and use one of the 4 inlconv/glue functions above
858 // to turn the OINLCALL into an expression, a statement, or patch it
859 // in to this nodes list or rlist as appropriate.
860 // NOTE it makes no sense to pass the glue functions down the
861 // recursion to the level where the OINLCALL gets created because they
862 // have to edit /this/ n, so you'd have to push that one down as well,
863 // but then you may as well do it here.  so this is cleaner and
864 // shorter and less complicated.
865 // The result of inlnode MUST be assigned back to n, e.g.
866 //
867 //      n.Left = inlnode(n.Left)
868 func inlnode(callerfn *ir.Func, n ir.Node, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr, edit func(ir.Node) ir.Node, profile *pgo.Profile) ir.Node {
869         if n == nil {
870                 return n
871         }
872
873         switch n.Op() {
874         case ir.ODEFER, ir.OGO:
875                 n := n.(*ir.GoDeferStmt)
876                 switch call := n.Call; call.Op() {
877                 case ir.OCALLMETH:
878                         base.FatalfAt(call.Pos(), "OCALLMETH missed by typecheck")
879                 case ir.OCALLFUNC:
880                         call := call.(*ir.CallExpr)
881                         call.NoInline = true
882                 }
883         case ir.OTAILCALL:
884                 n := n.(*ir.TailCallStmt)
885                 n.Call.NoInline = true // Not inline a tail call for now. Maybe we could inline it just like RETURN fn(arg)?
886
887         // TODO do them here (or earlier),
888         // so escape analysis can avoid more heapmoves.
889         case ir.OCLOSURE:
890                 return n
891         case ir.OCALLMETH:
892                 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
893         case ir.OCALLFUNC:
894                 n := n.(*ir.CallExpr)
895                 if n.Fun.Op() == ir.OMETHEXPR {
896                         // Prevent inlining some reflect.Value methods when using checkptr,
897                         // even when package reflect was compiled without it (#35073).
898                         if meth := ir.MethodExprName(n.Fun); meth != nil {
899                                 s := meth.Sym()
900                                 if base.Debug.Checkptr != 0 {
901                                         switch types.ReflectSymName(s) {
902                                         case "Value.UnsafeAddr", "Value.Pointer":
903                                                 return n
904                                         }
905                                 }
906                         }
907                 }
908         }
909
910         lno := ir.SetPos(n)
911
912         ir.EditChildren(n, edit)
913
914         // with all the branches out of the way, it is now time to
915         // transmogrify this node itself unless inhibited by the
916         // switch at the top of this function.
917         switch n.Op() {
918         case ir.OCALLMETH:
919                 base.FatalfAt(n.Pos(), "OCALLMETH missed by typecheck")
920
921         case ir.OCALLFUNC:
922                 call := n.(*ir.CallExpr)
923                 if call.NoInline {
924                         break
925                 }
926                 if base.Flag.LowerM > 3 {
927                         fmt.Printf("%v:call to func %+v\n", ir.Line(n), call.Fun)
928                 }
929                 if ir.IsIntrinsicCall(call) {
930                         break
931                 }
932                 if fn := inlCallee(callerfn, call.Fun, profile); fn != nil && typecheck.HaveInlineBody(fn) {
933                         n = mkinlcall(callerfn, call, fn, bigCaller, inlCalls)
934                 }
935         }
936
937         base.Pos = lno
938
939         return n
940 }
941
942 // inlCallee takes a function-typed expression and returns the underlying function ONAME
943 // that it refers to if statically known. Otherwise, it returns nil.
944 func inlCallee(caller *ir.Func, fn ir.Node, profile *pgo.Profile) (res *ir.Func) {
945         fn = ir.StaticValue(fn)
946         switch fn.Op() {
947         case ir.OMETHEXPR:
948                 fn := fn.(*ir.SelectorExpr)
949                 n := ir.MethodExprName(fn)
950                 // Check that receiver type matches fn.X.
951                 // TODO(mdempsky): Handle implicit dereference
952                 // of pointer receiver argument?
953                 if n == nil || !types.Identical(n.Type().Recv().Type, fn.X.Type()) {
954                         return nil
955                 }
956                 return n.Func
957         case ir.ONAME:
958                 fn := fn.(*ir.Name)
959                 if fn.Class == ir.PFUNC {
960                         return fn.Func
961                 }
962         case ir.OCLOSURE:
963                 fn := fn.(*ir.ClosureExpr)
964                 c := fn.Func
965                 if len(c.ClosureVars) != 0 && c.ClosureVars[0].Outer.Curfn != caller {
966                         return nil // inliner doesn't support inlining across closure frames
967                 }
968                 CanInline(c, profile)
969                 return c
970         }
971         return nil
972 }
973
974 var inlgen int
975
976 // SSADumpInline gives the SSA back end a chance to dump the function
977 // when producing output for debugging the compiler itself.
978 var SSADumpInline = func(*ir.Func) {}
979
980 // InlineCall allows the inliner implementation to be overridden.
981 // If it returns nil, the function will not be inlined.
982 var InlineCall = func(callerfn *ir.Func, call *ir.CallExpr, fn *ir.Func, inlIndex int) *ir.InlinedCallExpr {
983         base.Fatalf("inline.InlineCall not overridden")
984         panic("unreachable")
985 }
986
987 // inlineCostOK returns true if call n from caller to callee is cheap enough to
988 // inline. bigCaller indicates that caller is a big function.
989 //
990 // If inlineCostOK returns false, it also returns the max cost that the callee
991 // exceeded.
992 func inlineCostOK(n *ir.CallExpr, caller, callee *ir.Func, bigCaller bool) (bool, int32) {
993         maxCost := int32(inlineMaxBudget)
994         if bigCaller {
995                 // We use this to restrict inlining into very big functions.
996                 // See issue 26546 and 17566.
997                 maxCost = inlineBigFunctionMaxCost
998         }
999
1000         metric := callee.Inl.Cost
1001         if goexperiment.NewInliner {
1002                 ok, score := inlheur.GetCallSiteScore(n)
1003                 if ok {
1004                         metric = int32(score)
1005                 }
1006
1007         }
1008
1009         if metric <= maxCost {
1010                 // Simple case. Function is already cheap enough.
1011                 return true, 0
1012         }
1013
1014         // We'll also allow inlining of hot functions below inlineHotMaxBudget,
1015         // but only in small functions.
1016
1017         lineOffset := pgo.NodeLineOffset(n, caller)
1018         csi := pgo.CallSiteInfo{LineOffset: lineOffset, Caller: caller}
1019         if _, ok := candHotEdgeMap[csi]; !ok {
1020                 // Cold
1021                 return false, maxCost
1022         }
1023
1024         // Hot
1025
1026         if bigCaller {
1027                 if base.Debug.PGODebug > 0 {
1028                         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))
1029                 }
1030                 return false, maxCost
1031         }
1032
1033         if metric > inlineHotMaxBudget {
1034                 return false, inlineHotMaxBudget
1035         }
1036
1037         if !base.PGOHash.MatchPosWithInfo(n.Pos(), "inline", nil) {
1038                 // De-selected by PGO Hash.
1039                 return false, maxCost
1040         }
1041
1042         if base.Debug.PGODebug > 0 {
1043                 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))
1044         }
1045
1046         return true, 0
1047 }
1048
1049 // canInlineCallsite returns true if the call n from caller to callee can be
1050 // inlined. bigCaller indicates that caller is a big function. log indicates
1051 // that the 'cannot inline' reason should be logged.
1052 //
1053 // Preconditions: CanInline(callee) has already been called.
1054 func canInlineCallExpr(callerfn *ir.Func, n *ir.CallExpr, callee *ir.Func, bigCaller bool, log bool) bool {
1055         if callee.Inl == nil {
1056                 // callee is never inlinable.
1057                 if log && logopt.Enabled() {
1058                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1059                                 fmt.Sprintf("%s cannot be inlined", ir.PkgFuncName(callee)))
1060                 }
1061                 return false
1062         }
1063
1064         if ok, maxCost := inlineCostOK(n, callerfn, callee, bigCaller); !ok {
1065                 // callee cost too high for this call site.
1066                 if log && logopt.Enabled() {
1067                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1068                                 fmt.Sprintf("cost %d of %s exceeds max caller cost %d", callee.Inl.Cost, ir.PkgFuncName(callee), maxCost))
1069                 }
1070                 return false
1071         }
1072
1073         if callee == callerfn {
1074                 // Can't recursively inline a function into itself.
1075                 if log && logopt.Enabled() {
1076                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", fmt.Sprintf("recursive call to %s", ir.FuncName(callerfn)))
1077                 }
1078                 return false
1079         }
1080
1081         if base.Flag.Cfg.Instrumenting && types.IsNoInstrumentPkg(callee.Sym().Pkg) {
1082                 // Runtime package must not be instrumented.
1083                 // Instrument skips runtime package. However, some runtime code can be
1084                 // inlined into other packages and instrumented there. To avoid this,
1085                 // we disable inlining of runtime functions when instrumenting.
1086                 // The example that we observed is inlining of LockOSThread,
1087                 // which lead to false race reports on m contents.
1088                 if log && logopt.Enabled() {
1089                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1090                                 fmt.Sprintf("call to runtime function %s in instrumented build", ir.PkgFuncName(callee)))
1091                 }
1092                 return false
1093         }
1094
1095         if base.Flag.Race && types.IsNoRacePkg(callee.Sym().Pkg) {
1096                 if log && logopt.Enabled() {
1097                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1098                                 fmt.Sprintf(`call to into "no-race" package function %s in race build`, ir.PkgFuncName(callee)))
1099                 }
1100                 return false
1101         }
1102
1103         // Check if we've already inlined this function at this particular
1104         // call site, in order to stop inlining when we reach the beginning
1105         // of a recursion cycle again. We don't inline immediately recursive
1106         // functions, but allow inlining if there is a recursion cycle of
1107         // many functions. Most likely, the inlining will stop before we
1108         // even hit the beginning of the cycle again, but this catches the
1109         // unusual case.
1110         parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
1111         sym := callee.Linksym()
1112         for inlIndex := parent; inlIndex >= 0; inlIndex = base.Ctxt.InlTree.Parent(inlIndex) {
1113                 if base.Ctxt.InlTree.InlinedFunction(inlIndex) == sym {
1114                         if log {
1115                                 if base.Flag.LowerM > 1 {
1116                                         fmt.Printf("%v: cannot inline %v into %v: repeated recursive cycle\n", ir.Line(n), callee, ir.FuncName(callerfn))
1117                                 }
1118                                 if logopt.Enabled() {
1119                                         logopt.LogOpt(n.Pos(), "cannotInlineCall", "inline", ir.FuncName(callerfn),
1120                                                 fmt.Sprintf("repeated recursive cycle to %s", ir.PkgFuncName(callee)))
1121                                 }
1122                         }
1123                         return false
1124                 }
1125         }
1126
1127         return true
1128 }
1129
1130 // If n is a OCALLFUNC node, and fn is an ONAME node for a
1131 // function with an inlinable body, return an OINLCALL node that can replace n.
1132 // The returned node's Ninit has the parameter assignments, the Nbody is the
1133 // inlined function body, and (List, Rlist) contain the (input, output)
1134 // parameters.
1135 // The result of mkinlcall MUST be assigned back to n, e.g.
1136 //
1137 //      n.Left = mkinlcall(n.Left, fn, isddd)
1138 func mkinlcall(callerfn *ir.Func, n *ir.CallExpr, fn *ir.Func, bigCaller bool, inlCalls *[]*ir.InlinedCallExpr) ir.Node {
1139         if !canInlineCallExpr(callerfn, n, fn, bigCaller, true) {
1140                 return n
1141         }
1142         typecheck.AssertFixedCall(n)
1143
1144         parent := base.Ctxt.PosTable.Pos(n.Pos()).Base().InliningIndex()
1145         sym := fn.Linksym()
1146         inlIndex := base.Ctxt.InlTree.Add(parent, n.Pos(), sym, ir.FuncName(fn))
1147
1148         closureInitLSym := func(n *ir.CallExpr, fn *ir.Func) {
1149                 // The linker needs FuncInfo metadata for all inlined
1150                 // functions. This is typically handled by gc.enqueueFunc
1151                 // calling ir.InitLSym for all function declarations in
1152                 // typecheck.Target.Decls (ir.UseClosure adds all closures to
1153                 // Decls).
1154                 //
1155                 // However, non-trivial closures in Decls are ignored, and are
1156                 // insteaded enqueued when walk of the calling function
1157                 // discovers them.
1158                 //
1159                 // This presents a problem for direct calls to closures.
1160                 // Inlining will replace the entire closure definition with its
1161                 // body, which hides the closure from walk and thus suppresses
1162                 // symbol creation.
1163                 //
1164                 // Explicitly create a symbol early in this edge case to ensure
1165                 // we keep this metadata.
1166                 //
1167                 // TODO: Refactor to keep a reference so this can all be done
1168                 // by enqueueFunc.
1169
1170                 if n.Op() != ir.OCALLFUNC {
1171                         // Not a standard call.
1172                         return
1173                 }
1174                 if n.Fun.Op() != ir.OCLOSURE {
1175                         // Not a direct closure call.
1176                         return
1177                 }
1178
1179                 clo := n.Fun.(*ir.ClosureExpr)
1180                 if ir.IsTrivialClosure(clo) {
1181                         // enqueueFunc will handle trivial closures anyways.
1182                         return
1183                 }
1184
1185                 ir.InitLSym(fn, true)
1186         }
1187
1188         closureInitLSym(n, fn)
1189
1190         if base.Flag.GenDwarfInl > 0 {
1191                 if !sym.WasInlined() {
1192                         base.Ctxt.DwFixups.SetPrecursorFunc(sym, fn)
1193                         sym.Set(obj.AttrWasInlined, true)
1194                 }
1195         }
1196
1197         if base.Flag.LowerM != 0 {
1198                 fmt.Printf("%v: inlining call to %v\n", ir.Line(n), fn)
1199         }
1200         if base.Flag.LowerM > 2 {
1201                 fmt.Printf("%v: Before inlining: %+v\n", ir.Line(n), n)
1202         }
1203
1204         res := InlineCall(callerfn, n, fn, inlIndex)
1205
1206         if res == nil {
1207                 base.FatalfAt(n.Pos(), "inlining call to %v failed", fn)
1208         }
1209
1210         if base.Flag.LowerM > 2 {
1211                 fmt.Printf("%v: After inlining %+v\n\n", ir.Line(res), res)
1212         }
1213
1214         *inlCalls = append(*inlCalls, res)
1215
1216         return res
1217 }
1218
1219 // CalleeEffects appends any side effects from evaluating callee to init.
1220 func CalleeEffects(init *ir.Nodes, callee ir.Node) {
1221         for {
1222                 init.Append(ir.TakeInit(callee)...)
1223
1224                 switch callee.Op() {
1225                 case ir.ONAME, ir.OCLOSURE, ir.OMETHEXPR:
1226                         return // done
1227
1228                 case ir.OCONVNOP:
1229                         conv := callee.(*ir.ConvExpr)
1230                         callee = conv.X
1231
1232                 case ir.OINLCALL:
1233                         ic := callee.(*ir.InlinedCallExpr)
1234                         init.Append(ic.Body.Take()...)
1235                         callee = ic.SingleResult()
1236
1237                 default:
1238                         base.FatalfAt(callee.Pos(), "unexpected callee expression: %v", callee)
1239                 }
1240         }
1241 }
1242
1243 func pruneUnusedAutos(ll []*ir.Name, vis *hairyVisitor) []*ir.Name {
1244         s := make([]*ir.Name, 0, len(ll))
1245         for _, n := range ll {
1246                 if n.Class == ir.PAUTO {
1247                         if !vis.usedLocals.Has(n) {
1248                                 // TODO(mdempsky): Simplify code after confident that this
1249                                 // never happens anymore.
1250                                 base.FatalfAt(n.Pos(), "unused auto: %v", n)
1251                                 continue
1252                         }
1253                 }
1254                 s = append(s, n)
1255         }
1256         return s
1257 }
1258
1259 // numNonClosures returns the number of functions in list which are not closures.
1260 func numNonClosures(list []*ir.Func) int {
1261         count := 0
1262         for _, fn := range list {
1263                 if fn.OClosure == nil {
1264                         count++
1265                 }
1266         }
1267         return count
1268 }
1269
1270 func doList(list []ir.Node, do func(ir.Node) bool) bool {
1271         for _, x := range list {
1272                 if x != nil {
1273                         if do(x) {
1274                                 return true
1275                         }
1276                 }
1277         }
1278         return false
1279 }
1280
1281 // isIndexingCoverageCounter returns true if the specified node 'n' is indexing
1282 // into a coverage counter array.
1283 func isIndexingCoverageCounter(n ir.Node) bool {
1284         if n.Op() != ir.OINDEX {
1285                 return false
1286         }
1287         ixn := n.(*ir.IndexExpr)
1288         if ixn.X.Op() != ir.ONAME || !ixn.X.Type().IsArray() {
1289                 return false
1290         }
1291         nn := ixn.X.(*ir.Name)
1292         return nn.CoverageCounter()
1293 }
1294
1295 // isAtomicCoverageCounterUpdate examines the specified node to
1296 // determine whether it represents a call to sync/atomic.AddUint32 to
1297 // increment a coverage counter.
1298 func isAtomicCoverageCounterUpdate(cn *ir.CallExpr) bool {
1299         if cn.Fun.Op() != ir.ONAME {
1300                 return false
1301         }
1302         name := cn.Fun.(*ir.Name)
1303         if name.Class != ir.PFUNC {
1304                 return false
1305         }
1306         fn := name.Sym().Name
1307         if name.Sym().Pkg.Path != "sync/atomic" ||
1308                 (fn != "AddUint32" && fn != "StoreUint32") {
1309                 return false
1310         }
1311         if len(cn.Args) != 2 || cn.Args[0].Op() != ir.OADDR {
1312                 return false
1313         }
1314         adn := cn.Args[0].(*ir.AddrExpr)
1315         v := isIndexingCoverageCounter(adn.X)
1316         return v
1317 }
1318
1319 func postProcessCallSites(profile *pgo.Profile) {
1320         if base.Debug.DumpInlCallSiteScores != 0 {
1321                 budgetCallback := func(fn *ir.Func, prof *pgo.Profile) (int32, bool) {
1322                         v := inlineBudget(fn, prof, false, false)
1323                         return v, v == inlineHotMaxBudget
1324                 }
1325                 inlheur.DumpInlCallSiteScores(profile, budgetCallback)
1326         }
1327 }