github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/tools/go/ssa/builder.go (about)

     1  // Copyright 2013 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  // +build go1.5
     6  
     7  package ssa
     8  
     9  // This file implements the BUILD phase of SSA construction.
    10  //
    11  // SSA construction has two phases, CREATE and BUILD.  In the CREATE phase
    12  // (create.go), all packages are constructed and type-checked and
    13  // definitions of all package members are created, method-sets are
    14  // computed, and wrapper methods are synthesized.
    15  // ssa.Packages are created in arbitrary order.
    16  //
    17  // In the BUILD phase (builder.go), the builder traverses the AST of
    18  // each Go source function and generates SSA instructions for the
    19  // function body.  Initializer expressions for package-level variables
    20  // are emitted to the package's init() function in the order specified
    21  // by go/types.Info.InitOrder, then code for each function in the
    22  // package is generated in lexical order.
    23  // The BUILD phases for distinct packages are independent and are
    24  // executed in parallel.
    25  //
    26  // TODO(adonovan): indeed, building functions is now embarrassingly parallel.
    27  // Audit for concurrency then benchmark using more goroutines.
    28  //
    29  // The builder's and Program's indices (maps) are populated and
    30  // mutated during the CREATE phase, but during the BUILD phase they
    31  // remain constant.  The sole exception is Prog.methodSets and its
    32  // related maps, which are protected by a dedicated mutex.
    33  
    34  import (
    35  	"fmt"
    36  	"go/ast"
    37  	exact "go/constant"
    38  	"go/token"
    39  	"go/types"
    40  	"os"
    41  	"sync"
    42  )
    43  
    44  type opaqueType struct {
    45  	types.Type
    46  	name string
    47  }
    48  
    49  func (t *opaqueType) String() string { return t.name }
    50  
    51  var (
    52  	varOk    = newVar("ok", tBool)
    53  	varIndex = newVar("index", tInt)
    54  
    55  	// Type constants.
    56  	tBool       = types.Typ[types.Bool]
    57  	tByte       = types.Typ[types.Byte]
    58  	tInt        = types.Typ[types.Int]
    59  	tInvalid    = types.Typ[types.Invalid]
    60  	tString     = types.Typ[types.String]
    61  	tUntypedNil = types.Typ[types.UntypedNil]
    62  	tRangeIter  = &opaqueType{nil, "iter"} // the type of all "range" iterators
    63  	tEface      = new(types.Interface)
    64  
    65  	// SSA Value constants.
    66  	vZero = intConst(0)
    67  	vOne  = intConst(1)
    68  	vTrue = NewConst(exact.MakeBool(true), tBool)
    69  )
    70  
    71  // builder holds state associated with the package currently being built.
    72  // Its methods contain all the logic for AST-to-SSA conversion.
    73  type builder struct{}
    74  
    75  // cond emits to fn code to evaluate boolean condition e and jump
    76  // to t or f depending on its value, performing various simplifications.
    77  //
    78  // Postcondition: fn.currentBlock is nil.
    79  //
    80  func (b *builder) cond(fn *Function, e ast.Expr, t, f *BasicBlock) {
    81  	switch e := e.(type) {
    82  	case *ast.ParenExpr:
    83  		b.cond(fn, e.X, t, f)
    84  		return
    85  
    86  	case *ast.BinaryExpr:
    87  		switch e.Op {
    88  		case token.LAND:
    89  			ltrue := fn.newBasicBlock("cond.true")
    90  			b.cond(fn, e.X, ltrue, f)
    91  			fn.currentBlock = ltrue
    92  			b.cond(fn, e.Y, t, f)
    93  			return
    94  
    95  		case token.LOR:
    96  			lfalse := fn.newBasicBlock("cond.false")
    97  			b.cond(fn, e.X, t, lfalse)
    98  			fn.currentBlock = lfalse
    99  			b.cond(fn, e.Y, t, f)
   100  			return
   101  		}
   102  
   103  	case *ast.UnaryExpr:
   104  		if e.Op == token.NOT {
   105  			b.cond(fn, e.X, f, t)
   106  			return
   107  		}
   108  	}
   109  
   110  	// A traditional compiler would simplify "if false" (etc) here
   111  	// but we do not, for better fidelity to the source code.
   112  	//
   113  	// The value of a constant condition may be platform-specific,
   114  	// and may cause blocks that are reachable in some configuration
   115  	// to be hidden from subsequent analyses such as bug-finding tools.
   116  	emitIf(fn, b.expr(fn, e), t, f)
   117  }
   118  
   119  // logicalBinop emits code to fn to evaluate e, a &&- or
   120  // ||-expression whose reified boolean value is wanted.
   121  // The value is returned.
   122  //
   123  func (b *builder) logicalBinop(fn *Function, e *ast.BinaryExpr) Value {
   124  	rhs := fn.newBasicBlock("binop.rhs")
   125  	done := fn.newBasicBlock("binop.done")
   126  
   127  	// T(e) = T(e.X) = T(e.Y) after untyped constants have been
   128  	// eliminated.
   129  	// TODO(adonovan): not true; MyBool==MyBool yields UntypedBool.
   130  	t := fn.Pkg.typeOf(e)
   131  
   132  	var short Value // value of the short-circuit path
   133  	switch e.Op {
   134  	case token.LAND:
   135  		b.cond(fn, e.X, rhs, done)
   136  		short = NewConst(exact.MakeBool(false), t)
   137  
   138  	case token.LOR:
   139  		b.cond(fn, e.X, done, rhs)
   140  		short = NewConst(exact.MakeBool(true), t)
   141  	}
   142  
   143  	// Is rhs unreachable?
   144  	if rhs.Preds == nil {
   145  		// Simplify false&&y to false, true||y to true.
   146  		fn.currentBlock = done
   147  		return short
   148  	}
   149  
   150  	// Is done unreachable?
   151  	if done.Preds == nil {
   152  		// Simplify true&&y (or false||y) to y.
   153  		fn.currentBlock = rhs
   154  		return b.expr(fn, e.Y)
   155  	}
   156  
   157  	// All edges from e.X to done carry the short-circuit value.
   158  	var edges []Value
   159  	for _ = range done.Preds {
   160  		edges = append(edges, short)
   161  	}
   162  
   163  	// The edge from e.Y to done carries the value of e.Y.
   164  	fn.currentBlock = rhs
   165  	edges = append(edges, b.expr(fn, e.Y))
   166  	emitJump(fn, done)
   167  	fn.currentBlock = done
   168  
   169  	phi := &Phi{Edges: edges, Comment: e.Op.String()}
   170  	phi.pos = e.OpPos
   171  	phi.typ = t
   172  	return done.emit(phi)
   173  }
   174  
   175  // exprN lowers a multi-result expression e to SSA form, emitting code
   176  // to fn and returning a single Value whose type is a *types.Tuple.
   177  // The caller must access the components via Extract.
   178  //
   179  // Multi-result expressions include CallExprs in a multi-value
   180  // assignment or return statement, and "value,ok" uses of
   181  // TypeAssertExpr, IndexExpr (when X is a map), and UnaryExpr (when Op
   182  // is token.ARROW).
   183  //
   184  func (b *builder) exprN(fn *Function, e ast.Expr) Value {
   185  	typ := fn.Pkg.typeOf(e).(*types.Tuple)
   186  	switch e := e.(type) {
   187  	case *ast.ParenExpr:
   188  		return b.exprN(fn, e.X)
   189  
   190  	case *ast.CallExpr:
   191  		// Currently, no built-in function nor type conversion
   192  		// has multiple results, so we can avoid some of the
   193  		// cases for single-valued CallExpr.
   194  		var c Call
   195  		b.setCall(fn, e, &c.Call)
   196  		c.typ = typ
   197  		return fn.emit(&c)
   198  
   199  	case *ast.IndexExpr:
   200  		mapt := fn.Pkg.typeOf(e.X).Underlying().(*types.Map)
   201  		lookup := &Lookup{
   202  			X:       b.expr(fn, e.X),
   203  			Index:   emitConv(fn, b.expr(fn, e.Index), mapt.Key()),
   204  			CommaOk: true,
   205  		}
   206  		lookup.setType(typ)
   207  		lookup.setPos(e.Lbrack)
   208  		return fn.emit(lookup)
   209  
   210  	case *ast.TypeAssertExpr:
   211  		return emitTypeTest(fn, b.expr(fn, e.X), typ.At(0).Type(), e.Lparen)
   212  
   213  	case *ast.UnaryExpr: // must be receive <-
   214  		unop := &UnOp{
   215  			Op:      token.ARROW,
   216  			X:       b.expr(fn, e.X),
   217  			CommaOk: true,
   218  		}
   219  		unop.setType(typ)
   220  		unop.setPos(e.OpPos)
   221  		return fn.emit(unop)
   222  	}
   223  	panic(fmt.Sprintf("exprN(%T) in %s", e, fn))
   224  }
   225  
   226  // builtin emits to fn SSA instructions to implement a call to the
   227  // built-in function obj with the specified arguments
   228  // and return type.  It returns the value defined by the result.
   229  //
   230  // The result is nil if no special handling was required; in this case
   231  // the caller should treat this like an ordinary library function
   232  // call.
   233  //
   234  func (b *builder) builtin(fn *Function, obj *types.Builtin, args []ast.Expr, typ types.Type, pos token.Pos) Value {
   235  	switch obj.Name() {
   236  	case "make":
   237  		switch typ.Underlying().(type) {
   238  		case *types.Slice:
   239  			n := b.expr(fn, args[1])
   240  			m := n
   241  			if len(args) == 3 {
   242  				m = b.expr(fn, args[2])
   243  			}
   244  			if m, ok := m.(*Const); ok {
   245  				// treat make([]T, n, m) as new([m]T)[:n]
   246  				cap := m.Int64()
   247  				at := types.NewArray(typ.Underlying().(*types.Slice).Elem(), cap)
   248  				alloc := emitNew(fn, at, pos)
   249  				alloc.Comment = "makeslice"
   250  				v := &Slice{
   251  					X:    alloc,
   252  					High: n,
   253  				}
   254  				v.setPos(pos)
   255  				v.setType(typ)
   256  				return fn.emit(v)
   257  			}
   258  			v := &MakeSlice{
   259  				Len: n,
   260  				Cap: m,
   261  			}
   262  			v.setPos(pos)
   263  			v.setType(typ)
   264  			return fn.emit(v)
   265  
   266  		case *types.Map:
   267  			var res Value
   268  			if len(args) == 2 {
   269  				res = b.expr(fn, args[1])
   270  			}
   271  			v := &MakeMap{Reserve: res}
   272  			v.setPos(pos)
   273  			v.setType(typ)
   274  			return fn.emit(v)
   275  
   276  		case *types.Chan:
   277  			var sz Value = vZero
   278  			if len(args) == 2 {
   279  				sz = b.expr(fn, args[1])
   280  			}
   281  			v := &MakeChan{Size: sz}
   282  			v.setPos(pos)
   283  			v.setType(typ)
   284  			return fn.emit(v)
   285  		}
   286  
   287  	case "new":
   288  		alloc := emitNew(fn, deref(typ), pos)
   289  		alloc.Comment = "new"
   290  		return alloc
   291  
   292  	case "len", "cap":
   293  		// Special case: len or cap of an array or *array is
   294  		// based on the type, not the value which may be nil.
   295  		// We must still evaluate the value, though.  (If it
   296  		// was side-effect free, the whole call would have
   297  		// been constant-folded.)
   298  		t := deref(fn.Pkg.typeOf(args[0])).Underlying()
   299  		if at, ok := t.(*types.Array); ok {
   300  			b.expr(fn, args[0]) // for effects only
   301  			return intConst(at.Len())
   302  		}
   303  		// Otherwise treat as normal.
   304  
   305  	case "panic":
   306  		fn.emit(&Panic{
   307  			X:   emitConv(fn, b.expr(fn, args[0]), tEface),
   308  			pos: pos,
   309  		})
   310  		fn.currentBlock = fn.newBasicBlock("unreachable")
   311  		return vTrue // any non-nil Value will do
   312  	}
   313  	return nil // treat all others as a regular function call
   314  }
   315  
   316  // addr lowers a single-result addressable expression e to SSA form,
   317  // emitting code to fn and returning the location (an lvalue) defined
   318  // by the expression.
   319  //
   320  // If escaping is true, addr marks the base variable of the
   321  // addressable expression e as being a potentially escaping pointer
   322  // value.  For example, in this code:
   323  //
   324  //   a := A{
   325  //     b: [1]B{B{c: 1}}
   326  //   }
   327  //   return &a.b[0].c
   328  //
   329  // the application of & causes a.b[0].c to have its address taken,
   330  // which means that ultimately the local variable a must be
   331  // heap-allocated.  This is a simple but very conservative escape
   332  // analysis.
   333  //
   334  // Operations forming potentially escaping pointers include:
   335  // - &x, including when implicit in method call or composite literals.
   336  // - a[:] iff a is an array (not *array)
   337  // - references to variables in lexically enclosing functions.
   338  //
   339  func (b *builder) addr(fn *Function, e ast.Expr, escaping bool) lvalue {
   340  	switch e := e.(type) {
   341  	case *ast.Ident:
   342  		if isBlankIdent(e) {
   343  			return blank{}
   344  		}
   345  		obj := fn.Pkg.objectOf(e)
   346  		v := fn.Prog.packageLevelValue(obj) // var (address)
   347  		if v == nil {
   348  			v = fn.lookup(obj, escaping)
   349  		}
   350  		return &address{addr: v, pos: e.Pos(), expr: e}
   351  
   352  	case *ast.CompositeLit:
   353  		t := deref(fn.Pkg.typeOf(e))
   354  		var v *Alloc
   355  		if escaping {
   356  			v = emitNew(fn, t, e.Lbrace)
   357  		} else {
   358  			v = fn.addLocal(t, e.Lbrace)
   359  		}
   360  		v.Comment = "complit"
   361  		var sb storebuf
   362  		b.compLit(fn, v, e, true, &sb)
   363  		sb.emit(fn)
   364  		return &address{addr: v, pos: e.Lbrace, expr: e}
   365  
   366  	case *ast.ParenExpr:
   367  		return b.addr(fn, e.X, escaping)
   368  
   369  	case *ast.SelectorExpr:
   370  		sel, ok := fn.Pkg.info.Selections[e]
   371  		if !ok {
   372  			// qualified identifier
   373  			return b.addr(fn, e.Sel, escaping)
   374  		}
   375  		if sel.Kind() != types.FieldVal {
   376  			panic(sel)
   377  		}
   378  		wantAddr := true
   379  		v := b.receiver(fn, e.X, wantAddr, escaping, sel)
   380  		last := len(sel.Index()) - 1
   381  		return &address{
   382  			addr: emitFieldSelection(fn, v, sel.Index()[last], true, e.Sel),
   383  			pos:  e.Sel.Pos(),
   384  			expr: e.Sel,
   385  		}
   386  
   387  	case *ast.IndexExpr:
   388  		var x Value
   389  		var et types.Type
   390  		switch t := fn.Pkg.typeOf(e.X).Underlying().(type) {
   391  		case *types.Array:
   392  			x = b.addr(fn, e.X, escaping).address(fn)
   393  			et = types.NewPointer(t.Elem())
   394  		case *types.Pointer: // *array
   395  			x = b.expr(fn, e.X)
   396  			et = types.NewPointer(t.Elem().Underlying().(*types.Array).Elem())
   397  		case *types.Slice:
   398  			x = b.expr(fn, e.X)
   399  			et = types.NewPointer(t.Elem())
   400  		case *types.Map:
   401  			return &element{
   402  				m:   b.expr(fn, e.X),
   403  				k:   emitConv(fn, b.expr(fn, e.Index), t.Key()),
   404  				t:   t.Elem(),
   405  				pos: e.Lbrack,
   406  			}
   407  		default:
   408  			panic("unexpected container type in IndexExpr: " + t.String())
   409  		}
   410  		v := &IndexAddr{
   411  			X:     x,
   412  			Index: emitConv(fn, b.expr(fn, e.Index), tInt),
   413  		}
   414  		v.setPos(e.Lbrack)
   415  		v.setType(et)
   416  		return &address{addr: fn.emit(v), pos: e.Lbrack, expr: e}
   417  
   418  	case *ast.StarExpr:
   419  		return &address{addr: b.expr(fn, e.X), pos: e.Star, expr: e}
   420  	}
   421  
   422  	panic(fmt.Sprintf("unexpected address expression: %T", e))
   423  }
   424  
   425  type store struct {
   426  	lhs lvalue
   427  	rhs Value
   428  }
   429  
   430  type storebuf struct{ stores []store }
   431  
   432  func (sb *storebuf) store(lhs lvalue, rhs Value) {
   433  	sb.stores = append(sb.stores, store{lhs, rhs})
   434  }
   435  
   436  func (sb *storebuf) emit(fn *Function) {
   437  	for _, s := range sb.stores {
   438  		s.lhs.store(fn, s.rhs)
   439  	}
   440  }
   441  
   442  // assign emits to fn code to initialize the lvalue loc with the value
   443  // of expression e.  If isZero is true, assign assumes that loc holds
   444  // the zero value for its type.
   445  //
   446  // This is equivalent to loc.store(fn, b.expr(fn, e)), but may generate
   447  // better code in some cases, e.g., for composite literals in an
   448  // addressable location.
   449  //
   450  // If sb is not nil, assign generates code to evaluate expression e, but
   451  // not to update loc.  Instead, the necessary stores are appended to the
   452  // storebuf sb so that they can be executed later.  This allows correct
   453  // in-place update of existing variables when the RHS is a composite
   454  // literal that may reference parts of the LHS.
   455  //
   456  func (b *builder) assign(fn *Function, loc lvalue, e ast.Expr, isZero bool, sb *storebuf) {
   457  	// Can we initialize it in place?
   458  	if e, ok := unparen(e).(*ast.CompositeLit); ok {
   459  		// A CompositeLit never evaluates to a pointer,
   460  		// so if the type of the location is a pointer,
   461  		// an &-operation is implied.
   462  		if _, ok := loc.(blank); !ok { // avoid calling blank.typ()
   463  			if isPointer(loc.typ()) {
   464  				ptr := b.addr(fn, e, true).address(fn)
   465  				// copy address
   466  				if sb != nil {
   467  					sb.store(loc, ptr)
   468  				} else {
   469  					loc.store(fn, ptr)
   470  				}
   471  				return
   472  			}
   473  		}
   474  
   475  		if _, ok := loc.(*address); ok {
   476  			if isInterface(loc.typ()) {
   477  				// e.g. var x interface{} = T{...}
   478  				// Can't in-place initialize an interface value.
   479  				// Fall back to copying.
   480  			} else {
   481  				// x = T{...} or x := T{...}
   482  				addr := loc.address(fn)
   483  				if sb != nil {
   484  					b.compLit(fn, addr, e, isZero, sb)
   485  				} else {
   486  					var sb storebuf
   487  					b.compLit(fn, addr, e, isZero, &sb)
   488  					sb.emit(fn)
   489  				}
   490  
   491  				// Subtle: emit debug ref for aggregate types only;
   492  				// slice and map are handled by store ops in compLit.
   493  				switch loc.typ().Underlying().(type) {
   494  				case *types.Struct, *types.Array:
   495  					emitDebugRef(fn, e, addr, true)
   496  				}
   497  
   498  				return
   499  			}
   500  		}
   501  	}
   502  
   503  	// simple case: just copy
   504  	rhs := b.expr(fn, e)
   505  	if sb != nil {
   506  		sb.store(loc, rhs)
   507  	} else {
   508  		loc.store(fn, rhs)
   509  	}
   510  }
   511  
   512  // expr lowers a single-result expression e to SSA form, emitting code
   513  // to fn and returning the Value defined by the expression.
   514  //
   515  func (b *builder) expr(fn *Function, e ast.Expr) Value {
   516  	e = unparen(e)
   517  
   518  	tv := fn.Pkg.info.Types[e]
   519  
   520  	// Is expression a constant?
   521  	if tv.Value != nil {
   522  		return NewConst(tv.Value, tv.Type)
   523  	}
   524  
   525  	var v Value
   526  	if tv.Addressable() {
   527  		// Prefer pointer arithmetic ({Index,Field}Addr) followed
   528  		// by Load over subelement extraction (e.g. Index, Field),
   529  		// to avoid large copies.
   530  		v = b.addr(fn, e, false).load(fn)
   531  	} else {
   532  		v = b.expr0(fn, e, tv)
   533  	}
   534  	if fn.debugInfo() {
   535  		emitDebugRef(fn, e, v, false)
   536  	}
   537  	return v
   538  }
   539  
   540  func (b *builder) expr0(fn *Function, e ast.Expr, tv types.TypeAndValue) Value {
   541  	switch e := e.(type) {
   542  	case *ast.BasicLit:
   543  		panic("non-constant BasicLit") // unreachable
   544  
   545  	case *ast.FuncLit:
   546  		fn2 := &Function{
   547  			name:      fmt.Sprintf("%s$%d", fn.Name(), 1+len(fn.AnonFuncs)),
   548  			Signature: fn.Pkg.typeOf(e.Type).Underlying().(*types.Signature),
   549  			pos:       e.Type.Func,
   550  			parent:    fn,
   551  			Pkg:       fn.Pkg,
   552  			Prog:      fn.Prog,
   553  			syntax:    e,
   554  		}
   555  		fn.AnonFuncs = append(fn.AnonFuncs, fn2)
   556  		b.buildFunction(fn2)
   557  		if fn2.FreeVars == nil {
   558  			return fn2
   559  		}
   560  		v := &MakeClosure{Fn: fn2}
   561  		v.setType(tv.Type)
   562  		for _, fv := range fn2.FreeVars {
   563  			v.Bindings = append(v.Bindings, fv.outer)
   564  			fv.outer = nil
   565  		}
   566  		return fn.emit(v)
   567  
   568  	case *ast.TypeAssertExpr: // single-result form only
   569  		return emitTypeAssert(fn, b.expr(fn, e.X), tv.Type, e.Lparen)
   570  
   571  	case *ast.CallExpr:
   572  		if fn.Pkg.info.Types[e.Fun].IsType() {
   573  			// Explicit type conversion, e.g. string(x) or big.Int(x)
   574  			x := b.expr(fn, e.Args[0])
   575  			y := emitConv(fn, x, tv.Type)
   576  			if y != x {
   577  				switch y := y.(type) {
   578  				case *Convert:
   579  					y.pos = e.Lparen
   580  				case *ChangeType:
   581  					y.pos = e.Lparen
   582  				case *MakeInterface:
   583  					y.pos = e.Lparen
   584  				}
   585  			}
   586  			return y
   587  		}
   588  		// Call to "intrinsic" built-ins, e.g. new, make, panic.
   589  		if id, ok := unparen(e.Fun).(*ast.Ident); ok {
   590  			if obj, ok := fn.Pkg.info.Uses[id].(*types.Builtin); ok {
   591  				if v := b.builtin(fn, obj, e.Args, tv.Type, e.Lparen); v != nil {
   592  					return v
   593  				}
   594  			}
   595  		}
   596  		// Regular function call.
   597  		var v Call
   598  		b.setCall(fn, e, &v.Call)
   599  		v.setType(tv.Type)
   600  		return fn.emit(&v)
   601  
   602  	case *ast.UnaryExpr:
   603  		switch e.Op {
   604  		case token.AND: // &X --- potentially escaping.
   605  			addr := b.addr(fn, e.X, true)
   606  			if _, ok := unparen(e.X).(*ast.StarExpr); ok {
   607  				// &*p must panic if p is nil (http://golang.org/s/go12nil).
   608  				// For simplicity, we'll just (suboptimally) rely
   609  				// on the side effects of a load.
   610  				// TODO(adonovan): emit dedicated nilcheck.
   611  				addr.load(fn)
   612  			}
   613  			return addr.address(fn)
   614  		case token.ADD:
   615  			return b.expr(fn, e.X)
   616  		case token.NOT, token.ARROW, token.SUB, token.XOR: // ! <- - ^
   617  			v := &UnOp{
   618  				Op: e.Op,
   619  				X:  b.expr(fn, e.X),
   620  			}
   621  			v.setPos(e.OpPos)
   622  			v.setType(tv.Type)
   623  			return fn.emit(v)
   624  		default:
   625  			panic(e.Op)
   626  		}
   627  
   628  	case *ast.BinaryExpr:
   629  		switch e.Op {
   630  		case token.LAND, token.LOR:
   631  			return b.logicalBinop(fn, e)
   632  		case token.SHL, token.SHR:
   633  			fallthrough
   634  		case token.ADD, token.SUB, token.MUL, token.QUO, token.REM, token.AND, token.OR, token.XOR, token.AND_NOT:
   635  			return emitArith(fn, e.Op, b.expr(fn, e.X), b.expr(fn, e.Y), tv.Type, e.OpPos)
   636  
   637  		case token.EQL, token.NEQ, token.GTR, token.LSS, token.LEQ, token.GEQ:
   638  			cmp := emitCompare(fn, e.Op, b.expr(fn, e.X), b.expr(fn, e.Y), e.OpPos)
   639  			// The type of x==y may be UntypedBool.
   640  			return emitConv(fn, cmp, DefaultType(tv.Type))
   641  		default:
   642  			panic("illegal op in BinaryExpr: " + e.Op.String())
   643  		}
   644  
   645  	case *ast.SliceExpr:
   646  		var low, high, max Value
   647  		var x Value
   648  		switch fn.Pkg.typeOf(e.X).Underlying().(type) {
   649  		case *types.Array:
   650  			// Potentially escaping.
   651  			x = b.addr(fn, e.X, true).address(fn)
   652  		case *types.Basic, *types.Slice, *types.Pointer: // *array
   653  			x = b.expr(fn, e.X)
   654  		default:
   655  			panic("unreachable")
   656  		}
   657  		if e.High != nil {
   658  			high = b.expr(fn, e.High)
   659  		}
   660  		if e.Low != nil {
   661  			low = b.expr(fn, e.Low)
   662  		}
   663  		if e.Slice3 {
   664  			max = b.expr(fn, e.Max)
   665  		}
   666  		v := &Slice{
   667  			X:    x,
   668  			Low:  low,
   669  			High: high,
   670  			Max:  max,
   671  		}
   672  		v.setPos(e.Lbrack)
   673  		v.setType(tv.Type)
   674  		return fn.emit(v)
   675  
   676  	case *ast.Ident:
   677  		obj := fn.Pkg.info.Uses[e]
   678  		// Universal built-in or nil?
   679  		switch obj := obj.(type) {
   680  		case *types.Builtin:
   681  			return &Builtin{name: obj.Name(), sig: tv.Type.(*types.Signature)}
   682  		case *types.Nil:
   683  			return nilConst(tv.Type)
   684  		}
   685  		// Package-level func or var?
   686  		if v := fn.Prog.packageLevelValue(obj); v != nil {
   687  			if _, ok := obj.(*types.Var); ok {
   688  				return emitLoad(fn, v) // var (address)
   689  			}
   690  			return v // (func)
   691  		}
   692  		// Local var.
   693  		return emitLoad(fn, fn.lookup(obj, false)) // var (address)
   694  
   695  	case *ast.SelectorExpr:
   696  		sel, ok := fn.Pkg.info.Selections[e]
   697  		if !ok {
   698  			// qualified identifier
   699  			return b.expr(fn, e.Sel)
   700  		}
   701  		switch sel.Kind() {
   702  		case types.MethodExpr:
   703  			// (*T).f or T.f, the method f from the method-set of type T.
   704  			// The result is a "thunk".
   705  			return emitConv(fn, makeThunk(fn.Prog, sel), tv.Type)
   706  
   707  		case types.MethodVal:
   708  			// e.f where e is an expression and f is a method.
   709  			// The result is a "bound".
   710  			obj := sel.Obj().(*types.Func)
   711  			rt := recvType(obj)
   712  			wantAddr := isPointer(rt)
   713  			escaping := true
   714  			v := b.receiver(fn, e.X, wantAddr, escaping, sel)
   715  			if isInterface(rt) {
   716  				// If v has interface type I,
   717  				// we must emit a check that v is non-nil.
   718  				// We use: typeassert v.(I).
   719  				emitTypeAssert(fn, v, rt, token.NoPos)
   720  			}
   721  			c := &MakeClosure{
   722  				Fn:       makeBound(fn.Prog, obj),
   723  				Bindings: []Value{v},
   724  			}
   725  			c.setPos(e.Sel.Pos())
   726  			c.setType(tv.Type)
   727  			return fn.emit(c)
   728  
   729  		case types.FieldVal:
   730  			indices := sel.Index()
   731  			last := len(indices) - 1
   732  			v := b.expr(fn, e.X)
   733  			v = emitImplicitSelections(fn, v, indices[:last])
   734  			v = emitFieldSelection(fn, v, indices[last], false, e.Sel)
   735  			return v
   736  		}
   737  
   738  		panic("unexpected expression-relative selector")
   739  
   740  	case *ast.IndexExpr:
   741  		switch t := fn.Pkg.typeOf(e.X).Underlying().(type) {
   742  		case *types.Array:
   743  			// Non-addressable array (in a register).
   744  			v := &Index{
   745  				X:     b.expr(fn, e.X),
   746  				Index: emitConv(fn, b.expr(fn, e.Index), tInt),
   747  			}
   748  			v.setPos(e.Lbrack)
   749  			v.setType(t.Elem())
   750  			return fn.emit(v)
   751  
   752  		case *types.Map:
   753  			// Maps are not addressable.
   754  			mapt := fn.Pkg.typeOf(e.X).Underlying().(*types.Map)
   755  			v := &Lookup{
   756  				X:     b.expr(fn, e.X),
   757  				Index: emitConv(fn, b.expr(fn, e.Index), mapt.Key()),
   758  			}
   759  			v.setPos(e.Lbrack)
   760  			v.setType(mapt.Elem())
   761  			return fn.emit(v)
   762  
   763  		case *types.Basic: // => string
   764  			// Strings are not addressable.
   765  			v := &Lookup{
   766  				X:     b.expr(fn, e.X),
   767  				Index: b.expr(fn, e.Index),
   768  			}
   769  			v.setPos(e.Lbrack)
   770  			v.setType(tByte)
   771  			return fn.emit(v)
   772  
   773  		case *types.Slice, *types.Pointer: // *array
   774  			// Addressable slice/array; use IndexAddr and Load.
   775  			return b.addr(fn, e, false).load(fn)
   776  
   777  		default:
   778  			panic("unexpected container type in IndexExpr: " + t.String())
   779  		}
   780  
   781  	case *ast.CompositeLit, *ast.StarExpr:
   782  		// Addressable types (lvalues)
   783  		return b.addr(fn, e, false).load(fn)
   784  	}
   785  
   786  	panic(fmt.Sprintf("unexpected expr: %T", e))
   787  }
   788  
   789  // stmtList emits to fn code for all statements in list.
   790  func (b *builder) stmtList(fn *Function, list []ast.Stmt) {
   791  	for _, s := range list {
   792  		b.stmt(fn, s)
   793  	}
   794  }
   795  
   796  // receiver emits to fn code for expression e in the "receiver"
   797  // position of selection e.f (where f may be a field or a method) and
   798  // returns the effective receiver after applying the implicit field
   799  // selections of sel.
   800  //
   801  // wantAddr requests that the result is an an address.  If
   802  // !sel.Indirect(), this may require that e be built in addr() mode; it
   803  // must thus be addressable.
   804  //
   805  // escaping is defined as per builder.addr().
   806  //
   807  func (b *builder) receiver(fn *Function, e ast.Expr, wantAddr, escaping bool, sel *types.Selection) Value {
   808  	var v Value
   809  	if wantAddr && !sel.Indirect() && !isPointer(fn.Pkg.typeOf(e)) {
   810  		v = b.addr(fn, e, escaping).address(fn)
   811  	} else {
   812  		v = b.expr(fn, e)
   813  	}
   814  
   815  	last := len(sel.Index()) - 1
   816  	v = emitImplicitSelections(fn, v, sel.Index()[:last])
   817  	if !wantAddr && isPointer(v.Type()) {
   818  		v = emitLoad(fn, v)
   819  	}
   820  	return v
   821  }
   822  
   823  // setCallFunc populates the function parts of a CallCommon structure
   824  // (Func, Method, Recv, Args[0]) based on the kind of invocation
   825  // occurring in e.
   826  //
   827  func (b *builder) setCallFunc(fn *Function, e *ast.CallExpr, c *CallCommon) {
   828  	c.pos = e.Lparen
   829  
   830  	// Is this a method call?
   831  	if selector, ok := unparen(e.Fun).(*ast.SelectorExpr); ok {
   832  		sel, ok := fn.Pkg.info.Selections[selector]
   833  		if ok && sel.Kind() == types.MethodVal {
   834  			obj := sel.Obj().(*types.Func)
   835  			recv := recvType(obj)
   836  			wantAddr := isPointer(recv)
   837  			escaping := true
   838  			v := b.receiver(fn, selector.X, wantAddr, escaping, sel)
   839  			if isInterface(recv) {
   840  				// Invoke-mode call.
   841  				c.Value = v
   842  				c.Method = obj
   843  			} else {
   844  				// "Call"-mode call.
   845  				c.Value = fn.Prog.declaredFunc(obj)
   846  				c.Args = append(c.Args, v)
   847  			}
   848  			return
   849  		}
   850  
   851  		// sel.Kind()==MethodExpr indicates T.f() or (*T).f():
   852  		// a statically dispatched call to the method f in the
   853  		// method-set of T or *T.  T may be an interface.
   854  		//
   855  		// e.Fun would evaluate to a concrete method, interface
   856  		// wrapper function, or promotion wrapper.
   857  		//
   858  		// For now, we evaluate it in the usual way.
   859  		//
   860  		// TODO(adonovan): opt: inline expr() here, to make the
   861  		// call static and to avoid generation of wrappers.
   862  		// It's somewhat tricky as it may consume the first
   863  		// actual parameter if the call is "invoke" mode.
   864  		//
   865  		// Examples:
   866  		//  type T struct{}; func (T) f() {}   // "call" mode
   867  		//  type T interface { f() }           // "invoke" mode
   868  		//
   869  		//  type S struct{ T }
   870  		//
   871  		//  var s S
   872  		//  S.f(s)
   873  		//  (*S).f(&s)
   874  		//
   875  		// Suggested approach:
   876  		// - consume the first actual parameter expression
   877  		//   and build it with b.expr().
   878  		// - apply implicit field selections.
   879  		// - use MethodVal logic to populate fields of c.
   880  	}
   881  
   882  	// Evaluate the function operand in the usual way.
   883  	c.Value = b.expr(fn, e.Fun)
   884  }
   885  
   886  // emitCallArgs emits to f code for the actual parameters of call e to
   887  // a (possibly built-in) function of effective type sig.
   888  // The argument values are appended to args, which is then returned.
   889  //
   890  func (b *builder) emitCallArgs(fn *Function, sig *types.Signature, e *ast.CallExpr, args []Value) []Value {
   891  	// f(x, y, z...): pass slice z straight through.
   892  	if e.Ellipsis != 0 {
   893  		for i, arg := range e.Args {
   894  			v := emitConv(fn, b.expr(fn, arg), sig.Params().At(i).Type())
   895  			args = append(args, v)
   896  		}
   897  		return args
   898  	}
   899  
   900  	offset := len(args) // 1 if call has receiver, 0 otherwise
   901  
   902  	// Evaluate actual parameter expressions.
   903  	//
   904  	// If this is a chained call of the form f(g()) where g has
   905  	// multiple return values (MRV), they are flattened out into
   906  	// args; a suffix of them may end up in a varargs slice.
   907  	for _, arg := range e.Args {
   908  		v := b.expr(fn, arg)
   909  		if ttuple, ok := v.Type().(*types.Tuple); ok { // MRV chain
   910  			for i, n := 0, ttuple.Len(); i < n; i++ {
   911  				args = append(args, emitExtract(fn, v, i))
   912  			}
   913  		} else {
   914  			args = append(args, v)
   915  		}
   916  	}
   917  
   918  	// Actual->formal assignability conversions for normal parameters.
   919  	np := sig.Params().Len() // number of normal parameters
   920  	if sig.Variadic() {
   921  		np--
   922  	}
   923  	for i := 0; i < np; i++ {
   924  		args[offset+i] = emitConv(fn, args[offset+i], sig.Params().At(i).Type())
   925  	}
   926  
   927  	// Actual->formal assignability conversions for variadic parameter,
   928  	// and construction of slice.
   929  	if sig.Variadic() {
   930  		varargs := args[offset+np:]
   931  		st := sig.Params().At(np).Type().(*types.Slice)
   932  		vt := st.Elem()
   933  		if len(varargs) == 0 {
   934  			args = append(args, nilConst(st))
   935  		} else {
   936  			// Replace a suffix of args with a slice containing it.
   937  			at := types.NewArray(vt, int64(len(varargs)))
   938  			a := emitNew(fn, at, token.NoPos)
   939  			a.setPos(e.Rparen)
   940  			a.Comment = "varargs"
   941  			for i, arg := range varargs {
   942  				iaddr := &IndexAddr{
   943  					X:     a,
   944  					Index: intConst(int64(i)),
   945  				}
   946  				iaddr.setType(types.NewPointer(vt))
   947  				fn.emit(iaddr)
   948  				emitStore(fn, iaddr, arg, arg.Pos())
   949  			}
   950  			s := &Slice{X: a}
   951  			s.setType(st)
   952  			args[offset+np] = fn.emit(s)
   953  			args = args[:offset+np+1]
   954  		}
   955  	}
   956  	return args
   957  }
   958  
   959  // setCall emits to fn code to evaluate all the parameters of a function
   960  // call e, and populates *c with those values.
   961  //
   962  func (b *builder) setCall(fn *Function, e *ast.CallExpr, c *CallCommon) {
   963  	// First deal with the f(...) part and optional receiver.
   964  	b.setCallFunc(fn, e, c)
   965  
   966  	// Then append the other actual parameters.
   967  	sig, _ := fn.Pkg.typeOf(e.Fun).Underlying().(*types.Signature)
   968  	if sig == nil {
   969  		panic(fmt.Sprintf("no signature for call of %s", e.Fun))
   970  	}
   971  	c.Args = b.emitCallArgs(fn, sig, e, c.Args)
   972  }
   973  
   974  // assignOp emits to fn code to perform loc += incr or loc -= incr.
   975  func (b *builder) assignOp(fn *Function, loc lvalue, incr Value, op token.Token) {
   976  	oldv := loc.load(fn)
   977  	loc.store(fn, emitArith(fn, op, oldv, emitConv(fn, incr, oldv.Type()), loc.typ(), token.NoPos))
   978  }
   979  
   980  // localValueSpec emits to fn code to define all of the vars in the
   981  // function-local ValueSpec, spec.
   982  //
   983  func (b *builder) localValueSpec(fn *Function, spec *ast.ValueSpec) {
   984  	switch {
   985  	case len(spec.Values) == len(spec.Names):
   986  		// e.g. var x, y = 0, 1
   987  		// 1:1 assignment
   988  		for i, id := range spec.Names {
   989  			if !isBlankIdent(id) {
   990  				fn.addLocalForIdent(id)
   991  			}
   992  			lval := b.addr(fn, id, false) // non-escaping
   993  			b.assign(fn, lval, spec.Values[i], true, nil)
   994  		}
   995  
   996  	case len(spec.Values) == 0:
   997  		// e.g. var x, y int
   998  		// Locals are implicitly zero-initialized.
   999  		for _, id := range spec.Names {
  1000  			if !isBlankIdent(id) {
  1001  				lhs := fn.addLocalForIdent(id)
  1002  				if fn.debugInfo() {
  1003  					emitDebugRef(fn, id, lhs, true)
  1004  				}
  1005  			}
  1006  		}
  1007  
  1008  	default:
  1009  		// e.g. var x, y = pos()
  1010  		tuple := b.exprN(fn, spec.Values[0])
  1011  		for i, id := range spec.Names {
  1012  			if !isBlankIdent(id) {
  1013  				fn.addLocalForIdent(id)
  1014  				lhs := b.addr(fn, id, false) // non-escaping
  1015  				lhs.store(fn, emitExtract(fn, tuple, i))
  1016  			}
  1017  		}
  1018  	}
  1019  }
  1020  
  1021  // assignStmt emits code to fn for a parallel assignment of rhss to lhss.
  1022  // isDef is true if this is a short variable declaration (:=).
  1023  //
  1024  // Note the similarity with localValueSpec.
  1025  //
  1026  func (b *builder) assignStmt(fn *Function, lhss, rhss []ast.Expr, isDef bool) {
  1027  	// Side effects of all LHSs and RHSs must occur in left-to-right order.
  1028  	lvals := make([]lvalue, len(lhss))
  1029  	isZero := make([]bool, len(lhss))
  1030  	for i, lhs := range lhss {
  1031  		var lval lvalue = blank{}
  1032  		if !isBlankIdent(lhs) {
  1033  			if isDef {
  1034  				if obj := fn.Pkg.info.Defs[lhs.(*ast.Ident)]; obj != nil {
  1035  					fn.addNamedLocal(obj)
  1036  					isZero[i] = true
  1037  				}
  1038  			}
  1039  			lval = b.addr(fn, lhs, false) // non-escaping
  1040  		}
  1041  		lvals[i] = lval
  1042  	}
  1043  	if len(lhss) == len(rhss) {
  1044  		// Simple assignment:   x     = f()        (!isDef)
  1045  		// Parallel assignment: x, y  = f(), g()   (!isDef)
  1046  		// or short var decl:   x, y := f(), g()   (isDef)
  1047  		//
  1048  		// In all cases, the RHSs may refer to the LHSs,
  1049  		// so we need a storebuf.
  1050  		var sb storebuf
  1051  		for i := range rhss {
  1052  			b.assign(fn, lvals[i], rhss[i], isZero[i], &sb)
  1053  		}
  1054  		sb.emit(fn)
  1055  	} else {
  1056  		// e.g. x, y = pos()
  1057  		tuple := b.exprN(fn, rhss[0])
  1058  		emitDebugRef(fn, rhss[0], tuple, false)
  1059  		for i, lval := range lvals {
  1060  			lval.store(fn, emitExtract(fn, tuple, i))
  1061  		}
  1062  	}
  1063  }
  1064  
  1065  // arrayLen returns the length of the array whose composite literal elements are elts.
  1066  func (b *builder) arrayLen(fn *Function, elts []ast.Expr) int64 {
  1067  	var max int64 = -1
  1068  	var i int64 = -1
  1069  	for _, e := range elts {
  1070  		if kv, ok := e.(*ast.KeyValueExpr); ok {
  1071  			i = b.expr(fn, kv.Key).(*Const).Int64()
  1072  		} else {
  1073  			i++
  1074  		}
  1075  		if i > max {
  1076  			max = i
  1077  		}
  1078  	}
  1079  	return max + 1
  1080  }
  1081  
  1082  // compLit emits to fn code to initialize a composite literal e at
  1083  // address addr with type typ.
  1084  //
  1085  // Nested composite literals are recursively initialized in place
  1086  // where possible. If isZero is true, compLit assumes that addr
  1087  // holds the zero value for typ.
  1088  //
  1089  // Because the elements of a composite literal may refer to the
  1090  // variables being updated, as in the second line below,
  1091  //	x := T{a: 1}
  1092  //	x = T{a: x.a}
  1093  // all the reads must occur before all the writes.  Thus all stores to
  1094  // loc are emitted to the storebuf sb for later execution.
  1095  //
  1096  // A CompositeLit may have pointer type only in the recursive (nested)
  1097  // case when the type name is implicit.  e.g. in []*T{{}}, the inner
  1098  // literal has type *T behaves like &T{}.
  1099  // In that case, addr must hold a T, not a *T.
  1100  //
  1101  func (b *builder) compLit(fn *Function, addr Value, e *ast.CompositeLit, isZero bool, sb *storebuf) {
  1102  	typ := deref(fn.Pkg.typeOf(e))
  1103  	switch t := typ.Underlying().(type) {
  1104  	case *types.Struct:
  1105  		if !isZero && len(e.Elts) != t.NumFields() {
  1106  			// memclear
  1107  			sb.store(&address{addr, e.Lbrace, nil},
  1108  				zeroValue(fn, deref(addr.Type())))
  1109  			isZero = true
  1110  		}
  1111  		for i, e := range e.Elts {
  1112  			fieldIndex := i
  1113  			pos := e.Pos()
  1114  			if kv, ok := e.(*ast.KeyValueExpr); ok {
  1115  				fname := kv.Key.(*ast.Ident).Name
  1116  				for i, n := 0, t.NumFields(); i < n; i++ {
  1117  					sf := t.Field(i)
  1118  					if sf.Name() == fname {
  1119  						fieldIndex = i
  1120  						pos = kv.Colon
  1121  						e = kv.Value
  1122  						break
  1123  					}
  1124  				}
  1125  			}
  1126  			sf := t.Field(fieldIndex)
  1127  			faddr := &FieldAddr{
  1128  				X:     addr,
  1129  				Field: fieldIndex,
  1130  			}
  1131  			faddr.setType(types.NewPointer(sf.Type()))
  1132  			fn.emit(faddr)
  1133  			b.assign(fn, &address{addr: faddr, pos: pos, expr: e}, e, isZero, sb)
  1134  		}
  1135  
  1136  	case *types.Array, *types.Slice:
  1137  		var at *types.Array
  1138  		var array Value
  1139  		switch t := t.(type) {
  1140  		case *types.Slice:
  1141  			at = types.NewArray(t.Elem(), b.arrayLen(fn, e.Elts))
  1142  			alloc := emitNew(fn, at, e.Lbrace)
  1143  			alloc.Comment = "slicelit"
  1144  			array = alloc
  1145  		case *types.Array:
  1146  			at = t
  1147  			array = addr
  1148  
  1149  			if !isZero && int64(len(e.Elts)) != at.Len() {
  1150  				// memclear
  1151  				sb.store(&address{array, e.Lbrace, nil},
  1152  					zeroValue(fn, deref(array.Type())))
  1153  			}
  1154  		}
  1155  
  1156  		var idx *Const
  1157  		for _, e := range e.Elts {
  1158  			pos := e.Pos()
  1159  			if kv, ok := e.(*ast.KeyValueExpr); ok {
  1160  				idx = b.expr(fn, kv.Key).(*Const)
  1161  				pos = kv.Colon
  1162  				e = kv.Value
  1163  			} else {
  1164  				var idxval int64
  1165  				if idx != nil {
  1166  					idxval = idx.Int64() + 1
  1167  				}
  1168  				idx = intConst(idxval)
  1169  			}
  1170  			iaddr := &IndexAddr{
  1171  				X:     array,
  1172  				Index: idx,
  1173  			}
  1174  			iaddr.setType(types.NewPointer(at.Elem()))
  1175  			fn.emit(iaddr)
  1176  			if t != at { // slice
  1177  				// backing array is unaliased => storebuf not needed.
  1178  				b.assign(fn, &address{addr: iaddr, pos: pos, expr: e}, e, true, nil)
  1179  			} else {
  1180  				b.assign(fn, &address{addr: iaddr, pos: pos, expr: e}, e, true, sb)
  1181  			}
  1182  		}
  1183  
  1184  		if t != at { // slice
  1185  			s := &Slice{X: array}
  1186  			s.setPos(e.Lbrace)
  1187  			s.setType(typ)
  1188  			sb.store(&address{addr: addr, pos: e.Lbrace, expr: e}, fn.emit(s))
  1189  		}
  1190  
  1191  	case *types.Map:
  1192  		m := &MakeMap{Reserve: intConst(int64(len(e.Elts)))}
  1193  		m.setPos(e.Lbrace)
  1194  		m.setType(typ)
  1195  		fn.emit(m)
  1196  		for _, e := range e.Elts {
  1197  			e := e.(*ast.KeyValueExpr)
  1198  
  1199  			// If a key expression in a map literal is  itself a
  1200  			// composite literal, the type may be omitted.
  1201  			// For example:
  1202  			//	map[*struct{}]bool{{}: true}
  1203  			// An &-operation may be implied:
  1204  			//	map[*struct{}]bool{&struct{}{}: true}
  1205  			var key Value
  1206  			if _, ok := unparen(e.Key).(*ast.CompositeLit); ok && isPointer(t.Key()) {
  1207  				// A CompositeLit never evaluates to a pointer,
  1208  				// so if the type of the location is a pointer,
  1209  				// an &-operation is implied.
  1210  				key = b.addr(fn, e.Key, true).address(fn)
  1211  			} else {
  1212  				key = b.expr(fn, e.Key)
  1213  			}
  1214  
  1215  			loc := element{
  1216  				m:   m,
  1217  				k:   emitConv(fn, key, t.Key()),
  1218  				t:   t.Elem(),
  1219  				pos: e.Colon,
  1220  			}
  1221  
  1222  			// We call assign() only because it takes care
  1223  			// of any &-operation required in the recursive
  1224  			// case, e.g.,
  1225  			// map[int]*struct{}{0: {}} implies &struct{}{}.
  1226  			// In-place update is of course impossible,
  1227  			// and no storebuf is needed.
  1228  			b.assign(fn, &loc, e.Value, true, nil)
  1229  		}
  1230  		sb.store(&address{addr: addr, pos: e.Lbrace, expr: e}, m)
  1231  
  1232  	default:
  1233  		panic("unexpected CompositeLit type: " + t.String())
  1234  	}
  1235  }
  1236  
  1237  // switchStmt emits to fn code for the switch statement s, optionally
  1238  // labelled by label.
  1239  //
  1240  func (b *builder) switchStmt(fn *Function, s *ast.SwitchStmt, label *lblock) {
  1241  	// We treat SwitchStmt like a sequential if-else chain.
  1242  	// Multiway dispatch can be recovered later by ssautil.Switches()
  1243  	// to those cases that are free of side effects.
  1244  	if s.Init != nil {
  1245  		b.stmt(fn, s.Init)
  1246  	}
  1247  	var tag Value = vTrue
  1248  	if s.Tag != nil {
  1249  		tag = b.expr(fn, s.Tag)
  1250  	}
  1251  	done := fn.newBasicBlock("switch.done")
  1252  	if label != nil {
  1253  		label._break = done
  1254  	}
  1255  	// We pull the default case (if present) down to the end.
  1256  	// But each fallthrough label must point to the next
  1257  	// body block in source order, so we preallocate a
  1258  	// body block (fallthru) for the next case.
  1259  	// Unfortunately this makes for a confusing block order.
  1260  	var dfltBody *[]ast.Stmt
  1261  	var dfltFallthrough *BasicBlock
  1262  	var fallthru, dfltBlock *BasicBlock
  1263  	ncases := len(s.Body.List)
  1264  	for i, clause := range s.Body.List {
  1265  		body := fallthru
  1266  		if body == nil {
  1267  			body = fn.newBasicBlock("switch.body") // first case only
  1268  		}
  1269  
  1270  		// Preallocate body block for the next case.
  1271  		fallthru = done
  1272  		if i+1 < ncases {
  1273  			fallthru = fn.newBasicBlock("switch.body")
  1274  		}
  1275  
  1276  		cc := clause.(*ast.CaseClause)
  1277  		if cc.List == nil {
  1278  			// Default case.
  1279  			dfltBody = &cc.Body
  1280  			dfltFallthrough = fallthru
  1281  			dfltBlock = body
  1282  			continue
  1283  		}
  1284  
  1285  		var nextCond *BasicBlock
  1286  		for _, cond := range cc.List {
  1287  			nextCond = fn.newBasicBlock("switch.next")
  1288  			// TODO(adonovan): opt: when tag==vTrue, we'd
  1289  			// get better code if we use b.cond(cond)
  1290  			// instead of BinOp(EQL, tag, b.expr(cond))
  1291  			// followed by If.  Don't forget conversions
  1292  			// though.
  1293  			cond := emitCompare(fn, token.EQL, tag, b.expr(fn, cond), token.NoPos)
  1294  			emitIf(fn, cond, body, nextCond)
  1295  			fn.currentBlock = nextCond
  1296  		}
  1297  		fn.currentBlock = body
  1298  		fn.targets = &targets{
  1299  			tail:         fn.targets,
  1300  			_break:       done,
  1301  			_fallthrough: fallthru,
  1302  		}
  1303  		b.stmtList(fn, cc.Body)
  1304  		fn.targets = fn.targets.tail
  1305  		emitJump(fn, done)
  1306  		fn.currentBlock = nextCond
  1307  	}
  1308  	if dfltBlock != nil {
  1309  		emitJump(fn, dfltBlock)
  1310  		fn.currentBlock = dfltBlock
  1311  		fn.targets = &targets{
  1312  			tail:         fn.targets,
  1313  			_break:       done,
  1314  			_fallthrough: dfltFallthrough,
  1315  		}
  1316  		b.stmtList(fn, *dfltBody)
  1317  		fn.targets = fn.targets.tail
  1318  	}
  1319  	emitJump(fn, done)
  1320  	fn.currentBlock = done
  1321  }
  1322  
  1323  // typeSwitchStmt emits to fn code for the type switch statement s, optionally
  1324  // labelled by label.
  1325  //
  1326  func (b *builder) typeSwitchStmt(fn *Function, s *ast.TypeSwitchStmt, label *lblock) {
  1327  	// We treat TypeSwitchStmt like a sequential if-else chain.
  1328  	// Multiway dispatch can be recovered later by ssautil.Switches().
  1329  
  1330  	// Typeswitch lowering:
  1331  	//
  1332  	// var x X
  1333  	// switch y := x.(type) {
  1334  	// case T1, T2: S1                  // >1 	(y := x)
  1335  	// case nil:    SN                  // nil 	(y := x)
  1336  	// default:     SD                  // 0 types 	(y := x)
  1337  	// case T3:     S3                  // 1 type 	(y := x.(T3))
  1338  	// }
  1339  	//
  1340  	//      ...s.Init...
  1341  	// 	x := eval x
  1342  	// .caseT1:
  1343  	// 	t1, ok1 := typeswitch,ok x <T1>
  1344  	// 	if ok1 then goto S1 else goto .caseT2
  1345  	// .caseT2:
  1346  	// 	t2, ok2 := typeswitch,ok x <T2>
  1347  	// 	if ok2 then goto S1 else goto .caseNil
  1348  	// .S1:
  1349  	//      y := x
  1350  	// 	...S1...
  1351  	// 	goto done
  1352  	// .caseNil:
  1353  	// 	if t2, ok2 := typeswitch,ok x <T2>
  1354  	// 	if x == nil then goto SN else goto .caseT3
  1355  	// .SN:
  1356  	//      y := x
  1357  	// 	...SN...
  1358  	// 	goto done
  1359  	// .caseT3:
  1360  	// 	t3, ok3 := typeswitch,ok x <T3>
  1361  	// 	if ok3 then goto S3 else goto default
  1362  	// .S3:
  1363  	//      y := t3
  1364  	// 	...S3...
  1365  	// 	goto done
  1366  	// .default:
  1367  	//      y := x
  1368  	// 	...SD...
  1369  	// 	goto done
  1370  	// .done:
  1371  
  1372  	if s.Init != nil {
  1373  		b.stmt(fn, s.Init)
  1374  	}
  1375  
  1376  	var x Value
  1377  	switch ass := s.Assign.(type) {
  1378  	case *ast.ExprStmt: // x.(type)
  1379  		x = b.expr(fn, unparen(ass.X).(*ast.TypeAssertExpr).X)
  1380  	case *ast.AssignStmt: // y := x.(type)
  1381  		x = b.expr(fn, unparen(ass.Rhs[0]).(*ast.TypeAssertExpr).X)
  1382  	}
  1383  
  1384  	done := fn.newBasicBlock("typeswitch.done")
  1385  	if label != nil {
  1386  		label._break = done
  1387  	}
  1388  	var default_ *ast.CaseClause
  1389  	for _, clause := range s.Body.List {
  1390  		cc := clause.(*ast.CaseClause)
  1391  		if cc.List == nil {
  1392  			default_ = cc
  1393  			continue
  1394  		}
  1395  		body := fn.newBasicBlock("typeswitch.body")
  1396  		var next *BasicBlock
  1397  		var casetype types.Type
  1398  		var ti Value // ti, ok := typeassert,ok x <Ti>
  1399  		for _, cond := range cc.List {
  1400  			next = fn.newBasicBlock("typeswitch.next")
  1401  			casetype = fn.Pkg.typeOf(cond)
  1402  			var condv Value
  1403  			if casetype == tUntypedNil {
  1404  				condv = emitCompare(fn, token.EQL, x, nilConst(x.Type()), token.NoPos)
  1405  				ti = x
  1406  			} else {
  1407  				yok := emitTypeTest(fn, x, casetype, cc.Case)
  1408  				ti = emitExtract(fn, yok, 0)
  1409  				condv = emitExtract(fn, yok, 1)
  1410  			}
  1411  			emitIf(fn, condv, body, next)
  1412  			fn.currentBlock = next
  1413  		}
  1414  		if len(cc.List) != 1 {
  1415  			ti = x
  1416  		}
  1417  		fn.currentBlock = body
  1418  		b.typeCaseBody(fn, cc, ti, done)
  1419  		fn.currentBlock = next
  1420  	}
  1421  	if default_ != nil {
  1422  		b.typeCaseBody(fn, default_, x, done)
  1423  	} else {
  1424  		emitJump(fn, done)
  1425  	}
  1426  	fn.currentBlock = done
  1427  }
  1428  
  1429  func (b *builder) typeCaseBody(fn *Function, cc *ast.CaseClause, x Value, done *BasicBlock) {
  1430  	if obj := fn.Pkg.info.Implicits[cc]; obj != nil {
  1431  		// In a switch y := x.(type), each case clause
  1432  		// implicitly declares a distinct object y.
  1433  		// In a single-type case, y has that type.
  1434  		// In multi-type cases, 'case nil' and default,
  1435  		// y has the same type as the interface operand.
  1436  		emitStore(fn, fn.addNamedLocal(obj), x, obj.Pos())
  1437  	}
  1438  	fn.targets = &targets{
  1439  		tail:   fn.targets,
  1440  		_break: done,
  1441  	}
  1442  	b.stmtList(fn, cc.Body)
  1443  	fn.targets = fn.targets.tail
  1444  	emitJump(fn, done)
  1445  }
  1446  
  1447  // selectStmt emits to fn code for the select statement s, optionally
  1448  // labelled by label.
  1449  //
  1450  func (b *builder) selectStmt(fn *Function, s *ast.SelectStmt, label *lblock) {
  1451  	// A blocking select of a single case degenerates to a
  1452  	// simple send or receive.
  1453  	// TODO(adonovan): opt: is this optimization worth its weight?
  1454  	if len(s.Body.List) == 1 {
  1455  		clause := s.Body.List[0].(*ast.CommClause)
  1456  		if clause.Comm != nil {
  1457  			b.stmt(fn, clause.Comm)
  1458  			done := fn.newBasicBlock("select.done")
  1459  			if label != nil {
  1460  				label._break = done
  1461  			}
  1462  			fn.targets = &targets{
  1463  				tail:   fn.targets,
  1464  				_break: done,
  1465  			}
  1466  			b.stmtList(fn, clause.Body)
  1467  			fn.targets = fn.targets.tail
  1468  			emitJump(fn, done)
  1469  			fn.currentBlock = done
  1470  			return
  1471  		}
  1472  	}
  1473  
  1474  	// First evaluate all channels in all cases, and find
  1475  	// the directions of each state.
  1476  	var states []*SelectState
  1477  	blocking := true
  1478  	debugInfo := fn.debugInfo()
  1479  	for _, clause := range s.Body.List {
  1480  		var st *SelectState
  1481  		switch comm := clause.(*ast.CommClause).Comm.(type) {
  1482  		case nil: // default case
  1483  			blocking = false
  1484  			continue
  1485  
  1486  		case *ast.SendStmt: // ch<- i
  1487  			ch := b.expr(fn, comm.Chan)
  1488  			st = &SelectState{
  1489  				Dir:  types.SendOnly,
  1490  				Chan: ch,
  1491  				Send: emitConv(fn, b.expr(fn, comm.Value),
  1492  					ch.Type().Underlying().(*types.Chan).Elem()),
  1493  				Pos: comm.Arrow,
  1494  			}
  1495  			if debugInfo {
  1496  				st.DebugNode = comm
  1497  			}
  1498  
  1499  		case *ast.AssignStmt: // x := <-ch
  1500  			recv := unparen(comm.Rhs[0]).(*ast.UnaryExpr)
  1501  			st = &SelectState{
  1502  				Dir:  types.RecvOnly,
  1503  				Chan: b.expr(fn, recv.X),
  1504  				Pos:  recv.OpPos,
  1505  			}
  1506  			if debugInfo {
  1507  				st.DebugNode = recv
  1508  			}
  1509  
  1510  		case *ast.ExprStmt: // <-ch
  1511  			recv := unparen(comm.X).(*ast.UnaryExpr)
  1512  			st = &SelectState{
  1513  				Dir:  types.RecvOnly,
  1514  				Chan: b.expr(fn, recv.X),
  1515  				Pos:  recv.OpPos,
  1516  			}
  1517  			if debugInfo {
  1518  				st.DebugNode = recv
  1519  			}
  1520  		}
  1521  		states = append(states, st)
  1522  	}
  1523  
  1524  	// We dispatch on the (fair) result of Select using a
  1525  	// sequential if-else chain, in effect:
  1526  	//
  1527  	// idx, recvOk, r0...r_n-1 := select(...)
  1528  	// if idx == 0 {  // receive on channel 0  (first receive => r0)
  1529  	//     x, ok := r0, recvOk
  1530  	//     ...state0...
  1531  	// } else if v == 1 {   // send on channel 1
  1532  	//     ...state1...
  1533  	// } else {
  1534  	//     ...default...
  1535  	// }
  1536  	sel := &Select{
  1537  		States:   states,
  1538  		Blocking: blocking,
  1539  	}
  1540  	sel.setPos(s.Select)
  1541  	var vars []*types.Var
  1542  	vars = append(vars, varIndex, varOk)
  1543  	for _, st := range states {
  1544  		if st.Dir == types.RecvOnly {
  1545  			tElem := st.Chan.Type().Underlying().(*types.Chan).Elem()
  1546  			vars = append(vars, anonVar(tElem))
  1547  		}
  1548  	}
  1549  	sel.setType(types.NewTuple(vars...))
  1550  
  1551  	fn.emit(sel)
  1552  	idx := emitExtract(fn, sel, 0)
  1553  
  1554  	done := fn.newBasicBlock("select.done")
  1555  	if label != nil {
  1556  		label._break = done
  1557  	}
  1558  
  1559  	var defaultBody *[]ast.Stmt
  1560  	state := 0
  1561  	r := 2 // index in 'sel' tuple of value; increments if st.Dir==RECV
  1562  	for _, cc := range s.Body.List {
  1563  		clause := cc.(*ast.CommClause)
  1564  		if clause.Comm == nil {
  1565  			defaultBody = &clause.Body
  1566  			continue
  1567  		}
  1568  		body := fn.newBasicBlock("select.body")
  1569  		next := fn.newBasicBlock("select.next")
  1570  		emitIf(fn, emitCompare(fn, token.EQL, idx, intConst(int64(state)), token.NoPos), body, next)
  1571  		fn.currentBlock = body
  1572  		fn.targets = &targets{
  1573  			tail:   fn.targets,
  1574  			_break: done,
  1575  		}
  1576  		switch comm := clause.Comm.(type) {
  1577  		case *ast.ExprStmt: // <-ch
  1578  			if debugInfo {
  1579  				v := emitExtract(fn, sel, r)
  1580  				emitDebugRef(fn, states[state].DebugNode.(ast.Expr), v, false)
  1581  			}
  1582  			r++
  1583  
  1584  		case *ast.AssignStmt: // x := <-states[state].Chan
  1585  			if comm.Tok == token.DEFINE {
  1586  				fn.addLocalForIdent(comm.Lhs[0].(*ast.Ident))
  1587  			}
  1588  			x := b.addr(fn, comm.Lhs[0], false) // non-escaping
  1589  			v := emitExtract(fn, sel, r)
  1590  			if debugInfo {
  1591  				emitDebugRef(fn, states[state].DebugNode.(ast.Expr), v, false)
  1592  			}
  1593  			x.store(fn, v)
  1594  
  1595  			if len(comm.Lhs) == 2 { // x, ok := ...
  1596  				if comm.Tok == token.DEFINE {
  1597  					fn.addLocalForIdent(comm.Lhs[1].(*ast.Ident))
  1598  				}
  1599  				ok := b.addr(fn, comm.Lhs[1], false) // non-escaping
  1600  				ok.store(fn, emitExtract(fn, sel, 1))
  1601  			}
  1602  			r++
  1603  		}
  1604  		b.stmtList(fn, clause.Body)
  1605  		fn.targets = fn.targets.tail
  1606  		emitJump(fn, done)
  1607  		fn.currentBlock = next
  1608  		state++
  1609  	}
  1610  	if defaultBody != nil {
  1611  		fn.targets = &targets{
  1612  			tail:   fn.targets,
  1613  			_break: done,
  1614  		}
  1615  		b.stmtList(fn, *defaultBody)
  1616  		fn.targets = fn.targets.tail
  1617  	} else {
  1618  		// A blocking select must match some case.
  1619  		// (This should really be a runtime.errorString, not a string.)
  1620  		fn.emit(&Panic{
  1621  			X: emitConv(fn, stringConst("blocking select matched no case"), tEface),
  1622  		})
  1623  		fn.currentBlock = fn.newBasicBlock("unreachable")
  1624  	}
  1625  	emitJump(fn, done)
  1626  	fn.currentBlock = done
  1627  }
  1628  
  1629  // forStmt emits to fn code for the for statement s, optionally
  1630  // labelled by label.
  1631  //
  1632  func (b *builder) forStmt(fn *Function, s *ast.ForStmt, label *lblock) {
  1633  	//	...init...
  1634  	//      jump loop
  1635  	// loop:
  1636  	//      if cond goto body else done
  1637  	// body:
  1638  	//      ...body...
  1639  	//      jump post
  1640  	// post:				 (target of continue)
  1641  	//      ...post...
  1642  	//      jump loop
  1643  	// done:                                 (target of break)
  1644  	if s.Init != nil {
  1645  		b.stmt(fn, s.Init)
  1646  	}
  1647  	body := fn.newBasicBlock("for.body")
  1648  	done := fn.newBasicBlock("for.done") // target of 'break'
  1649  	loop := body                         // target of back-edge
  1650  	if s.Cond != nil {
  1651  		loop = fn.newBasicBlock("for.loop")
  1652  	}
  1653  	cont := loop // target of 'continue'
  1654  	if s.Post != nil {
  1655  		cont = fn.newBasicBlock("for.post")
  1656  	}
  1657  	if label != nil {
  1658  		label._break = done
  1659  		label._continue = cont
  1660  	}
  1661  	emitJump(fn, loop)
  1662  	fn.currentBlock = loop
  1663  	if loop != body {
  1664  		b.cond(fn, s.Cond, body, done)
  1665  		fn.currentBlock = body
  1666  	}
  1667  	fn.targets = &targets{
  1668  		tail:      fn.targets,
  1669  		_break:    done,
  1670  		_continue: cont,
  1671  	}
  1672  	b.stmt(fn, s.Body)
  1673  	fn.targets = fn.targets.tail
  1674  	emitJump(fn, cont)
  1675  
  1676  	if s.Post != nil {
  1677  		fn.currentBlock = cont
  1678  		b.stmt(fn, s.Post)
  1679  		emitJump(fn, loop) // back-edge
  1680  	}
  1681  	fn.currentBlock = done
  1682  }
  1683  
  1684  // rangeIndexed emits to fn the header for an integer-indexed loop
  1685  // over array, *array or slice value x.
  1686  // The v result is defined only if tv is non-nil.
  1687  // forPos is the position of the "for" token.
  1688  //
  1689  func (b *builder) rangeIndexed(fn *Function, x Value, tv types.Type, pos token.Pos) (k, v Value, loop, done *BasicBlock) {
  1690  	//
  1691  	//      length = len(x)
  1692  	//      index = -1
  1693  	// loop:                                   (target of continue)
  1694  	//      index++
  1695  	// 	if index < length goto body else done
  1696  	// body:
  1697  	//      k = index
  1698  	//      v = x[index]
  1699  	//      ...body...
  1700  	// 	jump loop
  1701  	// done:                                   (target of break)
  1702  
  1703  	// Determine number of iterations.
  1704  	var length Value
  1705  	if arr, ok := deref(x.Type()).Underlying().(*types.Array); ok {
  1706  		// For array or *array, the number of iterations is
  1707  		// known statically thanks to the type.  We avoid a
  1708  		// data dependence upon x, permitting later dead-code
  1709  		// elimination if x is pure, static unrolling, etc.
  1710  		// Ranging over a nil *array may have >0 iterations.
  1711  		// We still generate code for x, in case it has effects.
  1712  		length = intConst(arr.Len())
  1713  	} else {
  1714  		// length = len(x).
  1715  		var c Call
  1716  		c.Call.Value = makeLen(x.Type())
  1717  		c.Call.Args = []Value{x}
  1718  		c.setType(tInt)
  1719  		length = fn.emit(&c)
  1720  	}
  1721  
  1722  	index := fn.addLocal(tInt, token.NoPos)
  1723  	emitStore(fn, index, intConst(-1), pos)
  1724  
  1725  	loop = fn.newBasicBlock("rangeindex.loop")
  1726  	emitJump(fn, loop)
  1727  	fn.currentBlock = loop
  1728  
  1729  	incr := &BinOp{
  1730  		Op: token.ADD,
  1731  		X:  emitLoad(fn, index),
  1732  		Y:  vOne,
  1733  	}
  1734  	incr.setType(tInt)
  1735  	emitStore(fn, index, fn.emit(incr), pos)
  1736  
  1737  	body := fn.newBasicBlock("rangeindex.body")
  1738  	done = fn.newBasicBlock("rangeindex.done")
  1739  	emitIf(fn, emitCompare(fn, token.LSS, incr, length, token.NoPos), body, done)
  1740  	fn.currentBlock = body
  1741  
  1742  	k = emitLoad(fn, index)
  1743  	if tv != nil {
  1744  		switch t := x.Type().Underlying().(type) {
  1745  		case *types.Array:
  1746  			instr := &Index{
  1747  				X:     x,
  1748  				Index: k,
  1749  			}
  1750  			instr.setType(t.Elem())
  1751  			v = fn.emit(instr)
  1752  
  1753  		case *types.Pointer: // *array
  1754  			instr := &IndexAddr{
  1755  				X:     x,
  1756  				Index: k,
  1757  			}
  1758  			instr.setType(types.NewPointer(t.Elem().Underlying().(*types.Array).Elem()))
  1759  			v = emitLoad(fn, fn.emit(instr))
  1760  
  1761  		case *types.Slice:
  1762  			instr := &IndexAddr{
  1763  				X:     x,
  1764  				Index: k,
  1765  			}
  1766  			instr.setType(types.NewPointer(t.Elem()))
  1767  			v = emitLoad(fn, fn.emit(instr))
  1768  
  1769  		default:
  1770  			panic("rangeIndexed x:" + t.String())
  1771  		}
  1772  	}
  1773  	return
  1774  }
  1775  
  1776  // rangeIter emits to fn the header for a loop using
  1777  // Range/Next/Extract to iterate over map or string value x.
  1778  // tk and tv are the types of the key/value results k and v, or nil
  1779  // if the respective component is not wanted.
  1780  //
  1781  func (b *builder) rangeIter(fn *Function, x Value, tk, tv types.Type, pos token.Pos) (k, v Value, loop, done *BasicBlock) {
  1782  	//
  1783  	//	it = range x
  1784  	// loop:                                   (target of continue)
  1785  	//	okv = next it                      (ok, key, value)
  1786  	//  	ok = extract okv #0
  1787  	// 	if ok goto body else done
  1788  	// body:
  1789  	// 	k = extract okv #1
  1790  	// 	v = extract okv #2
  1791  	//      ...body...
  1792  	// 	jump loop
  1793  	// done:                                   (target of break)
  1794  	//
  1795  
  1796  	if tk == nil {
  1797  		tk = tInvalid
  1798  	}
  1799  	if tv == nil {
  1800  		tv = tInvalid
  1801  	}
  1802  
  1803  	rng := &Range{X: x}
  1804  	rng.setPos(pos)
  1805  	rng.setType(tRangeIter)
  1806  	it := fn.emit(rng)
  1807  
  1808  	loop = fn.newBasicBlock("rangeiter.loop")
  1809  	emitJump(fn, loop)
  1810  	fn.currentBlock = loop
  1811  
  1812  	_, isString := x.Type().Underlying().(*types.Basic)
  1813  
  1814  	okv := &Next{
  1815  		Iter:     it,
  1816  		IsString: isString,
  1817  	}
  1818  	okv.setType(types.NewTuple(
  1819  		varOk,
  1820  		newVar("k", tk),
  1821  		newVar("v", tv),
  1822  	))
  1823  	fn.emit(okv)
  1824  
  1825  	body := fn.newBasicBlock("rangeiter.body")
  1826  	done = fn.newBasicBlock("rangeiter.done")
  1827  	emitIf(fn, emitExtract(fn, okv, 0), body, done)
  1828  	fn.currentBlock = body
  1829  
  1830  	if tk != tInvalid {
  1831  		k = emitExtract(fn, okv, 1)
  1832  	}
  1833  	if tv != tInvalid {
  1834  		v = emitExtract(fn, okv, 2)
  1835  	}
  1836  	return
  1837  }
  1838  
  1839  // rangeChan emits to fn the header for a loop that receives from
  1840  // channel x until it fails.
  1841  // tk is the channel's element type, or nil if the k result is
  1842  // not wanted
  1843  // pos is the position of the '=' or ':=' token.
  1844  //
  1845  func (b *builder) rangeChan(fn *Function, x Value, tk types.Type, pos token.Pos) (k Value, loop, done *BasicBlock) {
  1846  	//
  1847  	// loop:                                   (target of continue)
  1848  	//      ko = <-x                           (key, ok)
  1849  	//      ok = extract ko #1
  1850  	//      if ok goto body else done
  1851  	// body:
  1852  	//      k = extract ko #0
  1853  	//      ...
  1854  	//      goto loop
  1855  	// done:                                   (target of break)
  1856  
  1857  	loop = fn.newBasicBlock("rangechan.loop")
  1858  	emitJump(fn, loop)
  1859  	fn.currentBlock = loop
  1860  	recv := &UnOp{
  1861  		Op:      token.ARROW,
  1862  		X:       x,
  1863  		CommaOk: true,
  1864  	}
  1865  	recv.setPos(pos)
  1866  	recv.setType(types.NewTuple(
  1867  		newVar("k", x.Type().Underlying().(*types.Chan).Elem()),
  1868  		varOk,
  1869  	))
  1870  	ko := fn.emit(recv)
  1871  	body := fn.newBasicBlock("rangechan.body")
  1872  	done = fn.newBasicBlock("rangechan.done")
  1873  	emitIf(fn, emitExtract(fn, ko, 1), body, done)
  1874  	fn.currentBlock = body
  1875  	if tk != nil {
  1876  		k = emitExtract(fn, ko, 0)
  1877  	}
  1878  	return
  1879  }
  1880  
  1881  // rangeStmt emits to fn code for the range statement s, optionally
  1882  // labelled by label.
  1883  //
  1884  func (b *builder) rangeStmt(fn *Function, s *ast.RangeStmt, label *lblock) {
  1885  	var tk, tv types.Type
  1886  	if s.Key != nil && !isBlankIdent(s.Key) {
  1887  		tk = fn.Pkg.typeOf(s.Key)
  1888  	}
  1889  	if s.Value != nil && !isBlankIdent(s.Value) {
  1890  		tv = fn.Pkg.typeOf(s.Value)
  1891  	}
  1892  
  1893  	// If iteration variables are defined (:=), this
  1894  	// occurs once outside the loop.
  1895  	//
  1896  	// Unlike a short variable declaration, a RangeStmt
  1897  	// using := never redeclares an existing variable; it
  1898  	// always creates a new one.
  1899  	if s.Tok == token.DEFINE {
  1900  		if tk != nil {
  1901  			fn.addLocalForIdent(s.Key.(*ast.Ident))
  1902  		}
  1903  		if tv != nil {
  1904  			fn.addLocalForIdent(s.Value.(*ast.Ident))
  1905  		}
  1906  	}
  1907  
  1908  	x := b.expr(fn, s.X)
  1909  
  1910  	var k, v Value
  1911  	var loop, done *BasicBlock
  1912  	switch rt := x.Type().Underlying().(type) {
  1913  	case *types.Slice, *types.Array, *types.Pointer: // *array
  1914  		k, v, loop, done = b.rangeIndexed(fn, x, tv, s.For)
  1915  
  1916  	case *types.Chan:
  1917  		k, loop, done = b.rangeChan(fn, x, tk, s.For)
  1918  
  1919  	case *types.Map, *types.Basic: // string
  1920  		k, v, loop, done = b.rangeIter(fn, x, tk, tv, s.For)
  1921  
  1922  	default:
  1923  		panic("Cannot range over: " + rt.String())
  1924  	}
  1925  
  1926  	// Evaluate both LHS expressions before we update either.
  1927  	var kl, vl lvalue
  1928  	if tk != nil {
  1929  		kl = b.addr(fn, s.Key, false) // non-escaping
  1930  	}
  1931  	if tv != nil {
  1932  		vl = b.addr(fn, s.Value, false) // non-escaping
  1933  	}
  1934  	if tk != nil {
  1935  		kl.store(fn, k)
  1936  	}
  1937  	if tv != nil {
  1938  		vl.store(fn, v)
  1939  	}
  1940  
  1941  	if label != nil {
  1942  		label._break = done
  1943  		label._continue = loop
  1944  	}
  1945  
  1946  	fn.targets = &targets{
  1947  		tail:      fn.targets,
  1948  		_break:    done,
  1949  		_continue: loop,
  1950  	}
  1951  	b.stmt(fn, s.Body)
  1952  	fn.targets = fn.targets.tail
  1953  	emitJump(fn, loop) // back-edge
  1954  	fn.currentBlock = done
  1955  }
  1956  
  1957  // stmt lowers statement s to SSA form, emitting code to fn.
  1958  func (b *builder) stmt(fn *Function, _s ast.Stmt) {
  1959  	// The label of the current statement.  If non-nil, its _goto
  1960  	// target is always set; its _break and _continue are set only
  1961  	// within the body of switch/typeswitch/select/for/range.
  1962  	// It is effectively an additional default-nil parameter of stmt().
  1963  	var label *lblock
  1964  start:
  1965  	switch s := _s.(type) {
  1966  	case *ast.EmptyStmt:
  1967  		// ignore.  (Usually removed by gofmt.)
  1968  
  1969  	case *ast.DeclStmt: // Con, Var or Typ
  1970  		d := s.Decl.(*ast.GenDecl)
  1971  		if d.Tok == token.VAR {
  1972  			for _, spec := range d.Specs {
  1973  				if vs, ok := spec.(*ast.ValueSpec); ok {
  1974  					b.localValueSpec(fn, vs)
  1975  				}
  1976  			}
  1977  		}
  1978  
  1979  	case *ast.LabeledStmt:
  1980  		label = fn.labelledBlock(s.Label)
  1981  		emitJump(fn, label._goto)
  1982  		fn.currentBlock = label._goto
  1983  		_s = s.Stmt
  1984  		goto start // effectively: tailcall stmt(fn, s.Stmt, label)
  1985  
  1986  	case *ast.ExprStmt:
  1987  		b.expr(fn, s.X)
  1988  
  1989  	case *ast.SendStmt:
  1990  		fn.emit(&Send{
  1991  			Chan: b.expr(fn, s.Chan),
  1992  			X: emitConv(fn, b.expr(fn, s.Value),
  1993  				fn.Pkg.typeOf(s.Chan).Underlying().(*types.Chan).Elem()),
  1994  			pos: s.Arrow,
  1995  		})
  1996  
  1997  	case *ast.IncDecStmt:
  1998  		op := token.ADD
  1999  		if s.Tok == token.DEC {
  2000  			op = token.SUB
  2001  		}
  2002  		loc := b.addr(fn, s.X, false)
  2003  		b.assignOp(fn, loc, NewConst(exact.MakeInt64(1), loc.typ()), op)
  2004  
  2005  	case *ast.AssignStmt:
  2006  		switch s.Tok {
  2007  		case token.ASSIGN, token.DEFINE:
  2008  			b.assignStmt(fn, s.Lhs, s.Rhs, s.Tok == token.DEFINE)
  2009  
  2010  		default: // +=, etc.
  2011  			op := s.Tok + token.ADD - token.ADD_ASSIGN
  2012  			b.assignOp(fn, b.addr(fn, s.Lhs[0], false), b.expr(fn, s.Rhs[0]), op)
  2013  		}
  2014  
  2015  	case *ast.GoStmt:
  2016  		// The "intrinsics" new/make/len/cap are forbidden here.
  2017  		// panic is treated like an ordinary function call.
  2018  		v := Go{pos: s.Go}
  2019  		b.setCall(fn, s.Call, &v.Call)
  2020  		fn.emit(&v)
  2021  
  2022  	case *ast.DeferStmt:
  2023  		// The "intrinsics" new/make/len/cap are forbidden here.
  2024  		// panic is treated like an ordinary function call.
  2025  		v := Defer{pos: s.Defer}
  2026  		b.setCall(fn, s.Call, &v.Call)
  2027  		fn.emit(&v)
  2028  
  2029  		// A deferred call can cause recovery from panic,
  2030  		// and control resumes at the Recover block.
  2031  		createRecoverBlock(fn)
  2032  
  2033  	case *ast.ReturnStmt:
  2034  		var results []Value
  2035  		if len(s.Results) == 1 && fn.Signature.Results().Len() > 1 {
  2036  			// Return of one expression in a multi-valued function.
  2037  			tuple := b.exprN(fn, s.Results[0])
  2038  			ttuple := tuple.Type().(*types.Tuple)
  2039  			for i, n := 0, ttuple.Len(); i < n; i++ {
  2040  				results = append(results,
  2041  					emitConv(fn, emitExtract(fn, tuple, i),
  2042  						fn.Signature.Results().At(i).Type()))
  2043  			}
  2044  		} else {
  2045  			// 1:1 return, or no-arg return in non-void function.
  2046  			for i, r := range s.Results {
  2047  				v := emitConv(fn, b.expr(fn, r), fn.Signature.Results().At(i).Type())
  2048  				results = append(results, v)
  2049  			}
  2050  		}
  2051  		if fn.namedResults != nil {
  2052  			// Function has named result parameters (NRPs).
  2053  			// Perform parallel assignment of return operands to NRPs.
  2054  			for i, r := range results {
  2055  				emitStore(fn, fn.namedResults[i], r, s.Return)
  2056  			}
  2057  		}
  2058  		// Run function calls deferred in this
  2059  		// function when explicitly returning from it.
  2060  		fn.emit(new(RunDefers))
  2061  		if fn.namedResults != nil {
  2062  			// Reload NRPs to form the result tuple.
  2063  			results = results[:0]
  2064  			for _, r := range fn.namedResults {
  2065  				results = append(results, emitLoad(fn, r))
  2066  			}
  2067  		}
  2068  		fn.emit(&Return{Results: results, pos: s.Return})
  2069  		fn.currentBlock = fn.newBasicBlock("unreachable")
  2070  
  2071  	case *ast.BranchStmt:
  2072  		var block *BasicBlock
  2073  		switch s.Tok {
  2074  		case token.BREAK:
  2075  			if s.Label != nil {
  2076  				block = fn.labelledBlock(s.Label)._break
  2077  			} else {
  2078  				for t := fn.targets; t != nil && block == nil; t = t.tail {
  2079  					block = t._break
  2080  				}
  2081  			}
  2082  
  2083  		case token.CONTINUE:
  2084  			if s.Label != nil {
  2085  				block = fn.labelledBlock(s.Label)._continue
  2086  			} else {
  2087  				for t := fn.targets; t != nil && block == nil; t = t.tail {
  2088  					block = t._continue
  2089  				}
  2090  			}
  2091  
  2092  		case token.FALLTHROUGH:
  2093  			for t := fn.targets; t != nil && block == nil; t = t.tail {
  2094  				block = t._fallthrough
  2095  			}
  2096  
  2097  		case token.GOTO:
  2098  			block = fn.labelledBlock(s.Label)._goto
  2099  		}
  2100  		emitJump(fn, block)
  2101  		fn.currentBlock = fn.newBasicBlock("unreachable")
  2102  
  2103  	case *ast.BlockStmt:
  2104  		b.stmtList(fn, s.List)
  2105  
  2106  	case *ast.IfStmt:
  2107  		if s.Init != nil {
  2108  			b.stmt(fn, s.Init)
  2109  		}
  2110  		then := fn.newBasicBlock("if.then")
  2111  		done := fn.newBasicBlock("if.done")
  2112  		els := done
  2113  		if s.Else != nil {
  2114  			els = fn.newBasicBlock("if.else")
  2115  		}
  2116  		b.cond(fn, s.Cond, then, els)
  2117  		fn.currentBlock = then
  2118  		b.stmt(fn, s.Body)
  2119  		emitJump(fn, done)
  2120  
  2121  		if s.Else != nil {
  2122  			fn.currentBlock = els
  2123  			b.stmt(fn, s.Else)
  2124  			emitJump(fn, done)
  2125  		}
  2126  
  2127  		fn.currentBlock = done
  2128  
  2129  	case *ast.SwitchStmt:
  2130  		b.switchStmt(fn, s, label)
  2131  
  2132  	case *ast.TypeSwitchStmt:
  2133  		b.typeSwitchStmt(fn, s, label)
  2134  
  2135  	case *ast.SelectStmt:
  2136  		b.selectStmt(fn, s, label)
  2137  
  2138  	case *ast.ForStmt:
  2139  		b.forStmt(fn, s, label)
  2140  
  2141  	case *ast.RangeStmt:
  2142  		b.rangeStmt(fn, s, label)
  2143  
  2144  	default:
  2145  		panic(fmt.Sprintf("unexpected statement kind: %T", s))
  2146  	}
  2147  }
  2148  
  2149  // buildFunction builds SSA code for the body of function fn.  Idempotent.
  2150  func (b *builder) buildFunction(fn *Function) {
  2151  	if fn.Blocks != nil {
  2152  		return // building already started
  2153  	}
  2154  
  2155  	var recvField *ast.FieldList
  2156  	var body *ast.BlockStmt
  2157  	var functype *ast.FuncType
  2158  	switch n := fn.syntax.(type) {
  2159  	case nil:
  2160  		return // not a Go source function.  (Synthetic, or from object file.)
  2161  	case *ast.FuncDecl:
  2162  		functype = n.Type
  2163  		recvField = n.Recv
  2164  		body = n.Body
  2165  	case *ast.FuncLit:
  2166  		functype = n.Type
  2167  		body = n.Body
  2168  	default:
  2169  		panic(n)
  2170  	}
  2171  
  2172  	if body == nil {
  2173  		// External function.
  2174  		if fn.Params == nil {
  2175  			// This condition ensures we add a non-empty
  2176  			// params list once only, but we may attempt
  2177  			// the degenerate empty case repeatedly.
  2178  			// TODO(adonovan): opt: don't do that.
  2179  
  2180  			// We set Function.Params even though there is no body
  2181  			// code to reference them.  This simplifies clients.
  2182  			if recv := fn.Signature.Recv(); recv != nil {
  2183  				fn.addParamObj(recv)
  2184  			}
  2185  			params := fn.Signature.Params()
  2186  			for i, n := 0, params.Len(); i < n; i++ {
  2187  				fn.addParamObj(params.At(i))
  2188  			}
  2189  		}
  2190  		return
  2191  	}
  2192  	if fn.Prog.mode&LogSource != 0 {
  2193  		defer logStack("build function %s @ %s", fn, fn.Prog.Fset.Position(fn.pos))()
  2194  	}
  2195  	fn.startBody()
  2196  	fn.createSyntacticParams(recvField, functype)
  2197  	b.stmt(fn, body)
  2198  	if cb := fn.currentBlock; cb != nil && (cb == fn.Blocks[0] || cb == fn.Recover || cb.Preds != nil) {
  2199  		// Control fell off the end of the function's body block.
  2200  		//
  2201  		// Block optimizations eliminate the current block, if
  2202  		// unreachable.  It is a builder invariant that
  2203  		// if this no-arg return is ill-typed for
  2204  		// fn.Signature.Results, this block must be
  2205  		// unreachable.  The sanity checker checks this.
  2206  		fn.emit(new(RunDefers))
  2207  		fn.emit(new(Return))
  2208  	}
  2209  	fn.finishBody()
  2210  }
  2211  
  2212  // buildFuncDecl builds SSA code for the function or method declared
  2213  // by decl in package pkg.
  2214  //
  2215  func (b *builder) buildFuncDecl(pkg *Package, decl *ast.FuncDecl) {
  2216  	id := decl.Name
  2217  	if isBlankIdent(id) {
  2218  		return // discard
  2219  	}
  2220  	fn := pkg.values[pkg.info.Defs[id]].(*Function)
  2221  	if decl.Recv == nil && id.Name == "init" {
  2222  		var v Call
  2223  		v.Call.Value = fn
  2224  		v.setType(types.NewTuple())
  2225  		pkg.init.emit(&v)
  2226  	}
  2227  	b.buildFunction(fn)
  2228  }
  2229  
  2230  // BuildAll calls Package.Build() for each package in prog.
  2231  // Building occurs in parallel unless the BuildSerially mode flag was set.
  2232  //
  2233  // BuildAll is intended for whole-program analysis; a typical compiler
  2234  // need only build a single package.
  2235  //
  2236  // BuildAll is idempotent and thread-safe.
  2237  //
  2238  func (prog *Program) Build() {
  2239  	var wg sync.WaitGroup
  2240  	for _, p := range prog.packages {
  2241  		if prog.mode&BuildSerially != 0 {
  2242  			p.Build()
  2243  		} else {
  2244  			wg.Add(1)
  2245  			go func(p *Package) {
  2246  				p.Build()
  2247  				wg.Done()
  2248  			}(p)
  2249  		}
  2250  	}
  2251  	wg.Wait()
  2252  }
  2253  
  2254  // Build builds SSA code for all functions and vars in package p.
  2255  //
  2256  // Precondition: CreatePackage must have been called for all of p's
  2257  // direct imports (and hence its direct imports must have been
  2258  // error-free).
  2259  //
  2260  // Build is idempotent and thread-safe.
  2261  //
  2262  func (p *Package) Build() { p.buildOnce.Do(p.build) }
  2263  
  2264  func (p *Package) build() {
  2265  	if p.info == nil {
  2266  		return // synthetic package, e.g. "testmain"
  2267  	}
  2268  	if p.files == nil {
  2269  		p.info = nil
  2270  		return // package loaded from export data
  2271  	}
  2272  
  2273  	// Ensure we have runtime type info for all exported members.
  2274  	// TODO(adonovan): ideally belongs in memberFromObject, but
  2275  	// that would require package creation in topological order.
  2276  	for name, mem := range p.Members {
  2277  		if ast.IsExported(name) {
  2278  			p.Prog.needMethodsOf(mem.Type())
  2279  		}
  2280  	}
  2281  	if p.Prog.mode&LogSource != 0 {
  2282  		defer logStack("build %s", p)()
  2283  	}
  2284  	init := p.init
  2285  	init.startBody()
  2286  
  2287  	var done *BasicBlock
  2288  
  2289  	if p.Prog.mode&BareInits == 0 {
  2290  		// Make init() skip if package is already initialized.
  2291  		initguard := p.Var("init$guard")
  2292  		doinit := init.newBasicBlock("init.start")
  2293  		done = init.newBasicBlock("init.done")
  2294  		emitIf(init, emitLoad(init, initguard), done, doinit)
  2295  		init.currentBlock = doinit
  2296  		emitStore(init, initguard, vTrue, token.NoPos)
  2297  
  2298  		// Call the init() function of each package we import.
  2299  		for _, pkg := range p.Pkg.Imports() {
  2300  			prereq := p.Prog.packages[pkg]
  2301  			if prereq == nil {
  2302  				panic(fmt.Sprintf("Package(%q).Build(): unsatisfied import: Program.CreatePackage(%q) was not called", p.Pkg.Path(), pkg.Path()))
  2303  			}
  2304  			var v Call
  2305  			v.Call.Value = prereq.init
  2306  			v.Call.pos = init.pos
  2307  			v.setType(types.NewTuple())
  2308  			init.emit(&v)
  2309  		}
  2310  	}
  2311  
  2312  	var b builder
  2313  
  2314  	// Initialize package-level vars in correct order.
  2315  	for _, varinit := range p.info.InitOrder {
  2316  		if init.Prog.mode&LogSource != 0 {
  2317  			fmt.Fprintf(os.Stderr, "build global initializer %v @ %s\n",
  2318  				varinit.Lhs, p.Prog.Fset.Position(varinit.Rhs.Pos()))
  2319  		}
  2320  		if len(varinit.Lhs) == 1 {
  2321  			// 1:1 initialization: var x, y = a(), b()
  2322  			var lval lvalue
  2323  			if v := varinit.Lhs[0]; v.Name() != "_" {
  2324  				lval = &address{addr: p.values[v].(*Global), pos: v.Pos()}
  2325  			} else {
  2326  				lval = blank{}
  2327  			}
  2328  			b.assign(init, lval, varinit.Rhs, true, nil)
  2329  		} else {
  2330  			// n:1 initialization: var x, y :=  f()
  2331  			tuple := b.exprN(init, varinit.Rhs)
  2332  			for i, v := range varinit.Lhs {
  2333  				if v.Name() == "_" {
  2334  					continue
  2335  				}
  2336  				emitStore(init, p.values[v].(*Global), emitExtract(init, tuple, i), v.Pos())
  2337  			}
  2338  		}
  2339  	}
  2340  
  2341  	// Build all package-level functions, init functions
  2342  	// and methods, including unreachable/blank ones.
  2343  	// We build them in source order, but it's not significant.
  2344  	for _, file := range p.files {
  2345  		for _, decl := range file.Decls {
  2346  			if decl, ok := decl.(*ast.FuncDecl); ok {
  2347  				b.buildFuncDecl(p, decl)
  2348  			}
  2349  		}
  2350  	}
  2351  
  2352  	// Finish up init().
  2353  	if p.Prog.mode&BareInits == 0 {
  2354  		emitJump(init, done)
  2355  		init.currentBlock = done
  2356  	}
  2357  	init.emit(new(Return))
  2358  	init.finishBody()
  2359  
  2360  	p.info = nil // We no longer need ASTs or go/types deductions.
  2361  
  2362  	if p.Prog.mode&SanityCheckFunctions != 0 {
  2363  		sanityCheckPackage(p)
  2364  	}
  2365  }
  2366  
  2367  // Like ObjectOf, but panics instead of returning nil.
  2368  // Only valid during p's create and build phases.
  2369  func (p *Package) objectOf(id *ast.Ident) types.Object {
  2370  	if o := p.info.ObjectOf(id); o != nil {
  2371  		return o
  2372  	}
  2373  	panic(fmt.Sprintf("no types.Object for ast.Ident %s @ %s",
  2374  		id.Name, p.Prog.Fset.Position(id.Pos())))
  2375  }
  2376  
  2377  // Like TypeOf, but panics instead of returning nil.
  2378  // Only valid during p's create and build phases.
  2379  func (p *Package) typeOf(e ast.Expr) types.Type {
  2380  	if T := p.info.TypeOf(e); T != nil {
  2381  		return T
  2382  	}
  2383  	panic(fmt.Sprintf("no type for %T @ %s",
  2384  		e, p.Prog.Fset.Position(e.Pos())))
  2385  }