github.com/hikaru7719/go@v0.0.0-20181025140707-c8b2ac68906a/src/cmd/compile/internal/gc/sinit.go (about)

     1  // Copyright 2009 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  package gc
     6  
     7  import (
     8  	"cmd/compile/internal/types"
     9  	"fmt"
    10  )
    11  
    12  // Static initialization ordering state.
    13  // These values are stored in two bits in Node.flags.
    14  const (
    15  	InitNotStarted = iota
    16  	InitDone
    17  	InitPending
    18  )
    19  
    20  type InitEntry struct {
    21  	Xoffset int64 // struct, array only
    22  	Expr    *Node // bytes of run-time computed expressions
    23  }
    24  
    25  type InitPlan struct {
    26  	E []InitEntry
    27  }
    28  
    29  var (
    30  	initlist  []*Node
    31  	initplans map[*Node]*InitPlan
    32  	inittemps = make(map[*Node]*Node)
    33  )
    34  
    35  // init1 walks the AST starting at n, and accumulates in out
    36  // the list of definitions needing init code in dependency order.
    37  func init1(n *Node, out *[]*Node) {
    38  	if n == nil {
    39  		return
    40  	}
    41  	init1(n.Left, out)
    42  	init1(n.Right, out)
    43  	for _, n1 := range n.List.Slice() {
    44  		init1(n1, out)
    45  	}
    46  
    47  	if n.isMethodExpression() {
    48  		// Methods called as Type.Method(receiver, ...).
    49  		// Definitions for method expressions are stored in type->nname.
    50  		init1(asNode(n.Type.FuncType().Nname), out)
    51  	}
    52  
    53  	if n.Op != ONAME {
    54  		return
    55  	}
    56  	switch n.Class() {
    57  	case PEXTERN, PFUNC:
    58  	default:
    59  		if n.isBlank() && n.Name.Curfn == nil && n.Name.Defn != nil && n.Name.Defn.Initorder() == InitNotStarted {
    60  			// blank names initialization is part of init() but not
    61  			// when they are inside a function.
    62  			break
    63  		}
    64  		return
    65  	}
    66  
    67  	if n.Initorder() == InitDone {
    68  		return
    69  	}
    70  	if n.Initorder() == InitPending {
    71  		// Since mutually recursive sets of functions are allowed,
    72  		// we don't necessarily raise an error if n depends on a node
    73  		// which is already waiting for its dependencies to be visited.
    74  		//
    75  		// initlist contains a cycle of identifiers referring to each other.
    76  		// If this cycle contains a variable, then this variable refers to itself.
    77  		// Conversely, if there exists an initialization cycle involving
    78  		// a variable in the program, the tree walk will reach a cycle
    79  		// involving that variable.
    80  		if n.Class() != PFUNC {
    81  			foundinitloop(n, n)
    82  		}
    83  
    84  		for i := len(initlist) - 1; i >= 0; i-- {
    85  			x := initlist[i]
    86  			if x == n {
    87  				break
    88  			}
    89  			if x.Class() != PFUNC {
    90  				foundinitloop(n, x)
    91  			}
    92  		}
    93  
    94  		// The loop involves only functions, ok.
    95  		return
    96  	}
    97  
    98  	// reached a new unvisited node.
    99  	n.SetInitorder(InitPending)
   100  	initlist = append(initlist, n)
   101  
   102  	// make sure that everything n depends on is initialized.
   103  	// n->defn is an assignment to n
   104  	if defn := n.Name.Defn; defn != nil {
   105  		switch defn.Op {
   106  		default:
   107  			Dump("defn", defn)
   108  			Fatalf("init1: bad defn")
   109  
   110  		case ODCLFUNC:
   111  			init2list(defn.Nbody, out)
   112  
   113  		case OAS:
   114  			if defn.Left != n {
   115  				Dump("defn", defn)
   116  				Fatalf("init1: bad defn")
   117  			}
   118  			if defn.Left.isBlank() && candiscard(defn.Right) {
   119  				defn.Op = OEMPTY
   120  				defn.Left = nil
   121  				defn.Right = nil
   122  				break
   123  			}
   124  
   125  			init2(defn.Right, out)
   126  			if Debug['j'] != 0 {
   127  				fmt.Printf("%v\n", n.Sym)
   128  			}
   129  			if n.isBlank() || !staticinit(n, out) {
   130  				if Debug['%'] != 0 {
   131  					Dump("nonstatic", defn)
   132  				}
   133  				*out = append(*out, defn)
   134  			}
   135  
   136  		case OAS2FUNC, OAS2MAPR, OAS2DOTTYPE, OAS2RECV:
   137  			if defn.Initorder() == InitDone {
   138  				break
   139  			}
   140  			defn.SetInitorder(InitPending)
   141  			for _, n2 := range defn.Rlist.Slice() {
   142  				init1(n2, out)
   143  			}
   144  			if Debug['%'] != 0 {
   145  				Dump("nonstatic", defn)
   146  			}
   147  			*out = append(*out, defn)
   148  			defn.SetInitorder(InitDone)
   149  		}
   150  	}
   151  
   152  	last := len(initlist) - 1
   153  	if initlist[last] != n {
   154  		Fatalf("bad initlist %v", initlist)
   155  	}
   156  	initlist[last] = nil // allow GC
   157  	initlist = initlist[:last]
   158  
   159  	n.SetInitorder(InitDone)
   160  }
   161  
   162  // foundinitloop prints an init loop error and exits.
   163  func foundinitloop(node, visited *Node) {
   164  	// If there have already been errors printed,
   165  	// those errors probably confused us and
   166  	// there might not be a loop. Let the user
   167  	// fix those first.
   168  	flusherrors()
   169  	if nerrors > 0 {
   170  		errorexit()
   171  	}
   172  
   173  	// Find the index of node and visited in the initlist.
   174  	var nodeindex, visitedindex int
   175  	for ; initlist[nodeindex] != node; nodeindex++ {
   176  	}
   177  	for ; initlist[visitedindex] != visited; visitedindex++ {
   178  	}
   179  
   180  	// There is a loop involving visited. We know about node and
   181  	// initlist = n1 <- ... <- visited <- ... <- node <- ...
   182  	fmt.Printf("%v: initialization loop:\n", visited.Line())
   183  
   184  	// Print visited -> ... -> n1 -> node.
   185  	for _, n := range initlist[visitedindex:] {
   186  		fmt.Printf("\t%v %v refers to\n", n.Line(), n.Sym)
   187  	}
   188  
   189  	// Print node -> ... -> visited.
   190  	for _, n := range initlist[nodeindex:visitedindex] {
   191  		fmt.Printf("\t%v %v refers to\n", n.Line(), n.Sym)
   192  	}
   193  
   194  	fmt.Printf("\t%v %v\n", visited.Line(), visited.Sym)
   195  	errorexit()
   196  }
   197  
   198  // recurse over n, doing init1 everywhere.
   199  func init2(n *Node, out *[]*Node) {
   200  	if n == nil || n.Initorder() == InitDone {
   201  		return
   202  	}
   203  
   204  	if n.Op == ONAME && n.Ninit.Len() != 0 {
   205  		Fatalf("name %v with ninit: %+v\n", n.Sym, n)
   206  	}
   207  
   208  	init1(n, out)
   209  	init2(n.Left, out)
   210  	init2(n.Right, out)
   211  	init2list(n.Ninit, out)
   212  	init2list(n.List, out)
   213  	init2list(n.Rlist, out)
   214  	init2list(n.Nbody, out)
   215  
   216  	switch n.Op {
   217  	case OCLOSURE:
   218  		init2list(n.Func.Closure.Nbody, out)
   219  	case ODOTMETH, OCALLPART:
   220  		init2(asNode(n.Type.FuncType().Nname), out)
   221  	}
   222  }
   223  
   224  func init2list(l Nodes, out *[]*Node) {
   225  	for _, n := range l.Slice() {
   226  		init2(n, out)
   227  	}
   228  }
   229  
   230  func initreorder(l []*Node, out *[]*Node) {
   231  	for _, n := range l {
   232  		switch n.Op {
   233  		case ODCLFUNC, ODCLCONST, ODCLTYPE:
   234  			continue
   235  		}
   236  
   237  		initreorder(n.Ninit.Slice(), out)
   238  		n.Ninit.Set(nil)
   239  		init1(n, out)
   240  	}
   241  }
   242  
   243  // initfix computes initialization order for a list l of top-level
   244  // declarations and outputs the corresponding list of statements
   245  // to include in the init() function body.
   246  func initfix(l []*Node) []*Node {
   247  	var lout []*Node
   248  	initplans = make(map[*Node]*InitPlan)
   249  	lno := lineno
   250  	initreorder(l, &lout)
   251  	lineno = lno
   252  	initplans = nil
   253  	return lout
   254  }
   255  
   256  // compilation of top-level (static) assignments
   257  // into DATA statements if at all possible.
   258  func staticinit(n *Node, out *[]*Node) bool {
   259  	if n.Op != ONAME || n.Class() != PEXTERN || n.Name.Defn == nil || n.Name.Defn.Op != OAS {
   260  		Fatalf("staticinit")
   261  	}
   262  
   263  	lineno = n.Pos
   264  	l := n.Name.Defn.Left
   265  	r := n.Name.Defn.Right
   266  	return staticassign(l, r, out)
   267  }
   268  
   269  // like staticassign but we are copying an already
   270  // initialized value r.
   271  func staticcopy(l *Node, r *Node, out *[]*Node) bool {
   272  	if r.Op != ONAME {
   273  		return false
   274  	}
   275  	if r.Class() == PFUNC {
   276  		gdata(l, r, Widthptr)
   277  		return true
   278  	}
   279  	if r.Class() != PEXTERN || r.Sym.Pkg != localpkg {
   280  		return false
   281  	}
   282  	if r.Name.Defn == nil { // probably zeroed but perhaps supplied externally and of unknown value
   283  		return false
   284  	}
   285  	if r.Name.Defn.Op != OAS {
   286  		return false
   287  	}
   288  	orig := r
   289  	r = r.Name.Defn.Right
   290  
   291  	for r.Op == OCONVNOP && !types.Identical(r.Type, l.Type) {
   292  		r = r.Left
   293  	}
   294  
   295  	switch r.Op {
   296  	case ONAME:
   297  		if staticcopy(l, r, out) {
   298  			return true
   299  		}
   300  		// We may have skipped past one or more OCONVNOPs, so
   301  		// use conv to ensure r is assignable to l (#13263).
   302  		*out = append(*out, nod(OAS, l, conv(r, l.Type)))
   303  		return true
   304  
   305  	case OLITERAL:
   306  		if isZero(r) {
   307  			return true
   308  		}
   309  		gdata(l, r, int(l.Type.Width))
   310  		return true
   311  
   312  	case OADDR:
   313  		switch r.Left.Op {
   314  		case ONAME:
   315  			gdata(l, r, int(l.Type.Width))
   316  			return true
   317  		}
   318  
   319  	case OPTRLIT:
   320  		switch r.Left.Op {
   321  		case OARRAYLIT, OSLICELIT, OSTRUCTLIT, OMAPLIT:
   322  			// copy pointer
   323  			gdata(l, nod(OADDR, inittemps[r], nil), int(l.Type.Width))
   324  			return true
   325  		}
   326  
   327  	case OSLICELIT:
   328  		// copy slice
   329  		a := inittemps[r]
   330  
   331  		n := l.copy()
   332  		n.Xoffset = l.Xoffset + int64(array_array)
   333  		gdata(n, nod(OADDR, a, nil), Widthptr)
   334  		n.Xoffset = l.Xoffset + int64(array_nel)
   335  		gdata(n, r.Right, Widthptr)
   336  		n.Xoffset = l.Xoffset + int64(array_cap)
   337  		gdata(n, r.Right, Widthptr)
   338  		return true
   339  
   340  	case OARRAYLIT, OSTRUCTLIT:
   341  		p := initplans[r]
   342  
   343  		n := l.copy()
   344  		for i := range p.E {
   345  			e := &p.E[i]
   346  			n.Xoffset = l.Xoffset + e.Xoffset
   347  			n.Type = e.Expr.Type
   348  			if e.Expr.Op == OLITERAL {
   349  				gdata(n, e.Expr, int(n.Type.Width))
   350  				continue
   351  			}
   352  			ll := n.sepcopy()
   353  			if staticassign(ll, e.Expr, out) {
   354  				continue
   355  			}
   356  			// Requires computation, but we're
   357  			// copying someone else's computation.
   358  			rr := orig.sepcopy()
   359  			rr.Type = ll.Type
   360  			rr.Xoffset += e.Xoffset
   361  			setlineno(rr)
   362  			*out = append(*out, nod(OAS, ll, rr))
   363  		}
   364  
   365  		return true
   366  	}
   367  
   368  	return false
   369  }
   370  
   371  func staticassign(l *Node, r *Node, out *[]*Node) bool {
   372  	for r.Op == OCONVNOP {
   373  		r = r.Left
   374  	}
   375  
   376  	switch r.Op {
   377  	case ONAME:
   378  		return staticcopy(l, r, out)
   379  
   380  	case OLITERAL:
   381  		if isZero(r) {
   382  			return true
   383  		}
   384  		gdata(l, r, int(l.Type.Width))
   385  		return true
   386  
   387  	case OADDR:
   388  		var nam Node
   389  		if stataddr(&nam, r.Left) {
   390  			n := *r
   391  			n.Left = &nam
   392  			gdata(l, &n, int(l.Type.Width))
   393  			return true
   394  		}
   395  		fallthrough
   396  
   397  	case OPTRLIT:
   398  		switch r.Left.Op {
   399  		case OARRAYLIT, OSLICELIT, OMAPLIT, OSTRUCTLIT:
   400  			// Init pointer.
   401  			a := staticname(r.Left.Type)
   402  
   403  			inittemps[r] = a
   404  			gdata(l, nod(OADDR, a, nil), int(l.Type.Width))
   405  
   406  			// Init underlying literal.
   407  			if !staticassign(a, r.Left, out) {
   408  				*out = append(*out, nod(OAS, a, r.Left))
   409  			}
   410  			return true
   411  		}
   412  		//dump("not static ptrlit", r);
   413  
   414  	case OSTRARRAYBYTE:
   415  		if l.Class() == PEXTERN && r.Left.Op == OLITERAL {
   416  			sval := r.Left.Val().U.(string)
   417  			slicebytes(l, sval, len(sval))
   418  			return true
   419  		}
   420  
   421  	case OSLICELIT:
   422  		initplan(r)
   423  		// Init slice.
   424  		bound := r.Right.Int64()
   425  		ta := types.NewArray(r.Type.Elem(), bound)
   426  		a := staticname(ta)
   427  		inittemps[r] = a
   428  		n := l.copy()
   429  		n.Xoffset = l.Xoffset + int64(array_array)
   430  		gdata(n, nod(OADDR, a, nil), Widthptr)
   431  		n.Xoffset = l.Xoffset + int64(array_nel)
   432  		gdata(n, r.Right, Widthptr)
   433  		n.Xoffset = l.Xoffset + int64(array_cap)
   434  		gdata(n, r.Right, Widthptr)
   435  
   436  		// Fall through to init underlying array.
   437  		l = a
   438  		fallthrough
   439  
   440  	case OARRAYLIT, OSTRUCTLIT:
   441  		initplan(r)
   442  
   443  		p := initplans[r]
   444  		n := l.copy()
   445  		for i := range p.E {
   446  			e := &p.E[i]
   447  			n.Xoffset = l.Xoffset + e.Xoffset
   448  			n.Type = e.Expr.Type
   449  			if e.Expr.Op == OLITERAL {
   450  				gdata(n, e.Expr, int(n.Type.Width))
   451  				continue
   452  			}
   453  			setlineno(e.Expr)
   454  			a := n.sepcopy()
   455  			if !staticassign(a, e.Expr, out) {
   456  				*out = append(*out, nod(OAS, a, e.Expr))
   457  			}
   458  		}
   459  
   460  		return true
   461  
   462  	case OMAPLIT:
   463  		break
   464  
   465  	case OCLOSURE:
   466  		if hasemptycvars(r) {
   467  			if Debug_closure > 0 {
   468  				Warnl(r.Pos, "closure converted to global")
   469  			}
   470  			// Closures with no captured variables are globals,
   471  			// so the assignment can be done at link time.
   472  			gdata(l, r.Func.Closure.Func.Nname, Widthptr)
   473  			return true
   474  		}
   475  		closuredebugruntimecheck(r)
   476  
   477  	case OCONVIFACE:
   478  		// This logic is mirrored in isStaticCompositeLiteral.
   479  		// If you change something here, change it there, and vice versa.
   480  
   481  		// Determine the underlying concrete type and value we are converting from.
   482  		val := r
   483  		for val.Op == OCONVIFACE {
   484  			val = val.Left
   485  		}
   486  		if val.Type.IsInterface() {
   487  			// val is an interface type.
   488  			// If val is nil, we can statically initialize l;
   489  			// both words are zero and so there no work to do, so report success.
   490  			// If val is non-nil, we have no concrete type to record,
   491  			// and we won't be able to statically initialize its value, so report failure.
   492  			return Isconst(val, CTNIL)
   493  		}
   494  
   495  		var itab *Node
   496  		if l.Type.IsEmptyInterface() {
   497  			itab = typename(val.Type)
   498  		} else {
   499  			itab = itabname(val.Type, l.Type)
   500  		}
   501  
   502  		// Create a copy of l to modify while we emit data.
   503  		n := l.copy()
   504  
   505  		// Emit itab, advance offset.
   506  		gdata(n, itab, Widthptr)
   507  		n.Xoffset += int64(Widthptr)
   508  
   509  		// Emit data.
   510  		if isdirectiface(val.Type) {
   511  			if Isconst(val, CTNIL) {
   512  				// Nil is zero, nothing to do.
   513  				return true
   514  			}
   515  			// Copy val directly into n.
   516  			n.Type = val.Type
   517  			setlineno(val)
   518  			a := n.sepcopy()
   519  			if !staticassign(a, val, out) {
   520  				*out = append(*out, nod(OAS, a, val))
   521  			}
   522  		} else {
   523  			// Construct temp to hold val, write pointer to temp into n.
   524  			a := staticname(val.Type)
   525  			inittemps[val] = a
   526  			if !staticassign(a, val, out) {
   527  				*out = append(*out, nod(OAS, a, val))
   528  			}
   529  			ptr := nod(OADDR, a, nil)
   530  			n.Type = types.NewPtr(val.Type)
   531  			gdata(n, ptr, Widthptr)
   532  		}
   533  
   534  		return true
   535  	}
   536  
   537  	//dump("not static", r);
   538  	return false
   539  }
   540  
   541  // initContext is the context in which static data is populated.
   542  // It is either in an init function or in any other function.
   543  // Static data populated in an init function will be written either
   544  // zero times (as a readonly, static data symbol) or
   545  // one time (during init function execution).
   546  // Either way, there is no opportunity for races or further modification,
   547  // so the data can be written to a (possibly readonly) data symbol.
   548  // Static data populated in any other function needs to be local to
   549  // that function to allow multiple instances of that function
   550  // to execute concurrently without clobbering each others' data.
   551  type initContext uint8
   552  
   553  const (
   554  	inInitFunction initContext = iota
   555  	inNonInitFunction
   556  )
   557  
   558  // from here down is the walk analysis
   559  // of composite literals.
   560  // most of the work is to generate
   561  // data statements for the constant
   562  // part of the composite literal.
   563  
   564  var statuniqgen int // name generator for static temps
   565  
   566  // staticname returns a name backed by a static data symbol.
   567  // Callers should call n.Name.SetReadonly(true) on the
   568  // returned node for readonly nodes.
   569  func staticname(t *types.Type) *Node {
   570  	// Don't use lookupN; it interns the resulting string, but these are all unique.
   571  	n := newname(lookup(fmt.Sprintf("statictmp_%d", statuniqgen)))
   572  	statuniqgen++
   573  	addvar(n, t, PEXTERN)
   574  	return n
   575  }
   576  
   577  func isLiteral(n *Node) bool {
   578  	// Treat nils as zeros rather than literals.
   579  	return n.Op == OLITERAL && n.Val().Ctype() != CTNIL
   580  }
   581  
   582  func (n *Node) isSimpleName() bool {
   583  	return n.Op == ONAME && n.Addable() && n.Class() != PAUTOHEAP && n.Class() != PEXTERN
   584  }
   585  
   586  func litas(l *Node, r *Node, init *Nodes) {
   587  	a := nod(OAS, l, r)
   588  	a = typecheck(a, Etop)
   589  	a = walkexpr(a, init)
   590  	init.Append(a)
   591  }
   592  
   593  // initGenType is a bitmap indicating the types of generation that will occur for a static value.
   594  type initGenType uint8
   595  
   596  const (
   597  	initDynamic initGenType = 1 << iota // contains some dynamic values, for which init code will be generated
   598  	initConst                           // contains some constant values, which may be written into data symbols
   599  )
   600  
   601  // getdyn calculates the initGenType for n.
   602  // If top is false, getdyn is recursing.
   603  func getdyn(n *Node, top bool) initGenType {
   604  	switch n.Op {
   605  	default:
   606  		if isLiteral(n) {
   607  			return initConst
   608  		}
   609  		return initDynamic
   610  
   611  	case OSLICELIT:
   612  		if !top {
   613  			return initDynamic
   614  		}
   615  
   616  	case OARRAYLIT, OSTRUCTLIT:
   617  	}
   618  
   619  	var mode initGenType
   620  	for _, n1 := range n.List.Slice() {
   621  		switch n1.Op {
   622  		case OKEY:
   623  			n1 = n1.Right
   624  		case OSTRUCTKEY:
   625  			n1 = n1.Left
   626  		}
   627  		mode |= getdyn(n1, false)
   628  		if mode == initDynamic|initConst {
   629  			break
   630  		}
   631  	}
   632  	return mode
   633  }
   634  
   635  // isStaticCompositeLiteral reports whether n is a compile-time constant.
   636  func isStaticCompositeLiteral(n *Node) bool {
   637  	switch n.Op {
   638  	case OSLICELIT:
   639  		return false
   640  	case OARRAYLIT:
   641  		for _, r := range n.List.Slice() {
   642  			if r.Op == OKEY {
   643  				r = r.Right
   644  			}
   645  			if !isStaticCompositeLiteral(r) {
   646  				return false
   647  			}
   648  		}
   649  		return true
   650  	case OSTRUCTLIT:
   651  		for _, r := range n.List.Slice() {
   652  			if r.Op != OSTRUCTKEY {
   653  				Fatalf("isStaticCompositeLiteral: rhs not OSTRUCTKEY: %v", r)
   654  			}
   655  			if !isStaticCompositeLiteral(r.Left) {
   656  				return false
   657  			}
   658  		}
   659  		return true
   660  	case OLITERAL:
   661  		return true
   662  	case OCONVIFACE:
   663  		// See staticassign's OCONVIFACE case for comments.
   664  		val := n
   665  		for val.Op == OCONVIFACE {
   666  			val = val.Left
   667  		}
   668  		if val.Type.IsInterface() {
   669  			return Isconst(val, CTNIL)
   670  		}
   671  		if isdirectiface(val.Type) && Isconst(val, CTNIL) {
   672  			return true
   673  		}
   674  		return isStaticCompositeLiteral(val)
   675  	}
   676  	return false
   677  }
   678  
   679  // initKind is a kind of static initialization: static, dynamic, or local.
   680  // Static initialization represents literals and
   681  // literal components of composite literals.
   682  // Dynamic initialization represents non-literals and
   683  // non-literal components of composite literals.
   684  // LocalCode initializion represents initialization
   685  // that occurs purely in generated code local to the function of use.
   686  // Initialization code is sometimes generated in passes,
   687  // first static then dynamic.
   688  type initKind uint8
   689  
   690  const (
   691  	initKindStatic initKind = iota + 1
   692  	initKindDynamic
   693  	initKindLocalCode
   694  )
   695  
   696  // fixedlit handles struct, array, and slice literals.
   697  // TODO: expand documentation.
   698  func fixedlit(ctxt initContext, kind initKind, n *Node, var_ *Node, init *Nodes) {
   699  	var splitnode func(*Node) (a *Node, value *Node)
   700  	switch n.Op {
   701  	case OARRAYLIT, OSLICELIT:
   702  		var k int64
   703  		splitnode = func(r *Node) (*Node, *Node) {
   704  			if r.Op == OKEY {
   705  				k = nonnegintconst(r.Left)
   706  				r = r.Right
   707  			}
   708  			a := nod(OINDEX, var_, nodintconst(k))
   709  			k++
   710  			return a, r
   711  		}
   712  	case OSTRUCTLIT:
   713  		splitnode = func(r *Node) (*Node, *Node) {
   714  			if r.Op != OSTRUCTKEY {
   715  				Fatalf("fixedlit: rhs not OSTRUCTKEY: %v", r)
   716  			}
   717  			if r.Sym.IsBlank() {
   718  				return nblank, r.Left
   719  			}
   720  			return nodSym(ODOT, var_, r.Sym), r.Left
   721  		}
   722  	default:
   723  		Fatalf("fixedlit bad op: %v", n.Op)
   724  	}
   725  
   726  	for _, r := range n.List.Slice() {
   727  		a, value := splitnode(r)
   728  
   729  		switch value.Op {
   730  		case OSLICELIT:
   731  			if (kind == initKindStatic && ctxt == inNonInitFunction) || (kind == initKindDynamic && ctxt == inInitFunction) {
   732  				slicelit(ctxt, value, a, init)
   733  				continue
   734  			}
   735  
   736  		case OARRAYLIT, OSTRUCTLIT:
   737  			fixedlit(ctxt, kind, value, a, init)
   738  			continue
   739  		}
   740  
   741  		islit := isLiteral(value)
   742  		if (kind == initKindStatic && !islit) || (kind == initKindDynamic && islit) {
   743  			continue
   744  		}
   745  
   746  		// build list of assignments: var[index] = expr
   747  		setlineno(value)
   748  		a = nod(OAS, a, value)
   749  		a = typecheck(a, Etop)
   750  		switch kind {
   751  		case initKindStatic:
   752  			genAsStatic(a)
   753  		case initKindDynamic, initKindLocalCode:
   754  			a = orderStmtInPlace(a, map[string][]*Node{})
   755  			a = walkstmt(a)
   756  			init.Append(a)
   757  		default:
   758  			Fatalf("fixedlit: bad kind %d", kind)
   759  		}
   760  
   761  	}
   762  }
   763  
   764  func slicelit(ctxt initContext, n *Node, var_ *Node, init *Nodes) {
   765  	// make an array type corresponding the number of elements we have
   766  	t := types.NewArray(n.Type.Elem(), n.Right.Int64())
   767  	dowidth(t)
   768  
   769  	if ctxt == inNonInitFunction {
   770  		// put everything into static array
   771  		vstat := staticname(t)
   772  
   773  		fixedlit(ctxt, initKindStatic, n, vstat, init)
   774  		fixedlit(ctxt, initKindDynamic, n, vstat, init)
   775  
   776  		// copy static to slice
   777  		var_ = typecheck(var_, Erv|Easgn)
   778  		var nam Node
   779  		if !stataddr(&nam, var_) || nam.Class() != PEXTERN {
   780  			Fatalf("slicelit: %v", var_)
   781  		}
   782  
   783  		var v Node
   784  		v.Type = types.Types[TINT]
   785  		setintconst(&v, t.NumElem())
   786  
   787  		nam.Xoffset += int64(array_array)
   788  		gdata(&nam, nod(OADDR, vstat, nil), Widthptr)
   789  		nam.Xoffset += int64(array_nel) - int64(array_array)
   790  		gdata(&nam, &v, Widthptr)
   791  		nam.Xoffset += int64(array_cap) - int64(array_nel)
   792  		gdata(&nam, &v, Widthptr)
   793  
   794  		return
   795  	}
   796  
   797  	// recipe for var = []t{...}
   798  	// 1. make a static array
   799  	//	var vstat [...]t
   800  	// 2. assign (data statements) the constant part
   801  	//	vstat = constpart{}
   802  	// 3. make an auto pointer to array and allocate heap to it
   803  	//	var vauto *[...]t = new([...]t)
   804  	// 4. copy the static array to the auto array
   805  	//	*vauto = vstat
   806  	// 5. for each dynamic part assign to the array
   807  	//	vauto[i] = dynamic part
   808  	// 6. assign slice of allocated heap to var
   809  	//	var = vauto[:]
   810  	//
   811  	// an optimization is done if there is no constant part
   812  	//	3. var vauto *[...]t = new([...]t)
   813  	//	5. vauto[i] = dynamic part
   814  	//	6. var = vauto[:]
   815  
   816  	// if the literal contains constants,
   817  	// make static initialized array (1),(2)
   818  	var vstat *Node
   819  
   820  	mode := getdyn(n, true)
   821  	if mode&initConst != 0 {
   822  		vstat = staticname(t)
   823  		if ctxt == inInitFunction {
   824  			vstat.Name.SetReadonly(true)
   825  		}
   826  		fixedlit(ctxt, initKindStatic, n, vstat, init)
   827  	}
   828  
   829  	// make new auto *array (3 declare)
   830  	vauto := temp(types.NewPtr(t))
   831  
   832  	// set auto to point at new temp or heap (3 assign)
   833  	var a *Node
   834  	if x := prealloc[n]; x != nil {
   835  		// temp allocated during order.go for dddarg
   836  		if !types.Identical(t, x.Type) {
   837  			panic("dotdotdot base type does not match order's assigned type")
   838  		}
   839  
   840  		if vstat == nil {
   841  			a = nod(OAS, x, nil)
   842  			a = typecheck(a, Etop)
   843  			init.Append(a) // zero new temp
   844  		} else {
   845  			// Declare that we're about to initialize all of x.
   846  			// (Which happens at the *vauto = vstat below.)
   847  			init.Append(nod(OVARDEF, x, nil))
   848  		}
   849  
   850  		a = nod(OADDR, x, nil)
   851  	} else if n.Esc == EscNone {
   852  		a = temp(t)
   853  		if vstat == nil {
   854  			a = nod(OAS, temp(t), nil)
   855  			a = typecheck(a, Etop)
   856  			init.Append(a) // zero new temp
   857  			a = a.Left
   858  		} else {
   859  			init.Append(nod(OVARDEF, a, nil))
   860  		}
   861  
   862  		a = nod(OADDR, a, nil)
   863  	} else {
   864  		a = nod(ONEW, nil, nil)
   865  		a.List.Set1(typenod(t))
   866  	}
   867  
   868  	a = nod(OAS, vauto, a)
   869  	a = typecheck(a, Etop)
   870  	a = walkexpr(a, init)
   871  	init.Append(a)
   872  
   873  	if vstat != nil {
   874  		// copy static to heap (4)
   875  		a = nod(OIND, vauto, nil)
   876  
   877  		a = nod(OAS, a, vstat)
   878  		a = typecheck(a, Etop)
   879  		a = walkexpr(a, init)
   880  		init.Append(a)
   881  	}
   882  
   883  	// put dynamics into array (5)
   884  	var index int64
   885  	for _, value := range n.List.Slice() {
   886  		if value.Op == OKEY {
   887  			index = nonnegintconst(value.Left)
   888  			value = value.Right
   889  		}
   890  		a := nod(OINDEX, vauto, nodintconst(index))
   891  		a.SetBounded(true)
   892  		index++
   893  
   894  		// TODO need to check bounds?
   895  
   896  		switch value.Op {
   897  		case OSLICELIT:
   898  			break
   899  
   900  		case OARRAYLIT, OSTRUCTLIT:
   901  			fixedlit(ctxt, initKindDynamic, value, a, init)
   902  			continue
   903  		}
   904  
   905  		if isLiteral(value) {
   906  			continue
   907  		}
   908  
   909  		// build list of vauto[c] = expr
   910  		setlineno(value)
   911  		a = nod(OAS, a, value)
   912  
   913  		a = typecheck(a, Etop)
   914  		a = orderStmtInPlace(a, map[string][]*Node{})
   915  		a = walkstmt(a)
   916  		init.Append(a)
   917  	}
   918  
   919  	// make slice out of heap (6)
   920  	a = nod(OAS, var_, nod(OSLICE, vauto, nil))
   921  
   922  	a = typecheck(a, Etop)
   923  	a = orderStmtInPlace(a, map[string][]*Node{})
   924  	a = walkstmt(a)
   925  	init.Append(a)
   926  }
   927  
   928  func maplit(n *Node, m *Node, init *Nodes) {
   929  	// make the map var
   930  	a := nod(OMAKE, nil, nil)
   931  	a.Esc = n.Esc
   932  	a.List.Set2(typenod(n.Type), nodintconst(int64(n.List.Len())))
   933  	litas(m, a, init)
   934  
   935  	// Split the initializers into static and dynamic.
   936  	var stat, dyn []*Node
   937  	for _, r := range n.List.Slice() {
   938  		if r.Op != OKEY {
   939  			Fatalf("maplit: rhs not OKEY: %v", r)
   940  		}
   941  		if isStaticCompositeLiteral(r.Left) && isStaticCompositeLiteral(r.Right) {
   942  			stat = append(stat, r)
   943  		} else {
   944  			dyn = append(dyn, r)
   945  		}
   946  	}
   947  
   948  	// Add static entries.
   949  	if len(stat) > 25 {
   950  		// For a large number of static entries, put them in an array and loop.
   951  
   952  		// build types [count]Tindex and [count]Tvalue
   953  		tk := types.NewArray(n.Type.Key(), int64(len(stat)))
   954  		tv := types.NewArray(n.Type.Elem(), int64(len(stat)))
   955  
   956  		// TODO(josharian): suppress alg generation for these types?
   957  		dowidth(tk)
   958  		dowidth(tv)
   959  
   960  		// make and initialize static arrays
   961  		vstatk := staticname(tk)
   962  		vstatk.Name.SetReadonly(true)
   963  		vstatv := staticname(tv)
   964  		vstatv.Name.SetReadonly(true)
   965  
   966  		datak := nod(OARRAYLIT, nil, nil)
   967  		datav := nod(OARRAYLIT, nil, nil)
   968  		for _, r := range stat {
   969  			datak.List.Append(r.Left)
   970  			datav.List.Append(r.Right)
   971  		}
   972  		fixedlit(inInitFunction, initKindStatic, datak, vstatk, init)
   973  		fixedlit(inInitFunction, initKindStatic, datav, vstatv, init)
   974  
   975  		// loop adding structure elements to map
   976  		// for i = 0; i < len(vstatk); i++ {
   977  		//	map[vstatk[i]] = vstatv[i]
   978  		// }
   979  		i := temp(types.Types[TINT])
   980  		rhs := nod(OINDEX, vstatv, i)
   981  		rhs.SetBounded(true)
   982  
   983  		kidx := nod(OINDEX, vstatk, i)
   984  		kidx.SetBounded(true)
   985  		lhs := nod(OINDEX, m, kidx)
   986  
   987  		zero := nod(OAS, i, nodintconst(0))
   988  		cond := nod(OLT, i, nodintconst(tk.NumElem()))
   989  		incr := nod(OAS, i, nod(OADD, i, nodintconst(1)))
   990  		body := nod(OAS, lhs, rhs)
   991  
   992  		loop := nod(OFOR, cond, incr)
   993  		loop.Nbody.Set1(body)
   994  		loop.Ninit.Set1(zero)
   995  
   996  		loop = typecheck(loop, Etop)
   997  		loop = walkstmt(loop)
   998  		init.Append(loop)
   999  	} else {
  1000  		// For a small number of static entries, just add them directly.
  1001  		addMapEntries(m, stat, init)
  1002  	}
  1003  
  1004  	// Add dynamic entries.
  1005  	addMapEntries(m, dyn, init)
  1006  }
  1007  
  1008  func addMapEntries(m *Node, dyn []*Node, init *Nodes) {
  1009  	if len(dyn) == 0 {
  1010  		return
  1011  	}
  1012  
  1013  	nerr := nerrors
  1014  
  1015  	// Build list of var[c] = expr.
  1016  	// Use temporaries so that mapassign1 can have addressable key, val.
  1017  	// TODO(josharian): avoid map key temporaries for mapfast_* assignments with literal keys.
  1018  	key := temp(m.Type.Key())
  1019  	val := temp(m.Type.Elem())
  1020  
  1021  	for _, r := range dyn {
  1022  		index, value := r.Left, r.Right
  1023  
  1024  		setlineno(index)
  1025  		a := nod(OAS, key, index)
  1026  		a = typecheck(a, Etop)
  1027  		a = walkstmt(a)
  1028  		init.Append(a)
  1029  
  1030  		setlineno(value)
  1031  		a = nod(OAS, val, value)
  1032  		a = typecheck(a, Etop)
  1033  		a = walkstmt(a)
  1034  		init.Append(a)
  1035  
  1036  		setlineno(val)
  1037  		a = nod(OAS, nod(OINDEX, m, key), val)
  1038  		a = typecheck(a, Etop)
  1039  		a = walkstmt(a)
  1040  		init.Append(a)
  1041  
  1042  		if nerr != nerrors {
  1043  			break
  1044  		}
  1045  	}
  1046  
  1047  	a := nod(OVARKILL, key, nil)
  1048  	a = typecheck(a, Etop)
  1049  	init.Append(a)
  1050  	a = nod(OVARKILL, val, nil)
  1051  	a = typecheck(a, Etop)
  1052  	init.Append(a)
  1053  }
  1054  
  1055  func anylit(n *Node, var_ *Node, init *Nodes) {
  1056  	t := n.Type
  1057  	switch n.Op {
  1058  	default:
  1059  		Fatalf("anylit: not lit, op=%v node=%v", n.Op, n)
  1060  
  1061  	case OPTRLIT:
  1062  		if !t.IsPtr() {
  1063  			Fatalf("anylit: not ptr")
  1064  		}
  1065  
  1066  		var r *Node
  1067  		if n.Right != nil {
  1068  			// n.Right is stack temporary used as backing store.
  1069  			init.Append(nod(OAS, n.Right, nil)) // zero backing store, just in case (#18410)
  1070  			r = nod(OADDR, n.Right, nil)
  1071  			r = typecheck(r, Erv)
  1072  		} else {
  1073  			r = nod(ONEW, nil, nil)
  1074  			r.SetTypecheck(1)
  1075  			r.Type = t
  1076  			r.Esc = n.Esc
  1077  		}
  1078  
  1079  		r = walkexpr(r, init)
  1080  		a := nod(OAS, var_, r)
  1081  
  1082  		a = typecheck(a, Etop)
  1083  		init.Append(a)
  1084  
  1085  		var_ = nod(OIND, var_, nil)
  1086  		var_ = typecheck(var_, Erv|Easgn)
  1087  		anylit(n.Left, var_, init)
  1088  
  1089  	case OSTRUCTLIT, OARRAYLIT:
  1090  		if !t.IsStruct() && !t.IsArray() {
  1091  			Fatalf("anylit: not struct/array")
  1092  		}
  1093  
  1094  		if var_.isSimpleName() && n.List.Len() > 4 {
  1095  			// lay out static data
  1096  			vstat := staticname(t)
  1097  			vstat.Name.SetReadonly(true)
  1098  
  1099  			ctxt := inInitFunction
  1100  			if n.Op == OARRAYLIT {
  1101  				ctxt = inNonInitFunction
  1102  			}
  1103  			fixedlit(ctxt, initKindStatic, n, vstat, init)
  1104  
  1105  			// copy static to var
  1106  			a := nod(OAS, var_, vstat)
  1107  
  1108  			a = typecheck(a, Etop)
  1109  			a = walkexpr(a, init)
  1110  			init.Append(a)
  1111  
  1112  			// add expressions to automatic
  1113  			fixedlit(inInitFunction, initKindDynamic, n, var_, init)
  1114  			break
  1115  		}
  1116  
  1117  		var components int64
  1118  		if n.Op == OARRAYLIT {
  1119  			components = t.NumElem()
  1120  		} else {
  1121  			components = int64(t.NumFields())
  1122  		}
  1123  		// initialization of an array or struct with unspecified components (missing fields or arrays)
  1124  		if var_.isSimpleName() || int64(n.List.Len()) < components {
  1125  			a := nod(OAS, var_, nil)
  1126  			a = typecheck(a, Etop)
  1127  			a = walkexpr(a, init)
  1128  			init.Append(a)
  1129  		}
  1130  
  1131  		fixedlit(inInitFunction, initKindLocalCode, n, var_, init)
  1132  
  1133  	case OSLICELIT:
  1134  		slicelit(inInitFunction, n, var_, init)
  1135  
  1136  	case OMAPLIT:
  1137  		if !t.IsMap() {
  1138  			Fatalf("anylit: not map")
  1139  		}
  1140  		maplit(n, var_, init)
  1141  	}
  1142  }
  1143  
  1144  func oaslit(n *Node, init *Nodes) bool {
  1145  	if n.Left == nil || n.Right == nil {
  1146  		// not a special composite literal assignment
  1147  		return false
  1148  	}
  1149  	if n.Left.Type == nil || n.Right.Type == nil {
  1150  		// not a special composite literal assignment
  1151  		return false
  1152  	}
  1153  	if !n.Left.isSimpleName() {
  1154  		// not a special composite literal assignment
  1155  		return false
  1156  	}
  1157  	if !types.Identical(n.Left.Type, n.Right.Type) {
  1158  		// not a special composite literal assignment
  1159  		return false
  1160  	}
  1161  
  1162  	switch n.Right.Op {
  1163  	default:
  1164  		// not a special composite literal assignment
  1165  		return false
  1166  
  1167  	case OSTRUCTLIT, OARRAYLIT, OSLICELIT, OMAPLIT:
  1168  		if vmatch1(n.Left, n.Right) {
  1169  			// not a special composite literal assignment
  1170  			return false
  1171  		}
  1172  		anylit(n.Right, n.Left, init)
  1173  	}
  1174  
  1175  	n.Op = OEMPTY
  1176  	n.Right = nil
  1177  	return true
  1178  }
  1179  
  1180  func getlit(lit *Node) int {
  1181  	if smallintconst(lit) {
  1182  		return int(lit.Int64())
  1183  	}
  1184  	return -1
  1185  }
  1186  
  1187  // stataddr sets nam to the static address of n and reports whether it succeeded.
  1188  func stataddr(nam *Node, n *Node) bool {
  1189  	if n == nil {
  1190  		return false
  1191  	}
  1192  
  1193  	switch n.Op {
  1194  	case ONAME:
  1195  		*nam = *n
  1196  		return n.Addable()
  1197  
  1198  	case ODOT:
  1199  		if !stataddr(nam, n.Left) {
  1200  			break
  1201  		}
  1202  		nam.Xoffset += n.Xoffset
  1203  		nam.Type = n.Type
  1204  		return true
  1205  
  1206  	case OINDEX:
  1207  		if n.Left.Type.IsSlice() {
  1208  			break
  1209  		}
  1210  		if !stataddr(nam, n.Left) {
  1211  			break
  1212  		}
  1213  		l := getlit(n.Right)
  1214  		if l < 0 {
  1215  			break
  1216  		}
  1217  
  1218  		// Check for overflow.
  1219  		if n.Type.Width != 0 && thearch.MAXWIDTH/n.Type.Width <= int64(l) {
  1220  			break
  1221  		}
  1222  		nam.Xoffset += int64(l) * n.Type.Width
  1223  		nam.Type = n.Type
  1224  		return true
  1225  	}
  1226  
  1227  	return false
  1228  }
  1229  
  1230  func initplan(n *Node) {
  1231  	if initplans[n] != nil {
  1232  		return
  1233  	}
  1234  	p := new(InitPlan)
  1235  	initplans[n] = p
  1236  	switch n.Op {
  1237  	default:
  1238  		Fatalf("initplan")
  1239  
  1240  	case OARRAYLIT, OSLICELIT:
  1241  		var k int64
  1242  		for _, a := range n.List.Slice() {
  1243  			if a.Op == OKEY {
  1244  				k = nonnegintconst(a.Left)
  1245  				a = a.Right
  1246  			}
  1247  			addvalue(p, k*n.Type.Elem().Width, a)
  1248  			k++
  1249  		}
  1250  
  1251  	case OSTRUCTLIT:
  1252  		for _, a := range n.List.Slice() {
  1253  			if a.Op != OSTRUCTKEY {
  1254  				Fatalf("initplan fixedlit")
  1255  			}
  1256  			addvalue(p, a.Xoffset, a.Left)
  1257  		}
  1258  
  1259  	case OMAPLIT:
  1260  		for _, a := range n.List.Slice() {
  1261  			if a.Op != OKEY {
  1262  				Fatalf("initplan maplit")
  1263  			}
  1264  			addvalue(p, -1, a.Right)
  1265  		}
  1266  	}
  1267  }
  1268  
  1269  func addvalue(p *InitPlan, xoffset int64, n *Node) {
  1270  	// special case: zero can be dropped entirely
  1271  	if isZero(n) {
  1272  		return
  1273  	}
  1274  
  1275  	// special case: inline struct and array (not slice) literals
  1276  	if isvaluelit(n) {
  1277  		initplan(n)
  1278  		q := initplans[n]
  1279  		for _, qe := range q.E {
  1280  			// qe is a copy; we are not modifying entries in q.E
  1281  			qe.Xoffset += xoffset
  1282  			p.E = append(p.E, qe)
  1283  		}
  1284  		return
  1285  	}
  1286  
  1287  	// add to plan
  1288  	p.E = append(p.E, InitEntry{Xoffset: xoffset, Expr: n})
  1289  }
  1290  
  1291  func isZero(n *Node) bool {
  1292  	switch n.Op {
  1293  	case OLITERAL:
  1294  		switch u := n.Val().U.(type) {
  1295  		default:
  1296  			Dump("unexpected literal", n)
  1297  			Fatalf("isZero")
  1298  		case *NilVal:
  1299  			return true
  1300  		case string:
  1301  			return u == ""
  1302  		case bool:
  1303  			return !u
  1304  		case *Mpint:
  1305  			return u.CmpInt64(0) == 0
  1306  		case *Mpflt:
  1307  			return u.CmpFloat64(0) == 0
  1308  		case *Mpcplx:
  1309  			return u.Real.CmpFloat64(0) == 0 && u.Imag.CmpFloat64(0) == 0
  1310  		}
  1311  
  1312  	case OARRAYLIT:
  1313  		for _, n1 := range n.List.Slice() {
  1314  			if n1.Op == OKEY {
  1315  				n1 = n1.Right
  1316  			}
  1317  			if !isZero(n1) {
  1318  				return false
  1319  			}
  1320  		}
  1321  		return true
  1322  
  1323  	case OSTRUCTLIT:
  1324  		for _, n1 := range n.List.Slice() {
  1325  			if !isZero(n1.Left) {
  1326  				return false
  1327  			}
  1328  		}
  1329  		return true
  1330  	}
  1331  
  1332  	return false
  1333  }
  1334  
  1335  func isvaluelit(n *Node) bool {
  1336  	return n.Op == OARRAYLIT || n.Op == OSTRUCTLIT
  1337  }
  1338  
  1339  func genAsStatic(as *Node) {
  1340  	if as.Left.Type == nil {
  1341  		Fatalf("genAsStatic as.Left not typechecked")
  1342  	}
  1343  
  1344  	var nam Node
  1345  	if !stataddr(&nam, as.Left) || (nam.Class() != PEXTERN && as.Left != nblank) {
  1346  		Fatalf("genAsStatic: lhs %v", as.Left)
  1347  	}
  1348  
  1349  	switch {
  1350  	case as.Right.Op == OLITERAL:
  1351  	case as.Right.Op == ONAME && as.Right.Class() == PFUNC:
  1352  	default:
  1353  		Fatalf("genAsStatic: rhs %v", as.Right)
  1354  	}
  1355  
  1356  	gdata(&nam, as.Right, int(as.Right.Type.Width))
  1357  }