github.com/Filosottile/go@v0.0.0-20170906193555-dbed9972d994/src/cmd/compile/internal/gc/ssa.go (about)

     1  // Copyright 2015 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  	"bytes"
     9  	"encoding/binary"
    10  	"fmt"
    11  	"html"
    12  	"os"
    13  	"sort"
    14  
    15  	"cmd/compile/internal/ssa"
    16  	"cmd/compile/internal/types"
    17  	"cmd/internal/obj"
    18  	"cmd/internal/objabi"
    19  	"cmd/internal/src"
    20  	"cmd/internal/sys"
    21  )
    22  
    23  var ssaConfig *ssa.Config
    24  var ssaCaches []ssa.Cache
    25  
    26  func initssaconfig() {
    27  	types_ := ssa.Types{
    28  		Bool:       types.Types[TBOOL],
    29  		Int8:       types.Types[TINT8],
    30  		Int16:      types.Types[TINT16],
    31  		Int32:      types.Types[TINT32],
    32  		Int64:      types.Types[TINT64],
    33  		UInt8:      types.Types[TUINT8],
    34  		UInt16:     types.Types[TUINT16],
    35  		UInt32:     types.Types[TUINT32],
    36  		UInt64:     types.Types[TUINT64],
    37  		Float32:    types.Types[TFLOAT32],
    38  		Float64:    types.Types[TFLOAT64],
    39  		Int:        types.Types[TINT],
    40  		Uintptr:    types.Types[TUINTPTR],
    41  		String:     types.Types[TSTRING],
    42  		BytePtr:    types.NewPtr(types.Types[TUINT8]),
    43  		Int32Ptr:   types.NewPtr(types.Types[TINT32]),
    44  		UInt32Ptr:  types.NewPtr(types.Types[TUINT32]),
    45  		IntPtr:     types.NewPtr(types.Types[TINT]),
    46  		UintptrPtr: types.NewPtr(types.Types[TUINTPTR]),
    47  		Float32Ptr: types.NewPtr(types.Types[TFLOAT32]),
    48  		Float64Ptr: types.NewPtr(types.Types[TFLOAT64]),
    49  		BytePtrPtr: types.NewPtr(types.NewPtr(types.Types[TUINT8])),
    50  	}
    51  	// Generate a few pointer types that are uncommon in the frontend but common in the backend.
    52  	// Caching is disabled in the backend, so generating these here avoids allocations.
    53  	_ = types.NewPtr(types.Types[TINTER])                             // *interface{}
    54  	_ = types.NewPtr(types.NewPtr(types.Types[TSTRING]))              // **string
    55  	_ = types.NewPtr(types.NewPtr(types.Idealstring))                 // **string
    56  	_ = types.NewPtr(types.NewSlice(types.Types[TINTER]))             // *[]interface{}
    57  	_ = types.NewPtr(types.NewPtr(types.Bytetype))                    // **byte
    58  	_ = types.NewPtr(types.NewSlice(types.Bytetype))                  // *[]byte
    59  	_ = types.NewPtr(types.NewSlice(types.Types[TSTRING]))            // *[]string
    60  	_ = types.NewPtr(types.NewSlice(types.Idealstring))               // *[]string
    61  	_ = types.NewPtr(types.NewPtr(types.NewPtr(types.Types[TUINT8]))) // ***uint8
    62  	_ = types.NewPtr(types.Types[TINT16])                             // *int16
    63  	_ = types.NewPtr(types.Types[TINT64])                             // *int64
    64  	_ = types.NewPtr(types.Errortype)                                 // *error
    65  	types.NewPtrCacheEnabled = false
    66  	ssaConfig = ssa.NewConfig(thearch.LinkArch.Name, types_, Ctxt, Debug['N'] == 0)
    67  	if thearch.LinkArch.Name == "386" {
    68  		ssaConfig.Set387(thearch.Use387)
    69  	}
    70  	ssaCaches = make([]ssa.Cache, nBackendWorkers)
    71  
    72  	// Set up some runtime functions we'll need to call.
    73  	Newproc = sysfunc("newproc")
    74  	Deferproc = sysfunc("deferproc")
    75  	Deferreturn = sysfunc("deferreturn")
    76  	Duffcopy = sysfunc("duffcopy")
    77  	Duffzero = sysfunc("duffzero")
    78  	panicindex = sysfunc("panicindex")
    79  	panicslice = sysfunc("panicslice")
    80  	panicdivide = sysfunc("panicdivide")
    81  	growslice = sysfunc("growslice")
    82  	panicdottypeE = sysfunc("panicdottypeE")
    83  	panicdottypeI = sysfunc("panicdottypeI")
    84  	panicnildottype = sysfunc("panicnildottype")
    85  	assertE2I = sysfunc("assertE2I")
    86  	assertE2I2 = sysfunc("assertE2I2")
    87  	assertI2I = sysfunc("assertI2I")
    88  	assertI2I2 = sysfunc("assertI2I2")
    89  	goschedguarded = sysfunc("goschedguarded")
    90  	writeBarrier = sysfunc("writeBarrier")
    91  	writebarrierptr = sysfunc("writebarrierptr")
    92  	typedmemmove = sysfunc("typedmemmove")
    93  	typedmemclr = sysfunc("typedmemclr")
    94  	Udiv = sysfunc("udiv")
    95  
    96  	// GO386=387 runtime functions
    97  	ControlWord64trunc = sysfunc("controlWord64trunc")
    98  	ControlWord32 = sysfunc("controlWord32")
    99  }
   100  
   101  // buildssa builds an SSA function for fn.
   102  // worker indicates which of the backend workers is doing the processing.
   103  func buildssa(fn *Node, worker int) *ssa.Func {
   104  	name := fn.funcname()
   105  	printssa := name == os.Getenv("GOSSAFUNC")
   106  	if printssa {
   107  		fmt.Println("generating SSA for", name)
   108  		dumplist("buildssa-enter", fn.Func.Enter)
   109  		dumplist("buildssa-body", fn.Nbody)
   110  		dumplist("buildssa-exit", fn.Func.Exit)
   111  	}
   112  
   113  	var s state
   114  	s.pushLine(fn.Pos)
   115  	defer s.popLine()
   116  
   117  	s.hasdefer = fn.Func.HasDefer()
   118  	if fn.Func.Pragma&CgoUnsafeArgs != 0 {
   119  		s.cgoUnsafeArgs = true
   120  	}
   121  
   122  	fe := ssafn{
   123  		curfn: fn,
   124  		log:   printssa,
   125  	}
   126  	s.curfn = fn
   127  
   128  	s.f = ssa.NewFunc(&fe)
   129  	s.config = ssaConfig
   130  	s.f.Config = ssaConfig
   131  	s.f.Cache = &ssaCaches[worker]
   132  	s.f.Cache.Reset()
   133  	s.f.DebugTest = s.f.DebugHashMatch("GOSSAHASH", name)
   134  	s.f.Name = name
   135  	if fn.Func.Pragma&Nosplit != 0 {
   136  		s.f.NoSplit = true
   137  	}
   138  	defer func() {
   139  		if s.f.WBPos.IsKnown() {
   140  			fn.Func.WBPos = s.f.WBPos
   141  		}
   142  	}()
   143  	s.exitCode = fn.Func.Exit
   144  	s.panics = map[funcLine]*ssa.Block{}
   145  
   146  	if name == os.Getenv("GOSSAFUNC") {
   147  		s.f.HTMLWriter = ssa.NewHTMLWriter("ssa.html", s.f.Frontend(), name)
   148  		// TODO: generate and print a mapping from nodes to values and blocks
   149  	}
   150  
   151  	// Allocate starting block
   152  	s.f.Entry = s.f.NewBlock(ssa.BlockPlain)
   153  
   154  	// Allocate starting values
   155  	s.labels = map[string]*ssaLabel{}
   156  	s.labeledNodes = map[*Node]*ssaLabel{}
   157  	s.fwdVars = map[*Node]*ssa.Value{}
   158  	s.startmem = s.entryNewValue0(ssa.OpInitMem, types.TypeMem)
   159  	s.sp = s.entryNewValue0(ssa.OpSP, types.Types[TUINTPTR]) // TODO: use generic pointer type (unsafe.Pointer?) instead
   160  	s.sb = s.entryNewValue0(ssa.OpSB, types.Types[TUINTPTR])
   161  
   162  	s.startBlock(s.f.Entry)
   163  	s.vars[&memVar] = s.startmem
   164  
   165  	s.varsyms = map[*Node]interface{}{}
   166  
   167  	// Generate addresses of local declarations
   168  	s.decladdrs = map[*Node]*ssa.Value{}
   169  	for _, n := range fn.Func.Dcl {
   170  		switch n.Class() {
   171  		case PPARAM, PPARAMOUT:
   172  			aux := s.lookupSymbol(n, &ssa.ArgSymbol{Node: n})
   173  			s.decladdrs[n] = s.entryNewValue1A(ssa.OpAddr, types.NewPtr(n.Type), aux, s.sp)
   174  			if n.Class() == PPARAMOUT && s.canSSA(n) {
   175  				// Save ssa-able PPARAMOUT variables so we can
   176  				// store them back to the stack at the end of
   177  				// the function.
   178  				s.returns = append(s.returns, n)
   179  			}
   180  		case PAUTO:
   181  			// processed at each use, to prevent Addr coming
   182  			// before the decl.
   183  		case PAUTOHEAP:
   184  			// moved to heap - already handled by frontend
   185  		case PFUNC:
   186  			// local function - already handled by frontend
   187  		default:
   188  			s.Fatalf("local variable with class %s unimplemented", classnames[n.Class()])
   189  		}
   190  	}
   191  
   192  	// Populate SSAable arguments.
   193  	for _, n := range fn.Func.Dcl {
   194  		if n.Class() == PPARAM && s.canSSA(n) {
   195  			s.vars[n] = s.newValue0A(ssa.OpArg, n.Type, n)
   196  		}
   197  	}
   198  
   199  	// Convert the AST-based IR to the SSA-based IR
   200  	s.stmtList(fn.Func.Enter)
   201  	s.stmtList(fn.Nbody)
   202  
   203  	// fallthrough to exit
   204  	if s.curBlock != nil {
   205  		s.pushLine(fn.Func.Endlineno)
   206  		s.exit()
   207  		s.popLine()
   208  	}
   209  
   210  	s.insertPhis()
   211  
   212  	// Don't carry reference this around longer than necessary
   213  	s.exitCode = Nodes{}
   214  
   215  	// Main call to ssa package to compile function
   216  	ssa.Compile(s.f)
   217  	return s.f
   218  }
   219  
   220  type state struct {
   221  	// configuration (arch) information
   222  	config *ssa.Config
   223  
   224  	// function we're building
   225  	f *ssa.Func
   226  
   227  	// Node for function
   228  	curfn *Node
   229  
   230  	// labels and labeled control flow nodes (OFOR, OFORUNTIL, OSWITCH, OSELECT) in f
   231  	labels       map[string]*ssaLabel
   232  	labeledNodes map[*Node]*ssaLabel
   233  
   234  	// Code that must precede any return
   235  	// (e.g., copying value of heap-escaped paramout back to true paramout)
   236  	exitCode Nodes
   237  
   238  	// unlabeled break and continue statement tracking
   239  	breakTo    *ssa.Block // current target for plain break statement
   240  	continueTo *ssa.Block // current target for plain continue statement
   241  
   242  	// current location where we're interpreting the AST
   243  	curBlock *ssa.Block
   244  
   245  	// variable assignments in the current block (map from variable symbol to ssa value)
   246  	// *Node is the unique identifier (an ONAME Node) for the variable.
   247  	// TODO: keep a single varnum map, then make all of these maps slices instead?
   248  	vars map[*Node]*ssa.Value
   249  
   250  	// fwdVars are variables that are used before they are defined in the current block.
   251  	// This map exists just to coalesce multiple references into a single FwdRef op.
   252  	// *Node is the unique identifier (an ONAME Node) for the variable.
   253  	fwdVars map[*Node]*ssa.Value
   254  
   255  	// all defined variables at the end of each block. Indexed by block ID.
   256  	defvars []map[*Node]*ssa.Value
   257  
   258  	// addresses of PPARAM and PPARAMOUT variables.
   259  	decladdrs map[*Node]*ssa.Value
   260  
   261  	// symbols for PEXTERN, PAUTO and PPARAMOUT variables so they can be reused.
   262  	varsyms map[*Node]interface{}
   263  
   264  	// starting values. Memory, stack pointer, and globals pointer
   265  	startmem *ssa.Value
   266  	sp       *ssa.Value
   267  	sb       *ssa.Value
   268  
   269  	// line number stack. The current line number is top of stack
   270  	line []src.XPos
   271  
   272  	// list of panic calls by function name and line number.
   273  	// Used to deduplicate panic calls.
   274  	panics map[funcLine]*ssa.Block
   275  
   276  	// list of PPARAMOUT (return) variables.
   277  	returns []*Node
   278  
   279  	cgoUnsafeArgs bool
   280  	hasdefer      bool // whether the function contains a defer statement
   281  }
   282  
   283  type funcLine struct {
   284  	f    *obj.LSym
   285  	file string
   286  	line uint
   287  }
   288  
   289  type ssaLabel struct {
   290  	target         *ssa.Block // block identified by this label
   291  	breakTarget    *ssa.Block // block to break to in control flow node identified by this label
   292  	continueTarget *ssa.Block // block to continue to in control flow node identified by this label
   293  }
   294  
   295  // label returns the label associated with sym, creating it if necessary.
   296  func (s *state) label(sym *types.Sym) *ssaLabel {
   297  	lab := s.labels[sym.Name]
   298  	if lab == nil {
   299  		lab = new(ssaLabel)
   300  		s.labels[sym.Name] = lab
   301  	}
   302  	return lab
   303  }
   304  
   305  func (s *state) Logf(msg string, args ...interface{}) { s.f.Logf(msg, args...) }
   306  func (s *state) Log() bool                            { return s.f.Log() }
   307  func (s *state) Fatalf(msg string, args ...interface{}) {
   308  	s.f.Frontend().Fatalf(s.peekPos(), msg, args...)
   309  }
   310  func (s *state) Warnl(pos src.XPos, msg string, args ...interface{}) { s.f.Warnl(pos, msg, args...) }
   311  func (s *state) Debug_checknil() bool                                { return s.f.Frontend().Debug_checknil() }
   312  
   313  var (
   314  	// dummy node for the memory variable
   315  	memVar = Node{Op: ONAME, Sym: &types.Sym{Name: "mem"}}
   316  
   317  	// dummy nodes for temporary variables
   318  	ptrVar    = Node{Op: ONAME, Sym: &types.Sym{Name: "ptr"}}
   319  	lenVar    = Node{Op: ONAME, Sym: &types.Sym{Name: "len"}}
   320  	newlenVar = Node{Op: ONAME, Sym: &types.Sym{Name: "newlen"}}
   321  	capVar    = Node{Op: ONAME, Sym: &types.Sym{Name: "cap"}}
   322  	typVar    = Node{Op: ONAME, Sym: &types.Sym{Name: "typ"}}
   323  	okVar     = Node{Op: ONAME, Sym: &types.Sym{Name: "ok"}}
   324  )
   325  
   326  // startBlock sets the current block we're generating code in to b.
   327  func (s *state) startBlock(b *ssa.Block) {
   328  	if s.curBlock != nil {
   329  		s.Fatalf("starting block %v when block %v has not ended", b, s.curBlock)
   330  	}
   331  	s.curBlock = b
   332  	s.vars = map[*Node]*ssa.Value{}
   333  	for n := range s.fwdVars {
   334  		delete(s.fwdVars, n)
   335  	}
   336  }
   337  
   338  // endBlock marks the end of generating code for the current block.
   339  // Returns the (former) current block. Returns nil if there is no current
   340  // block, i.e. if no code flows to the current execution point.
   341  func (s *state) endBlock() *ssa.Block {
   342  	b := s.curBlock
   343  	if b == nil {
   344  		return nil
   345  	}
   346  	for len(s.defvars) <= int(b.ID) {
   347  		s.defvars = append(s.defvars, nil)
   348  	}
   349  	s.defvars[b.ID] = s.vars
   350  	s.curBlock = nil
   351  	s.vars = nil
   352  	b.Pos = s.peekPos()
   353  	return b
   354  }
   355  
   356  // pushLine pushes a line number on the line number stack.
   357  func (s *state) pushLine(line src.XPos) {
   358  	if !line.IsKnown() {
   359  		// the frontend may emit node with line number missing,
   360  		// use the parent line number in this case.
   361  		line = s.peekPos()
   362  		if Debug['K'] != 0 {
   363  			Warn("buildssa: unknown position (line 0)")
   364  		}
   365  	}
   366  	s.line = append(s.line, line)
   367  }
   368  
   369  // popLine pops the top of the line number stack.
   370  func (s *state) popLine() {
   371  	s.line = s.line[:len(s.line)-1]
   372  }
   373  
   374  // peekPos peeks the top of the line number stack.
   375  func (s *state) peekPos() src.XPos {
   376  	return s.line[len(s.line)-1]
   377  }
   378  
   379  // newValue0 adds a new value with no arguments to the current block.
   380  func (s *state) newValue0(op ssa.Op, t *types.Type) *ssa.Value {
   381  	return s.curBlock.NewValue0(s.peekPos(), op, t)
   382  }
   383  
   384  // newValue0A adds a new value with no arguments and an aux value to the current block.
   385  func (s *state) newValue0A(op ssa.Op, t *types.Type, aux interface{}) *ssa.Value {
   386  	return s.curBlock.NewValue0A(s.peekPos(), op, t, aux)
   387  }
   388  
   389  // newValue0I adds a new value with no arguments and an auxint value to the current block.
   390  func (s *state) newValue0I(op ssa.Op, t *types.Type, auxint int64) *ssa.Value {
   391  	return s.curBlock.NewValue0I(s.peekPos(), op, t, auxint)
   392  }
   393  
   394  // newValue1 adds a new value with one argument to the current block.
   395  func (s *state) newValue1(op ssa.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
   396  	return s.curBlock.NewValue1(s.peekPos(), op, t, arg)
   397  }
   398  
   399  // newValue1A adds a new value with one argument and an aux value to the current block.
   400  func (s *state) newValue1A(op ssa.Op, t *types.Type, aux interface{}, arg *ssa.Value) *ssa.Value {
   401  	return s.curBlock.NewValue1A(s.peekPos(), op, t, aux, arg)
   402  }
   403  
   404  // newValue1I adds a new value with one argument and an auxint value to the current block.
   405  func (s *state) newValue1I(op ssa.Op, t *types.Type, aux int64, arg *ssa.Value) *ssa.Value {
   406  	return s.curBlock.NewValue1I(s.peekPos(), op, t, aux, arg)
   407  }
   408  
   409  // newValue2 adds a new value with two arguments to the current block.
   410  func (s *state) newValue2(op ssa.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
   411  	return s.curBlock.NewValue2(s.peekPos(), op, t, arg0, arg1)
   412  }
   413  
   414  // newValue2I adds a new value with two arguments and an auxint value to the current block.
   415  func (s *state) newValue2I(op ssa.Op, t *types.Type, aux int64, arg0, arg1 *ssa.Value) *ssa.Value {
   416  	return s.curBlock.NewValue2I(s.peekPos(), op, t, aux, arg0, arg1)
   417  }
   418  
   419  // newValue3 adds a new value with three arguments to the current block.
   420  func (s *state) newValue3(op ssa.Op, t *types.Type, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
   421  	return s.curBlock.NewValue3(s.peekPos(), op, t, arg0, arg1, arg2)
   422  }
   423  
   424  // newValue3I adds a new value with three arguments and an auxint value to the current block.
   425  func (s *state) newValue3I(op ssa.Op, t *types.Type, aux int64, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
   426  	return s.curBlock.NewValue3I(s.peekPos(), op, t, aux, arg0, arg1, arg2)
   427  }
   428  
   429  // newValue3A adds a new value with three arguments and an aux value to the current block.
   430  func (s *state) newValue3A(op ssa.Op, t *types.Type, aux interface{}, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
   431  	return s.curBlock.NewValue3A(s.peekPos(), op, t, aux, arg0, arg1, arg2)
   432  }
   433  
   434  // newValue4 adds a new value with four arguments to the current block.
   435  func (s *state) newValue4(op ssa.Op, t *types.Type, arg0, arg1, arg2, arg3 *ssa.Value) *ssa.Value {
   436  	return s.curBlock.NewValue4(s.peekPos(), op, t, arg0, arg1, arg2, arg3)
   437  }
   438  
   439  // entryNewValue0 adds a new value with no arguments to the entry block.
   440  func (s *state) entryNewValue0(op ssa.Op, t *types.Type) *ssa.Value {
   441  	return s.f.Entry.NewValue0(src.NoXPos, op, t)
   442  }
   443  
   444  // entryNewValue0A adds a new value with no arguments and an aux value to the entry block.
   445  func (s *state) entryNewValue0A(op ssa.Op, t *types.Type, aux interface{}) *ssa.Value {
   446  	return s.f.Entry.NewValue0A(s.peekPos(), op, t, aux)
   447  }
   448  
   449  // entryNewValue1 adds a new value with one argument to the entry block.
   450  func (s *state) entryNewValue1(op ssa.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
   451  	return s.f.Entry.NewValue1(s.peekPos(), op, t, arg)
   452  }
   453  
   454  // entryNewValue1 adds a new value with one argument and an auxint value to the entry block.
   455  func (s *state) entryNewValue1I(op ssa.Op, t *types.Type, auxint int64, arg *ssa.Value) *ssa.Value {
   456  	return s.f.Entry.NewValue1I(s.peekPos(), op, t, auxint, arg)
   457  }
   458  
   459  // entryNewValue1A adds a new value with one argument and an aux value to the entry block.
   460  func (s *state) entryNewValue1A(op ssa.Op, t *types.Type, aux interface{}, arg *ssa.Value) *ssa.Value {
   461  	return s.f.Entry.NewValue1A(s.peekPos(), op, t, aux, arg)
   462  }
   463  
   464  // entryNewValue2 adds a new value with two arguments to the entry block.
   465  func (s *state) entryNewValue2(op ssa.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
   466  	return s.f.Entry.NewValue2(s.peekPos(), op, t, arg0, arg1)
   467  }
   468  
   469  // const* routines add a new const value to the entry block.
   470  func (s *state) constSlice(t *types.Type) *ssa.Value {
   471  	return s.f.ConstSlice(s.peekPos(), t)
   472  }
   473  func (s *state) constInterface(t *types.Type) *ssa.Value {
   474  	return s.f.ConstInterface(s.peekPos(), t)
   475  }
   476  func (s *state) constNil(t *types.Type) *ssa.Value { return s.f.ConstNil(s.peekPos(), t) }
   477  func (s *state) constEmptyString(t *types.Type) *ssa.Value {
   478  	return s.f.ConstEmptyString(s.peekPos(), t)
   479  }
   480  func (s *state) constBool(c bool) *ssa.Value {
   481  	return s.f.ConstBool(s.peekPos(), types.Types[TBOOL], c)
   482  }
   483  func (s *state) constInt8(t *types.Type, c int8) *ssa.Value {
   484  	return s.f.ConstInt8(s.peekPos(), t, c)
   485  }
   486  func (s *state) constInt16(t *types.Type, c int16) *ssa.Value {
   487  	return s.f.ConstInt16(s.peekPos(), t, c)
   488  }
   489  func (s *state) constInt32(t *types.Type, c int32) *ssa.Value {
   490  	return s.f.ConstInt32(s.peekPos(), t, c)
   491  }
   492  func (s *state) constInt64(t *types.Type, c int64) *ssa.Value {
   493  	return s.f.ConstInt64(s.peekPos(), t, c)
   494  }
   495  func (s *state) constFloat32(t *types.Type, c float64) *ssa.Value {
   496  	return s.f.ConstFloat32(s.peekPos(), t, c)
   497  }
   498  func (s *state) constFloat64(t *types.Type, c float64) *ssa.Value {
   499  	return s.f.ConstFloat64(s.peekPos(), t, c)
   500  }
   501  func (s *state) constInt(t *types.Type, c int64) *ssa.Value {
   502  	if s.config.PtrSize == 8 {
   503  		return s.constInt64(t, c)
   504  	}
   505  	if int64(int32(c)) != c {
   506  		s.Fatalf("integer constant too big %d", c)
   507  	}
   508  	return s.constInt32(t, int32(c))
   509  }
   510  func (s *state) constOffPtrSP(t *types.Type, c int64) *ssa.Value {
   511  	return s.f.ConstOffPtrSP(s.peekPos(), t, c, s.sp)
   512  }
   513  
   514  // stmtList converts the statement list n to SSA and adds it to s.
   515  func (s *state) stmtList(l Nodes) {
   516  	for _, n := range l.Slice() {
   517  		s.stmt(n)
   518  	}
   519  }
   520  
   521  // stmt converts the statement n to SSA and adds it to s.
   522  func (s *state) stmt(n *Node) {
   523  	s.pushLine(n.Pos)
   524  	defer s.popLine()
   525  
   526  	// If s.curBlock is nil, and n isn't a label (which might have an associated goto somewhere),
   527  	// then this code is dead. Stop here.
   528  	if s.curBlock == nil && n.Op != OLABEL {
   529  		return
   530  	}
   531  
   532  	s.stmtList(n.Ninit)
   533  	switch n.Op {
   534  
   535  	case OBLOCK:
   536  		s.stmtList(n.List)
   537  
   538  	// No-ops
   539  	case OEMPTY, ODCLCONST, ODCLTYPE, OFALL:
   540  
   541  	// Expression statements
   542  	case OCALLFUNC:
   543  		if isIntrinsicCall(n) {
   544  			s.intrinsicCall(n)
   545  			return
   546  		}
   547  		fallthrough
   548  
   549  	case OCALLMETH, OCALLINTER:
   550  		s.call(n, callNormal)
   551  		if n.Op == OCALLFUNC && n.Left.Op == ONAME && n.Left.Class() == PFUNC {
   552  			if fn := n.Left.Sym.Name; compiling_runtime && fn == "throw" ||
   553  				n.Left.Sym.Pkg == Runtimepkg && (fn == "throwinit" || fn == "gopanic" || fn == "panicwrap" || fn == "block") {
   554  				m := s.mem()
   555  				b := s.endBlock()
   556  				b.Kind = ssa.BlockExit
   557  				b.SetControl(m)
   558  				// TODO: never rewrite OPANIC to OCALLFUNC in the
   559  				// first place. Need to wait until all backends
   560  				// go through SSA.
   561  			}
   562  		}
   563  	case ODEFER:
   564  		s.call(n.Left, callDefer)
   565  	case OPROC:
   566  		s.call(n.Left, callGo)
   567  
   568  	case OAS2DOTTYPE:
   569  		res, resok := s.dottype(n.Rlist.First(), true)
   570  		deref := false
   571  		if !canSSAType(n.Rlist.First().Type) {
   572  			if res.Op != ssa.OpLoad {
   573  				s.Fatalf("dottype of non-load")
   574  			}
   575  			mem := s.mem()
   576  			if mem.Op == ssa.OpVarKill {
   577  				mem = mem.Args[0]
   578  			}
   579  			if res.Args[1] != mem {
   580  				s.Fatalf("memory no longer live from 2-result dottype load")
   581  			}
   582  			deref = true
   583  			res = res.Args[0]
   584  		}
   585  		s.assign(n.List.First(), res, deref, 0)
   586  		s.assign(n.List.Second(), resok, false, 0)
   587  		return
   588  
   589  	case OAS2FUNC:
   590  		// We come here only when it is an intrinsic call returning two values.
   591  		if !isIntrinsicCall(n.Rlist.First()) {
   592  			s.Fatalf("non-intrinsic AS2FUNC not expanded %v", n.Rlist.First())
   593  		}
   594  		v := s.intrinsicCall(n.Rlist.First())
   595  		v1 := s.newValue1(ssa.OpSelect0, n.List.First().Type, v)
   596  		v2 := s.newValue1(ssa.OpSelect1, n.List.Second().Type, v)
   597  		s.assign(n.List.First(), v1, false, 0)
   598  		s.assign(n.List.Second(), v2, false, 0)
   599  		return
   600  
   601  	case ODCL:
   602  		if n.Left.Class() == PAUTOHEAP {
   603  			Fatalf("DCL %v", n)
   604  		}
   605  
   606  	case OLABEL:
   607  		sym := n.Left.Sym
   608  		lab := s.label(sym)
   609  
   610  		// Associate label with its control flow node, if any
   611  		if ctl := n.labeledControl(); ctl != nil {
   612  			s.labeledNodes[ctl] = lab
   613  		}
   614  
   615  		// The label might already have a target block via a goto.
   616  		if lab.target == nil {
   617  			lab.target = s.f.NewBlock(ssa.BlockPlain)
   618  		}
   619  
   620  		// Go to that label.
   621  		// (We pretend "label:" is preceded by "goto label", unless the predecessor is unreachable.)
   622  		if s.curBlock != nil {
   623  			b := s.endBlock()
   624  			b.AddEdgeTo(lab.target)
   625  		}
   626  		s.startBlock(lab.target)
   627  
   628  	case OGOTO:
   629  		sym := n.Left.Sym
   630  
   631  		lab := s.label(sym)
   632  		if lab.target == nil {
   633  			lab.target = s.f.NewBlock(ssa.BlockPlain)
   634  		}
   635  
   636  		b := s.endBlock()
   637  		b.AddEdgeTo(lab.target)
   638  
   639  	case OAS:
   640  		if n.Left == n.Right && n.Left.Op == ONAME {
   641  			// An x=x assignment. No point in doing anything
   642  			// here. In addition, skipping this assignment
   643  			// prevents generating:
   644  			//   VARDEF x
   645  			//   COPY x -> x
   646  			// which is bad because x is incorrectly considered
   647  			// dead before the vardef. See issue #14904.
   648  			return
   649  		}
   650  
   651  		// Evaluate RHS.
   652  		rhs := n.Right
   653  		if rhs != nil {
   654  			switch rhs.Op {
   655  			case OSTRUCTLIT, OARRAYLIT, OSLICELIT:
   656  				// All literals with nonzero fields have already been
   657  				// rewritten during walk. Any that remain are just T{}
   658  				// or equivalents. Use the zero value.
   659  				if !iszero(rhs) {
   660  					Fatalf("literal with nonzero value in SSA: %v", rhs)
   661  				}
   662  				rhs = nil
   663  			case OAPPEND:
   664  				// Check whether we're writing the result of an append back to the same slice.
   665  				// If so, we handle it specially to avoid write barriers on the fast
   666  				// (non-growth) path.
   667  				if !samesafeexpr(n.Left, rhs.List.First()) {
   668  					break
   669  				}
   670  				// If the slice can be SSA'd, it'll be on the stack,
   671  				// so there will be no write barriers,
   672  				// so there's no need to attempt to prevent them.
   673  				if s.canSSA(n.Left) {
   674  					if Debug_append > 0 { // replicating old diagnostic message
   675  						Warnl(n.Pos, "append: len-only update (in local slice)")
   676  					}
   677  					break
   678  				}
   679  				if Debug_append > 0 {
   680  					Warnl(n.Pos, "append: len-only update")
   681  				}
   682  				s.append(rhs, true)
   683  				return
   684  			}
   685  		}
   686  
   687  		if isblank(n.Left) {
   688  			// _ = rhs
   689  			// Just evaluate rhs for side-effects.
   690  			if rhs != nil {
   691  				s.expr(rhs)
   692  			}
   693  			return
   694  		}
   695  
   696  		var t *types.Type
   697  		if n.Right != nil {
   698  			t = n.Right.Type
   699  		} else {
   700  			t = n.Left.Type
   701  		}
   702  
   703  		var r *ssa.Value
   704  		deref := !canSSAType(t)
   705  		if deref {
   706  			if rhs == nil {
   707  				r = nil // Signal assign to use OpZero.
   708  			} else {
   709  				r = s.addr(rhs, false)
   710  			}
   711  		} else {
   712  			if rhs == nil {
   713  				r = s.zeroVal(t)
   714  			} else {
   715  				r = s.expr(rhs)
   716  			}
   717  		}
   718  
   719  		var skip skipMask
   720  		if rhs != nil && (rhs.Op == OSLICE || rhs.Op == OSLICE3 || rhs.Op == OSLICESTR) && samesafeexpr(rhs.Left, n.Left) {
   721  			// We're assigning a slicing operation back to its source.
   722  			// Don't write back fields we aren't changing. See issue #14855.
   723  			i, j, k := rhs.SliceBounds()
   724  			if i != nil && (i.Op == OLITERAL && i.Val().Ctype() == CTINT && i.Int64() == 0) {
   725  				// [0:...] is the same as [:...]
   726  				i = nil
   727  			}
   728  			// TODO: detect defaults for len/cap also.
   729  			// Currently doesn't really work because (*p)[:len(*p)] appears here as:
   730  			//    tmp = len(*p)
   731  			//    (*p)[:tmp]
   732  			//if j != nil && (j.Op == OLEN && samesafeexpr(j.Left, n.Left)) {
   733  			//      j = nil
   734  			//}
   735  			//if k != nil && (k.Op == OCAP && samesafeexpr(k.Left, n.Left)) {
   736  			//      k = nil
   737  			//}
   738  			if i == nil {
   739  				skip |= skipPtr
   740  				if j == nil {
   741  					skip |= skipLen
   742  				}
   743  				if k == nil {
   744  					skip |= skipCap
   745  				}
   746  			}
   747  		}
   748  
   749  		s.assign(n.Left, r, deref, skip)
   750  
   751  	case OIF:
   752  		bThen := s.f.NewBlock(ssa.BlockPlain)
   753  		bEnd := s.f.NewBlock(ssa.BlockPlain)
   754  		var bElse *ssa.Block
   755  		var likely int8
   756  		if n.Likely() {
   757  			likely = 1
   758  		}
   759  		if n.Rlist.Len() != 0 {
   760  			bElse = s.f.NewBlock(ssa.BlockPlain)
   761  			s.condBranch(n.Left, bThen, bElse, likely)
   762  		} else {
   763  			s.condBranch(n.Left, bThen, bEnd, likely)
   764  		}
   765  
   766  		s.startBlock(bThen)
   767  		s.stmtList(n.Nbody)
   768  		if b := s.endBlock(); b != nil {
   769  			b.AddEdgeTo(bEnd)
   770  		}
   771  
   772  		if n.Rlist.Len() != 0 {
   773  			s.startBlock(bElse)
   774  			s.stmtList(n.Rlist)
   775  			if b := s.endBlock(); b != nil {
   776  				b.AddEdgeTo(bEnd)
   777  			}
   778  		}
   779  		s.startBlock(bEnd)
   780  
   781  	case ORETURN:
   782  		s.stmtList(n.List)
   783  		s.exit()
   784  	case ORETJMP:
   785  		s.stmtList(n.List)
   786  		b := s.exit()
   787  		b.Kind = ssa.BlockRetJmp // override BlockRet
   788  		b.Aux = n.Left.Sym.Linksym()
   789  
   790  	case OCONTINUE, OBREAK:
   791  		var to *ssa.Block
   792  		if n.Left == nil {
   793  			// plain break/continue
   794  			switch n.Op {
   795  			case OCONTINUE:
   796  				to = s.continueTo
   797  			case OBREAK:
   798  				to = s.breakTo
   799  			}
   800  		} else {
   801  			// labeled break/continue; look up the target
   802  			sym := n.Left.Sym
   803  			lab := s.label(sym)
   804  			switch n.Op {
   805  			case OCONTINUE:
   806  				to = lab.continueTarget
   807  			case OBREAK:
   808  				to = lab.breakTarget
   809  			}
   810  		}
   811  
   812  		b := s.endBlock()
   813  		b.AddEdgeTo(to)
   814  
   815  	case OFOR, OFORUNTIL:
   816  		// OFOR: for Ninit; Left; Right { Nbody }
   817  		// For      = cond; body; incr
   818  		// Foruntil = body; incr; cond
   819  		bCond := s.f.NewBlock(ssa.BlockPlain)
   820  		bBody := s.f.NewBlock(ssa.BlockPlain)
   821  		bIncr := s.f.NewBlock(ssa.BlockPlain)
   822  		bEnd := s.f.NewBlock(ssa.BlockPlain)
   823  
   824  		// first, jump to condition test (OFOR) or body (OFORUNTIL)
   825  		b := s.endBlock()
   826  		if n.Op == OFOR {
   827  			b.AddEdgeTo(bCond)
   828  			// generate code to test condition
   829  			s.startBlock(bCond)
   830  			if n.Left != nil {
   831  				s.condBranch(n.Left, bBody, bEnd, 1)
   832  			} else {
   833  				b := s.endBlock()
   834  				b.Kind = ssa.BlockPlain
   835  				b.AddEdgeTo(bBody)
   836  			}
   837  
   838  		} else {
   839  			b.AddEdgeTo(bBody)
   840  		}
   841  
   842  		// set up for continue/break in body
   843  		prevContinue := s.continueTo
   844  		prevBreak := s.breakTo
   845  		s.continueTo = bIncr
   846  		s.breakTo = bEnd
   847  		lab := s.labeledNodes[n]
   848  		if lab != nil {
   849  			// labeled for loop
   850  			lab.continueTarget = bIncr
   851  			lab.breakTarget = bEnd
   852  		}
   853  
   854  		// generate body
   855  		s.startBlock(bBody)
   856  		s.stmtList(n.Nbody)
   857  
   858  		// tear down continue/break
   859  		s.continueTo = prevContinue
   860  		s.breakTo = prevBreak
   861  		if lab != nil {
   862  			lab.continueTarget = nil
   863  			lab.breakTarget = nil
   864  		}
   865  
   866  		// done with body, goto incr
   867  		if b := s.endBlock(); b != nil {
   868  			b.AddEdgeTo(bIncr)
   869  		}
   870  
   871  		// generate incr
   872  		s.startBlock(bIncr)
   873  		if n.Right != nil {
   874  			s.stmt(n.Right)
   875  		}
   876  		if b := s.endBlock(); b != nil {
   877  			b.AddEdgeTo(bCond)
   878  		}
   879  
   880  		if n.Op == OFORUNTIL {
   881  			// generate code to test condition
   882  			s.startBlock(bCond)
   883  			if n.Left != nil {
   884  				s.condBranch(n.Left, bBody, bEnd, 1)
   885  			} else {
   886  				b := s.endBlock()
   887  				b.Kind = ssa.BlockPlain
   888  				b.AddEdgeTo(bBody)
   889  			}
   890  		}
   891  
   892  		s.startBlock(bEnd)
   893  
   894  	case OSWITCH, OSELECT:
   895  		// These have been mostly rewritten by the front end into their Nbody fields.
   896  		// Our main task is to correctly hook up any break statements.
   897  		bEnd := s.f.NewBlock(ssa.BlockPlain)
   898  
   899  		prevBreak := s.breakTo
   900  		s.breakTo = bEnd
   901  		lab := s.labeledNodes[n]
   902  		if lab != nil {
   903  			// labeled
   904  			lab.breakTarget = bEnd
   905  		}
   906  
   907  		// generate body code
   908  		s.stmtList(n.Nbody)
   909  
   910  		s.breakTo = prevBreak
   911  		if lab != nil {
   912  			lab.breakTarget = nil
   913  		}
   914  
   915  		// walk adds explicit OBREAK nodes to the end of all reachable code paths.
   916  		// If we still have a current block here, then mark it unreachable.
   917  		if s.curBlock != nil {
   918  			m := s.mem()
   919  			b := s.endBlock()
   920  			b.Kind = ssa.BlockExit
   921  			b.SetControl(m)
   922  		}
   923  		s.startBlock(bEnd)
   924  
   925  	case OVARKILL:
   926  		// Insert a varkill op to record that a variable is no longer live.
   927  		// We only care about liveness info at call sites, so putting the
   928  		// varkill in the store chain is enough to keep it correctly ordered
   929  		// with respect to call ops.
   930  		if !s.canSSA(n.Left) {
   931  			s.vars[&memVar] = s.newValue1A(ssa.OpVarKill, types.TypeMem, n.Left, s.mem())
   932  		}
   933  
   934  	case OVARLIVE:
   935  		// Insert a varlive op to record that a variable is still live.
   936  		if !n.Left.Addrtaken() {
   937  			s.Fatalf("VARLIVE variable %v must have Addrtaken set", n.Left)
   938  		}
   939  		var aux interface{}
   940  		switch n.Left.Class() {
   941  		case PAUTO:
   942  			aux = s.lookupSymbol(n.Left, &ssa.AutoSymbol{Node: n.Left})
   943  		case PPARAM, PPARAMOUT:
   944  			aux = s.lookupSymbol(n.Left, &ssa.ArgSymbol{Node: n.Left})
   945  		default:
   946  			s.Fatalf("VARLIVE variable %v must be Auto or Arg", n.Left)
   947  		}
   948  		s.vars[&memVar] = s.newValue1A(ssa.OpVarLive, types.TypeMem, aux, s.mem())
   949  
   950  	case OCHECKNIL:
   951  		p := s.expr(n.Left)
   952  		s.nilCheck(p)
   953  
   954  	default:
   955  		s.Fatalf("unhandled stmt %v", n.Op)
   956  	}
   957  }
   958  
   959  // exit processes any code that needs to be generated just before returning.
   960  // It returns a BlockRet block that ends the control flow. Its control value
   961  // will be set to the final memory state.
   962  func (s *state) exit() *ssa.Block {
   963  	if s.hasdefer {
   964  		s.rtcall(Deferreturn, true, nil)
   965  	}
   966  
   967  	// Run exit code. Typically, this code copies heap-allocated PPARAMOUT
   968  	// variables back to the stack.
   969  	s.stmtList(s.exitCode)
   970  
   971  	// Store SSAable PPARAMOUT variables back to stack locations.
   972  	for _, n := range s.returns {
   973  		addr := s.decladdrs[n]
   974  		val := s.variable(n, n.Type)
   975  		s.vars[&memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, n, s.mem())
   976  		s.vars[&memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, n.Type, addr, val, s.mem())
   977  		// TODO: if val is ever spilled, we'd like to use the
   978  		// PPARAMOUT slot for spilling it. That won't happen
   979  		// currently.
   980  	}
   981  
   982  	// Do actual return.
   983  	m := s.mem()
   984  	b := s.endBlock()
   985  	b.Kind = ssa.BlockRet
   986  	b.SetControl(m)
   987  	return b
   988  }
   989  
   990  type opAndType struct {
   991  	op    Op
   992  	etype types.EType
   993  }
   994  
   995  var opToSSA = map[opAndType]ssa.Op{
   996  	opAndType{OADD, TINT8}:    ssa.OpAdd8,
   997  	opAndType{OADD, TUINT8}:   ssa.OpAdd8,
   998  	opAndType{OADD, TINT16}:   ssa.OpAdd16,
   999  	opAndType{OADD, TUINT16}:  ssa.OpAdd16,
  1000  	opAndType{OADD, TINT32}:   ssa.OpAdd32,
  1001  	opAndType{OADD, TUINT32}:  ssa.OpAdd32,
  1002  	opAndType{OADD, TPTR32}:   ssa.OpAdd32,
  1003  	opAndType{OADD, TINT64}:   ssa.OpAdd64,
  1004  	opAndType{OADD, TUINT64}:  ssa.OpAdd64,
  1005  	opAndType{OADD, TPTR64}:   ssa.OpAdd64,
  1006  	opAndType{OADD, TFLOAT32}: ssa.OpAdd32F,
  1007  	opAndType{OADD, TFLOAT64}: ssa.OpAdd64F,
  1008  
  1009  	opAndType{OSUB, TINT8}:    ssa.OpSub8,
  1010  	opAndType{OSUB, TUINT8}:   ssa.OpSub8,
  1011  	opAndType{OSUB, TINT16}:   ssa.OpSub16,
  1012  	opAndType{OSUB, TUINT16}:  ssa.OpSub16,
  1013  	opAndType{OSUB, TINT32}:   ssa.OpSub32,
  1014  	opAndType{OSUB, TUINT32}:  ssa.OpSub32,
  1015  	opAndType{OSUB, TINT64}:   ssa.OpSub64,
  1016  	opAndType{OSUB, TUINT64}:  ssa.OpSub64,
  1017  	opAndType{OSUB, TFLOAT32}: ssa.OpSub32F,
  1018  	opAndType{OSUB, TFLOAT64}: ssa.OpSub64F,
  1019  
  1020  	opAndType{ONOT, TBOOL}: ssa.OpNot,
  1021  
  1022  	opAndType{OMINUS, TINT8}:    ssa.OpNeg8,
  1023  	opAndType{OMINUS, TUINT8}:   ssa.OpNeg8,
  1024  	opAndType{OMINUS, TINT16}:   ssa.OpNeg16,
  1025  	opAndType{OMINUS, TUINT16}:  ssa.OpNeg16,
  1026  	opAndType{OMINUS, TINT32}:   ssa.OpNeg32,
  1027  	opAndType{OMINUS, TUINT32}:  ssa.OpNeg32,
  1028  	opAndType{OMINUS, TINT64}:   ssa.OpNeg64,
  1029  	opAndType{OMINUS, TUINT64}:  ssa.OpNeg64,
  1030  	opAndType{OMINUS, TFLOAT32}: ssa.OpNeg32F,
  1031  	opAndType{OMINUS, TFLOAT64}: ssa.OpNeg64F,
  1032  
  1033  	opAndType{OCOM, TINT8}:   ssa.OpCom8,
  1034  	opAndType{OCOM, TUINT8}:  ssa.OpCom8,
  1035  	opAndType{OCOM, TINT16}:  ssa.OpCom16,
  1036  	opAndType{OCOM, TUINT16}: ssa.OpCom16,
  1037  	opAndType{OCOM, TINT32}:  ssa.OpCom32,
  1038  	opAndType{OCOM, TUINT32}: ssa.OpCom32,
  1039  	opAndType{OCOM, TINT64}:  ssa.OpCom64,
  1040  	opAndType{OCOM, TUINT64}: ssa.OpCom64,
  1041  
  1042  	opAndType{OIMAG, TCOMPLEX64}:  ssa.OpComplexImag,
  1043  	opAndType{OIMAG, TCOMPLEX128}: ssa.OpComplexImag,
  1044  	opAndType{OREAL, TCOMPLEX64}:  ssa.OpComplexReal,
  1045  	opAndType{OREAL, TCOMPLEX128}: ssa.OpComplexReal,
  1046  
  1047  	opAndType{OMUL, TINT8}:    ssa.OpMul8,
  1048  	opAndType{OMUL, TUINT8}:   ssa.OpMul8,
  1049  	opAndType{OMUL, TINT16}:   ssa.OpMul16,
  1050  	opAndType{OMUL, TUINT16}:  ssa.OpMul16,
  1051  	opAndType{OMUL, TINT32}:   ssa.OpMul32,
  1052  	opAndType{OMUL, TUINT32}:  ssa.OpMul32,
  1053  	opAndType{OMUL, TINT64}:   ssa.OpMul64,
  1054  	opAndType{OMUL, TUINT64}:  ssa.OpMul64,
  1055  	opAndType{OMUL, TFLOAT32}: ssa.OpMul32F,
  1056  	opAndType{OMUL, TFLOAT64}: ssa.OpMul64F,
  1057  
  1058  	opAndType{ODIV, TFLOAT32}: ssa.OpDiv32F,
  1059  	opAndType{ODIV, TFLOAT64}: ssa.OpDiv64F,
  1060  
  1061  	opAndType{ODIV, TINT8}:   ssa.OpDiv8,
  1062  	opAndType{ODIV, TUINT8}:  ssa.OpDiv8u,
  1063  	opAndType{ODIV, TINT16}:  ssa.OpDiv16,
  1064  	opAndType{ODIV, TUINT16}: ssa.OpDiv16u,
  1065  	opAndType{ODIV, TINT32}:  ssa.OpDiv32,
  1066  	opAndType{ODIV, TUINT32}: ssa.OpDiv32u,
  1067  	opAndType{ODIV, TINT64}:  ssa.OpDiv64,
  1068  	opAndType{ODIV, TUINT64}: ssa.OpDiv64u,
  1069  
  1070  	opAndType{OMOD, TINT8}:   ssa.OpMod8,
  1071  	opAndType{OMOD, TUINT8}:  ssa.OpMod8u,
  1072  	opAndType{OMOD, TINT16}:  ssa.OpMod16,
  1073  	opAndType{OMOD, TUINT16}: ssa.OpMod16u,
  1074  	opAndType{OMOD, TINT32}:  ssa.OpMod32,
  1075  	opAndType{OMOD, TUINT32}: ssa.OpMod32u,
  1076  	opAndType{OMOD, TINT64}:  ssa.OpMod64,
  1077  	opAndType{OMOD, TUINT64}: ssa.OpMod64u,
  1078  
  1079  	opAndType{OAND, TINT8}:   ssa.OpAnd8,
  1080  	opAndType{OAND, TUINT8}:  ssa.OpAnd8,
  1081  	opAndType{OAND, TINT16}:  ssa.OpAnd16,
  1082  	opAndType{OAND, TUINT16}: ssa.OpAnd16,
  1083  	opAndType{OAND, TINT32}:  ssa.OpAnd32,
  1084  	opAndType{OAND, TUINT32}: ssa.OpAnd32,
  1085  	opAndType{OAND, TINT64}:  ssa.OpAnd64,
  1086  	opAndType{OAND, TUINT64}: ssa.OpAnd64,
  1087  
  1088  	opAndType{OOR, TINT8}:   ssa.OpOr8,
  1089  	opAndType{OOR, TUINT8}:  ssa.OpOr8,
  1090  	opAndType{OOR, TINT16}:  ssa.OpOr16,
  1091  	opAndType{OOR, TUINT16}: ssa.OpOr16,
  1092  	opAndType{OOR, TINT32}:  ssa.OpOr32,
  1093  	opAndType{OOR, TUINT32}: ssa.OpOr32,
  1094  	opAndType{OOR, TINT64}:  ssa.OpOr64,
  1095  	opAndType{OOR, TUINT64}: ssa.OpOr64,
  1096  
  1097  	opAndType{OXOR, TINT8}:   ssa.OpXor8,
  1098  	opAndType{OXOR, TUINT8}:  ssa.OpXor8,
  1099  	opAndType{OXOR, TINT16}:  ssa.OpXor16,
  1100  	opAndType{OXOR, TUINT16}: ssa.OpXor16,
  1101  	opAndType{OXOR, TINT32}:  ssa.OpXor32,
  1102  	opAndType{OXOR, TUINT32}: ssa.OpXor32,
  1103  	opAndType{OXOR, TINT64}:  ssa.OpXor64,
  1104  	opAndType{OXOR, TUINT64}: ssa.OpXor64,
  1105  
  1106  	opAndType{OEQ, TBOOL}:      ssa.OpEqB,
  1107  	opAndType{OEQ, TINT8}:      ssa.OpEq8,
  1108  	opAndType{OEQ, TUINT8}:     ssa.OpEq8,
  1109  	opAndType{OEQ, TINT16}:     ssa.OpEq16,
  1110  	opAndType{OEQ, TUINT16}:    ssa.OpEq16,
  1111  	opAndType{OEQ, TINT32}:     ssa.OpEq32,
  1112  	opAndType{OEQ, TUINT32}:    ssa.OpEq32,
  1113  	opAndType{OEQ, TINT64}:     ssa.OpEq64,
  1114  	opAndType{OEQ, TUINT64}:    ssa.OpEq64,
  1115  	opAndType{OEQ, TINTER}:     ssa.OpEqInter,
  1116  	opAndType{OEQ, TSLICE}:     ssa.OpEqSlice,
  1117  	opAndType{OEQ, TFUNC}:      ssa.OpEqPtr,
  1118  	opAndType{OEQ, TMAP}:       ssa.OpEqPtr,
  1119  	opAndType{OEQ, TCHAN}:      ssa.OpEqPtr,
  1120  	opAndType{OEQ, TPTR32}:     ssa.OpEqPtr,
  1121  	opAndType{OEQ, TPTR64}:     ssa.OpEqPtr,
  1122  	opAndType{OEQ, TUINTPTR}:   ssa.OpEqPtr,
  1123  	opAndType{OEQ, TUNSAFEPTR}: ssa.OpEqPtr,
  1124  	opAndType{OEQ, TFLOAT64}:   ssa.OpEq64F,
  1125  	opAndType{OEQ, TFLOAT32}:   ssa.OpEq32F,
  1126  
  1127  	opAndType{ONE, TBOOL}:      ssa.OpNeqB,
  1128  	opAndType{ONE, TINT8}:      ssa.OpNeq8,
  1129  	opAndType{ONE, TUINT8}:     ssa.OpNeq8,
  1130  	opAndType{ONE, TINT16}:     ssa.OpNeq16,
  1131  	opAndType{ONE, TUINT16}:    ssa.OpNeq16,
  1132  	opAndType{ONE, TINT32}:     ssa.OpNeq32,
  1133  	opAndType{ONE, TUINT32}:    ssa.OpNeq32,
  1134  	opAndType{ONE, TINT64}:     ssa.OpNeq64,
  1135  	opAndType{ONE, TUINT64}:    ssa.OpNeq64,
  1136  	opAndType{ONE, TINTER}:     ssa.OpNeqInter,
  1137  	opAndType{ONE, TSLICE}:     ssa.OpNeqSlice,
  1138  	opAndType{ONE, TFUNC}:      ssa.OpNeqPtr,
  1139  	opAndType{ONE, TMAP}:       ssa.OpNeqPtr,
  1140  	opAndType{ONE, TCHAN}:      ssa.OpNeqPtr,
  1141  	opAndType{ONE, TPTR32}:     ssa.OpNeqPtr,
  1142  	opAndType{ONE, TPTR64}:     ssa.OpNeqPtr,
  1143  	opAndType{ONE, TUINTPTR}:   ssa.OpNeqPtr,
  1144  	opAndType{ONE, TUNSAFEPTR}: ssa.OpNeqPtr,
  1145  	opAndType{ONE, TFLOAT64}:   ssa.OpNeq64F,
  1146  	opAndType{ONE, TFLOAT32}:   ssa.OpNeq32F,
  1147  
  1148  	opAndType{OLT, TINT8}:    ssa.OpLess8,
  1149  	opAndType{OLT, TUINT8}:   ssa.OpLess8U,
  1150  	opAndType{OLT, TINT16}:   ssa.OpLess16,
  1151  	opAndType{OLT, TUINT16}:  ssa.OpLess16U,
  1152  	opAndType{OLT, TINT32}:   ssa.OpLess32,
  1153  	opAndType{OLT, TUINT32}:  ssa.OpLess32U,
  1154  	opAndType{OLT, TINT64}:   ssa.OpLess64,
  1155  	opAndType{OLT, TUINT64}:  ssa.OpLess64U,
  1156  	opAndType{OLT, TFLOAT64}: ssa.OpLess64F,
  1157  	opAndType{OLT, TFLOAT32}: ssa.OpLess32F,
  1158  
  1159  	opAndType{OGT, TINT8}:    ssa.OpGreater8,
  1160  	opAndType{OGT, TUINT8}:   ssa.OpGreater8U,
  1161  	opAndType{OGT, TINT16}:   ssa.OpGreater16,
  1162  	opAndType{OGT, TUINT16}:  ssa.OpGreater16U,
  1163  	opAndType{OGT, TINT32}:   ssa.OpGreater32,
  1164  	opAndType{OGT, TUINT32}:  ssa.OpGreater32U,
  1165  	opAndType{OGT, TINT64}:   ssa.OpGreater64,
  1166  	opAndType{OGT, TUINT64}:  ssa.OpGreater64U,
  1167  	opAndType{OGT, TFLOAT64}: ssa.OpGreater64F,
  1168  	opAndType{OGT, TFLOAT32}: ssa.OpGreater32F,
  1169  
  1170  	opAndType{OLE, TINT8}:    ssa.OpLeq8,
  1171  	opAndType{OLE, TUINT8}:   ssa.OpLeq8U,
  1172  	opAndType{OLE, TINT16}:   ssa.OpLeq16,
  1173  	opAndType{OLE, TUINT16}:  ssa.OpLeq16U,
  1174  	opAndType{OLE, TINT32}:   ssa.OpLeq32,
  1175  	opAndType{OLE, TUINT32}:  ssa.OpLeq32U,
  1176  	opAndType{OLE, TINT64}:   ssa.OpLeq64,
  1177  	opAndType{OLE, TUINT64}:  ssa.OpLeq64U,
  1178  	opAndType{OLE, TFLOAT64}: ssa.OpLeq64F,
  1179  	opAndType{OLE, TFLOAT32}: ssa.OpLeq32F,
  1180  
  1181  	opAndType{OGE, TINT8}:    ssa.OpGeq8,
  1182  	opAndType{OGE, TUINT8}:   ssa.OpGeq8U,
  1183  	opAndType{OGE, TINT16}:   ssa.OpGeq16,
  1184  	opAndType{OGE, TUINT16}:  ssa.OpGeq16U,
  1185  	opAndType{OGE, TINT32}:   ssa.OpGeq32,
  1186  	opAndType{OGE, TUINT32}:  ssa.OpGeq32U,
  1187  	opAndType{OGE, TINT64}:   ssa.OpGeq64,
  1188  	opAndType{OGE, TUINT64}:  ssa.OpGeq64U,
  1189  	opAndType{OGE, TFLOAT64}: ssa.OpGeq64F,
  1190  	opAndType{OGE, TFLOAT32}: ssa.OpGeq32F,
  1191  }
  1192  
  1193  func (s *state) concreteEtype(t *types.Type) types.EType {
  1194  	e := t.Etype
  1195  	switch e {
  1196  	default:
  1197  		return e
  1198  	case TINT:
  1199  		if s.config.PtrSize == 8 {
  1200  			return TINT64
  1201  		}
  1202  		return TINT32
  1203  	case TUINT:
  1204  		if s.config.PtrSize == 8 {
  1205  			return TUINT64
  1206  		}
  1207  		return TUINT32
  1208  	case TUINTPTR:
  1209  		if s.config.PtrSize == 8 {
  1210  			return TUINT64
  1211  		}
  1212  		return TUINT32
  1213  	}
  1214  }
  1215  
  1216  func (s *state) ssaOp(op Op, t *types.Type) ssa.Op {
  1217  	etype := s.concreteEtype(t)
  1218  	x, ok := opToSSA[opAndType{op, etype}]
  1219  	if !ok {
  1220  		s.Fatalf("unhandled binary op %v %s", op, etype)
  1221  	}
  1222  	return x
  1223  }
  1224  
  1225  func floatForComplex(t *types.Type) *types.Type {
  1226  	if t.Size() == 8 {
  1227  		return types.Types[TFLOAT32]
  1228  	} else {
  1229  		return types.Types[TFLOAT64]
  1230  	}
  1231  }
  1232  
  1233  type opAndTwoTypes struct {
  1234  	op     Op
  1235  	etype1 types.EType
  1236  	etype2 types.EType
  1237  }
  1238  
  1239  type twoTypes struct {
  1240  	etype1 types.EType
  1241  	etype2 types.EType
  1242  }
  1243  
  1244  type twoOpsAndType struct {
  1245  	op1              ssa.Op
  1246  	op2              ssa.Op
  1247  	intermediateType types.EType
  1248  }
  1249  
  1250  var fpConvOpToSSA = map[twoTypes]twoOpsAndType{
  1251  
  1252  	twoTypes{TINT8, TFLOAT32}:  twoOpsAndType{ssa.OpSignExt8to32, ssa.OpCvt32to32F, TINT32},
  1253  	twoTypes{TINT16, TFLOAT32}: twoOpsAndType{ssa.OpSignExt16to32, ssa.OpCvt32to32F, TINT32},
  1254  	twoTypes{TINT32, TFLOAT32}: twoOpsAndType{ssa.OpCopy, ssa.OpCvt32to32F, TINT32},
  1255  	twoTypes{TINT64, TFLOAT32}: twoOpsAndType{ssa.OpCopy, ssa.OpCvt64to32F, TINT64},
  1256  
  1257  	twoTypes{TINT8, TFLOAT64}:  twoOpsAndType{ssa.OpSignExt8to32, ssa.OpCvt32to64F, TINT32},
  1258  	twoTypes{TINT16, TFLOAT64}: twoOpsAndType{ssa.OpSignExt16to32, ssa.OpCvt32to64F, TINT32},
  1259  	twoTypes{TINT32, TFLOAT64}: twoOpsAndType{ssa.OpCopy, ssa.OpCvt32to64F, TINT32},
  1260  	twoTypes{TINT64, TFLOAT64}: twoOpsAndType{ssa.OpCopy, ssa.OpCvt64to64F, TINT64},
  1261  
  1262  	twoTypes{TFLOAT32, TINT8}:  twoOpsAndType{ssa.OpCvt32Fto32, ssa.OpTrunc32to8, TINT32},
  1263  	twoTypes{TFLOAT32, TINT16}: twoOpsAndType{ssa.OpCvt32Fto32, ssa.OpTrunc32to16, TINT32},
  1264  	twoTypes{TFLOAT32, TINT32}: twoOpsAndType{ssa.OpCvt32Fto32, ssa.OpCopy, TINT32},
  1265  	twoTypes{TFLOAT32, TINT64}: twoOpsAndType{ssa.OpCvt32Fto64, ssa.OpCopy, TINT64},
  1266  
  1267  	twoTypes{TFLOAT64, TINT8}:  twoOpsAndType{ssa.OpCvt64Fto32, ssa.OpTrunc32to8, TINT32},
  1268  	twoTypes{TFLOAT64, TINT16}: twoOpsAndType{ssa.OpCvt64Fto32, ssa.OpTrunc32to16, TINT32},
  1269  	twoTypes{TFLOAT64, TINT32}: twoOpsAndType{ssa.OpCvt64Fto32, ssa.OpCopy, TINT32},
  1270  	twoTypes{TFLOAT64, TINT64}: twoOpsAndType{ssa.OpCvt64Fto64, ssa.OpCopy, TINT64},
  1271  	// unsigned
  1272  	twoTypes{TUINT8, TFLOAT32}:  twoOpsAndType{ssa.OpZeroExt8to32, ssa.OpCvt32to32F, TINT32},
  1273  	twoTypes{TUINT16, TFLOAT32}: twoOpsAndType{ssa.OpZeroExt16to32, ssa.OpCvt32to32F, TINT32},
  1274  	twoTypes{TUINT32, TFLOAT32}: twoOpsAndType{ssa.OpZeroExt32to64, ssa.OpCvt64to32F, TINT64}, // go wide to dodge unsigned
  1275  	twoTypes{TUINT64, TFLOAT32}: twoOpsAndType{ssa.OpCopy, ssa.OpInvalid, TUINT64},            // Cvt64Uto32F, branchy code expansion instead
  1276  
  1277  	twoTypes{TUINT8, TFLOAT64}:  twoOpsAndType{ssa.OpZeroExt8to32, ssa.OpCvt32to64F, TINT32},
  1278  	twoTypes{TUINT16, TFLOAT64}: twoOpsAndType{ssa.OpZeroExt16to32, ssa.OpCvt32to64F, TINT32},
  1279  	twoTypes{TUINT32, TFLOAT64}: twoOpsAndType{ssa.OpZeroExt32to64, ssa.OpCvt64to64F, TINT64}, // go wide to dodge unsigned
  1280  	twoTypes{TUINT64, TFLOAT64}: twoOpsAndType{ssa.OpCopy, ssa.OpInvalid, TUINT64},            // Cvt64Uto64F, branchy code expansion instead
  1281  
  1282  	twoTypes{TFLOAT32, TUINT8}:  twoOpsAndType{ssa.OpCvt32Fto32, ssa.OpTrunc32to8, TINT32},
  1283  	twoTypes{TFLOAT32, TUINT16}: twoOpsAndType{ssa.OpCvt32Fto32, ssa.OpTrunc32to16, TINT32},
  1284  	twoTypes{TFLOAT32, TUINT32}: twoOpsAndType{ssa.OpCvt32Fto64, ssa.OpTrunc64to32, TINT64}, // go wide to dodge unsigned
  1285  	twoTypes{TFLOAT32, TUINT64}: twoOpsAndType{ssa.OpInvalid, ssa.OpCopy, TUINT64},          // Cvt32Fto64U, branchy code expansion instead
  1286  
  1287  	twoTypes{TFLOAT64, TUINT8}:  twoOpsAndType{ssa.OpCvt64Fto32, ssa.OpTrunc32to8, TINT32},
  1288  	twoTypes{TFLOAT64, TUINT16}: twoOpsAndType{ssa.OpCvt64Fto32, ssa.OpTrunc32to16, TINT32},
  1289  	twoTypes{TFLOAT64, TUINT32}: twoOpsAndType{ssa.OpCvt64Fto64, ssa.OpTrunc64to32, TINT64}, // go wide to dodge unsigned
  1290  	twoTypes{TFLOAT64, TUINT64}: twoOpsAndType{ssa.OpInvalid, ssa.OpCopy, TUINT64},          // Cvt64Fto64U, branchy code expansion instead
  1291  
  1292  	// float
  1293  	twoTypes{TFLOAT64, TFLOAT32}: twoOpsAndType{ssa.OpCvt64Fto32F, ssa.OpCopy, TFLOAT32},
  1294  	twoTypes{TFLOAT64, TFLOAT64}: twoOpsAndType{ssa.OpRound64F, ssa.OpCopy, TFLOAT64},
  1295  	twoTypes{TFLOAT32, TFLOAT32}: twoOpsAndType{ssa.OpRound32F, ssa.OpCopy, TFLOAT32},
  1296  	twoTypes{TFLOAT32, TFLOAT64}: twoOpsAndType{ssa.OpCvt32Fto64F, ssa.OpCopy, TFLOAT64},
  1297  }
  1298  
  1299  // this map is used only for 32-bit arch, and only includes the difference
  1300  // on 32-bit arch, don't use int64<->float conversion for uint32
  1301  var fpConvOpToSSA32 = map[twoTypes]twoOpsAndType{
  1302  	twoTypes{TUINT32, TFLOAT32}: twoOpsAndType{ssa.OpCopy, ssa.OpCvt32Uto32F, TUINT32},
  1303  	twoTypes{TUINT32, TFLOAT64}: twoOpsAndType{ssa.OpCopy, ssa.OpCvt32Uto64F, TUINT32},
  1304  	twoTypes{TFLOAT32, TUINT32}: twoOpsAndType{ssa.OpCvt32Fto32U, ssa.OpCopy, TUINT32},
  1305  	twoTypes{TFLOAT64, TUINT32}: twoOpsAndType{ssa.OpCvt64Fto32U, ssa.OpCopy, TUINT32},
  1306  }
  1307  
  1308  // uint64<->float conversions, only on machines that have intructions for that
  1309  var uint64fpConvOpToSSA = map[twoTypes]twoOpsAndType{
  1310  	twoTypes{TUINT64, TFLOAT32}: twoOpsAndType{ssa.OpCopy, ssa.OpCvt64Uto32F, TUINT64},
  1311  	twoTypes{TUINT64, TFLOAT64}: twoOpsAndType{ssa.OpCopy, ssa.OpCvt64Uto64F, TUINT64},
  1312  	twoTypes{TFLOAT32, TUINT64}: twoOpsAndType{ssa.OpCvt32Fto64U, ssa.OpCopy, TUINT64},
  1313  	twoTypes{TFLOAT64, TUINT64}: twoOpsAndType{ssa.OpCvt64Fto64U, ssa.OpCopy, TUINT64},
  1314  }
  1315  
  1316  var shiftOpToSSA = map[opAndTwoTypes]ssa.Op{
  1317  	opAndTwoTypes{OLSH, TINT8, TUINT8}:   ssa.OpLsh8x8,
  1318  	opAndTwoTypes{OLSH, TUINT8, TUINT8}:  ssa.OpLsh8x8,
  1319  	opAndTwoTypes{OLSH, TINT8, TUINT16}:  ssa.OpLsh8x16,
  1320  	opAndTwoTypes{OLSH, TUINT8, TUINT16}: ssa.OpLsh8x16,
  1321  	opAndTwoTypes{OLSH, TINT8, TUINT32}:  ssa.OpLsh8x32,
  1322  	opAndTwoTypes{OLSH, TUINT8, TUINT32}: ssa.OpLsh8x32,
  1323  	opAndTwoTypes{OLSH, TINT8, TUINT64}:  ssa.OpLsh8x64,
  1324  	opAndTwoTypes{OLSH, TUINT8, TUINT64}: ssa.OpLsh8x64,
  1325  
  1326  	opAndTwoTypes{OLSH, TINT16, TUINT8}:   ssa.OpLsh16x8,
  1327  	opAndTwoTypes{OLSH, TUINT16, TUINT8}:  ssa.OpLsh16x8,
  1328  	opAndTwoTypes{OLSH, TINT16, TUINT16}:  ssa.OpLsh16x16,
  1329  	opAndTwoTypes{OLSH, TUINT16, TUINT16}: ssa.OpLsh16x16,
  1330  	opAndTwoTypes{OLSH, TINT16, TUINT32}:  ssa.OpLsh16x32,
  1331  	opAndTwoTypes{OLSH, TUINT16, TUINT32}: ssa.OpLsh16x32,
  1332  	opAndTwoTypes{OLSH, TINT16, TUINT64}:  ssa.OpLsh16x64,
  1333  	opAndTwoTypes{OLSH, TUINT16, TUINT64}: ssa.OpLsh16x64,
  1334  
  1335  	opAndTwoTypes{OLSH, TINT32, TUINT8}:   ssa.OpLsh32x8,
  1336  	opAndTwoTypes{OLSH, TUINT32, TUINT8}:  ssa.OpLsh32x8,
  1337  	opAndTwoTypes{OLSH, TINT32, TUINT16}:  ssa.OpLsh32x16,
  1338  	opAndTwoTypes{OLSH, TUINT32, TUINT16}: ssa.OpLsh32x16,
  1339  	opAndTwoTypes{OLSH, TINT32, TUINT32}:  ssa.OpLsh32x32,
  1340  	opAndTwoTypes{OLSH, TUINT32, TUINT32}: ssa.OpLsh32x32,
  1341  	opAndTwoTypes{OLSH, TINT32, TUINT64}:  ssa.OpLsh32x64,
  1342  	opAndTwoTypes{OLSH, TUINT32, TUINT64}: ssa.OpLsh32x64,
  1343  
  1344  	opAndTwoTypes{OLSH, TINT64, TUINT8}:   ssa.OpLsh64x8,
  1345  	opAndTwoTypes{OLSH, TUINT64, TUINT8}:  ssa.OpLsh64x8,
  1346  	opAndTwoTypes{OLSH, TINT64, TUINT16}:  ssa.OpLsh64x16,
  1347  	opAndTwoTypes{OLSH, TUINT64, TUINT16}: ssa.OpLsh64x16,
  1348  	opAndTwoTypes{OLSH, TINT64, TUINT32}:  ssa.OpLsh64x32,
  1349  	opAndTwoTypes{OLSH, TUINT64, TUINT32}: ssa.OpLsh64x32,
  1350  	opAndTwoTypes{OLSH, TINT64, TUINT64}:  ssa.OpLsh64x64,
  1351  	opAndTwoTypes{OLSH, TUINT64, TUINT64}: ssa.OpLsh64x64,
  1352  
  1353  	opAndTwoTypes{ORSH, TINT8, TUINT8}:   ssa.OpRsh8x8,
  1354  	opAndTwoTypes{ORSH, TUINT8, TUINT8}:  ssa.OpRsh8Ux8,
  1355  	opAndTwoTypes{ORSH, TINT8, TUINT16}:  ssa.OpRsh8x16,
  1356  	opAndTwoTypes{ORSH, TUINT8, TUINT16}: ssa.OpRsh8Ux16,
  1357  	opAndTwoTypes{ORSH, TINT8, TUINT32}:  ssa.OpRsh8x32,
  1358  	opAndTwoTypes{ORSH, TUINT8, TUINT32}: ssa.OpRsh8Ux32,
  1359  	opAndTwoTypes{ORSH, TINT8, TUINT64}:  ssa.OpRsh8x64,
  1360  	opAndTwoTypes{ORSH, TUINT8, TUINT64}: ssa.OpRsh8Ux64,
  1361  
  1362  	opAndTwoTypes{ORSH, TINT16, TUINT8}:   ssa.OpRsh16x8,
  1363  	opAndTwoTypes{ORSH, TUINT16, TUINT8}:  ssa.OpRsh16Ux8,
  1364  	opAndTwoTypes{ORSH, TINT16, TUINT16}:  ssa.OpRsh16x16,
  1365  	opAndTwoTypes{ORSH, TUINT16, TUINT16}: ssa.OpRsh16Ux16,
  1366  	opAndTwoTypes{ORSH, TINT16, TUINT32}:  ssa.OpRsh16x32,
  1367  	opAndTwoTypes{ORSH, TUINT16, TUINT32}: ssa.OpRsh16Ux32,
  1368  	opAndTwoTypes{ORSH, TINT16, TUINT64}:  ssa.OpRsh16x64,
  1369  	opAndTwoTypes{ORSH, TUINT16, TUINT64}: ssa.OpRsh16Ux64,
  1370  
  1371  	opAndTwoTypes{ORSH, TINT32, TUINT8}:   ssa.OpRsh32x8,
  1372  	opAndTwoTypes{ORSH, TUINT32, TUINT8}:  ssa.OpRsh32Ux8,
  1373  	opAndTwoTypes{ORSH, TINT32, TUINT16}:  ssa.OpRsh32x16,
  1374  	opAndTwoTypes{ORSH, TUINT32, TUINT16}: ssa.OpRsh32Ux16,
  1375  	opAndTwoTypes{ORSH, TINT32, TUINT32}:  ssa.OpRsh32x32,
  1376  	opAndTwoTypes{ORSH, TUINT32, TUINT32}: ssa.OpRsh32Ux32,
  1377  	opAndTwoTypes{ORSH, TINT32, TUINT64}:  ssa.OpRsh32x64,
  1378  	opAndTwoTypes{ORSH, TUINT32, TUINT64}: ssa.OpRsh32Ux64,
  1379  
  1380  	opAndTwoTypes{ORSH, TINT64, TUINT8}:   ssa.OpRsh64x8,
  1381  	opAndTwoTypes{ORSH, TUINT64, TUINT8}:  ssa.OpRsh64Ux8,
  1382  	opAndTwoTypes{ORSH, TINT64, TUINT16}:  ssa.OpRsh64x16,
  1383  	opAndTwoTypes{ORSH, TUINT64, TUINT16}: ssa.OpRsh64Ux16,
  1384  	opAndTwoTypes{ORSH, TINT64, TUINT32}:  ssa.OpRsh64x32,
  1385  	opAndTwoTypes{ORSH, TUINT64, TUINT32}: ssa.OpRsh64Ux32,
  1386  	opAndTwoTypes{ORSH, TINT64, TUINT64}:  ssa.OpRsh64x64,
  1387  	opAndTwoTypes{ORSH, TUINT64, TUINT64}: ssa.OpRsh64Ux64,
  1388  }
  1389  
  1390  func (s *state) ssaShiftOp(op Op, t *types.Type, u *types.Type) ssa.Op {
  1391  	etype1 := s.concreteEtype(t)
  1392  	etype2 := s.concreteEtype(u)
  1393  	x, ok := shiftOpToSSA[opAndTwoTypes{op, etype1, etype2}]
  1394  	if !ok {
  1395  		s.Fatalf("unhandled shift op %v etype=%s/%s", op, etype1, etype2)
  1396  	}
  1397  	return x
  1398  }
  1399  
  1400  // expr converts the expression n to ssa, adds it to s and returns the ssa result.
  1401  func (s *state) expr(n *Node) *ssa.Value {
  1402  	if !(n.Op == ONAME || n.Op == OLITERAL && n.Sym != nil) {
  1403  		// ONAMEs and named OLITERALs have the line number
  1404  		// of the decl, not the use. See issue 14742.
  1405  		s.pushLine(n.Pos)
  1406  		defer s.popLine()
  1407  	}
  1408  
  1409  	s.stmtList(n.Ninit)
  1410  	switch n.Op {
  1411  	case OARRAYBYTESTRTMP:
  1412  		slice := s.expr(n.Left)
  1413  		ptr := s.newValue1(ssa.OpSlicePtr, s.f.Config.Types.BytePtr, slice)
  1414  		len := s.newValue1(ssa.OpSliceLen, types.Types[TINT], slice)
  1415  		return s.newValue2(ssa.OpStringMake, n.Type, ptr, len)
  1416  	case OSTRARRAYBYTETMP:
  1417  		str := s.expr(n.Left)
  1418  		ptr := s.newValue1(ssa.OpStringPtr, s.f.Config.Types.BytePtr, str)
  1419  		len := s.newValue1(ssa.OpStringLen, types.Types[TINT], str)
  1420  		return s.newValue3(ssa.OpSliceMake, n.Type, ptr, len, len)
  1421  	case OCFUNC:
  1422  		aux := s.lookupSymbol(n, &ssa.ExternSymbol{Sym: n.Left.Sym.Linksym()})
  1423  		return s.entryNewValue1A(ssa.OpAddr, n.Type, aux, s.sb)
  1424  	case ONAME:
  1425  		if n.Class() == PFUNC {
  1426  			// "value" of a function is the address of the function's closure
  1427  			sym := funcsym(n.Sym).Linksym()
  1428  			aux := s.lookupSymbol(n, &ssa.ExternSymbol{Sym: sym})
  1429  			return s.entryNewValue1A(ssa.OpAddr, types.NewPtr(n.Type), aux, s.sb)
  1430  		}
  1431  		if s.canSSA(n) {
  1432  			return s.variable(n, n.Type)
  1433  		}
  1434  		addr := s.addr(n, false)
  1435  		return s.newValue2(ssa.OpLoad, n.Type, addr, s.mem())
  1436  	case OCLOSUREVAR:
  1437  		addr := s.addr(n, false)
  1438  		return s.newValue2(ssa.OpLoad, n.Type, addr, s.mem())
  1439  	case OLITERAL:
  1440  		switch u := n.Val().U.(type) {
  1441  		case *Mpint:
  1442  			i := u.Int64()
  1443  			switch n.Type.Size() {
  1444  			case 1:
  1445  				return s.constInt8(n.Type, int8(i))
  1446  			case 2:
  1447  				return s.constInt16(n.Type, int16(i))
  1448  			case 4:
  1449  				return s.constInt32(n.Type, int32(i))
  1450  			case 8:
  1451  				return s.constInt64(n.Type, i)
  1452  			default:
  1453  				s.Fatalf("bad integer size %d", n.Type.Size())
  1454  				return nil
  1455  			}
  1456  		case string:
  1457  			if u == "" {
  1458  				return s.constEmptyString(n.Type)
  1459  			}
  1460  			return s.entryNewValue0A(ssa.OpConstString, n.Type, u)
  1461  		case bool:
  1462  			return s.constBool(u)
  1463  		case *NilVal:
  1464  			t := n.Type
  1465  			switch {
  1466  			case t.IsSlice():
  1467  				return s.constSlice(t)
  1468  			case t.IsInterface():
  1469  				return s.constInterface(t)
  1470  			default:
  1471  				return s.constNil(t)
  1472  			}
  1473  		case *Mpflt:
  1474  			switch n.Type.Size() {
  1475  			case 4:
  1476  				return s.constFloat32(n.Type, u.Float32())
  1477  			case 8:
  1478  				return s.constFloat64(n.Type, u.Float64())
  1479  			default:
  1480  				s.Fatalf("bad float size %d", n.Type.Size())
  1481  				return nil
  1482  			}
  1483  		case *Mpcplx:
  1484  			r := &u.Real
  1485  			i := &u.Imag
  1486  			switch n.Type.Size() {
  1487  			case 8:
  1488  				pt := types.Types[TFLOAT32]
  1489  				return s.newValue2(ssa.OpComplexMake, n.Type,
  1490  					s.constFloat32(pt, r.Float32()),
  1491  					s.constFloat32(pt, i.Float32()))
  1492  			case 16:
  1493  				pt := types.Types[TFLOAT64]
  1494  				return s.newValue2(ssa.OpComplexMake, n.Type,
  1495  					s.constFloat64(pt, r.Float64()),
  1496  					s.constFloat64(pt, i.Float64()))
  1497  			default:
  1498  				s.Fatalf("bad float size %d", n.Type.Size())
  1499  				return nil
  1500  			}
  1501  
  1502  		default:
  1503  			s.Fatalf("unhandled OLITERAL %v", n.Val().Ctype())
  1504  			return nil
  1505  		}
  1506  	case OCONVNOP:
  1507  		to := n.Type
  1508  		from := n.Left.Type
  1509  
  1510  		// Assume everything will work out, so set up our return value.
  1511  		// Anything interesting that happens from here is a fatal.
  1512  		x := s.expr(n.Left)
  1513  
  1514  		// Special case for not confusing GC and liveness.
  1515  		// We don't want pointers accidentally classified
  1516  		// as not-pointers or vice-versa because of copy
  1517  		// elision.
  1518  		if to.IsPtrShaped() != from.IsPtrShaped() {
  1519  			return s.newValue2(ssa.OpConvert, to, x, s.mem())
  1520  		}
  1521  
  1522  		v := s.newValue1(ssa.OpCopy, to, x) // ensure that v has the right type
  1523  
  1524  		// CONVNOP closure
  1525  		if to.Etype == TFUNC && from.IsPtrShaped() {
  1526  			return v
  1527  		}
  1528  
  1529  		// named <--> unnamed type or typed <--> untyped const
  1530  		if from.Etype == to.Etype {
  1531  			return v
  1532  		}
  1533  
  1534  		// unsafe.Pointer <--> *T
  1535  		if to.Etype == TUNSAFEPTR && from.IsPtr() || from.Etype == TUNSAFEPTR && to.IsPtr() {
  1536  			return v
  1537  		}
  1538  
  1539  		dowidth(from)
  1540  		dowidth(to)
  1541  		if from.Width != to.Width {
  1542  			s.Fatalf("CONVNOP width mismatch %v (%d) -> %v (%d)\n", from, from.Width, to, to.Width)
  1543  			return nil
  1544  		}
  1545  		if etypesign(from.Etype) != etypesign(to.Etype) {
  1546  			s.Fatalf("CONVNOP sign mismatch %v (%s) -> %v (%s)\n", from, from.Etype, to, to.Etype)
  1547  			return nil
  1548  		}
  1549  
  1550  		if instrumenting {
  1551  			// These appear to be fine, but they fail the
  1552  			// integer constraint below, so okay them here.
  1553  			// Sample non-integer conversion: map[string]string -> *uint8
  1554  			return v
  1555  		}
  1556  
  1557  		if etypesign(from.Etype) == 0 {
  1558  			s.Fatalf("CONVNOP unrecognized non-integer %v -> %v\n", from, to)
  1559  			return nil
  1560  		}
  1561  
  1562  		// integer, same width, same sign
  1563  		return v
  1564  
  1565  	case OCONV:
  1566  		x := s.expr(n.Left)
  1567  		ft := n.Left.Type // from type
  1568  		tt := n.Type      // to type
  1569  		if ft.IsBoolean() && tt.IsKind(TUINT8) {
  1570  			// Bool -> uint8 is generated internally when indexing into runtime.staticbyte.
  1571  			return s.newValue1(ssa.OpCopy, n.Type, x)
  1572  		}
  1573  		if ft.IsInteger() && tt.IsInteger() {
  1574  			var op ssa.Op
  1575  			if tt.Size() == ft.Size() {
  1576  				op = ssa.OpCopy
  1577  			} else if tt.Size() < ft.Size() {
  1578  				// truncation
  1579  				switch 10*ft.Size() + tt.Size() {
  1580  				case 21:
  1581  					op = ssa.OpTrunc16to8
  1582  				case 41:
  1583  					op = ssa.OpTrunc32to8
  1584  				case 42:
  1585  					op = ssa.OpTrunc32to16
  1586  				case 81:
  1587  					op = ssa.OpTrunc64to8
  1588  				case 82:
  1589  					op = ssa.OpTrunc64to16
  1590  				case 84:
  1591  					op = ssa.OpTrunc64to32
  1592  				default:
  1593  					s.Fatalf("weird integer truncation %v -> %v", ft, tt)
  1594  				}
  1595  			} else if ft.IsSigned() {
  1596  				// sign extension
  1597  				switch 10*ft.Size() + tt.Size() {
  1598  				case 12:
  1599  					op = ssa.OpSignExt8to16
  1600  				case 14:
  1601  					op = ssa.OpSignExt8to32
  1602  				case 18:
  1603  					op = ssa.OpSignExt8to64
  1604  				case 24:
  1605  					op = ssa.OpSignExt16to32
  1606  				case 28:
  1607  					op = ssa.OpSignExt16to64
  1608  				case 48:
  1609  					op = ssa.OpSignExt32to64
  1610  				default:
  1611  					s.Fatalf("bad integer sign extension %v -> %v", ft, tt)
  1612  				}
  1613  			} else {
  1614  				// zero extension
  1615  				switch 10*ft.Size() + tt.Size() {
  1616  				case 12:
  1617  					op = ssa.OpZeroExt8to16
  1618  				case 14:
  1619  					op = ssa.OpZeroExt8to32
  1620  				case 18:
  1621  					op = ssa.OpZeroExt8to64
  1622  				case 24:
  1623  					op = ssa.OpZeroExt16to32
  1624  				case 28:
  1625  					op = ssa.OpZeroExt16to64
  1626  				case 48:
  1627  					op = ssa.OpZeroExt32to64
  1628  				default:
  1629  					s.Fatalf("weird integer sign extension %v -> %v", ft, tt)
  1630  				}
  1631  			}
  1632  			return s.newValue1(op, n.Type, x)
  1633  		}
  1634  
  1635  		if ft.IsFloat() || tt.IsFloat() {
  1636  			conv, ok := fpConvOpToSSA[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]
  1637  			if s.config.RegSize == 4 && thearch.LinkArch.Family != sys.MIPS {
  1638  				if conv1, ok1 := fpConvOpToSSA32[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]; ok1 {
  1639  					conv = conv1
  1640  				}
  1641  			}
  1642  			if thearch.LinkArch.Family == sys.ARM64 {
  1643  				if conv1, ok1 := uint64fpConvOpToSSA[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]; ok1 {
  1644  					conv = conv1
  1645  				}
  1646  			}
  1647  
  1648  			if thearch.LinkArch.Family == sys.MIPS {
  1649  				if ft.Size() == 4 && ft.IsInteger() && !ft.IsSigned() {
  1650  					// tt is float32 or float64, and ft is also unsigned
  1651  					if tt.Size() == 4 {
  1652  						return s.uint32Tofloat32(n, x, ft, tt)
  1653  					}
  1654  					if tt.Size() == 8 {
  1655  						return s.uint32Tofloat64(n, x, ft, tt)
  1656  					}
  1657  				} else if tt.Size() == 4 && tt.IsInteger() && !tt.IsSigned() {
  1658  					// ft is float32 or float64, and tt is unsigned integer
  1659  					if ft.Size() == 4 {
  1660  						return s.float32ToUint32(n, x, ft, tt)
  1661  					}
  1662  					if ft.Size() == 8 {
  1663  						return s.float64ToUint32(n, x, ft, tt)
  1664  					}
  1665  				}
  1666  			}
  1667  
  1668  			if !ok {
  1669  				s.Fatalf("weird float conversion %v -> %v", ft, tt)
  1670  			}
  1671  			op1, op2, it := conv.op1, conv.op2, conv.intermediateType
  1672  
  1673  			if op1 != ssa.OpInvalid && op2 != ssa.OpInvalid {
  1674  				// normal case, not tripping over unsigned 64
  1675  				if op1 == ssa.OpCopy {
  1676  					if op2 == ssa.OpCopy {
  1677  						return x
  1678  					}
  1679  					return s.newValue1(op2, n.Type, x)
  1680  				}
  1681  				if op2 == ssa.OpCopy {
  1682  					return s.newValue1(op1, n.Type, x)
  1683  				}
  1684  				return s.newValue1(op2, n.Type, s.newValue1(op1, types.Types[it], x))
  1685  			}
  1686  			// Tricky 64-bit unsigned cases.
  1687  			if ft.IsInteger() {
  1688  				// tt is float32 or float64, and ft is also unsigned
  1689  				if tt.Size() == 4 {
  1690  					return s.uint64Tofloat32(n, x, ft, tt)
  1691  				}
  1692  				if tt.Size() == 8 {
  1693  					return s.uint64Tofloat64(n, x, ft, tt)
  1694  				}
  1695  				s.Fatalf("weird unsigned integer to float conversion %v -> %v", ft, tt)
  1696  			}
  1697  			// ft is float32 or float64, and tt is unsigned integer
  1698  			if ft.Size() == 4 {
  1699  				return s.float32ToUint64(n, x, ft, tt)
  1700  			}
  1701  			if ft.Size() == 8 {
  1702  				return s.float64ToUint64(n, x, ft, tt)
  1703  			}
  1704  			s.Fatalf("weird float to unsigned integer conversion %v -> %v", ft, tt)
  1705  			return nil
  1706  		}
  1707  
  1708  		if ft.IsComplex() && tt.IsComplex() {
  1709  			var op ssa.Op
  1710  			if ft.Size() == tt.Size() {
  1711  				switch ft.Size() {
  1712  				case 8:
  1713  					op = ssa.OpRound32F
  1714  				case 16:
  1715  					op = ssa.OpRound64F
  1716  				default:
  1717  					s.Fatalf("weird complex conversion %v -> %v", ft, tt)
  1718  				}
  1719  			} else if ft.Size() == 8 && tt.Size() == 16 {
  1720  				op = ssa.OpCvt32Fto64F
  1721  			} else if ft.Size() == 16 && tt.Size() == 8 {
  1722  				op = ssa.OpCvt64Fto32F
  1723  			} else {
  1724  				s.Fatalf("weird complex conversion %v -> %v", ft, tt)
  1725  			}
  1726  			ftp := floatForComplex(ft)
  1727  			ttp := floatForComplex(tt)
  1728  			return s.newValue2(ssa.OpComplexMake, tt,
  1729  				s.newValue1(op, ttp, s.newValue1(ssa.OpComplexReal, ftp, x)),
  1730  				s.newValue1(op, ttp, s.newValue1(ssa.OpComplexImag, ftp, x)))
  1731  		}
  1732  
  1733  		s.Fatalf("unhandled OCONV %s -> %s", n.Left.Type.Etype, n.Type.Etype)
  1734  		return nil
  1735  
  1736  	case ODOTTYPE:
  1737  		res, _ := s.dottype(n, false)
  1738  		return res
  1739  
  1740  	// binary ops
  1741  	case OLT, OEQ, ONE, OLE, OGE, OGT:
  1742  		a := s.expr(n.Left)
  1743  		b := s.expr(n.Right)
  1744  		if n.Left.Type.IsComplex() {
  1745  			pt := floatForComplex(n.Left.Type)
  1746  			op := s.ssaOp(OEQ, pt)
  1747  			r := s.newValue2(op, types.Types[TBOOL], s.newValue1(ssa.OpComplexReal, pt, a), s.newValue1(ssa.OpComplexReal, pt, b))
  1748  			i := s.newValue2(op, types.Types[TBOOL], s.newValue1(ssa.OpComplexImag, pt, a), s.newValue1(ssa.OpComplexImag, pt, b))
  1749  			c := s.newValue2(ssa.OpAndB, types.Types[TBOOL], r, i)
  1750  			switch n.Op {
  1751  			case OEQ:
  1752  				return c
  1753  			case ONE:
  1754  				return s.newValue1(ssa.OpNot, types.Types[TBOOL], c)
  1755  			default:
  1756  				s.Fatalf("ordered complex compare %v", n.Op)
  1757  			}
  1758  		}
  1759  		return s.newValue2(s.ssaOp(n.Op, n.Left.Type), types.Types[TBOOL], a, b)
  1760  	case OMUL:
  1761  		a := s.expr(n.Left)
  1762  		b := s.expr(n.Right)
  1763  		if n.Type.IsComplex() {
  1764  			mulop := ssa.OpMul64F
  1765  			addop := ssa.OpAdd64F
  1766  			subop := ssa.OpSub64F
  1767  			pt := floatForComplex(n.Type) // Could be Float32 or Float64
  1768  			wt := types.Types[TFLOAT64]   // Compute in Float64 to minimize cancelation error
  1769  
  1770  			areal := s.newValue1(ssa.OpComplexReal, pt, a)
  1771  			breal := s.newValue1(ssa.OpComplexReal, pt, b)
  1772  			aimag := s.newValue1(ssa.OpComplexImag, pt, a)
  1773  			bimag := s.newValue1(ssa.OpComplexImag, pt, b)
  1774  
  1775  			if pt != wt { // Widen for calculation
  1776  				areal = s.newValue1(ssa.OpCvt32Fto64F, wt, areal)
  1777  				breal = s.newValue1(ssa.OpCvt32Fto64F, wt, breal)
  1778  				aimag = s.newValue1(ssa.OpCvt32Fto64F, wt, aimag)
  1779  				bimag = s.newValue1(ssa.OpCvt32Fto64F, wt, bimag)
  1780  			}
  1781  
  1782  			xreal := s.newValue2(subop, wt, s.newValue2(mulop, wt, areal, breal), s.newValue2(mulop, wt, aimag, bimag))
  1783  			ximag := s.newValue2(addop, wt, s.newValue2(mulop, wt, areal, bimag), s.newValue2(mulop, wt, aimag, breal))
  1784  
  1785  			if pt != wt { // Narrow to store back
  1786  				xreal = s.newValue1(ssa.OpCvt64Fto32F, pt, xreal)
  1787  				ximag = s.newValue1(ssa.OpCvt64Fto32F, pt, ximag)
  1788  			}
  1789  
  1790  			return s.newValue2(ssa.OpComplexMake, n.Type, xreal, ximag)
  1791  		}
  1792  		return s.newValue2(s.ssaOp(n.Op, n.Type), a.Type, a, b)
  1793  
  1794  	case ODIV:
  1795  		a := s.expr(n.Left)
  1796  		b := s.expr(n.Right)
  1797  		if n.Type.IsComplex() {
  1798  			// TODO this is not executed because the front-end substitutes a runtime call.
  1799  			// That probably ought to change; with modest optimization the widen/narrow
  1800  			// conversions could all be elided in larger expression trees.
  1801  			mulop := ssa.OpMul64F
  1802  			addop := ssa.OpAdd64F
  1803  			subop := ssa.OpSub64F
  1804  			divop := ssa.OpDiv64F
  1805  			pt := floatForComplex(n.Type) // Could be Float32 or Float64
  1806  			wt := types.Types[TFLOAT64]   // Compute in Float64 to minimize cancelation error
  1807  
  1808  			areal := s.newValue1(ssa.OpComplexReal, pt, a)
  1809  			breal := s.newValue1(ssa.OpComplexReal, pt, b)
  1810  			aimag := s.newValue1(ssa.OpComplexImag, pt, a)
  1811  			bimag := s.newValue1(ssa.OpComplexImag, pt, b)
  1812  
  1813  			if pt != wt { // Widen for calculation
  1814  				areal = s.newValue1(ssa.OpCvt32Fto64F, wt, areal)
  1815  				breal = s.newValue1(ssa.OpCvt32Fto64F, wt, breal)
  1816  				aimag = s.newValue1(ssa.OpCvt32Fto64F, wt, aimag)
  1817  				bimag = s.newValue1(ssa.OpCvt32Fto64F, wt, bimag)
  1818  			}
  1819  
  1820  			denom := s.newValue2(addop, wt, s.newValue2(mulop, wt, breal, breal), s.newValue2(mulop, wt, bimag, bimag))
  1821  			xreal := s.newValue2(addop, wt, s.newValue2(mulop, wt, areal, breal), s.newValue2(mulop, wt, aimag, bimag))
  1822  			ximag := s.newValue2(subop, wt, s.newValue2(mulop, wt, aimag, breal), s.newValue2(mulop, wt, areal, bimag))
  1823  
  1824  			// TODO not sure if this is best done in wide precision or narrow
  1825  			// Double-rounding might be an issue.
  1826  			// Note that the pre-SSA implementation does the entire calculation
  1827  			// in wide format, so wide is compatible.
  1828  			xreal = s.newValue2(divop, wt, xreal, denom)
  1829  			ximag = s.newValue2(divop, wt, ximag, denom)
  1830  
  1831  			if pt != wt { // Narrow to store back
  1832  				xreal = s.newValue1(ssa.OpCvt64Fto32F, pt, xreal)
  1833  				ximag = s.newValue1(ssa.OpCvt64Fto32F, pt, ximag)
  1834  			}
  1835  			return s.newValue2(ssa.OpComplexMake, n.Type, xreal, ximag)
  1836  		}
  1837  		if n.Type.IsFloat() {
  1838  			return s.newValue2(s.ssaOp(n.Op, n.Type), a.Type, a, b)
  1839  		}
  1840  		return s.intDivide(n, a, b)
  1841  	case OMOD:
  1842  		a := s.expr(n.Left)
  1843  		b := s.expr(n.Right)
  1844  		return s.intDivide(n, a, b)
  1845  	case OADD, OSUB:
  1846  		a := s.expr(n.Left)
  1847  		b := s.expr(n.Right)
  1848  		if n.Type.IsComplex() {
  1849  			pt := floatForComplex(n.Type)
  1850  			op := s.ssaOp(n.Op, pt)
  1851  			return s.newValue2(ssa.OpComplexMake, n.Type,
  1852  				s.newValue2(op, pt, s.newValue1(ssa.OpComplexReal, pt, a), s.newValue1(ssa.OpComplexReal, pt, b)),
  1853  				s.newValue2(op, pt, s.newValue1(ssa.OpComplexImag, pt, a), s.newValue1(ssa.OpComplexImag, pt, b)))
  1854  		}
  1855  		return s.newValue2(s.ssaOp(n.Op, n.Type), a.Type, a, b)
  1856  	case OAND, OOR, OXOR:
  1857  		a := s.expr(n.Left)
  1858  		b := s.expr(n.Right)
  1859  		return s.newValue2(s.ssaOp(n.Op, n.Type), a.Type, a, b)
  1860  	case OLSH, ORSH:
  1861  		a := s.expr(n.Left)
  1862  		b := s.expr(n.Right)
  1863  		return s.newValue2(s.ssaShiftOp(n.Op, n.Type, n.Right.Type), a.Type, a, b)
  1864  	case OANDAND, OOROR:
  1865  		// To implement OANDAND (and OOROR), we introduce a
  1866  		// new temporary variable to hold the result. The
  1867  		// variable is associated with the OANDAND node in the
  1868  		// s.vars table (normally variables are only
  1869  		// associated with ONAME nodes). We convert
  1870  		//     A && B
  1871  		// to
  1872  		//     var = A
  1873  		//     if var {
  1874  		//         var = B
  1875  		//     }
  1876  		// Using var in the subsequent block introduces the
  1877  		// necessary phi variable.
  1878  		el := s.expr(n.Left)
  1879  		s.vars[n] = el
  1880  
  1881  		b := s.endBlock()
  1882  		b.Kind = ssa.BlockIf
  1883  		b.SetControl(el)
  1884  		// In theory, we should set b.Likely here based on context.
  1885  		// However, gc only gives us likeliness hints
  1886  		// in a single place, for plain OIF statements,
  1887  		// and passing around context is finnicky, so don't bother for now.
  1888  
  1889  		bRight := s.f.NewBlock(ssa.BlockPlain)
  1890  		bResult := s.f.NewBlock(ssa.BlockPlain)
  1891  		if n.Op == OANDAND {
  1892  			b.AddEdgeTo(bRight)
  1893  			b.AddEdgeTo(bResult)
  1894  		} else if n.Op == OOROR {
  1895  			b.AddEdgeTo(bResult)
  1896  			b.AddEdgeTo(bRight)
  1897  		}
  1898  
  1899  		s.startBlock(bRight)
  1900  		er := s.expr(n.Right)
  1901  		s.vars[n] = er
  1902  
  1903  		b = s.endBlock()
  1904  		b.AddEdgeTo(bResult)
  1905  
  1906  		s.startBlock(bResult)
  1907  		return s.variable(n, types.Types[TBOOL])
  1908  	case OCOMPLEX:
  1909  		r := s.expr(n.Left)
  1910  		i := s.expr(n.Right)
  1911  		return s.newValue2(ssa.OpComplexMake, n.Type, r, i)
  1912  
  1913  	// unary ops
  1914  	case OMINUS:
  1915  		a := s.expr(n.Left)
  1916  		if n.Type.IsComplex() {
  1917  			tp := floatForComplex(n.Type)
  1918  			negop := s.ssaOp(n.Op, tp)
  1919  			return s.newValue2(ssa.OpComplexMake, n.Type,
  1920  				s.newValue1(negop, tp, s.newValue1(ssa.OpComplexReal, tp, a)),
  1921  				s.newValue1(negop, tp, s.newValue1(ssa.OpComplexImag, tp, a)))
  1922  		}
  1923  		return s.newValue1(s.ssaOp(n.Op, n.Type), a.Type, a)
  1924  	case ONOT, OCOM:
  1925  		a := s.expr(n.Left)
  1926  		return s.newValue1(s.ssaOp(n.Op, n.Type), a.Type, a)
  1927  	case OIMAG, OREAL:
  1928  		a := s.expr(n.Left)
  1929  		return s.newValue1(s.ssaOp(n.Op, n.Left.Type), n.Type, a)
  1930  	case OPLUS:
  1931  		return s.expr(n.Left)
  1932  
  1933  	case OADDR:
  1934  		return s.addr(n.Left, n.Bounded())
  1935  
  1936  	case OINDREGSP:
  1937  		addr := s.constOffPtrSP(types.NewPtr(n.Type), n.Xoffset)
  1938  		return s.newValue2(ssa.OpLoad, n.Type, addr, s.mem())
  1939  
  1940  	case OIND:
  1941  		p := s.exprPtr(n.Left, false, n.Pos)
  1942  		return s.newValue2(ssa.OpLoad, n.Type, p, s.mem())
  1943  
  1944  	case ODOT:
  1945  		t := n.Left.Type
  1946  		if canSSAType(t) {
  1947  			v := s.expr(n.Left)
  1948  			return s.newValue1I(ssa.OpStructSelect, n.Type, int64(fieldIdx(n)), v)
  1949  		}
  1950  		if n.Left.Op == OSTRUCTLIT {
  1951  			// All literals with nonzero fields have already been
  1952  			// rewritten during walk. Any that remain are just T{}
  1953  			// or equivalents. Use the zero value.
  1954  			if !iszero(n.Left) {
  1955  				Fatalf("literal with nonzero value in SSA: %v", n.Left)
  1956  			}
  1957  			return s.zeroVal(n.Type)
  1958  		}
  1959  		p := s.addr(n, false)
  1960  		return s.newValue2(ssa.OpLoad, n.Type, p, s.mem())
  1961  
  1962  	case ODOTPTR:
  1963  		p := s.exprPtr(n.Left, false, n.Pos)
  1964  		p = s.newValue1I(ssa.OpOffPtr, types.NewPtr(n.Type), n.Xoffset, p)
  1965  		return s.newValue2(ssa.OpLoad, n.Type, p, s.mem())
  1966  
  1967  	case OINDEX:
  1968  		switch {
  1969  		case n.Left.Type.IsString():
  1970  			if n.Bounded() && Isconst(n.Left, CTSTR) && Isconst(n.Right, CTINT) {
  1971  				// Replace "abc"[1] with 'b'.
  1972  				// Delayed until now because "abc"[1] is not an ideal constant.
  1973  				// See test/fixedbugs/issue11370.go.
  1974  				return s.newValue0I(ssa.OpConst8, types.Types[TUINT8], int64(int8(n.Left.Val().U.(string)[n.Right.Int64()])))
  1975  			}
  1976  			a := s.expr(n.Left)
  1977  			i := s.expr(n.Right)
  1978  			i = s.extendIndex(i, panicindex)
  1979  			if !n.Bounded() {
  1980  				len := s.newValue1(ssa.OpStringLen, types.Types[TINT], a)
  1981  				s.boundsCheck(i, len)
  1982  			}
  1983  			ptrtyp := s.f.Config.Types.BytePtr
  1984  			ptr := s.newValue1(ssa.OpStringPtr, ptrtyp, a)
  1985  			if Isconst(n.Right, CTINT) {
  1986  				ptr = s.newValue1I(ssa.OpOffPtr, ptrtyp, n.Right.Int64(), ptr)
  1987  			} else {
  1988  				ptr = s.newValue2(ssa.OpAddPtr, ptrtyp, ptr, i)
  1989  			}
  1990  			return s.newValue2(ssa.OpLoad, types.Types[TUINT8], ptr, s.mem())
  1991  		case n.Left.Type.IsSlice():
  1992  			p := s.addr(n, false)
  1993  			return s.newValue2(ssa.OpLoad, n.Left.Type.Elem(), p, s.mem())
  1994  		case n.Left.Type.IsArray():
  1995  			if bound := n.Left.Type.NumElem(); bound <= 1 {
  1996  				// SSA can handle arrays of length at most 1.
  1997  				a := s.expr(n.Left)
  1998  				i := s.expr(n.Right)
  1999  				if bound == 0 {
  2000  					// Bounds check will never succeed.  Might as well
  2001  					// use constants for the bounds check.
  2002  					z := s.constInt(types.Types[TINT], 0)
  2003  					s.boundsCheck(z, z)
  2004  					// The return value won't be live, return junk.
  2005  					return s.newValue0(ssa.OpUnknown, n.Type)
  2006  				}
  2007  				i = s.extendIndex(i, panicindex)
  2008  				if !n.Bounded() {
  2009  					s.boundsCheck(i, s.constInt(types.Types[TINT], bound))
  2010  				}
  2011  				return s.newValue1I(ssa.OpArraySelect, n.Type, 0, a)
  2012  			}
  2013  			p := s.addr(n, false)
  2014  			return s.newValue2(ssa.OpLoad, n.Left.Type.Elem(), p, s.mem())
  2015  		default:
  2016  			s.Fatalf("bad type for index %v", n.Left.Type)
  2017  			return nil
  2018  		}
  2019  
  2020  	case OLEN, OCAP:
  2021  		switch {
  2022  		case n.Left.Type.IsSlice():
  2023  			op := ssa.OpSliceLen
  2024  			if n.Op == OCAP {
  2025  				op = ssa.OpSliceCap
  2026  			}
  2027  			return s.newValue1(op, types.Types[TINT], s.expr(n.Left))
  2028  		case n.Left.Type.IsString(): // string; not reachable for OCAP
  2029  			return s.newValue1(ssa.OpStringLen, types.Types[TINT], s.expr(n.Left))
  2030  		case n.Left.Type.IsMap(), n.Left.Type.IsChan():
  2031  			return s.referenceTypeBuiltin(n, s.expr(n.Left))
  2032  		default: // array
  2033  			return s.constInt(types.Types[TINT], n.Left.Type.NumElem())
  2034  		}
  2035  
  2036  	case OSPTR:
  2037  		a := s.expr(n.Left)
  2038  		if n.Left.Type.IsSlice() {
  2039  			return s.newValue1(ssa.OpSlicePtr, n.Type, a)
  2040  		} else {
  2041  			return s.newValue1(ssa.OpStringPtr, n.Type, a)
  2042  		}
  2043  
  2044  	case OITAB:
  2045  		a := s.expr(n.Left)
  2046  		return s.newValue1(ssa.OpITab, n.Type, a)
  2047  
  2048  	case OIDATA:
  2049  		a := s.expr(n.Left)
  2050  		return s.newValue1(ssa.OpIData, n.Type, a)
  2051  
  2052  	case OEFACE:
  2053  		tab := s.expr(n.Left)
  2054  		data := s.expr(n.Right)
  2055  		return s.newValue2(ssa.OpIMake, n.Type, tab, data)
  2056  
  2057  	case OSLICE, OSLICEARR, OSLICE3, OSLICE3ARR:
  2058  		v := s.expr(n.Left)
  2059  		var i, j, k *ssa.Value
  2060  		low, high, max := n.SliceBounds()
  2061  		if low != nil {
  2062  			i = s.extendIndex(s.expr(low), panicslice)
  2063  		}
  2064  		if high != nil {
  2065  			j = s.extendIndex(s.expr(high), panicslice)
  2066  		}
  2067  		if max != nil {
  2068  			k = s.extendIndex(s.expr(max), panicslice)
  2069  		}
  2070  		p, l, c := s.slice(n.Left.Type, v, i, j, k)
  2071  		return s.newValue3(ssa.OpSliceMake, n.Type, p, l, c)
  2072  
  2073  	case OSLICESTR:
  2074  		v := s.expr(n.Left)
  2075  		var i, j *ssa.Value
  2076  		low, high, _ := n.SliceBounds()
  2077  		if low != nil {
  2078  			i = s.extendIndex(s.expr(low), panicslice)
  2079  		}
  2080  		if high != nil {
  2081  			j = s.extendIndex(s.expr(high), panicslice)
  2082  		}
  2083  		p, l, _ := s.slice(n.Left.Type, v, i, j, nil)
  2084  		return s.newValue2(ssa.OpStringMake, n.Type, p, l)
  2085  
  2086  	case OCALLFUNC:
  2087  		if isIntrinsicCall(n) {
  2088  			return s.intrinsicCall(n)
  2089  		}
  2090  		fallthrough
  2091  
  2092  	case OCALLINTER, OCALLMETH:
  2093  		a := s.call(n, callNormal)
  2094  		return s.newValue2(ssa.OpLoad, n.Type, a, s.mem())
  2095  
  2096  	case OGETG:
  2097  		return s.newValue1(ssa.OpGetG, n.Type, s.mem())
  2098  
  2099  	case OAPPEND:
  2100  		return s.append(n, false)
  2101  
  2102  	case OSTRUCTLIT, OARRAYLIT:
  2103  		// All literals with nonzero fields have already been
  2104  		// rewritten during walk. Any that remain are just T{}
  2105  		// or equivalents. Use the zero value.
  2106  		if !iszero(n) {
  2107  			Fatalf("literal with nonzero value in SSA: %v", n)
  2108  		}
  2109  		return s.zeroVal(n.Type)
  2110  
  2111  	default:
  2112  		s.Fatalf("unhandled expr %v", n.Op)
  2113  		return nil
  2114  	}
  2115  }
  2116  
  2117  // append converts an OAPPEND node to SSA.
  2118  // If inplace is false, it converts the OAPPEND expression n to an ssa.Value,
  2119  // adds it to s, and returns the Value.
  2120  // If inplace is true, it writes the result of the OAPPEND expression n
  2121  // back to the slice being appended to, and returns nil.
  2122  // inplace MUST be set to false if the slice can be SSA'd.
  2123  func (s *state) append(n *Node, inplace bool) *ssa.Value {
  2124  	// If inplace is false, process as expression "append(s, e1, e2, e3)":
  2125  	//
  2126  	// ptr, len, cap := s
  2127  	// newlen := len + 3
  2128  	// if newlen > cap {
  2129  	//     ptr, len, cap = growslice(s, newlen)
  2130  	//     newlen = len + 3 // recalculate to avoid a spill
  2131  	// }
  2132  	// // with write barriers, if needed:
  2133  	// *(ptr+len) = e1
  2134  	// *(ptr+len+1) = e2
  2135  	// *(ptr+len+2) = e3
  2136  	// return makeslice(ptr, newlen, cap)
  2137  	//
  2138  	//
  2139  	// If inplace is true, process as statement "s = append(s, e1, e2, e3)":
  2140  	//
  2141  	// a := &s
  2142  	// ptr, len, cap := s
  2143  	// newlen := len + 3
  2144  	// if newlen > cap {
  2145  	//    newptr, len, newcap = growslice(ptr, len, cap, newlen)
  2146  	//    vardef(a)       // if necessary, advise liveness we are writing a new a
  2147  	//    *a.cap = newcap // write before ptr to avoid a spill
  2148  	//    *a.ptr = newptr // with write barrier
  2149  	// }
  2150  	// newlen = len + 3 // recalculate to avoid a spill
  2151  	// *a.len = newlen
  2152  	// // with write barriers, if needed:
  2153  	// *(ptr+len) = e1
  2154  	// *(ptr+len+1) = e2
  2155  	// *(ptr+len+2) = e3
  2156  
  2157  	et := n.Type.Elem()
  2158  	pt := types.NewPtr(et)
  2159  
  2160  	// Evaluate slice
  2161  	sn := n.List.First() // the slice node is the first in the list
  2162  
  2163  	var slice, addr *ssa.Value
  2164  	if inplace {
  2165  		addr = s.addr(sn, false)
  2166  		slice = s.newValue2(ssa.OpLoad, n.Type, addr, s.mem())
  2167  	} else {
  2168  		slice = s.expr(sn)
  2169  	}
  2170  
  2171  	// Allocate new blocks
  2172  	grow := s.f.NewBlock(ssa.BlockPlain)
  2173  	assign := s.f.NewBlock(ssa.BlockPlain)
  2174  
  2175  	// Decide if we need to grow
  2176  	nargs := int64(n.List.Len() - 1)
  2177  	p := s.newValue1(ssa.OpSlicePtr, pt, slice)
  2178  	l := s.newValue1(ssa.OpSliceLen, types.Types[TINT], slice)
  2179  	c := s.newValue1(ssa.OpSliceCap, types.Types[TINT], slice)
  2180  	nl := s.newValue2(s.ssaOp(OADD, types.Types[TINT]), types.Types[TINT], l, s.constInt(types.Types[TINT], nargs))
  2181  
  2182  	cmp := s.newValue2(s.ssaOp(OGT, types.Types[TINT]), types.Types[TBOOL], nl, c)
  2183  	s.vars[&ptrVar] = p
  2184  
  2185  	if !inplace {
  2186  		s.vars[&newlenVar] = nl
  2187  		s.vars[&capVar] = c
  2188  	} else {
  2189  		s.vars[&lenVar] = l
  2190  	}
  2191  
  2192  	b := s.endBlock()
  2193  	b.Kind = ssa.BlockIf
  2194  	b.Likely = ssa.BranchUnlikely
  2195  	b.SetControl(cmp)
  2196  	b.AddEdgeTo(grow)
  2197  	b.AddEdgeTo(assign)
  2198  
  2199  	// Call growslice
  2200  	s.startBlock(grow)
  2201  	taddr := s.expr(n.Left)
  2202  	r := s.rtcall(growslice, true, []*types.Type{pt, types.Types[TINT], types.Types[TINT]}, taddr, p, l, c, nl)
  2203  
  2204  	if inplace {
  2205  		if sn.Op == ONAME {
  2206  			// Tell liveness we're about to build a new slice
  2207  			s.vars[&memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, sn, s.mem())
  2208  		}
  2209  		capaddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, int64(array_cap), addr)
  2210  		s.vars[&memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, types.Types[TINT], capaddr, r[2], s.mem())
  2211  		s.vars[&memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, pt, addr, r[0], s.mem())
  2212  		// load the value we just stored to avoid having to spill it
  2213  		s.vars[&ptrVar] = s.newValue2(ssa.OpLoad, pt, addr, s.mem())
  2214  		s.vars[&lenVar] = r[1] // avoid a spill in the fast path
  2215  	} else {
  2216  		s.vars[&ptrVar] = r[0]
  2217  		s.vars[&newlenVar] = s.newValue2(s.ssaOp(OADD, types.Types[TINT]), types.Types[TINT], r[1], s.constInt(types.Types[TINT], nargs))
  2218  		s.vars[&capVar] = r[2]
  2219  	}
  2220  
  2221  	b = s.endBlock()
  2222  	b.AddEdgeTo(assign)
  2223  
  2224  	// assign new elements to slots
  2225  	s.startBlock(assign)
  2226  
  2227  	if inplace {
  2228  		l = s.variable(&lenVar, types.Types[TINT]) // generates phi for len
  2229  		nl = s.newValue2(s.ssaOp(OADD, types.Types[TINT]), types.Types[TINT], l, s.constInt(types.Types[TINT], nargs))
  2230  		lenaddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, int64(array_nel), addr)
  2231  		s.vars[&memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, types.Types[TINT], lenaddr, nl, s.mem())
  2232  	}
  2233  
  2234  	// Evaluate args
  2235  	type argRec struct {
  2236  		// if store is true, we're appending the value v.  If false, we're appending the
  2237  		// value at *v.
  2238  		v     *ssa.Value
  2239  		store bool
  2240  	}
  2241  	args := make([]argRec, 0, nargs)
  2242  	for _, n := range n.List.Slice()[1:] {
  2243  		if canSSAType(n.Type) {
  2244  			args = append(args, argRec{v: s.expr(n), store: true})
  2245  		} else {
  2246  			v := s.addr(n, false)
  2247  			args = append(args, argRec{v: v})
  2248  		}
  2249  	}
  2250  
  2251  	p = s.variable(&ptrVar, pt) // generates phi for ptr
  2252  	if !inplace {
  2253  		nl = s.variable(&newlenVar, types.Types[TINT]) // generates phi for nl
  2254  		c = s.variable(&capVar, types.Types[TINT])     // generates phi for cap
  2255  	}
  2256  	p2 := s.newValue2(ssa.OpPtrIndex, pt, p, l)
  2257  	for i, arg := range args {
  2258  		addr := s.newValue2(ssa.OpPtrIndex, pt, p2, s.constInt(types.Types[TINT], int64(i)))
  2259  		if arg.store {
  2260  			s.storeType(et, addr, arg.v, 0)
  2261  		} else {
  2262  			store := s.newValue3I(ssa.OpMove, types.TypeMem, et.Size(), addr, arg.v, s.mem())
  2263  			store.Aux = et
  2264  			s.vars[&memVar] = store
  2265  		}
  2266  	}
  2267  
  2268  	delete(s.vars, &ptrVar)
  2269  	if inplace {
  2270  		delete(s.vars, &lenVar)
  2271  		return nil
  2272  	}
  2273  	delete(s.vars, &newlenVar)
  2274  	delete(s.vars, &capVar)
  2275  	// make result
  2276  	return s.newValue3(ssa.OpSliceMake, n.Type, p, nl, c)
  2277  }
  2278  
  2279  // condBranch evaluates the boolean expression cond and branches to yes
  2280  // if cond is true and no if cond is false.
  2281  // This function is intended to handle && and || better than just calling
  2282  // s.expr(cond) and branching on the result.
  2283  func (s *state) condBranch(cond *Node, yes, no *ssa.Block, likely int8) {
  2284  	if cond.Op == OANDAND {
  2285  		mid := s.f.NewBlock(ssa.BlockPlain)
  2286  		s.stmtList(cond.Ninit)
  2287  		s.condBranch(cond.Left, mid, no, max8(likely, 0))
  2288  		s.startBlock(mid)
  2289  		s.condBranch(cond.Right, yes, no, likely)
  2290  		return
  2291  		// Note: if likely==1, then both recursive calls pass 1.
  2292  		// If likely==-1, then we don't have enough information to decide
  2293  		// whether the first branch is likely or not. So we pass 0 for
  2294  		// the likeliness of the first branch.
  2295  		// TODO: have the frontend give us branch prediction hints for
  2296  		// OANDAND and OOROR nodes (if it ever has such info).
  2297  	}
  2298  	if cond.Op == OOROR {
  2299  		mid := s.f.NewBlock(ssa.BlockPlain)
  2300  		s.stmtList(cond.Ninit)
  2301  		s.condBranch(cond.Left, yes, mid, min8(likely, 0))
  2302  		s.startBlock(mid)
  2303  		s.condBranch(cond.Right, yes, no, likely)
  2304  		return
  2305  		// Note: if likely==-1, then both recursive calls pass -1.
  2306  		// If likely==1, then we don't have enough info to decide
  2307  		// the likelihood of the first branch.
  2308  	}
  2309  	if cond.Op == ONOT {
  2310  		s.stmtList(cond.Ninit)
  2311  		s.condBranch(cond.Left, no, yes, -likely)
  2312  		return
  2313  	}
  2314  	c := s.expr(cond)
  2315  	b := s.endBlock()
  2316  	b.Kind = ssa.BlockIf
  2317  	b.SetControl(c)
  2318  	b.Likely = ssa.BranchPrediction(likely) // gc and ssa both use -1/0/+1 for likeliness
  2319  	b.AddEdgeTo(yes)
  2320  	b.AddEdgeTo(no)
  2321  }
  2322  
  2323  type skipMask uint8
  2324  
  2325  const (
  2326  	skipPtr skipMask = 1 << iota
  2327  	skipLen
  2328  	skipCap
  2329  )
  2330  
  2331  // assign does left = right.
  2332  // Right has already been evaluated to ssa, left has not.
  2333  // If deref is true, then we do left = *right instead (and right has already been nil-checked).
  2334  // If deref is true and right == nil, just do left = 0.
  2335  // skip indicates assignments (at the top level) that can be avoided.
  2336  func (s *state) assign(left *Node, right *ssa.Value, deref bool, skip skipMask) {
  2337  	if left.Op == ONAME && isblank(left) {
  2338  		return
  2339  	}
  2340  	t := left.Type
  2341  	dowidth(t)
  2342  	if s.canSSA(left) {
  2343  		if deref {
  2344  			s.Fatalf("can SSA LHS %v but not RHS %s", left, right)
  2345  		}
  2346  		if left.Op == ODOT {
  2347  			// We're assigning to a field of an ssa-able value.
  2348  			// We need to build a new structure with the new value for the
  2349  			// field we're assigning and the old values for the other fields.
  2350  			// For instance:
  2351  			//   type T struct {a, b, c int}
  2352  			//   var T x
  2353  			//   x.b = 5
  2354  			// For the x.b = 5 assignment we want to generate x = T{x.a, 5, x.c}
  2355  
  2356  			// Grab information about the structure type.
  2357  			t := left.Left.Type
  2358  			nf := t.NumFields()
  2359  			idx := fieldIdx(left)
  2360  
  2361  			// Grab old value of structure.
  2362  			old := s.expr(left.Left)
  2363  
  2364  			// Make new structure.
  2365  			new := s.newValue0(ssa.StructMakeOp(t.NumFields()), t)
  2366  
  2367  			// Add fields as args.
  2368  			for i := 0; i < nf; i++ {
  2369  				if i == idx {
  2370  					new.AddArg(right)
  2371  				} else {
  2372  					new.AddArg(s.newValue1I(ssa.OpStructSelect, t.FieldType(i), int64(i), old))
  2373  				}
  2374  			}
  2375  
  2376  			// Recursively assign the new value we've made to the base of the dot op.
  2377  			s.assign(left.Left, new, false, 0)
  2378  			// TODO: do we need to update named values here?
  2379  			return
  2380  		}
  2381  		if left.Op == OINDEX && left.Left.Type.IsArray() {
  2382  			// We're assigning to an element of an ssa-able array.
  2383  			// a[i] = v
  2384  			t := left.Left.Type
  2385  			n := t.NumElem()
  2386  
  2387  			i := s.expr(left.Right) // index
  2388  			if n == 0 {
  2389  				// The bounds check must fail.  Might as well
  2390  				// ignore the actual index and just use zeros.
  2391  				z := s.constInt(types.Types[TINT], 0)
  2392  				s.boundsCheck(z, z)
  2393  				return
  2394  			}
  2395  			if n != 1 {
  2396  				s.Fatalf("assigning to non-1-length array")
  2397  			}
  2398  			// Rewrite to a = [1]{v}
  2399  			i = s.extendIndex(i, panicindex)
  2400  			s.boundsCheck(i, s.constInt(types.Types[TINT], 1))
  2401  			v := s.newValue1(ssa.OpArrayMake1, t, right)
  2402  			s.assign(left.Left, v, false, 0)
  2403  			return
  2404  		}
  2405  		// Update variable assignment.
  2406  		s.vars[left] = right
  2407  		s.addNamedValue(left, right)
  2408  		return
  2409  	}
  2410  	// Left is not ssa-able. Compute its address.
  2411  	addr := s.addr(left, false)
  2412  	if left.Op == ONAME && skip == 0 {
  2413  		s.vars[&memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, left, s.mem())
  2414  	}
  2415  	if isReflectHeaderDataField(left) {
  2416  		// Package unsafe's documentation says storing pointers into
  2417  		// reflect.SliceHeader and reflect.StringHeader's Data fields
  2418  		// is valid, even though they have type uintptr (#19168).
  2419  		// Mark it pointer type to signal the writebarrier pass to
  2420  		// insert a write barrier.
  2421  		t = types.Types[TUNSAFEPTR]
  2422  	}
  2423  	if deref {
  2424  		// Treat as a mem->mem move.
  2425  		var store *ssa.Value
  2426  		if right == nil {
  2427  			store = s.newValue2I(ssa.OpZero, types.TypeMem, t.Size(), addr, s.mem())
  2428  		} else {
  2429  			store = s.newValue3I(ssa.OpMove, types.TypeMem, t.Size(), addr, right, s.mem())
  2430  		}
  2431  		store.Aux = t
  2432  		s.vars[&memVar] = store
  2433  		return
  2434  	}
  2435  	// Treat as a store.
  2436  	s.storeType(t, addr, right, skip)
  2437  }
  2438  
  2439  // zeroVal returns the zero value for type t.
  2440  func (s *state) zeroVal(t *types.Type) *ssa.Value {
  2441  	switch {
  2442  	case t.IsInteger():
  2443  		switch t.Size() {
  2444  		case 1:
  2445  			return s.constInt8(t, 0)
  2446  		case 2:
  2447  			return s.constInt16(t, 0)
  2448  		case 4:
  2449  			return s.constInt32(t, 0)
  2450  		case 8:
  2451  			return s.constInt64(t, 0)
  2452  		default:
  2453  			s.Fatalf("bad sized integer type %v", t)
  2454  		}
  2455  	case t.IsFloat():
  2456  		switch t.Size() {
  2457  		case 4:
  2458  			return s.constFloat32(t, 0)
  2459  		case 8:
  2460  			return s.constFloat64(t, 0)
  2461  		default:
  2462  			s.Fatalf("bad sized float type %v", t)
  2463  		}
  2464  	case t.IsComplex():
  2465  		switch t.Size() {
  2466  		case 8:
  2467  			z := s.constFloat32(types.Types[TFLOAT32], 0)
  2468  			return s.entryNewValue2(ssa.OpComplexMake, t, z, z)
  2469  		case 16:
  2470  			z := s.constFloat64(types.Types[TFLOAT64], 0)
  2471  			return s.entryNewValue2(ssa.OpComplexMake, t, z, z)
  2472  		default:
  2473  			s.Fatalf("bad sized complex type %v", t)
  2474  		}
  2475  
  2476  	case t.IsString():
  2477  		return s.constEmptyString(t)
  2478  	case t.IsPtrShaped():
  2479  		return s.constNil(t)
  2480  	case t.IsBoolean():
  2481  		return s.constBool(false)
  2482  	case t.IsInterface():
  2483  		return s.constInterface(t)
  2484  	case t.IsSlice():
  2485  		return s.constSlice(t)
  2486  	case t.IsStruct():
  2487  		n := t.NumFields()
  2488  		v := s.entryNewValue0(ssa.StructMakeOp(t.NumFields()), t)
  2489  		for i := 0; i < n; i++ {
  2490  			v.AddArg(s.zeroVal(t.FieldType(i)))
  2491  		}
  2492  		return v
  2493  	case t.IsArray():
  2494  		switch t.NumElem() {
  2495  		case 0:
  2496  			return s.entryNewValue0(ssa.OpArrayMake0, t)
  2497  		case 1:
  2498  			return s.entryNewValue1(ssa.OpArrayMake1, t, s.zeroVal(t.Elem()))
  2499  		}
  2500  	}
  2501  	s.Fatalf("zero for type %v not implemented", t)
  2502  	return nil
  2503  }
  2504  
  2505  type callKind int8
  2506  
  2507  const (
  2508  	callNormal callKind = iota
  2509  	callDefer
  2510  	callGo
  2511  )
  2512  
  2513  var intrinsics map[intrinsicKey]intrinsicBuilder
  2514  
  2515  // An intrinsicBuilder converts a call node n into an ssa value that
  2516  // implements that call as an intrinsic. args is a list of arguments to the func.
  2517  type intrinsicBuilder func(s *state, n *Node, args []*ssa.Value) *ssa.Value
  2518  
  2519  type intrinsicKey struct {
  2520  	arch *sys.Arch
  2521  	pkg  string
  2522  	fn   string
  2523  }
  2524  
  2525  func init() {
  2526  	intrinsics = map[intrinsicKey]intrinsicBuilder{}
  2527  
  2528  	var all []*sys.Arch
  2529  	var p4 []*sys.Arch
  2530  	var p8 []*sys.Arch
  2531  	for _, a := range sys.Archs {
  2532  		all = append(all, a)
  2533  		if a.PtrSize == 4 {
  2534  			p4 = append(p4, a)
  2535  		} else {
  2536  			p8 = append(p8, a)
  2537  		}
  2538  	}
  2539  
  2540  	// add adds the intrinsic b for pkg.fn for the given list of architectures.
  2541  	add := func(pkg, fn string, b intrinsicBuilder, archs ...*sys.Arch) {
  2542  		for _, a := range archs {
  2543  			intrinsics[intrinsicKey{a, pkg, fn}] = b
  2544  		}
  2545  	}
  2546  	// addF does the same as add but operates on architecture families.
  2547  	addF := func(pkg, fn string, b intrinsicBuilder, archFamilies ...sys.ArchFamily) {
  2548  		m := 0
  2549  		for _, f := range archFamilies {
  2550  			if f >= 32 {
  2551  				panic("too many architecture families")
  2552  			}
  2553  			m |= 1 << uint(f)
  2554  		}
  2555  		for _, a := range all {
  2556  			if m>>uint(a.Family)&1 != 0 {
  2557  				intrinsics[intrinsicKey{a, pkg, fn}] = b
  2558  			}
  2559  		}
  2560  	}
  2561  	// alias defines pkg.fn = pkg2.fn2 for all architectures in archs for which pkg2.fn2 exists.
  2562  	alias := func(pkg, fn, pkg2, fn2 string, archs ...*sys.Arch) {
  2563  		for _, a := range archs {
  2564  			if b, ok := intrinsics[intrinsicKey{a, pkg2, fn2}]; ok {
  2565  				intrinsics[intrinsicKey{a, pkg, fn}] = b
  2566  			}
  2567  		}
  2568  	}
  2569  
  2570  	/******** runtime ********/
  2571  	if !instrumenting {
  2572  		add("runtime", "slicebytetostringtmp",
  2573  			func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2574  				// Compiler frontend optimizations emit OARRAYBYTESTRTMP nodes
  2575  				// for the backend instead of slicebytetostringtmp calls
  2576  				// when not instrumenting.
  2577  				slice := args[0]
  2578  				ptr := s.newValue1(ssa.OpSlicePtr, s.f.Config.Types.BytePtr, slice)
  2579  				len := s.newValue1(ssa.OpSliceLen, types.Types[TINT], slice)
  2580  				return s.newValue2(ssa.OpStringMake, n.Type, ptr, len)
  2581  			},
  2582  			all...)
  2583  	}
  2584  	add("runtime", "KeepAlive",
  2585  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2586  			data := s.newValue1(ssa.OpIData, s.f.Config.Types.BytePtr, args[0])
  2587  			s.vars[&memVar] = s.newValue2(ssa.OpKeepAlive, types.TypeMem, data, s.mem())
  2588  			return nil
  2589  		},
  2590  		all...)
  2591  	add("runtime", "getclosureptr",
  2592  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2593  			return s.newValue0(ssa.OpGetClosurePtr, s.f.Config.Types.Uintptr)
  2594  		},
  2595  		all...)
  2596  
  2597  	/******** runtime/internal/sys ********/
  2598  	addF("runtime/internal/sys", "Ctz32",
  2599  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2600  			return s.newValue1(ssa.OpCtz32, types.Types[TINT], args[0])
  2601  		},
  2602  		sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS)
  2603  	addF("runtime/internal/sys", "Ctz64",
  2604  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2605  			return s.newValue1(ssa.OpCtz64, types.Types[TINT], args[0])
  2606  		},
  2607  		sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS)
  2608  	addF("runtime/internal/sys", "Bswap32",
  2609  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2610  			return s.newValue1(ssa.OpBswap32, types.Types[TUINT32], args[0])
  2611  		},
  2612  		sys.AMD64, sys.ARM64, sys.ARM, sys.S390X)
  2613  	addF("runtime/internal/sys", "Bswap64",
  2614  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2615  			return s.newValue1(ssa.OpBswap64, types.Types[TUINT64], args[0])
  2616  		},
  2617  		sys.AMD64, sys.ARM64, sys.ARM, sys.S390X)
  2618  
  2619  	/******** runtime/internal/atomic ********/
  2620  	addF("runtime/internal/atomic", "Load",
  2621  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2622  			v := s.newValue2(ssa.OpAtomicLoad32, types.NewTuple(types.Types[TUINT32], types.TypeMem), args[0], s.mem())
  2623  			s.vars[&memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
  2624  			return s.newValue1(ssa.OpSelect0, types.Types[TUINT32], v)
  2625  		},
  2626  		sys.AMD64, sys.ARM64, sys.S390X, sys.MIPS, sys.PPC64)
  2627  
  2628  	addF("runtime/internal/atomic", "Load64",
  2629  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2630  			v := s.newValue2(ssa.OpAtomicLoad64, types.NewTuple(types.Types[TUINT64], types.TypeMem), args[0], s.mem())
  2631  			s.vars[&memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
  2632  			return s.newValue1(ssa.OpSelect0, types.Types[TUINT64], v)
  2633  		},
  2634  		sys.AMD64, sys.ARM64, sys.S390X, sys.PPC64)
  2635  	addF("runtime/internal/atomic", "Loadp",
  2636  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2637  			v := s.newValue2(ssa.OpAtomicLoadPtr, types.NewTuple(s.f.Config.Types.BytePtr, types.TypeMem), args[0], s.mem())
  2638  			s.vars[&memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
  2639  			return s.newValue1(ssa.OpSelect0, s.f.Config.Types.BytePtr, v)
  2640  		},
  2641  		sys.AMD64, sys.ARM64, sys.S390X, sys.MIPS, sys.PPC64)
  2642  
  2643  	addF("runtime/internal/atomic", "Store",
  2644  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2645  			s.vars[&memVar] = s.newValue3(ssa.OpAtomicStore32, types.TypeMem, args[0], args[1], s.mem())
  2646  			return nil
  2647  		},
  2648  		sys.AMD64, sys.ARM64, sys.S390X, sys.MIPS, sys.PPC64)
  2649  	addF("runtime/internal/atomic", "Store64",
  2650  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2651  			s.vars[&memVar] = s.newValue3(ssa.OpAtomicStore64, types.TypeMem, args[0], args[1], s.mem())
  2652  			return nil
  2653  		},
  2654  		sys.AMD64, sys.ARM64, sys.S390X, sys.PPC64)
  2655  	addF("runtime/internal/atomic", "StorepNoWB",
  2656  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2657  			s.vars[&memVar] = s.newValue3(ssa.OpAtomicStorePtrNoWB, types.TypeMem, args[0], args[1], s.mem())
  2658  			return nil
  2659  		},
  2660  		sys.AMD64, sys.ARM64, sys.S390X, sys.MIPS)
  2661  
  2662  	addF("runtime/internal/atomic", "Xchg",
  2663  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2664  			v := s.newValue3(ssa.OpAtomicExchange32, types.NewTuple(types.Types[TUINT32], types.TypeMem), args[0], args[1], s.mem())
  2665  			s.vars[&memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
  2666  			return s.newValue1(ssa.OpSelect0, types.Types[TUINT32], v)
  2667  		},
  2668  		sys.AMD64, sys.ARM64, sys.S390X, sys.MIPS, sys.PPC64)
  2669  	addF("runtime/internal/atomic", "Xchg64",
  2670  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2671  			v := s.newValue3(ssa.OpAtomicExchange64, types.NewTuple(types.Types[TUINT64], types.TypeMem), args[0], args[1], s.mem())
  2672  			s.vars[&memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
  2673  			return s.newValue1(ssa.OpSelect0, types.Types[TUINT64], v)
  2674  		},
  2675  		sys.AMD64, sys.ARM64, sys.S390X, sys.PPC64)
  2676  
  2677  	addF("runtime/internal/atomic", "Xadd",
  2678  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2679  			v := s.newValue3(ssa.OpAtomicAdd32, types.NewTuple(types.Types[TUINT32], types.TypeMem), args[0], args[1], s.mem())
  2680  			s.vars[&memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
  2681  			return s.newValue1(ssa.OpSelect0, types.Types[TUINT32], v)
  2682  		},
  2683  		sys.AMD64, sys.ARM64, sys.S390X, sys.MIPS, sys.PPC64)
  2684  	addF("runtime/internal/atomic", "Xadd64",
  2685  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2686  			v := s.newValue3(ssa.OpAtomicAdd64, types.NewTuple(types.Types[TUINT64], types.TypeMem), args[0], args[1], s.mem())
  2687  			s.vars[&memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
  2688  			return s.newValue1(ssa.OpSelect0, types.Types[TUINT64], v)
  2689  		},
  2690  		sys.AMD64, sys.ARM64, sys.S390X, sys.PPC64)
  2691  
  2692  	addF("runtime/internal/atomic", "Cas",
  2693  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2694  			v := s.newValue4(ssa.OpAtomicCompareAndSwap32, types.NewTuple(types.Types[TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
  2695  			s.vars[&memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
  2696  			return s.newValue1(ssa.OpSelect0, types.Types[TBOOL], v)
  2697  		},
  2698  		sys.AMD64, sys.ARM64, sys.S390X, sys.MIPS, sys.PPC64)
  2699  	addF("runtime/internal/atomic", "Cas64",
  2700  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2701  			v := s.newValue4(ssa.OpAtomicCompareAndSwap64, types.NewTuple(types.Types[TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
  2702  			s.vars[&memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
  2703  			return s.newValue1(ssa.OpSelect0, types.Types[TBOOL], v)
  2704  		},
  2705  		sys.AMD64, sys.ARM64, sys.S390X, sys.PPC64)
  2706  
  2707  	addF("runtime/internal/atomic", "And8",
  2708  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2709  			s.vars[&memVar] = s.newValue3(ssa.OpAtomicAnd8, types.TypeMem, args[0], args[1], s.mem())
  2710  			return nil
  2711  		},
  2712  		sys.AMD64, sys.ARM64, sys.MIPS, sys.PPC64)
  2713  	addF("runtime/internal/atomic", "Or8",
  2714  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2715  			s.vars[&memVar] = s.newValue3(ssa.OpAtomicOr8, types.TypeMem, args[0], args[1], s.mem())
  2716  			return nil
  2717  		},
  2718  		sys.AMD64, sys.ARM64, sys.MIPS, sys.PPC64)
  2719  
  2720  	alias("runtime/internal/atomic", "Loadint64", "runtime/internal/atomic", "Load64", all...)
  2721  	alias("runtime/internal/atomic", "Xaddint64", "runtime/internal/atomic", "Xadd64", all...)
  2722  	alias("runtime/internal/atomic", "Loaduint", "runtime/internal/atomic", "Load", p4...)
  2723  	alias("runtime/internal/atomic", "Loaduint", "runtime/internal/atomic", "Load64", p8...)
  2724  	alias("runtime/internal/atomic", "Loaduintptr", "runtime/internal/atomic", "Load", p4...)
  2725  	alias("runtime/internal/atomic", "Loaduintptr", "runtime/internal/atomic", "Load64", p8...)
  2726  	alias("runtime/internal/atomic", "Storeuintptr", "runtime/internal/atomic", "Store", p4...)
  2727  	alias("runtime/internal/atomic", "Storeuintptr", "runtime/internal/atomic", "Store64", p8...)
  2728  	alias("runtime/internal/atomic", "Xchguintptr", "runtime/internal/atomic", "Xchg", p4...)
  2729  	alias("runtime/internal/atomic", "Xchguintptr", "runtime/internal/atomic", "Xchg64", p8...)
  2730  	alias("runtime/internal/atomic", "Xadduintptr", "runtime/internal/atomic", "Xadd", p4...)
  2731  	alias("runtime/internal/atomic", "Xadduintptr", "runtime/internal/atomic", "Xadd64", p8...)
  2732  	alias("runtime/internal/atomic", "Casuintptr", "runtime/internal/atomic", "Cas", p4...)
  2733  	alias("runtime/internal/atomic", "Casuintptr", "runtime/internal/atomic", "Cas64", p8...)
  2734  	alias("runtime/internal/atomic", "Casp1", "runtime/internal/atomic", "Cas", p4...)
  2735  	alias("runtime/internal/atomic", "Casp1", "runtime/internal/atomic", "Cas64", p8...)
  2736  
  2737  	/******** math ********/
  2738  	addF("math", "Sqrt",
  2739  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2740  			return s.newValue1(ssa.OpSqrt, types.Types[TFLOAT64], args[0])
  2741  		},
  2742  		sys.AMD64, sys.ARM, sys.ARM64, sys.MIPS, sys.PPC64, sys.S390X)
  2743  	addF("math", "Trunc",
  2744  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2745  			return s.newValue1(ssa.OpTrunc, types.Types[TFLOAT64], args[0])
  2746  		},
  2747  		sys.PPC64)
  2748  	addF("math", "Ceil",
  2749  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2750  			return s.newValue1(ssa.OpCeil, types.Types[TFLOAT64], args[0])
  2751  		},
  2752  		sys.PPC64)
  2753  	addF("math", "Floor",
  2754  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2755  			return s.newValue1(ssa.OpFloor, types.Types[TFLOAT64], args[0])
  2756  		},
  2757  		sys.PPC64)
  2758  
  2759  	/******** math/bits ********/
  2760  	addF("math/bits", "TrailingZeros64",
  2761  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2762  			return s.newValue1(ssa.OpCtz64, types.Types[TINT], args[0])
  2763  		},
  2764  		sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64)
  2765  	addF("math/bits", "TrailingZeros32",
  2766  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2767  			return s.newValue1(ssa.OpCtz32, types.Types[TINT], args[0])
  2768  		},
  2769  		sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64)
  2770  	addF("math/bits", "TrailingZeros16",
  2771  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2772  			x := s.newValue1(ssa.OpZeroExt16to32, types.Types[TUINT32], args[0])
  2773  			c := s.constInt32(types.Types[TUINT32], 1<<16)
  2774  			y := s.newValue2(ssa.OpOr32, types.Types[TUINT32], x, c)
  2775  			return s.newValue1(ssa.OpCtz32, types.Types[TINT], y)
  2776  		},
  2777  		sys.ARM, sys.MIPS)
  2778  	addF("math/bits", "TrailingZeros16",
  2779  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2780  			x := s.newValue1(ssa.OpZeroExt16to64, types.Types[TUINT64], args[0])
  2781  			c := s.constInt64(types.Types[TUINT64], 1<<16)
  2782  			y := s.newValue2(ssa.OpOr64, types.Types[TUINT64], x, c)
  2783  			return s.newValue1(ssa.OpCtz64, types.Types[TINT], y)
  2784  		},
  2785  		sys.AMD64, sys.ARM64, sys.S390X)
  2786  	addF("math/bits", "TrailingZeros8",
  2787  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2788  			x := s.newValue1(ssa.OpZeroExt8to32, types.Types[TUINT32], args[0])
  2789  			c := s.constInt32(types.Types[TUINT32], 1<<8)
  2790  			y := s.newValue2(ssa.OpOr32, types.Types[TUINT32], x, c)
  2791  			return s.newValue1(ssa.OpCtz32, types.Types[TINT], y)
  2792  		},
  2793  		sys.ARM, sys.MIPS)
  2794  	addF("math/bits", "TrailingZeros8",
  2795  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2796  			x := s.newValue1(ssa.OpZeroExt8to64, types.Types[TUINT64], args[0])
  2797  			c := s.constInt64(types.Types[TUINT64], 1<<8)
  2798  			y := s.newValue2(ssa.OpOr64, types.Types[TUINT64], x, c)
  2799  			return s.newValue1(ssa.OpCtz64, types.Types[TINT], y)
  2800  		},
  2801  		sys.AMD64, sys.ARM64, sys.S390X)
  2802  	alias("math/bits", "ReverseBytes64", "runtime/internal/sys", "Bswap64", all...)
  2803  	alias("math/bits", "ReverseBytes32", "runtime/internal/sys", "Bswap32", all...)
  2804  	// ReverseBytes inlines correctly, no need to intrinsify it.
  2805  	// ReverseBytes16 lowers to a rotate, no need for anything special here.
  2806  	addF("math/bits", "Len64",
  2807  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2808  			return s.newValue1(ssa.OpBitLen64, types.Types[TINT], args[0])
  2809  		},
  2810  		sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64)
  2811  	addF("math/bits", "Len32",
  2812  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2813  			if s.config.PtrSize == 4 {
  2814  				return s.newValue1(ssa.OpBitLen32, types.Types[TINT], args[0])
  2815  			}
  2816  			x := s.newValue1(ssa.OpZeroExt32to64, types.Types[TUINT64], args[0])
  2817  			return s.newValue1(ssa.OpBitLen64, types.Types[TINT], x)
  2818  		},
  2819  		sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64)
  2820  	addF("math/bits", "Len16",
  2821  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2822  			if s.config.PtrSize == 4 {
  2823  				x := s.newValue1(ssa.OpZeroExt16to32, types.Types[TUINT32], args[0])
  2824  				return s.newValue1(ssa.OpBitLen32, types.Types[TINT], x)
  2825  			}
  2826  			x := s.newValue1(ssa.OpZeroExt16to64, types.Types[TUINT64], args[0])
  2827  			return s.newValue1(ssa.OpBitLen64, types.Types[TINT], x)
  2828  		},
  2829  		sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64)
  2830  	// Note: disabled on AMD64 because the Go code is faster!
  2831  	addF("math/bits", "Len8",
  2832  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2833  			if s.config.PtrSize == 4 {
  2834  				x := s.newValue1(ssa.OpZeroExt8to32, types.Types[TUINT32], args[0])
  2835  				return s.newValue1(ssa.OpBitLen32, types.Types[TINT], x)
  2836  			}
  2837  			x := s.newValue1(ssa.OpZeroExt8to64, types.Types[TUINT64], args[0])
  2838  			return s.newValue1(ssa.OpBitLen64, types.Types[TINT], x)
  2839  		},
  2840  		sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64)
  2841  
  2842  	addF("math/bits", "Len",
  2843  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2844  			if s.config.PtrSize == 4 {
  2845  				return s.newValue1(ssa.OpBitLen32, types.Types[TINT], args[0])
  2846  			}
  2847  			return s.newValue1(ssa.OpBitLen64, types.Types[TINT], args[0])
  2848  		},
  2849  		sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64)
  2850  	// LeadingZeros is handled because it trivially calls Len.
  2851  	addF("math/bits", "Reverse64",
  2852  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2853  			return s.newValue1(ssa.OpBitRev64, types.Types[TINT], args[0])
  2854  		},
  2855  		sys.ARM64)
  2856  	addF("math/bits", "Reverse32",
  2857  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2858  			return s.newValue1(ssa.OpBitRev32, types.Types[TINT], args[0])
  2859  		},
  2860  		sys.ARM64)
  2861  	addF("math/bits", "Reverse16",
  2862  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2863  			return s.newValue1(ssa.OpBitRev16, types.Types[TINT], args[0])
  2864  		},
  2865  		sys.ARM64)
  2866  	addF("math/bits", "Reverse8",
  2867  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2868  			return s.newValue1(ssa.OpBitRev8, types.Types[TINT], args[0])
  2869  		},
  2870  		sys.ARM64)
  2871  	addF("math/bits", "Reverse",
  2872  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2873  			if s.config.PtrSize == 4 {
  2874  				return s.newValue1(ssa.OpBitRev32, types.Types[TINT], args[0])
  2875  			}
  2876  			return s.newValue1(ssa.OpBitRev64, types.Types[TINT], args[0])
  2877  		},
  2878  		sys.ARM64)
  2879  	makeOnesCountAMD64 := func(op64 ssa.Op, op32 ssa.Op) func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2880  		return func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2881  			aux := s.lookupSymbol(n, &ssa.ExternSymbol{Sym: syslook("support_popcnt").Sym.Linksym()})
  2882  			addr := s.entryNewValue1A(ssa.OpAddr, types.Types[TBOOL].PtrTo(), aux, s.sb)
  2883  			v := s.newValue2(ssa.OpLoad, types.Types[TBOOL], addr, s.mem())
  2884  			b := s.endBlock()
  2885  			b.Kind = ssa.BlockIf
  2886  			b.SetControl(v)
  2887  			bTrue := s.f.NewBlock(ssa.BlockPlain)
  2888  			bFalse := s.f.NewBlock(ssa.BlockPlain)
  2889  			bEnd := s.f.NewBlock(ssa.BlockPlain)
  2890  			b.AddEdgeTo(bTrue)
  2891  			b.AddEdgeTo(bFalse)
  2892  			b.Likely = ssa.BranchLikely // most machines have popcnt nowadays
  2893  
  2894  			// We have the intrinsic - use it directly.
  2895  			s.startBlock(bTrue)
  2896  			op := op64
  2897  			if s.config.PtrSize == 4 {
  2898  				op = op32
  2899  			}
  2900  			s.vars[n] = s.newValue1(op, types.Types[TINT], args[0])
  2901  			s.endBlock().AddEdgeTo(bEnd)
  2902  
  2903  			// Call the pure Go version.
  2904  			s.startBlock(bFalse)
  2905  			a := s.call(n, callNormal)
  2906  			s.vars[n] = s.newValue2(ssa.OpLoad, types.Types[TINT], a, s.mem())
  2907  			s.endBlock().AddEdgeTo(bEnd)
  2908  
  2909  			// Merge results.
  2910  			s.startBlock(bEnd)
  2911  			return s.variable(n, types.Types[TINT])
  2912  		}
  2913  	}
  2914  	addF("math/bits", "OnesCount64",
  2915  		makeOnesCountAMD64(ssa.OpPopCount64, ssa.OpPopCount64),
  2916  		sys.AMD64)
  2917  	addF("math/bits", "OnesCount64",
  2918  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2919  			return s.newValue1(ssa.OpPopCount64, types.Types[TINT], args[0])
  2920  		},
  2921  		sys.PPC64)
  2922  	addF("math/bits", "OnesCount32",
  2923  		makeOnesCountAMD64(ssa.OpPopCount32, ssa.OpPopCount32),
  2924  		sys.AMD64)
  2925  	addF("math/bits", "OnesCount32",
  2926  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2927  			return s.newValue1(ssa.OpPopCount32, types.Types[TINT], args[0])
  2928  		},
  2929  		sys.PPC64)
  2930  	addF("math/bits", "OnesCount16",
  2931  		makeOnesCountAMD64(ssa.OpPopCount16, ssa.OpPopCount16),
  2932  		sys.AMD64)
  2933  	// Note: no OnesCount8, the Go implementation is faster - just a table load.
  2934  	addF("math/bits", "OnesCount",
  2935  		makeOnesCountAMD64(ssa.OpPopCount64, ssa.OpPopCount32),
  2936  		sys.AMD64)
  2937  
  2938  	/******** sync/atomic ********/
  2939  
  2940  	// Note: these are disabled by flag_race in findIntrinsic below.
  2941  	alias("sync/atomic", "LoadInt32", "runtime/internal/atomic", "Load", all...)
  2942  	alias("sync/atomic", "LoadInt64", "runtime/internal/atomic", "Load64", all...)
  2943  	alias("sync/atomic", "LoadPointer", "runtime/internal/atomic", "Loadp", all...)
  2944  	alias("sync/atomic", "LoadUint32", "runtime/internal/atomic", "Load", all...)
  2945  	alias("sync/atomic", "LoadUint64", "runtime/internal/atomic", "Load64", all...)
  2946  	alias("sync/atomic", "LoadUintptr", "runtime/internal/atomic", "Load", p4...)
  2947  	alias("sync/atomic", "LoadUintptr", "runtime/internal/atomic", "Load64", p8...)
  2948  
  2949  	alias("sync/atomic", "StoreInt32", "runtime/internal/atomic", "Store", all...)
  2950  	alias("sync/atomic", "StoreInt64", "runtime/internal/atomic", "Store64", all...)
  2951  	// Note: not StorePointer, that needs a write barrier.  Same below for {CompareAnd}Swap.
  2952  	alias("sync/atomic", "StoreUint32", "runtime/internal/atomic", "Store", all...)
  2953  	alias("sync/atomic", "StoreUint64", "runtime/internal/atomic", "Store64", all...)
  2954  	alias("sync/atomic", "StoreUintptr", "runtime/internal/atomic", "Store", p4...)
  2955  	alias("sync/atomic", "StoreUintptr", "runtime/internal/atomic", "Store64", p8...)
  2956  
  2957  	alias("sync/atomic", "SwapInt32", "runtime/internal/atomic", "Xchg", all...)
  2958  	alias("sync/atomic", "SwapInt64", "runtime/internal/atomic", "Xchg64", all...)
  2959  	alias("sync/atomic", "SwapUint32", "runtime/internal/atomic", "Xchg", all...)
  2960  	alias("sync/atomic", "SwapUint64", "runtime/internal/atomic", "Xchg64", all...)
  2961  	alias("sync/atomic", "SwapUintptr", "runtime/internal/atomic", "Xchg", p4...)
  2962  	alias("sync/atomic", "SwapUintptr", "runtime/internal/atomic", "Xchg64", p8...)
  2963  
  2964  	alias("sync/atomic", "CompareAndSwapInt32", "runtime/internal/atomic", "Cas", all...)
  2965  	alias("sync/atomic", "CompareAndSwapInt64", "runtime/internal/atomic", "Cas64", all...)
  2966  	alias("sync/atomic", "CompareAndSwapUint32", "runtime/internal/atomic", "Cas", all...)
  2967  	alias("sync/atomic", "CompareAndSwapUint64", "runtime/internal/atomic", "Cas64", all...)
  2968  	alias("sync/atomic", "CompareAndSwapUintptr", "runtime/internal/atomic", "Cas", p4...)
  2969  	alias("sync/atomic", "CompareAndSwapUintptr", "runtime/internal/atomic", "Cas64", p8...)
  2970  
  2971  	alias("sync/atomic", "AddInt32", "runtime/internal/atomic", "Xadd", all...)
  2972  	alias("sync/atomic", "AddInt64", "runtime/internal/atomic", "Xadd64", all...)
  2973  	alias("sync/atomic", "AddUint32", "runtime/internal/atomic", "Xadd", all...)
  2974  	alias("sync/atomic", "AddUint64", "runtime/internal/atomic", "Xadd64", all...)
  2975  	alias("sync/atomic", "AddUintptr", "runtime/internal/atomic", "Xadd", p4...)
  2976  	alias("sync/atomic", "AddUintptr", "runtime/internal/atomic", "Xadd64", p8...)
  2977  
  2978  	/******** math/big ********/
  2979  	add("math/big", "mulWW",
  2980  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2981  			return s.newValue2(ssa.OpMul64uhilo, types.NewTuple(types.Types[TUINT64], types.Types[TUINT64]), args[0], args[1])
  2982  		},
  2983  		sys.ArchAMD64)
  2984  	add("math/big", "divWW",
  2985  		func(s *state, n *Node, args []*ssa.Value) *ssa.Value {
  2986  			return s.newValue3(ssa.OpDiv128u, types.NewTuple(types.Types[TUINT64], types.Types[TUINT64]), args[0], args[1], args[2])
  2987  		},
  2988  		sys.ArchAMD64)
  2989  }
  2990  
  2991  // findIntrinsic returns a function which builds the SSA equivalent of the
  2992  // function identified by the symbol sym.  If sym is not an intrinsic call, returns nil.
  2993  func findIntrinsic(sym *types.Sym) intrinsicBuilder {
  2994  	if ssa.IntrinsicsDisable {
  2995  		return nil
  2996  	}
  2997  	if sym == nil || sym.Pkg == nil {
  2998  		return nil
  2999  	}
  3000  	pkg := sym.Pkg.Path
  3001  	if sym.Pkg == localpkg {
  3002  		pkg = myimportpath
  3003  	}
  3004  	if flag_race && pkg == "sync/atomic" {
  3005  		// The race detector needs to be able to intercept these calls.
  3006  		// We can't intrinsify them.
  3007  		return nil
  3008  	}
  3009  	fn := sym.Name
  3010  	return intrinsics[intrinsicKey{thearch.LinkArch.Arch, pkg, fn}]
  3011  }
  3012  
  3013  func isIntrinsicCall(n *Node) bool {
  3014  	if n == nil || n.Left == nil {
  3015  		return false
  3016  	}
  3017  	return findIntrinsic(n.Left.Sym) != nil
  3018  }
  3019  
  3020  // intrinsicCall converts a call to a recognized intrinsic function into the intrinsic SSA operation.
  3021  func (s *state) intrinsicCall(n *Node) *ssa.Value {
  3022  	v := findIntrinsic(n.Left.Sym)(s, n, s.intrinsicArgs(n))
  3023  	if ssa.IntrinsicsDebug > 0 {
  3024  		x := v
  3025  		if x == nil {
  3026  			x = s.mem()
  3027  		}
  3028  		if x.Op == ssa.OpSelect0 || x.Op == ssa.OpSelect1 {
  3029  			x = x.Args[0]
  3030  		}
  3031  		Warnl(n.Pos, "intrinsic substitution for %v with %s", n.Left.Sym.Name, x.LongString())
  3032  	}
  3033  	return v
  3034  }
  3035  
  3036  type callArg struct {
  3037  	offset int64
  3038  	v      *ssa.Value
  3039  }
  3040  type byOffset []callArg
  3041  
  3042  func (x byOffset) Len() int      { return len(x) }
  3043  func (x byOffset) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
  3044  func (x byOffset) Less(i, j int) bool {
  3045  	return x[i].offset < x[j].offset
  3046  }
  3047  
  3048  // intrinsicArgs extracts args from n, evaluates them to SSA values, and returns them.
  3049  func (s *state) intrinsicArgs(n *Node) []*ssa.Value {
  3050  	// This code is complicated because of how walk transforms calls. For a call node,
  3051  	// each entry in n.List is either an assignment to OINDREGSP which actually
  3052  	// stores an arg, or an assignment to a temporary which computes an arg
  3053  	// which is later assigned.
  3054  	// The args can also be out of order.
  3055  	// TODO: when walk goes away someday, this code can go away also.
  3056  	var args []callArg
  3057  	temps := map[*Node]*ssa.Value{}
  3058  	for _, a := range n.List.Slice() {
  3059  		if a.Op != OAS {
  3060  			s.Fatalf("non-assignment as a function argument %s", opnames[a.Op])
  3061  		}
  3062  		l, r := a.Left, a.Right
  3063  		switch l.Op {
  3064  		case ONAME:
  3065  			// Evaluate and store to "temporary".
  3066  			// Walk ensures these temporaries are dead outside of n.
  3067  			temps[l] = s.expr(r)
  3068  		case OINDREGSP:
  3069  			// Store a value to an argument slot.
  3070  			var v *ssa.Value
  3071  			if x, ok := temps[r]; ok {
  3072  				// This is a previously computed temporary.
  3073  				v = x
  3074  			} else {
  3075  				// This is an explicit value; evaluate it.
  3076  				v = s.expr(r)
  3077  			}
  3078  			args = append(args, callArg{l.Xoffset, v})
  3079  		default:
  3080  			s.Fatalf("function argument assignment target not allowed: %s", opnames[l.Op])
  3081  		}
  3082  	}
  3083  	sort.Sort(byOffset(args))
  3084  	res := make([]*ssa.Value, len(args))
  3085  	for i, a := range args {
  3086  		res[i] = a.v
  3087  	}
  3088  	return res
  3089  }
  3090  
  3091  // Calls the function n using the specified call type.
  3092  // Returns the address of the return value (or nil if none).
  3093  func (s *state) call(n *Node, k callKind) *ssa.Value {
  3094  	var sym *types.Sym     // target symbol (if static)
  3095  	var closure *ssa.Value // ptr to closure to run (if dynamic)
  3096  	var codeptr *ssa.Value // ptr to target code (if dynamic)
  3097  	var rcvr *ssa.Value    // receiver to set
  3098  	fn := n.Left
  3099  	switch n.Op {
  3100  	case OCALLFUNC:
  3101  		if k == callNormal && fn.Op == ONAME && fn.Class() == PFUNC {
  3102  			sym = fn.Sym
  3103  			break
  3104  		}
  3105  		closure = s.expr(fn)
  3106  	case OCALLMETH:
  3107  		if fn.Op != ODOTMETH {
  3108  			Fatalf("OCALLMETH: n.Left not an ODOTMETH: %v", fn)
  3109  		}
  3110  		if k == callNormal {
  3111  			sym = fn.Sym
  3112  			break
  3113  		}
  3114  		// Make a name n2 for the function.
  3115  		// fn.Sym might be sync.(*Mutex).Unlock.
  3116  		// Make a PFUNC node out of that, then evaluate it.
  3117  		// We get back an SSA value representing &sync.(*Mutex).Unlock·f.
  3118  		// We can then pass that to defer or go.
  3119  		n2 := newnamel(fn.Pos, fn.Sym)
  3120  		n2.Name.Curfn = s.curfn
  3121  		n2.SetClass(PFUNC)
  3122  		n2.Pos = fn.Pos
  3123  		n2.Type = types.Types[TUINT8] // dummy type for a static closure. Could use runtime.funcval if we had it.
  3124  		closure = s.expr(n2)
  3125  		// Note: receiver is already assigned in n.List, so we don't
  3126  		// want to set it here.
  3127  	case OCALLINTER:
  3128  		if fn.Op != ODOTINTER {
  3129  			Fatalf("OCALLINTER: n.Left not an ODOTINTER: %v", fn.Op)
  3130  		}
  3131  		i := s.expr(fn.Left)
  3132  		itab := s.newValue1(ssa.OpITab, types.Types[TUINTPTR], i)
  3133  		if k != callNormal {
  3134  			s.nilCheck(itab)
  3135  		}
  3136  		itabidx := fn.Xoffset + 2*int64(Widthptr) + 8 // offset of fun field in runtime.itab
  3137  		itab = s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.UintptrPtr, itabidx, itab)
  3138  		if k == callNormal {
  3139  			codeptr = s.newValue2(ssa.OpLoad, types.Types[TUINTPTR], itab, s.mem())
  3140  		} else {
  3141  			closure = itab
  3142  		}
  3143  		rcvr = s.newValue1(ssa.OpIData, types.Types[TUINTPTR], i)
  3144  	}
  3145  	dowidth(fn.Type)
  3146  	stksize := fn.Type.ArgWidth() // includes receiver
  3147  
  3148  	// Run all argument assignments. The arg slots have already
  3149  	// been offset by the appropriate amount (+2*widthptr for go/defer,
  3150  	// +widthptr for interface calls).
  3151  	// For OCALLMETH, the receiver is set in these statements.
  3152  	s.stmtList(n.List)
  3153  
  3154  	// Set receiver (for interface calls)
  3155  	if rcvr != nil {
  3156  		argStart := Ctxt.FixedFrameSize()
  3157  		if k != callNormal {
  3158  			argStart += int64(2 * Widthptr)
  3159  		}
  3160  		addr := s.constOffPtrSP(s.f.Config.Types.UintptrPtr, argStart)
  3161  		s.vars[&memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, types.Types[TUINTPTR], addr, rcvr, s.mem())
  3162  	}
  3163  
  3164  	// Defer/go args
  3165  	if k != callNormal {
  3166  		// Write argsize and closure (args to Newproc/Deferproc).
  3167  		argStart := Ctxt.FixedFrameSize()
  3168  		argsize := s.constInt32(types.Types[TUINT32], int32(stksize))
  3169  		addr := s.constOffPtrSP(s.f.Config.Types.UInt32Ptr, argStart)
  3170  		s.vars[&memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, types.Types[TUINT32], addr, argsize, s.mem())
  3171  		addr = s.constOffPtrSP(s.f.Config.Types.UintptrPtr, argStart+int64(Widthptr))
  3172  		s.vars[&memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, types.Types[TUINTPTR], addr, closure, s.mem())
  3173  		stksize += 2 * int64(Widthptr)
  3174  	}
  3175  
  3176  	// call target
  3177  	var call *ssa.Value
  3178  	switch {
  3179  	case k == callDefer:
  3180  		call = s.newValue1A(ssa.OpStaticCall, types.TypeMem, Deferproc, s.mem())
  3181  	case k == callGo:
  3182  		call = s.newValue1A(ssa.OpStaticCall, types.TypeMem, Newproc, s.mem())
  3183  	case closure != nil:
  3184  		codeptr = s.newValue2(ssa.OpLoad, types.Types[TUINTPTR], closure, s.mem())
  3185  		call = s.newValue3(ssa.OpClosureCall, types.TypeMem, codeptr, closure, s.mem())
  3186  	case codeptr != nil:
  3187  		call = s.newValue2(ssa.OpInterCall, types.TypeMem, codeptr, s.mem())
  3188  	case sym != nil:
  3189  		call = s.newValue1A(ssa.OpStaticCall, types.TypeMem, sym.Linksym(), s.mem())
  3190  	default:
  3191  		Fatalf("bad call type %v %v", n.Op, n)
  3192  	}
  3193  	call.AuxInt = stksize // Call operations carry the argsize of the callee along with them
  3194  	s.vars[&memVar] = call
  3195  
  3196  	// Finish block for defers
  3197  	if k == callDefer {
  3198  		b := s.endBlock()
  3199  		b.Kind = ssa.BlockDefer
  3200  		b.SetControl(call)
  3201  		bNext := s.f.NewBlock(ssa.BlockPlain)
  3202  		b.AddEdgeTo(bNext)
  3203  		// Add recover edge to exit code.
  3204  		r := s.f.NewBlock(ssa.BlockPlain)
  3205  		s.startBlock(r)
  3206  		s.exit()
  3207  		b.AddEdgeTo(r)
  3208  		b.Likely = ssa.BranchLikely
  3209  		s.startBlock(bNext)
  3210  	}
  3211  
  3212  	res := n.Left.Type.Results()
  3213  	if res.NumFields() == 0 || k != callNormal {
  3214  		// call has no return value. Continue with the next statement.
  3215  		return nil
  3216  	}
  3217  	fp := res.Field(0)
  3218  	return s.constOffPtrSP(types.NewPtr(fp.Type), fp.Offset+Ctxt.FixedFrameSize())
  3219  }
  3220  
  3221  // etypesign returns the signed-ness of e, for integer/pointer etypes.
  3222  // -1 means signed, +1 means unsigned, 0 means non-integer/non-pointer.
  3223  func etypesign(e types.EType) int8 {
  3224  	switch e {
  3225  	case TINT8, TINT16, TINT32, TINT64, TINT:
  3226  		return -1
  3227  	case TUINT8, TUINT16, TUINT32, TUINT64, TUINT, TUINTPTR, TUNSAFEPTR:
  3228  		return +1
  3229  	}
  3230  	return 0
  3231  }
  3232  
  3233  // lookupSymbol is used to retrieve the symbol (Extern, Arg or Auto) used for a particular node.
  3234  // This improves the effectiveness of cse by using the same Aux values for the
  3235  // same symbols.
  3236  func (s *state) lookupSymbol(n *Node, sym interface{}) interface{} {
  3237  	switch sym.(type) {
  3238  	default:
  3239  		s.Fatalf("sym %v is of unknown type %T", sym, sym)
  3240  	case *ssa.ExternSymbol, *ssa.ArgSymbol, *ssa.AutoSymbol:
  3241  		// these are the only valid types
  3242  	}
  3243  
  3244  	if lsym, ok := s.varsyms[n]; ok {
  3245  		return lsym
  3246  	}
  3247  	s.varsyms[n] = sym
  3248  	return sym
  3249  }
  3250  
  3251  // addr converts the address of the expression n to SSA, adds it to s and returns the SSA result.
  3252  // The value that the returned Value represents is guaranteed to be non-nil.
  3253  // If bounded is true then this address does not require a nil check for its operand
  3254  // even if that would otherwise be implied.
  3255  func (s *state) addr(n *Node, bounded bool) *ssa.Value {
  3256  	t := types.NewPtr(n.Type)
  3257  	switch n.Op {
  3258  	case ONAME:
  3259  		switch n.Class() {
  3260  		case PEXTERN:
  3261  			// global variable
  3262  			aux := s.lookupSymbol(n, &ssa.ExternSymbol{Sym: n.Sym.Linksym()})
  3263  			v := s.entryNewValue1A(ssa.OpAddr, t, aux, s.sb)
  3264  			// TODO: Make OpAddr use AuxInt as well as Aux.
  3265  			if n.Xoffset != 0 {
  3266  				v = s.entryNewValue1I(ssa.OpOffPtr, v.Type, n.Xoffset, v)
  3267  			}
  3268  			return v
  3269  		case PPARAM:
  3270  			// parameter slot
  3271  			v := s.decladdrs[n]
  3272  			if v != nil {
  3273  				return v
  3274  			}
  3275  			if n == nodfp {
  3276  				// Special arg that points to the frame pointer (Used by ORECOVER).
  3277  				aux := s.lookupSymbol(n, &ssa.ArgSymbol{Node: n})
  3278  				return s.entryNewValue1A(ssa.OpAddr, t, aux, s.sp)
  3279  			}
  3280  			s.Fatalf("addr of undeclared ONAME %v. declared: %v", n, s.decladdrs)
  3281  			return nil
  3282  		case PAUTO:
  3283  			aux := s.lookupSymbol(n, &ssa.AutoSymbol{Node: n})
  3284  			return s.newValue1A(ssa.OpAddr, t, aux, s.sp)
  3285  		case PPARAMOUT: // Same as PAUTO -- cannot generate LEA early.
  3286  			// ensure that we reuse symbols for out parameters so
  3287  			// that cse works on their addresses
  3288  			aux := s.lookupSymbol(n, &ssa.ArgSymbol{Node: n})
  3289  			return s.newValue1A(ssa.OpAddr, t, aux, s.sp)
  3290  		default:
  3291  			s.Fatalf("variable address class %v not implemented", classnames[n.Class()])
  3292  			return nil
  3293  		}
  3294  	case OINDREGSP:
  3295  		// indirect off REGSP
  3296  		// used for storing/loading arguments/returns to/from callees
  3297  		return s.constOffPtrSP(t, n.Xoffset)
  3298  	case OINDEX:
  3299  		if n.Left.Type.IsSlice() {
  3300  			a := s.expr(n.Left)
  3301  			i := s.expr(n.Right)
  3302  			i = s.extendIndex(i, panicindex)
  3303  			len := s.newValue1(ssa.OpSliceLen, types.Types[TINT], a)
  3304  			if !n.Bounded() {
  3305  				s.boundsCheck(i, len)
  3306  			}
  3307  			p := s.newValue1(ssa.OpSlicePtr, t, a)
  3308  			return s.newValue2(ssa.OpPtrIndex, t, p, i)
  3309  		} else { // array
  3310  			a := s.addr(n.Left, bounded)
  3311  			i := s.expr(n.Right)
  3312  			i = s.extendIndex(i, panicindex)
  3313  			len := s.constInt(types.Types[TINT], n.Left.Type.NumElem())
  3314  			if !n.Bounded() {
  3315  				s.boundsCheck(i, len)
  3316  			}
  3317  			return s.newValue2(ssa.OpPtrIndex, types.NewPtr(n.Left.Type.Elem()), a, i)
  3318  		}
  3319  	case OIND:
  3320  		return s.exprPtr(n.Left, bounded, n.Pos)
  3321  	case ODOT:
  3322  		p := s.addr(n.Left, bounded)
  3323  		return s.newValue1I(ssa.OpOffPtr, t, n.Xoffset, p)
  3324  	case ODOTPTR:
  3325  		p := s.exprPtr(n.Left, bounded, n.Pos)
  3326  		return s.newValue1I(ssa.OpOffPtr, t, n.Xoffset, p)
  3327  	case OCLOSUREVAR:
  3328  		return s.newValue1I(ssa.OpOffPtr, t, n.Xoffset,
  3329  			s.entryNewValue0(ssa.OpGetClosurePtr, s.f.Config.Types.BytePtr))
  3330  	case OCONVNOP:
  3331  		addr := s.addr(n.Left, bounded)
  3332  		return s.newValue1(ssa.OpCopy, t, addr) // ensure that addr has the right type
  3333  	case OCALLFUNC, OCALLINTER, OCALLMETH:
  3334  		return s.call(n, callNormal)
  3335  	case ODOTTYPE:
  3336  		v, _ := s.dottype(n, false)
  3337  		if v.Op != ssa.OpLoad {
  3338  			s.Fatalf("dottype of non-load")
  3339  		}
  3340  		if v.Args[1] != s.mem() {
  3341  			s.Fatalf("memory no longer live from dottype load")
  3342  		}
  3343  		return v.Args[0]
  3344  	default:
  3345  		s.Fatalf("unhandled addr %v", n.Op)
  3346  		return nil
  3347  	}
  3348  }
  3349  
  3350  // canSSA reports whether n is SSA-able.
  3351  // n must be an ONAME (or an ODOT sequence with an ONAME base).
  3352  func (s *state) canSSA(n *Node) bool {
  3353  	if Debug['N'] != 0 {
  3354  		return false
  3355  	}
  3356  	for n.Op == ODOT || (n.Op == OINDEX && n.Left.Type.IsArray()) {
  3357  		n = n.Left
  3358  	}
  3359  	if n.Op != ONAME {
  3360  		return false
  3361  	}
  3362  	if n.Addrtaken() {
  3363  		return false
  3364  	}
  3365  	if n.isParamHeapCopy() {
  3366  		return false
  3367  	}
  3368  	if n.Class() == PAUTOHEAP {
  3369  		Fatalf("canSSA of PAUTOHEAP %v", n)
  3370  	}
  3371  	switch n.Class() {
  3372  	case PEXTERN:
  3373  		return false
  3374  	case PPARAMOUT:
  3375  		if s.hasdefer {
  3376  			// TODO: handle this case? Named return values must be
  3377  			// in memory so that the deferred function can see them.
  3378  			// Maybe do: if !strings.HasPrefix(n.String(), "~") { return false }
  3379  			// Or maybe not, see issue 18860.  Even unnamed return values
  3380  			// must be written back so if a defer recovers, the caller can see them.
  3381  			return false
  3382  		}
  3383  		if s.cgoUnsafeArgs {
  3384  			// Cgo effectively takes the address of all result args,
  3385  			// but the compiler can't see that.
  3386  			return false
  3387  		}
  3388  	}
  3389  	if n.Class() == PPARAM && n.Sym != nil && n.Sym.Name == ".this" {
  3390  		// wrappers generated by genwrapper need to update
  3391  		// the .this pointer in place.
  3392  		// TODO: treat as a PPARMOUT?
  3393  		return false
  3394  	}
  3395  	return canSSAType(n.Type)
  3396  	// TODO: try to make more variables SSAable?
  3397  }
  3398  
  3399  // canSSA reports whether variables of type t are SSA-able.
  3400  func canSSAType(t *types.Type) bool {
  3401  	dowidth(t)
  3402  	if t.Width > int64(4*Widthptr) {
  3403  		// 4*Widthptr is an arbitrary constant. We want it
  3404  		// to be at least 3*Widthptr so slices can be registerized.
  3405  		// Too big and we'll introduce too much register pressure.
  3406  		return false
  3407  	}
  3408  	switch t.Etype {
  3409  	case TARRAY:
  3410  		// We can't do larger arrays because dynamic indexing is
  3411  		// not supported on SSA variables.
  3412  		// TODO: allow if all indexes are constant.
  3413  		if t.NumElem() <= 1 {
  3414  			return canSSAType(t.Elem())
  3415  		}
  3416  		return false
  3417  	case TSTRUCT:
  3418  		if t.NumFields() > ssa.MaxStruct {
  3419  			return false
  3420  		}
  3421  		for _, t1 := range t.Fields().Slice() {
  3422  			if !canSSAType(t1.Type) {
  3423  				return false
  3424  			}
  3425  		}
  3426  		return true
  3427  	default:
  3428  		return true
  3429  	}
  3430  }
  3431  
  3432  // exprPtr evaluates n to a pointer and nil-checks it.
  3433  func (s *state) exprPtr(n *Node, bounded bool, lineno src.XPos) *ssa.Value {
  3434  	p := s.expr(n)
  3435  	if bounded || n.NonNil() {
  3436  		if s.f.Frontend().Debug_checknil() && lineno.Line() > 1 {
  3437  			s.f.Warnl(lineno, "removed nil check")
  3438  		}
  3439  		return p
  3440  	}
  3441  	s.nilCheck(p)
  3442  	return p
  3443  }
  3444  
  3445  // nilCheck generates nil pointer checking code.
  3446  // Used only for automatically inserted nil checks,
  3447  // not for user code like 'x != nil'.
  3448  func (s *state) nilCheck(ptr *ssa.Value) {
  3449  	if disable_checknil != 0 || s.curfn.Func.NilCheckDisabled() {
  3450  		return
  3451  	}
  3452  	s.newValue2(ssa.OpNilCheck, types.TypeVoid, ptr, s.mem())
  3453  }
  3454  
  3455  // boundsCheck generates bounds checking code. Checks if 0 <= idx < len, branches to exit if not.
  3456  // Starts a new block on return.
  3457  // idx is already converted to full int width.
  3458  func (s *state) boundsCheck(idx, len *ssa.Value) {
  3459  	if Debug['B'] != 0 {
  3460  		return
  3461  	}
  3462  
  3463  	// bounds check
  3464  	cmp := s.newValue2(ssa.OpIsInBounds, types.Types[TBOOL], idx, len)
  3465  	s.check(cmp, panicindex)
  3466  }
  3467  
  3468  // sliceBoundsCheck generates slice bounds checking code. Checks if 0 <= idx <= len, branches to exit if not.
  3469  // Starts a new block on return.
  3470  // idx and len are already converted to full int width.
  3471  func (s *state) sliceBoundsCheck(idx, len *ssa.Value) {
  3472  	if Debug['B'] != 0 {
  3473  		return
  3474  	}
  3475  
  3476  	// bounds check
  3477  	cmp := s.newValue2(ssa.OpIsSliceInBounds, types.Types[TBOOL], idx, len)
  3478  	s.check(cmp, panicslice)
  3479  }
  3480  
  3481  // If cmp (a bool) is false, panic using the given function.
  3482  func (s *state) check(cmp *ssa.Value, fn *obj.LSym) {
  3483  	b := s.endBlock()
  3484  	b.Kind = ssa.BlockIf
  3485  	b.SetControl(cmp)
  3486  	b.Likely = ssa.BranchLikely
  3487  	bNext := s.f.NewBlock(ssa.BlockPlain)
  3488  	line := s.peekPos()
  3489  	pos := Ctxt.PosTable.Pos(line)
  3490  	fl := funcLine{f: fn, file: pos.Filename(), line: pos.Line()}
  3491  	bPanic := s.panics[fl]
  3492  	if bPanic == nil {
  3493  		bPanic = s.f.NewBlock(ssa.BlockPlain)
  3494  		s.panics[fl] = bPanic
  3495  		s.startBlock(bPanic)
  3496  		// The panic call takes/returns memory to ensure that the right
  3497  		// memory state is observed if the panic happens.
  3498  		s.rtcall(fn, false, nil)
  3499  	}
  3500  	b.AddEdgeTo(bNext)
  3501  	b.AddEdgeTo(bPanic)
  3502  	s.startBlock(bNext)
  3503  }
  3504  
  3505  func (s *state) intDivide(n *Node, a, b *ssa.Value) *ssa.Value {
  3506  	needcheck := true
  3507  	switch b.Op {
  3508  	case ssa.OpConst8, ssa.OpConst16, ssa.OpConst32, ssa.OpConst64:
  3509  		if b.AuxInt != 0 {
  3510  			needcheck = false
  3511  		}
  3512  	}
  3513  	if needcheck {
  3514  		// do a size-appropriate check for zero
  3515  		cmp := s.newValue2(s.ssaOp(ONE, n.Type), types.Types[TBOOL], b, s.zeroVal(n.Type))
  3516  		s.check(cmp, panicdivide)
  3517  	}
  3518  	return s.newValue2(s.ssaOp(n.Op, n.Type), a.Type, a, b)
  3519  }
  3520  
  3521  // rtcall issues a call to the given runtime function fn with the listed args.
  3522  // Returns a slice of results of the given result types.
  3523  // The call is added to the end of the current block.
  3524  // If returns is false, the block is marked as an exit block.
  3525  func (s *state) rtcall(fn *obj.LSym, returns bool, results []*types.Type, args ...*ssa.Value) []*ssa.Value {
  3526  	// Write args to the stack
  3527  	off := Ctxt.FixedFrameSize()
  3528  	for _, arg := range args {
  3529  		t := arg.Type
  3530  		off = Rnd(off, t.Alignment())
  3531  		ptr := s.constOffPtrSP(t.PtrTo(), off)
  3532  		size := t.Size()
  3533  		s.vars[&memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, t, ptr, arg, s.mem())
  3534  		off += size
  3535  	}
  3536  	off = Rnd(off, int64(Widthreg))
  3537  
  3538  	// Issue call
  3539  	call := s.newValue1A(ssa.OpStaticCall, types.TypeMem, fn, s.mem())
  3540  	s.vars[&memVar] = call
  3541  
  3542  	if !returns {
  3543  		// Finish block
  3544  		b := s.endBlock()
  3545  		b.Kind = ssa.BlockExit
  3546  		b.SetControl(call)
  3547  		call.AuxInt = off - Ctxt.FixedFrameSize()
  3548  		if len(results) > 0 {
  3549  			Fatalf("panic call can't have results")
  3550  		}
  3551  		return nil
  3552  	}
  3553  
  3554  	// Load results
  3555  	res := make([]*ssa.Value, len(results))
  3556  	for i, t := range results {
  3557  		off = Rnd(off, t.Alignment())
  3558  		ptr := s.constOffPtrSP(types.NewPtr(t), off)
  3559  		res[i] = s.newValue2(ssa.OpLoad, t, ptr, s.mem())
  3560  		off += t.Size()
  3561  	}
  3562  	off = Rnd(off, int64(Widthptr))
  3563  
  3564  	// Remember how much callee stack space we needed.
  3565  	call.AuxInt = off
  3566  
  3567  	return res
  3568  }
  3569  
  3570  // do *left = right for type t.
  3571  func (s *state) storeType(t *types.Type, left, right *ssa.Value, skip skipMask) {
  3572  	if skip == 0 && (!types.Haspointers(t) || ssa.IsStackAddr(left)) {
  3573  		// Known to not have write barrier. Store the whole type.
  3574  		s.vars[&memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, t, left, right, s.mem())
  3575  		return
  3576  	}
  3577  
  3578  	// store scalar fields first, so write barrier stores for
  3579  	// pointer fields can be grouped together, and scalar values
  3580  	// don't need to be live across the write barrier call.
  3581  	// TODO: if the writebarrier pass knows how to reorder stores,
  3582  	// we can do a single store here as long as skip==0.
  3583  	s.storeTypeScalars(t, left, right, skip)
  3584  	if skip&skipPtr == 0 && types.Haspointers(t) {
  3585  		s.storeTypePtrs(t, left, right)
  3586  	}
  3587  }
  3588  
  3589  // do *left = right for all scalar (non-pointer) parts of t.
  3590  func (s *state) storeTypeScalars(t *types.Type, left, right *ssa.Value, skip skipMask) {
  3591  	switch {
  3592  	case t.IsBoolean() || t.IsInteger() || t.IsFloat() || t.IsComplex():
  3593  		s.vars[&memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, t, left, right, s.mem())
  3594  	case t.IsPtrShaped():
  3595  		// no scalar fields.
  3596  	case t.IsString():
  3597  		if skip&skipLen != 0 {
  3598  			return
  3599  		}
  3600  		len := s.newValue1(ssa.OpStringLen, types.Types[TINT], right)
  3601  		lenAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, s.config.PtrSize, left)
  3602  		s.vars[&memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, types.Types[TINT], lenAddr, len, s.mem())
  3603  	case t.IsSlice():
  3604  		if skip&skipLen == 0 {
  3605  			len := s.newValue1(ssa.OpSliceLen, types.Types[TINT], right)
  3606  			lenAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, s.config.PtrSize, left)
  3607  			s.vars[&memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, types.Types[TINT], lenAddr, len, s.mem())
  3608  		}
  3609  		if skip&skipCap == 0 {
  3610  			cap := s.newValue1(ssa.OpSliceCap, types.Types[TINT], right)
  3611  			capAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, 2*s.config.PtrSize, left)
  3612  			s.vars[&memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, types.Types[TINT], capAddr, cap, s.mem())
  3613  		}
  3614  	case t.IsInterface():
  3615  		// itab field doesn't need a write barrier (even though it is a pointer).
  3616  		itab := s.newValue1(ssa.OpITab, s.f.Config.Types.BytePtr, right)
  3617  		s.vars[&memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, types.Types[TUINTPTR], left, itab, s.mem())
  3618  	case t.IsStruct():
  3619  		n := t.NumFields()
  3620  		for i := 0; i < n; i++ {
  3621  			ft := t.FieldType(i)
  3622  			addr := s.newValue1I(ssa.OpOffPtr, ft.PtrTo(), t.FieldOff(i), left)
  3623  			val := s.newValue1I(ssa.OpStructSelect, ft, int64(i), right)
  3624  			s.storeTypeScalars(ft, addr, val, 0)
  3625  		}
  3626  	case t.IsArray() && t.NumElem() == 0:
  3627  		// nothing
  3628  	case t.IsArray() && t.NumElem() == 1:
  3629  		s.storeTypeScalars(t.Elem(), left, s.newValue1I(ssa.OpArraySelect, t.Elem(), 0, right), 0)
  3630  	default:
  3631  		s.Fatalf("bad write barrier type %v", t)
  3632  	}
  3633  }
  3634  
  3635  // do *left = right for all pointer parts of t.
  3636  func (s *state) storeTypePtrs(t *types.Type, left, right *ssa.Value) {
  3637  	switch {
  3638  	case t.IsPtrShaped():
  3639  		s.vars[&memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, t, left, right, s.mem())
  3640  	case t.IsString():
  3641  		ptr := s.newValue1(ssa.OpStringPtr, s.f.Config.Types.BytePtr, right)
  3642  		s.vars[&memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, s.f.Config.Types.BytePtr, left, ptr, s.mem())
  3643  	case t.IsSlice():
  3644  		ptr := s.newValue1(ssa.OpSlicePtr, s.f.Config.Types.BytePtr, right)
  3645  		s.vars[&memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, s.f.Config.Types.BytePtr, left, ptr, s.mem())
  3646  	case t.IsInterface():
  3647  		// itab field is treated as a scalar.
  3648  		idata := s.newValue1(ssa.OpIData, s.f.Config.Types.BytePtr, right)
  3649  		idataAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.BytePtrPtr, s.config.PtrSize, left)
  3650  		s.vars[&memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, s.f.Config.Types.BytePtr, idataAddr, idata, s.mem())
  3651  	case t.IsStruct():
  3652  		n := t.NumFields()
  3653  		for i := 0; i < n; i++ {
  3654  			ft := t.FieldType(i)
  3655  			if !types.Haspointers(ft) {
  3656  				continue
  3657  			}
  3658  			addr := s.newValue1I(ssa.OpOffPtr, ft.PtrTo(), t.FieldOff(i), left)
  3659  			val := s.newValue1I(ssa.OpStructSelect, ft, int64(i), right)
  3660  			s.storeTypePtrs(ft, addr, val)
  3661  		}
  3662  	case t.IsArray() && t.NumElem() == 0:
  3663  		// nothing
  3664  	case t.IsArray() && t.NumElem() == 1:
  3665  		s.storeTypePtrs(t.Elem(), left, s.newValue1I(ssa.OpArraySelect, t.Elem(), 0, right))
  3666  	default:
  3667  		s.Fatalf("bad write barrier type %v", t)
  3668  	}
  3669  }
  3670  
  3671  // slice computes the slice v[i:j:k] and returns ptr, len, and cap of result.
  3672  // i,j,k may be nil, in which case they are set to their default value.
  3673  // t is a slice, ptr to array, or string type.
  3674  func (s *state) slice(t *types.Type, v, i, j, k *ssa.Value) (p, l, c *ssa.Value) {
  3675  	var elemtype *types.Type
  3676  	var ptrtype *types.Type
  3677  	var ptr *ssa.Value
  3678  	var len *ssa.Value
  3679  	var cap *ssa.Value
  3680  	zero := s.constInt(types.Types[TINT], 0)
  3681  	switch {
  3682  	case t.IsSlice():
  3683  		elemtype = t.Elem()
  3684  		ptrtype = types.NewPtr(elemtype)
  3685  		ptr = s.newValue1(ssa.OpSlicePtr, ptrtype, v)
  3686  		len = s.newValue1(ssa.OpSliceLen, types.Types[TINT], v)
  3687  		cap = s.newValue1(ssa.OpSliceCap, types.Types[TINT], v)
  3688  	case t.IsString():
  3689  		elemtype = types.Types[TUINT8]
  3690  		ptrtype = types.NewPtr(elemtype)
  3691  		ptr = s.newValue1(ssa.OpStringPtr, ptrtype, v)
  3692  		len = s.newValue1(ssa.OpStringLen, types.Types[TINT], v)
  3693  		cap = len
  3694  	case t.IsPtr():
  3695  		if !t.Elem().IsArray() {
  3696  			s.Fatalf("bad ptr to array in slice %v\n", t)
  3697  		}
  3698  		elemtype = t.Elem().Elem()
  3699  		ptrtype = types.NewPtr(elemtype)
  3700  		s.nilCheck(v)
  3701  		ptr = v
  3702  		len = s.constInt(types.Types[TINT], t.Elem().NumElem())
  3703  		cap = len
  3704  	default:
  3705  		s.Fatalf("bad type in slice %v\n", t)
  3706  	}
  3707  
  3708  	// Set default values
  3709  	if i == nil {
  3710  		i = zero
  3711  	}
  3712  	if j == nil {
  3713  		j = len
  3714  	}
  3715  	if k == nil {
  3716  		k = cap
  3717  	}
  3718  
  3719  	// Panic if slice indices are not in bounds.
  3720  	s.sliceBoundsCheck(i, j)
  3721  	if j != k {
  3722  		s.sliceBoundsCheck(j, k)
  3723  	}
  3724  	if k != cap {
  3725  		s.sliceBoundsCheck(k, cap)
  3726  	}
  3727  
  3728  	// Generate the following code assuming that indexes are in bounds.
  3729  	// The masking is to make sure that we don't generate a slice
  3730  	// that points to the next object in memory.
  3731  	// rlen = j - i
  3732  	// rcap = k - i
  3733  	// delta = i * elemsize
  3734  	// rptr = p + delta&mask(rcap)
  3735  	// result = (SliceMake rptr rlen rcap)
  3736  	// where mask(x) is 0 if x==0 and -1 if x>0.
  3737  	subOp := s.ssaOp(OSUB, types.Types[TINT])
  3738  	mulOp := s.ssaOp(OMUL, types.Types[TINT])
  3739  	andOp := s.ssaOp(OAND, types.Types[TINT])
  3740  	rlen := s.newValue2(subOp, types.Types[TINT], j, i)
  3741  	var rcap *ssa.Value
  3742  	switch {
  3743  	case t.IsString():
  3744  		// Capacity of the result is unimportant. However, we use
  3745  		// rcap to test if we've generated a zero-length slice.
  3746  		// Use length of strings for that.
  3747  		rcap = rlen
  3748  	case j == k:
  3749  		rcap = rlen
  3750  	default:
  3751  		rcap = s.newValue2(subOp, types.Types[TINT], k, i)
  3752  	}
  3753  
  3754  	var rptr *ssa.Value
  3755  	if (i.Op == ssa.OpConst64 || i.Op == ssa.OpConst32) && i.AuxInt == 0 {
  3756  		// No pointer arithmetic necessary.
  3757  		rptr = ptr
  3758  	} else {
  3759  		// delta = # of bytes to offset pointer by.
  3760  		delta := s.newValue2(mulOp, types.Types[TINT], i, s.constInt(types.Types[TINT], elemtype.Width))
  3761  		// If we're slicing to the point where the capacity is zero,
  3762  		// zero out the delta.
  3763  		mask := s.newValue1(ssa.OpSlicemask, types.Types[TINT], rcap)
  3764  		delta = s.newValue2(andOp, types.Types[TINT], delta, mask)
  3765  		// Compute rptr = ptr + delta
  3766  		rptr = s.newValue2(ssa.OpAddPtr, ptrtype, ptr, delta)
  3767  	}
  3768  
  3769  	return rptr, rlen, rcap
  3770  }
  3771  
  3772  type u642fcvtTab struct {
  3773  	geq, cvt2F, and, rsh, or, add ssa.Op
  3774  	one                           func(*state, *types.Type, int64) *ssa.Value
  3775  }
  3776  
  3777  var u64_f64 u642fcvtTab = u642fcvtTab{
  3778  	geq:   ssa.OpGeq64,
  3779  	cvt2F: ssa.OpCvt64to64F,
  3780  	and:   ssa.OpAnd64,
  3781  	rsh:   ssa.OpRsh64Ux64,
  3782  	or:    ssa.OpOr64,
  3783  	add:   ssa.OpAdd64F,
  3784  	one:   (*state).constInt64,
  3785  }
  3786  
  3787  var u64_f32 u642fcvtTab = u642fcvtTab{
  3788  	geq:   ssa.OpGeq64,
  3789  	cvt2F: ssa.OpCvt64to32F,
  3790  	and:   ssa.OpAnd64,
  3791  	rsh:   ssa.OpRsh64Ux64,
  3792  	or:    ssa.OpOr64,
  3793  	add:   ssa.OpAdd32F,
  3794  	one:   (*state).constInt64,
  3795  }
  3796  
  3797  func (s *state) uint64Tofloat64(n *Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  3798  	return s.uint64Tofloat(&u64_f64, n, x, ft, tt)
  3799  }
  3800  
  3801  func (s *state) uint64Tofloat32(n *Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  3802  	return s.uint64Tofloat(&u64_f32, n, x, ft, tt)
  3803  }
  3804  
  3805  func (s *state) uint64Tofloat(cvttab *u642fcvtTab, n *Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  3806  	// if x >= 0 {
  3807  	//    result = (floatY) x
  3808  	// } else {
  3809  	// 	  y = uintX(x) ; y = x & 1
  3810  	// 	  z = uintX(x) ; z = z >> 1
  3811  	// 	  z = z >> 1
  3812  	// 	  z = z | y
  3813  	// 	  result = floatY(z)
  3814  	// 	  result = result + result
  3815  	// }
  3816  	//
  3817  	// Code borrowed from old code generator.
  3818  	// What's going on: large 64-bit "unsigned" looks like
  3819  	// negative number to hardware's integer-to-float
  3820  	// conversion. However, because the mantissa is only
  3821  	// 63 bits, we don't need the LSB, so instead we do an
  3822  	// unsigned right shift (divide by two), convert, and
  3823  	// double. However, before we do that, we need to be
  3824  	// sure that we do not lose a "1" if that made the
  3825  	// difference in the resulting rounding. Therefore, we
  3826  	// preserve it, and OR (not ADD) it back in. The case
  3827  	// that matters is when the eleven discarded bits are
  3828  	// equal to 10000000001; that rounds up, and the 1 cannot
  3829  	// be lost else it would round down if the LSB of the
  3830  	// candidate mantissa is 0.
  3831  	cmp := s.newValue2(cvttab.geq, types.Types[TBOOL], x, s.zeroVal(ft))
  3832  	b := s.endBlock()
  3833  	b.Kind = ssa.BlockIf
  3834  	b.SetControl(cmp)
  3835  	b.Likely = ssa.BranchLikely
  3836  
  3837  	bThen := s.f.NewBlock(ssa.BlockPlain)
  3838  	bElse := s.f.NewBlock(ssa.BlockPlain)
  3839  	bAfter := s.f.NewBlock(ssa.BlockPlain)
  3840  
  3841  	b.AddEdgeTo(bThen)
  3842  	s.startBlock(bThen)
  3843  	a0 := s.newValue1(cvttab.cvt2F, tt, x)
  3844  	s.vars[n] = a0
  3845  	s.endBlock()
  3846  	bThen.AddEdgeTo(bAfter)
  3847  
  3848  	b.AddEdgeTo(bElse)
  3849  	s.startBlock(bElse)
  3850  	one := cvttab.one(s, ft, 1)
  3851  	y := s.newValue2(cvttab.and, ft, x, one)
  3852  	z := s.newValue2(cvttab.rsh, ft, x, one)
  3853  	z = s.newValue2(cvttab.or, ft, z, y)
  3854  	a := s.newValue1(cvttab.cvt2F, tt, z)
  3855  	a1 := s.newValue2(cvttab.add, tt, a, a)
  3856  	s.vars[n] = a1
  3857  	s.endBlock()
  3858  	bElse.AddEdgeTo(bAfter)
  3859  
  3860  	s.startBlock(bAfter)
  3861  	return s.variable(n, n.Type)
  3862  }
  3863  
  3864  type u322fcvtTab struct {
  3865  	cvtI2F, cvtF2F ssa.Op
  3866  }
  3867  
  3868  var u32_f64 u322fcvtTab = u322fcvtTab{
  3869  	cvtI2F: ssa.OpCvt32to64F,
  3870  	cvtF2F: ssa.OpCopy,
  3871  }
  3872  
  3873  var u32_f32 u322fcvtTab = u322fcvtTab{
  3874  	cvtI2F: ssa.OpCvt32to32F,
  3875  	cvtF2F: ssa.OpCvt64Fto32F,
  3876  }
  3877  
  3878  func (s *state) uint32Tofloat64(n *Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  3879  	return s.uint32Tofloat(&u32_f64, n, x, ft, tt)
  3880  }
  3881  
  3882  func (s *state) uint32Tofloat32(n *Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  3883  	return s.uint32Tofloat(&u32_f32, n, x, ft, tt)
  3884  }
  3885  
  3886  func (s *state) uint32Tofloat(cvttab *u322fcvtTab, n *Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  3887  	// if x >= 0 {
  3888  	// 	result = floatY(x)
  3889  	// } else {
  3890  	// 	result = floatY(float64(x) + (1<<32))
  3891  	// }
  3892  	cmp := s.newValue2(ssa.OpGeq32, types.Types[TBOOL], x, s.zeroVal(ft))
  3893  	b := s.endBlock()
  3894  	b.Kind = ssa.BlockIf
  3895  	b.SetControl(cmp)
  3896  	b.Likely = ssa.BranchLikely
  3897  
  3898  	bThen := s.f.NewBlock(ssa.BlockPlain)
  3899  	bElse := s.f.NewBlock(ssa.BlockPlain)
  3900  	bAfter := s.f.NewBlock(ssa.BlockPlain)
  3901  
  3902  	b.AddEdgeTo(bThen)
  3903  	s.startBlock(bThen)
  3904  	a0 := s.newValue1(cvttab.cvtI2F, tt, x)
  3905  	s.vars[n] = a0
  3906  	s.endBlock()
  3907  	bThen.AddEdgeTo(bAfter)
  3908  
  3909  	b.AddEdgeTo(bElse)
  3910  	s.startBlock(bElse)
  3911  	a1 := s.newValue1(ssa.OpCvt32to64F, types.Types[TFLOAT64], x)
  3912  	twoToThe32 := s.constFloat64(types.Types[TFLOAT64], float64(1<<32))
  3913  	a2 := s.newValue2(ssa.OpAdd64F, types.Types[TFLOAT64], a1, twoToThe32)
  3914  	a3 := s.newValue1(cvttab.cvtF2F, tt, a2)
  3915  
  3916  	s.vars[n] = a3
  3917  	s.endBlock()
  3918  	bElse.AddEdgeTo(bAfter)
  3919  
  3920  	s.startBlock(bAfter)
  3921  	return s.variable(n, n.Type)
  3922  }
  3923  
  3924  // referenceTypeBuiltin generates code for the len/cap builtins for maps and channels.
  3925  func (s *state) referenceTypeBuiltin(n *Node, x *ssa.Value) *ssa.Value {
  3926  	if !n.Left.Type.IsMap() && !n.Left.Type.IsChan() {
  3927  		s.Fatalf("node must be a map or a channel")
  3928  	}
  3929  	// if n == nil {
  3930  	//   return 0
  3931  	// } else {
  3932  	//   // len
  3933  	//   return *((*int)n)
  3934  	//   // cap
  3935  	//   return *(((*int)n)+1)
  3936  	// }
  3937  	lenType := n.Type
  3938  	nilValue := s.constNil(types.Types[TUINTPTR])
  3939  	cmp := s.newValue2(ssa.OpEqPtr, types.Types[TBOOL], x, nilValue)
  3940  	b := s.endBlock()
  3941  	b.Kind = ssa.BlockIf
  3942  	b.SetControl(cmp)
  3943  	b.Likely = ssa.BranchUnlikely
  3944  
  3945  	bThen := s.f.NewBlock(ssa.BlockPlain)
  3946  	bElse := s.f.NewBlock(ssa.BlockPlain)
  3947  	bAfter := s.f.NewBlock(ssa.BlockPlain)
  3948  
  3949  	// length/capacity of a nil map/chan is zero
  3950  	b.AddEdgeTo(bThen)
  3951  	s.startBlock(bThen)
  3952  	s.vars[n] = s.zeroVal(lenType)
  3953  	s.endBlock()
  3954  	bThen.AddEdgeTo(bAfter)
  3955  
  3956  	b.AddEdgeTo(bElse)
  3957  	s.startBlock(bElse)
  3958  	if n.Op == OLEN {
  3959  		// length is stored in the first word for map/chan
  3960  		s.vars[n] = s.newValue2(ssa.OpLoad, lenType, x, s.mem())
  3961  	} else if n.Op == OCAP {
  3962  		// capacity is stored in the second word for chan
  3963  		sw := s.newValue1I(ssa.OpOffPtr, lenType.PtrTo(), lenType.Width, x)
  3964  		s.vars[n] = s.newValue2(ssa.OpLoad, lenType, sw, s.mem())
  3965  	} else {
  3966  		s.Fatalf("op must be OLEN or OCAP")
  3967  	}
  3968  	s.endBlock()
  3969  	bElse.AddEdgeTo(bAfter)
  3970  
  3971  	s.startBlock(bAfter)
  3972  	return s.variable(n, lenType)
  3973  }
  3974  
  3975  type f2uCvtTab struct {
  3976  	ltf, cvt2U, subf, or ssa.Op
  3977  	floatValue           func(*state, *types.Type, float64) *ssa.Value
  3978  	intValue             func(*state, *types.Type, int64) *ssa.Value
  3979  	cutoff               uint64
  3980  }
  3981  
  3982  var f32_u64 f2uCvtTab = f2uCvtTab{
  3983  	ltf:        ssa.OpLess32F,
  3984  	cvt2U:      ssa.OpCvt32Fto64,
  3985  	subf:       ssa.OpSub32F,
  3986  	or:         ssa.OpOr64,
  3987  	floatValue: (*state).constFloat32,
  3988  	intValue:   (*state).constInt64,
  3989  	cutoff:     9223372036854775808,
  3990  }
  3991  
  3992  var f64_u64 f2uCvtTab = f2uCvtTab{
  3993  	ltf:        ssa.OpLess64F,
  3994  	cvt2U:      ssa.OpCvt64Fto64,
  3995  	subf:       ssa.OpSub64F,
  3996  	or:         ssa.OpOr64,
  3997  	floatValue: (*state).constFloat64,
  3998  	intValue:   (*state).constInt64,
  3999  	cutoff:     9223372036854775808,
  4000  }
  4001  
  4002  var f32_u32 f2uCvtTab = f2uCvtTab{
  4003  	ltf:        ssa.OpLess32F,
  4004  	cvt2U:      ssa.OpCvt32Fto32,
  4005  	subf:       ssa.OpSub32F,
  4006  	or:         ssa.OpOr32,
  4007  	floatValue: (*state).constFloat32,
  4008  	intValue:   func(s *state, t *types.Type, v int64) *ssa.Value { return s.constInt32(t, int32(v)) },
  4009  	cutoff:     2147483648,
  4010  }
  4011  
  4012  var f64_u32 f2uCvtTab = f2uCvtTab{
  4013  	ltf:        ssa.OpLess64F,
  4014  	cvt2U:      ssa.OpCvt64Fto32,
  4015  	subf:       ssa.OpSub64F,
  4016  	or:         ssa.OpOr32,
  4017  	floatValue: (*state).constFloat64,
  4018  	intValue:   func(s *state, t *types.Type, v int64) *ssa.Value { return s.constInt32(t, int32(v)) },
  4019  	cutoff:     2147483648,
  4020  }
  4021  
  4022  func (s *state) float32ToUint64(n *Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  4023  	return s.floatToUint(&f32_u64, n, x, ft, tt)
  4024  }
  4025  func (s *state) float64ToUint64(n *Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  4026  	return s.floatToUint(&f64_u64, n, x, ft, tt)
  4027  }
  4028  
  4029  func (s *state) float32ToUint32(n *Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  4030  	return s.floatToUint(&f32_u32, n, x, ft, tt)
  4031  }
  4032  
  4033  func (s *state) float64ToUint32(n *Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  4034  	return s.floatToUint(&f64_u32, n, x, ft, tt)
  4035  }
  4036  
  4037  func (s *state) floatToUint(cvttab *f2uCvtTab, n *Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  4038  	// cutoff:=1<<(intY_Size-1)
  4039  	// if x < floatX(cutoff) {
  4040  	// 	result = uintY(x)
  4041  	// } else {
  4042  	// 	y = x - floatX(cutoff)
  4043  	// 	z = uintY(y)
  4044  	// 	result = z | -(cutoff)
  4045  	// }
  4046  	cutoff := cvttab.floatValue(s, ft, float64(cvttab.cutoff))
  4047  	cmp := s.newValue2(cvttab.ltf, types.Types[TBOOL], x, cutoff)
  4048  	b := s.endBlock()
  4049  	b.Kind = ssa.BlockIf
  4050  	b.SetControl(cmp)
  4051  	b.Likely = ssa.BranchLikely
  4052  
  4053  	bThen := s.f.NewBlock(ssa.BlockPlain)
  4054  	bElse := s.f.NewBlock(ssa.BlockPlain)
  4055  	bAfter := s.f.NewBlock(ssa.BlockPlain)
  4056  
  4057  	b.AddEdgeTo(bThen)
  4058  	s.startBlock(bThen)
  4059  	a0 := s.newValue1(cvttab.cvt2U, tt, x)
  4060  	s.vars[n] = a0
  4061  	s.endBlock()
  4062  	bThen.AddEdgeTo(bAfter)
  4063  
  4064  	b.AddEdgeTo(bElse)
  4065  	s.startBlock(bElse)
  4066  	y := s.newValue2(cvttab.subf, ft, x, cutoff)
  4067  	y = s.newValue1(cvttab.cvt2U, tt, y)
  4068  	z := cvttab.intValue(s, tt, int64(-cvttab.cutoff))
  4069  	a1 := s.newValue2(cvttab.or, tt, y, z)
  4070  	s.vars[n] = a1
  4071  	s.endBlock()
  4072  	bElse.AddEdgeTo(bAfter)
  4073  
  4074  	s.startBlock(bAfter)
  4075  	return s.variable(n, n.Type)
  4076  }
  4077  
  4078  // dottype generates SSA for a type assertion node.
  4079  // commaok indicates whether to panic or return a bool.
  4080  // If commaok is false, resok will be nil.
  4081  func (s *state) dottype(n *Node, commaok bool) (res, resok *ssa.Value) {
  4082  	iface := s.expr(n.Left)   // input interface
  4083  	target := s.expr(n.Right) // target type
  4084  	byteptr := s.f.Config.Types.BytePtr
  4085  
  4086  	if n.Type.IsInterface() {
  4087  		if n.Type.IsEmptyInterface() {
  4088  			// Converting to an empty interface.
  4089  			// Input could be an empty or nonempty interface.
  4090  			if Debug_typeassert > 0 {
  4091  				Warnl(n.Pos, "type assertion inlined")
  4092  			}
  4093  
  4094  			// Get itab/type field from input.
  4095  			itab := s.newValue1(ssa.OpITab, byteptr, iface)
  4096  			// Conversion succeeds iff that field is not nil.
  4097  			cond := s.newValue2(ssa.OpNeqPtr, types.Types[TBOOL], itab, s.constNil(byteptr))
  4098  
  4099  			if n.Left.Type.IsEmptyInterface() && commaok {
  4100  				// Converting empty interface to empty interface with ,ok is just a nil check.
  4101  				return iface, cond
  4102  			}
  4103  
  4104  			// Branch on nilness.
  4105  			b := s.endBlock()
  4106  			b.Kind = ssa.BlockIf
  4107  			b.SetControl(cond)
  4108  			b.Likely = ssa.BranchLikely
  4109  			bOk := s.f.NewBlock(ssa.BlockPlain)
  4110  			bFail := s.f.NewBlock(ssa.BlockPlain)
  4111  			b.AddEdgeTo(bOk)
  4112  			b.AddEdgeTo(bFail)
  4113  
  4114  			if !commaok {
  4115  				// On failure, panic by calling panicnildottype.
  4116  				s.startBlock(bFail)
  4117  				s.rtcall(panicnildottype, false, nil, target)
  4118  
  4119  				// On success, return (perhaps modified) input interface.
  4120  				s.startBlock(bOk)
  4121  				if n.Left.Type.IsEmptyInterface() {
  4122  					res = iface // Use input interface unchanged.
  4123  					return
  4124  				}
  4125  				// Load type out of itab, build interface with existing idata.
  4126  				off := s.newValue1I(ssa.OpOffPtr, byteptr, int64(Widthptr), itab)
  4127  				typ := s.newValue2(ssa.OpLoad, byteptr, off, s.mem())
  4128  				idata := s.newValue1(ssa.OpIData, n.Type, iface)
  4129  				res = s.newValue2(ssa.OpIMake, n.Type, typ, idata)
  4130  				return
  4131  			}
  4132  
  4133  			s.startBlock(bOk)
  4134  			// nonempty -> empty
  4135  			// Need to load type from itab
  4136  			off := s.newValue1I(ssa.OpOffPtr, byteptr, int64(Widthptr), itab)
  4137  			s.vars[&typVar] = s.newValue2(ssa.OpLoad, byteptr, off, s.mem())
  4138  			s.endBlock()
  4139  
  4140  			// itab is nil, might as well use that as the nil result.
  4141  			s.startBlock(bFail)
  4142  			s.vars[&typVar] = itab
  4143  			s.endBlock()
  4144  
  4145  			// Merge point.
  4146  			bEnd := s.f.NewBlock(ssa.BlockPlain)
  4147  			bOk.AddEdgeTo(bEnd)
  4148  			bFail.AddEdgeTo(bEnd)
  4149  			s.startBlock(bEnd)
  4150  			idata := s.newValue1(ssa.OpIData, n.Type, iface)
  4151  			res = s.newValue2(ssa.OpIMake, n.Type, s.variable(&typVar, byteptr), idata)
  4152  			resok = cond
  4153  			delete(s.vars, &typVar)
  4154  			return
  4155  		}
  4156  		// converting to a nonempty interface needs a runtime call.
  4157  		if Debug_typeassert > 0 {
  4158  			Warnl(n.Pos, "type assertion not inlined")
  4159  		}
  4160  		if n.Left.Type.IsEmptyInterface() {
  4161  			if commaok {
  4162  				call := s.rtcall(assertE2I2, true, []*types.Type{n.Type, types.Types[TBOOL]}, target, iface)
  4163  				return call[0], call[1]
  4164  			}
  4165  			return s.rtcall(assertE2I, true, []*types.Type{n.Type}, target, iface)[0], nil
  4166  		}
  4167  		if commaok {
  4168  			call := s.rtcall(assertI2I2, true, []*types.Type{n.Type, types.Types[TBOOL]}, target, iface)
  4169  			return call[0], call[1]
  4170  		}
  4171  		return s.rtcall(assertI2I, true, []*types.Type{n.Type}, target, iface)[0], nil
  4172  	}
  4173  
  4174  	if Debug_typeassert > 0 {
  4175  		Warnl(n.Pos, "type assertion inlined")
  4176  	}
  4177  
  4178  	// Converting to a concrete type.
  4179  	direct := isdirectiface(n.Type)
  4180  	itab := s.newValue1(ssa.OpITab, byteptr, iface) // type word of interface
  4181  	if Debug_typeassert > 0 {
  4182  		Warnl(n.Pos, "type assertion inlined")
  4183  	}
  4184  	var targetITab *ssa.Value
  4185  	if n.Left.Type.IsEmptyInterface() {
  4186  		// Looking for pointer to target type.
  4187  		targetITab = target
  4188  	} else {
  4189  		// Looking for pointer to itab for target type and source interface.
  4190  		targetITab = s.expr(n.List.First())
  4191  	}
  4192  
  4193  	var tmp *Node       // temporary for use with large types
  4194  	var addr *ssa.Value // address of tmp
  4195  	if commaok && !canSSAType(n.Type) {
  4196  		// unSSAable type, use temporary.
  4197  		// TODO: get rid of some of these temporaries.
  4198  		tmp = tempAt(n.Pos, s.curfn, n.Type)
  4199  		addr = s.addr(tmp, false)
  4200  		s.vars[&memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, tmp, s.mem())
  4201  	}
  4202  
  4203  	cond := s.newValue2(ssa.OpEqPtr, types.Types[TBOOL], itab, targetITab)
  4204  	b := s.endBlock()
  4205  	b.Kind = ssa.BlockIf
  4206  	b.SetControl(cond)
  4207  	b.Likely = ssa.BranchLikely
  4208  
  4209  	bOk := s.f.NewBlock(ssa.BlockPlain)
  4210  	bFail := s.f.NewBlock(ssa.BlockPlain)
  4211  	b.AddEdgeTo(bOk)
  4212  	b.AddEdgeTo(bFail)
  4213  
  4214  	if !commaok {
  4215  		// on failure, panic by calling panicdottype
  4216  		s.startBlock(bFail)
  4217  		taddr := s.expr(n.Right.Right)
  4218  		if n.Left.Type.IsEmptyInterface() {
  4219  			s.rtcall(panicdottypeE, false, nil, itab, target, taddr)
  4220  		} else {
  4221  			s.rtcall(panicdottypeI, false, nil, itab, target, taddr)
  4222  		}
  4223  
  4224  		// on success, return data from interface
  4225  		s.startBlock(bOk)
  4226  		if direct {
  4227  			return s.newValue1(ssa.OpIData, n.Type, iface), nil
  4228  		}
  4229  		p := s.newValue1(ssa.OpIData, types.NewPtr(n.Type), iface)
  4230  		return s.newValue2(ssa.OpLoad, n.Type, p, s.mem()), nil
  4231  	}
  4232  
  4233  	// commaok is the more complicated case because we have
  4234  	// a control flow merge point.
  4235  	bEnd := s.f.NewBlock(ssa.BlockPlain)
  4236  	// Note that we need a new valVar each time (unlike okVar where we can
  4237  	// reuse the variable) because it might have a different type every time.
  4238  	valVar := &Node{Op: ONAME, Sym: &types.Sym{Name: "val"}}
  4239  
  4240  	// type assertion succeeded
  4241  	s.startBlock(bOk)
  4242  	if tmp == nil {
  4243  		if direct {
  4244  			s.vars[valVar] = s.newValue1(ssa.OpIData, n.Type, iface)
  4245  		} else {
  4246  			p := s.newValue1(ssa.OpIData, types.NewPtr(n.Type), iface)
  4247  			s.vars[valVar] = s.newValue2(ssa.OpLoad, n.Type, p, s.mem())
  4248  		}
  4249  	} else {
  4250  		p := s.newValue1(ssa.OpIData, types.NewPtr(n.Type), iface)
  4251  		store := s.newValue3I(ssa.OpMove, types.TypeMem, n.Type.Size(), addr, p, s.mem())
  4252  		store.Aux = n.Type
  4253  		s.vars[&memVar] = store
  4254  	}
  4255  	s.vars[&okVar] = s.constBool(true)
  4256  	s.endBlock()
  4257  	bOk.AddEdgeTo(bEnd)
  4258  
  4259  	// type assertion failed
  4260  	s.startBlock(bFail)
  4261  	if tmp == nil {
  4262  		s.vars[valVar] = s.zeroVal(n.Type)
  4263  	} else {
  4264  		store := s.newValue2I(ssa.OpZero, types.TypeMem, n.Type.Size(), addr, s.mem())
  4265  		store.Aux = n.Type
  4266  		s.vars[&memVar] = store
  4267  	}
  4268  	s.vars[&okVar] = s.constBool(false)
  4269  	s.endBlock()
  4270  	bFail.AddEdgeTo(bEnd)
  4271  
  4272  	// merge point
  4273  	s.startBlock(bEnd)
  4274  	if tmp == nil {
  4275  		res = s.variable(valVar, n.Type)
  4276  		delete(s.vars, valVar)
  4277  	} else {
  4278  		res = s.newValue2(ssa.OpLoad, n.Type, addr, s.mem())
  4279  		s.vars[&memVar] = s.newValue1A(ssa.OpVarKill, types.TypeMem, tmp, s.mem())
  4280  	}
  4281  	resok = s.variable(&okVar, types.Types[TBOOL])
  4282  	delete(s.vars, &okVar)
  4283  	return res, resok
  4284  }
  4285  
  4286  // variable returns the value of a variable at the current location.
  4287  func (s *state) variable(name *Node, t *types.Type) *ssa.Value {
  4288  	v := s.vars[name]
  4289  	if v != nil {
  4290  		return v
  4291  	}
  4292  	v = s.fwdVars[name]
  4293  	if v != nil {
  4294  		return v
  4295  	}
  4296  
  4297  	if s.curBlock == s.f.Entry {
  4298  		// No variable should be live at entry.
  4299  		s.Fatalf("Value live at entry. It shouldn't be. func %s, node %v, value %v", s.f.Name, name, v)
  4300  	}
  4301  	// Make a FwdRef, which records a value that's live on block input.
  4302  	// We'll find the matching definition as part of insertPhis.
  4303  	v = s.newValue0A(ssa.OpFwdRef, t, name)
  4304  	s.fwdVars[name] = v
  4305  	s.addNamedValue(name, v)
  4306  	return v
  4307  }
  4308  
  4309  func (s *state) mem() *ssa.Value {
  4310  	return s.variable(&memVar, types.TypeMem)
  4311  }
  4312  
  4313  func (s *state) addNamedValue(n *Node, v *ssa.Value) {
  4314  	if n.Class() == Pxxx {
  4315  		// Don't track our dummy nodes (&memVar etc.).
  4316  		return
  4317  	}
  4318  	if n.IsAutoTmp() {
  4319  		// Don't track temporary variables.
  4320  		return
  4321  	}
  4322  	if n.Class() == PPARAMOUT {
  4323  		// Don't track named output values.  This prevents return values
  4324  		// from being assigned too early. See #14591 and #14762. TODO: allow this.
  4325  		return
  4326  	}
  4327  	if n.Class() == PAUTO && n.Xoffset != 0 {
  4328  		s.Fatalf("AUTO var with offset %v %d", n, n.Xoffset)
  4329  	}
  4330  	loc := ssa.LocalSlot{N: n, Type: n.Type, Off: 0}
  4331  	values, ok := s.f.NamedValues[loc]
  4332  	if !ok {
  4333  		s.f.Names = append(s.f.Names, loc)
  4334  	}
  4335  	s.f.NamedValues[loc] = append(values, v)
  4336  }
  4337  
  4338  // Branch is an unresolved branch.
  4339  type Branch struct {
  4340  	P *obj.Prog  // branch instruction
  4341  	B *ssa.Block // target
  4342  }
  4343  
  4344  // SSAGenState contains state needed during Prog generation.
  4345  type SSAGenState struct {
  4346  	pp *Progs
  4347  
  4348  	// Branches remembers all the branch instructions we've seen
  4349  	// and where they would like to go.
  4350  	Branches []Branch
  4351  
  4352  	// bstart remembers where each block starts (indexed by block ID)
  4353  	bstart []*obj.Prog
  4354  
  4355  	// 387 port: maps from SSE registers (REG_X?) to 387 registers (REG_F?)
  4356  	SSEto387 map[int16]int16
  4357  	// Some architectures require a 64-bit temporary for FP-related register shuffling. Examples include x86-387, PPC, and Sparc V8.
  4358  	ScratchFpMem *Node
  4359  
  4360  	maxarg int64 // largest frame size for arguments to calls made by the function
  4361  
  4362  	// Map from GC safe points to stack map index, generated by
  4363  	// liveness analysis.
  4364  	stackMapIndex map[*ssa.Value]int
  4365  }
  4366  
  4367  // Prog appends a new Prog.
  4368  func (s *SSAGenState) Prog(as obj.As) *obj.Prog {
  4369  	return s.pp.Prog(as)
  4370  }
  4371  
  4372  // Pc returns the current Prog.
  4373  func (s *SSAGenState) Pc() *obj.Prog {
  4374  	return s.pp.next
  4375  }
  4376  
  4377  // SetPos sets the current source position.
  4378  func (s *SSAGenState) SetPos(pos src.XPos) {
  4379  	s.pp.pos = pos
  4380  }
  4381  
  4382  // DebugFriendlySetPos sets the position subject to heuristics
  4383  // that reduce "jumpy" line number churn when debugging.
  4384  // Spill/fill/copy instructions from the register allocator,
  4385  // phi functions, and instructions with a no-pos position
  4386  // are examples of instructions that can cause churn.
  4387  func (s *SSAGenState) DebugFriendlySetPosFrom(v *ssa.Value) {
  4388  	// The two choices here are either to leave lineno unchanged,
  4389  	// or to explicitly set it to src.NoXPos.  Leaving it unchanged
  4390  	// (reusing the preceding line number) produces slightly better-
  4391  	// looking assembly language output from the compiler, and is
  4392  	// expected by some already-existing tests.
  4393  	// The debug information appears to be the same in either case
  4394  	switch v.Op {
  4395  	case ssa.OpPhi, ssa.OpCopy, ssa.OpLoadReg, ssa.OpStoreReg:
  4396  		// leave the position unchanged from beginning of block
  4397  		// or previous line number.
  4398  	default:
  4399  		if v.Pos != src.NoXPos {
  4400  			s.SetPos(v.Pos)
  4401  		}
  4402  	}
  4403  }
  4404  
  4405  // genssa appends entries to pp for each instruction in f.
  4406  func genssa(f *ssa.Func, pp *Progs) {
  4407  	var s SSAGenState
  4408  
  4409  	e := f.Frontend().(*ssafn)
  4410  
  4411  	// Generate GC bitmaps, except if the stack is too large,
  4412  	// in which compilation will fail later anyway (issue 20529).
  4413  	if e.stksize < maxStackSize {
  4414  		s.stackMapIndex = liveness(e, f)
  4415  	}
  4416  
  4417  	// Remember where each block starts.
  4418  	s.bstart = make([]*obj.Prog, f.NumBlocks())
  4419  	s.pp = pp
  4420  	var progToValue map[*obj.Prog]*ssa.Value
  4421  	var progToBlock map[*obj.Prog]*ssa.Block
  4422  	var valueToProg []*obj.Prog
  4423  	var logProgs = e.log
  4424  	if logProgs {
  4425  		progToValue = make(map[*obj.Prog]*ssa.Value, f.NumValues())
  4426  		progToBlock = make(map[*obj.Prog]*ssa.Block, f.NumBlocks())
  4427  		f.Logf("genssa %s\n", f.Name)
  4428  		progToBlock[s.pp.next] = f.Blocks[0]
  4429  	}
  4430  
  4431  	if thearch.Use387 {
  4432  		s.SSEto387 = map[int16]int16{}
  4433  	}
  4434  
  4435  	s.ScratchFpMem = e.scratchFpMem
  4436  
  4437  	logLocationLists := Debug_locationlist != 0
  4438  	if Ctxt.Flag_locationlists {
  4439  		e.curfn.Func.DebugInfo = ssa.BuildFuncDebug(f, logLocationLists)
  4440  		valueToProg = make([]*obj.Prog, f.NumValues())
  4441  	}
  4442  	// Emit basic blocks
  4443  	for i, b := range f.Blocks {
  4444  		s.bstart[b.ID] = s.pp.next
  4445  		// Emit values in block
  4446  		thearch.SSAMarkMoves(&s, b)
  4447  		for _, v := range b.Values {
  4448  			x := s.pp.next
  4449  			s.DebugFriendlySetPosFrom(v)
  4450  			switch v.Op {
  4451  			case ssa.OpInitMem:
  4452  				// memory arg needs no code
  4453  			case ssa.OpArg:
  4454  				// input args need no code
  4455  			case ssa.OpSP, ssa.OpSB:
  4456  				// nothing to do
  4457  			case ssa.OpSelect0, ssa.OpSelect1:
  4458  				// nothing to do
  4459  			case ssa.OpGetG:
  4460  				// nothing to do when there's a g register,
  4461  				// and checkLower complains if there's not
  4462  			case ssa.OpVarDef, ssa.OpVarLive, ssa.OpKeepAlive:
  4463  				// nothing to do; already used by liveness
  4464  			case ssa.OpVarKill:
  4465  				// Zero variable if it is ambiguously live.
  4466  				// After the VARKILL anything this variable references
  4467  				// might be collected. If it were to become live again later,
  4468  				// the GC will see references to already-collected objects.
  4469  				// See issue 20029.
  4470  				n := v.Aux.(*Node)
  4471  				if n.Name.Needzero() {
  4472  					if n.Class() != PAUTO {
  4473  						v.Fatalf("zero of variable which isn't PAUTO %v", n)
  4474  					}
  4475  					if n.Type.Size()%int64(Widthptr) != 0 {
  4476  						v.Fatalf("zero of variable not a multiple of ptr size %v", n)
  4477  					}
  4478  					thearch.ZeroAuto(s.pp, n)
  4479  				}
  4480  			case ssa.OpPhi:
  4481  				CheckLoweredPhi(v)
  4482  			case ssa.OpRegKill:
  4483  				// nothing to do
  4484  			default:
  4485  				// let the backend handle it
  4486  				thearch.SSAGenValue(&s, v)
  4487  			}
  4488  
  4489  			if Ctxt.Flag_locationlists {
  4490  				valueToProg[v.ID] = x
  4491  			}
  4492  			if logProgs {
  4493  				for ; x != s.pp.next; x = x.Link {
  4494  					progToValue[x] = v
  4495  				}
  4496  			}
  4497  		}
  4498  		// Emit control flow instructions for block
  4499  		var next *ssa.Block
  4500  		if i < len(f.Blocks)-1 && Debug['N'] == 0 {
  4501  			// If -N, leave next==nil so every block with successors
  4502  			// ends in a JMP (except call blocks - plive doesn't like
  4503  			// select{send,recv} followed by a JMP call).  Helps keep
  4504  			// line numbers for otherwise empty blocks.
  4505  			next = f.Blocks[i+1]
  4506  		}
  4507  		x := s.pp.next
  4508  		s.SetPos(b.Pos)
  4509  		thearch.SSAGenBlock(&s, b, next)
  4510  		if logProgs {
  4511  			for ; x != s.pp.next; x = x.Link {
  4512  				progToBlock[x] = b
  4513  			}
  4514  		}
  4515  	}
  4516  
  4517  	if Ctxt.Flag_locationlists {
  4518  		for _, locList := range e.curfn.Func.DebugInfo.Variables {
  4519  			for _, loc := range locList.Locations {
  4520  				loc.StartProg = valueToProg[loc.Start.ID]
  4521  				if loc.End == nil {
  4522  					Fatalf("empty loc %v compiling %v", loc, f.Name)
  4523  				}
  4524  				loc.EndProg = valueToProg[loc.End.ID]
  4525  				if !logLocationLists {
  4526  					loc.Start = nil
  4527  					loc.End = nil
  4528  				}
  4529  			}
  4530  		}
  4531  	}
  4532  
  4533  	// Resolve branches
  4534  	for _, br := range s.Branches {
  4535  		br.P.To.Val = s.bstart[br.B.ID]
  4536  	}
  4537  
  4538  	if logProgs {
  4539  		for p := pp.Text; p != nil; p = p.Link {
  4540  			var s string
  4541  			if v, ok := progToValue[p]; ok {
  4542  				s = v.String()
  4543  			} else if b, ok := progToBlock[p]; ok {
  4544  				s = b.String()
  4545  			} else {
  4546  				s = "   " // most value and branch strings are 2-3 characters long
  4547  			}
  4548  			f.Logf("%s\t%s\n", s, p)
  4549  		}
  4550  		if f.HTMLWriter != nil {
  4551  			// LineHist is defunct now - this code won't do
  4552  			// anything.
  4553  			// TODO: fix this (ideally without a global variable)
  4554  			// saved := pp.Text.Ctxt.LineHist.PrintFilenameOnly
  4555  			// pp.Text.Ctxt.LineHist.PrintFilenameOnly = true
  4556  			var buf bytes.Buffer
  4557  			buf.WriteString("<code>")
  4558  			buf.WriteString("<dl class=\"ssa-gen\">")
  4559  			for p := pp.Text; p != nil; p = p.Link {
  4560  				buf.WriteString("<dt class=\"ssa-prog-src\">")
  4561  				if v, ok := progToValue[p]; ok {
  4562  					buf.WriteString(v.HTML())
  4563  				} else if b, ok := progToBlock[p]; ok {
  4564  					buf.WriteString(b.HTML())
  4565  				}
  4566  				buf.WriteString("</dt>")
  4567  				buf.WriteString("<dd class=\"ssa-prog\">")
  4568  				buf.WriteString(html.EscapeString(p.String()))
  4569  				buf.WriteString("</dd>")
  4570  				buf.WriteString("</li>")
  4571  			}
  4572  			buf.WriteString("</dl>")
  4573  			buf.WriteString("</code>")
  4574  			f.HTMLWriter.WriteColumn("genssa", buf.String())
  4575  			// pp.Text.Ctxt.LineHist.PrintFilenameOnly = saved
  4576  		}
  4577  	}
  4578  
  4579  	defframe(&s, e)
  4580  	if Debug['f'] != 0 {
  4581  		frame(0)
  4582  	}
  4583  
  4584  	f.HTMLWriter.Close()
  4585  	f.HTMLWriter = nil
  4586  }
  4587  
  4588  func defframe(s *SSAGenState, e *ssafn) {
  4589  	pp := s.pp
  4590  
  4591  	frame := Rnd(s.maxarg+e.stksize, int64(Widthreg))
  4592  	if thearch.PadFrame != nil {
  4593  		frame = thearch.PadFrame(frame)
  4594  	}
  4595  
  4596  	// Fill in argument and frame size.
  4597  	pp.Text.To.Type = obj.TYPE_TEXTSIZE
  4598  	pp.Text.To.Val = int32(Rnd(e.curfn.Type.ArgWidth(), int64(Widthreg)))
  4599  	pp.Text.To.Offset = frame
  4600  
  4601  	// Insert code to zero ambiguously live variables so that the
  4602  	// garbage collector only sees initialized values when it
  4603  	// looks for pointers.
  4604  	p := pp.Text
  4605  	var lo, hi int64
  4606  
  4607  	// Opaque state for backend to use. Current backends use it to
  4608  	// keep track of which helper registers have been zeroed.
  4609  	var state uint32
  4610  
  4611  	// Iterate through declarations. They are sorted in decreasing Xoffset order.
  4612  	for _, n := range e.curfn.Func.Dcl {
  4613  		if !n.Name.Needzero() {
  4614  			continue
  4615  		}
  4616  		if n.Class() != PAUTO {
  4617  			Fatalf("needzero class %d", n.Class())
  4618  		}
  4619  		if n.Type.Size()%int64(Widthptr) != 0 || n.Xoffset%int64(Widthptr) != 0 || n.Type.Size() == 0 {
  4620  			Fatalf("var %L has size %d offset %d", n, n.Type.Size(), n.Xoffset)
  4621  		}
  4622  
  4623  		if lo != hi && n.Xoffset+n.Type.Size() >= lo-int64(2*Widthreg) {
  4624  			// Merge with range we already have.
  4625  			lo = n.Xoffset
  4626  			continue
  4627  		}
  4628  
  4629  		// Zero old range
  4630  		p = thearch.ZeroRange(pp, p, frame+lo, hi-lo, &state)
  4631  
  4632  		// Set new range.
  4633  		lo = n.Xoffset
  4634  		hi = lo + n.Type.Size()
  4635  	}
  4636  
  4637  	// Zero final range.
  4638  	thearch.ZeroRange(pp, p, frame+lo, hi-lo, &state)
  4639  }
  4640  
  4641  type FloatingEQNEJump struct {
  4642  	Jump  obj.As
  4643  	Index int
  4644  }
  4645  
  4646  func (s *SSAGenState) oneFPJump(b *ssa.Block, jumps *FloatingEQNEJump) {
  4647  	p := s.Prog(jumps.Jump)
  4648  	p.To.Type = obj.TYPE_BRANCH
  4649  	to := jumps.Index
  4650  	s.Branches = append(s.Branches, Branch{p, b.Succs[to].Block()})
  4651  }
  4652  
  4653  func (s *SSAGenState) FPJump(b, next *ssa.Block, jumps *[2][2]FloatingEQNEJump) {
  4654  	switch next {
  4655  	case b.Succs[0].Block():
  4656  		s.oneFPJump(b, &jumps[0][0])
  4657  		s.oneFPJump(b, &jumps[0][1])
  4658  	case b.Succs[1].Block():
  4659  		s.oneFPJump(b, &jumps[1][0])
  4660  		s.oneFPJump(b, &jumps[1][1])
  4661  	default:
  4662  		s.oneFPJump(b, &jumps[1][0])
  4663  		s.oneFPJump(b, &jumps[1][1])
  4664  		q := s.Prog(obj.AJMP)
  4665  		q.To.Type = obj.TYPE_BRANCH
  4666  		s.Branches = append(s.Branches, Branch{q, b.Succs[1].Block()})
  4667  	}
  4668  }
  4669  
  4670  func AuxOffset(v *ssa.Value) (offset int64) {
  4671  	if v.Aux == nil {
  4672  		return 0
  4673  	}
  4674  	switch sym := v.Aux.(type) {
  4675  
  4676  	case *ssa.AutoSymbol:
  4677  		n := sym.Node.(*Node)
  4678  		return n.Xoffset
  4679  	}
  4680  	return 0
  4681  }
  4682  
  4683  // AddAux adds the offset in the aux fields (AuxInt and Aux) of v to a.
  4684  func AddAux(a *obj.Addr, v *ssa.Value) {
  4685  	AddAux2(a, v, v.AuxInt)
  4686  }
  4687  func AddAux2(a *obj.Addr, v *ssa.Value, offset int64) {
  4688  	if a.Type != obj.TYPE_MEM && a.Type != obj.TYPE_ADDR {
  4689  		v.Fatalf("bad AddAux addr %v", a)
  4690  	}
  4691  	// add integer offset
  4692  	a.Offset += offset
  4693  
  4694  	// If no additional symbol offset, we're done.
  4695  	if v.Aux == nil {
  4696  		return
  4697  	}
  4698  	// Add symbol's offset from its base register.
  4699  	switch sym := v.Aux.(type) {
  4700  	case *ssa.ExternSymbol:
  4701  		a.Name = obj.NAME_EXTERN
  4702  		a.Sym = sym.Sym
  4703  	case *ssa.ArgSymbol:
  4704  		n := sym.Node.(*Node)
  4705  		a.Name = obj.NAME_PARAM
  4706  		a.Sym = n.Orig.Sym.Linksym()
  4707  		a.Offset += n.Xoffset
  4708  	case *ssa.AutoSymbol:
  4709  		n := sym.Node.(*Node)
  4710  		a.Name = obj.NAME_AUTO
  4711  		a.Sym = n.Sym.Linksym()
  4712  		a.Offset += n.Xoffset
  4713  	default:
  4714  		v.Fatalf("aux in %s not implemented %#v", v, v.Aux)
  4715  	}
  4716  }
  4717  
  4718  // extendIndex extends v to a full int width.
  4719  // panic using the given function if v does not fit in an int (only on 32-bit archs).
  4720  func (s *state) extendIndex(v *ssa.Value, panicfn *obj.LSym) *ssa.Value {
  4721  	size := v.Type.Size()
  4722  	if size == s.config.PtrSize {
  4723  		return v
  4724  	}
  4725  	if size > s.config.PtrSize {
  4726  		// truncate 64-bit indexes on 32-bit pointer archs. Test the
  4727  		// high word and branch to out-of-bounds failure if it is not 0.
  4728  		if Debug['B'] == 0 {
  4729  			hi := s.newValue1(ssa.OpInt64Hi, types.Types[TUINT32], v)
  4730  			cmp := s.newValue2(ssa.OpEq32, types.Types[TBOOL], hi, s.constInt32(types.Types[TUINT32], 0))
  4731  			s.check(cmp, panicfn)
  4732  		}
  4733  		return s.newValue1(ssa.OpTrunc64to32, types.Types[TINT], v)
  4734  	}
  4735  
  4736  	// Extend value to the required size
  4737  	var op ssa.Op
  4738  	if v.Type.IsSigned() {
  4739  		switch 10*size + s.config.PtrSize {
  4740  		case 14:
  4741  			op = ssa.OpSignExt8to32
  4742  		case 18:
  4743  			op = ssa.OpSignExt8to64
  4744  		case 24:
  4745  			op = ssa.OpSignExt16to32
  4746  		case 28:
  4747  			op = ssa.OpSignExt16to64
  4748  		case 48:
  4749  			op = ssa.OpSignExt32to64
  4750  		default:
  4751  			s.Fatalf("bad signed index extension %s", v.Type)
  4752  		}
  4753  	} else {
  4754  		switch 10*size + s.config.PtrSize {
  4755  		case 14:
  4756  			op = ssa.OpZeroExt8to32
  4757  		case 18:
  4758  			op = ssa.OpZeroExt8to64
  4759  		case 24:
  4760  			op = ssa.OpZeroExt16to32
  4761  		case 28:
  4762  			op = ssa.OpZeroExt16to64
  4763  		case 48:
  4764  			op = ssa.OpZeroExt32to64
  4765  		default:
  4766  			s.Fatalf("bad unsigned index extension %s", v.Type)
  4767  		}
  4768  	}
  4769  	return s.newValue1(op, types.Types[TINT], v)
  4770  }
  4771  
  4772  // CheckLoweredPhi checks that regalloc and stackalloc correctly handled phi values.
  4773  // Called during ssaGenValue.
  4774  func CheckLoweredPhi(v *ssa.Value) {
  4775  	if v.Op != ssa.OpPhi {
  4776  		v.Fatalf("CheckLoweredPhi called with non-phi value: %v", v.LongString())
  4777  	}
  4778  	if v.Type.IsMemory() {
  4779  		return
  4780  	}
  4781  	f := v.Block.Func
  4782  	loc := f.RegAlloc[v.ID]
  4783  	for _, a := range v.Args {
  4784  		if aloc := f.RegAlloc[a.ID]; aloc != loc { // TODO: .Equal() instead?
  4785  			v.Fatalf("phi arg at different location than phi: %v @ %s, but arg %v @ %s\n%s\n", v, loc, a, aloc, v.Block.Func)
  4786  		}
  4787  	}
  4788  }
  4789  
  4790  // CheckLoweredGetClosurePtr checks that v is the first instruction in the function's entry block.
  4791  // The output of LoweredGetClosurePtr is generally hardwired to the correct register.
  4792  // That register contains the closure pointer on closure entry.
  4793  func CheckLoweredGetClosurePtr(v *ssa.Value) {
  4794  	entry := v.Block.Func.Entry
  4795  	if entry != v.Block || entry.Values[0] != v {
  4796  		Fatalf("in %s, badly placed LoweredGetClosurePtr: %v %v", v.Block.Func.Name, v.Block, v)
  4797  	}
  4798  }
  4799  
  4800  // AutoVar returns a *Node and int64 representing the auto variable and offset within it
  4801  // where v should be spilled.
  4802  func AutoVar(v *ssa.Value) (*Node, int64) {
  4803  	loc := v.Block.Func.RegAlloc[v.ID].(ssa.LocalSlot)
  4804  	if v.Type.Size() > loc.Type.Size() {
  4805  		v.Fatalf("spill/restore type %s doesn't fit in slot type %s", v.Type, loc.Type)
  4806  	}
  4807  	return loc.N.(*Node), loc.Off
  4808  }
  4809  
  4810  func AddrAuto(a *obj.Addr, v *ssa.Value) {
  4811  	n, off := AutoVar(v)
  4812  	a.Type = obj.TYPE_MEM
  4813  	a.Sym = n.Sym.Linksym()
  4814  	a.Reg = int16(thearch.REGSP)
  4815  	a.Offset = n.Xoffset + off
  4816  	if n.Class() == PPARAM || n.Class() == PPARAMOUT {
  4817  		a.Name = obj.NAME_PARAM
  4818  	} else {
  4819  		a.Name = obj.NAME_AUTO
  4820  	}
  4821  }
  4822  
  4823  func (s *SSAGenState) AddrScratch(a *obj.Addr) {
  4824  	if s.ScratchFpMem == nil {
  4825  		panic("no scratch memory available; forgot to declare usesScratch for Op?")
  4826  	}
  4827  	a.Type = obj.TYPE_MEM
  4828  	a.Name = obj.NAME_AUTO
  4829  	a.Sym = s.ScratchFpMem.Sym.Linksym()
  4830  	a.Reg = int16(thearch.REGSP)
  4831  	a.Offset = s.ScratchFpMem.Xoffset
  4832  }
  4833  
  4834  func (s *SSAGenState) Call(v *ssa.Value) *obj.Prog {
  4835  	idx, ok := s.stackMapIndex[v]
  4836  	if !ok {
  4837  		Fatalf("missing stack map index for %v", v.LongString())
  4838  	}
  4839  	p := s.Prog(obj.APCDATA)
  4840  	Addrconst(&p.From, objabi.PCDATA_StackMapIndex)
  4841  	Addrconst(&p.To, int64(idx))
  4842  
  4843  	if sym, _ := v.Aux.(*obj.LSym); sym == Deferreturn {
  4844  		// Deferred calls will appear to be returning to
  4845  		// the CALL deferreturn(SB) that we are about to emit.
  4846  		// However, the stack trace code will show the line
  4847  		// of the instruction byte before the return PC.
  4848  		// To avoid that being an unrelated instruction,
  4849  		// insert an actual hardware NOP that will have the right line number.
  4850  		// This is different from obj.ANOP, which is a virtual no-op
  4851  		// that doesn't make it into the instruction stream.
  4852  		thearch.Ginsnop(s.pp)
  4853  	}
  4854  
  4855  	p = s.Prog(obj.ACALL)
  4856  	if sym, ok := v.Aux.(*obj.LSym); ok {
  4857  		p.To.Type = obj.TYPE_MEM
  4858  		p.To.Name = obj.NAME_EXTERN
  4859  		p.To.Sym = sym
  4860  	} else {
  4861  		// TODO(mdempsky): Can these differences be eliminated?
  4862  		switch thearch.LinkArch.Family {
  4863  		case sys.AMD64, sys.I386, sys.PPC64, sys.S390X:
  4864  			p.To.Type = obj.TYPE_REG
  4865  		case sys.ARM, sys.ARM64, sys.MIPS, sys.MIPS64:
  4866  			p.To.Type = obj.TYPE_MEM
  4867  		default:
  4868  			Fatalf("unknown indirect call family")
  4869  		}
  4870  		p.To.Reg = v.Args[0].Reg()
  4871  	}
  4872  	if s.maxarg < v.AuxInt {
  4873  		s.maxarg = v.AuxInt
  4874  	}
  4875  	return p
  4876  }
  4877  
  4878  // fieldIdx finds the index of the field referred to by the ODOT node n.
  4879  func fieldIdx(n *Node) int {
  4880  	t := n.Left.Type
  4881  	f := n.Sym
  4882  	if !t.IsStruct() {
  4883  		panic("ODOT's LHS is not a struct")
  4884  	}
  4885  
  4886  	var i int
  4887  	for _, t1 := range t.Fields().Slice() {
  4888  		if t1.Sym != f {
  4889  			i++
  4890  			continue
  4891  		}
  4892  		if t1.Offset != n.Xoffset {
  4893  			panic("field offset doesn't match")
  4894  		}
  4895  		return i
  4896  	}
  4897  	panic(fmt.Sprintf("can't find field in expr %v\n", n))
  4898  
  4899  	// TODO: keep the result of this function somewhere in the ODOT Node
  4900  	// so we don't have to recompute it each time we need it.
  4901  }
  4902  
  4903  // ssafn holds frontend information about a function that the backend is processing.
  4904  // It also exports a bunch of compiler services for the ssa backend.
  4905  type ssafn struct {
  4906  	curfn        *Node
  4907  	strings      map[string]interface{} // map from constant string to data symbols
  4908  	scratchFpMem *Node                  // temp for floating point register / memory moves on some architectures
  4909  	stksize      int64                  // stack size for current frame
  4910  	stkptrsize   int64                  // prefix of stack containing pointers
  4911  	log          bool
  4912  }
  4913  
  4914  // StringData returns a symbol (a *types.Sym wrapped in an interface) which
  4915  // is the data component of a global string constant containing s.
  4916  func (e *ssafn) StringData(s string) interface{} {
  4917  	if aux, ok := e.strings[s]; ok {
  4918  		return aux
  4919  	}
  4920  	if e.strings == nil {
  4921  		e.strings = make(map[string]interface{})
  4922  	}
  4923  	data := stringsym(s)
  4924  	aux := &ssa.ExternSymbol{Sym: data}
  4925  	e.strings[s] = aux
  4926  	return aux
  4927  }
  4928  
  4929  func (e *ssafn) Auto(pos src.XPos, t *types.Type) ssa.GCNode {
  4930  	n := tempAt(pos, e.curfn, t) // Note: adds new auto to e.curfn.Func.Dcl list
  4931  	return n
  4932  }
  4933  
  4934  func (e *ssafn) SplitString(name ssa.LocalSlot) (ssa.LocalSlot, ssa.LocalSlot) {
  4935  	n := name.N.(*Node)
  4936  	ptrType := types.NewPtr(types.Types[TUINT8])
  4937  	lenType := types.Types[TINT]
  4938  	if n.Class() == PAUTO && !n.Addrtaken() {
  4939  		// Split this string up into two separate variables.
  4940  		p := e.splitSlot(&name, ".ptr", 0, ptrType)
  4941  		l := e.splitSlot(&name, ".len", ptrType.Size(), lenType)
  4942  		return p, l
  4943  	}
  4944  	// Return the two parts of the larger variable.
  4945  	return ssa.LocalSlot{N: n, Type: ptrType, Off: name.Off}, ssa.LocalSlot{N: n, Type: lenType, Off: name.Off + int64(Widthptr)}
  4946  }
  4947  
  4948  func (e *ssafn) SplitInterface(name ssa.LocalSlot) (ssa.LocalSlot, ssa.LocalSlot) {
  4949  	n := name.N.(*Node)
  4950  	t := types.NewPtr(types.Types[TUINT8])
  4951  	if n.Class() == PAUTO && !n.Addrtaken() {
  4952  		// Split this interface up into two separate variables.
  4953  		f := ".itab"
  4954  		if n.Type.IsEmptyInterface() {
  4955  			f = ".type"
  4956  		}
  4957  		c := e.splitSlot(&name, f, 0, t)
  4958  		d := e.splitSlot(&name, ".data", t.Size(), t)
  4959  		return c, d
  4960  	}
  4961  	// Return the two parts of the larger variable.
  4962  	return ssa.LocalSlot{N: n, Type: t, Off: name.Off}, ssa.LocalSlot{N: n, Type: t, Off: name.Off + int64(Widthptr)}
  4963  }
  4964  
  4965  func (e *ssafn) SplitSlice(name ssa.LocalSlot) (ssa.LocalSlot, ssa.LocalSlot, ssa.LocalSlot) {
  4966  	n := name.N.(*Node)
  4967  	ptrType := types.NewPtr(name.Type.ElemType())
  4968  	lenType := types.Types[TINT]
  4969  	if n.Class() == PAUTO && !n.Addrtaken() {
  4970  		// Split this slice up into three separate variables.
  4971  		p := e.splitSlot(&name, ".ptr", 0, ptrType)
  4972  		l := e.splitSlot(&name, ".len", ptrType.Size(), lenType)
  4973  		c := e.splitSlot(&name, ".cap", ptrType.Size()+lenType.Size(), lenType)
  4974  		return p, l, c
  4975  	}
  4976  	// Return the three parts of the larger variable.
  4977  	return ssa.LocalSlot{N: n, Type: ptrType, Off: name.Off},
  4978  		ssa.LocalSlot{N: n, Type: lenType, Off: name.Off + int64(Widthptr)},
  4979  		ssa.LocalSlot{N: n, Type: lenType, Off: name.Off + int64(2*Widthptr)}
  4980  }
  4981  
  4982  func (e *ssafn) SplitComplex(name ssa.LocalSlot) (ssa.LocalSlot, ssa.LocalSlot) {
  4983  	n := name.N.(*Node)
  4984  	s := name.Type.Size() / 2
  4985  	var t *types.Type
  4986  	if s == 8 {
  4987  		t = types.Types[TFLOAT64]
  4988  	} else {
  4989  		t = types.Types[TFLOAT32]
  4990  	}
  4991  	if n.Class() == PAUTO && !n.Addrtaken() {
  4992  		// Split this complex up into two separate variables.
  4993  		r := e.splitSlot(&name, ".real", 0, t)
  4994  		i := e.splitSlot(&name, ".imag", t.Size(), t)
  4995  		return r, i
  4996  	}
  4997  	// Return the two parts of the larger variable.
  4998  	return ssa.LocalSlot{N: n, Type: t, Off: name.Off}, ssa.LocalSlot{N: n, Type: t, Off: name.Off + s}
  4999  }
  5000  
  5001  func (e *ssafn) SplitInt64(name ssa.LocalSlot) (ssa.LocalSlot, ssa.LocalSlot) {
  5002  	n := name.N.(*Node)
  5003  	var t *types.Type
  5004  	if name.Type.IsSigned() {
  5005  		t = types.Types[TINT32]
  5006  	} else {
  5007  		t = types.Types[TUINT32]
  5008  	}
  5009  	if n.Class() == PAUTO && !n.Addrtaken() {
  5010  		// Split this int64 up into two separate variables.
  5011  		if thearch.LinkArch.ByteOrder == binary.BigEndian {
  5012  			return e.splitSlot(&name, ".hi", 0, t), e.splitSlot(&name, ".lo", t.Size(), types.Types[TUINT32])
  5013  		}
  5014  		return e.splitSlot(&name, ".hi", t.Size(), t), e.splitSlot(&name, ".lo", 0, types.Types[TUINT32])
  5015  	}
  5016  	// Return the two parts of the larger variable.
  5017  	if thearch.LinkArch.ByteOrder == binary.BigEndian {
  5018  		return ssa.LocalSlot{N: n, Type: t, Off: name.Off}, ssa.LocalSlot{N: n, Type: types.Types[TUINT32], Off: name.Off + 4}
  5019  	}
  5020  	return ssa.LocalSlot{N: n, Type: t, Off: name.Off + 4}, ssa.LocalSlot{N: n, Type: types.Types[TUINT32], Off: name.Off}
  5021  }
  5022  
  5023  func (e *ssafn) SplitStruct(name ssa.LocalSlot, i int) ssa.LocalSlot {
  5024  	n := name.N.(*Node)
  5025  	st := name.Type
  5026  	ft := st.FieldType(i)
  5027  	var offset int64
  5028  	for f := 0; f < i; f++ {
  5029  		offset += st.FieldType(f).Size()
  5030  	}
  5031  	if n.Class() == PAUTO && !n.Addrtaken() {
  5032  		// Note: the _ field may appear several times.  But
  5033  		// have no fear, identically-named but distinct Autos are
  5034  		// ok, albeit maybe confusing for a debugger.
  5035  		return e.splitSlot(&name, "."+st.FieldName(i), offset, ft)
  5036  	}
  5037  	return ssa.LocalSlot{N: n, Type: ft, Off: name.Off + st.FieldOff(i)}
  5038  }
  5039  
  5040  func (e *ssafn) SplitArray(name ssa.LocalSlot) ssa.LocalSlot {
  5041  	n := name.N.(*Node)
  5042  	at := name.Type
  5043  	if at.NumElem() != 1 {
  5044  		Fatalf("bad array size")
  5045  	}
  5046  	et := at.ElemType()
  5047  	if n.Class() == PAUTO && !n.Addrtaken() {
  5048  		return e.splitSlot(&name, "[0]", 0, et)
  5049  	}
  5050  	return ssa.LocalSlot{N: n, Type: et, Off: name.Off}
  5051  }
  5052  
  5053  func (e *ssafn) DerefItab(it *obj.LSym, offset int64) *obj.LSym {
  5054  	return itabsym(it, offset)
  5055  }
  5056  
  5057  // splitSlot returns a slot representing the data of parent starting at offset.
  5058  func (e *ssafn) splitSlot(parent *ssa.LocalSlot, suffix string, offset int64, t *types.Type) ssa.LocalSlot {
  5059  	s := &types.Sym{Name: parent.N.(*Node).Sym.Name + suffix, Pkg: localpkg}
  5060  
  5061  	n := new(Node)
  5062  	n.Name = new(Name)
  5063  	n.Op = ONAME
  5064  	n.Pos = parent.N.(*Node).Pos
  5065  	n.Orig = n
  5066  
  5067  	s.Def = asTypesNode(n)
  5068  	asNode(s.Def).Name.SetUsed(true)
  5069  	n.Sym = s
  5070  	n.Type = t
  5071  	n.SetClass(PAUTO)
  5072  	n.SetAddable(true)
  5073  	n.Esc = EscNever
  5074  	n.Name.Curfn = e.curfn
  5075  	e.curfn.Func.Dcl = append(e.curfn.Func.Dcl, n)
  5076  	dowidth(t)
  5077  	return ssa.LocalSlot{N: n, Type: t, Off: 0, SplitOf: parent, SplitOffset: offset}
  5078  }
  5079  
  5080  func (e *ssafn) CanSSA(t *types.Type) bool {
  5081  	return canSSAType(t)
  5082  }
  5083  
  5084  func (e *ssafn) Line(pos src.XPos) string {
  5085  	return linestr(pos)
  5086  }
  5087  
  5088  // Log logs a message from the compiler.
  5089  func (e *ssafn) Logf(msg string, args ...interface{}) {
  5090  	if e.log {
  5091  		fmt.Printf(msg, args...)
  5092  	}
  5093  }
  5094  
  5095  func (e *ssafn) Log() bool {
  5096  	return e.log
  5097  }
  5098  
  5099  // Fatal reports a compiler error and exits.
  5100  func (e *ssafn) Fatalf(pos src.XPos, msg string, args ...interface{}) {
  5101  	lineno = pos
  5102  	Fatalf(msg, args...)
  5103  }
  5104  
  5105  // Warnl reports a "warning", which is usually flag-triggered
  5106  // logging output for the benefit of tests.
  5107  func (e *ssafn) Warnl(pos src.XPos, fmt_ string, args ...interface{}) {
  5108  	Warnl(pos, fmt_, args...)
  5109  }
  5110  
  5111  func (e *ssafn) Debug_checknil() bool {
  5112  	return Debug_checknil != 0
  5113  }
  5114  
  5115  func (e *ssafn) Debug_wb() bool {
  5116  	return Debug_wb != 0
  5117  }
  5118  
  5119  func (e *ssafn) UseWriteBarrier() bool {
  5120  	return use_writebarrier
  5121  }
  5122  
  5123  func (e *ssafn) Syslook(name string) *obj.LSym {
  5124  	switch name {
  5125  	case "goschedguarded":
  5126  		return goschedguarded
  5127  	case "writeBarrier":
  5128  		return writeBarrier
  5129  	case "writebarrierptr":
  5130  		return writebarrierptr
  5131  	case "typedmemmove":
  5132  		return typedmemmove
  5133  	case "typedmemclr":
  5134  		return typedmemclr
  5135  	}
  5136  	Fatalf("unknown Syslook func %v", name)
  5137  	return nil
  5138  }
  5139  
  5140  func (n *Node) Typ() *types.Type {
  5141  	return n.Type
  5142  }