github.com/stingnevermore/go@v0.0.0-20180120041312-3810f5bfed72/src/cmd/compile/internal/gc/inl.go (about)

     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 caninl determines which
     6  // functions are suitable for inlining, and for those that are it
     7  // saves a copy of the body. Then inlcalls 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, lazy typechecking (default)
    15  //      2: (unassigned)
    16  //      3: allow variadic functions
    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  // TODO:
    28  //   - inline functions with ... args
    29  
    30  package gc
    31  
    32  import (
    33  	"cmd/compile/internal/types"
    34  	"cmd/internal/obj"
    35  	"cmd/internal/src"
    36  	"fmt"
    37  	"strings"
    38  )
    39  
    40  // Get the function's package. For ordinary functions it's on the ->sym, but for imported methods
    41  // the ->sym can be re-used in the local package, so peel it off the receiver's type.
    42  func fnpkg(fn *Node) *types.Pkg {
    43  	if fn.IsMethod() {
    44  		// method
    45  		rcvr := fn.Type.Recv().Type
    46  
    47  		if rcvr.IsPtr() {
    48  			rcvr = rcvr.Elem()
    49  		}
    50  		if rcvr.Sym == nil {
    51  			Fatalf("receiver with no sym: [%v] %L  (%v)", fn.Sym, fn, rcvr)
    52  		}
    53  		return rcvr.Sym.Pkg
    54  	}
    55  
    56  	// non-method
    57  	return fn.Sym.Pkg
    58  }
    59  
    60  // Lazy typechecking of imported bodies. For local functions, caninl will set ->typecheck
    61  // because they're a copy of an already checked body.
    62  func typecheckinl(fn *Node) {
    63  	lno := setlineno(fn)
    64  
    65  	// typecheckinl is only for imported functions;
    66  	// their bodies may refer to unsafe as long as the package
    67  	// was marked safe during import (which was checked then).
    68  	// the ->inl of a local function has been typechecked before caninl copied it.
    69  	pkg := fnpkg(fn)
    70  
    71  	if pkg == localpkg || pkg == nil {
    72  		return // typecheckinl on local function
    73  	}
    74  
    75  	if Debug['m'] > 2 || Debug_export != 0 {
    76  		fmt.Printf("typecheck import [%v] %L { %#v }\n", fn.Sym, fn, fn.Func.Inl)
    77  	}
    78  
    79  	save_safemode := safemode
    80  	safemode = false
    81  
    82  	savefn := Curfn
    83  	Curfn = fn
    84  	typecheckslice(fn.Func.Inl.Slice(), Etop)
    85  	Curfn = savefn
    86  
    87  	safemode = save_safemode
    88  
    89  	lineno = lno
    90  }
    91  
    92  // Caninl determines whether fn is inlineable.
    93  // If so, caninl saves fn->nbody in fn->inl and substitutes it with a copy.
    94  // fn and ->nbody will already have been typechecked.
    95  func caninl(fn *Node) {
    96  	if fn.Op != ODCLFUNC {
    97  		Fatalf("caninl %v", fn)
    98  	}
    99  	if fn.Func.Nname == nil {
   100  		Fatalf("caninl no nname %+v", fn)
   101  	}
   102  
   103  	var reason string // reason, if any, that the function was not inlined
   104  	if Debug['m'] > 1 {
   105  		defer func() {
   106  			if reason != "" {
   107  				fmt.Printf("%v: cannot inline %v: %s\n", fn.Line(), fn.Func.Nname, reason)
   108  			}
   109  		}()
   110  	}
   111  
   112  	// If marked "go:noinline", don't inline
   113  	if fn.Func.Pragma&Noinline != 0 {
   114  		reason = "marked go:noinline"
   115  		return
   116  	}
   117  
   118  	// If marked "go:cgo_unsafe_args", don't inline, since the
   119  	// function makes assumptions about its argument frame layout.
   120  	if fn.Func.Pragma&CgoUnsafeArgs != 0 {
   121  		reason = "marked go:cgo_unsafe_args"
   122  		return
   123  	}
   124  
   125  	// The nowritebarrierrec checker currently works at function
   126  	// granularity, so inlining yeswritebarrierrec functions can
   127  	// confuse it (#22342). As a workaround, disallow inlining
   128  	// them for now.
   129  	if fn.Func.Pragma&Yeswritebarrierrec != 0 {
   130  		reason = "marked go:yeswritebarrierrec"
   131  		return
   132  	}
   133  
   134  	// If fn has no body (is defined outside of Go), cannot inline it.
   135  	if fn.Nbody.Len() == 0 {
   136  		reason = "no function body"
   137  		return
   138  	}
   139  
   140  	if fn.Typecheck() == 0 {
   141  		Fatalf("caninl on non-typechecked function %v", fn)
   142  	}
   143  
   144  	// can't handle ... args yet
   145  	if Debug['l'] < 3 {
   146  		f := fn.Type.Params().Fields()
   147  		if len := f.Len(); len > 0 {
   148  			if t := f.Index(len - 1); t.Isddd() {
   149  				reason = "has ... args"
   150  				return
   151  			}
   152  		}
   153  	}
   154  
   155  	// Runtime package must not be instrumented.
   156  	// Instrument skips runtime package. However, some runtime code can be
   157  	// inlined into other packages and instrumented there. To avoid this,
   158  	// we disable inlining of runtime functions when instrumenting.
   159  	// The example that we observed is inlining of LockOSThread,
   160  	// which lead to false race reports on m contents.
   161  	if instrumenting && myimportpath == "runtime" {
   162  		reason = "instrumenting and is runtime function"
   163  		return
   164  	}
   165  
   166  	n := fn.Func.Nname
   167  	if n.Func.InlinabilityChecked() {
   168  		return
   169  	}
   170  	defer n.Func.SetInlinabilityChecked(true)
   171  
   172  	const maxBudget = 80
   173  	visitor := hairyVisitor{budget: maxBudget}
   174  	if visitor.visitList(fn.Nbody) {
   175  		reason = visitor.reason
   176  		return
   177  	}
   178  	if visitor.budget < 0 {
   179  		reason = fmt.Sprintf("function too complex: cost %d exceeds budget %d", maxBudget-visitor.budget, maxBudget)
   180  		return
   181  	}
   182  
   183  	savefn := Curfn
   184  	Curfn = fn
   185  
   186  	n.Func.Inl.Set(fn.Nbody.Slice())
   187  	fn.Nbody.Set(inlcopylist(n.Func.Inl.Slice()))
   188  	inldcl := inlcopylist(n.Name.Defn.Func.Dcl)
   189  	n.Func.Inldcl.Set(inldcl)
   190  	n.Func.InlCost = maxBudget - visitor.budget
   191  
   192  	// hack, TODO, check for better way to link method nodes back to the thing with the ->inl
   193  	// this is so export can find the body of a method
   194  	fn.Type.FuncType().Nname = asTypesNode(n)
   195  
   196  	if Debug['m'] > 1 {
   197  		fmt.Printf("%v: can inline %#v as: %#v { %#v }\n", fn.Line(), n, fn.Type, n.Func.Inl)
   198  	} else if Debug['m'] != 0 {
   199  		fmt.Printf("%v: can inline %v\n", fn.Line(), n)
   200  	}
   201  
   202  	Curfn = savefn
   203  }
   204  
   205  // inlFlood marks n's inline body for export and recursively ensures
   206  // all called functions are marked too.
   207  func inlFlood(n *Node) {
   208  	if n == nil {
   209  		return
   210  	}
   211  	if n.Op != ONAME || n.Class() != PFUNC {
   212  		Fatalf("inlFlood: unexpected %v, %v, %v", n, n.Op, n.Class())
   213  	}
   214  	if n.Func == nil {
   215  		// TODO(mdempsky): Should init have a Func too?
   216  		if n.Sym.Name == "init" {
   217  			return
   218  		}
   219  		Fatalf("inlFlood: missing Func on %v", n)
   220  	}
   221  	if n.Func.Inl.Len() == 0 {
   222  		return
   223  	}
   224  
   225  	if n.Func.ExportInline() {
   226  		return
   227  	}
   228  	n.Func.SetExportInline(true)
   229  
   230  	typecheckinl(n)
   231  
   232  	// Recursively flood any functions called by this one.
   233  	inspectList(n.Func.Inl, func(n *Node) bool {
   234  		switch n.Op {
   235  		case OCALLFUNC, OCALLMETH:
   236  			inlFlood(asNode(n.Left.Type.Nname()))
   237  		}
   238  		return true
   239  	})
   240  }
   241  
   242  // hairyVisitor visits a function body to determine its inlining
   243  // hairiness and whether or not it can be inlined.
   244  type hairyVisitor struct {
   245  	budget int32
   246  	reason string
   247  }
   248  
   249  // Look for anything we want to punt on.
   250  func (v *hairyVisitor) visitList(ll Nodes) bool {
   251  	for _, n := range ll.Slice() {
   252  		if v.visit(n) {
   253  			return true
   254  		}
   255  	}
   256  	return false
   257  }
   258  
   259  func (v *hairyVisitor) visit(n *Node) bool {
   260  	if n == nil {
   261  		return false
   262  	}
   263  
   264  	switch n.Op {
   265  	// Call is okay if inlinable and we have the budget for the body.
   266  	case OCALLFUNC:
   267  		if isIntrinsicCall(n) {
   268  			v.budget--
   269  			break
   270  		}
   271  		// Functions that call runtime.getcaller{pc,sp} can not be inlined
   272  		// because getcaller{pc,sp} expect a pointer to the caller's first argument.
   273  		if n.Left.Op == ONAME && n.Left.Class() == PFUNC && isRuntimePkg(n.Left.Sym.Pkg) {
   274  			fn := n.Left.Sym.Name
   275  			if fn == "getcallerpc" || fn == "getcallersp" {
   276  				v.reason = "call to " + fn
   277  				return true
   278  			}
   279  		}
   280  
   281  		if fn := n.Left.Func; fn != nil && fn.Inl.Len() != 0 {
   282  			v.budget -= fn.InlCost
   283  			break
   284  		}
   285  		if n.Left.isMethodExpression() {
   286  			if d := asNode(n.Left.Sym.Def); d != nil && d.Func.Inl.Len() != 0 {
   287  				v.budget -= d.Func.InlCost
   288  				break
   289  			}
   290  		}
   291  		// TODO(mdempsky): Budget for OCLOSURE calls if we
   292  		// ever allow that. See #15561 and #23093.
   293  		if Debug['l'] < 4 {
   294  			v.reason = "non-leaf function"
   295  			return true
   296  		}
   297  
   298  	// Call is okay if inlinable and we have the budget for the body.
   299  	case OCALLMETH:
   300  		t := n.Left.Type
   301  		if t == nil {
   302  			Fatalf("no function type for [%p] %+v\n", n.Left, n.Left)
   303  		}
   304  		if t.Nname() == nil {
   305  			Fatalf("no function definition for [%p] %+v\n", t, t)
   306  		}
   307  		if inlfn := asNode(t.FuncType().Nname).Func; inlfn.Inl.Len() != 0 {
   308  			v.budget -= inlfn.InlCost
   309  			break
   310  		}
   311  		if Debug['l'] < 4 {
   312  			v.reason = "non-leaf method"
   313  			return true
   314  		}
   315  
   316  	// Things that are too hairy, irrespective of the budget
   317  	case OCALL, OCALLINTER, OPANIC, ORECOVER:
   318  		if Debug['l'] < 4 {
   319  			v.reason = "non-leaf op " + n.Op.String()
   320  			return true
   321  		}
   322  
   323  	case OCLOSURE,
   324  		OCALLPART,
   325  		ORANGE,
   326  		OFOR,
   327  		OFORUNTIL,
   328  		OSELECT,
   329  		OTYPESW,
   330  		OPROC,
   331  		ODEFER,
   332  		ODCLTYPE, // can't print yet
   333  		OBREAK,
   334  		ORETJMP:
   335  		v.reason = "unhandled op " + n.Op.String()
   336  		return true
   337  
   338  	case ODCLCONST, OEMPTY, OFALL, OLABEL:
   339  		// These nodes don't produce code; omit from inlining budget.
   340  		return false
   341  	}
   342  
   343  	v.budget--
   344  	// TODO(mdempsky/josharian): Hacks to appease toolstash; remove.
   345  	// See issue 17566 and CL 31674 for discussion.
   346  	switch n.Op {
   347  	case OSTRUCTKEY:
   348  		v.budget--
   349  	case OSLICE, OSLICEARR, OSLICESTR:
   350  		v.budget--
   351  	case OSLICE3, OSLICE3ARR:
   352  		v.budget -= 2
   353  	}
   354  
   355  	// When debugging, don't stop early, to get full cost of inlining this function
   356  	if v.budget < 0 && Debug['m'] < 2 {
   357  		return true
   358  	}
   359  
   360  	return v.visit(n.Left) || v.visit(n.Right) ||
   361  		v.visitList(n.List) || v.visitList(n.Rlist) ||
   362  		v.visitList(n.Ninit) || v.visitList(n.Nbody)
   363  }
   364  
   365  // Inlcopy and inlcopylist recursively copy the body of a function.
   366  // Any name-like node of non-local class is marked for re-export by adding it to
   367  // the exportlist.
   368  func inlcopylist(ll []*Node) []*Node {
   369  	s := make([]*Node, 0, len(ll))
   370  	for _, n := range ll {
   371  		s = append(s, inlcopy(n))
   372  	}
   373  	return s
   374  }
   375  
   376  func inlcopy(n *Node) *Node {
   377  	if n == nil {
   378  		return nil
   379  	}
   380  
   381  	switch n.Op {
   382  	case ONAME, OTYPE, OLITERAL:
   383  		return n
   384  	}
   385  
   386  	m := *n
   387  	if m.Func != nil {
   388  		m.Func.Inl.Set(nil)
   389  	}
   390  	m.Left = inlcopy(n.Left)
   391  	m.Right = inlcopy(n.Right)
   392  	m.List.Set(inlcopylist(n.List.Slice()))
   393  	m.Rlist.Set(inlcopylist(n.Rlist.Slice()))
   394  	m.Ninit.Set(inlcopylist(n.Ninit.Slice()))
   395  	m.Nbody.Set(inlcopylist(n.Nbody.Slice()))
   396  
   397  	return &m
   398  }
   399  
   400  // Inlcalls/nodelist/node walks fn's statements and expressions and substitutes any
   401  // calls made to inlineable functions. This is the external entry point.
   402  func inlcalls(fn *Node) {
   403  	savefn := Curfn
   404  	Curfn = fn
   405  	fn = inlnode(fn)
   406  	if fn != Curfn {
   407  		Fatalf("inlnode replaced curfn")
   408  	}
   409  	Curfn = savefn
   410  }
   411  
   412  // Turn an OINLCALL into a statement.
   413  func inlconv2stmt(n *Node) {
   414  	n.Op = OBLOCK
   415  
   416  	// n->ninit stays
   417  	n.List.Set(n.Nbody.Slice())
   418  
   419  	n.Nbody.Set(nil)
   420  	n.Rlist.Set(nil)
   421  }
   422  
   423  // Turn an OINLCALL into a single valued expression.
   424  // The result of inlconv2expr MUST be assigned back to n, e.g.
   425  // 	n.Left = inlconv2expr(n.Left)
   426  func inlconv2expr(n *Node) *Node {
   427  	r := n.Rlist.First()
   428  	return addinit(r, append(n.Ninit.Slice(), n.Nbody.Slice()...))
   429  }
   430  
   431  // Turn the rlist (with the return values) of the OINLCALL in
   432  // n into an expression list lumping the ninit and body
   433  // containing the inlined statements on the first list element so
   434  // order will be preserved Used in return, oas2func and call
   435  // statements.
   436  func inlconv2list(n *Node) []*Node {
   437  	if n.Op != OINLCALL || n.Rlist.Len() == 0 {
   438  		Fatalf("inlconv2list %+v\n", n)
   439  	}
   440  
   441  	s := n.Rlist.Slice()
   442  	s[0] = addinit(s[0], append(n.Ninit.Slice(), n.Nbody.Slice()...))
   443  	return s
   444  }
   445  
   446  func inlnodelist(l Nodes) {
   447  	s := l.Slice()
   448  	for i := range s {
   449  		s[i] = inlnode(s[i])
   450  	}
   451  }
   452  
   453  // inlnode recurses over the tree to find inlineable calls, which will
   454  // be turned into OINLCALLs by mkinlcall. When the recursion comes
   455  // back up will examine left, right, list, rlist, ninit, ntest, nincr,
   456  // nbody and nelse and use one of the 4 inlconv/glue functions above
   457  // to turn the OINLCALL into an expression, a statement, or patch it
   458  // in to this nodes list or rlist as appropriate.
   459  // NOTE it makes no sense to pass the glue functions down the
   460  // recursion to the level where the OINLCALL gets created because they
   461  // have to edit /this/ n, so you'd have to push that one down as well,
   462  // but then you may as well do it here.  so this is cleaner and
   463  // shorter and less complicated.
   464  // The result of inlnode MUST be assigned back to n, e.g.
   465  // 	n.Left = inlnode(n.Left)
   466  func inlnode(n *Node) *Node {
   467  	if n == nil {
   468  		return n
   469  	}
   470  
   471  	switch n.Op {
   472  	// inhibit inlining of their argument
   473  	case ODEFER, OPROC:
   474  		switch n.Left.Op {
   475  		case OCALLFUNC, OCALLMETH:
   476  			n.Left.SetNoInline(true)
   477  		}
   478  		return n
   479  
   480  	// TODO do them here (or earlier),
   481  	// so escape analysis can avoid more heapmoves.
   482  	case OCLOSURE:
   483  		return n
   484  	}
   485  
   486  	lno := setlineno(n)
   487  
   488  	inlnodelist(n.Ninit)
   489  	for _, n1 := range n.Ninit.Slice() {
   490  		if n1.Op == OINLCALL {
   491  			inlconv2stmt(n1)
   492  		}
   493  	}
   494  
   495  	n.Left = inlnode(n.Left)
   496  	if n.Left != nil && n.Left.Op == OINLCALL {
   497  		n.Left = inlconv2expr(n.Left)
   498  	}
   499  
   500  	n.Right = inlnode(n.Right)
   501  	if n.Right != nil && n.Right.Op == OINLCALL {
   502  		if n.Op == OFOR || n.Op == OFORUNTIL {
   503  			inlconv2stmt(n.Right)
   504  		} else {
   505  			n.Right = inlconv2expr(n.Right)
   506  		}
   507  	}
   508  
   509  	inlnodelist(n.List)
   510  	switch n.Op {
   511  	case OBLOCK:
   512  		for _, n2 := range n.List.Slice() {
   513  			if n2.Op == OINLCALL {
   514  				inlconv2stmt(n2)
   515  			}
   516  		}
   517  
   518  	case ORETURN, OCALLFUNC, OCALLMETH, OCALLINTER, OAPPEND, OCOMPLEX:
   519  		// if we just replaced arg in f(arg()) or return arg with an inlined call
   520  		// and arg returns multiple values, glue as list
   521  		if n.List.Len() == 1 && n.List.First().Op == OINLCALL && n.List.First().Rlist.Len() > 1 {
   522  			n.List.Set(inlconv2list(n.List.First()))
   523  			break
   524  		}
   525  		fallthrough
   526  
   527  	default:
   528  		s := n.List.Slice()
   529  		for i1, n1 := range s {
   530  			if n1 != nil && n1.Op == OINLCALL {
   531  				s[i1] = inlconv2expr(s[i1])
   532  			}
   533  		}
   534  	}
   535  
   536  	inlnodelist(n.Rlist)
   537  	if n.Op == OAS2FUNC && n.Rlist.First().Op == OINLCALL {
   538  		n.Rlist.Set(inlconv2list(n.Rlist.First()))
   539  		n.Op = OAS2
   540  		n.SetTypecheck(0)
   541  		n = typecheck(n, Etop)
   542  	} else {
   543  		s := n.Rlist.Slice()
   544  		for i1, n1 := range s {
   545  			if n1.Op == OINLCALL {
   546  				if n.Op == OIF {
   547  					inlconv2stmt(n1)
   548  				} else {
   549  					s[i1] = inlconv2expr(s[i1])
   550  				}
   551  			}
   552  		}
   553  	}
   554  
   555  	inlnodelist(n.Nbody)
   556  	for _, n := range n.Nbody.Slice() {
   557  		if n.Op == OINLCALL {
   558  			inlconv2stmt(n)
   559  		}
   560  	}
   561  
   562  	// with all the branches out of the way, it is now time to
   563  	// transmogrify this node itself unless inhibited by the
   564  	// switch at the top of this function.
   565  	switch n.Op {
   566  	case OCALLFUNC, OCALLMETH:
   567  		if n.NoInline() {
   568  			return n
   569  		}
   570  	}
   571  
   572  	switch n.Op {
   573  	case OCALLFUNC:
   574  		if Debug['m'] > 3 {
   575  			fmt.Printf("%v:call to func %+v\n", n.Line(), n.Left)
   576  		}
   577  		if n.Left.Func != nil && n.Left.Func.Inl.Len() != 0 && !isIntrinsicCall(n) { // normal case
   578  			n = mkinlcall(n, n.Left, n.Isddd())
   579  		} else if n.Left.isMethodExpression() && asNode(n.Left.Sym.Def) != nil {
   580  			n = mkinlcall(n, asNode(n.Left.Sym.Def), n.Isddd())
   581  		} else if n.Left.Op == OCLOSURE {
   582  			if f := inlinableClosure(n.Left); f != nil {
   583  				n = mkinlcall(n, f, n.Isddd())
   584  			}
   585  		} else if n.Left.Op == ONAME && n.Left.Name != nil && n.Left.Name.Defn != nil {
   586  			if d := n.Left.Name.Defn; d.Op == OAS && d.Right.Op == OCLOSURE {
   587  				if f := inlinableClosure(d.Right); f != nil {
   588  					// NB: this check is necessary to prevent indirect re-assignment of the variable
   589  					// having the address taken after the invocation or only used for reads is actually fine
   590  					// but we have no easy way to distinguish the safe cases
   591  					if d.Left.Addrtaken() {
   592  						if Debug['m'] > 1 {
   593  							fmt.Printf("%v: cannot inline escaping closure variable %v\n", n.Line(), n.Left)
   594  						}
   595  						break
   596  					}
   597  
   598  					// ensure the variable is never re-assigned
   599  					if unsafe, a := reassigned(n.Left); unsafe {
   600  						if Debug['m'] > 1 {
   601  							if a != nil {
   602  								fmt.Printf("%v: cannot inline re-assigned closure variable at %v: %v\n", n.Line(), a.Line(), a)
   603  							} else {
   604  								fmt.Printf("%v: cannot inline global closure variable %v\n", n.Line(), n.Left)
   605  							}
   606  						}
   607  						break
   608  					}
   609  					n = mkinlcall(n, f, n.Isddd())
   610  				}
   611  			}
   612  		}
   613  
   614  	case OCALLMETH:
   615  		if Debug['m'] > 3 {
   616  			fmt.Printf("%v:call to meth %L\n", n.Line(), n.Left.Right)
   617  		}
   618  
   619  		// typecheck should have resolved ODOTMETH->type, whose nname points to the actual function.
   620  		if n.Left.Type == nil {
   621  			Fatalf("no function type for [%p] %+v\n", n.Left, n.Left)
   622  		}
   623  
   624  		if n.Left.Type.Nname() == nil {
   625  			Fatalf("no function definition for [%p] %+v\n", n.Left.Type, n.Left.Type)
   626  		}
   627  
   628  		n = mkinlcall(n, asNode(n.Left.Type.FuncType().Nname), n.Isddd())
   629  	}
   630  
   631  	lineno = lno
   632  	return n
   633  }
   634  
   635  // inlinableClosure takes an OCLOSURE node and follows linkage to the matching ONAME with
   636  // the inlinable body. Returns nil if the function is not inlinable.
   637  func inlinableClosure(n *Node) *Node {
   638  	c := n.Func.Closure
   639  	caninl(c)
   640  	f := c.Func.Nname
   641  	if f == nil || f.Func.Inl.Len() == 0 {
   642  		return nil
   643  	}
   644  	return f
   645  }
   646  
   647  // reassigned takes an ONAME node, walks the function in which it is defined, and returns a boolean
   648  // indicating whether the name has any assignments other than its declaration.
   649  // The second return value is the first such assignment encountered in the walk, if any. It is mostly
   650  // useful for -m output documenting the reason for inhibited optimizations.
   651  // NB: global variables are always considered to be re-assigned.
   652  // TODO: handle initial declaration not including an assignment and followed by a single assignment?
   653  func reassigned(n *Node) (bool, *Node) {
   654  	if n.Op != ONAME {
   655  		Fatalf("reassigned %v", n)
   656  	}
   657  	// no way to reliably check for no-reassignment of globals, assume it can be
   658  	if n.Name.Curfn == nil {
   659  		return true, nil
   660  	}
   661  	f := n.Name.Curfn
   662  	// There just might be a good reason for this although this can be pretty surprising:
   663  	// local variables inside a closure have Curfn pointing to the OCLOSURE node instead
   664  	// of the corresponding ODCLFUNC.
   665  	// We need to walk the function body to check for reassignments so we follow the
   666  	// linkage to the ODCLFUNC node as that is where body is held.
   667  	if f.Op == OCLOSURE {
   668  		f = f.Func.Closure
   669  	}
   670  	v := reassignVisitor{name: n}
   671  	a := v.visitList(f.Nbody)
   672  	return a != nil, a
   673  }
   674  
   675  type reassignVisitor struct {
   676  	name *Node
   677  }
   678  
   679  func (v *reassignVisitor) visit(n *Node) *Node {
   680  	if n == nil {
   681  		return nil
   682  	}
   683  	switch n.Op {
   684  	case OAS:
   685  		if n.Left == v.name && n != v.name.Name.Defn {
   686  			return n
   687  		}
   688  		return nil
   689  	case OAS2, OAS2FUNC, OAS2MAPR, OAS2DOTTYPE:
   690  		for _, p := range n.List.Slice() {
   691  			if p == v.name && n != v.name.Name.Defn {
   692  				return n
   693  			}
   694  		}
   695  		return nil
   696  	}
   697  	if a := v.visit(n.Left); a != nil {
   698  		return a
   699  	}
   700  	if a := v.visit(n.Right); a != nil {
   701  		return a
   702  	}
   703  	if a := v.visitList(n.List); a != nil {
   704  		return a
   705  	}
   706  	if a := v.visitList(n.Rlist); a != nil {
   707  		return a
   708  	}
   709  	if a := v.visitList(n.Ninit); a != nil {
   710  		return a
   711  	}
   712  	if a := v.visitList(n.Nbody); a != nil {
   713  		return a
   714  	}
   715  	return nil
   716  }
   717  
   718  func (v *reassignVisitor) visitList(l Nodes) *Node {
   719  	for _, n := range l.Slice() {
   720  		if a := v.visit(n); a != nil {
   721  			return a
   722  		}
   723  	}
   724  	return nil
   725  }
   726  
   727  // The result of mkinlcall MUST be assigned back to n, e.g.
   728  // 	n.Left = mkinlcall(n.Left, fn, isddd)
   729  func mkinlcall(n *Node, fn *Node, isddd bool) *Node {
   730  	save_safemode := safemode
   731  
   732  	// imported functions may refer to unsafe as long as the
   733  	// package was marked safe during import (already checked).
   734  	pkg := fnpkg(fn)
   735  
   736  	if pkg != localpkg && pkg != nil {
   737  		safemode = false
   738  	}
   739  	n = mkinlcall1(n, fn, isddd)
   740  	safemode = save_safemode
   741  	return n
   742  }
   743  
   744  func tinlvar(t *types.Field, inlvars map[*Node]*Node) *Node {
   745  	if asNode(t.Nname) != nil && !isblank(asNode(t.Nname)) {
   746  		inlvar := inlvars[asNode(t.Nname)]
   747  		if inlvar == nil {
   748  			Fatalf("missing inlvar for %v\n", asNode(t.Nname))
   749  		}
   750  		return inlvar
   751  	}
   752  
   753  	return typecheck(nblank, Erv|Easgn)
   754  }
   755  
   756  var inlgen int
   757  
   758  // If n is a call, and fn is a function with an inlinable body,
   759  // return an OINLCALL.
   760  // On return ninit has the parameter assignments, the nbody is the
   761  // inlined function body and list, rlist contain the input, output
   762  // parameters.
   763  // The result of mkinlcall1 MUST be assigned back to n, e.g.
   764  // 	n.Left = mkinlcall1(n.Left, fn, isddd)
   765  func mkinlcall1(n, fn *Node, isddd bool) *Node {
   766  	if fn.Func.Inl.Len() == 0 {
   767  		// No inlinable body.
   768  		return n
   769  	}
   770  
   771  	if fn == Curfn || fn.Name.Defn == Curfn {
   772  		// Can't recursively inline a function into itself.
   773  		return n
   774  	}
   775  
   776  	if Debug_typecheckinl == 0 {
   777  		typecheckinl(fn)
   778  	}
   779  
   780  	// We have a function node, and it has an inlineable body.
   781  	if Debug['m'] > 1 {
   782  		fmt.Printf("%v: inlining call to %v %#v { %#v }\n", n.Line(), fn.Sym, fn.Type, fn.Func.Inl)
   783  	} else if Debug['m'] != 0 {
   784  		fmt.Printf("%v: inlining call to %v\n", n.Line(), fn)
   785  	}
   786  	if Debug['m'] > 2 {
   787  		fmt.Printf("%v: Before inlining: %+v\n", n.Line(), n)
   788  	}
   789  
   790  	ninit := n.Ninit
   791  
   792  	// Make temp names to use instead of the originals.
   793  	inlvars := make(map[*Node]*Node)
   794  
   795  	// record formals/locals for later post-processing
   796  	var inlfvars []*Node
   797  
   798  	// Find declarations corresponding to inlineable body.
   799  	var dcl []*Node
   800  	if fn.Name.Defn != nil {
   801  		dcl = fn.Func.Inldcl.Slice() // local function
   802  
   803  		// handle captured variables when inlining closures
   804  		if c := fn.Name.Defn.Func.Closure; c != nil {
   805  			for _, v := range c.Func.Cvars.Slice() {
   806  				if v.Op == OXXX {
   807  					continue
   808  				}
   809  
   810  				o := v.Name.Param.Outer
   811  				// make sure the outer param matches the inlining location
   812  				// NB: if we enabled inlining of functions containing OCLOSURE or refined
   813  				// the reassigned check via some sort of copy propagation this would most
   814  				// likely need to be changed to a loop to walk up to the correct Param
   815  				if o == nil || (o.Name.Curfn != Curfn && o.Name.Curfn.Func.Closure != Curfn) {
   816  					Fatalf("%v: unresolvable capture %v %v\n", n.Line(), fn, v)
   817  				}
   818  
   819  				if v.Name.Byval() {
   820  					iv := typecheck(inlvar(v), Erv)
   821  					ninit.Append(nod(ODCL, iv, nil))
   822  					ninit.Append(typecheck(nod(OAS, iv, o), Etop))
   823  					inlvars[v] = iv
   824  				} else {
   825  					addr := newname(lookup("&" + v.Sym.Name))
   826  					addr.Type = types.NewPtr(v.Type)
   827  					ia := typecheck(inlvar(addr), Erv)
   828  					ninit.Append(nod(ODCL, ia, nil))
   829  					ninit.Append(typecheck(nod(OAS, ia, nod(OADDR, o, nil)), Etop))
   830  					inlvars[addr] = ia
   831  
   832  					// When capturing by reference, all occurrence of the captured var
   833  					// must be substituted with dereference of the temporary address
   834  					inlvars[v] = typecheck(nod(OIND, ia, nil), Erv)
   835  				}
   836  			}
   837  		}
   838  	} else {
   839  		dcl = fn.Func.Dcl // imported function
   840  	}
   841  
   842  	for _, ln := range dcl {
   843  		if ln.Op != ONAME {
   844  			continue
   845  		}
   846  		if ln.Class() == PPARAMOUT { // return values handled below.
   847  			continue
   848  		}
   849  		if ln.isParamStackCopy() { // ignore the on-stack copy of a parameter that moved to the heap
   850  			continue
   851  		}
   852  		inlvars[ln] = typecheck(inlvar(ln), Erv)
   853  		if ln.Class() == PPARAM || ln.Name.Param.Stackcopy != nil && ln.Name.Param.Stackcopy.Class() == PPARAM {
   854  			ninit.Append(nod(ODCL, inlvars[ln], nil))
   855  		}
   856  		if genDwarfInline > 0 {
   857  			inlf := inlvars[ln]
   858  			if ln.Class() == PPARAM {
   859  				inlf.SetInlFormal(true)
   860  			} else {
   861  				inlf.SetInlLocal(true)
   862  			}
   863  			inlf.Pos = ln.Pos
   864  			inlfvars = append(inlfvars, inlf)
   865  		}
   866  	}
   867  
   868  	// temporaries for return values.
   869  	var retvars []*Node
   870  	for i, t := range fn.Type.Results().Fields().Slice() {
   871  		var m *Node
   872  		var mpos src.XPos
   873  		if t != nil && asNode(t.Nname) != nil && !isblank(asNode(t.Nname)) {
   874  			mpos = asNode(t.Nname).Pos
   875  			m = inlvar(asNode(t.Nname))
   876  			m = typecheck(m, Erv)
   877  			inlvars[asNode(t.Nname)] = m
   878  		} else {
   879  			// anonymous return values, synthesize names for use in assignment that replaces return
   880  			m = retvar(t, i)
   881  		}
   882  
   883  		if genDwarfInline > 0 {
   884  			// Don't update the src.Pos on a return variable if it
   885  			// was manufactured by the inliner (e.g. "~R2"); such vars
   886  			// were not part of the original callee.
   887  			if !strings.HasPrefix(m.Sym.Name, "~R") {
   888  				m.SetInlFormal(true)
   889  				m.Pos = mpos
   890  				inlfvars = append(inlfvars, m)
   891  			}
   892  		}
   893  
   894  		ninit.Append(nod(ODCL, m, nil))
   895  		retvars = append(retvars, m)
   896  	}
   897  
   898  	// Assign arguments to the parameters' temp names.
   899  	as := nod(OAS2, nil, nil)
   900  	as.Rlist.Set(n.List.Slice())
   901  
   902  	// For non-dotted calls to variadic functions, we assign the
   903  	// variadic parameter's temp name separately.
   904  	var vas *Node
   905  
   906  	if fn.IsMethod() {
   907  		rcv := fn.Type.Recv()
   908  
   909  		if n.Left.Op == ODOTMETH {
   910  			// For x.M(...), assign x directly to the
   911  			// receiver parameter.
   912  			if n.Left.Left == nil {
   913  				Fatalf("method call without receiver: %+v", n)
   914  			}
   915  			ras := nod(OAS, tinlvar(rcv, inlvars), n.Left.Left)
   916  			ras = typecheck(ras, Etop)
   917  			ninit.Append(ras)
   918  		} else {
   919  			// For T.M(...), add the receiver parameter to
   920  			// as.List, so it's assigned by the normal
   921  			// arguments.
   922  			if as.Rlist.Len() == 0 {
   923  				Fatalf("non-method call to method without first arg: %+v", n)
   924  			}
   925  			as.List.Append(tinlvar(rcv, inlvars))
   926  		}
   927  	}
   928  
   929  	for _, param := range fn.Type.Params().Fields().Slice() {
   930  		// For ordinary parameters or variadic parameters in
   931  		// dotted calls, just add the variable to the
   932  		// assignment list, and we're done.
   933  		if !param.Isddd() || isddd {
   934  			as.List.Append(tinlvar(param, inlvars))
   935  			continue
   936  		}
   937  
   938  		// Otherwise, we need to collect the remaining values
   939  		// to pass as a slice.
   940  
   941  		numvals := n.List.Len()
   942  		if numvals == 1 && n.List.First().Type.IsFuncArgStruct() {
   943  			numvals = n.List.First().Type.NumFields()
   944  		}
   945  
   946  		x := as.List.Len()
   947  		for as.List.Len() < numvals {
   948  			as.List.Append(argvar(param.Type, as.List.Len()))
   949  		}
   950  		varargs := as.List.Slice()[x:]
   951  
   952  		vas = nod(OAS, tinlvar(param, inlvars), nil)
   953  		if len(varargs) == 0 {
   954  			vas.Right = nodnil()
   955  			vas.Right.Type = param.Type
   956  		} else {
   957  			vas.Right = nod(OCOMPLIT, nil, typenod(param.Type))
   958  			vas.Right.List.Set(varargs)
   959  		}
   960  	}
   961  
   962  	if as.Rlist.Len() != 0 {
   963  		as = typecheck(as, Etop)
   964  		ninit.Append(as)
   965  	}
   966  
   967  	if vas != nil {
   968  		vas = typecheck(vas, Etop)
   969  		ninit.Append(vas)
   970  	}
   971  
   972  	// Zero the return parameters.
   973  	for _, n := range retvars {
   974  		ras := nod(OAS, n, nil)
   975  		ras = typecheck(ras, Etop)
   976  		ninit.Append(ras)
   977  	}
   978  
   979  	retlabel := autolabel(".i")
   980  	retlabel.Etype = 1 // flag 'safe' for escape analysis (no backjumps)
   981  
   982  	inlgen++
   983  
   984  	parent := -1
   985  	if b := Ctxt.PosTable.Pos(n.Pos).Base(); b != nil {
   986  		parent = b.InliningIndex()
   987  	}
   988  	newIndex := Ctxt.InlTree.Add(parent, n.Pos, fn.Sym.Linksym())
   989  
   990  	if genDwarfInline > 0 {
   991  		if !fn.Sym.Linksym().WasInlined() {
   992  			Ctxt.DwFixups.SetPrecursorFunc(fn.Sym.Linksym(), fn)
   993  			fn.Sym.Linksym().Set(obj.AttrWasInlined, true)
   994  		}
   995  	}
   996  
   997  	subst := inlsubst{
   998  		retlabel:    retlabel,
   999  		retvars:     retvars,
  1000  		inlvars:     inlvars,
  1001  		bases:       make(map[*src.PosBase]*src.PosBase),
  1002  		newInlIndex: newIndex,
  1003  	}
  1004  
  1005  	body := subst.list(fn.Func.Inl)
  1006  
  1007  	lab := nod(OLABEL, retlabel, nil)
  1008  	body = append(body, lab)
  1009  
  1010  	typecheckslice(body, Etop)
  1011  
  1012  	if genDwarfInline > 0 {
  1013  		for _, v := range inlfvars {
  1014  			v.Pos = subst.updatedPos(v.Pos)
  1015  		}
  1016  	}
  1017  
  1018  	//dumplist("ninit post", ninit);
  1019  
  1020  	call := nod(OINLCALL, nil, nil)
  1021  	call.Ninit.Set(ninit.Slice())
  1022  	call.Nbody.Set(body)
  1023  	call.Rlist.Set(retvars)
  1024  	call.Type = n.Type
  1025  	call.SetTypecheck(1)
  1026  
  1027  	// transitive inlining
  1028  	// might be nice to do this before exporting the body,
  1029  	// but can't emit the body with inlining expanded.
  1030  	// instead we emit the things that the body needs
  1031  	// and each use must redo the inlining.
  1032  	// luckily these are small.
  1033  	inlnodelist(call.Nbody)
  1034  	for _, n := range call.Nbody.Slice() {
  1035  		if n.Op == OINLCALL {
  1036  			inlconv2stmt(n)
  1037  		}
  1038  	}
  1039  
  1040  	if Debug['m'] > 2 {
  1041  		fmt.Printf("%v: After inlining %+v\n\n", call.Line(), call)
  1042  	}
  1043  
  1044  	return call
  1045  }
  1046  
  1047  // Every time we expand a function we generate a new set of tmpnames,
  1048  // PAUTO's in the calling functions, and link them off of the
  1049  // PPARAM's, PAUTOS and PPARAMOUTs of the called function.
  1050  func inlvar(var_ *Node) *Node {
  1051  	if Debug['m'] > 3 {
  1052  		fmt.Printf("inlvar %+v\n", var_)
  1053  	}
  1054  
  1055  	n := newname(var_.Sym)
  1056  	n.Type = var_.Type
  1057  	n.SetClass(PAUTO)
  1058  	n.Name.SetUsed(true)
  1059  	n.Name.Curfn = Curfn // the calling function, not the called one
  1060  	n.SetAddrtaken(var_.Addrtaken())
  1061  
  1062  	Curfn.Func.Dcl = append(Curfn.Func.Dcl, n)
  1063  	return n
  1064  }
  1065  
  1066  // Synthesize a variable to store the inlined function's results in.
  1067  func retvar(t *types.Field, i int) *Node {
  1068  	n := newname(lookupN("~R", i))
  1069  	n.Type = t.Type
  1070  	n.SetClass(PAUTO)
  1071  	n.Name.SetUsed(true)
  1072  	n.Name.Curfn = Curfn // the calling function, not the called one
  1073  	Curfn.Func.Dcl = append(Curfn.Func.Dcl, n)
  1074  	return n
  1075  }
  1076  
  1077  // Synthesize a variable to store the inlined function's arguments
  1078  // when they come from a multiple return call.
  1079  func argvar(t *types.Type, i int) *Node {
  1080  	n := newname(lookupN("~arg", i))
  1081  	n.Type = t.Elem()
  1082  	n.SetClass(PAUTO)
  1083  	n.Name.SetUsed(true)
  1084  	n.Name.Curfn = Curfn // the calling function, not the called one
  1085  	Curfn.Func.Dcl = append(Curfn.Func.Dcl, n)
  1086  	return n
  1087  }
  1088  
  1089  // The inlsubst type implements the actual inlining of a single
  1090  // function call.
  1091  type inlsubst struct {
  1092  	// Target of the goto substituted in place of a return.
  1093  	retlabel *Node
  1094  
  1095  	// Temporary result variables.
  1096  	retvars []*Node
  1097  
  1098  	inlvars map[*Node]*Node
  1099  
  1100  	// bases maps from original PosBase to PosBase with an extra
  1101  	// inlined call frame.
  1102  	bases map[*src.PosBase]*src.PosBase
  1103  
  1104  	// newInlIndex is the index of the inlined call frame to
  1105  	// insert for inlined nodes.
  1106  	newInlIndex int
  1107  }
  1108  
  1109  // list inlines a list of nodes.
  1110  func (subst *inlsubst) list(ll Nodes) []*Node {
  1111  	s := make([]*Node, 0, ll.Len())
  1112  	for _, n := range ll.Slice() {
  1113  		s = append(s, subst.node(n))
  1114  	}
  1115  	return s
  1116  }
  1117  
  1118  // node recursively copies a node from the saved pristine body of the
  1119  // inlined function, substituting references to input/output
  1120  // parameters with ones to the tmpnames, and substituting returns with
  1121  // assignments to the output.
  1122  func (subst *inlsubst) node(n *Node) *Node {
  1123  	if n == nil {
  1124  		return nil
  1125  	}
  1126  
  1127  	switch n.Op {
  1128  	case ONAME:
  1129  		if inlvar := subst.inlvars[n]; inlvar != nil { // These will be set during inlnode
  1130  			if Debug['m'] > 2 {
  1131  				fmt.Printf("substituting name %+v  ->  %+v\n", n, inlvar)
  1132  			}
  1133  			return inlvar
  1134  		}
  1135  
  1136  		if Debug['m'] > 2 {
  1137  			fmt.Printf("not substituting name %+v\n", n)
  1138  		}
  1139  		return n
  1140  
  1141  	case OLITERAL, OTYPE:
  1142  		// If n is a named constant or type, we can continue
  1143  		// using it in the inline copy. Otherwise, make a copy
  1144  		// so we can update the line number.
  1145  		if n.Sym != nil {
  1146  			return n
  1147  		}
  1148  
  1149  		// Since we don't handle bodies with closures, this return is guaranteed to belong to the current inlined function.
  1150  
  1151  	//		dump("Return before substitution", n);
  1152  	case ORETURN:
  1153  		m := nod(OGOTO, subst.retlabel, nil)
  1154  		m.Ninit.Set(subst.list(n.Ninit))
  1155  
  1156  		if len(subst.retvars) != 0 && n.List.Len() != 0 {
  1157  			as := nod(OAS2, nil, nil)
  1158  
  1159  			// Make a shallow copy of retvars.
  1160  			// Otherwise OINLCALL.Rlist will be the same list,
  1161  			// and later walk and typecheck may clobber it.
  1162  			for _, n := range subst.retvars {
  1163  				as.List.Append(n)
  1164  			}
  1165  			as.Rlist.Set(subst.list(n.List))
  1166  			as = typecheck(as, Etop)
  1167  			m.Ninit.Append(as)
  1168  		}
  1169  
  1170  		typecheckslice(m.Ninit.Slice(), Etop)
  1171  		m = typecheck(m, Etop)
  1172  
  1173  		//		dump("Return after substitution", m);
  1174  		return m
  1175  
  1176  	case OGOTO, OLABEL:
  1177  		m := nod(OXXX, nil, nil)
  1178  		*m = *n
  1179  		m.Pos = subst.updatedPos(m.Pos)
  1180  		m.Ninit.Set(nil)
  1181  		p := fmt.Sprintf("%s·%d", n.Left.Sym.Name, inlgen)
  1182  		m.Left = newname(lookup(p))
  1183  
  1184  		return m
  1185  	}
  1186  
  1187  	m := nod(OXXX, nil, nil)
  1188  	*m = *n
  1189  	m.Pos = subst.updatedPos(m.Pos)
  1190  	m.Ninit.Set(nil)
  1191  
  1192  	if n.Op == OCLOSURE {
  1193  		Fatalf("cannot inline function containing closure: %+v", n)
  1194  	}
  1195  
  1196  	m.Left = subst.node(n.Left)
  1197  	m.Right = subst.node(n.Right)
  1198  	m.List.Set(subst.list(n.List))
  1199  	m.Rlist.Set(subst.list(n.Rlist))
  1200  	m.Ninit.Set(append(m.Ninit.Slice(), subst.list(n.Ninit)...))
  1201  	m.Nbody.Set(subst.list(n.Nbody))
  1202  
  1203  	return m
  1204  }
  1205  
  1206  func (subst *inlsubst) updatedPos(xpos src.XPos) src.XPos {
  1207  	pos := Ctxt.PosTable.Pos(xpos)
  1208  	oldbase := pos.Base() // can be nil
  1209  	newbase := subst.bases[oldbase]
  1210  	if newbase == nil {
  1211  		newbase = src.NewInliningBase(oldbase, subst.newInlIndex)
  1212  		subst.bases[oldbase] = newbase
  1213  	}
  1214  	pos.SetBase(newbase)
  1215  	return Ctxt.PosTable.XPos(pos)
  1216  }