Source file src/cmd/compile/internal/ssagen/ssa.go

     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 ssagen
     6  
     7  import (
     8  	"bufio"
     9  	"bytes"
    10  	"cmp"
    11  	"fmt"
    12  	"go/constant"
    13  	"html"
    14  	"internal/buildcfg"
    15  	"internal/goexperiment"
    16  	"internal/runtime/gc"
    17  	"os"
    18  	"path/filepath"
    19  	"slices"
    20  	"strings"
    21  
    22  	"cmd/compile/internal/abi"
    23  	"cmd/compile/internal/base"
    24  	"cmd/compile/internal/ir"
    25  	"cmd/compile/internal/liveness"
    26  	"cmd/compile/internal/objw"
    27  	"cmd/compile/internal/reflectdata"
    28  	"cmd/compile/internal/rttype"
    29  	"cmd/compile/internal/ssa"
    30  	"cmd/compile/internal/ssa/block"
    31  	"cmd/compile/internal/ssa/ssaconfig"
    32  	"cmd/compile/internal/ssa/ssadebug"
    33  	"cmd/compile/internal/ssa/ssahtml"
    34  	"cmd/compile/internal/ssa/ssaop"
    35  	"cmd/compile/internal/staticdata"
    36  	"cmd/compile/internal/typecheck"
    37  	"cmd/compile/internal/types"
    38  	"cmd/internal/obj"
    39  	"cmd/internal/objabi"
    40  	"cmd/internal/src"
    41  	"cmd/internal/sys"
    42  
    43  	rtabi "internal/abi"
    44  )
    45  
    46  var ssaConfig *ssa.Config
    47  var ssaCaches []ssa.Cache
    48  
    49  var ssaDump string     // early copy of $GOSSAFUNC; the func name to dump output for
    50  var ssaDir string      // optional destination for ssa dump file
    51  var ssaDumpStdout bool // whether to dump to stdout
    52  var ssaDumpCFG string  // generate CFGs for these phases
    53  const ssaDumpFile = "ssa.html"
    54  
    55  // ssaDumpInlined holds all inlined functions when ssaDump contains a function name.
    56  var ssaDumpInlined []*ir.Func
    57  
    58  // Maximum size we will aggregate heap allocations of scalar locals.
    59  // Almost certainly can't hurt to be as big as the tiny allocator.
    60  // Might help to be a bit bigger.
    61  const maxAggregatedHeapAllocation = 16
    62  
    63  func DumpInline(fn *ir.Func) {
    64  	if ssaDump != "" && ssaDump == ir.FuncName(fn) {
    65  		ssaDumpInlined = append(ssaDumpInlined, fn)
    66  	}
    67  }
    68  
    69  func InitEnv() {
    70  	ssaDump = os.Getenv("GOSSAFUNC")
    71  	if ssaDump == "" {
    72  		ssaDump = base.Debug.Html
    73  	}
    74  	ssaDir = os.Getenv("GOSSADIR")
    75  	if ssaDump != "" {
    76  		if strings.HasSuffix(ssaDump, "+") {
    77  			ssaDump = ssaDump[:len(ssaDump)-1]
    78  			ssaDumpStdout = true
    79  		}
    80  		spl := strings.Split(ssaDump, ":")
    81  		if len(spl) > 1 {
    82  			ssaDump = spl[0]
    83  			ssaDumpCFG = spl[1]
    84  		}
    85  	}
    86  }
    87  
    88  func InitConfig(config *ssa.Config) {
    89  	ssaConfig = config
    90  
    91  	if Arch.SoftFloat {
    92  		softfloatInit()
    93  	}
    94  
    95  	// Generate a few pointer types that are uncommon in the frontend but common in the backend.
    96  	// Caching is disabled in the backend, so generating these here avoids allocations.
    97  	_ = types.NewPtr(types.Types[types.TINTER])                             // *interface{}
    98  	_ = types.NewPtr(types.NewPtr(types.Types[types.TSTRING]))              // **string
    99  	_ = types.NewPtr(types.NewSlice(types.Types[types.TINTER]))             // *[]interface{}
   100  	_ = types.NewPtr(types.NewPtr(types.ByteType))                          // **byte
   101  	_ = types.NewPtr(types.NewSlice(types.ByteType))                        // *[]byte
   102  	_ = types.NewPtr(types.NewSlice(types.Types[types.TSTRING]))            // *[]string
   103  	_ = types.NewPtr(types.NewPtr(types.NewPtr(types.Types[types.TUINT8]))) // ***uint8
   104  	_ = types.NewPtr(types.Types[types.TINT16])                             // *int16
   105  	_ = types.NewPtr(types.Types[types.TINT64])                             // *int64
   106  	_ = types.NewPtr(types.ErrorType)                                       // *error
   107  	_ = types.NewPtr(reflectdata.MapType())                                 // *internal/runtime/maps.Map
   108  	_ = types.NewPtr(deferstruct())                                         // *runtime._defer
   109  	types.NewPtrCacheEnabled = false
   110  
   111  	ssaConfig.Race = base.Flag.Race
   112  	ssaCaches = make([]ssa.Cache, base.Flag.LowerC)
   113  
   114  	// Set up some runtime functions we'll need to call.
   115  	ir.Syms.AssertE2I = typecheck.LookupRuntimeFunc("assertE2I")
   116  	ir.Syms.AssertE2I2 = typecheck.LookupRuntimeFunc("assertE2I2")
   117  	ir.Syms.CgoCheckMemmove = typecheck.LookupRuntimeFunc("cgoCheckMemmove")
   118  	ir.Syms.CgoCheckPtrWrite = typecheck.LookupRuntimeFunc("cgoCheckPtrWrite")
   119  	ir.Syms.CheckPtrAlignment = typecheck.LookupRuntimeFunc("checkptrAlignment")
   120  	ir.Syms.Deferproc = typecheck.LookupRuntimeFunc("deferproc")
   121  	ir.Syms.Deferprocat = typecheck.LookupRuntimeFunc("deferprocat")
   122  	ir.Syms.DeferprocStack = typecheck.LookupRuntimeFunc("deferprocStack")
   123  	ir.Syms.Deferreturn = typecheck.LookupRuntimeFunc("deferreturn")
   124  	ir.Syms.Duffcopy = typecheck.LookupRuntimeFunc("duffcopy")
   125  	ir.Syms.Duffzero = typecheck.LookupRuntimeFunc("duffzero")
   126  	ir.Syms.GCWriteBarrier[0] = typecheck.LookupRuntimeFunc("gcWriteBarrier1")
   127  	ir.Syms.GCWriteBarrier[1] = typecheck.LookupRuntimeFunc("gcWriteBarrier2")
   128  	ir.Syms.GCWriteBarrier[2] = typecheck.LookupRuntimeFunc("gcWriteBarrier3")
   129  	ir.Syms.GCWriteBarrier[3] = typecheck.LookupRuntimeFunc("gcWriteBarrier4")
   130  	ir.Syms.GCWriteBarrier[4] = typecheck.LookupRuntimeFunc("gcWriteBarrier5")
   131  	ir.Syms.GCWriteBarrier[5] = typecheck.LookupRuntimeFunc("gcWriteBarrier6")
   132  	ir.Syms.GCWriteBarrier[6] = typecheck.LookupRuntimeFunc("gcWriteBarrier7")
   133  	ir.Syms.GCWriteBarrier[7] = typecheck.LookupRuntimeFunc("gcWriteBarrier8")
   134  	ir.Syms.Goschedguarded = typecheck.LookupRuntimeFunc("goschedguarded")
   135  	ir.Syms.Growslice = typecheck.LookupRuntimeFunc("growslice")
   136  	ir.Syms.GrowsliceBuf = typecheck.LookupRuntimeFunc("growsliceBuf")
   137  	ir.Syms.GrowsliceBufNoAlias = typecheck.LookupRuntimeFunc("growsliceBufNoAlias")
   138  	ir.Syms.GrowsliceNoAlias = typecheck.LookupRuntimeFunc("growsliceNoAlias")
   139  	ir.Syms.MoveSlice = typecheck.LookupRuntimeFunc("moveSlice")
   140  	ir.Syms.MoveSliceNoScan = typecheck.LookupRuntimeFunc("moveSliceNoScan")
   141  	ir.Syms.MoveSliceNoCap = typecheck.LookupRuntimeFunc("moveSliceNoCap")
   142  	ir.Syms.MoveSliceNoCapNoScan = typecheck.LookupRuntimeFunc("moveSliceNoCapNoScan")
   143  	ir.Syms.InterfaceSwitch = typecheck.LookupRuntimeFunc("interfaceSwitch")
   144  	for i := 1; i < len(ir.Syms.MallocGCSmallNoScan); i++ {
   145  		ir.Syms.MallocGCSmallNoScan[i] = typecheck.LookupRuntimeFunc(fmt.Sprintf("mallocgcSmallNoScanSC%d", i))
   146  	}
   147  	for i := 1; i < len(ir.Syms.MallocGCSmallScanNoHeader); i++ {
   148  		ir.Syms.MallocGCSmallScanNoHeader[i] = typecheck.LookupRuntimeFunc(fmt.Sprintf("mallocgcSmallScanNoHeaderSC%d", i))
   149  	}
   150  	ir.Syms.MallocGCTiny = typecheck.LookupRuntimeFunc("mallocgcTinySC2")
   151  	ir.Syms.MallocGC = typecheck.LookupRuntimeFunc("mallocgc")
   152  	ir.Syms.Memmove = typecheck.LookupRuntimeFunc("memmove")
   153  	ir.Syms.Memequal = typecheck.LookupRuntimeFunc("memequal")
   154  	ir.Syms.Msanread = typecheck.LookupRuntimeFunc("msanread")
   155  	ir.Syms.Msanwrite = typecheck.LookupRuntimeFunc("msanwrite")
   156  	ir.Syms.Msanmove = typecheck.LookupRuntimeFunc("msanmove")
   157  	ir.Syms.Asanread = typecheck.LookupRuntimeFunc("asanread")
   158  	ir.Syms.Asanwrite = typecheck.LookupRuntimeFunc("asanwrite")
   159  	ir.Syms.Newobject = typecheck.LookupRuntimeFunc("newobject")
   160  	ir.Syms.Newproc = typecheck.LookupRuntimeFunc("newproc")
   161  	ir.Syms.PanicBounds = typecheck.LookupRuntimeFunc("panicBounds")
   162  	ir.Syms.PanicExtend = typecheck.LookupRuntimeFunc("panicExtend")
   163  	ir.Syms.Panicdivide = typecheck.LookupRuntimeFunc("panicdivide")
   164  	ir.Syms.PanicdottypeE = typecheck.LookupRuntimeFunc("panicdottypeE")
   165  	ir.Syms.PanicdottypeI = typecheck.LookupRuntimeFunc("panicdottypeI")
   166  	ir.Syms.Panicnildottype = typecheck.LookupRuntimeFunc("panicnildottype")
   167  	ir.Syms.Panicoverflow = typecheck.LookupRuntimeFunc("panicoverflow")
   168  	ir.Syms.Panicshift = typecheck.LookupRuntimeFunc("panicshift")
   169  	ir.Syms.PanicSimdImm = typecheck.LookupRuntimeFunc("panicSimdImm")
   170  	ir.Syms.Racefuncenter = typecheck.LookupRuntimeFunc("racefuncenter")
   171  	ir.Syms.Racefuncexit = typecheck.LookupRuntimeFunc("racefuncexit")
   172  	ir.Syms.Raceread = typecheck.LookupRuntimeFunc("raceread")
   173  	ir.Syms.Racereadrange = typecheck.LookupRuntimeFunc("racereadrange")
   174  	ir.Syms.Racewrite = typecheck.LookupRuntimeFunc("racewrite")
   175  	ir.Syms.Racewriterange = typecheck.LookupRuntimeFunc("racewriterange")
   176  	ir.Syms.TypeAssert = typecheck.LookupRuntimeFunc("typeAssert")
   177  	ir.Syms.WBZero = typecheck.LookupRuntimeFunc("wbZero")
   178  	ir.Syms.WBMove = typecheck.LookupRuntimeFunc("wbMove")
   179  	ir.Syms.X86HasAVX = typecheck.LookupRuntimeVar("x86HasAVX")                       // bool
   180  	ir.Syms.X86HasFMA = typecheck.LookupRuntimeVar("x86HasFMA")                       // bool
   181  	ir.Syms.X86HasPOPCNT = typecheck.LookupRuntimeVar("x86HasPOPCNT")                 // bool
   182  	ir.Syms.X86HasSSE41 = typecheck.LookupRuntimeVar("x86HasSSE41")                   // bool
   183  	ir.Syms.ARMHasVFPv4 = typecheck.LookupRuntimeVar("armHasVFPv4")                   // bool
   184  	ir.Syms.ARM64HasATOMICS = typecheck.LookupRuntimeVar("arm64HasATOMICS")           // bool
   185  	ir.Syms.Loong64HasLAMCAS = typecheck.LookupRuntimeVar("loong64HasLAMCAS")         // bool
   186  	ir.Syms.Loong64HasLAM_BH = typecheck.LookupRuntimeVar("loong64HasLAM_BH")         // bool
   187  	ir.Syms.Loong64HasDBAR_HINTS = typecheck.LookupRuntimeVar("loong64HasDBAR_HINTS") // bool
   188  	ir.Syms.Loong64HasLSX = typecheck.LookupRuntimeVar("loong64HasLSX")               // bool
   189  	ir.Syms.RISCV64HasV = typecheck.LookupRuntimeVar("riscv64HasV")                   // bool
   190  	ir.Syms.RISCV64HasZbb = typecheck.LookupRuntimeVar("riscv64HasZbb")               // bool
   191  	ir.Syms.Staticuint64s = typecheck.LookupRuntimeVar("staticuint64s")
   192  	ir.Syms.Typedmemmove = typecheck.LookupRuntimeFunc("typedmemmove")
   193  	ir.Syms.Udiv = typecheck.LookupRuntimeVar("udiv")                 // asm func with special ABI
   194  	ir.Syms.WriteBarrier = typecheck.LookupRuntimeVar("writeBarrier") // struct { bool; ... }
   195  	ir.Syms.Zerobase = typecheck.LookupRuntimeVar("zerobase")
   196  	ir.Syms.ZeroVal = typecheck.LookupRuntimeVar("zeroVal")
   197  
   198  	if Arch.LinkArch.Family == sys.Wasm {
   199  		BoundsCheckFunc[ssa.BoundsIndex] = typecheck.LookupRuntimeFunc("goPanicIndex")
   200  		BoundsCheckFunc[ssa.BoundsIndexU] = typecheck.LookupRuntimeFunc("goPanicIndexU")
   201  		BoundsCheckFunc[ssa.BoundsSliceAlen] = typecheck.LookupRuntimeFunc("goPanicSliceAlen")
   202  		BoundsCheckFunc[ssa.BoundsSliceAlenU] = typecheck.LookupRuntimeFunc("goPanicSliceAlenU")
   203  		BoundsCheckFunc[ssa.BoundsSliceAcap] = typecheck.LookupRuntimeFunc("goPanicSliceAcap")
   204  		BoundsCheckFunc[ssa.BoundsSliceAcapU] = typecheck.LookupRuntimeFunc("goPanicSliceAcapU")
   205  		BoundsCheckFunc[ssa.BoundsSliceB] = typecheck.LookupRuntimeFunc("goPanicSliceB")
   206  		BoundsCheckFunc[ssa.BoundsSliceBU] = typecheck.LookupRuntimeFunc("goPanicSliceBU")
   207  		BoundsCheckFunc[ssa.BoundsSlice3Alen] = typecheck.LookupRuntimeFunc("goPanicSlice3Alen")
   208  		BoundsCheckFunc[ssa.BoundsSlice3AlenU] = typecheck.LookupRuntimeFunc("goPanicSlice3AlenU")
   209  		BoundsCheckFunc[ssa.BoundsSlice3Acap] = typecheck.LookupRuntimeFunc("goPanicSlice3Acap")
   210  		BoundsCheckFunc[ssa.BoundsSlice3AcapU] = typecheck.LookupRuntimeFunc("goPanicSlice3AcapU")
   211  		BoundsCheckFunc[ssa.BoundsSlice3B] = typecheck.LookupRuntimeFunc("goPanicSlice3B")
   212  		BoundsCheckFunc[ssa.BoundsSlice3BU] = typecheck.LookupRuntimeFunc("goPanicSlice3BU")
   213  		BoundsCheckFunc[ssa.BoundsSlice3C] = typecheck.LookupRuntimeFunc("goPanicSlice3C")
   214  		BoundsCheckFunc[ssa.BoundsSlice3CU] = typecheck.LookupRuntimeFunc("goPanicSlice3CU")
   215  		BoundsCheckFunc[ssa.BoundsConvert] = typecheck.LookupRuntimeFunc("goPanicSliceConvert")
   216  	}
   217  
   218  	// Wasm (all asm funcs with special ABIs)
   219  	ir.Syms.WasmDiv = typecheck.LookupRuntimeVar("wasmDiv")
   220  	ir.Syms.WasmTruncS = typecheck.LookupRuntimeVar("wasmTruncS")
   221  	ir.Syms.WasmTruncU = typecheck.LookupRuntimeVar("wasmTruncU")
   222  	ir.Syms.SigPanic = typecheck.LookupRuntimeFunc("sigpanic")
   223  }
   224  
   225  func InitTables() {
   226  	initIntrinsics(nil)
   227  }
   228  
   229  // AbiForBodylessFuncStackMap returns the ABI for a bodyless function's stack map.
   230  // This is not necessarily the ABI used to call it.
   231  // Currently (1.17 dev) such a stack map is always ABI0;
   232  // any ABI wrapper that is present is nosplit, hence a precise
   233  // stack map is not needed there (the parameters survive only long
   234  // enough to call the wrapped assembly function).
   235  func AbiForBodylessFuncStackMap(fn *ir.Func) *abi.ABIConfig {
   236  	return ssaConfig.ABI0
   237  }
   238  
   239  // abiForFunc implements ABI policy for a function.
   240  // Passing a nil function returns the default ABI based on experiment configuration.
   241  func abiForFunc(fn *ir.Func, abi0, abi1 *abi.ABIConfig) *abi.ABIConfig {
   242  	if buildcfg.Experiment.RegabiArgs {
   243  		// Select the ABI based on the function's defining ABI.
   244  		if fn == nil {
   245  			return abi1
   246  		}
   247  		switch fn.ABI {
   248  		case obj.ABI0:
   249  			return abi0
   250  		case obj.ABIInternal:
   251  			// TODO(austin): Clean up the nomenclature here.
   252  			// It's not clear that "abi1" is ABIInternal.
   253  			return abi1
   254  		}
   255  		base.Fatalf("function %v has unknown ABI %v", fn, fn.ABI)
   256  		panic("not reachable")
   257  	}
   258  
   259  	a := abi0
   260  	if fn != nil {
   261  		if fn.Pragma&ir.RegisterParams != 0 { // TODO(register args) remove after register abi is working
   262  			a = abi1
   263  		}
   264  	}
   265  	return a
   266  }
   267  
   268  // emitOpenDeferInfo emits FUNCDATA information about the defers in a function
   269  // that is using open-coded defers.  This funcdata is used to determine the active
   270  // defers in a function and execute those defers during panic processing.
   271  //
   272  // The funcdata is all encoded in varints (since values will almost always be less than
   273  // 128, but stack offsets could potentially be up to 2Gbyte). All "locations" (offsets)
   274  // for stack variables are specified as the number of bytes below varp (pointer to the
   275  // top of the local variables) for their starting address. The format is:
   276  //
   277  //   - Offset of the deferBits variable
   278  //   - Offset of the first closure slot (the rest are laid out consecutively).
   279  func (s *state) emitOpenDeferInfo() {
   280  	firstOffset := s.openDefers[0].closureNode.FrameOffset()
   281  
   282  	// Verify that cmpstackvarlt laid out the slots in order.
   283  	for i, r := range s.openDefers {
   284  		have := r.closureNode.FrameOffset()
   285  		want := firstOffset + int64(i)*int64(types.PtrSize)
   286  		if have != want {
   287  			base.FatalfAt(s.curfn.Pos(), "unexpected frame offset for open-coded defer slot #%v: have %v, want %v", i, have, want)
   288  		}
   289  	}
   290  
   291  	x := base.Ctxt.Lookup(s.curfn.LSym.Name + ".opendefer")
   292  	x.Set(obj.AttrContentAddressable, true)
   293  	x.Align = 1
   294  	s.curfn.LSym.Func().OpenCodedDeferInfo = x
   295  
   296  	off := 0
   297  	off = objw.Uvarint(x, off, uint64(-s.deferBitsTemp.FrameOffset()))
   298  	off = objw.Uvarint(x, off, uint64(-firstOffset))
   299  }
   300  
   301  // buildssa builds an SSA function for fn.
   302  // worker indicates which of the backend workers is doing the processing.
   303  func buildssa(compiler ssa.Compiler, fn *ir.Func, worker int, isPgoHot bool) (*ssa.Func, ssa.HTMLWriter) {
   304  	name := ir.FuncName(fn)
   305  
   306  	abiSelf := abiForFunc(fn, ssaConfig.ABI0, ssaConfig.ABI1)
   307  
   308  	printssa := false
   309  	// match either a simple name e.g. "(*Reader).Reset", package.name e.g. "compress/gzip.(*Reader).Reset", or subpackage name "gzip.(*Reader).Reset"
   310  	// optionally allows an ABI suffix specification in the GOSSAHASH, e.g. "(*Reader).Reset<0>" etc
   311  	if strings.Contains(ssaDump, name) { // in all the cases the function name is entirely contained within the GOSSAFUNC string.
   312  		nameOptABI := name
   313  		if l := len(ssaDump); l > 1 && ssaDump[l-2] == ',' { // ABI specification
   314  			nameOptABI = ssa.FuncNameABI(name, abiSelf.Which())
   315  		} else if strings.HasSuffix(ssaDump, ">") { // if they use the linker syntax instead....
   316  			l := len(ssaDump)
   317  			if l >= 3 && ssaDump[l-3] == '<' {
   318  				nameOptABI = ssa.FuncNameABI(name, abiSelf.Which())
   319  				ssaDump = ssaDump[:l-3] + "," + ssaDump[l-2:l-1]
   320  			}
   321  		}
   322  		pkgDotName := base.Ctxt.Pkgpath + "." + nameOptABI
   323  		printssa = nameOptABI == ssaDump || // "(*Reader).Reset"
   324  			pkgDotName == ssaDump || // "compress/gzip.(*Reader).Reset"
   325  			strings.HasSuffix(pkgDotName, ssaDump) && strings.HasSuffix(pkgDotName, "/"+ssaDump) // "gzip.(*Reader).Reset"
   326  	}
   327  
   328  	var astBuf *bytes.Buffer
   329  	if printssa {
   330  		astBuf = &bytes.Buffer{}
   331  		ir.FDumpList(astBuf, "buildssa-body", fn.Body)
   332  		if ssaDumpStdout {
   333  			fmt.Println("generating SSA for", name)
   334  			fmt.Print(astBuf.String())
   335  		}
   336  	}
   337  
   338  	var s state
   339  	s.pushLine(fn.Pos())
   340  	defer s.popLine()
   341  
   342  	s.hasdefer = fn.HasDefer()
   343  	if fn.Pragma&ir.CgoUnsafeArgs != 0 {
   344  		s.cgoUnsafeArgs = true
   345  	}
   346  	s.checkPtrEnabled = ir.ShouldCheckPtr(fn, 1)
   347  
   348  	if base.Flag.Cfg.Instrumenting && fn.Pragma&ir.Norace == 0 && !fn.ABIWrapper() {
   349  		if !base.Flag.Race || !objabi.LookupPkgSpecial(fn.Sym().Pkg.Path).NoRaceFunc {
   350  			s.instrumentMemory = true
   351  			if base.Flag.Race {
   352  				s.instrumentEnterExit = true
   353  			}
   354  		}
   355  	}
   356  
   357  	fe := ssafn{
   358  		curfn: fn,
   359  		log:   printssa && ssaDumpStdout,
   360  	}
   361  	s.curfn = fn
   362  
   363  	cache := &ssaCaches[worker]
   364  	cache.Reset()
   365  
   366  	s.f = ssaConfig.NewFunc(&fe, cache)
   367  	s.config = ssaConfig
   368  	s.f.Type = fn.Type()
   369  	s.f.Name = name
   370  	s.f.PrintOrHtmlSSA = printssa
   371  	if fn.Pragma&ir.Nosplit != 0 {
   372  		s.f.NoSplit = true
   373  	}
   374  	s.f.ABI0 = ssaConfig.ABI0
   375  	s.f.ABI1 = ssaConfig.ABI1
   376  	s.f.ABIDefault = abiForFunc(nil, ssaConfig.ABI0, ssaConfig.ABI1)
   377  	s.f.ABISelf = abiSelf
   378  
   379  	s.panics = map[funcLine]*ssa.Block{}
   380  	s.softFloat = s.config.SoftFloat
   381  
   382  	// Allocate starting block
   383  	s.f.Entry = s.f.NewBlock(block.BlockPlain)
   384  	s.f.Entry.Pos = fn.Pos()
   385  	s.f.IsPgoHot = isPgoHot
   386  	var htmlWriter *ssahtml.HTMLWriter
   387  
   388  	if printssa {
   389  		ssaDF := ssaDumpFile
   390  		if ssaDir != "" {
   391  			ssaDF = filepath.Join(ssaDir, base.Ctxt.Pkgpath+"."+s.f.NameABI()+".html")
   392  			ssaD := filepath.Dir(ssaDF)
   393  			os.MkdirAll(ssaD, 0755)
   394  		}
   395  		htmlWriter = ssahtml.NewHTMLWriter(ssaDF, s.f, ssaDumpCFG, compiler.Passes())
   396  		// TODO: generate and print a mapping from nodes to values and blocks
   397  		dumpSourcesColumn(htmlWriter, fn)
   398  		htmlWriter.WriteAST("AST", astBuf)
   399  		s.f.FatalCleanup = htmlWriter.FatalCleanup
   400  	}
   401  
   402  	// Allocate starting values
   403  	s.labels = map[string]*ssaLabel{}
   404  	s.fwdVars = map[ir.Node]*ssa.Value{}
   405  	s.startmem = s.entryNewValue0(ssaop.OpInitMem, types.TypeMem)
   406  
   407  	s.hasOpenDefers = base.Flag.N == 0 && s.hasdefer && !s.curfn.OpenCodedDeferDisallowed()
   408  	switch {
   409  	case base.Debug.NoOpenDefer != 0:
   410  		s.hasOpenDefers = false
   411  	case s.hasOpenDefers && (base.Ctxt.Flag_shared || base.Ctxt.Flag_dynlink) && base.Ctxt.Arch.Name == "386":
   412  		// Don't support open-coded defers for 386 ONLY when using shared
   413  		// libraries, because there is extra code (added by rewriteToUseGot())
   414  		// preceding the deferreturn/ret code that we don't track correctly.
   415  		//
   416  		// TODO this restriction can be removed given adjusted offset in computeDeferReturn in cmd/link/internal/ld/pcln.go
   417  		s.hasOpenDefers = false
   418  	}
   419  	if s.hasOpenDefers && s.instrumentEnterExit {
   420  		// Skip doing open defers if we need to instrument function
   421  		// returns for the race detector, since we will not generate that
   422  		// code in the case of the extra deferreturn/ret segment.
   423  		s.hasOpenDefers = false
   424  	}
   425  	if s.hasOpenDefers {
   426  		// Similarly, skip if there are any heap-allocated result
   427  		// parameters that need to be copied back to their stack slots.
   428  		for _, f := range s.curfn.Type().Results() {
   429  			if !f.Nname.(*ir.Name).OnStack() {
   430  				s.hasOpenDefers = false
   431  				break
   432  			}
   433  		}
   434  	}
   435  	if s.hasOpenDefers &&
   436  		s.curfn.NumReturns*s.curfn.NumDefers > 15 {
   437  		// Since we are generating defer calls at every exit for
   438  		// open-coded defers, skip doing open-coded defers if there are
   439  		// too many returns (especially if there are multiple defers).
   440  		// Open-coded defers are most important for improving performance
   441  		// for smaller functions (which don't have many returns).
   442  		s.hasOpenDefers = false
   443  	}
   444  
   445  	s.sp = s.entryNewValue0(ssaop.OpSP, types.Types[types.TUINTPTR]) // TODO: use generic pointer type (unsafe.Pointer?) instead
   446  	s.sb = s.entryNewValue0(ssaop.OpSB, types.Types[types.TUINTPTR])
   447  
   448  	s.startBlock(s.f.Entry)
   449  	s.vars[memVar] = s.startmem
   450  	if s.hasOpenDefers {
   451  		// Create the deferBits variable and stack slot.  deferBits is a
   452  		// bitmask showing which of the open-coded defers in this function
   453  		// have been activated.
   454  		deferBitsTemp := typecheck.TempAt(src.NoXPos, s.curfn, types.Types[types.TUINT8])
   455  		deferBitsTemp.SetAddrtaken(true)
   456  		s.deferBitsTemp = deferBitsTemp
   457  		// For this value, AuxInt is initialized to zero by default
   458  		startDeferBits := s.entryNewValue0(ssaop.OpConst8, types.Types[types.TUINT8])
   459  		s.vars[deferBitsVar] = startDeferBits
   460  		s.deferBitsAddr = s.addr(deferBitsTemp)
   461  		s.store(types.Types[types.TUINT8], s.deferBitsAddr, startDeferBits)
   462  		// Make sure that the deferBits stack slot is kept alive (for use
   463  		// by panics) and stores to deferBits are not eliminated, even if
   464  		// all checking code on deferBits in the function exit can be
   465  		// eliminated, because the defer statements were all
   466  		// unconditional.
   467  		s.vars[memVar] = s.newValue1Apos(ssaop.OpVarLive, types.TypeMem, deferBitsTemp, s.mem(), false)
   468  	}
   469  
   470  	var params *abi.ABIParamResultInfo
   471  	params = s.f.ABISelf.ABIAnalyze(fn.Type(), true)
   472  
   473  	// The backend's stackframe pass prunes away entries from the fn's
   474  	// Dcl list, including PARAMOUT nodes that correspond to output
   475  	// params passed in registers. Walk the Dcl list and capture these
   476  	// nodes to a side list, so that we'll have them available during
   477  	// DWARF-gen later on. See issue 48573 for more details.
   478  	var debugInfo ssadebug.FuncDebug
   479  	for _, n := range fn.Dcl {
   480  		if n.Class == ir.PPARAMOUT && n.IsOutputParamInRegisters() {
   481  			debugInfo.RegOutputParams = append(debugInfo.RegOutputParams, n)
   482  		}
   483  	}
   484  	fn.DebugInfo = &debugInfo
   485  
   486  	// Generate addresses of local declarations
   487  	s.decladdrs = map[*ir.Name]*ssa.Value{}
   488  	for _, n := range fn.Dcl {
   489  		switch n.Class {
   490  		case ir.PPARAM:
   491  			// Be aware that blank and unnamed input parameters will not appear here, but do appear in the type
   492  			s.decladdrs[n] = s.entryNewValue2A(ssaop.OpLocalAddr, types.NewPtr(n.Type()), n, s.sp, s.startmem)
   493  		case ir.PPARAMOUT:
   494  			s.decladdrs[n] = s.entryNewValue2A(ssaop.OpLocalAddr, types.NewPtr(n.Type()), n, s.sp, s.startmem)
   495  		case ir.PAUTO:
   496  			// processed at each use, to prevent Addr coming
   497  			// before the decl.
   498  		default:
   499  			s.Fatalf("local variable with class %v unimplemented", n.Class)
   500  		}
   501  	}
   502  
   503  	s.f.OwnAux = ssa.OwnAuxCall(fn.LSym, params)
   504  
   505  	// Populate SSAable arguments.
   506  	for _, n := range fn.Dcl {
   507  		if n.Class == ir.PPARAM {
   508  			if s.canSSA(n) {
   509  				v := s.newValue0A(ssaop.OpArg, n.Type(), n)
   510  				s.vars[n] = v
   511  				s.addNamedValue(n, v) // This helps with debugging information, not needed for compilation itself.
   512  			} else { // address was taken AND/OR too large for SSA
   513  				paramAssignment := ssa.ParamAssignmentForArgName(s.f, n)
   514  				if len(paramAssignment.Registers) > 0 {
   515  					if ssa.CanSSA(n.Type()) { // SSA-able type, so address was taken -- receive value in OpArg, DO NOT bind to var, store immediately to memory.
   516  						v := s.newValue0A(ssaop.OpArg, n.Type(), n)
   517  						s.store(n.Type(), s.decladdrs[n], v)
   518  					} else { // Too big for SSA.
   519  						// Brute force, and early, do a bunch of stores from registers
   520  						// Note that expand calls knows about this and doesn't trouble itself with larger-than-SSA-able Args in registers.
   521  						s.storeParameterRegsToStack(s.f.ABISelf, paramAssignment, n, s.decladdrs[n], false)
   522  					}
   523  				}
   524  			}
   525  		}
   526  	}
   527  
   528  	// Populate closure variables.
   529  	if fn.Needctxt() {
   530  		clo := s.entryNewValue0(ssaop.OpGetClosurePtr, s.f.Config.Types.BytePtr)
   531  		if fn.RangeParent != nil && base.Flag.N != 0 {
   532  			// For a range body closure, keep its closure pointer live on the
   533  			// stack with a special name, so the debugger can look for it and
   534  			// find the parent frame.
   535  			sym := &types.Sym{Name: ".closureptr", Pkg: types.LocalPkg}
   536  			cloSlot := s.curfn.NewLocal(src.NoXPos, sym, s.f.Config.Types.BytePtr)
   537  			cloSlot.SetUsed(true)
   538  			cloSlot.SetEsc(ir.EscNever)
   539  			cloSlot.SetAddrtaken(true)
   540  			s.f.CloSlot = cloSlot
   541  			s.vars[memVar] = s.newValue1Apos(ssaop.OpVarDef, types.TypeMem, cloSlot, s.mem(), false)
   542  			addr := s.addr(cloSlot)
   543  			s.store(s.f.Config.Types.BytePtr, addr, clo)
   544  			// Keep it from being dead-store eliminated.
   545  			s.vars[memVar] = s.newValue1Apos(ssaop.OpVarLive, types.TypeMem, cloSlot, s.mem(), false)
   546  		}
   547  		csiter := typecheck.NewClosureStructIter(fn.ClosureVars)
   548  		for {
   549  			n, typ, offset := csiter.Next()
   550  			if n == nil {
   551  				break
   552  			}
   553  
   554  			ptr := s.newValue1I(ssaop.OpOffPtr, types.NewPtr(typ), offset, clo)
   555  
   556  			// If n is a small variable captured by value, promote
   557  			// it to PAUTO so it can be converted to SSA.
   558  			//
   559  			// Note: While we never capture a variable by value if
   560  			// the user took its address, we may have generated
   561  			// runtime calls that did (#43701). Since we don't
   562  			// convert Addrtaken variables to SSA anyway, no point
   563  			// in promoting them either.
   564  			if n.Byval() && !n.Addrtaken() && ssa.CanSSA(n.Type()) {
   565  				n.Class = ir.PAUTO
   566  				fn.Dcl = append(fn.Dcl, n)
   567  				s.assign(n, s.load(n.Type(), ptr), false, 0)
   568  				continue
   569  			}
   570  
   571  			if !n.Byval() {
   572  				ptr = s.load(typ, ptr)
   573  			}
   574  			s.setHeapaddr(fn.Pos(), n, ptr)
   575  		}
   576  	}
   577  
   578  	// Convert the AST-based IR to the SSA-based IR
   579  	if s.instrumentEnterExit {
   580  		s.rtcall(ir.Syms.Racefuncenter, true, nil, s.newValue0(ssaop.OpGetCallerPC, types.Types[types.TUINTPTR]))
   581  	}
   582  	s.zeroResults()
   583  	s.paramsToHeap()
   584  	s.stmtList(fn.Body)
   585  
   586  	// fallthrough to exit
   587  	if s.curBlock != nil {
   588  		s.pushLine(fn.Endlineno)
   589  		s.exit()
   590  		s.popLine()
   591  	}
   592  
   593  	for _, b := range s.f.Blocks {
   594  		if b.Pos != src.NoXPos {
   595  			s.updateUnsetPredPos(b)
   596  		}
   597  	}
   598  
   599  	if htmlWriter.Enabled() {
   600  		htmlWriter.WritePhase("before insert phis", "before insert phis")
   601  	}
   602  
   603  	s.insertPhis()
   604  
   605  	// Main call to ssa package to compile function
   606  	compiler.Compile(s.f, htmlWriter)
   607  
   608  	fe.AllocFrame(s.f)
   609  
   610  	if len(s.openDefers) != 0 {
   611  		s.emitOpenDeferInfo()
   612  	}
   613  
   614  	// Record incoming parameter spill information for morestack calls emitted in the assembler.
   615  	// This is done here, using all the parameters (used, partially used, and unused) because
   616  	// it mimics the behavior of the former ABI (everything stored) and because it's not 100%
   617  	// clear if naming conventions are respected in autogenerated code.
   618  	// TODO figure out exactly what's unused, don't spill it. Make liveness fine-grained, also.
   619  	for _, p := range params.InParams() {
   620  		typs, offs := p.RegisterTypesAndOffsets()
   621  		if len(offs) < len(typs) {
   622  			s.Fatalf("len(offs)=%d < len(typs)=%d, params=\n%s", len(offs), len(typs), params)
   623  		}
   624  		for i, t := range typs {
   625  			o := offs[i]                // offset within parameter
   626  			fo := p.FrameOffset(params) // offset of parameter in frame
   627  			reg := ssa.ObjRegForAbiReg(p.Registers[i], s.f.Config)
   628  			s.f.RegArgs = append(s.f.RegArgs, ssa.Spill{Reg: reg, Offset: fo + o, Type: t})
   629  		}
   630  	}
   631  
   632  	return s.f, htmlWriter
   633  }
   634  
   635  func (s *state) storeParameterRegsToStack(abi *abi.ABIConfig, paramAssignment *abi.ABIParamAssignment, n *ir.Name, addr *ssa.Value, pointersOnly bool) {
   636  	typs, offs := paramAssignment.RegisterTypesAndOffsets()
   637  	for i, t := range typs {
   638  		if pointersOnly && !t.IsPtrShaped() {
   639  			continue
   640  		}
   641  		r := paramAssignment.Registers[i]
   642  		o := offs[i]
   643  		op, reg := ssa.ArgOpAndRegisterFor(r, abi)
   644  		aux := &ssa.AuxNameOffset{Name: n, Offset: o}
   645  		v := s.newValue0I(op, t, reg)
   646  		v.Aux = aux
   647  		p := s.newValue1I(ssaop.OpOffPtr, types.NewPtr(t), o, addr)
   648  		s.store(t, p, v)
   649  	}
   650  }
   651  
   652  // zeroResults zeros the return values at the start of the function.
   653  // We need to do this very early in the function.  Defer might stop a
   654  // panic and show the return values as they exist at the time of
   655  // panic.  For precise stacks, the garbage collector assumes results
   656  // are always live, so we need to zero them before any allocations,
   657  // even allocations to move params/results to the heap.
   658  func (s *state) zeroResults() {
   659  	for _, f := range s.curfn.Type().Results() {
   660  		n := f.Nname.(*ir.Name)
   661  		if !n.OnStack() {
   662  			// The local which points to the return value is the
   663  			// thing that needs zeroing. This is already handled
   664  			// by a Needzero annotation in plive.go:(*liveness).epilogue.
   665  			continue
   666  		}
   667  		// Zero the stack location containing f.
   668  		if typ := n.Type(); ssa.CanSSA(typ) {
   669  			s.assign(n, s.zeroVal(typ), false, 0)
   670  		} else {
   671  			if typ.HasPointers() || ssa.IsMergeCandidate(n) {
   672  				s.vars[memVar] = s.newValue1A(ssaop.OpVarDef, types.TypeMem, n, s.mem())
   673  			}
   674  			s.zero(n.Type(), s.decladdrs[n])
   675  		}
   676  	}
   677  }
   678  
   679  // paramsToHeap produces code to allocate memory for heap-escaped parameters
   680  // and to copy non-result parameters' values from the stack.
   681  func (s *state) paramsToHeap() {
   682  	do := func(params []*types.Field) {
   683  		for _, f := range params {
   684  			if f.Nname == nil {
   685  				continue // anonymous or blank parameter
   686  			}
   687  			n := f.Nname.(*ir.Name)
   688  			if ir.IsBlank(n) || n.OnStack() {
   689  				continue
   690  			}
   691  			s.newHeapaddr(n)
   692  			if n.Class == ir.PPARAM {
   693  				s.move(n.Type(), s.expr(n.Heapaddr), s.decladdrs[n])
   694  			}
   695  		}
   696  	}
   697  
   698  	typ := s.curfn.Type()
   699  	do(typ.Recvs())
   700  	do(typ.Params())
   701  	do(typ.Results())
   702  }
   703  
   704  // allocSizeAndAlign returns the size and alignment of t.
   705  // Normally just t.Size() and t.Alignment(), but there
   706  // is a special case to handle 64-bit atomics on 32-bit systems.
   707  func allocSizeAndAlign(t *types.Type) (int64, int64) {
   708  	size, align := t.Size(), t.Alignment()
   709  	if types.PtrSize == 4 && align == 4 && size >= 8 {
   710  		// For 64-bit atomics on 32-bit systems.
   711  		size = types.RoundUp(size, 8)
   712  		align = 8
   713  	}
   714  	return size, align
   715  }
   716  func allocSize(t *types.Type) int64 {
   717  	size, _ := allocSizeAndAlign(t)
   718  	return size
   719  }
   720  func allocAlign(t *types.Type) int64 {
   721  	_, align := allocSizeAndAlign(t)
   722  	return align
   723  }
   724  
   725  // newHeapaddr allocates heap memory for n and sets its heap address.
   726  func (s *state) newHeapaddr(n *ir.Name) {
   727  	size := allocSize(n.Type())
   728  	if n.Type().HasPointers() || size >= maxAggregatedHeapAllocation || size == 0 {
   729  		s.setHeapaddr(n.Pos(), n, s.newObject(n.Type()))
   730  		return
   731  	}
   732  
   733  	// Do we have room together with our pending allocations?
   734  	// If not, flush all the current ones.
   735  	var used int64
   736  	for _, v := range s.pendingHeapAllocations {
   737  		used += allocSize(v.Type.Elem())
   738  	}
   739  	if used+size > maxAggregatedHeapAllocation {
   740  		s.flushPendingHeapAllocations()
   741  	}
   742  
   743  	var allocCall *ssa.Value // (SelectN [0] (call of runtime.newobject))
   744  	if len(s.pendingHeapAllocations) == 0 {
   745  		// Make an allocation, but the type being allocated is just
   746  		// the first pending object. We will come back and update it
   747  		// later if needed.
   748  		allocCall = s.newObjectNonSpecialized(n.Type(), nil)
   749  	} else {
   750  		allocCall = s.pendingHeapAllocations[0].Args[0]
   751  	}
   752  	// v is an offset to the shared allocation. Offsets are dummy 0s for now.
   753  	v := s.newValue1I(ssaop.OpOffPtr, n.Type().PtrTo(), 0, allocCall)
   754  
   755  	// Add to list of pending allocations.
   756  	s.pendingHeapAllocations = append(s.pendingHeapAllocations, v)
   757  
   758  	// Finally, record for posterity.
   759  	s.setHeapaddr(n.Pos(), n, v)
   760  }
   761  
   762  func (s *state) flushPendingHeapAllocations() {
   763  	pending := s.pendingHeapAllocations
   764  	if len(pending) == 0 {
   765  		return // nothing to do
   766  	}
   767  	s.pendingHeapAllocations = nil // reset state
   768  	ptr := pending[0].Args[0]      // The SelectN [0] op
   769  	call := ptr.Args[0]            // The runtime.newobject call
   770  
   771  	if len(pending) == 1 {
   772  		// Just a single object, do a standard allocation.
   773  		v := pending[0]
   774  		v.Op = ssaop.OpCopy // instead of OffPtr [0]
   775  		return
   776  	}
   777  
   778  	// Sort in decreasing alignment.
   779  	// This way we never have to worry about padding.
   780  	// (Stable not required; just cleaner to keep program order among equal alignments.)
   781  	slices.SortStableFunc(pending, func(x, y *ssa.Value) int {
   782  		return cmp.Compare(allocAlign(y.Type.Elem()), allocAlign(x.Type.Elem()))
   783  	})
   784  
   785  	// Figure out how much data we need allocate.
   786  	var size int64
   787  	for _, v := range pending {
   788  		v.AuxInt = size // Adjust OffPtr to the right value while we are here.
   789  		size += allocSize(v.Type.Elem())
   790  	}
   791  	align := allocAlign(pending[0].Type.Elem())
   792  	size = types.RoundUp(size, align)
   793  
   794  	// Convert newObject call to a mallocgc call.
   795  	args := []*ssa.Value{
   796  		s.constInt(types.Types[types.TUINTPTR], size),
   797  		s.constNil(call.Args[0].Type), // a nil *runtime._type
   798  		s.constBool(true),             // needZero TODO: false is ok?
   799  		call.Args[1],                  // memory
   800  	}
   801  	mallocSym := ir.Syms.MallocGC
   802  	if specialMallocSym := s.specializedMallocSym(size, false); specialMallocSym != nil {
   803  		mallocSym = specialMallocSym
   804  	}
   805  	call.Aux = ssa.StaticAuxCall(mallocSym, s.f.ABIDefault.ABIAnalyzeTypes(
   806  		[]*types.Type{args[0].Type, args[1].Type, args[2].Type},
   807  		[]*types.Type{types.Types[types.TUNSAFEPTR]},
   808  	))
   809  	call.AuxInt = 4 * s.config.PtrSize // arg+results size, uintptr/ptr/bool/ptr
   810  	call.SetArgs4(args[0], args[1], args[2], args[3])
   811  	// TODO: figure out how to pass alignment to runtime
   812  
   813  	call.Type = types.NewTuple(types.Types[types.TUNSAFEPTR], types.TypeMem)
   814  	ptr.Type = types.Types[types.TUNSAFEPTR]
   815  }
   816  
   817  func (s *state) specializedMallocSym(size int64, hasPointers bool) *obj.LSym {
   818  	if !s.sizeSpecializedMallocEnabled() {
   819  		return nil
   820  	}
   821  	const specializedMallocMax = 80 // This must match the constant in mkmalloc.
   822  	if size > specializedMallocMax {
   823  		return nil
   824  	}
   825  	divRoundUp := func(n, a uintptr) uintptr { return (n + a - 1) / a }
   826  	sizeClass := gc.SizeToSizeClass8[divRoundUp(uintptr(size), gc.SmallSizeDiv)]
   827  	if hasPointers {
   828  		return ir.Syms.MallocGCSmallScanNoHeader[sizeClass]
   829  	}
   830  	if size < gc.TinySize {
   831  		return ir.Syms.MallocGCTiny
   832  	}
   833  	return ir.Syms.MallocGCSmallNoScan[sizeClass]
   834  }
   835  
   836  func (s *state) sizeSpecializedMallocEnabled() bool {
   837  	if base.Flag.CompilingRuntime {
   838  		// The compiler forces the values of the asan, msan, and race flags to false if
   839  		// we're compiling the runtime, so we lose the information about whether we're
   840  		// building in asan, msan, or race mode. Because the specialized functions don't
   841  		// work in that mode, just turn if off in that case.
   842  		// TODO(matloob): Save the information about whether the flags were passed in
   843  		// originally so we can turn off size specialized malloc in that case instead
   844  		// using Instrumenting below. Then we can remove this condition.
   845  		return false
   846  	}
   847  
   848  	return !base.Flag.Cfg.Instrumenting
   849  }
   850  
   851  // setHeapaddr allocates a new PAUTO variable to store ptr (which must be non-nil)
   852  // and then sets it as n's heap address.
   853  func (s *state) setHeapaddr(pos src.XPos, n *ir.Name, ptr *ssa.Value) {
   854  	if !ptr.Type.IsPtr() || !types.Identical(n.Type(), ptr.Type.Elem()) {
   855  		base.FatalfAt(n.Pos(), "setHeapaddr %L with type %v", n, ptr.Type)
   856  	}
   857  
   858  	// Declare variable to hold address.
   859  	sym := &types.Sym{Name: "&" + n.Sym().Name, Pkg: types.LocalPkg}
   860  	addr := s.curfn.NewLocal(pos, sym, types.NewPtr(n.Type()))
   861  	addr.SetUsed(true)
   862  	types.CalcSize(addr.Type())
   863  
   864  	if n.Class == ir.PPARAMOUT {
   865  		addr.SetIsOutputParamHeapAddr(true)
   866  	}
   867  
   868  	n.Heapaddr = addr
   869  	s.assign(addr, ptr, false, 0)
   870  }
   871  
   872  // newObject returns an SSA value denoting new(typ).
   873  func (s *state) newObject(typ *types.Type) *ssa.Value {
   874  	if typ.Size() == 0 {
   875  		return s.newValue1A(ssaop.OpAddr, types.NewPtr(typ), ir.Syms.Zerobase, s.sb)
   876  	}
   877  	rtype := s.reflectType(typ)
   878  	if specialMallocSym := s.specializedMallocSym(typ.Size(), typ.HasPointers()); specialMallocSym != nil {
   879  		return s.rtcall(specialMallocSym, true, []*types.Type{types.NewPtr(typ)},
   880  			s.constInt(types.Types[types.TUINTPTR], typ.Size()),
   881  			rtype,
   882  			s.constBool(true),
   883  		)[0]
   884  	}
   885  	return s.rtcall(ir.Syms.Newobject, true, []*types.Type{types.NewPtr(typ)}, rtype)[0]
   886  }
   887  
   888  // newObjectNonSpecialized returns an SSA value denoting new(typ). It does
   889  // not produce size-specialized malloc functions.
   890  func (s *state) newObjectNonSpecialized(typ *types.Type, rtype *ssa.Value) *ssa.Value {
   891  	if typ.Size() == 0 {
   892  		return s.newValue1A(ssaop.OpAddr, types.NewPtr(typ), ir.Syms.Zerobase, s.sb)
   893  	}
   894  	if rtype == nil {
   895  		rtype = s.reflectType(typ)
   896  	}
   897  	return s.rtcall(ir.Syms.Newobject, true, []*types.Type{types.NewPtr(typ)}, rtype)[0]
   898  }
   899  
   900  func (s *state) checkPtrAlignment(n *ir.ConvExpr, v *ssa.Value, count *ssa.Value) {
   901  	if !n.Type().IsPtr() {
   902  		s.Fatalf("expected pointer type: %v", n.Type())
   903  	}
   904  	elem, rtypeExpr := n.Type().Elem(), n.ElemRType
   905  	if count != nil {
   906  		if !elem.IsArray() {
   907  			s.Fatalf("expected array type: %v", elem)
   908  		}
   909  		elem, rtypeExpr = elem.Elem(), n.ElemElemRType
   910  	}
   911  	size := elem.Size()
   912  	// Casting from larger type to smaller one is ok, so for smallest type, do nothing.
   913  	if elem.Alignment() == 1 && (size == 0 || size == 1 || count == nil) {
   914  		return
   915  	}
   916  	if count == nil {
   917  		count = s.constInt(types.Types[types.TUINTPTR], 1)
   918  	}
   919  	if count.Type.Size() != s.config.PtrSize {
   920  		s.Fatalf("expected count fit to a uintptr size, have: %d, want: %d", count.Type.Size(), s.config.PtrSize)
   921  	}
   922  	var rtype *ssa.Value
   923  	if rtypeExpr != nil {
   924  		rtype = s.expr(rtypeExpr)
   925  	} else {
   926  		rtype = s.reflectType(elem)
   927  	}
   928  	s.rtcall(ir.Syms.CheckPtrAlignment, true, nil, v, rtype, count)
   929  }
   930  
   931  // reflectType returns an SSA value representing a pointer to typ's
   932  // reflection type descriptor.
   933  func (s *state) reflectType(typ *types.Type) *ssa.Value {
   934  	// TODO(mdempsky): Make this Fatalf under Unified IR; frontend needs
   935  	// to supply RType expressions.
   936  	lsym := reflectdata.TypeLinksym(typ)
   937  	return s.entryNewValue1A(ssaop.OpAddr, types.NewPtr(types.Types[types.TUINT8]), lsym, s.sb)
   938  }
   939  
   940  func dumpSourcesColumn(writer *ssahtml.HTMLWriter, fn *ir.Func) {
   941  	// Read sources of target function fn.
   942  	fname := base.Ctxt.PosTable.Pos(fn.Pos()).Filename()
   943  	targetFn, err := readFuncLines(fname, fn.Pos().Line(), fn.Endlineno.Line())
   944  	if err != nil {
   945  		writer.Logf("cannot read sources for function %v: %v", fn, err)
   946  	}
   947  
   948  	// Read sources of inlined functions.
   949  	var inlFns []*ssahtml.FuncLines
   950  	for _, fi := range ssaDumpInlined {
   951  		elno := fi.Endlineno
   952  		fname := base.Ctxt.PosTable.Pos(fi.Pos()).Filename()
   953  		fnLines, err := readFuncLines(fname, fi.Pos().Line(), elno.Line())
   954  		if err != nil {
   955  			writer.Logf("cannot read sources for inlined function %v: %v", fi, err)
   956  			continue
   957  		}
   958  		inlFns = append(inlFns, fnLines)
   959  	}
   960  
   961  	slices.SortFunc(inlFns, ssahtml.ByTopoCmp)
   962  	if targetFn != nil {
   963  		inlFns = append([]*ssahtml.FuncLines{targetFn}, inlFns...)
   964  	}
   965  
   966  	writer.WriteSources("sources", inlFns)
   967  }
   968  
   969  func readFuncLines(file string, start, end uint) (*ssahtml.FuncLines, error) {
   970  	f, err := os.Open(os.ExpandEnv(file))
   971  	if err != nil {
   972  		return nil, err
   973  	}
   974  	defer f.Close() // ignore error
   975  	var lines []string
   976  	ln := uint(1)
   977  	scanner := bufio.NewScanner(f)
   978  	for scanner.Scan() && ln <= end {
   979  		if ln >= start {
   980  			lines = append(lines, scanner.Text())
   981  		}
   982  		ln++
   983  	}
   984  	if err := scanner.Err(); err != nil {
   985  		return nil, fmt.Errorf("scanning %s: %v", file, err)
   986  	}
   987  	return &ssahtml.FuncLines{Filename: file, StartLineno: start, Lines: lines}, nil
   988  }
   989  
   990  // updateUnsetPredPos propagates the earliest-value position information for b
   991  // towards all of b's predecessors that need a position, and recurs on that
   992  // predecessor if its position is updated. B should have a non-empty position.
   993  func (s *state) updateUnsetPredPos(b *ssa.Block) {
   994  	if b.Pos == src.NoXPos {
   995  		s.Fatalf("Block %s should have a position", b)
   996  	}
   997  	bestPos := src.NoXPos
   998  	for _, e := range b.Preds {
   999  		p := e.Block()
  1000  		if !p.LackingPos() {
  1001  			continue
  1002  		}
  1003  		if bestPos == src.NoXPos {
  1004  			bestPos = b.Pos
  1005  			for _, v := range b.Values {
  1006  				if v.LackingPos() {
  1007  					continue
  1008  				}
  1009  				if v.Pos != src.NoXPos {
  1010  					// Assume values are still in roughly textual order;
  1011  					// TODO: could also seek minimum position?
  1012  					bestPos = v.Pos
  1013  					break
  1014  				}
  1015  			}
  1016  		}
  1017  		p.Pos = bestPos
  1018  		s.updateUnsetPredPos(p) // We do not expect long chains of these, thus recursion is okay.
  1019  	}
  1020  }
  1021  
  1022  // Information about each open-coded defer.
  1023  type openDeferInfo struct {
  1024  	// The node representing the call of the defer
  1025  	n *ir.CallExpr
  1026  	// If defer call is closure call, the address of the argtmp where the
  1027  	// closure is stored.
  1028  	closure *ssa.Value
  1029  	// The node representing the argtmp where the closure is stored - used for
  1030  	// function, method, or interface call, to store a closure that panic
  1031  	// processing can use for this defer.
  1032  	closureNode *ir.Name
  1033  }
  1034  
  1035  type state struct {
  1036  	// configuration (arch) information
  1037  	config *ssa.Config
  1038  
  1039  	// function we're building
  1040  	f *ssa.Func
  1041  
  1042  	// Node for function
  1043  	curfn *ir.Func
  1044  
  1045  	// labels in f
  1046  	labels map[string]*ssaLabel
  1047  
  1048  	// unlabeled break and continue statement tracking
  1049  	breakTo    *ssa.Block // current target for plain break statement
  1050  	continueTo *ssa.Block // current target for plain continue statement
  1051  
  1052  	// current location where we're interpreting the AST
  1053  	curBlock *ssa.Block
  1054  
  1055  	// variable assignments in the current block (map from variable symbol to ssa value)
  1056  	// *Node is the unique identifier (an ONAME Node) for the variable.
  1057  	// TODO: keep a single varnum map, then make all of these maps slices instead?
  1058  	vars map[ir.Node]*ssa.Value
  1059  
  1060  	// fwdVars are variables that are used before they are defined in the current block.
  1061  	// This map exists just to coalesce multiple references into a single FwdRef op.
  1062  	// *Node is the unique identifier (an ONAME Node) for the variable.
  1063  	fwdVars map[ir.Node]*ssa.Value
  1064  
  1065  	// all defined variables at the end of each block. Indexed by block ID.
  1066  	defvars []map[ir.Node]*ssa.Value
  1067  
  1068  	// addresses of PPARAM and PPARAMOUT variables on the stack.
  1069  	decladdrs map[*ir.Name]*ssa.Value
  1070  
  1071  	// starting values. Memory, stack pointer, and globals pointer
  1072  	startmem *ssa.Value
  1073  	sp       *ssa.Value
  1074  	sb       *ssa.Value
  1075  	// value representing address of where deferBits autotmp is stored
  1076  	deferBitsAddr *ssa.Value
  1077  	deferBitsTemp *ir.Name
  1078  
  1079  	// line number stack. The current line number is top of stack
  1080  	line []src.XPos
  1081  	// the last line number processed; it may have been popped
  1082  	lastPos src.XPos
  1083  
  1084  	// list of panic calls by function name and line number.
  1085  	// Used to deduplicate panic calls.
  1086  	panics map[funcLine]*ssa.Block
  1087  
  1088  	cgoUnsafeArgs       bool
  1089  	hasdefer            bool // whether the function contains a defer statement
  1090  	softFloat           bool
  1091  	hasOpenDefers       bool // whether we are doing open-coded defers
  1092  	checkPtrEnabled     bool // whether to insert checkptr instrumentation
  1093  	instrumentEnterExit bool // whether to instrument function enter/exit
  1094  	instrumentMemory    bool // whether to instrument memory operations
  1095  
  1096  	// If doing open-coded defers, list of info about the defer calls in
  1097  	// scanning order. Hence, at exit we should run these defers in reverse
  1098  	// order of this list
  1099  	openDefers []*openDeferInfo
  1100  	// For open-coded defers, this is the beginning and end blocks of the last
  1101  	// defer exit code that we have generated so far. We use these to share
  1102  	// code between exits if the shareDeferExits option (disabled by default)
  1103  	// is on.
  1104  	lastDeferExit       *ssa.Block // Entry block of last defer exit code we generated
  1105  	lastDeferFinalBlock *ssa.Block // Final block of last defer exit code we generated
  1106  	lastDeferCount      int        // Number of defers encountered at that point
  1107  
  1108  	prevCall *ssa.Value // the previous call; use this to tie results to the call op.
  1109  
  1110  	// List of allocations in the current block that are still pending.
  1111  	// They are all (OffPtr (Select0 (runtime call))) and have the correct types,
  1112  	// but the offsets are not set yet, and the type of the runtime call is also not final.
  1113  	pendingHeapAllocations []*ssa.Value
  1114  
  1115  	// First argument of append calls that could be stack allocated.
  1116  	appendTargets map[ir.Node]bool
  1117  
  1118  	// Block starting position, indexed by block id.
  1119  	blockStarts []src.XPos
  1120  
  1121  	// Information for stack allocation. Indexed by the first argument
  1122  	// to an append call. Normally a slice-typed variable, but not always.
  1123  	backingStores map[ir.Node]*backingStoreInfo
  1124  }
  1125  
  1126  type backingStoreInfo struct {
  1127  	// Size of backing store array (in elements)
  1128  	K int64
  1129  	// Stack-allocated backing store variable.
  1130  	store *ir.Name
  1131  	// Dynamic boolean variable marking the fact that we used this backing store.
  1132  	used *ir.Name
  1133  	// Have we used this variable statically yet? This is just a hint
  1134  	// to avoid checking the dynamic variable if the answer is obvious.
  1135  	// (usedStatic == true implies used == true)
  1136  	usedStatic bool
  1137  }
  1138  
  1139  type funcLine struct {
  1140  	f    *obj.LSym
  1141  	base *src.PosBase
  1142  	line uint
  1143  }
  1144  
  1145  type ssaLabel struct {
  1146  	target         *ssa.Block // block identified by this label
  1147  	breakTarget    *ssa.Block // block to break to in control flow node identified by this label
  1148  	continueTarget *ssa.Block // block to continue to in control flow node identified by this label
  1149  }
  1150  
  1151  // label returns the label associated with sym, creating it if necessary.
  1152  func (s *state) label(sym *types.Sym) *ssaLabel {
  1153  	lab := s.labels[sym.Name]
  1154  	if lab == nil {
  1155  		lab = new(ssaLabel)
  1156  		s.labels[sym.Name] = lab
  1157  	}
  1158  	return lab
  1159  }
  1160  
  1161  func (s *state) Logf(msg string, args ...any) { s.f.Logf(msg, args...) }
  1162  func (s *state) Log() bool                    { return s.f.Log() }
  1163  func (s *state) Fatalf(msg string, args ...any) {
  1164  	s.f.Frontend().Fatalf(s.peekPos(), msg, args...)
  1165  }
  1166  func (s *state) Warnl(pos src.XPos, msg string, args ...any) { s.f.Warnl(pos, msg, args...) }
  1167  func (s *state) Debug_checknil() bool                        { return s.f.Frontend().Debug_checknil() }
  1168  
  1169  func ssaMarker(name string) *ir.Name {
  1170  	return ir.NewNameAt(base.Pos, &types.Sym{Name: name}, nil)
  1171  }
  1172  
  1173  var (
  1174  	// marker node for the memory variable
  1175  	memVar = ssaMarker("mem")
  1176  
  1177  	// marker nodes for temporary variables
  1178  	ptrVar       = ssaMarker("ptr")
  1179  	lenVar       = ssaMarker("len")
  1180  	capVar       = ssaMarker("cap")
  1181  	typVar       = ssaMarker("typ")
  1182  	okVar        = ssaMarker("ok")
  1183  	deferBitsVar = ssaMarker("deferBits")
  1184  	hashVar      = ssaMarker("hash")
  1185  )
  1186  
  1187  // startBlock sets the current block we're generating code in to b.
  1188  func (s *state) startBlock(b *ssa.Block) {
  1189  	if s.curBlock != nil {
  1190  		s.Fatalf("starting block %v when block %v has not ended", b, s.curBlock)
  1191  	}
  1192  	s.curBlock = b
  1193  	s.vars = map[ir.Node]*ssa.Value{}
  1194  	clear(s.fwdVars)
  1195  	for len(s.blockStarts) <= int(b.ID) {
  1196  		s.blockStarts = append(s.blockStarts, src.NoXPos)
  1197  	}
  1198  }
  1199  
  1200  // endBlock marks the end of generating code for the current block.
  1201  // Returns the (former) current block. Returns nil if there is no current
  1202  // block, i.e. if no code flows to the current execution point.
  1203  func (s *state) endBlock() *ssa.Block {
  1204  	b := s.curBlock
  1205  	if b == nil {
  1206  		return nil
  1207  	}
  1208  
  1209  	s.flushPendingHeapAllocations()
  1210  
  1211  	for len(s.defvars) <= int(b.ID) {
  1212  		s.defvars = append(s.defvars, nil)
  1213  	}
  1214  	s.defvars[b.ID] = s.vars
  1215  	s.curBlock = nil
  1216  	s.vars = nil
  1217  	if b.LackingPos() {
  1218  		// Empty plain blocks get the line of their successor (handled after all blocks created),
  1219  		// except for increment blocks in For statements (handled in ssa conversion of OFOR),
  1220  		// and for blocks ending in GOTO/BREAK/CONTINUE.
  1221  		b.Pos = src.NoXPos
  1222  	} else {
  1223  		b.Pos = s.lastPos
  1224  		if s.blockStarts[b.ID] == src.NoXPos {
  1225  			s.blockStarts[b.ID] = s.lastPos
  1226  		}
  1227  	}
  1228  	return b
  1229  }
  1230  
  1231  // pushLine pushes a line number on the line number stack.
  1232  func (s *state) pushLine(line src.XPos) {
  1233  	if !line.IsKnown() {
  1234  		// the frontend may emit node with line number missing,
  1235  		// use the parent line number in this case.
  1236  		line = s.peekPos()
  1237  		if base.Flag.K != 0 {
  1238  			base.Warn("buildssa: unknown position (line 0)")
  1239  		}
  1240  	} else {
  1241  		s.lastPos = line
  1242  	}
  1243  	// The first position we see for a new block is its starting position
  1244  	// (the line number for its phis, if any).
  1245  	if b := s.curBlock; b != nil && s.blockStarts[b.ID] == src.NoXPos {
  1246  		s.blockStarts[b.ID] = line
  1247  	}
  1248  
  1249  	s.line = append(s.line, line)
  1250  }
  1251  
  1252  // popLine pops the top of the line number stack.
  1253  func (s *state) popLine() {
  1254  	s.line = s.line[:len(s.line)-1]
  1255  }
  1256  
  1257  // peekPos peeks the top of the line number stack.
  1258  func (s *state) peekPos() src.XPos {
  1259  	return s.line[len(s.line)-1]
  1260  }
  1261  
  1262  // newValue0 adds a new value with no arguments to the current block.
  1263  func (s *state) newValue0(op ssaop.Op, t *types.Type) *ssa.Value {
  1264  	return s.curBlock.NewValue0(s.peekPos(), op, t)
  1265  }
  1266  
  1267  // newValue0A adds a new value with no arguments and an aux value to the current block.
  1268  func (s *state) newValue0A(op ssaop.Op, t *types.Type, aux ssa.Aux) *ssa.Value {
  1269  	return s.curBlock.NewValue0A(s.peekPos(), op, t, aux)
  1270  }
  1271  
  1272  // newValue0I adds a new value with no arguments and an auxint value to the current block.
  1273  func (s *state) newValue0I(op ssaop.Op, t *types.Type, auxint int64) *ssa.Value {
  1274  	return s.curBlock.NewValue0I(s.peekPos(), op, t, auxint)
  1275  }
  1276  
  1277  // newValue1 adds a new value with one argument to the current block.
  1278  func (s *state) newValue1(op ssaop.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
  1279  	return s.curBlock.NewValue1(s.peekPos(), op, t, arg)
  1280  }
  1281  
  1282  // newValue1A adds a new value with one argument and an aux value to the current block.
  1283  func (s *state) newValue1A(op ssaop.Op, t *types.Type, aux ssa.Aux, arg *ssa.Value) *ssa.Value {
  1284  	return s.curBlock.NewValue1A(s.peekPos(), op, t, aux, arg)
  1285  }
  1286  
  1287  // newValue1Apos adds a new value with one argument and an aux value to the current block.
  1288  // isStmt determines whether the created values may be a statement or not
  1289  // (i.e., false means never, yes means maybe).
  1290  func (s *state) newValue1Apos(op ssaop.Op, t *types.Type, aux ssa.Aux, arg *ssa.Value, isStmt bool) *ssa.Value {
  1291  	if isStmt {
  1292  		return s.curBlock.NewValue1A(s.peekPos(), op, t, aux, arg)
  1293  	}
  1294  	return s.curBlock.NewValue1A(s.peekPos().WithNotStmt(), op, t, aux, arg)
  1295  }
  1296  
  1297  // newValue1I adds a new value with one argument and an auxint value to the current block.
  1298  func (s *state) newValue1I(op ssaop.Op, t *types.Type, aux int64, arg *ssa.Value) *ssa.Value {
  1299  	return s.curBlock.NewValue1I(s.peekPos(), op, t, aux, arg)
  1300  }
  1301  
  1302  // newValue2 adds a new value with two arguments to the current block.
  1303  func (s *state) newValue2(op ssaop.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
  1304  	return s.curBlock.NewValue2(s.peekPos(), op, t, arg0, arg1)
  1305  }
  1306  
  1307  // newValue2A adds a new value with two arguments and an aux value to the current block.
  1308  func (s *state) newValue2A(op ssaop.Op, t *types.Type, aux ssa.Aux, arg0, arg1 *ssa.Value) *ssa.Value {
  1309  	return s.curBlock.NewValue2A(s.peekPos(), op, t, aux, arg0, arg1)
  1310  }
  1311  
  1312  // newValue2Apos adds a new value with two arguments and an aux value to the current block.
  1313  // isStmt determines whether the created values may be a statement or not
  1314  // (i.e., false means never, yes means maybe).
  1315  func (s *state) newValue2Apos(op ssaop.Op, t *types.Type, aux ssa.Aux, arg0, arg1 *ssa.Value, isStmt bool) *ssa.Value {
  1316  	if isStmt {
  1317  		return s.curBlock.NewValue2A(s.peekPos(), op, t, aux, arg0, arg1)
  1318  	}
  1319  	return s.curBlock.NewValue2A(s.peekPos().WithNotStmt(), op, t, aux, arg0, arg1)
  1320  }
  1321  
  1322  // newValue2I adds a new value with two arguments and an auxint value to the current block.
  1323  func (s *state) newValue2I(op ssaop.Op, t *types.Type, aux int64, arg0, arg1 *ssa.Value) *ssa.Value {
  1324  	return s.curBlock.NewValue2I(s.peekPos(), op, t, aux, arg0, arg1)
  1325  }
  1326  
  1327  // newValue3 adds a new value with three arguments to the current block.
  1328  func (s *state) newValue3(op ssaop.Op, t *types.Type, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
  1329  	return s.curBlock.NewValue3(s.peekPos(), op, t, arg0, arg1, arg2)
  1330  }
  1331  
  1332  // newValue3I adds a new value with three arguments and an auxint value to the current block.
  1333  func (s *state) newValue3I(op ssaop.Op, t *types.Type, aux int64, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
  1334  	return s.curBlock.NewValue3I(s.peekPos(), op, t, aux, arg0, arg1, arg2)
  1335  }
  1336  
  1337  // newValue3A adds a new value with three arguments and an aux value to the current block.
  1338  func (s *state) newValue3A(op ssaop.Op, t *types.Type, aux ssa.Aux, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
  1339  	return s.curBlock.NewValue3A(s.peekPos(), op, t, aux, arg0, arg1, arg2)
  1340  }
  1341  
  1342  // newValue3Apos adds a new value with three arguments and an aux value to the current block.
  1343  // isStmt determines whether the created values may be a statement or not
  1344  // (i.e., false means never, yes means maybe).
  1345  func (s *state) newValue3Apos(op ssaop.Op, t *types.Type, aux ssa.Aux, arg0, arg1, arg2 *ssa.Value, isStmt bool) *ssa.Value {
  1346  	if isStmt {
  1347  		return s.curBlock.NewValue3A(s.peekPos(), op, t, aux, arg0, arg1, arg2)
  1348  	}
  1349  	return s.curBlock.NewValue3A(s.peekPos().WithNotStmt(), op, t, aux, arg0, arg1, arg2)
  1350  }
  1351  
  1352  // newValue4 adds a new value with four arguments to the current block.
  1353  func (s *state) newValue4(op ssaop.Op, t *types.Type, arg0, arg1, arg2, arg3 *ssa.Value) *ssa.Value {
  1354  	return s.curBlock.NewValue4(s.peekPos(), op, t, arg0, arg1, arg2, arg3)
  1355  }
  1356  
  1357  // newValue4A adds a new value with four arguments and an aux value to the current block.
  1358  func (s *state) newValue4A(op ssaop.Op, t *types.Type, aux ssa.Aux, arg0, arg1, arg2, arg3 *ssa.Value) *ssa.Value {
  1359  	return s.curBlock.NewValue4A(s.peekPos(), op, t, aux, arg0, arg1, arg2, arg3)
  1360  }
  1361  
  1362  // newValue4I adds a new value with four arguments and an auxint value to the current block.
  1363  func (s *state) newValue4I(op ssaop.Op, t *types.Type, aux int64, arg0, arg1, arg2, arg3 *ssa.Value) *ssa.Value {
  1364  	return s.curBlock.NewValue4I(s.peekPos(), op, t, aux, arg0, arg1, arg2, arg3)
  1365  }
  1366  
  1367  func (s *state) entryBlock() *ssa.Block {
  1368  	b := s.f.Entry
  1369  	if base.Flag.N > 0 && s.curBlock != nil {
  1370  		// If optimizations are off, allocate in current block instead. Since with -N
  1371  		// we're not doing the CSE or tighten passes, putting lots of stuff in the
  1372  		// entry block leads to O(n^2) entries in the live value map during regalloc.
  1373  		// See issue 45897.
  1374  		b = s.curBlock
  1375  	}
  1376  	return b
  1377  }
  1378  
  1379  // entryNewValue0 adds a new value with no arguments to the entry block.
  1380  func (s *state) entryNewValue0(op ssaop.Op, t *types.Type) *ssa.Value {
  1381  	return s.entryBlock().NewValue0(src.NoXPos, op, t)
  1382  }
  1383  
  1384  // entryNewValue0A adds a new value with no arguments and an aux value to the entry block.
  1385  func (s *state) entryNewValue0A(op ssaop.Op, t *types.Type, aux ssa.Aux) *ssa.Value {
  1386  	return s.entryBlock().NewValue0A(src.NoXPos, op, t, aux)
  1387  }
  1388  
  1389  // entryNewValue1 adds a new value with one argument to the entry block.
  1390  func (s *state) entryNewValue1(op ssaop.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
  1391  	return s.entryBlock().NewValue1(src.NoXPos, op, t, arg)
  1392  }
  1393  
  1394  // entryNewValue1I adds a new value with one argument and an auxint value to the entry block.
  1395  func (s *state) entryNewValue1I(op ssaop.Op, t *types.Type, auxint int64, arg *ssa.Value) *ssa.Value {
  1396  	return s.entryBlock().NewValue1I(src.NoXPos, op, t, auxint, arg)
  1397  }
  1398  
  1399  // entryNewValue1A adds a new value with one argument and an aux value to the entry block.
  1400  func (s *state) entryNewValue1A(op ssaop.Op, t *types.Type, aux ssa.Aux, arg *ssa.Value) *ssa.Value {
  1401  	return s.entryBlock().NewValue1A(src.NoXPos, op, t, aux, arg)
  1402  }
  1403  
  1404  // entryNewValue2 adds a new value with two arguments to the entry block.
  1405  func (s *state) entryNewValue2(op ssaop.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
  1406  	return s.entryBlock().NewValue2(src.NoXPos, op, t, arg0, arg1)
  1407  }
  1408  
  1409  // entryNewValue2A adds a new value with two arguments and an aux value to the entry block.
  1410  func (s *state) entryNewValue2A(op ssaop.Op, t *types.Type, aux ssa.Aux, arg0, arg1 *ssa.Value) *ssa.Value {
  1411  	return s.entryBlock().NewValue2A(src.NoXPos, op, t, aux, arg0, arg1)
  1412  }
  1413  
  1414  // const* routines add a new const value to the entry block.
  1415  func (s *state) constSlice(t *types.Type) *ssa.Value {
  1416  	return s.f.ConstSlice(t)
  1417  }
  1418  func (s *state) constInterface(t *types.Type) *ssa.Value {
  1419  	return s.f.ConstInterface(t)
  1420  }
  1421  func (s *state) constNil(t *types.Type) *ssa.Value { return s.f.ConstNil(t) }
  1422  func (s *state) constEmptyString(t *types.Type) *ssa.Value {
  1423  	return s.f.ConstEmptyString(t)
  1424  }
  1425  func (s *state) constBool(c bool) *ssa.Value {
  1426  	return s.f.ConstBool(types.Types[types.TBOOL], c)
  1427  }
  1428  func (s *state) constInt8(t *types.Type, c int8) *ssa.Value {
  1429  	return s.f.ConstInt8(t, c)
  1430  }
  1431  func (s *state) constInt16(t *types.Type, c int16) *ssa.Value {
  1432  	return s.f.ConstInt16(t, c)
  1433  }
  1434  func (s *state) constInt32(t *types.Type, c int32) *ssa.Value {
  1435  	return s.f.ConstInt32(t, c)
  1436  }
  1437  func (s *state) constInt64(t *types.Type, c int64) *ssa.Value {
  1438  	return s.f.ConstInt64(t, c)
  1439  }
  1440  func (s *state) constFloat32(t *types.Type, c float64) *ssa.Value {
  1441  	return s.f.ConstFloat32(t, c)
  1442  }
  1443  func (s *state) constFloat64(t *types.Type, c float64) *ssa.Value {
  1444  	return s.f.ConstFloat64(t, c)
  1445  }
  1446  func (s *state) constInt(t *types.Type, c int64) *ssa.Value {
  1447  	if s.config.PtrSize == 8 {
  1448  		return s.constInt64(t, c)
  1449  	}
  1450  	if int64(int32(c)) != c {
  1451  		s.Fatalf("integer constant too big %d", c)
  1452  	}
  1453  	return s.constInt32(t, int32(c))
  1454  }
  1455  
  1456  // newValueOrSfCall* are wrappers around newValue*, which may create a call to a
  1457  // soft-float runtime function instead (when emitting soft-float code).
  1458  func (s *state) newValueOrSfCall1(op ssaop.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
  1459  	if s.softFloat {
  1460  		if c, ok := s.sfcall(op, arg); ok {
  1461  			return c
  1462  		}
  1463  	}
  1464  	return s.newValue1(op, t, arg)
  1465  }
  1466  func (s *state) newValueOrSfCall2(op ssaop.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
  1467  	if s.softFloat {
  1468  		if c, ok := s.sfcall(op, arg0, arg1); ok {
  1469  			return c
  1470  		}
  1471  	}
  1472  	return s.newValue2(op, t, arg0, arg1)
  1473  }
  1474  
  1475  type instrumentKind uint8
  1476  
  1477  const (
  1478  	instrumentRead = iota
  1479  	instrumentWrite
  1480  	instrumentMove
  1481  )
  1482  
  1483  func (s *state) instrument(t *types.Type, addr *ssa.Value, kind instrumentKind) {
  1484  	s.instrument2(t, addr, nil, kind)
  1485  }
  1486  
  1487  // instrumentFields instruments a read/write operation on addr.
  1488  // If it is instrumenting for MSAN or ASAN and t is a struct type, it instruments
  1489  // operation for each field, instead of for the whole struct.
  1490  func (s *state) instrumentFields(t *types.Type, addr *ssa.Value, kind instrumentKind) {
  1491  	if !(base.Flag.MSan || base.Flag.ASan) || !isStructNotSIMD(t) {
  1492  		s.instrument(t, addr, kind)
  1493  		return
  1494  	}
  1495  	for _, f := range t.Fields() {
  1496  		if f.Sym.IsBlank() {
  1497  			continue
  1498  		}
  1499  		offptr := s.newValue1I(ssaop.OpOffPtr, types.NewPtr(f.Type), f.Offset, addr)
  1500  		s.instrumentFields(f.Type, offptr, kind)
  1501  	}
  1502  }
  1503  
  1504  func (s *state) instrumentMove(t *types.Type, dst, src *ssa.Value) {
  1505  	if base.Flag.MSan {
  1506  		s.instrument2(t, dst, src, instrumentMove)
  1507  	} else {
  1508  		s.instrument(t, src, instrumentRead)
  1509  		s.instrument(t, dst, instrumentWrite)
  1510  	}
  1511  }
  1512  
  1513  func (s *state) instrument2(t *types.Type, addr, addr2 *ssa.Value, kind instrumentKind) {
  1514  	if !s.instrumentMemory {
  1515  		return
  1516  	}
  1517  
  1518  	w := t.Size()
  1519  	if w == 0 {
  1520  		return // can't race on zero-sized things
  1521  	}
  1522  
  1523  	if ssa.IsSanitizerSafeAddr(addr) {
  1524  		return
  1525  	}
  1526  
  1527  	var fn *obj.LSym
  1528  	needWidth := false
  1529  
  1530  	if addr2 != nil && kind != instrumentMove {
  1531  		panic("instrument2: non-nil addr2 for non-move instrumentation")
  1532  	}
  1533  
  1534  	if base.Flag.MSan {
  1535  		switch kind {
  1536  		case instrumentRead:
  1537  			fn = ir.Syms.Msanread
  1538  		case instrumentWrite:
  1539  			fn = ir.Syms.Msanwrite
  1540  		case instrumentMove:
  1541  			fn = ir.Syms.Msanmove
  1542  		default:
  1543  			panic("unreachable")
  1544  		}
  1545  		needWidth = true
  1546  	} else if base.Flag.Race && t.NumComponents(types.CountBlankFields) > 1 {
  1547  		// for composite objects we have to write every address
  1548  		// because a write might happen to any subobject.
  1549  		// composites with only one element don't have subobjects, though.
  1550  		switch kind {
  1551  		case instrumentRead:
  1552  			fn = ir.Syms.Racereadrange
  1553  		case instrumentWrite:
  1554  			fn = ir.Syms.Racewriterange
  1555  		default:
  1556  			panic("unreachable")
  1557  		}
  1558  		needWidth = true
  1559  	} else if base.Flag.Race {
  1560  		// for non-composite objects we can write just the start
  1561  		// address, as any write must write the first byte.
  1562  		switch kind {
  1563  		case instrumentRead:
  1564  			fn = ir.Syms.Raceread
  1565  		case instrumentWrite:
  1566  			fn = ir.Syms.Racewrite
  1567  		default:
  1568  			panic("unreachable")
  1569  		}
  1570  	} else if base.Flag.ASan {
  1571  		switch kind {
  1572  		case instrumentRead:
  1573  			fn = ir.Syms.Asanread
  1574  		case instrumentWrite:
  1575  			fn = ir.Syms.Asanwrite
  1576  		default:
  1577  			panic("unreachable")
  1578  		}
  1579  		needWidth = true
  1580  	} else {
  1581  		panic("unreachable")
  1582  	}
  1583  
  1584  	args := []*ssa.Value{addr}
  1585  	if addr2 != nil {
  1586  		args = append(args, addr2)
  1587  	}
  1588  	if needWidth {
  1589  		args = append(args, s.constInt(types.Types[types.TUINTPTR], w))
  1590  	}
  1591  	s.rtcall(fn, true, nil, args...)
  1592  }
  1593  
  1594  func (s *state) load(t *types.Type, src *ssa.Value) *ssa.Value {
  1595  	s.instrumentFields(t, src, instrumentRead)
  1596  	return s.rawLoad(t, src)
  1597  }
  1598  
  1599  func (s *state) rawLoad(t *types.Type, src *ssa.Value) *ssa.Value {
  1600  	return s.newValue2(ssaop.OpLoad, t, src, s.mem())
  1601  }
  1602  
  1603  func (s *state) store(t *types.Type, dst, val *ssa.Value) {
  1604  	s.vars[memVar] = s.newValue3A(ssaop.OpStore, types.TypeMem, t, dst, val, s.mem())
  1605  }
  1606  
  1607  func (s *state) zero(t *types.Type, dst *ssa.Value) {
  1608  	s.instrument(t, dst, instrumentWrite)
  1609  	store := s.newValue2I(ssaop.OpZero, types.TypeMem, t.Size(), dst, s.mem())
  1610  	store.Aux = t
  1611  	s.vars[memVar] = store
  1612  }
  1613  
  1614  func (s *state) move(t *types.Type, dst, src *ssa.Value) {
  1615  	s.moveWhichMayOverlap(t, dst, src, false)
  1616  }
  1617  func (s *state) moveWhichMayOverlap(t *types.Type, dst, src *ssa.Value, mayOverlap bool) {
  1618  	s.instrumentMove(t, dst, src)
  1619  	if mayOverlap && t.IsArray() && t.NumElem() > 1 && !ssa.IsInlinableMemmove(dst, src, t.Size(), s.f.Config) {
  1620  		// Normally, when moving Go values of type T from one location to another,
  1621  		// we don't need to worry about partial overlaps. The two Ts must either be
  1622  		// in disjoint (nonoverlapping) memory or in exactly the same location.
  1623  		// There are 2 cases where this isn't true:
  1624  		//  1) Using unsafe you can arrange partial overlaps.
  1625  		//  2) Since Go 1.17, you can use a cast from a slice to a ptr-to-array.
  1626  		//     https://go.dev/ref/spec#Conversions_from_slice_to_array_pointer
  1627  		//     This feature can be used to construct partial overlaps of array types.
  1628  		//       var a [3]int
  1629  		//       p := (*[2]int)(a[:])
  1630  		//       q := (*[2]int)(a[1:])
  1631  		//       *p = *q
  1632  		// We don't care about solving 1. Or at least, we haven't historically
  1633  		// and no one has complained.
  1634  		// For 2, we need to ensure that if there might be partial overlap,
  1635  		// then we can't use OpMove; we must use memmove instead.
  1636  		// (memmove handles partial overlap by copying in the correct
  1637  		// direction. OpMove does not.)
  1638  		//
  1639  		// Note that we have to be careful here not to introduce a call when
  1640  		// we're marshaling arguments to a call or unmarshaling results from a call.
  1641  		// Cases where this is happening must pass mayOverlap to false.
  1642  		// (Currently this only happens when unmarshaling results of a call.)
  1643  		if t.HasPointers() {
  1644  			s.rtcall(ir.Syms.Typedmemmove, true, nil, s.reflectType(t), dst, src)
  1645  			// We would have otherwise implemented this move with straightline code,
  1646  			// including a write barrier. Pretend we issue a write barrier here,
  1647  			// so that the write barrier tests work. (Otherwise they'd need to know
  1648  			// the details of IsInlineableMemmove.)
  1649  			s.curfn.SetWBPos(s.peekPos())
  1650  		} else {
  1651  			s.rtcall(ir.Syms.Memmove, true, nil, dst, src, s.constInt(types.Types[types.TUINTPTR], t.Size()))
  1652  		}
  1653  		ssa.LogLargeCopy(s.f.Name, s.peekPos(), t.Size())
  1654  		return
  1655  	}
  1656  	store := s.newValue3I(ssaop.OpMove, types.TypeMem, t.Size(), dst, src, s.mem())
  1657  	store.Aux = t
  1658  	s.vars[memVar] = store
  1659  }
  1660  
  1661  // stmtList converts the statement list n to SSA and adds it to s.
  1662  func (s *state) stmtList(l ir.Nodes) {
  1663  	for _, n := range l {
  1664  		s.stmt(n)
  1665  	}
  1666  }
  1667  
  1668  func peelConvNop(n ir.Node) ir.Node {
  1669  	if n == nil {
  1670  		return n
  1671  	}
  1672  	for n.Op() == ir.OCONVNOP {
  1673  		n = n.(*ir.ConvExpr).X
  1674  	}
  1675  	return n
  1676  }
  1677  
  1678  // stmt converts the statement n to SSA and adds it to s.
  1679  func (s *state) stmt(n ir.Node) {
  1680  	s.pushLine(n.Pos())
  1681  	defer s.popLine()
  1682  
  1683  	// If s.curBlock is nil, and n isn't a label (which might have an associated goto somewhere),
  1684  	// then this code is dead. Stop here.
  1685  	if s.curBlock == nil && n.Op() != ir.OLABEL {
  1686  		return
  1687  	}
  1688  
  1689  	s.stmtList(n.Init())
  1690  	switch n.Op() {
  1691  
  1692  	case ir.OBLOCK:
  1693  		n := n.(*ir.BlockStmt)
  1694  		s.stmtList(n.List)
  1695  
  1696  	case ir.OFALL: // no-op
  1697  
  1698  	// Expression statements
  1699  	case ir.OCALLFUNC:
  1700  		n := n.(*ir.CallExpr)
  1701  		if ir.IsIntrinsicCall(n) {
  1702  			s.intrinsicCall(n)
  1703  			return
  1704  		}
  1705  		fallthrough
  1706  
  1707  	case ir.OCALLINTER:
  1708  		n := n.(*ir.CallExpr)
  1709  		s.callResult(n, callNormal)
  1710  		if n.Op() == ir.OCALLFUNC && n.Fun.Op() == ir.ONAME && n.Fun.(*ir.Name).Class == ir.PFUNC {
  1711  			if fn := n.Fun.Sym().Name; base.Flag.CompilingRuntime && fn == "throw" ||
  1712  				n.Fun.Sym().Pkg == ir.Pkgs.Runtime &&
  1713  					(fn == "throwinit" || fn == "gopanic" || fn == "panicwrap" || fn == "block" ||
  1714  						fn == "panicmakeslicelen" || fn == "panicmakeslicecap" || fn == "panicunsafeslicelen" ||
  1715  						fn == "panicunsafeslicenilptr" || fn == "panicunsafestringlen" || fn == "panicunsafestringnilptr" ||
  1716  						fn == "panicrangestate") {
  1717  				m := s.mem()
  1718  				b := s.endBlock()
  1719  				b.Kind = block.BlockExit
  1720  				b.SetControl(m)
  1721  				// TODO: never rewrite OPANIC to OCALLFUNC in the
  1722  				// first place. Need to wait until all backends
  1723  				// go through SSA.
  1724  			}
  1725  		}
  1726  	case ir.ODEFER:
  1727  		n := n.(*ir.GoDeferStmt)
  1728  		if base.Debug.Defer > 0 {
  1729  			var defertype string
  1730  			if s.hasOpenDefers {
  1731  				defertype = "open-coded"
  1732  			} else if n.Esc() == ir.EscNever {
  1733  				defertype = "stack-allocated"
  1734  			} else {
  1735  				defertype = "heap-allocated"
  1736  			}
  1737  			base.WarnfAt(n.Pos(), "%s defer", defertype)
  1738  		}
  1739  		if s.hasOpenDefers {
  1740  			s.openDeferRecord(n.Call.(*ir.CallExpr))
  1741  		} else {
  1742  			d := callDefer
  1743  			if n.Esc() == ir.EscNever && n.DeferAt == nil {
  1744  				d = callDeferStack
  1745  			}
  1746  			s.call(n.Call.(*ir.CallExpr), d, false, n.DeferAt)
  1747  		}
  1748  	case ir.OGO:
  1749  		n := n.(*ir.GoDeferStmt)
  1750  		s.callResult(n.Call.(*ir.CallExpr), callGo)
  1751  
  1752  	case ir.OAS2DOTTYPE:
  1753  		n := n.(*ir.AssignListStmt)
  1754  		var res, resok *ssa.Value
  1755  		if n.Rhs[0].Op() == ir.ODOTTYPE2 {
  1756  			res, resok = s.dottype(n.Rhs[0].(*ir.TypeAssertExpr), true)
  1757  		} else {
  1758  			res, resok = s.dynamicDottype(n.Rhs[0].(*ir.DynamicTypeAssertExpr), true)
  1759  		}
  1760  		deref := false
  1761  		if !ssa.CanSSA(n.Rhs[0].Type()) {
  1762  			if res.Op != ssaop.OpLoad {
  1763  				s.Fatalf("dottype of non-load")
  1764  			}
  1765  			mem := s.mem()
  1766  			if res.Args[1] != mem {
  1767  				s.Fatalf("memory no longer live from 2-result dottype load")
  1768  			}
  1769  			deref = true
  1770  			res = res.Args[0]
  1771  		}
  1772  		s.assign(n.Lhs[0], res, deref, 0)
  1773  		s.assign(n.Lhs[1], resok, false, 0)
  1774  		return
  1775  
  1776  	case ir.OAS2FUNC:
  1777  		// We come here only when it is an intrinsic call returning two values.
  1778  		n := n.(*ir.AssignListStmt)
  1779  		call := n.Rhs[0].(*ir.CallExpr)
  1780  		if !ir.IsIntrinsicCall(call) {
  1781  			s.Fatalf("non-intrinsic AS2FUNC not expanded %v", call)
  1782  		}
  1783  		v := s.intrinsicCall(call)
  1784  		v1 := s.newValue1(ssaop.OpSelect0, n.Lhs[0].Type(), v)
  1785  		v2 := s.newValue1(ssaop.OpSelect1, n.Lhs[1].Type(), v)
  1786  		s.assign(n.Lhs[0], v1, false, 0)
  1787  		s.assign(n.Lhs[1], v2, false, 0)
  1788  		return
  1789  
  1790  	case ir.ODCL:
  1791  		n := n.(*ir.Decl)
  1792  		if v := n.X; v.Esc() == ir.EscHeap {
  1793  			s.newHeapaddr(v)
  1794  		}
  1795  
  1796  	case ir.OLABEL:
  1797  		n := n.(*ir.LabelStmt)
  1798  		sym := n.Label
  1799  		if sym.IsBlank() {
  1800  			// Nothing to do because the label isn't targetable. See issue 52278.
  1801  			break
  1802  		}
  1803  		lab := s.label(sym)
  1804  
  1805  		// The label might already have a target block via a goto.
  1806  		if lab.target == nil {
  1807  			lab.target = s.f.NewBlock(block.BlockPlain)
  1808  		}
  1809  
  1810  		// Go to that label.
  1811  		// (We pretend "label:" is preceded by "goto label", unless the predecessor is unreachable.)
  1812  		if s.curBlock != nil {
  1813  			b := s.endBlock()
  1814  			b.AddEdgeTo(lab.target)
  1815  		}
  1816  		s.startBlock(lab.target)
  1817  
  1818  	case ir.OGOTO:
  1819  		n := n.(*ir.BranchStmt)
  1820  		sym := n.Label
  1821  
  1822  		lab := s.label(sym)
  1823  		if lab.target == nil {
  1824  			lab.target = s.f.NewBlock(block.BlockPlain)
  1825  		}
  1826  
  1827  		b := s.endBlock()
  1828  		b.Pos = s.lastPos.WithIsStmt() // Do this even if b is an empty block.
  1829  		b.AddEdgeTo(lab.target)
  1830  
  1831  	case ir.OAS:
  1832  		n := n.(*ir.AssignStmt)
  1833  		if n.X == n.Y && n.X.Op() == ir.ONAME {
  1834  			// An x=x assignment. No point in doing anything
  1835  			// here. In addition, skipping this assignment
  1836  			// prevents generating:
  1837  			//   VARDEF x
  1838  			//   COPY x -> x
  1839  			// which is bad because x is incorrectly considered
  1840  			// dead before the vardef. See issue #14904.
  1841  			return
  1842  		}
  1843  
  1844  		// mayOverlap keeps track of whether the LHS and RHS might
  1845  		// refer to partially overlapping memory. Partial overlapping can
  1846  		// only happen for arrays, see the comment in moveWhichMayOverlap.
  1847  		//
  1848  		// If both sides of the assignment are not dereferences, then partial
  1849  		// overlap can't happen. Partial overlap can only occur only when the
  1850  		// arrays referenced are strictly smaller parts of the same base array.
  1851  		// If one side of the assignment is a full array, then partial overlap
  1852  		// can't happen. (The arrays are either disjoint or identical.)
  1853  		ny := peelConvNop(n.Y)
  1854  		mayOverlap := n.X.Op() == ir.ODEREF && (n.Y != nil && ny.Op() == ir.ODEREF)
  1855  		if ny != nil && ny.Op() == ir.ODEREF {
  1856  			p := peelConvNop(ny.(*ir.StarExpr).X)
  1857  			if p.Op() == ir.OSPTR && p.(*ir.UnaryExpr).X.Type().IsString() {
  1858  				// Pointer fields of strings point to unmodifiable memory.
  1859  				// That memory can't overlap with the memory being written.
  1860  				mayOverlap = false
  1861  			}
  1862  		}
  1863  
  1864  		// Evaluate RHS.
  1865  		rhs := n.Y
  1866  		if rhs != nil {
  1867  			switch rhs.Op() {
  1868  			case ir.OSTRUCTLIT, ir.OARRAYLIT, ir.OSLICELIT:
  1869  				// All literals with nonzero fields have already been
  1870  				// rewritten during walk. Any that remain are just T{}
  1871  				// or equivalents. Use the zero value.
  1872  				if !ir.IsZero(rhs) {
  1873  					s.Fatalf("literal with nonzero value in SSA: %v", rhs)
  1874  				}
  1875  				rhs = nil
  1876  			case ir.OAPPEND:
  1877  				rhs := rhs.(*ir.CallExpr)
  1878  				// Check whether we're writing the result of an append back to the same slice.
  1879  				// If so, we handle it specially to avoid write barriers on the fast
  1880  				// (non-growth) path.
  1881  				if !ir.SameSafeExpr(n.X, rhs.Args[0]) || base.Flag.N != 0 {
  1882  					break
  1883  				}
  1884  				// If the slice can be SSA'd, it'll be on the stack,
  1885  				// so there will be no write barriers,
  1886  				// so there's no need to attempt to prevent them.
  1887  				if s.canSSA(n.X) {
  1888  					if base.Debug.Append > 0 { // replicating old diagnostic message
  1889  						base.WarnfAt(n.Pos(), "append: len-only update (in local slice)")
  1890  					}
  1891  					break
  1892  				}
  1893  				if base.Debug.Append > 0 {
  1894  					base.WarnfAt(n.Pos(), "append: len-only update")
  1895  				}
  1896  				s.append(rhs, true)
  1897  				return
  1898  			}
  1899  		}
  1900  
  1901  		if ir.IsBlank(n.X) {
  1902  			// _ = rhs
  1903  			// Just evaluate rhs for side-effects.
  1904  			if rhs != nil {
  1905  				s.expr(rhs)
  1906  			}
  1907  			return
  1908  		}
  1909  
  1910  		var t *types.Type
  1911  		if n.Y != nil {
  1912  			t = n.Y.Type()
  1913  		} else {
  1914  			t = n.X.Type()
  1915  		}
  1916  
  1917  		var r *ssa.Value
  1918  		deref := !ssa.CanSSA(t)
  1919  		if deref {
  1920  			if rhs == nil {
  1921  				r = nil // Signal assign to use OpZero.
  1922  			} else {
  1923  				r = s.addr(rhs)
  1924  			}
  1925  		} else {
  1926  			if rhs == nil {
  1927  				r = s.zeroVal(t)
  1928  			} else {
  1929  				r = s.expr(rhs)
  1930  			}
  1931  		}
  1932  
  1933  		var skip skipMask
  1934  		if rhs != nil && (rhs.Op() == ir.OSLICE || rhs.Op() == ir.OSLICE3 || rhs.Op() == ir.OSLICESTR) && ir.SameSafeExpr(rhs.(*ir.SliceExpr).X, n.X) {
  1935  			// We're assigning a slicing operation back to its source.
  1936  			// Don't write back fields we aren't changing. See issue #14855.
  1937  			rhs := rhs.(*ir.SliceExpr)
  1938  			i, j, k := rhs.Low, rhs.High, rhs.Max
  1939  			if i != nil && (i.Op() == ir.OLITERAL && i.Val().Kind() == constant.Int && ir.Int64Val(i) == 0) {
  1940  				// [0:...] is the same as [:...]
  1941  				i = nil
  1942  			}
  1943  			// TODO: detect defaults for len/cap also.
  1944  			// Currently doesn't really work because (*p)[:len(*p)] appears here as:
  1945  			//    tmp = len(*p)
  1946  			//    (*p)[:tmp]
  1947  			// if j != nil && (j.Op == OLEN && SameSafeExpr(j.Left, n.Left)) {
  1948  			//      j = nil
  1949  			// }
  1950  			// if k != nil && (k.Op == OCAP && SameSafeExpr(k.Left, n.Left)) {
  1951  			//      k = nil
  1952  			// }
  1953  			if i == nil {
  1954  				skip |= skipPtr
  1955  				if j == nil {
  1956  					skip |= skipLen
  1957  				}
  1958  				if k == nil {
  1959  					skip |= skipCap
  1960  				}
  1961  			}
  1962  		}
  1963  
  1964  		s.assignWhichMayOverlap(n.X, r, deref, skip, mayOverlap)
  1965  
  1966  	case ir.OIF:
  1967  		n := n.(*ir.IfStmt)
  1968  		if ir.IsConst(n.Cond, constant.Bool) {
  1969  			s.stmtList(n.Cond.Init())
  1970  			if ir.BoolVal(n.Cond) {
  1971  				s.stmtList(n.Body)
  1972  			} else {
  1973  				s.stmtList(n.Else)
  1974  			}
  1975  			break
  1976  		}
  1977  
  1978  		bEnd := s.f.NewBlock(block.BlockPlain)
  1979  		var likely int8
  1980  		if n.Likely {
  1981  			likely = 1
  1982  		}
  1983  		var bThen *ssa.Block
  1984  		if len(n.Body) != 0 {
  1985  			bThen = s.f.NewBlock(block.BlockPlain)
  1986  		} else {
  1987  			bThen = bEnd
  1988  		}
  1989  		var bElse *ssa.Block
  1990  		if len(n.Else) != 0 {
  1991  			bElse = s.f.NewBlock(block.BlockPlain)
  1992  		} else {
  1993  			bElse = bEnd
  1994  		}
  1995  		s.condBranch(n.Cond, bThen, bElse, likely)
  1996  
  1997  		if len(n.Body) != 0 {
  1998  			s.startBlock(bThen)
  1999  			s.stmtList(n.Body)
  2000  			if b := s.endBlock(); b != nil {
  2001  				b.AddEdgeTo(bEnd)
  2002  			}
  2003  		}
  2004  		if len(n.Else) != 0 {
  2005  			s.startBlock(bElse)
  2006  			s.stmtList(n.Else)
  2007  			if b := s.endBlock(); b != nil {
  2008  				b.AddEdgeTo(bEnd)
  2009  			}
  2010  		}
  2011  		s.startBlock(bEnd)
  2012  
  2013  	case ir.ORETURN:
  2014  		n := n.(*ir.ReturnStmt)
  2015  		s.stmtList(n.Results)
  2016  		b := s.exit()
  2017  		b.Pos = s.lastPos.WithIsStmt()
  2018  
  2019  	case ir.OTAILCALL:
  2020  		n := n.(*ir.TailCallStmt)
  2021  		s.callResult(n.Call, callTail)
  2022  		call := s.mem()
  2023  		b := s.endBlock()
  2024  		b.Kind = block.BlockRetJmp // could use BlockExit. BlockRetJmp is mostly for clarity.
  2025  		b.SetControl(call)
  2026  
  2027  	case ir.OCONTINUE, ir.OBREAK:
  2028  		n := n.(*ir.BranchStmt)
  2029  		var to *ssa.Block
  2030  		if n.Label == nil {
  2031  			// plain break/continue
  2032  			switch n.Op() {
  2033  			case ir.OCONTINUE:
  2034  				to = s.continueTo
  2035  			case ir.OBREAK:
  2036  				to = s.breakTo
  2037  			}
  2038  		} else {
  2039  			// labeled break/continue; look up the target
  2040  			sym := n.Label
  2041  			lab := s.label(sym)
  2042  			switch n.Op() {
  2043  			case ir.OCONTINUE:
  2044  				to = lab.continueTarget
  2045  			case ir.OBREAK:
  2046  				to = lab.breakTarget
  2047  			}
  2048  		}
  2049  
  2050  		b := s.endBlock()
  2051  		if n.Pos().IsStmt() == src.PosNotStmt {
  2052  			// the front end generated this branch, and it is
  2053  			// not a statement in the source (for example, the
  2054  			// implicit default case of a switch). See issue 81705.
  2055  			b.Pos = s.lastPos.WithNotStmt()
  2056  		} else {
  2057  			b.Pos = s.lastPos.WithIsStmt() // Do this even if b is an empty block.
  2058  		}
  2059  		b.AddEdgeTo(to)
  2060  
  2061  	case ir.OFOR:
  2062  		// OFOR: for Ninit; Left; Right { Nbody }
  2063  		// cond (Left); body (Nbody); incr (Right)
  2064  		n := n.(*ir.ForStmt)
  2065  		base.Assert(!n.DistinctVars) // Should all be rewritten before escape analysis
  2066  		bCond := s.f.NewBlock(block.BlockPlain)
  2067  		bBody := s.f.NewBlock(block.BlockPlain)
  2068  		bIncr := s.f.NewBlock(block.BlockPlain)
  2069  		bEnd := s.f.NewBlock(block.BlockPlain)
  2070  
  2071  		// ensure empty for loops have correct position; issue #30167
  2072  		bBody.Pos = n.Pos()
  2073  
  2074  		// first, jump to condition test
  2075  		b := s.endBlock()
  2076  		b.AddEdgeTo(bCond)
  2077  
  2078  		// generate code to test condition
  2079  		s.startBlock(bCond)
  2080  		if n.Cond != nil {
  2081  			s.condBranch(n.Cond, bBody, bEnd, 1)
  2082  		} else {
  2083  			b := s.endBlock()
  2084  			b.Kind = block.BlockPlain
  2085  			b.AddEdgeTo(bBody)
  2086  		}
  2087  
  2088  		// set up for continue/break in body
  2089  		prevContinue := s.continueTo
  2090  		prevBreak := s.breakTo
  2091  		s.continueTo = bIncr
  2092  		s.breakTo = bEnd
  2093  		var lab *ssaLabel
  2094  		if sym := n.Label; sym != nil {
  2095  			// labeled for loop
  2096  			lab = s.label(sym)
  2097  			lab.continueTarget = bIncr
  2098  			lab.breakTarget = bEnd
  2099  		}
  2100  
  2101  		// generate body
  2102  		s.startBlock(bBody)
  2103  		s.stmtList(n.Body)
  2104  
  2105  		// tear down continue/break
  2106  		s.continueTo = prevContinue
  2107  		s.breakTo = prevBreak
  2108  		if lab != nil {
  2109  			lab.continueTarget = nil
  2110  			lab.breakTarget = nil
  2111  		}
  2112  
  2113  		// done with body, goto incr
  2114  		if b := s.endBlock(); b != nil {
  2115  			b.AddEdgeTo(bIncr)
  2116  		}
  2117  
  2118  		// generate incr
  2119  		s.startBlock(bIncr)
  2120  		if n.Post != nil {
  2121  			s.stmt(n.Post)
  2122  		}
  2123  		if b := s.endBlock(); b != nil {
  2124  			b.AddEdgeTo(bCond)
  2125  			// It can happen that bIncr ends in a block containing only VARKILL,
  2126  			// and that muddles the debugging experience.
  2127  			if b.Pos == src.NoXPos {
  2128  				b.Pos = bCond.Pos
  2129  			}
  2130  		}
  2131  
  2132  		s.startBlock(bEnd)
  2133  
  2134  	case ir.OSWITCH, ir.OSELECT:
  2135  		// These have been mostly rewritten by the front end into their Nbody fields.
  2136  		// Our main task is to correctly hook up any break statements.
  2137  		bEnd := s.f.NewBlock(block.BlockPlain)
  2138  
  2139  		prevBreak := s.breakTo
  2140  		s.breakTo = bEnd
  2141  		var sym *types.Sym
  2142  		var body ir.Nodes
  2143  		if n.Op() == ir.OSWITCH {
  2144  			n := n.(*ir.SwitchStmt)
  2145  			sym = n.Label
  2146  			body = n.Compiled
  2147  		} else {
  2148  			n := n.(*ir.SelectStmt)
  2149  			sym = n.Label
  2150  			body = n.Compiled
  2151  		}
  2152  
  2153  		var lab *ssaLabel
  2154  		if sym != nil {
  2155  			// labeled
  2156  			lab = s.label(sym)
  2157  			lab.breakTarget = bEnd
  2158  		}
  2159  
  2160  		// End the current block at the position of the switch or select
  2161  		// statement. The jump at the end of the block gives the statement
  2162  		// an instruction that executes before any case is evaluated. In
  2163  		// optimized builds, the empty block is fused away. Without this, a
  2164  		// switch with no tag has no such instruction, and a breakpoint on
  2165  		// the switch line stops only after all cases fail. See issue 81705.
  2166  		if s.curBlock != nil && n.Pos().IsStmt() != src.PosNotStmt {
  2167  			b := s.endBlock()
  2168  			b.Pos = n.Pos().WithIsStmt()
  2169  			bStart := s.f.NewBlock(block.BlockPlain)
  2170  			b.AddEdgeTo(bStart)
  2171  			s.startBlock(bStart)
  2172  		}
  2173  
  2174  		// generate body code
  2175  		s.stmtList(body)
  2176  
  2177  		s.breakTo = prevBreak
  2178  		if lab != nil {
  2179  			lab.breakTarget = nil
  2180  		}
  2181  
  2182  		// walk adds explicit OBREAK nodes to the end of all reachable code paths.
  2183  		// If we still have a current block here, then mark it unreachable.
  2184  		if s.curBlock != nil {
  2185  			m := s.mem()
  2186  			b := s.endBlock()
  2187  			b.Kind = block.BlockExit
  2188  			b.SetControl(m)
  2189  		}
  2190  		s.startBlock(bEnd)
  2191  
  2192  	case ir.OJUMPTABLE:
  2193  		n := n.(*ir.JumpTableStmt)
  2194  
  2195  		// Make blocks we'll need.
  2196  		jt := s.f.NewBlock(block.BlockJumpTable)
  2197  		bEnd := s.f.NewBlock(block.BlockPlain)
  2198  
  2199  		// The only thing that needs evaluating is the index we're looking up.
  2200  		idx := s.expr(n.Idx)
  2201  		unsigned := idx.Type.IsUnsigned()
  2202  
  2203  		// Extend so we can do everything in uintptr arithmetic.
  2204  		t := types.Types[types.TUINTPTR]
  2205  		idx = s.conv(nil, idx, idx.Type, t)
  2206  
  2207  		// The ending condition for the current block decides whether we'll use
  2208  		// the jump table at all.
  2209  		// We check that min <= idx <= max and jump around the jump table
  2210  		// if that test fails.
  2211  		// We implement min <= idx <= max with 0 <= idx-min <= max-min, because
  2212  		// we'll need idx-min anyway as the control value for the jump table.
  2213  		var min, max uint64
  2214  		if unsigned {
  2215  			min, _ = constant.Uint64Val(n.Cases[0])
  2216  			max, _ = constant.Uint64Val(n.Cases[len(n.Cases)-1])
  2217  		} else {
  2218  			mn, _ := constant.Int64Val(n.Cases[0])
  2219  			mx, _ := constant.Int64Val(n.Cases[len(n.Cases)-1])
  2220  			min = uint64(mn)
  2221  			max = uint64(mx)
  2222  		}
  2223  		// Compare idx-min with max-min, to see if we can use the jump table.
  2224  		idx = s.newValue2(s.ssaOp(ir.OSUB, t), t, idx, s.uintptrConstant(min))
  2225  		width := s.uintptrConstant(max - min)
  2226  		cmp := s.newValue2(s.ssaOp(ir.OLE, t), types.Types[types.TBOOL], idx, width)
  2227  		b := s.endBlock()
  2228  		b.Kind = block.BlockIf
  2229  		b.SetControl(cmp)
  2230  		b.AddEdgeTo(jt)             // in range - use jump table
  2231  		b.AddEdgeTo(bEnd)           // out of range - no case in the jump table will trigger
  2232  		b.Likely = ssa.BranchLikely // TODO: assumes missing the table entirely is unlikely. True?
  2233  
  2234  		// Build jump table block.
  2235  		s.startBlock(jt)
  2236  		jt.Pos = n.Pos()
  2237  		if base.Flag.Cfg.SpectreIndex {
  2238  			idx = s.newValue2(ssaop.OpSpectreSliceIndex, t, idx, width)
  2239  		}
  2240  		jt.SetControl(idx)
  2241  
  2242  		// Figure out where we should go for each index in the table.
  2243  		table := make([]*ssa.Block, max-min+1)
  2244  		for i := range table {
  2245  			table[i] = bEnd // default target
  2246  		}
  2247  		for i := range n.Targets {
  2248  			c := n.Cases[i]
  2249  			lab := s.label(n.Targets[i])
  2250  			if lab.target == nil {
  2251  				lab.target = s.f.NewBlock(block.BlockPlain)
  2252  			}
  2253  			var val uint64
  2254  			if unsigned {
  2255  				val, _ = constant.Uint64Val(c)
  2256  			} else {
  2257  				vl, _ := constant.Int64Val(c)
  2258  				val = uint64(vl)
  2259  			}
  2260  			// Overwrite the default target.
  2261  			table[val-min] = lab.target
  2262  		}
  2263  		for _, t := range table {
  2264  			jt.AddEdgeTo(t)
  2265  		}
  2266  		s.endBlock()
  2267  
  2268  		s.startBlock(bEnd)
  2269  
  2270  	case ir.OINTERFACESWITCH:
  2271  		n := n.(*ir.InterfaceSwitchStmt)
  2272  		typs := s.f.Config.Types
  2273  
  2274  		t := s.expr(n.RuntimeType)
  2275  		h := s.expr(n.Hash)
  2276  		d := s.newValue1A(ssaop.OpAddr, typs.BytePtr, n.Descriptor, s.sb)
  2277  
  2278  		// Check the cache first.
  2279  		var merge *ssa.Block
  2280  		if base.Flag.N == 0 && rtabi.UseInterfaceSwitchCache(Arch.LinkArch.Family) {
  2281  			// Note: we can only use the cache if we have the right atomic load instruction.
  2282  			// Double-check that here.
  2283  			if intrinsics.lookup(Arch.LinkArch.Arch, "internal/runtime/atomic", "Loadp") == nil {
  2284  				s.Fatalf("atomic load not available")
  2285  			}
  2286  			merge = s.f.NewBlock(block.BlockPlain)
  2287  			cacheHit := s.f.NewBlock(block.BlockPlain)
  2288  			cacheMiss := s.f.NewBlock(block.BlockPlain)
  2289  			loopHead := s.f.NewBlock(block.BlockPlain)
  2290  			loopBody := s.f.NewBlock(block.BlockPlain)
  2291  
  2292  			// Pick right size ops.
  2293  			var mul, and, add, zext ssaop.Op
  2294  			if s.config.PtrSize == 4 {
  2295  				mul = ssaop.OpMul32
  2296  				and = ssaop.OpAnd32
  2297  				add = ssaop.OpAdd32
  2298  				zext = ssaop.OpCopy
  2299  			} else {
  2300  				mul = ssaop.OpMul64
  2301  				and = ssaop.OpAnd64
  2302  				add = ssaop.OpAdd64
  2303  				zext = ssaop.OpZeroExt32to64
  2304  			}
  2305  
  2306  			// Load cache pointer out of descriptor, with an atomic load so
  2307  			// we ensure that we see a fully written cache.
  2308  			atomicLoad := s.newValue2(ssaop.OpAtomicLoadPtr, types.NewTuple(typs.BytePtr, types.TypeMem), d, s.mem())
  2309  			cache := s.newValue1(ssaop.OpSelect0, typs.BytePtr, atomicLoad)
  2310  			s.vars[memVar] = s.newValue1(ssaop.OpSelect1, types.TypeMem, atomicLoad)
  2311  
  2312  			// Initialize hash variable.
  2313  			s.vars[hashVar] = s.newValue1(zext, typs.Uintptr, h)
  2314  
  2315  			// Load mask from cache.
  2316  			mask := s.newValue2(ssaop.OpLoad, typs.Uintptr, cache, s.mem())
  2317  			// Jump to loop head.
  2318  			b := s.endBlock()
  2319  			b.AddEdgeTo(loopHead)
  2320  
  2321  			// At loop head, get pointer to the cache entry.
  2322  			//   e := &cache.Entries[hash&mask]
  2323  			s.startBlock(loopHead)
  2324  			entries := s.newValue2(ssaop.OpAddPtr, typs.UintptrPtr, cache, s.uintptrConstant(uint64(s.config.PtrSize)))
  2325  			idx := s.newValue2(and, typs.Uintptr, s.variable(hashVar, typs.Uintptr), mask)
  2326  			idx = s.newValue2(mul, typs.Uintptr, idx, s.uintptrConstant(uint64(3*s.config.PtrSize)))
  2327  			e := s.newValue2(ssaop.OpAddPtr, typs.UintptrPtr, entries, idx)
  2328  			//   hash++
  2329  			s.vars[hashVar] = s.newValue2(add, typs.Uintptr, s.variable(hashVar, typs.Uintptr), s.uintptrConstant(1))
  2330  
  2331  			// Look for a cache hit.
  2332  			//   if e.Typ == t { goto hit }
  2333  			eTyp := s.newValue2(ssaop.OpLoad, typs.Uintptr, e, s.mem())
  2334  			cmp1 := s.newValue2(ssaop.OpEqPtr, typs.Bool, t, eTyp)
  2335  			b = s.endBlock()
  2336  			b.Kind = block.BlockIf
  2337  			b.SetControl(cmp1)
  2338  			b.AddEdgeTo(cacheHit)
  2339  			b.AddEdgeTo(loopBody)
  2340  
  2341  			// Look for an empty entry, the tombstone for this hash table.
  2342  			//   if e.Typ == nil { goto miss }
  2343  			s.startBlock(loopBody)
  2344  			cmp2 := s.newValue2(ssaop.OpEqPtr, typs.Bool, eTyp, s.constNil(typs.BytePtr))
  2345  			b = s.endBlock()
  2346  			b.Kind = block.BlockIf
  2347  			b.SetControl(cmp2)
  2348  			b.AddEdgeTo(cacheMiss)
  2349  			b.AddEdgeTo(loopHead)
  2350  
  2351  			// On a hit, load the data fields of the cache entry.
  2352  			//   Case = e.Case
  2353  			//   Itab = e.Itab
  2354  			s.startBlock(cacheHit)
  2355  			eCase := s.newValue2(ssaop.OpLoad, typs.Int, s.newValue1I(ssaop.OpOffPtr, typs.IntPtr, s.config.PtrSize, e), s.mem())
  2356  			eItab := s.newValue2(ssaop.OpLoad, typs.BytePtr, s.newValue1I(ssaop.OpOffPtr, typs.BytePtrPtr, 2*s.config.PtrSize, e), s.mem())
  2357  			s.assign(n.Case, eCase, false, 0)
  2358  			s.assign(n.Itab, eItab, false, 0)
  2359  			b = s.endBlock()
  2360  			b.AddEdgeTo(merge)
  2361  
  2362  			// On a miss, call into the runtime to get the answer.
  2363  			s.startBlock(cacheMiss)
  2364  		}
  2365  
  2366  		r := s.rtcall(ir.Syms.InterfaceSwitch, true, []*types.Type{typs.Int, typs.BytePtr}, d, t)
  2367  		s.assign(n.Case, r[0], false, 0)
  2368  		s.assign(n.Itab, r[1], false, 0)
  2369  
  2370  		if merge != nil {
  2371  			// Cache hits merge in here.
  2372  			b := s.endBlock()
  2373  			b.Kind = block.BlockPlain
  2374  			b.AddEdgeTo(merge)
  2375  			s.startBlock(merge)
  2376  		}
  2377  
  2378  	case ir.OCHECKNIL:
  2379  		n := n.(*ir.UnaryExpr)
  2380  		p := s.expr(n.X)
  2381  		_ = s.nilCheck(p)
  2382  		// TODO: check that throwing away the nilcheck result is ok.
  2383  
  2384  	case ir.OINLMARK:
  2385  		n := n.(*ir.InlineMarkStmt)
  2386  		s.newValue1I(ssaop.OpInlMark, types.TypeVoid, n.Index, s.mem())
  2387  
  2388  	default:
  2389  		s.Fatalf("unhandled stmt %v", n.Op())
  2390  	}
  2391  }
  2392  
  2393  // If true, share as many open-coded defer exits as possible (with the downside of
  2394  // worse line-number information)
  2395  const shareDeferExits = false
  2396  
  2397  // exit processes any code that needs to be generated just before returning.
  2398  // It returns a BlockRet block that ends the control flow. Its control value
  2399  // will be set to the final memory state.
  2400  func (s *state) exit() *ssa.Block {
  2401  	if s.hasdefer {
  2402  		if s.hasOpenDefers {
  2403  			if shareDeferExits && s.lastDeferExit != nil && len(s.openDefers) == s.lastDeferCount {
  2404  				if s.curBlock.Kind != block.BlockPlain {
  2405  					panic("Block for an exit should be BlockPlain")
  2406  				}
  2407  				s.curBlock.AddEdgeTo(s.lastDeferExit)
  2408  				s.endBlock()
  2409  				return s.lastDeferFinalBlock
  2410  			}
  2411  			s.openDeferExit()
  2412  		} else {
  2413  			// Shared deferreturn is assigned the "last" position in the function.
  2414  			// The linker picks the first deferreturn call it sees, so this is
  2415  			// the only sensible "shared" place.
  2416  			// To not-share deferreturn, the protocol would need to be changed
  2417  			// so that the call to deferproc-etc would receive the PC offset from
  2418  			// the return PC, and the runtime would need to use that instead of
  2419  			// the deferreturn retrieved from the pcln information.
  2420  			// opendefers would remain a problem, however.
  2421  			s.pushLine(s.curfn.Endlineno)
  2422  			s.rtcall(ir.Syms.Deferreturn, true, nil)
  2423  			s.popLine()
  2424  		}
  2425  	}
  2426  
  2427  	// Do actual return.
  2428  	// These currently turn into self-copies (in many cases).
  2429  	resultFields := s.curfn.Type().Results()
  2430  	results := make([]*ssa.Value, len(resultFields)+1, len(resultFields)+1)
  2431  	// Store SSAable and heap-escaped PPARAMOUT variables back to stack locations.
  2432  	for i, f := range resultFields {
  2433  		n := f.Nname.(*ir.Name)
  2434  		if s.canSSA(n) { // result is in some SSA variable
  2435  			if !n.IsOutputParamInRegisters() && n.Type().HasPointers() {
  2436  				// We are about to store to the result slot.
  2437  				s.vars[memVar] = s.newValue1A(ssaop.OpVarDef, types.TypeMem, n, s.mem())
  2438  			}
  2439  			results[i] = s.variable(n, n.Type())
  2440  		} else if !n.OnStack() { // result is actually heap allocated
  2441  			// We are about to copy the in-heap result to the result slot.
  2442  			if n.Type().HasPointers() {
  2443  				s.vars[memVar] = s.newValue1A(ssaop.OpVarDef, types.TypeMem, n, s.mem())
  2444  			}
  2445  			ha := s.expr(n.Heapaddr)
  2446  			s.instrumentFields(n.Type(), ha, instrumentRead)
  2447  			results[i] = s.newValue2(ssaop.OpDereference, n.Type(), ha, s.mem())
  2448  		} else { // result is not SSA-able; not escaped, so not on heap, but too large for SSA.
  2449  			// Before register ABI this ought to be a self-move, home=dest,
  2450  			// With register ABI, it's still a self-move if parameter is on stack (i.e., too big or overflowed)
  2451  			// No VarDef, as the result slot is already holding live value.
  2452  			results[i] = s.newValue2(ssaop.OpDereference, n.Type(), s.addr(n), s.mem())
  2453  		}
  2454  	}
  2455  
  2456  	// In -race mode, we need to call racefuncexit.
  2457  	// Note: This has to happen after we load any heap-allocated results,
  2458  	// otherwise races will be attributed to the caller instead.
  2459  	if s.instrumentEnterExit {
  2460  		s.rtcall(ir.Syms.Racefuncexit, true, nil)
  2461  	}
  2462  
  2463  	results[len(results)-1] = s.mem()
  2464  	m := s.newValue0(ssaop.OpMakeResult, s.f.OwnAux.LateExpansionResultType())
  2465  	m.AddArgs(results...)
  2466  
  2467  	b := s.endBlock()
  2468  	b.Kind = block.BlockRet
  2469  	b.SetControl(m)
  2470  	if s.hasdefer && s.hasOpenDefers {
  2471  		s.lastDeferFinalBlock = b
  2472  	}
  2473  	return b
  2474  }
  2475  
  2476  type opAndType struct {
  2477  	op    ir.Op
  2478  	etype types.Kind
  2479  }
  2480  
  2481  var opToSSA = map[opAndType]ssaop.Op{
  2482  	{ir.OADD, types.TINT8}:    ssaop.OpAdd8,
  2483  	{ir.OADD, types.TUINT8}:   ssaop.OpAdd8,
  2484  	{ir.OADD, types.TINT16}:   ssaop.OpAdd16,
  2485  	{ir.OADD, types.TUINT16}:  ssaop.OpAdd16,
  2486  	{ir.OADD, types.TINT32}:   ssaop.OpAdd32,
  2487  	{ir.OADD, types.TUINT32}:  ssaop.OpAdd32,
  2488  	{ir.OADD, types.TINT64}:   ssaop.OpAdd64,
  2489  	{ir.OADD, types.TUINT64}:  ssaop.OpAdd64,
  2490  	{ir.OADD, types.TFLOAT32}: ssaop.OpAdd32F,
  2491  	{ir.OADD, types.TFLOAT64}: ssaop.OpAdd64F,
  2492  
  2493  	{ir.OSUB, types.TINT8}:    ssaop.OpSub8,
  2494  	{ir.OSUB, types.TUINT8}:   ssaop.OpSub8,
  2495  	{ir.OSUB, types.TINT16}:   ssaop.OpSub16,
  2496  	{ir.OSUB, types.TUINT16}:  ssaop.OpSub16,
  2497  	{ir.OSUB, types.TINT32}:   ssaop.OpSub32,
  2498  	{ir.OSUB, types.TUINT32}:  ssaop.OpSub32,
  2499  	{ir.OSUB, types.TINT64}:   ssaop.OpSub64,
  2500  	{ir.OSUB, types.TUINT64}:  ssaop.OpSub64,
  2501  	{ir.OSUB, types.TFLOAT32}: ssaop.OpSub32F,
  2502  	{ir.OSUB, types.TFLOAT64}: ssaop.OpSub64F,
  2503  
  2504  	{ir.ONOT, types.TBOOL}: ssaop.OpNot,
  2505  
  2506  	{ir.ONEG, types.TINT8}:    ssaop.OpNeg8,
  2507  	{ir.ONEG, types.TUINT8}:   ssaop.OpNeg8,
  2508  	{ir.ONEG, types.TINT16}:   ssaop.OpNeg16,
  2509  	{ir.ONEG, types.TUINT16}:  ssaop.OpNeg16,
  2510  	{ir.ONEG, types.TINT32}:   ssaop.OpNeg32,
  2511  	{ir.ONEG, types.TUINT32}:  ssaop.OpNeg32,
  2512  	{ir.ONEG, types.TINT64}:   ssaop.OpNeg64,
  2513  	{ir.ONEG, types.TUINT64}:  ssaop.OpNeg64,
  2514  	{ir.ONEG, types.TFLOAT32}: ssaop.OpNeg32F,
  2515  	{ir.ONEG, types.TFLOAT64}: ssaop.OpNeg64F,
  2516  
  2517  	{ir.OBITNOT, types.TINT8}:   ssaop.OpCom8,
  2518  	{ir.OBITNOT, types.TUINT8}:  ssaop.OpCom8,
  2519  	{ir.OBITNOT, types.TINT16}:  ssaop.OpCom16,
  2520  	{ir.OBITNOT, types.TUINT16}: ssaop.OpCom16,
  2521  	{ir.OBITNOT, types.TINT32}:  ssaop.OpCom32,
  2522  	{ir.OBITNOT, types.TUINT32}: ssaop.OpCom32,
  2523  	{ir.OBITNOT, types.TINT64}:  ssaop.OpCom64,
  2524  	{ir.OBITNOT, types.TUINT64}: ssaop.OpCom64,
  2525  
  2526  	{ir.OIMAG, types.TCOMPLEX64}:  ssaop.OpComplexImag,
  2527  	{ir.OIMAG, types.TCOMPLEX128}: ssaop.OpComplexImag,
  2528  	{ir.OREAL, types.TCOMPLEX64}:  ssaop.OpComplexReal,
  2529  	{ir.OREAL, types.TCOMPLEX128}: ssaop.OpComplexReal,
  2530  
  2531  	{ir.OMUL, types.TINT8}:    ssaop.OpMul8,
  2532  	{ir.OMUL, types.TUINT8}:   ssaop.OpMul8,
  2533  	{ir.OMUL, types.TINT16}:   ssaop.OpMul16,
  2534  	{ir.OMUL, types.TUINT16}:  ssaop.OpMul16,
  2535  	{ir.OMUL, types.TINT32}:   ssaop.OpMul32,
  2536  	{ir.OMUL, types.TUINT32}:  ssaop.OpMul32,
  2537  	{ir.OMUL, types.TINT64}:   ssaop.OpMul64,
  2538  	{ir.OMUL, types.TUINT64}:  ssaop.OpMul64,
  2539  	{ir.OMUL, types.TFLOAT32}: ssaop.OpMul32F,
  2540  	{ir.OMUL, types.TFLOAT64}: ssaop.OpMul64F,
  2541  
  2542  	{ir.ODIV, types.TFLOAT32}: ssaop.OpDiv32F,
  2543  	{ir.ODIV, types.TFLOAT64}: ssaop.OpDiv64F,
  2544  
  2545  	{ir.ODIV, types.TINT8}:   ssaop.OpDiv8,
  2546  	{ir.ODIV, types.TUINT8}:  ssaop.OpDiv8u,
  2547  	{ir.ODIV, types.TINT16}:  ssaop.OpDiv16,
  2548  	{ir.ODIV, types.TUINT16}: ssaop.OpDiv16u,
  2549  	{ir.ODIV, types.TINT32}:  ssaop.OpDiv32,
  2550  	{ir.ODIV, types.TUINT32}: ssaop.OpDiv32u,
  2551  	{ir.ODIV, types.TINT64}:  ssaop.OpDiv64,
  2552  	{ir.ODIV, types.TUINT64}: ssaop.OpDiv64u,
  2553  
  2554  	{ir.OMOD, types.TINT8}:   ssaop.OpMod8,
  2555  	{ir.OMOD, types.TUINT8}:  ssaop.OpMod8u,
  2556  	{ir.OMOD, types.TINT16}:  ssaop.OpMod16,
  2557  	{ir.OMOD, types.TUINT16}: ssaop.OpMod16u,
  2558  	{ir.OMOD, types.TINT32}:  ssaop.OpMod32,
  2559  	{ir.OMOD, types.TUINT32}: ssaop.OpMod32u,
  2560  	{ir.OMOD, types.TINT64}:  ssaop.OpMod64,
  2561  	{ir.OMOD, types.TUINT64}: ssaop.OpMod64u,
  2562  
  2563  	{ir.OAND, types.TINT8}:   ssaop.OpAnd8,
  2564  	{ir.OAND, types.TUINT8}:  ssaop.OpAnd8,
  2565  	{ir.OAND, types.TINT16}:  ssaop.OpAnd16,
  2566  	{ir.OAND, types.TUINT16}: ssaop.OpAnd16,
  2567  	{ir.OAND, types.TINT32}:  ssaop.OpAnd32,
  2568  	{ir.OAND, types.TUINT32}: ssaop.OpAnd32,
  2569  	{ir.OAND, types.TINT64}:  ssaop.OpAnd64,
  2570  	{ir.OAND, types.TUINT64}: ssaop.OpAnd64,
  2571  
  2572  	{ir.OOR, types.TINT8}:   ssaop.OpOr8,
  2573  	{ir.OOR, types.TUINT8}:  ssaop.OpOr8,
  2574  	{ir.OOR, types.TINT16}:  ssaop.OpOr16,
  2575  	{ir.OOR, types.TUINT16}: ssaop.OpOr16,
  2576  	{ir.OOR, types.TINT32}:  ssaop.OpOr32,
  2577  	{ir.OOR, types.TUINT32}: ssaop.OpOr32,
  2578  	{ir.OOR, types.TINT64}:  ssaop.OpOr64,
  2579  	{ir.OOR, types.TUINT64}: ssaop.OpOr64,
  2580  
  2581  	{ir.OXOR, types.TINT8}:   ssaop.OpXor8,
  2582  	{ir.OXOR, types.TUINT8}:  ssaop.OpXor8,
  2583  	{ir.OXOR, types.TINT16}:  ssaop.OpXor16,
  2584  	{ir.OXOR, types.TUINT16}: ssaop.OpXor16,
  2585  	{ir.OXOR, types.TINT32}:  ssaop.OpXor32,
  2586  	{ir.OXOR, types.TUINT32}: ssaop.OpXor32,
  2587  	{ir.OXOR, types.TINT64}:  ssaop.OpXor64,
  2588  	{ir.OXOR, types.TUINT64}: ssaop.OpXor64,
  2589  
  2590  	{ir.OEQ, types.TBOOL}:      ssaop.OpEqB,
  2591  	{ir.OEQ, types.TINT8}:      ssaop.OpEq8,
  2592  	{ir.OEQ, types.TUINT8}:     ssaop.OpEq8,
  2593  	{ir.OEQ, types.TINT16}:     ssaop.OpEq16,
  2594  	{ir.OEQ, types.TUINT16}:    ssaop.OpEq16,
  2595  	{ir.OEQ, types.TINT32}:     ssaop.OpEq32,
  2596  	{ir.OEQ, types.TUINT32}:    ssaop.OpEq32,
  2597  	{ir.OEQ, types.TINT64}:     ssaop.OpEq64,
  2598  	{ir.OEQ, types.TUINT64}:    ssaop.OpEq64,
  2599  	{ir.OEQ, types.TINTER}:     ssaop.OpEqInter,
  2600  	{ir.OEQ, types.TSLICE}:     ssaop.OpEqSlice,
  2601  	{ir.OEQ, types.TFUNC}:      ssaop.OpEqPtr,
  2602  	{ir.OEQ, types.TMAP}:       ssaop.OpEqPtr,
  2603  	{ir.OEQ, types.TCHAN}:      ssaop.OpEqPtr,
  2604  	{ir.OEQ, types.TPTR}:       ssaop.OpEqPtr,
  2605  	{ir.OEQ, types.TUINTPTR}:   ssaop.OpEqPtr,
  2606  	{ir.OEQ, types.TUNSAFEPTR}: ssaop.OpEqPtr,
  2607  	{ir.OEQ, types.TFLOAT64}:   ssaop.OpEq64F,
  2608  	{ir.OEQ, types.TFLOAT32}:   ssaop.OpEq32F,
  2609  
  2610  	{ir.ONE, types.TBOOL}:      ssaop.OpNeqB,
  2611  	{ir.ONE, types.TINT8}:      ssaop.OpNeq8,
  2612  	{ir.ONE, types.TUINT8}:     ssaop.OpNeq8,
  2613  	{ir.ONE, types.TINT16}:     ssaop.OpNeq16,
  2614  	{ir.ONE, types.TUINT16}:    ssaop.OpNeq16,
  2615  	{ir.ONE, types.TINT32}:     ssaop.OpNeq32,
  2616  	{ir.ONE, types.TUINT32}:    ssaop.OpNeq32,
  2617  	{ir.ONE, types.TINT64}:     ssaop.OpNeq64,
  2618  	{ir.ONE, types.TUINT64}:    ssaop.OpNeq64,
  2619  	{ir.ONE, types.TINTER}:     ssaop.OpNeqInter,
  2620  	{ir.ONE, types.TSLICE}:     ssaop.OpNeqSlice,
  2621  	{ir.ONE, types.TFUNC}:      ssaop.OpNeqPtr,
  2622  	{ir.ONE, types.TMAP}:       ssaop.OpNeqPtr,
  2623  	{ir.ONE, types.TCHAN}:      ssaop.OpNeqPtr,
  2624  	{ir.ONE, types.TPTR}:       ssaop.OpNeqPtr,
  2625  	{ir.ONE, types.TUINTPTR}:   ssaop.OpNeqPtr,
  2626  	{ir.ONE, types.TUNSAFEPTR}: ssaop.OpNeqPtr,
  2627  	{ir.ONE, types.TFLOAT64}:   ssaop.OpNeq64F,
  2628  	{ir.ONE, types.TFLOAT32}:   ssaop.OpNeq32F,
  2629  
  2630  	{ir.OLT, types.TINT8}:    ssaop.OpLess8,
  2631  	{ir.OLT, types.TUINT8}:   ssaop.OpLess8U,
  2632  	{ir.OLT, types.TINT16}:   ssaop.OpLess16,
  2633  	{ir.OLT, types.TUINT16}:  ssaop.OpLess16U,
  2634  	{ir.OLT, types.TINT32}:   ssaop.OpLess32,
  2635  	{ir.OLT, types.TUINT32}:  ssaop.OpLess32U,
  2636  	{ir.OLT, types.TINT64}:   ssaop.OpLess64,
  2637  	{ir.OLT, types.TUINT64}:  ssaop.OpLess64U,
  2638  	{ir.OLT, types.TFLOAT64}: ssaop.OpLess64F,
  2639  	{ir.OLT, types.TFLOAT32}: ssaop.OpLess32F,
  2640  
  2641  	{ir.OLE, types.TINT8}:    ssaop.OpLeq8,
  2642  	{ir.OLE, types.TUINT8}:   ssaop.OpLeq8U,
  2643  	{ir.OLE, types.TINT16}:   ssaop.OpLeq16,
  2644  	{ir.OLE, types.TUINT16}:  ssaop.OpLeq16U,
  2645  	{ir.OLE, types.TINT32}:   ssaop.OpLeq32,
  2646  	{ir.OLE, types.TUINT32}:  ssaop.OpLeq32U,
  2647  	{ir.OLE, types.TINT64}:   ssaop.OpLeq64,
  2648  	{ir.OLE, types.TUINT64}:  ssaop.OpLeq64U,
  2649  	{ir.OLE, types.TFLOAT64}: ssaop.OpLeq64F,
  2650  	{ir.OLE, types.TFLOAT32}: ssaop.OpLeq32F,
  2651  }
  2652  
  2653  func (s *state) concreteEtype(t *types.Type) types.Kind {
  2654  	e := t.Kind()
  2655  	switch e {
  2656  	default:
  2657  		return e
  2658  	case types.TINT:
  2659  		if s.config.PtrSize == 8 {
  2660  			return types.TINT64
  2661  		}
  2662  		return types.TINT32
  2663  	case types.TUINT:
  2664  		if s.config.PtrSize == 8 {
  2665  			return types.TUINT64
  2666  		}
  2667  		return types.TUINT32
  2668  	case types.TUINTPTR:
  2669  		if s.config.PtrSize == 8 {
  2670  			return types.TUINT64
  2671  		}
  2672  		return types.TUINT32
  2673  	}
  2674  }
  2675  
  2676  func (s *state) ssaOp(op ir.Op, t *types.Type) ssaop.Op {
  2677  	etype := s.concreteEtype(t)
  2678  	x, ok := opToSSA[opAndType{op, etype}]
  2679  	if !ok {
  2680  		s.Fatalf("unhandled binary op %v %s", op, etype)
  2681  	}
  2682  	return x
  2683  }
  2684  
  2685  type opAndTwoTypes struct {
  2686  	op     ir.Op
  2687  	etype1 types.Kind
  2688  	etype2 types.Kind
  2689  }
  2690  
  2691  type twoTypes struct {
  2692  	etype1 types.Kind
  2693  	etype2 types.Kind
  2694  }
  2695  
  2696  type twoOpsAndType struct {
  2697  	op1              ssaop.Op
  2698  	op2              ssaop.Op
  2699  	intermediateType types.Kind
  2700  }
  2701  
  2702  var fpConvOpToSSA = map[twoTypes]twoOpsAndType{
  2703  
  2704  	{types.TINT8, types.TFLOAT32}:  {ssaop.OpSignExt8to32, ssaop.OpCvt32to32F, types.TINT32},
  2705  	{types.TINT16, types.TFLOAT32}: {ssaop.OpSignExt16to32, ssaop.OpCvt32to32F, types.TINT32},
  2706  	{types.TINT32, types.TFLOAT32}: {ssaop.OpCopy, ssaop.OpCvt32to32F, types.TINT32},
  2707  	{types.TINT64, types.TFLOAT32}: {ssaop.OpCopy, ssaop.OpCvt64to32F, types.TINT64},
  2708  
  2709  	{types.TINT8, types.TFLOAT64}:  {ssaop.OpSignExt8to32, ssaop.OpCvt32to64F, types.TINT32},
  2710  	{types.TINT16, types.TFLOAT64}: {ssaop.OpSignExt16to32, ssaop.OpCvt32to64F, types.TINT32},
  2711  	{types.TINT32, types.TFLOAT64}: {ssaop.OpCopy, ssaop.OpCvt32to64F, types.TINT32},
  2712  	{types.TINT64, types.TFLOAT64}: {ssaop.OpCopy, ssaop.OpCvt64to64F, types.TINT64},
  2713  
  2714  	{types.TFLOAT32, types.TINT8}:  {ssaop.OpCvt32Fto32, ssaop.OpTrunc32to8, types.TINT32},
  2715  	{types.TFLOAT32, types.TINT16}: {ssaop.OpCvt32Fto32, ssaop.OpTrunc32to16, types.TINT32},
  2716  	{types.TFLOAT32, types.TINT32}: {ssaop.OpCvt32Fto32, ssaop.OpCopy, types.TINT32},
  2717  	{types.TFLOAT32, types.TINT64}: {ssaop.OpCvt32Fto64, ssaop.OpCopy, types.TINT64},
  2718  
  2719  	{types.TFLOAT64, types.TINT8}:  {ssaop.OpCvt64Fto32, ssaop.OpTrunc32to8, types.TINT32},
  2720  	{types.TFLOAT64, types.TINT16}: {ssaop.OpCvt64Fto32, ssaop.OpTrunc32to16, types.TINT32},
  2721  	{types.TFLOAT64, types.TINT32}: {ssaop.OpCvt64Fto32, ssaop.OpCopy, types.TINT32},
  2722  	{types.TFLOAT64, types.TINT64}: {ssaop.OpCvt64Fto64, ssaop.OpCopy, types.TINT64},
  2723  	// unsigned
  2724  	{types.TUINT8, types.TFLOAT32}:  {ssaop.OpZeroExt8to32, ssaop.OpCvt32to32F, types.TINT32},
  2725  	{types.TUINT16, types.TFLOAT32}: {ssaop.OpZeroExt16to32, ssaop.OpCvt32to32F, types.TINT32},
  2726  	{types.TUINT32, types.TFLOAT32}: {ssaop.OpZeroExt32to64, ssaop.OpCvt64to32F, types.TINT64}, // go wide to dodge unsigned
  2727  	{types.TUINT64, types.TFLOAT32}: {ssaop.OpCopy, ssaop.OpInvalid, types.TUINT64},            // Cvt64Uto32F, branchy code expansion instead
  2728  
  2729  	{types.TUINT8, types.TFLOAT64}:  {ssaop.OpZeroExt8to32, ssaop.OpCvt32to64F, types.TINT32},
  2730  	{types.TUINT16, types.TFLOAT64}: {ssaop.OpZeroExt16to32, ssaop.OpCvt32to64F, types.TINT32},
  2731  	{types.TUINT32, types.TFLOAT64}: {ssaop.OpZeroExt32to64, ssaop.OpCvt64to64F, types.TINT64}, // go wide to dodge unsigned
  2732  	{types.TUINT64, types.TFLOAT64}: {ssaop.OpCopy, ssaop.OpInvalid, types.TUINT64},            // Cvt64Uto64F, branchy code expansion instead
  2733  
  2734  	{types.TFLOAT32, types.TUINT8}:  {ssaop.OpCvt32Fto32, ssaop.OpTrunc32to8, types.TINT32},
  2735  	{types.TFLOAT32, types.TUINT16}: {ssaop.OpCvt32Fto32, ssaop.OpTrunc32to16, types.TINT32},
  2736  	{types.TFLOAT32, types.TUINT32}: {ssaop.OpInvalid, ssaop.OpCopy, types.TINT64},  // Cvt64Fto32U, branchy code expansion instead
  2737  	{types.TFLOAT32, types.TUINT64}: {ssaop.OpInvalid, ssaop.OpCopy, types.TUINT64}, // Cvt32Fto64U, branchy code expansion instead
  2738  
  2739  	{types.TFLOAT64, types.TUINT8}:  {ssaop.OpCvt64Fto32, ssaop.OpTrunc32to8, types.TINT32},
  2740  	{types.TFLOAT64, types.TUINT16}: {ssaop.OpCvt64Fto32, ssaop.OpTrunc32to16, types.TINT32},
  2741  	{types.TFLOAT64, types.TUINT32}: {ssaop.OpInvalid, ssaop.OpCopy, types.TINT64},  // Cvt64Fto32U, branchy code expansion instead
  2742  	{types.TFLOAT64, types.TUINT64}: {ssaop.OpInvalid, ssaop.OpCopy, types.TUINT64}, // Cvt64Fto64U, branchy code expansion instead
  2743  
  2744  	// float
  2745  	{types.TFLOAT64, types.TFLOAT32}: {ssaop.OpCvt64Fto32F, ssaop.OpCopy, types.TFLOAT32},
  2746  	{types.TFLOAT64, types.TFLOAT64}: {ssaop.OpRound64F, ssaop.OpCopy, types.TFLOAT64},
  2747  	{types.TFLOAT32, types.TFLOAT32}: {ssaop.OpRound32F, ssaop.OpCopy, types.TFLOAT32},
  2748  	{types.TFLOAT32, types.TFLOAT64}: {ssaop.OpCvt32Fto64F, ssaop.OpCopy, types.TFLOAT64},
  2749  }
  2750  
  2751  // this map is used only for 32-bit arch, and only includes the difference
  2752  // on 32-bit arch, don't use int64<->float conversion for uint32
  2753  var fpConvOpToSSA32 = map[twoTypes]twoOpsAndType{
  2754  	{types.TUINT32, types.TFLOAT32}: {ssaop.OpCopy, ssaop.OpCvt32Uto32F, types.TUINT32},
  2755  	{types.TUINT32, types.TFLOAT64}: {ssaop.OpCopy, ssaop.OpCvt32Uto64F, types.TUINT32},
  2756  	{types.TFLOAT32, types.TUINT32}: {ssaop.OpCvt32Fto32U, ssaop.OpCopy, types.TUINT32},
  2757  	{types.TFLOAT64, types.TUINT32}: {ssaop.OpCvt64Fto32U, ssaop.OpCopy, types.TUINT32},
  2758  }
  2759  
  2760  // uint64<->float conversions, only on machines that have instructions for that
  2761  var uint64fpConvOpToSSA = map[twoTypes]twoOpsAndType{
  2762  	{types.TUINT64, types.TFLOAT32}: {ssaop.OpCopy, ssaop.OpCvt64Uto32F, types.TUINT64},
  2763  	{types.TUINT64, types.TFLOAT64}: {ssaop.OpCopy, ssaop.OpCvt64Uto64F, types.TUINT64},
  2764  	{types.TFLOAT32, types.TUINT64}: {ssaop.OpCvt32Fto64U, ssaop.OpCopy, types.TUINT64},
  2765  	{types.TFLOAT64, types.TUINT64}: {ssaop.OpCvt64Fto64U, ssaop.OpCopy, types.TUINT64},
  2766  }
  2767  
  2768  var shiftOpToSSA = map[opAndTwoTypes]ssaop.Op{
  2769  	{ir.OLSH, types.TINT8, types.TUINT8}:   ssaop.OpLsh8x8,
  2770  	{ir.OLSH, types.TUINT8, types.TUINT8}:  ssaop.OpLsh8x8,
  2771  	{ir.OLSH, types.TINT8, types.TUINT16}:  ssaop.OpLsh8x16,
  2772  	{ir.OLSH, types.TUINT8, types.TUINT16}: ssaop.OpLsh8x16,
  2773  	{ir.OLSH, types.TINT8, types.TUINT32}:  ssaop.OpLsh8x32,
  2774  	{ir.OLSH, types.TUINT8, types.TUINT32}: ssaop.OpLsh8x32,
  2775  	{ir.OLSH, types.TINT8, types.TUINT64}:  ssaop.OpLsh8x64,
  2776  	{ir.OLSH, types.TUINT8, types.TUINT64}: ssaop.OpLsh8x64,
  2777  
  2778  	{ir.OLSH, types.TINT16, types.TUINT8}:   ssaop.OpLsh16x8,
  2779  	{ir.OLSH, types.TUINT16, types.TUINT8}:  ssaop.OpLsh16x8,
  2780  	{ir.OLSH, types.TINT16, types.TUINT16}:  ssaop.OpLsh16x16,
  2781  	{ir.OLSH, types.TUINT16, types.TUINT16}: ssaop.OpLsh16x16,
  2782  	{ir.OLSH, types.TINT16, types.TUINT32}:  ssaop.OpLsh16x32,
  2783  	{ir.OLSH, types.TUINT16, types.TUINT32}: ssaop.OpLsh16x32,
  2784  	{ir.OLSH, types.TINT16, types.TUINT64}:  ssaop.OpLsh16x64,
  2785  	{ir.OLSH, types.TUINT16, types.TUINT64}: ssaop.OpLsh16x64,
  2786  
  2787  	{ir.OLSH, types.TINT32, types.TUINT8}:   ssaop.OpLsh32x8,
  2788  	{ir.OLSH, types.TUINT32, types.TUINT8}:  ssaop.OpLsh32x8,
  2789  	{ir.OLSH, types.TINT32, types.TUINT16}:  ssaop.OpLsh32x16,
  2790  	{ir.OLSH, types.TUINT32, types.TUINT16}: ssaop.OpLsh32x16,
  2791  	{ir.OLSH, types.TINT32, types.TUINT32}:  ssaop.OpLsh32x32,
  2792  	{ir.OLSH, types.TUINT32, types.TUINT32}: ssaop.OpLsh32x32,
  2793  	{ir.OLSH, types.TINT32, types.TUINT64}:  ssaop.OpLsh32x64,
  2794  	{ir.OLSH, types.TUINT32, types.TUINT64}: ssaop.OpLsh32x64,
  2795  
  2796  	{ir.OLSH, types.TINT64, types.TUINT8}:   ssaop.OpLsh64x8,
  2797  	{ir.OLSH, types.TUINT64, types.TUINT8}:  ssaop.OpLsh64x8,
  2798  	{ir.OLSH, types.TINT64, types.TUINT16}:  ssaop.OpLsh64x16,
  2799  	{ir.OLSH, types.TUINT64, types.TUINT16}: ssaop.OpLsh64x16,
  2800  	{ir.OLSH, types.TINT64, types.TUINT32}:  ssaop.OpLsh64x32,
  2801  	{ir.OLSH, types.TUINT64, types.TUINT32}: ssaop.OpLsh64x32,
  2802  	{ir.OLSH, types.TINT64, types.TUINT64}:  ssaop.OpLsh64x64,
  2803  	{ir.OLSH, types.TUINT64, types.TUINT64}: ssaop.OpLsh64x64,
  2804  
  2805  	{ir.ORSH, types.TINT8, types.TUINT8}:   ssaop.OpRsh8x8,
  2806  	{ir.ORSH, types.TUINT8, types.TUINT8}:  ssaop.OpRsh8Ux8,
  2807  	{ir.ORSH, types.TINT8, types.TUINT16}:  ssaop.OpRsh8x16,
  2808  	{ir.ORSH, types.TUINT8, types.TUINT16}: ssaop.OpRsh8Ux16,
  2809  	{ir.ORSH, types.TINT8, types.TUINT32}:  ssaop.OpRsh8x32,
  2810  	{ir.ORSH, types.TUINT8, types.TUINT32}: ssaop.OpRsh8Ux32,
  2811  	{ir.ORSH, types.TINT8, types.TUINT64}:  ssaop.OpRsh8x64,
  2812  	{ir.ORSH, types.TUINT8, types.TUINT64}: ssaop.OpRsh8Ux64,
  2813  
  2814  	{ir.ORSH, types.TINT16, types.TUINT8}:   ssaop.OpRsh16x8,
  2815  	{ir.ORSH, types.TUINT16, types.TUINT8}:  ssaop.OpRsh16Ux8,
  2816  	{ir.ORSH, types.TINT16, types.TUINT16}:  ssaop.OpRsh16x16,
  2817  	{ir.ORSH, types.TUINT16, types.TUINT16}: ssaop.OpRsh16Ux16,
  2818  	{ir.ORSH, types.TINT16, types.TUINT32}:  ssaop.OpRsh16x32,
  2819  	{ir.ORSH, types.TUINT16, types.TUINT32}: ssaop.OpRsh16Ux32,
  2820  	{ir.ORSH, types.TINT16, types.TUINT64}:  ssaop.OpRsh16x64,
  2821  	{ir.ORSH, types.TUINT16, types.TUINT64}: ssaop.OpRsh16Ux64,
  2822  
  2823  	{ir.ORSH, types.TINT32, types.TUINT8}:   ssaop.OpRsh32x8,
  2824  	{ir.ORSH, types.TUINT32, types.TUINT8}:  ssaop.OpRsh32Ux8,
  2825  	{ir.ORSH, types.TINT32, types.TUINT16}:  ssaop.OpRsh32x16,
  2826  	{ir.ORSH, types.TUINT32, types.TUINT16}: ssaop.OpRsh32Ux16,
  2827  	{ir.ORSH, types.TINT32, types.TUINT32}:  ssaop.OpRsh32x32,
  2828  	{ir.ORSH, types.TUINT32, types.TUINT32}: ssaop.OpRsh32Ux32,
  2829  	{ir.ORSH, types.TINT32, types.TUINT64}:  ssaop.OpRsh32x64,
  2830  	{ir.ORSH, types.TUINT32, types.TUINT64}: ssaop.OpRsh32Ux64,
  2831  
  2832  	{ir.ORSH, types.TINT64, types.TUINT8}:   ssaop.OpRsh64x8,
  2833  	{ir.ORSH, types.TUINT64, types.TUINT8}:  ssaop.OpRsh64Ux8,
  2834  	{ir.ORSH, types.TINT64, types.TUINT16}:  ssaop.OpRsh64x16,
  2835  	{ir.ORSH, types.TUINT64, types.TUINT16}: ssaop.OpRsh64Ux16,
  2836  	{ir.ORSH, types.TINT64, types.TUINT32}:  ssaop.OpRsh64x32,
  2837  	{ir.ORSH, types.TUINT64, types.TUINT32}: ssaop.OpRsh64Ux32,
  2838  	{ir.ORSH, types.TINT64, types.TUINT64}:  ssaop.OpRsh64x64,
  2839  	{ir.ORSH, types.TUINT64, types.TUINT64}: ssaop.OpRsh64Ux64,
  2840  }
  2841  
  2842  func (s *state) ssaShiftOp(op ir.Op, t *types.Type, u *types.Type) ssaop.Op {
  2843  	etype1 := s.concreteEtype(t)
  2844  	etype2 := s.concreteEtype(u)
  2845  	x, ok := shiftOpToSSA[opAndTwoTypes{op, etype1, etype2}]
  2846  	if !ok {
  2847  		s.Fatalf("unhandled shift op %v etype=%s/%s", op, etype1, etype2)
  2848  	}
  2849  	return x
  2850  }
  2851  
  2852  func (s *state) uintptrConstant(v uint64) *ssa.Value {
  2853  	if s.config.PtrSize == 4 {
  2854  		return s.newValue0I(ssaop.OpConst32, types.Types[types.TUINTPTR], int64(v))
  2855  	}
  2856  	return s.newValue0I(ssaop.OpConst64, types.Types[types.TUINTPTR], int64(v))
  2857  }
  2858  
  2859  func (s *state) conv(n ir.Node, v *ssa.Value, ft, tt *types.Type) *ssa.Value {
  2860  	if ft.IsBoolean() && tt.IsKind(types.TUINT8) {
  2861  		// Bool -> uint8 is generated internally when indexing into runtime.staticbyte.
  2862  		return s.newValue1(ssaop.OpCvtBoolToUint8, tt, v)
  2863  	}
  2864  	if ft.IsInteger() && tt.IsInteger() {
  2865  		var op ssaop.Op
  2866  		if tt.Size() == ft.Size() {
  2867  			op = ssaop.OpCopy
  2868  		} else if tt.Size() < ft.Size() {
  2869  			// truncation
  2870  			switch 10*ft.Size() + tt.Size() {
  2871  			case 21:
  2872  				op = ssaop.OpTrunc16to8
  2873  			case 41:
  2874  				op = ssaop.OpTrunc32to8
  2875  			case 42:
  2876  				op = ssaop.OpTrunc32to16
  2877  			case 81:
  2878  				op = ssaop.OpTrunc64to8
  2879  			case 82:
  2880  				op = ssaop.OpTrunc64to16
  2881  			case 84:
  2882  				op = ssaop.OpTrunc64to32
  2883  			default:
  2884  				s.Fatalf("weird integer truncation %v -> %v", ft, tt)
  2885  			}
  2886  		} else if ft.IsSigned() {
  2887  			// sign extension
  2888  			switch 10*ft.Size() + tt.Size() {
  2889  			case 12:
  2890  				op = ssaop.OpSignExt8to16
  2891  			case 14:
  2892  				op = ssaop.OpSignExt8to32
  2893  			case 18:
  2894  				op = ssaop.OpSignExt8to64
  2895  			case 24:
  2896  				op = ssaop.OpSignExt16to32
  2897  			case 28:
  2898  				op = ssaop.OpSignExt16to64
  2899  			case 48:
  2900  				op = ssaop.OpSignExt32to64
  2901  			default:
  2902  				s.Fatalf("bad integer sign extension %v -> %v", ft, tt)
  2903  			}
  2904  		} else {
  2905  			// zero extension
  2906  			switch 10*ft.Size() + tt.Size() {
  2907  			case 12:
  2908  				op = ssaop.OpZeroExt8to16
  2909  			case 14:
  2910  				op = ssaop.OpZeroExt8to32
  2911  			case 18:
  2912  				op = ssaop.OpZeroExt8to64
  2913  			case 24:
  2914  				op = ssaop.OpZeroExt16to32
  2915  			case 28:
  2916  				op = ssaop.OpZeroExt16to64
  2917  			case 48:
  2918  				op = ssaop.OpZeroExt32to64
  2919  			default:
  2920  				s.Fatalf("weird integer sign extension %v -> %v", ft, tt)
  2921  			}
  2922  		}
  2923  		return s.newValue1(op, tt, v)
  2924  	}
  2925  
  2926  	if ft.IsComplex() && tt.IsComplex() {
  2927  		var op ssaop.Op
  2928  		if ft.Size() == tt.Size() {
  2929  			switch ft.Size() {
  2930  			case 8:
  2931  				op = ssaop.OpRound32F
  2932  			case 16:
  2933  				op = ssaop.OpRound64F
  2934  			default:
  2935  				s.Fatalf("weird complex conversion %v -> %v", ft, tt)
  2936  			}
  2937  		} else if ft.Size() == 8 && tt.Size() == 16 {
  2938  			op = ssaop.OpCvt32Fto64F
  2939  		} else if ft.Size() == 16 && tt.Size() == 8 {
  2940  			op = ssaop.OpCvt64Fto32F
  2941  		} else {
  2942  			s.Fatalf("weird complex conversion %v -> %v", ft, tt)
  2943  		}
  2944  		ftp := types.FloatForComplex(ft)
  2945  		ttp := types.FloatForComplex(tt)
  2946  		return s.newValue2(ssaop.OpComplexMake, tt,
  2947  			s.newValueOrSfCall1(op, ttp, s.newValue1(ssaop.OpComplexReal, ftp, v)),
  2948  			s.newValueOrSfCall1(op, ttp, s.newValue1(ssaop.OpComplexImag, ftp, v)))
  2949  	}
  2950  
  2951  	if tt.IsComplex() { // and ft is not complex
  2952  		// Needed for generics support - can't happen in normal Go code.
  2953  		et := types.FloatForComplex(tt)
  2954  		v = s.conv(n, v, ft, et)
  2955  		return s.newValue2(ssaop.OpComplexMake, tt, v, s.zeroVal(et))
  2956  	}
  2957  
  2958  	if ft.IsFloat() || tt.IsFloat() {
  2959  		cft, ctt := s.concreteEtype(ft), s.concreteEtype(tt)
  2960  		conv, ok := fpConvOpToSSA[twoTypes{cft, ctt}]
  2961  		// there's a change to a conversion-op table, this restores the old behavior if ConvertHash is false.
  2962  		// use salted hash to distinguish unsigned convert at a Pos from signed convert at a Pos
  2963  		if ctt == types.TUINT32 && ft.IsFloat() && !base.ConvertHash.MatchPosWithInfo(n.Pos(), "U", nil) {
  2964  			// revert to old behavior
  2965  			conv.op1 = ssaop.OpCvt64Fto64
  2966  			if cft == types.TFLOAT32 {
  2967  				conv.op1 = ssaop.OpCvt32Fto64
  2968  			}
  2969  			conv.op2 = ssaop.OpTrunc64to32
  2970  
  2971  		}
  2972  		if s.config.RegSize == 4 && Arch.LinkArch.Family != sys.MIPS && !s.softFloat {
  2973  			if conv1, ok1 := fpConvOpToSSA32[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]; ok1 {
  2974  				conv = conv1
  2975  			}
  2976  		}
  2977  		if Arch.LinkArch.Family == sys.ARM64 || Arch.LinkArch.Family == sys.Wasm || Arch.LinkArch.Family == sys.S390X || s.softFloat {
  2978  			if conv1, ok1 := uint64fpConvOpToSSA[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]; ok1 {
  2979  				conv = conv1
  2980  			}
  2981  		}
  2982  
  2983  		if Arch.LinkArch.Family == sys.MIPS && !s.softFloat {
  2984  			if ft.Size() == 4 && ft.IsInteger() && !ft.IsSigned() {
  2985  				// tt is float32 or float64, and ft is also unsigned
  2986  				if tt.Size() == 4 {
  2987  					return s.uint32Tofloat32(n, v, ft, tt)
  2988  				}
  2989  				if tt.Size() == 8 {
  2990  					return s.uint32Tofloat64(n, v, ft, tt)
  2991  				}
  2992  			} else if tt.Size() == 4 && tt.IsInteger() && !tt.IsSigned() {
  2993  				// ft is float32 or float64, and tt is unsigned integer
  2994  				if ft.Size() == 4 {
  2995  					return s.float32ToUint32(n, v, ft, tt)
  2996  				}
  2997  				if ft.Size() == 8 {
  2998  					return s.float64ToUint32(n, v, ft, tt)
  2999  				}
  3000  			}
  3001  		}
  3002  
  3003  		if !ok {
  3004  			s.Fatalf("weird float conversion %v -> %v", ft, tt)
  3005  		}
  3006  		op1, op2, it := conv.op1, conv.op2, conv.intermediateType
  3007  
  3008  		if op1 != ssaop.OpInvalid && op2 != ssaop.OpInvalid {
  3009  			// normal case, not tripping over unsigned 64
  3010  			if op1 == ssaop.OpCopy {
  3011  				if op2 == ssaop.OpCopy {
  3012  					return v
  3013  				}
  3014  				return s.newValueOrSfCall1(op2, tt, v)
  3015  			}
  3016  			if op2 == ssaop.OpCopy {
  3017  				return s.newValueOrSfCall1(op1, tt, v)
  3018  			}
  3019  			return s.newValueOrSfCall1(op2, tt, s.newValueOrSfCall1(op1, types.Types[it], v))
  3020  		}
  3021  		// Tricky 64-bit unsigned cases.
  3022  		if ft.IsInteger() {
  3023  			// tt is float32 or float64, and ft is also unsigned
  3024  			if tt.Size() == 4 {
  3025  				return s.uint64Tofloat32(n, v, ft, tt)
  3026  			}
  3027  			if tt.Size() == 8 {
  3028  				return s.uint64Tofloat64(n, v, ft, tt)
  3029  			}
  3030  			s.Fatalf("weird unsigned integer to float conversion %v -> %v", ft, tt)
  3031  		}
  3032  		// ft is float32 or float64, and tt is unsigned integer
  3033  		if ft.Size() == 4 {
  3034  			switch tt.Size() {
  3035  			case 8:
  3036  				return s.float32ToUint64(n, v, ft, tt)
  3037  			case 4, 2, 1:
  3038  				// TODO should 2 and 1 saturate or truncate?
  3039  				return s.float32ToUint32(n, v, ft, tt)
  3040  			}
  3041  		}
  3042  		if ft.Size() == 8 {
  3043  			switch tt.Size() {
  3044  			case 8:
  3045  				return s.float64ToUint64(n, v, ft, tt)
  3046  			case 4, 2, 1:
  3047  				// TODO should 2 and 1 saturate or truncate?
  3048  				return s.float64ToUint32(n, v, ft, tt)
  3049  			}
  3050  
  3051  		}
  3052  		s.Fatalf("weird float to unsigned integer conversion %v -> %v", ft, tt)
  3053  		return nil
  3054  	}
  3055  
  3056  	s.Fatalf("unhandled OCONV %s -> %s", ft.Kind(), tt.Kind())
  3057  	return nil
  3058  }
  3059  
  3060  // expr converts the expression n to ssa, adds it to s and returns the ssa result.
  3061  func (s *state) expr(n ir.Node) *ssa.Value {
  3062  	return s.exprCheckPtr(n, true)
  3063  }
  3064  
  3065  func (s *state) exprCheckPtr(n ir.Node, checkPtrOK bool) *ssa.Value {
  3066  	if ir.HasUniquePos(n) {
  3067  		// ONAMEs and named OLITERALs have the line number
  3068  		// of the decl, not the use. See issue 14742.
  3069  		s.pushLine(n.Pos())
  3070  		defer s.popLine()
  3071  	}
  3072  
  3073  	s.stmtList(n.Init())
  3074  	switch n.Op() {
  3075  	case ir.OBYTES2STRTMP:
  3076  		n := n.(*ir.ConvExpr)
  3077  		slice := s.expr(n.X)
  3078  		ptr := s.newValue1(ssaop.OpSlicePtr, s.f.Config.Types.BytePtr, slice)
  3079  		len := s.newValue1(ssaop.OpSliceLen, types.Types[types.TINT], slice)
  3080  		return s.newValue2(ssaop.OpStringMake, n.Type(), ptr, len)
  3081  	case ir.OSTR2BYTESTMP:
  3082  		n := n.(*ir.ConvExpr)
  3083  		str := s.expr(n.X)
  3084  		ptr := s.newValue1(ssaop.OpStringPtr, s.f.Config.Types.BytePtr, str)
  3085  		if !n.NonNil() {
  3086  			// We need to ensure []byte("") evaluates to []byte{}, and not []byte(nil).
  3087  			//
  3088  			// TODO(mdempsky): Investigate using "len != 0" instead of "ptr != nil".
  3089  			cond := s.newValue2(ssaop.OpNeqPtr, types.Types[types.TBOOL], ptr, s.constNil(ptr.Type))
  3090  			zerobase := s.newValue1A(ssaop.OpAddr, ptr.Type, ir.Syms.Zerobase, s.sb)
  3091  			ptr = s.ternary(cond, ptr, zerobase)
  3092  		}
  3093  		len := s.newValue1(ssaop.OpStringLen, types.Types[types.TINT], str)
  3094  		return s.newValue3(ssaop.OpSliceMake, n.Type(), ptr, len, len)
  3095  	case ir.OCFUNC:
  3096  		n := n.(*ir.UnaryExpr)
  3097  		name := n.X.(*ir.Name)
  3098  		aux := name.Linksym()
  3099  		// OCFUNC is used to build function values, which must
  3100  		// always reference ABIInternal entry points.
  3101  		if aux.ABI() != obj.ABIInternal {
  3102  			s.Fatalf("expected ABIInternal: %v", aux.ABI())
  3103  		}
  3104  		if buildcfg.GOARCH == "wasm32" {
  3105  			// wasm32 function values store a call_indirect table index.
  3106  			// Read it from the same function-value symbol used by static
  3107  			// data and closures.
  3108  			funcval := staticdata.FuncLinksym(name)
  3109  			addr := s.entryNewValue1A(ssaop.OpAddr, types.NewPtr(n.Type()), funcval, s.sb)
  3110  			return s.load(n.Type(), addr)
  3111  		}
  3112  		return s.entryNewValue1A(ssaop.OpAddr, n.Type(), aux, s.sb)
  3113  	case ir.ONAME:
  3114  		n := n.(*ir.Name)
  3115  		if n.Class == ir.PFUNC {
  3116  			// "value" of a function is the address of the function's closure
  3117  			sym := staticdata.FuncLinksym(n)
  3118  			return s.entryNewValue1A(ssaop.OpAddr, types.NewPtr(n.Type()), sym, s.sb)
  3119  		}
  3120  		if s.canSSA(n) {
  3121  			return s.variable(n, n.Type())
  3122  		}
  3123  		return s.load(n.Type(), s.addr(n))
  3124  	case ir.OLINKSYMOFFSET:
  3125  		n := n.(*ir.LinksymOffsetExpr)
  3126  		return s.load(n.Type(), s.addr(n))
  3127  	case ir.ONIL:
  3128  		n := n.(*ir.NilExpr)
  3129  		t := n.Type()
  3130  		switch {
  3131  		case t.IsSlice():
  3132  			return s.constSlice(t)
  3133  		case t.IsInterface():
  3134  			return s.constInterface(t)
  3135  		default:
  3136  			return s.constNil(t)
  3137  		}
  3138  	case ir.OLITERAL:
  3139  		switch u := n.Val(); u.Kind() {
  3140  		case constant.Int:
  3141  			i := ir.IntVal(n.Type(), u)
  3142  			switch n.Type().Size() {
  3143  			case 1:
  3144  				return s.constInt8(n.Type(), int8(i))
  3145  			case 2:
  3146  				return s.constInt16(n.Type(), int16(i))
  3147  			case 4:
  3148  				return s.constInt32(n.Type(), int32(i))
  3149  			case 8:
  3150  				return s.constInt64(n.Type(), i)
  3151  			default:
  3152  				s.Fatalf("bad integer size %d", n.Type().Size())
  3153  				return nil
  3154  			}
  3155  		case constant.String:
  3156  			i := constant.StringVal(u)
  3157  			if i == "" {
  3158  				return s.constEmptyString(n.Type())
  3159  			}
  3160  			return s.entryNewValue0A(ssaop.OpConstString, n.Type(), ssa.StringToAux(i))
  3161  		case constant.Bool:
  3162  			return s.constBool(constant.BoolVal(u))
  3163  		case constant.Float:
  3164  			f, _ := constant.Float64Val(u)
  3165  			switch n.Type().Size() {
  3166  			case 4:
  3167  				return s.constFloat32(n.Type(), f)
  3168  			case 8:
  3169  				return s.constFloat64(n.Type(), f)
  3170  			default:
  3171  				s.Fatalf("bad float size %d", n.Type().Size())
  3172  				return nil
  3173  			}
  3174  		case constant.Complex:
  3175  			re, _ := constant.Float64Val(constant.Real(u))
  3176  			im, _ := constant.Float64Val(constant.Imag(u))
  3177  			switch n.Type().Size() {
  3178  			case 8:
  3179  				pt := types.Types[types.TFLOAT32]
  3180  				return s.newValue2(ssaop.OpComplexMake, n.Type(),
  3181  					s.constFloat32(pt, re),
  3182  					s.constFloat32(pt, im))
  3183  			case 16:
  3184  				pt := types.Types[types.TFLOAT64]
  3185  				return s.newValue2(ssaop.OpComplexMake, n.Type(),
  3186  					s.constFloat64(pt, re),
  3187  					s.constFloat64(pt, im))
  3188  			default:
  3189  				s.Fatalf("bad complex size %d", n.Type().Size())
  3190  				return nil
  3191  			}
  3192  		default:
  3193  			s.Fatalf("unhandled OLITERAL %v", u.Kind())
  3194  			return nil
  3195  		}
  3196  	case ir.OCONVNOP:
  3197  		n := n.(*ir.ConvExpr)
  3198  		to := n.Type()
  3199  		from := n.X.Type()
  3200  
  3201  		// Assume everything will work out, so set up our return value.
  3202  		// Anything interesting that happens from here is a fatal.
  3203  		x := s.expr(n.X)
  3204  		if to == from {
  3205  			return x
  3206  		}
  3207  
  3208  		// Special case for not confusing GC and liveness.
  3209  		// We don't want pointers accidentally classified
  3210  		// as not-pointers or vice-versa because of copy
  3211  		// elision.
  3212  		if to.IsPtrShaped() != from.IsPtrShaped() {
  3213  			return s.newValue2(ssaop.OpConvert, to, x, s.mem())
  3214  		}
  3215  
  3216  		v := s.newValue1(ssaop.OpCopy, to, x) // ensure that v has the right type
  3217  
  3218  		// CONVNOP closure
  3219  		if to.Kind() == types.TFUNC && from.IsPtrShaped() {
  3220  			return v
  3221  		}
  3222  
  3223  		// named <--> unnamed type or typed <--> untyped const
  3224  		if from.Kind() == to.Kind() {
  3225  			return v
  3226  		}
  3227  
  3228  		// unsafe.Pointer <--> *T
  3229  		if to.IsUnsafePtr() && from.IsPtrShaped() || from.IsUnsafePtr() && to.IsPtrShaped() {
  3230  			if s.checkPtrEnabled && checkPtrOK && to.IsPtr() && from.IsUnsafePtr() {
  3231  				s.checkPtrAlignment(n, v, nil)
  3232  			}
  3233  			return v
  3234  		}
  3235  
  3236  		// map <--> *internal/runtime/maps.Map
  3237  		mt := types.NewPtr(reflectdata.MapType())
  3238  		if to.Kind() == types.TMAP && from == mt {
  3239  			return v
  3240  		}
  3241  
  3242  		types.CalcSize(from)
  3243  		types.CalcSize(to)
  3244  		if from.Size() != to.Size() {
  3245  			s.Fatalf("CONVNOP width mismatch %v (%d) -> %v (%d)\n", from, from.Size(), to, to.Size())
  3246  			return nil
  3247  		}
  3248  		if etypesign(from.Kind()) != etypesign(to.Kind()) {
  3249  			s.Fatalf("CONVNOP sign mismatch %v (%s) -> %v (%s)\n", from, from.Kind(), to, to.Kind())
  3250  			return nil
  3251  		}
  3252  
  3253  		if base.Flag.Cfg.Instrumenting {
  3254  			// These appear to be fine, but they fail the
  3255  			// integer constraint below, so okay them here.
  3256  			// Sample non-integer conversion: map[string]string -> *uint8
  3257  			return v
  3258  		}
  3259  
  3260  		if etypesign(from.Kind()) == 0 {
  3261  			s.Fatalf("CONVNOP unrecognized non-integer %v -> %v\n", from, to)
  3262  			return nil
  3263  		}
  3264  
  3265  		// integer, same width, same sign
  3266  		return v
  3267  
  3268  	case ir.OCONV:
  3269  		n := n.(*ir.ConvExpr)
  3270  		x := s.expr(n.X)
  3271  		return s.conv(n, x, n.X.Type(), n.Type())
  3272  
  3273  	case ir.ODOTTYPE:
  3274  		n := n.(*ir.TypeAssertExpr)
  3275  		res, _ := s.dottype(n, false)
  3276  		return res
  3277  
  3278  	case ir.ODYNAMICDOTTYPE:
  3279  		n := n.(*ir.DynamicTypeAssertExpr)
  3280  		res, _ := s.dynamicDottype(n, false)
  3281  		return res
  3282  
  3283  	// binary ops
  3284  	case ir.OLT, ir.OEQ, ir.ONE, ir.OLE, ir.OGE, ir.OGT:
  3285  		n := n.(*ir.BinaryExpr)
  3286  		a := s.expr(n.X)
  3287  		b := s.expr(n.Y)
  3288  		if t := n.X.Type(); t.IsSIMD() {
  3289  			c := s.newValue2(simdEqualOp(t), types.Types[types.TBOOL], a, b)
  3290  			switch n.Op() {
  3291  			case ir.OEQ:
  3292  				return c
  3293  			case ir.ONE:
  3294  				return s.newValue1(ssaop.OpNot, types.Types[types.TBOOL], c)
  3295  			default:
  3296  				s.Fatalf("ordered SIMD compare %v", n.Op())
  3297  			}
  3298  		}
  3299  		if n.X.Type().IsComplex() {
  3300  			pt := types.FloatForComplex(n.X.Type())
  3301  			op := s.ssaOp(ir.OEQ, pt)
  3302  			r := s.newValueOrSfCall2(op, types.Types[types.TBOOL], s.newValue1(ssaop.OpComplexReal, pt, a), s.newValue1(ssaop.OpComplexReal, pt, b))
  3303  			i := s.newValueOrSfCall2(op, types.Types[types.TBOOL], s.newValue1(ssaop.OpComplexImag, pt, a), s.newValue1(ssaop.OpComplexImag, pt, b))
  3304  			c := s.newValue2(ssaop.OpAndB, types.Types[types.TBOOL], r, i)
  3305  			switch n.Op() {
  3306  			case ir.OEQ:
  3307  				return c
  3308  			case ir.ONE:
  3309  				return s.newValue1(ssaop.OpNot, types.Types[types.TBOOL], c)
  3310  			default:
  3311  				s.Fatalf("ordered complex compare %v", n.Op())
  3312  			}
  3313  		}
  3314  
  3315  		// Convert OGE and OGT into OLE and OLT.
  3316  		op := n.Op()
  3317  		switch op {
  3318  		case ir.OGE:
  3319  			op, a, b = ir.OLE, b, a
  3320  		case ir.OGT:
  3321  			op, a, b = ir.OLT, b, a
  3322  		}
  3323  		if n.X.Type().IsFloat() {
  3324  			// float comparison
  3325  			return s.newValueOrSfCall2(s.ssaOp(op, n.X.Type()), types.Types[types.TBOOL], a, b)
  3326  		}
  3327  		// integer comparison
  3328  		return s.newValue2(s.ssaOp(op, n.X.Type()), types.Types[types.TBOOL], a, b)
  3329  	case ir.OMUL:
  3330  		n := n.(*ir.BinaryExpr)
  3331  		a := s.expr(n.X)
  3332  		b := s.expr(n.Y)
  3333  		if n.Type().IsComplex() {
  3334  			mulop := ssaop.OpMul64F
  3335  			addop := ssaop.OpAdd64F
  3336  			subop := ssaop.OpSub64F
  3337  			pt := types.FloatForComplex(n.Type()) // Could be Float32 or Float64
  3338  			wt := types.Types[types.TFLOAT64]     // Compute in Float64 to minimize cancellation error
  3339  
  3340  			areal := s.newValue1(ssaop.OpComplexReal, pt, a)
  3341  			breal := s.newValue1(ssaop.OpComplexReal, pt, b)
  3342  			aimag := s.newValue1(ssaop.OpComplexImag, pt, a)
  3343  			bimag := s.newValue1(ssaop.OpComplexImag, pt, b)
  3344  
  3345  			if pt != wt { // Widen for calculation
  3346  				areal = s.newValueOrSfCall1(ssaop.OpCvt32Fto64F, wt, areal)
  3347  				breal = s.newValueOrSfCall1(ssaop.OpCvt32Fto64F, wt, breal)
  3348  				aimag = s.newValueOrSfCall1(ssaop.OpCvt32Fto64F, wt, aimag)
  3349  				bimag = s.newValueOrSfCall1(ssaop.OpCvt32Fto64F, wt, bimag)
  3350  			}
  3351  
  3352  			xreal := s.newValueOrSfCall2(subop, wt, s.newValueOrSfCall2(mulop, wt, areal, breal), s.newValueOrSfCall2(mulop, wt, aimag, bimag))
  3353  			ximag := s.newValueOrSfCall2(addop, wt, s.newValueOrSfCall2(mulop, wt, areal, bimag), s.newValueOrSfCall2(mulop, wt, aimag, breal))
  3354  
  3355  			if pt != wt { // Narrow to store back
  3356  				xreal = s.newValueOrSfCall1(ssaop.OpCvt64Fto32F, pt, xreal)
  3357  				ximag = s.newValueOrSfCall1(ssaop.OpCvt64Fto32F, pt, ximag)
  3358  			}
  3359  
  3360  			return s.newValue2(ssaop.OpComplexMake, n.Type(), xreal, ximag)
  3361  		}
  3362  
  3363  		if n.Type().IsFloat() {
  3364  			return s.newValueOrSfCall2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
  3365  		}
  3366  
  3367  		return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
  3368  
  3369  	case ir.ODIV:
  3370  		n := n.(*ir.BinaryExpr)
  3371  		a := s.expr(n.X)
  3372  		b := s.expr(n.Y)
  3373  		if n.Type().IsComplex() {
  3374  			// TODO this is not executed because the front-end substitutes a runtime call.
  3375  			// That probably ought to change; with modest optimization the widen/narrow
  3376  			// conversions could all be elided in larger expression trees.
  3377  			mulop := ssaop.OpMul64F
  3378  			addop := ssaop.OpAdd64F
  3379  			subop := ssaop.OpSub64F
  3380  			divop := ssaop.OpDiv64F
  3381  			pt := types.FloatForComplex(n.Type()) // Could be Float32 or Float64
  3382  			wt := types.Types[types.TFLOAT64]     // Compute in Float64 to minimize cancellation error
  3383  
  3384  			areal := s.newValue1(ssaop.OpComplexReal, pt, a)
  3385  			breal := s.newValue1(ssaop.OpComplexReal, pt, b)
  3386  			aimag := s.newValue1(ssaop.OpComplexImag, pt, a)
  3387  			bimag := s.newValue1(ssaop.OpComplexImag, pt, b)
  3388  
  3389  			if pt != wt { // Widen for calculation
  3390  				areal = s.newValueOrSfCall1(ssaop.OpCvt32Fto64F, wt, areal)
  3391  				breal = s.newValueOrSfCall1(ssaop.OpCvt32Fto64F, wt, breal)
  3392  				aimag = s.newValueOrSfCall1(ssaop.OpCvt32Fto64F, wt, aimag)
  3393  				bimag = s.newValueOrSfCall1(ssaop.OpCvt32Fto64F, wt, bimag)
  3394  			}
  3395  
  3396  			denom := s.newValueOrSfCall2(addop, wt, s.newValueOrSfCall2(mulop, wt, breal, breal), s.newValueOrSfCall2(mulop, wt, bimag, bimag))
  3397  			xreal := s.newValueOrSfCall2(addop, wt, s.newValueOrSfCall2(mulop, wt, areal, breal), s.newValueOrSfCall2(mulop, wt, aimag, bimag))
  3398  			ximag := s.newValueOrSfCall2(subop, wt, s.newValueOrSfCall2(mulop, wt, aimag, breal), s.newValueOrSfCall2(mulop, wt, areal, bimag))
  3399  
  3400  			// TODO not sure if this is best done in wide precision or narrow
  3401  			// Double-rounding might be an issue.
  3402  			// Note that the pre-SSA implementation does the entire calculation
  3403  			// in wide format, so wide is compatible.
  3404  			xreal = s.newValueOrSfCall2(divop, wt, xreal, denom)
  3405  			ximag = s.newValueOrSfCall2(divop, wt, ximag, denom)
  3406  
  3407  			if pt != wt { // Narrow to store back
  3408  				xreal = s.newValueOrSfCall1(ssaop.OpCvt64Fto32F, pt, xreal)
  3409  				ximag = s.newValueOrSfCall1(ssaop.OpCvt64Fto32F, pt, ximag)
  3410  			}
  3411  			return s.newValue2(ssaop.OpComplexMake, n.Type(), xreal, ximag)
  3412  		}
  3413  		if n.Type().IsFloat() {
  3414  			return s.newValueOrSfCall2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
  3415  		}
  3416  		return s.intDivide(n, a, b)
  3417  	case ir.OMOD:
  3418  		n := n.(*ir.BinaryExpr)
  3419  		a := s.expr(n.X)
  3420  		b := s.expr(n.Y)
  3421  		return s.intDivide(n, a, b)
  3422  	case ir.OADD, ir.OSUB:
  3423  		n := n.(*ir.BinaryExpr)
  3424  		a := s.expr(n.X)
  3425  		b := s.expr(n.Y)
  3426  		if n.Type().IsComplex() {
  3427  			pt := types.FloatForComplex(n.Type())
  3428  			op := s.ssaOp(n.Op(), pt)
  3429  			return s.newValue2(ssaop.OpComplexMake, n.Type(),
  3430  				s.newValueOrSfCall2(op, pt, s.newValue1(ssaop.OpComplexReal, pt, a), s.newValue1(ssaop.OpComplexReal, pt, b)),
  3431  				s.newValueOrSfCall2(op, pt, s.newValue1(ssaop.OpComplexImag, pt, a), s.newValue1(ssaop.OpComplexImag, pt, b)))
  3432  		}
  3433  		if n.Type().IsFloat() {
  3434  			return s.newValueOrSfCall2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
  3435  		}
  3436  		return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
  3437  	case ir.OAND, ir.OOR, ir.OXOR:
  3438  		n := n.(*ir.BinaryExpr)
  3439  		a := s.expr(n.X)
  3440  		b := s.expr(n.Y)
  3441  		return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
  3442  	case ir.OANDNOT:
  3443  		n := n.(*ir.BinaryExpr)
  3444  		a := s.expr(n.X)
  3445  		b := s.expr(n.Y)
  3446  		b = s.newValue1(s.ssaOp(ir.OBITNOT, b.Type), b.Type, b)
  3447  		return s.newValue2(s.ssaOp(ir.OAND, n.Type()), a.Type, a, b)
  3448  	case ir.OLSH, ir.ORSH:
  3449  		n := n.(*ir.BinaryExpr)
  3450  		a := s.expr(n.X)
  3451  		b := s.expr(n.Y)
  3452  		bt := b.Type
  3453  		if bt.IsSigned() {
  3454  			cmp := s.newValue2(s.ssaOp(ir.OLE, bt), types.Types[types.TBOOL], s.zeroVal(bt), b)
  3455  			s.check(cmp, ir.Syms.Panicshift)
  3456  			bt = bt.ToUnsigned()
  3457  		}
  3458  		return s.newValue2(s.ssaShiftOp(n.Op(), n.Type(), bt), a.Type, a, b)
  3459  	case ir.OANDAND, ir.OOROR:
  3460  		// To implement OANDAND (and OOROR), we introduce a
  3461  		// new temporary variable to hold the result. The
  3462  		// variable is associated with the OANDAND node in the
  3463  		// s.vars table (normally variables are only
  3464  		// associated with ONAME nodes). We convert
  3465  		//     A && B
  3466  		// to
  3467  		//     var = A
  3468  		//     if var {
  3469  		//         var = B
  3470  		//     }
  3471  		// Using var in the subsequent block introduces the
  3472  		// necessary phi variable.
  3473  		n := n.(*ir.LogicalExpr)
  3474  		el := s.expr(n.X)
  3475  		s.vars[n] = el
  3476  
  3477  		b := s.endBlock()
  3478  		b.Kind = block.BlockIf
  3479  		b.SetControl(el)
  3480  		// In theory, we should set b.Likely here based on context.
  3481  		// However, gc only gives us likeliness hints
  3482  		// in a single place, for plain OIF statements,
  3483  		// and passing around context is finicky, so don't bother for now.
  3484  
  3485  		bRight := s.f.NewBlock(block.BlockPlain)
  3486  		bResult := s.f.NewBlock(block.BlockPlain)
  3487  		if n.Op() == ir.OANDAND {
  3488  			b.AddEdgeTo(bRight)
  3489  			b.AddEdgeTo(bResult)
  3490  		} else if n.Op() == ir.OOROR {
  3491  			b.AddEdgeTo(bResult)
  3492  			b.AddEdgeTo(bRight)
  3493  		}
  3494  
  3495  		s.startBlock(bRight)
  3496  		er := s.expr(n.Y)
  3497  		s.vars[n] = er
  3498  
  3499  		b = s.endBlock()
  3500  		b.AddEdgeTo(bResult)
  3501  
  3502  		s.startBlock(bResult)
  3503  		return s.variable(n, types.Types[types.TBOOL])
  3504  	case ir.OCOMPLEX:
  3505  		n := n.(*ir.BinaryExpr)
  3506  		r := s.expr(n.X)
  3507  		i := s.expr(n.Y)
  3508  		return s.newValue2(ssaop.OpComplexMake, n.Type(), r, i)
  3509  
  3510  	// unary ops
  3511  	case ir.ONEG:
  3512  		n := n.(*ir.UnaryExpr)
  3513  		a := s.expr(n.X)
  3514  		if n.Type().IsComplex() {
  3515  			tp := types.FloatForComplex(n.Type())
  3516  			negop := s.ssaOp(n.Op(), tp)
  3517  			return s.newValue2(ssaop.OpComplexMake, n.Type(),
  3518  				s.newValue1(negop, tp, s.newValue1(ssaop.OpComplexReal, tp, a)),
  3519  				s.newValue1(negop, tp, s.newValue1(ssaop.OpComplexImag, tp, a)))
  3520  		}
  3521  		return s.newValue1(s.ssaOp(n.Op(), n.Type()), a.Type, a)
  3522  	case ir.ONOT, ir.OBITNOT:
  3523  		n := n.(*ir.UnaryExpr)
  3524  		a := s.expr(n.X)
  3525  		return s.newValue1(s.ssaOp(n.Op(), n.Type()), a.Type, a)
  3526  	case ir.OIMAG, ir.OREAL:
  3527  		n := n.(*ir.UnaryExpr)
  3528  		a := s.expr(n.X)
  3529  		return s.newValue1(s.ssaOp(n.Op(), n.X.Type()), n.Type(), a)
  3530  	case ir.OPLUS:
  3531  		n := n.(*ir.UnaryExpr)
  3532  		return s.expr(n.X)
  3533  
  3534  	case ir.OADDR:
  3535  		n := n.(*ir.AddrExpr)
  3536  		return s.addr(n.X)
  3537  
  3538  	case ir.ORESULT:
  3539  		n := n.(*ir.ResultExpr)
  3540  		if s.prevCall == nil || s.prevCall.Op != ssaop.OpStaticLECall && s.prevCall.Op != ssaop.OpInterLECall && s.prevCall.Op != ssaop.OpClosureLECall {
  3541  			panic("Expected to see a previous call")
  3542  		}
  3543  		which := n.Index
  3544  		if which == -1 {
  3545  			panic(fmt.Errorf("ORESULT %v does not match call %s", n, s.prevCall))
  3546  		}
  3547  		return s.resultOfCall(s.prevCall, which, n.Type())
  3548  
  3549  	case ir.ODEREF:
  3550  		n := n.(*ir.StarExpr)
  3551  		p := s.exprPtr(n.X, n.Bounded(), n.Pos())
  3552  		return s.load(n.Type(), p)
  3553  
  3554  	case ir.ODOT:
  3555  		n := n.(*ir.SelectorExpr)
  3556  		if n.X.Op() == ir.OSTRUCTLIT {
  3557  			// All literals with nonzero fields have already been
  3558  			// rewritten during walk. Any that remain are just T{}
  3559  			// or equivalents. Use the zero value.
  3560  			if !ir.IsZero(n.X) {
  3561  				s.Fatalf("literal with nonzero value in SSA: %v", n.X)
  3562  			}
  3563  			return s.zeroVal(n.Type())
  3564  		}
  3565  		// If n is addressable and can't be represented in
  3566  		// SSA, then load just the selected field. This
  3567  		// prevents false memory dependencies in race/msan/asan
  3568  		// instrumentation.
  3569  		if ir.IsAddressable(n) && !s.canSSA(n) {
  3570  			p := s.addr(n)
  3571  			return s.load(n.Type(), p)
  3572  		}
  3573  		v := s.expr(n.X)
  3574  		return s.newValue1I(ssaop.OpStructSelect, n.Type(), int64(fieldIdx(n)), v)
  3575  
  3576  	case ir.ODOTPTR:
  3577  		n := n.(*ir.SelectorExpr)
  3578  		p := s.exprPtr(n.X, n.Bounded(), n.Pos())
  3579  		p = s.newValue1I(ssaop.OpOffPtr, types.NewPtr(n.Type()), n.Offset(), p)
  3580  		return s.load(n.Type(), p)
  3581  
  3582  	case ir.OINDEX:
  3583  		n := n.(*ir.IndexExpr)
  3584  		switch {
  3585  		case n.X.Type().IsString():
  3586  			if n.Bounded() && ir.IsConst(n.X, constant.String) && ir.IsConst(n.Index, constant.Int) {
  3587  				// Replace "abc"[1] with 'b'.
  3588  				// Delayed until now because "abc"[1] is not an ideal constant.
  3589  				// See test/fixedbugs/issue11370.go.
  3590  				return s.newValue0I(ssaop.OpConst8, types.Types[types.TUINT8], int64(int8(ir.StringVal(n.X)[ir.Int64Val(n.Index)])))
  3591  			}
  3592  			a := s.expr(n.X)
  3593  			i := s.expr(n.Index)
  3594  			len := s.newValue1(ssaop.OpStringLen, types.Types[types.TINT], a)
  3595  			i = s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded())
  3596  			ptrtyp := s.f.Config.Types.BytePtr
  3597  			ptr := s.newValue1(ssaop.OpStringPtr, ptrtyp, a)
  3598  			if ir.IsConst(n.Index, constant.Int) {
  3599  				ptr = s.newValue1I(ssaop.OpOffPtr, ptrtyp, ir.Int64Val(n.Index), ptr)
  3600  			} else {
  3601  				ptr = s.newValue2(ssaop.OpAddPtr, ptrtyp, ptr, i)
  3602  			}
  3603  			return s.load(types.Types[types.TUINT8], ptr)
  3604  		case n.X.Type().IsSlice():
  3605  			p := s.addr(n)
  3606  			return s.load(n.X.Type().Elem(), p)
  3607  		case n.X.Type().IsArray():
  3608  			if ssa.CanSSA(n.X.Type()) {
  3609  				// SSA can handle arrays of length at most 1.
  3610  				bound := n.X.Type().NumElem()
  3611  				a := s.expr(n.X)
  3612  				i := s.expr(n.Index)
  3613  				len := s.constInt(types.Types[types.TINT], bound)
  3614  				if bound == 0 {
  3615  					// Bounds check will never succeed.
  3616  					s.boundsCheck(i, len, ssa.BoundsIndex, false)
  3617  					// The return value won't be live. In case bounds checks
  3618  					// are turned off, load from (*T)(nil) to cause a segfault.
  3619  					return s.load(n.Type(), s.constNil(n.Type().PtrTo()))
  3620  				}
  3621  				s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded()) // checks i == 0
  3622  				return s.newValue1I(ssaop.OpArraySelect, n.Type(), 0, a)
  3623  			}
  3624  			p := s.addr(n)
  3625  			return s.load(n.X.Type().Elem(), p)
  3626  		default:
  3627  			s.Fatalf("bad type for index %v", n.X.Type())
  3628  			return nil
  3629  		}
  3630  
  3631  	case ir.OLEN, ir.OCAP:
  3632  		n := n.(*ir.UnaryExpr)
  3633  		// Note: all constant cases are handled by the frontend. If len or cap
  3634  		// makes it here, we want the side effects of the argument. See issue 72844.
  3635  		a := s.expr(n.X)
  3636  		t := n.X.Type()
  3637  		switch {
  3638  		case t.IsSlice():
  3639  			op := ssaop.OpSliceLen
  3640  			if n.Op() == ir.OCAP {
  3641  				op = ssaop.OpSliceCap
  3642  			}
  3643  			return s.newValue1(op, types.Types[types.TINT], a)
  3644  		case t.IsString(): // string; not reachable for OCAP
  3645  			return s.newValue1(ssaop.OpStringLen, types.Types[types.TINT], a)
  3646  		case t.IsMap(), t.IsChan():
  3647  			return s.referenceTypeBuiltin(n, a)
  3648  		case t.IsArray():
  3649  			return s.constInt(types.Types[types.TINT], t.NumElem())
  3650  		case t.IsPtr() && t.Elem().IsArray():
  3651  			return s.constInt(types.Types[types.TINT], t.Elem().NumElem())
  3652  		default:
  3653  			s.Fatalf("bad type in len/cap: %v", t)
  3654  			return nil
  3655  		}
  3656  
  3657  	case ir.OSPTR:
  3658  		n := n.(*ir.UnaryExpr)
  3659  		a := s.expr(n.X)
  3660  		if n.X.Type().IsSlice() {
  3661  			if n.Bounded() {
  3662  				return s.newValue1(ssaop.OpSlicePtr, n.Type(), a)
  3663  			}
  3664  			return s.newValue1(ssaop.OpSlicePtrUnchecked, n.Type(), a)
  3665  		} else {
  3666  			return s.newValue1(ssaop.OpStringPtr, n.Type(), a)
  3667  		}
  3668  
  3669  	case ir.OITAB:
  3670  		n := n.(*ir.UnaryExpr)
  3671  		a := s.expr(n.X)
  3672  		return s.newValue1(ssaop.OpITab, n.Type(), a)
  3673  
  3674  	case ir.OIDATA:
  3675  		n := n.(*ir.UnaryExpr)
  3676  		a := s.expr(n.X)
  3677  		return s.newValue1(ssaop.OpIData, n.Type(), a)
  3678  
  3679  	case ir.OMAKEFACE:
  3680  		n := n.(*ir.BinaryExpr)
  3681  		tab := s.expr(n.X)
  3682  		data := s.expr(n.Y)
  3683  		return s.newValue2(ssaop.OpIMake, n.Type(), tab, data)
  3684  
  3685  	case ir.OSLICEHEADER:
  3686  		n := n.(*ir.SliceHeaderExpr)
  3687  		p := s.expr(n.Ptr)
  3688  		l := s.expr(n.Len)
  3689  		c := s.expr(n.Cap)
  3690  		return s.newValue3(ssaop.OpSliceMake, n.Type(), p, l, c)
  3691  
  3692  	case ir.OSTRINGHEADER:
  3693  		n := n.(*ir.StringHeaderExpr)
  3694  		p := s.expr(n.Ptr)
  3695  		l := s.expr(n.Len)
  3696  		return s.newValue2(ssaop.OpStringMake, n.Type(), p, l)
  3697  
  3698  	case ir.OSLICE, ir.OSLICEARR, ir.OSLICE3, ir.OSLICE3ARR:
  3699  		n := n.(*ir.SliceExpr)
  3700  		check := s.checkPtrEnabled && n.Op() == ir.OSLICE3ARR && n.X.Op() == ir.OCONVNOP && n.X.(*ir.ConvExpr).X.Type().IsUnsafePtr()
  3701  		v := s.exprCheckPtr(n.X, !check)
  3702  		var i, j, k *ssa.Value
  3703  		if n.Low != nil {
  3704  			i = s.expr(n.Low)
  3705  		}
  3706  		if n.High != nil {
  3707  			j = s.expr(n.High)
  3708  		}
  3709  		if n.Max != nil {
  3710  			k = s.expr(n.Max)
  3711  		}
  3712  		p, l, c := s.slice(v, i, j, k, n.Bounded())
  3713  		if check {
  3714  			// Emit checkptr instrumentation after bound check to prevent false positive, see #46938.
  3715  			s.checkPtrAlignment(n.X.(*ir.ConvExpr), v, s.conv(n.Max, k, k.Type, types.Types[types.TUINTPTR]))
  3716  		}
  3717  		return s.newValue3(ssaop.OpSliceMake, n.Type(), p, l, c)
  3718  
  3719  	case ir.OSLICESTR:
  3720  		n := n.(*ir.SliceExpr)
  3721  		v := s.expr(n.X)
  3722  		var i, j *ssa.Value
  3723  		if n.Low != nil {
  3724  			i = s.expr(n.Low)
  3725  		}
  3726  		if n.High != nil {
  3727  			j = s.expr(n.High)
  3728  		}
  3729  		p, l, _ := s.slice(v, i, j, nil, n.Bounded())
  3730  		return s.newValue2(ssaop.OpStringMake, n.Type(), p, l)
  3731  
  3732  	case ir.OSLICE2ARRPTR:
  3733  		// if arrlen > slice.len {
  3734  		//   panic(...)
  3735  		// }
  3736  		// slice.ptr
  3737  		n := n.(*ir.ConvExpr)
  3738  		v := s.expr(n.X)
  3739  		nelem := n.Type().Elem().NumElem()
  3740  		arrlen := s.constInt(types.Types[types.TINT], nelem)
  3741  		cap := s.newValue1(ssaop.OpSliceLen, types.Types[types.TINT], v)
  3742  		s.boundsCheck(arrlen, cap, ssa.BoundsConvert, false)
  3743  		op := ssaop.OpSlicePtr
  3744  		if nelem == 0 {
  3745  			op = ssaop.OpSlicePtrUnchecked
  3746  		}
  3747  		return s.newValue1(op, n.Type(), v)
  3748  
  3749  	case ir.OCALLFUNC:
  3750  		n := n.(*ir.CallExpr)
  3751  		if ir.IsIntrinsicCall(n) {
  3752  			return s.intrinsicCall(n)
  3753  		}
  3754  		fallthrough
  3755  
  3756  	case ir.OCALLINTER:
  3757  		n := n.(*ir.CallExpr)
  3758  		return s.callResult(n, callNormal)
  3759  
  3760  	case ir.OGETG:
  3761  		n := n.(*ir.CallExpr)
  3762  		return s.newValue1(ssaop.OpGetG, n.Type(), s.mem())
  3763  
  3764  	case ir.OGETCALLERSP:
  3765  		n := n.(*ir.CallExpr)
  3766  		return s.newValue1(ssaop.OpGetCallerSP, n.Type(), s.mem())
  3767  
  3768  	case ir.OAPPEND:
  3769  		return s.append(n.(*ir.CallExpr), false)
  3770  
  3771  	case ir.OMOVE2HEAP:
  3772  		return s.move2heap(n.(*ir.MoveToHeapExpr))
  3773  
  3774  	case ir.OMIN, ir.OMAX:
  3775  		return s.minMax(n.(*ir.CallExpr))
  3776  
  3777  	case ir.OSTRUCTLIT, ir.OARRAYLIT:
  3778  		// All literals with nonzero fields have already been
  3779  		// rewritten during walk. Any that remain are just T{}
  3780  		// or equivalents. Use the zero value.
  3781  		n := n.(*ir.CompLitExpr)
  3782  		if !ir.IsZero(n) {
  3783  			s.Fatalf("literal with nonzero value in SSA: %v", n)
  3784  		}
  3785  		return s.zeroVal(n.Type())
  3786  
  3787  	case ir.ONEW:
  3788  		n := n.(*ir.UnaryExpr)
  3789  		if x, ok := n.X.(*ir.DynamicType); ok && x.Op() == ir.ODYNAMICTYPE {
  3790  			return s.newObjectNonSpecialized(n.Type().Elem(), s.expr(x.RType))
  3791  		}
  3792  		return s.newObject(n.Type().Elem())
  3793  
  3794  	case ir.OUNSAFEADD:
  3795  		n := n.(*ir.BinaryExpr)
  3796  		ptr := s.expr(n.X)
  3797  		len := s.expr(n.Y)
  3798  
  3799  		// Force len to uintptr to prevent misuse of garbage bits in the
  3800  		// upper part of the register (#48536).
  3801  		len = s.conv(n, len, len.Type, types.Types[types.TUINTPTR])
  3802  
  3803  		return s.newValue2(ssaop.OpAddPtr, n.Type(), ptr, len)
  3804  
  3805  	default:
  3806  		s.Fatalf("unhandled expr %v", n.Op())
  3807  		return nil
  3808  	}
  3809  }
  3810  
  3811  func (s *state) resultOfCall(c *ssa.Value, which int64, t *types.Type) *ssa.Value {
  3812  	aux := c.Aux.(*ssa.AuxCall)
  3813  	pa := aux.ParamAssignmentForResult(which)
  3814  	// TODO(register args) determine if in-memory TypeOK is better loaded early from SelectNAddr or later when SelectN is expanded.
  3815  	// SelectN is better for pattern-matching and possible call-aware analysis we might want to do in the future.
  3816  	if len(pa.Registers) == 0 && !ssa.CanSSA(t) {
  3817  		addr := s.newValue1I(ssaop.OpSelectNAddr, types.NewPtr(t), which, c)
  3818  		return s.rawLoad(t, addr)
  3819  	}
  3820  	return s.newValue1I(ssaop.OpSelectN, t, which, c)
  3821  }
  3822  
  3823  func (s *state) resultAddrOfCall(c *ssa.Value, which int64, t *types.Type) *ssa.Value {
  3824  	aux := c.Aux.(*ssa.AuxCall)
  3825  	pa := aux.ParamAssignmentForResult(which)
  3826  	if len(pa.Registers) == 0 {
  3827  		return s.newValue1I(ssaop.OpSelectNAddr, types.NewPtr(t), which, c)
  3828  	}
  3829  	_, addr := s.temp(c.Pos, t)
  3830  	rval := s.newValue1I(ssaop.OpSelectN, t, which, c)
  3831  	s.vars[memVar] = s.newValue3Apos(ssaop.OpStore, types.TypeMem, t, addr, rval, s.mem(), false)
  3832  	return addr
  3833  }
  3834  
  3835  // Get backing store information for an append call.
  3836  func (s *state) getBackingStoreInfoForAppend(n *ir.CallExpr) *backingStoreInfo {
  3837  	if n.Esc() != ir.EscNone {
  3838  		return nil
  3839  	}
  3840  	return s.getBackingStoreInfo(n.Args[0])
  3841  }
  3842  func (s *state) getBackingStoreInfo(n ir.Node) *backingStoreInfo {
  3843  	t := n.Type()
  3844  	et := t.Elem()
  3845  	maxStackSize := int64(base.Debug.VariableMakeThreshold)
  3846  	if et.Size() == 0 || et.Size() > maxStackSize {
  3847  		return nil
  3848  	}
  3849  	if base.Flag.N != 0 {
  3850  		return nil
  3851  	}
  3852  	if !base.VariableMakeHash.MatchPos(n.Pos(), nil) {
  3853  		return nil
  3854  	}
  3855  	i := s.backingStores[n]
  3856  	if i != nil {
  3857  		return i
  3858  	}
  3859  
  3860  	// Build type of backing store.
  3861  	K := maxStackSize / et.Size() // rounds down
  3862  	KT := types.NewArray(et, K)
  3863  	KT.SetNoalg(true)
  3864  	types.CalcArraySize(KT)
  3865  	// Align more than naturally for the type KT. See issue 73199.
  3866  	align := types.NewArray(types.Types[types.TUINTPTR], 0)
  3867  	types.CalcArraySize(align)
  3868  	storeTyp := types.NewStruct([]*types.Field{
  3869  		{Sym: types.BlankSym, Type: align},
  3870  		{Sym: types.BlankSym, Type: KT},
  3871  	})
  3872  	storeTyp.SetNoalg(true)
  3873  	types.CalcStructSize(storeTyp)
  3874  
  3875  	// Make backing store variable.
  3876  	backingStore := typecheck.TempAt(n.Pos(), s.curfn, storeTyp)
  3877  	backingStore.SetAddrtaken(true)
  3878  
  3879  	// Make "used" boolean.
  3880  	used := typecheck.TempAt(n.Pos(), s.curfn, types.Types[types.TBOOL])
  3881  	if s.curBlock == s.f.Entry {
  3882  		s.vars[used] = s.constBool(false)
  3883  	} else {
  3884  		// initialize this variable at end of entry block
  3885  		s.defvars[s.f.Entry.ID][used] = s.constBool(false)
  3886  	}
  3887  
  3888  	// Initialize an info structure.
  3889  	if s.backingStores == nil {
  3890  		s.backingStores = map[ir.Node]*backingStoreInfo{}
  3891  	}
  3892  	i = &backingStoreInfo{K: K, store: backingStore, used: used, usedStatic: false}
  3893  	s.backingStores[n] = i
  3894  	return i
  3895  }
  3896  
  3897  // append converts an OAPPEND node to SSA.
  3898  // If inplace is false, it converts the OAPPEND expression n to an ssa.Value,
  3899  // adds it to s, and returns the Value.
  3900  // If inplace is true, it writes the result of the OAPPEND expression n
  3901  // back to the slice being appended to, and returns nil.
  3902  // inplace MUST be set to false if the slice can be SSA'd.
  3903  // Note: this code only handles fixed-count appends. Dotdotdot appends
  3904  // have already been rewritten at this point (by walk).
  3905  func (s *state) append(n *ir.CallExpr, inplace bool) *ssa.Value {
  3906  	// If inplace is false, process as expression "append(s, e1, e2, e3)":
  3907  	//
  3908  	// ptr, len, cap := s
  3909  	// len += 3
  3910  	// if uint(len) > uint(cap) {
  3911  	//     ptr, len, cap = growslice(ptr, len, cap, 3, typ)
  3912  	//     Note that len is unmodified by growslice.
  3913  	// }
  3914  	// // with write barriers, if needed:
  3915  	// *(ptr+(len-3)) = e1
  3916  	// *(ptr+(len-2)) = e2
  3917  	// *(ptr+(len-1)) = e3
  3918  	// return makeslice(ptr, len, cap)
  3919  	//
  3920  	//
  3921  	// If inplace is true, process as statement "s = append(s, e1, e2, e3)":
  3922  	//
  3923  	// a := &s
  3924  	// ptr, len, cap := s
  3925  	// len += 3
  3926  	// if uint(len) > uint(cap) {
  3927  	//    ptr, len, cap = growslice(ptr, len, cap, 3, typ)
  3928  	//    vardef(a)    // if necessary, advise liveness we are writing a new a
  3929  	//    *a.cap = cap // write before ptr to avoid a spill
  3930  	//    *a.ptr = ptr // with write barrier
  3931  	// }
  3932  	// *a.len = len
  3933  	// // with write barriers, if needed:
  3934  	// *(ptr+(len-3)) = e1
  3935  	// *(ptr+(len-2)) = e2
  3936  	// *(ptr+(len-1)) = e3
  3937  
  3938  	et := n.Type().Elem()
  3939  	pt := types.NewPtr(et)
  3940  
  3941  	// Evaluate slice
  3942  	sn := n.Args[0] // the slice node is the first in the list
  3943  	var slice, addr *ssa.Value
  3944  	if inplace {
  3945  		addr = s.addr(sn)
  3946  		slice = s.load(n.Type(), addr)
  3947  	} else {
  3948  		slice = s.expr(sn)
  3949  	}
  3950  
  3951  	// Allocate new blocks
  3952  	grow := s.f.NewBlock(block.BlockPlain)
  3953  	assign := s.f.NewBlock(block.BlockPlain)
  3954  
  3955  	// Decomposse input slice.
  3956  	p := s.newValue1(ssaop.OpSlicePtr, pt, slice)
  3957  	l := s.newValue1(ssaop.OpSliceLen, types.Types[types.TINT], slice)
  3958  	c := s.newValue1(ssaop.OpSliceCap, types.Types[types.TINT], slice)
  3959  
  3960  	// Add number of new elements to length.
  3961  	nargs := s.constInt(types.Types[types.TINT], int64(len(n.Args)-1))
  3962  	oldLen := l
  3963  	l = s.newValue2(s.ssaOp(ir.OADD, types.Types[types.TINT]), types.Types[types.TINT], l, nargs)
  3964  
  3965  	// Decide if we need to grow
  3966  	cmp := s.newValue2(s.ssaOp(ir.OLT, types.Types[types.TUINT]), types.Types[types.TBOOL], c, l)
  3967  
  3968  	// Record values of ptr/len/cap before branch.
  3969  	s.vars[ptrVar] = p
  3970  	s.vars[lenVar] = l
  3971  	if !inplace {
  3972  		s.vars[capVar] = c
  3973  	}
  3974  
  3975  	b := s.endBlock()
  3976  	b.Kind = block.BlockIf
  3977  	b.Likely = ssa.BranchUnlikely
  3978  	b.SetControl(cmp)
  3979  	b.AddEdgeTo(grow)
  3980  	b.AddEdgeTo(assign)
  3981  
  3982  	// If the result of the append does not escape, we can use
  3983  	// a stack-allocated backing store if len is small enough.
  3984  	// A stack-allocated backing store could be used at every
  3985  	// append that qualifies, but we limit it in some cases to
  3986  	// avoid wasted code and stack space.
  3987  	//
  3988  	// Note that we have two different strategies.
  3989  	// 1. The standard strategy is just to allocate the full
  3990  	//    backing store at the first append.
  3991  	// 2. An alternate strategy is used when
  3992  	//        a. The backing store eventually escapes via move2heap
  3993  	//    and b. The capacity is used somehow
  3994  	//    In this case, we don't want to just allocate
  3995  	//    the full buffer at the first append, because when
  3996  	//    we move2heap the buffer to the heap when it escapes,
  3997  	//    we might end up wasting memory because we can't
  3998  	//    change the capacity.
  3999  	//    So in this case we use growsliceBuf to reuse the buffer
  4000  	//    and walk one step up the size class ladder each time.
  4001  	//
  4002  	// TODO: handle ... append case? Currently we handle only
  4003  	// a fixed number of appended elements.
  4004  	var info *backingStoreInfo
  4005  	if !inplace {
  4006  		info = s.getBackingStoreInfoForAppend(n)
  4007  	}
  4008  
  4009  	if !inplace && info != nil && !n.UseBuf && !info.usedStatic {
  4010  		// if l <= K {
  4011  		//   if !used {
  4012  		//     if oldLen == 0 {
  4013  		//       var store [K]T
  4014  		//       s = store[:l:K]
  4015  		//       used = true
  4016  		//     }
  4017  		//   }
  4018  		// }
  4019  		// ... if we didn't use the stack backing store, call growslice ...
  4020  		//
  4021  		// oldLen==0 is not strictly necessary, but requiring it means
  4022  		// we don't have to worry about copying existing elements.
  4023  		// Allowing oldLen>0 would add complication. Worth it? I would guess not.
  4024  		//
  4025  		// TODO: instead of the used boolean, we could insist that this only applies
  4026  		// to monotonic slices, those which once they have >0 entries never go back
  4027  		// to 0 entries. Then oldLen==0 is enough.
  4028  		//
  4029  		// We also do this for append(x, ...) once for every x.
  4030  		// It is ok to do it more often, but it is probably helpful only for
  4031  		// the first instance. TODO: this could use more tuning. Using ir.Node
  4032  		// as the key works for *ir.Name instances but probably nothing else.
  4033  		info.usedStatic = true
  4034  		// TODO: unset usedStatic somehow?
  4035  
  4036  		usedTestBlock := s.f.NewBlock(block.BlockPlain)
  4037  		oldLenTestBlock := s.f.NewBlock(block.BlockPlain)
  4038  		bodyBlock := s.f.NewBlock(block.BlockPlain)
  4039  		growSlice := s.f.NewBlock(block.BlockPlain)
  4040  		tInt := types.Types[types.TINT]
  4041  		tBool := types.Types[types.TBOOL]
  4042  
  4043  		// if l <= K
  4044  		s.startBlock(grow)
  4045  		kTest := s.newValue2(s.ssaOp(ir.OLE, tInt), tBool, l, s.constInt(tInt, info.K))
  4046  		b := s.endBlock()
  4047  		b.Kind = block.BlockIf
  4048  		b.SetControl(kTest)
  4049  		b.AddEdgeTo(usedTestBlock)
  4050  		b.AddEdgeTo(growSlice)
  4051  		b.Likely = ssa.BranchLikely
  4052  
  4053  		// if !used
  4054  		s.startBlock(usedTestBlock)
  4055  		usedTest := s.newValue1(ssaop.OpNot, tBool, s.expr(info.used))
  4056  		b = s.endBlock()
  4057  		b.Kind = block.BlockIf
  4058  		b.SetControl(usedTest)
  4059  		b.AddEdgeTo(oldLenTestBlock)
  4060  		b.AddEdgeTo(growSlice)
  4061  		b.Likely = ssa.BranchLikely
  4062  
  4063  		// if oldLen == 0
  4064  		s.startBlock(oldLenTestBlock)
  4065  		oldLenTest := s.newValue2(s.ssaOp(ir.OEQ, tInt), tBool, oldLen, s.constInt(tInt, 0))
  4066  		b = s.endBlock()
  4067  		b.Kind = block.BlockIf
  4068  		b.SetControl(oldLenTest)
  4069  		b.AddEdgeTo(bodyBlock)
  4070  		b.AddEdgeTo(growSlice)
  4071  		b.Likely = ssa.BranchLikely
  4072  
  4073  		// var store struct { _ [0]uintptr; arr [K]T }
  4074  		s.startBlock(bodyBlock)
  4075  		if et.HasPointers() {
  4076  			s.vars[memVar] = s.newValue1A(ssaop.OpVarDef, types.TypeMem, info.store, s.mem())
  4077  		}
  4078  		addr := s.addr(info.store)
  4079  		s.zero(info.store.Type(), addr)
  4080  
  4081  		// s = store.arr[:l:K]
  4082  		s.vars[ptrVar] = addr
  4083  		s.vars[lenVar] = l // nargs would also be ok because of the oldLen==0 test.
  4084  		s.vars[capVar] = s.constInt(tInt, info.K)
  4085  
  4086  		// used = true
  4087  		s.assign(info.used, s.constBool(true), false, 0)
  4088  		b = s.endBlock()
  4089  		b.AddEdgeTo(assign)
  4090  
  4091  		// New block to use for growslice call.
  4092  		grow = growSlice
  4093  	}
  4094  
  4095  	// Call growslice
  4096  	s.startBlock(grow)
  4097  	taddr := s.expr(n.Fun)
  4098  	var r []*ssa.Value
  4099  	if info != nil && n.UseBuf {
  4100  		// Use stack-allocated buffer as backing store, if we can.
  4101  		if et.HasPointers() && !info.usedStatic {
  4102  			// Initialize in the function header. Not the best place,
  4103  			// but it makes sure we don't scan this area before it is
  4104  			// initialized.
  4105  			mem := s.defvars[s.f.Entry.ID][memVar]
  4106  			mem = s.f.Entry.NewValue1A(n.Pos(), ssaop.OpVarDef, types.TypeMem, info.store, mem)
  4107  			addr := s.f.Entry.NewValue2A(n.Pos(), ssaop.OpLocalAddr, types.NewPtr(info.store.Type()), info.store, s.sp, mem)
  4108  			mem = s.f.Entry.NewValue2I(n.Pos(), ssaop.OpZero, types.TypeMem, info.store.Type().Size(), addr, mem)
  4109  			mem.Aux = info.store.Type()
  4110  			s.defvars[s.f.Entry.ID][memVar] = mem
  4111  			info.usedStatic = true
  4112  		}
  4113  		fn := ir.Syms.GrowsliceBuf
  4114  		if goexperiment.RuntimeFreegc && n.AppendNoAlias && !et.HasPointers() {
  4115  			// The append is for a non-aliased slice where the runtime knows how to free
  4116  			// the old logically dead backing store after growth.
  4117  			// TODO(thepudds): for now, we only use the NoAlias version for element types
  4118  			// without pointers while waiting on additional runtime support (CL 698515).
  4119  			fn = ir.Syms.GrowsliceBufNoAlias
  4120  		}
  4121  		r = s.rtcall(fn, true, []*types.Type{n.Type()}, p, l, c, nargs, taddr, s.addr(info.store), s.constInt(types.Types[types.TINT], info.K))
  4122  	} else {
  4123  		fn := ir.Syms.Growslice
  4124  		if goexperiment.RuntimeFreegc && n.AppendNoAlias && !et.HasPointers() {
  4125  			// The append is for a non-aliased slice where the runtime knows how to free
  4126  			// the old logically dead backing store after growth.
  4127  			// TODO(thepudds): for now, we only use the NoAlias version for element types
  4128  			// without pointers while waiting on additional runtime support (CL 698515).
  4129  			fn = ir.Syms.GrowsliceNoAlias
  4130  		}
  4131  		r = s.rtcall(fn, true, []*types.Type{n.Type()}, p, l, c, nargs, taddr)
  4132  	}
  4133  
  4134  	// Decompose output slice
  4135  	p = s.newValue1(ssaop.OpSlicePtr, pt, r[0])
  4136  	l = s.newValue1(ssaop.OpSliceLen, types.Types[types.TINT], r[0])
  4137  	c = s.newValue1(ssaop.OpSliceCap, types.Types[types.TINT], r[0])
  4138  
  4139  	s.vars[ptrVar] = p
  4140  	s.vars[lenVar] = l
  4141  	s.vars[capVar] = c
  4142  	if inplace {
  4143  		if sn.Op() == ir.ONAME {
  4144  			sn := sn.(*ir.Name)
  4145  			if sn.Class != ir.PEXTERN {
  4146  				// Tell liveness we're about to build a new slice
  4147  				s.vars[memVar] = s.newValue1A(ssaop.OpVarDef, types.TypeMem, sn, s.mem())
  4148  			}
  4149  		}
  4150  		capaddr := s.newValue1I(ssaop.OpOffPtr, s.f.Config.Types.IntPtr, types.SliceCapOffset, addr)
  4151  		s.store(types.Types[types.TINT], capaddr, c)
  4152  		s.store(pt, addr, p)
  4153  	}
  4154  
  4155  	b = s.endBlock()
  4156  	b.AddEdgeTo(assign)
  4157  
  4158  	// assign new elements to slots
  4159  	s.startBlock(assign)
  4160  	p = s.variable(ptrVar, pt)                      // generates phi for ptr
  4161  	l = s.variable(lenVar, types.Types[types.TINT]) // generates phi for len
  4162  	if !inplace {
  4163  		c = s.variable(capVar, types.Types[types.TINT]) // generates phi for cap
  4164  	}
  4165  
  4166  	if inplace {
  4167  		// Update length in place.
  4168  		// We have to wait until here to make sure growslice succeeded.
  4169  		lenaddr := s.newValue1I(ssaop.OpOffPtr, s.f.Config.Types.IntPtr, types.SliceLenOffset, addr)
  4170  		s.store(types.Types[types.TINT], lenaddr, l)
  4171  	}
  4172  
  4173  	// Evaluate args
  4174  	type argRec struct {
  4175  		// if store is true, we're appending the value v.  If false, we're appending the
  4176  		// value at *v.
  4177  		v     *ssa.Value
  4178  		store bool
  4179  	}
  4180  	args := make([]argRec, 0, len(n.Args[1:]))
  4181  	for _, n := range n.Args[1:] {
  4182  		if ssa.CanSSA(n.Type()) {
  4183  			args = append(args, argRec{v: s.expr(n), store: true})
  4184  		} else {
  4185  			v := s.addr(n)
  4186  			args = append(args, argRec{v: v})
  4187  		}
  4188  	}
  4189  
  4190  	// Write args into slice.
  4191  	oldLen = s.newValue2(s.ssaOp(ir.OSUB, types.Types[types.TINT]), types.Types[types.TINT], l, nargs)
  4192  	p2 := s.newValue2(ssaop.OpPtrIndex, pt, p, oldLen)
  4193  	for i, arg := range args {
  4194  		addr := s.newValue2(ssaop.OpPtrIndex, pt, p2, s.constInt(types.Types[types.TINT], int64(i)))
  4195  		if arg.store {
  4196  			s.storeType(et, addr, arg.v, 0, true)
  4197  		} else {
  4198  			s.move(et, addr, arg.v)
  4199  		}
  4200  	}
  4201  
  4202  	// The following deletions have no practical effect at this time
  4203  	// because state.vars has been reset by the preceding state.startBlock.
  4204  	// They only enforce the fact that these variables are no longer need in
  4205  	// the current scope.
  4206  	delete(s.vars, ptrVar)
  4207  	delete(s.vars, lenVar)
  4208  	if !inplace {
  4209  		delete(s.vars, capVar)
  4210  	}
  4211  
  4212  	// make result
  4213  	if inplace {
  4214  		return nil
  4215  	}
  4216  	return s.newValue3(ssaop.OpSliceMake, n.Type(), p, l, c)
  4217  }
  4218  
  4219  func (s *state) move2heap(n *ir.MoveToHeapExpr) *ssa.Value {
  4220  	// s := n.Slice
  4221  	// if s.ptr points to current stack frame {
  4222  	//     s2 := make([]T, s.len, s.cap)
  4223  	//     copy(s2[:cap], s[:cap])
  4224  	//     s = s2
  4225  	// }
  4226  	// return s
  4227  
  4228  	slice := s.expr(n.Slice)
  4229  	et := slice.Type.Elem()
  4230  	pt := types.NewPtr(et)
  4231  
  4232  	info := s.getBackingStoreInfo(n)
  4233  	if info == nil {
  4234  		// Backing store will never be stack allocated, so
  4235  		// move2heap is a no-op.
  4236  		return slice
  4237  	}
  4238  
  4239  	// Decomposse input slice.
  4240  	p := s.newValue1(ssaop.OpSlicePtr, pt, slice)
  4241  	l := s.newValue1(ssaop.OpSliceLen, types.Types[types.TINT], slice)
  4242  	c := s.newValue1(ssaop.OpSliceCap, types.Types[types.TINT], slice)
  4243  
  4244  	moveBlock := s.f.NewBlock(block.BlockPlain)
  4245  	mergeBlock := s.f.NewBlock(block.BlockPlain)
  4246  
  4247  	s.vars[ptrVar] = p
  4248  	s.vars[lenVar] = l
  4249  	s.vars[capVar] = c
  4250  
  4251  	// Decide if we need to move the slice backing store.
  4252  	// It needs to be moved if it is currently on the stack.
  4253  	sub := ssaop.OpSub64
  4254  	less := ssaop.OpLess64U
  4255  	if s.config.PtrSize == 4 {
  4256  		sub = ssaop.OpSub32
  4257  		less = ssaop.OpLess32U
  4258  	}
  4259  	callerSP := s.newValue1(ssaop.OpGetCallerSP, types.Types[types.TUINTPTR], s.mem())
  4260  	frameSize := s.newValue2(sub, types.Types[types.TUINTPTR], callerSP, s.sp)
  4261  	pInt := s.newValue2(ssaop.OpConvert, types.Types[types.TUINTPTR], p, s.mem())
  4262  	off := s.newValue2(sub, types.Types[types.TUINTPTR], pInt, s.sp)
  4263  	cond := s.newValue2(less, types.Types[types.TBOOL], off, frameSize)
  4264  
  4265  	b := s.endBlock()
  4266  	b.Kind = block.BlockIf
  4267  	b.Likely = ssa.BranchUnlikely // fast path is to not have to call into runtime
  4268  	b.SetControl(cond)
  4269  	b.AddEdgeTo(moveBlock)
  4270  	b.AddEdgeTo(mergeBlock)
  4271  
  4272  	// Move the slice to heap
  4273  	s.startBlock(moveBlock)
  4274  	var newSlice *ssa.Value
  4275  	if et.HasPointers() {
  4276  		typ := s.expr(n.RType)
  4277  		if n.PreserveCapacity {
  4278  			newSlice = s.rtcall(ir.Syms.MoveSlice, true, []*types.Type{slice.Type}, typ, p, l, c)[0]
  4279  		} else {
  4280  			newSlice = s.rtcall(ir.Syms.MoveSliceNoCap, true, []*types.Type{slice.Type}, typ, p, l)[0]
  4281  		}
  4282  	} else {
  4283  		elemSize := s.constInt(types.Types[types.TUINTPTR], et.Size())
  4284  		if n.PreserveCapacity {
  4285  			newSlice = s.rtcall(ir.Syms.MoveSliceNoScan, true, []*types.Type{slice.Type}, elemSize, p, l, c)[0]
  4286  		} else {
  4287  			newSlice = s.rtcall(ir.Syms.MoveSliceNoCapNoScan, true, []*types.Type{slice.Type}, elemSize, p, l)[0]
  4288  		}
  4289  	}
  4290  	// Decompose output slice
  4291  	s.vars[ptrVar] = s.newValue1(ssaop.OpSlicePtr, pt, newSlice)
  4292  	s.vars[lenVar] = s.newValue1(ssaop.OpSliceLen, types.Types[types.TINT], newSlice)
  4293  	s.vars[capVar] = s.newValue1(ssaop.OpSliceCap, types.Types[types.TINT], newSlice)
  4294  	b = s.endBlock()
  4295  	b.AddEdgeTo(mergeBlock)
  4296  
  4297  	// Merge fast path (no moving) and slow path (moved)
  4298  	s.startBlock(mergeBlock)
  4299  	p = s.variable(ptrVar, pt)                      // generates phi for ptr
  4300  	l = s.variable(lenVar, types.Types[types.TINT]) // generates phi for len
  4301  	c = s.variable(capVar, types.Types[types.TINT]) // generates phi for cap
  4302  	delete(s.vars, ptrVar)
  4303  	delete(s.vars, lenVar)
  4304  	delete(s.vars, capVar)
  4305  	return s.newValue3(ssaop.OpSliceMake, slice.Type, p, l, c)
  4306  }
  4307  
  4308  // minMax converts an OMIN/OMAX builtin call into SSA.
  4309  func (s *state) minMax(n *ir.CallExpr) *ssa.Value {
  4310  	// The OMIN/OMAX builtin is variadic, but its semantics are
  4311  	// equivalent to left-folding a binary min/max operation across the
  4312  	// arguments list.
  4313  	fold := func(op func(x, a *ssa.Value) *ssa.Value) *ssa.Value {
  4314  		x := s.expr(n.Args[0])
  4315  		for _, arg := range n.Args[1:] {
  4316  			x = op(x, s.expr(arg))
  4317  		}
  4318  		return x
  4319  	}
  4320  
  4321  	typ := n.Type()
  4322  
  4323  	if typ.IsFloat() || typ.IsString() {
  4324  		// min/max semantics for floats are tricky because of NaNs and
  4325  		// negative zero. Some architectures have instructions which
  4326  		// we can use to generate the right result. For others we must
  4327  		// call into the runtime instead.
  4328  		//
  4329  		// Strings are conceptually simpler, but we currently desugar
  4330  		// string comparisons during walk, not ssagen.
  4331  
  4332  		if typ.IsFloat() {
  4333  			hasIntrinsic := false
  4334  			switch Arch.LinkArch.Family {
  4335  			case sys.AMD64, sys.ARM64, sys.Loong64, sys.RISCV64, sys.Wasm:
  4336  				hasIntrinsic = true
  4337  			case sys.PPC64:
  4338  				hasIntrinsic = buildcfg.GOPPC64 >= 9
  4339  			case sys.S390X:
  4340  				// FIXME: add check once GOS390X exists
  4341  			}
  4342  
  4343  			if hasIntrinsic {
  4344  				var op ssaop.Op
  4345  				switch {
  4346  				case typ.Kind() == types.TFLOAT64 && n.Op() == ir.OMIN:
  4347  					op = ssaop.OpMin64F
  4348  				case typ.Kind() == types.TFLOAT64 && n.Op() == ir.OMAX:
  4349  					op = ssaop.OpMax64F
  4350  				case typ.Kind() == types.TFLOAT32 && n.Op() == ir.OMIN:
  4351  					op = ssaop.OpMin32F
  4352  				case typ.Kind() == types.TFLOAT32 && n.Op() == ir.OMAX:
  4353  					op = ssaop.OpMax32F
  4354  				}
  4355  				return fold(func(x, a *ssa.Value) *ssa.Value {
  4356  					return s.newValue2(op, typ, x, a)
  4357  				})
  4358  			}
  4359  		}
  4360  		var name string
  4361  		switch typ.Kind() {
  4362  		case types.TFLOAT32:
  4363  			switch n.Op() {
  4364  			case ir.OMIN:
  4365  				name = "fmin32"
  4366  			case ir.OMAX:
  4367  				name = "fmax32"
  4368  			}
  4369  		case types.TFLOAT64:
  4370  			switch n.Op() {
  4371  			case ir.OMIN:
  4372  				name = "fmin64"
  4373  			case ir.OMAX:
  4374  				name = "fmax64"
  4375  			}
  4376  		case types.TSTRING:
  4377  			switch n.Op() {
  4378  			case ir.OMIN:
  4379  				name = "strmin"
  4380  			case ir.OMAX:
  4381  				name = "strmax"
  4382  			}
  4383  		}
  4384  		fn := typecheck.LookupRuntimeFunc(name)
  4385  
  4386  		return fold(func(x, a *ssa.Value) *ssa.Value {
  4387  			return s.rtcall(fn, true, []*types.Type{typ}, x, a)[0]
  4388  		})
  4389  	}
  4390  
  4391  	if typ.IsInteger() {
  4392  		if Arch.LinkArch.Family == sys.RISCV64 && buildcfg.GORISCV64 >= 22 && typ.Size() == 8 {
  4393  			var op ssaop.Op
  4394  			switch {
  4395  			case typ.IsSigned() && n.Op() == ir.OMIN:
  4396  				op = ssaop.OpMin64
  4397  			case typ.IsSigned() && n.Op() == ir.OMAX:
  4398  				op = ssaop.OpMax64
  4399  			case typ.IsUnsigned() && n.Op() == ir.OMIN:
  4400  				op = ssaop.OpMin64u
  4401  			case typ.IsUnsigned() && n.Op() == ir.OMAX:
  4402  				op = ssaop.OpMax64u
  4403  			}
  4404  			return fold(func(x, a *ssa.Value) *ssa.Value {
  4405  				return s.newValue2(op, typ, x, a)
  4406  			})
  4407  		}
  4408  	}
  4409  
  4410  	lt := s.ssaOp(ir.OLT, typ)
  4411  
  4412  	return fold(func(x, a *ssa.Value) *ssa.Value {
  4413  		switch n.Op() {
  4414  		case ir.OMIN:
  4415  			// a < x ? a : x
  4416  			return s.ternary(s.newValue2(lt, types.Types[types.TBOOL], a, x), a, x)
  4417  		case ir.OMAX:
  4418  			// x < a ? a : x
  4419  			return s.ternary(s.newValue2(lt, types.Types[types.TBOOL], x, a), a, x)
  4420  		}
  4421  		panic("unreachable")
  4422  	})
  4423  }
  4424  
  4425  // ternary emits code to evaluate cond ? x : y.
  4426  func (s *state) ternary(cond, x, y *ssa.Value) *ssa.Value {
  4427  	// Note that we need a new ternaryVar each time (unlike okVar where we can
  4428  	// reuse the variable) because it might have a different type every time.
  4429  	ternaryVar := ssaMarker("ternary")
  4430  
  4431  	bThen := s.f.NewBlock(block.BlockPlain)
  4432  	bElse := s.f.NewBlock(block.BlockPlain)
  4433  	bEnd := s.f.NewBlock(block.BlockPlain)
  4434  
  4435  	b := s.endBlock()
  4436  	b.Kind = block.BlockIf
  4437  	b.SetControl(cond)
  4438  	b.AddEdgeTo(bThen)
  4439  	b.AddEdgeTo(bElse)
  4440  
  4441  	s.startBlock(bThen)
  4442  	s.vars[ternaryVar] = x
  4443  	s.endBlock().AddEdgeTo(bEnd)
  4444  
  4445  	s.startBlock(bElse)
  4446  	s.vars[ternaryVar] = y
  4447  	s.endBlock().AddEdgeTo(bEnd)
  4448  
  4449  	s.startBlock(bEnd)
  4450  	r := s.variable(ternaryVar, x.Type)
  4451  	delete(s.vars, ternaryVar)
  4452  	return r
  4453  }
  4454  
  4455  // condBranch evaluates the boolean expression cond and branches to yes
  4456  // if cond is true and no if cond is false.
  4457  // This function is intended to handle && and || better than just calling
  4458  // s.expr(cond) and branching on the result.
  4459  func (s *state) condBranch(cond ir.Node, yes, no *ssa.Block, likely int8) {
  4460  	switch cond.Op() {
  4461  	case ir.OANDAND:
  4462  		cond := cond.(*ir.LogicalExpr)
  4463  		mid := s.f.NewBlock(block.BlockPlain)
  4464  		s.stmtList(cond.Init())
  4465  		s.condBranch(cond.X, mid, no, max(likely, 0))
  4466  		s.startBlock(mid)
  4467  		s.condBranch(cond.Y, yes, no, likely)
  4468  		return
  4469  		// Note: if likely==1, then both recursive calls pass 1.
  4470  		// If likely==-1, then we don't have enough information to decide
  4471  		// whether the first branch is likely or not. So we pass 0 for
  4472  		// the likeliness of the first branch.
  4473  		// TODO: have the frontend give us branch prediction hints for
  4474  		// OANDAND and OOROR nodes (if it ever has such info).
  4475  	case ir.OOROR:
  4476  		cond := cond.(*ir.LogicalExpr)
  4477  		mid := s.f.NewBlock(block.BlockPlain)
  4478  		s.stmtList(cond.Init())
  4479  		s.condBranch(cond.X, yes, mid, min(likely, 0))
  4480  		s.startBlock(mid)
  4481  		s.condBranch(cond.Y, yes, no, likely)
  4482  		return
  4483  		// Note: if likely==-1, then both recursive calls pass -1.
  4484  		// If likely==1, then we don't have enough info to decide
  4485  		// the likelihood of the first branch.
  4486  	case ir.ONOT:
  4487  		cond := cond.(*ir.UnaryExpr)
  4488  		s.stmtList(cond.Init())
  4489  		s.condBranch(cond.X, no, yes, -likely)
  4490  		return
  4491  	case ir.OCONVNOP:
  4492  		cond := cond.(*ir.ConvExpr)
  4493  		s.stmtList(cond.Init())
  4494  		s.condBranch(cond.X, yes, no, likely)
  4495  		return
  4496  	}
  4497  	c := s.expr(cond)
  4498  	b := s.endBlock()
  4499  	b.Kind = block.BlockIf
  4500  	b.SetControl(c)
  4501  	b.Likely = ssa.BranchPrediction(likely) // gc and ssa both use -1/0/+1 for likeliness
  4502  	b.AddEdgeTo(yes)
  4503  	b.AddEdgeTo(no)
  4504  }
  4505  
  4506  type skipMask uint8
  4507  
  4508  const (
  4509  	skipPtr skipMask = 1 << iota
  4510  	skipLen
  4511  	skipCap
  4512  )
  4513  
  4514  // assign does left = right.
  4515  // Right has already been evaluated to ssa, left has not.
  4516  // If deref is true, then we do left = *right instead (and right has already been nil-checked).
  4517  // If deref is true and right == nil, just do left = 0.
  4518  // skip indicates assignments (at the top level) that can be avoided.
  4519  // mayOverlap indicates whether left&right might partially overlap in memory. Default is false.
  4520  func (s *state) assign(left ir.Node, right *ssa.Value, deref bool, skip skipMask) {
  4521  	s.assignWhichMayOverlap(left, right, deref, skip, false)
  4522  }
  4523  func (s *state) assignWhichMayOverlap(left ir.Node, right *ssa.Value, deref bool, skip skipMask, mayOverlap bool) {
  4524  	if left.Op() == ir.ONAME && ir.IsBlank(left) {
  4525  		return
  4526  	}
  4527  	t := left.Type()
  4528  	types.CalcSize(t)
  4529  	if s.canSSA(left) {
  4530  		if deref {
  4531  			s.Fatalf("can SSA LHS %v but not RHS %s", left, right)
  4532  		}
  4533  		if left.Op() == ir.ODOT {
  4534  			// We're assigning to a field of an ssa-able value.
  4535  			// We need to build a new structure with the new value for the
  4536  			// field we're assigning and the old values for the other fields.
  4537  			// For instance:
  4538  			//   type T struct {a, b, c int}
  4539  			//   var T x
  4540  			//   x.b = 5
  4541  			// For the x.b = 5 assignment we want to generate x = T{x.a, 5, x.c}
  4542  
  4543  			// Grab information about the structure type.
  4544  			left := left.(*ir.SelectorExpr)
  4545  			t := left.X.Type()
  4546  			nf := t.NumFields()
  4547  			idx := fieldIdx(left)
  4548  
  4549  			// Grab old value of structure.
  4550  			old := s.expr(left.X)
  4551  
  4552  			if left.Type().Size() == 0 {
  4553  				// Nothing to do when assigning zero-sized things.
  4554  				return
  4555  			}
  4556  
  4557  			// Make new structure.
  4558  			new := s.newValue0(ssaop.OpStructMake, t)
  4559  
  4560  			// Add fields as args.
  4561  			for i := 0; i < nf; i++ {
  4562  				if i == idx {
  4563  					new.AddArg(right)
  4564  				} else {
  4565  					new.AddArg(s.newValue1I(ssaop.OpStructSelect, t.FieldType(i), int64(i), old))
  4566  				}
  4567  			}
  4568  
  4569  			// Recursively assign the new value we've made to the base of the dot op.
  4570  			s.assign(left.X, new, false, 0)
  4571  			// TODO: do we need to update named values here?
  4572  			return
  4573  		}
  4574  		if left.Op() == ir.OINDEX && left.(*ir.IndexExpr).X.Type().IsArray() {
  4575  			left := left.(*ir.IndexExpr)
  4576  			s.pushLine(left.Pos())
  4577  			defer s.popLine()
  4578  			// We're assigning to an element of an ssa-able array.
  4579  			// a[i] = v
  4580  			t := left.X.Type()
  4581  			n := t.NumElem()
  4582  
  4583  			i := s.expr(left.Index) // index
  4584  			if n == 0 {
  4585  				_ = s.expr(left.X) // Evaluating left.X for any side-effects.
  4586  				// The bounds check must fail.  Might as well
  4587  				// ignore the actual index and just use zeros.
  4588  				z := s.constInt(types.Types[types.TINT], 0)
  4589  				s.boundsCheck(z, z, ssa.BoundsIndex, false)
  4590  				return
  4591  			}
  4592  			if t.Size() == 0 {
  4593  				_ = s.expr(left.X) // Evaluating left.X for any side-effects.
  4594  				// Generate bounds check for left, since this can happen
  4595  				// for 0-size assignment case, see issue #79236.
  4596  				len := s.constInt(types.Types[types.TINT], n)
  4597  				s.boundsCheck(i, len, ssa.BoundsIndex, false)
  4598  				return
  4599  			}
  4600  			if n != 1 {
  4601  				// This can happen in weird, always-panics cases, like:
  4602  				//     var x [0][2]int
  4603  				//     x[i][j] = 5
  4604  				// We know it always panics because the LHS is ssa-able,
  4605  				// and arrays of length > 1 can't be ssa-able unless
  4606  				// they are somewhere inside an outer [0].
  4607  				// We can ignore the actual assignment, it is dynamically
  4608  				// unreachable. See issue 77635.
  4609  				// Still, evaluating left.X for any side-effects.
  4610  				_ = s.expr(left.X)
  4611  				return
  4612  			}
  4613  
  4614  			// Rewrite to a = [1]{v}
  4615  			len := s.constInt(types.Types[types.TINT], 1)
  4616  			s.boundsCheck(i, len, ssa.BoundsIndex, false) // checks i == 0
  4617  			v := s.newValue1(ssaop.OpArrayMake1, t, right)
  4618  			s.assign(left.X, v, false, 0)
  4619  			return
  4620  		}
  4621  		left := left.(*ir.Name)
  4622  		// Update variable assignment.
  4623  		s.vars[left] = right
  4624  		s.addNamedValue(left, right)
  4625  		return
  4626  	}
  4627  
  4628  	// If this assignment clobbers an entire local variable, then emit
  4629  	// OpVarDef so liveness analysis knows the variable is redefined.
  4630  	if base, ok := clobberBase(left).(*ir.Name); ok && base.OnStack() && skip == 0 && (t.HasPointers() || ssa.IsMergeCandidate(base)) {
  4631  		s.vars[memVar] = s.newValue1Apos(ssaop.OpVarDef, types.TypeMem, base, s.mem(), !ir.IsAutoTmp(base))
  4632  	}
  4633  
  4634  	// Left is not ssa-able. Compute its address.
  4635  	addr := s.addr(left)
  4636  	if ir.IsReflectHeaderDataField(left) {
  4637  		// Package unsafe's documentation says storing pointers into
  4638  		// reflect.SliceHeader and reflect.StringHeader's Data fields
  4639  		// is valid, even though they have type uintptr (#19168).
  4640  		// Mark it pointer type to signal the writebarrier pass to
  4641  		// insert a write barrier.
  4642  		t = types.Types[types.TUNSAFEPTR]
  4643  	}
  4644  	if deref {
  4645  		// Treat as a mem->mem move.
  4646  		if right == nil {
  4647  			s.zero(t, addr)
  4648  		} else {
  4649  			s.moveWhichMayOverlap(t, addr, right, mayOverlap)
  4650  		}
  4651  		return
  4652  	}
  4653  	// Treat as a store.
  4654  	s.storeType(t, addr, right, skip, !ir.IsAutoTmp(left))
  4655  }
  4656  
  4657  // zeroVal returns the zero value for type t.
  4658  func (s *state) zeroVal(t *types.Type) *ssa.Value {
  4659  	if t.Size() == 0 {
  4660  		return s.entryNewValue0(ssaop.OpEmpty, t)
  4661  	}
  4662  	b := s.entryBlock()
  4663  	if t.ContainsSIMD() {
  4664  		// SIMD code needs to be guarded by feature checks, so
  4665  		// we can't put its zero value in the entry block.
  4666  		b = s.curBlock
  4667  	}
  4668  	switch {
  4669  	case t.IsInteger():
  4670  		switch t.Size() {
  4671  		case 1:
  4672  			return s.constInt8(t, 0)
  4673  		case 2:
  4674  			return s.constInt16(t, 0)
  4675  		case 4:
  4676  			return s.constInt32(t, 0)
  4677  		case 8:
  4678  			return s.constInt64(t, 0)
  4679  		default:
  4680  			s.Fatalf("bad sized integer type %v", t)
  4681  		}
  4682  	case t.IsFloat():
  4683  		switch t.Size() {
  4684  		case 4:
  4685  			return s.constFloat32(t, 0)
  4686  		case 8:
  4687  			return s.constFloat64(t, 0)
  4688  		default:
  4689  			s.Fatalf("bad sized float type %v", t)
  4690  		}
  4691  	case t.IsComplex():
  4692  		switch t.Size() {
  4693  		case 8:
  4694  			z := s.constFloat32(types.Types[types.TFLOAT32], 0)
  4695  			return s.entryNewValue2(ssaop.OpComplexMake, t, z, z)
  4696  		case 16:
  4697  			z := s.constFloat64(types.Types[types.TFLOAT64], 0)
  4698  			return s.entryNewValue2(ssaop.OpComplexMake, t, z, z)
  4699  		default:
  4700  			s.Fatalf("bad sized complex type %v", t)
  4701  		}
  4702  
  4703  	case t.IsString():
  4704  		return s.constEmptyString(t)
  4705  	case t.IsPtrShaped():
  4706  		return s.constNil(t)
  4707  	case t.IsBoolean():
  4708  		return s.constBool(false)
  4709  	case t.IsInterface():
  4710  		return s.constInterface(t)
  4711  	case t.IsSlice():
  4712  		return s.constSlice(t)
  4713  	case isStructNotSIMD(t):
  4714  		n := t.NumFields()
  4715  		v := b.NewValue0(src.NoXPos, ssaop.OpStructMake, t)
  4716  		for i := 0; i < n; i++ {
  4717  			v.AddArg(s.zeroVal(t.FieldType(i)))
  4718  		}
  4719  		return v
  4720  	case t.IsArray() && t.NumElem() == 1:
  4721  		return b.NewValue1(src.NoXPos, ssaop.OpArrayMake1, t, s.zeroVal(t.Elem()))
  4722  	case t.IsSIMD():
  4723  		return b.NewValue0(src.NoXPos, ssaop.OpZeroSIMD, t)
  4724  	}
  4725  	s.Fatalf("zero for type %v not implemented", t)
  4726  	return nil
  4727  }
  4728  
  4729  type callKind int8
  4730  
  4731  const (
  4732  	callNormal callKind = iota
  4733  	callDefer
  4734  	callDeferStack
  4735  	callGo
  4736  	callTail
  4737  )
  4738  
  4739  type sfRtCallDef struct {
  4740  	rtfn  *obj.LSym
  4741  	rtype types.Kind
  4742  }
  4743  
  4744  var softFloatOps map[ssaop.Op]sfRtCallDef
  4745  
  4746  func softfloatInit() {
  4747  	// Some of these operations get transformed by sfcall.
  4748  	softFloatOps = map[ssaop.Op]sfRtCallDef{
  4749  		ssaop.OpAdd32F: {typecheck.LookupRuntimeFunc("fadd32"), types.TFLOAT32},
  4750  		ssaop.OpAdd64F: {typecheck.LookupRuntimeFunc("fadd64"), types.TFLOAT64},
  4751  		ssaop.OpSub32F: {typecheck.LookupRuntimeFunc("fadd32"), types.TFLOAT32},
  4752  		ssaop.OpSub64F: {typecheck.LookupRuntimeFunc("fadd64"), types.TFLOAT64},
  4753  		ssaop.OpMul32F: {typecheck.LookupRuntimeFunc("fmul32"), types.TFLOAT32},
  4754  		ssaop.OpMul64F: {typecheck.LookupRuntimeFunc("fmul64"), types.TFLOAT64},
  4755  		ssaop.OpDiv32F: {typecheck.LookupRuntimeFunc("fdiv32"), types.TFLOAT32},
  4756  		ssaop.OpDiv64F: {typecheck.LookupRuntimeFunc("fdiv64"), types.TFLOAT64},
  4757  
  4758  		ssaop.OpEq64F:   {typecheck.LookupRuntimeFunc("feq64"), types.TBOOL},
  4759  		ssaop.OpEq32F:   {typecheck.LookupRuntimeFunc("feq32"), types.TBOOL},
  4760  		ssaop.OpNeq64F:  {typecheck.LookupRuntimeFunc("feq64"), types.TBOOL},
  4761  		ssaop.OpNeq32F:  {typecheck.LookupRuntimeFunc("feq32"), types.TBOOL},
  4762  		ssaop.OpLess64F: {typecheck.LookupRuntimeFunc("fgt64"), types.TBOOL},
  4763  		ssaop.OpLess32F: {typecheck.LookupRuntimeFunc("fgt32"), types.TBOOL},
  4764  		ssaop.OpLeq64F:  {typecheck.LookupRuntimeFunc("fge64"), types.TBOOL},
  4765  		ssaop.OpLeq32F:  {typecheck.LookupRuntimeFunc("fge32"), types.TBOOL},
  4766  
  4767  		ssaop.OpCvt32to32F:  {typecheck.LookupRuntimeFunc("fint32to32"), types.TFLOAT32},
  4768  		ssaop.OpCvt32Fto32:  {typecheck.LookupRuntimeFunc("f32toint32"), types.TINT32},
  4769  		ssaop.OpCvt64to32F:  {typecheck.LookupRuntimeFunc("fint64to32"), types.TFLOAT32},
  4770  		ssaop.OpCvt32Fto64:  {typecheck.LookupRuntimeFunc("f32toint64"), types.TINT64},
  4771  		ssaop.OpCvt64Uto32F: {typecheck.LookupRuntimeFunc("fuint64to32"), types.TFLOAT32},
  4772  		ssaop.OpCvt32Fto64U: {typecheck.LookupRuntimeFunc("f32touint64"), types.TUINT64},
  4773  		ssaop.OpCvt32to64F:  {typecheck.LookupRuntimeFunc("fint32to64"), types.TFLOAT64},
  4774  		ssaop.OpCvt64Fto32:  {typecheck.LookupRuntimeFunc("f64toint32"), types.TINT32},
  4775  		ssaop.OpCvt64to64F:  {typecheck.LookupRuntimeFunc("fint64to64"), types.TFLOAT64},
  4776  		ssaop.OpCvt64Fto64:  {typecheck.LookupRuntimeFunc("f64toint64"), types.TINT64},
  4777  		ssaop.OpCvt64Uto64F: {typecheck.LookupRuntimeFunc("fuint64to64"), types.TFLOAT64},
  4778  		ssaop.OpCvt64Fto64U: {typecheck.LookupRuntimeFunc("f64touint64"), types.TUINT64},
  4779  		ssaop.OpCvt32Fto64F: {typecheck.LookupRuntimeFunc("f32to64"), types.TFLOAT64},
  4780  		ssaop.OpCvt64Fto32F: {typecheck.LookupRuntimeFunc("f64to32"), types.TFLOAT32},
  4781  	}
  4782  }
  4783  
  4784  // TODO: do not emit sfcall if operation can be optimized to constant in later
  4785  // opt phase
  4786  func (s *state) sfcall(op ssaop.Op, args ...*ssa.Value) (*ssa.Value, bool) {
  4787  	f2i := func(t *types.Type) *types.Type {
  4788  		switch t.Kind() {
  4789  		case types.TFLOAT32:
  4790  			return types.Types[types.TUINT32]
  4791  		case types.TFLOAT64:
  4792  			return types.Types[types.TUINT64]
  4793  		}
  4794  		return t
  4795  	}
  4796  
  4797  	if callDef, ok := softFloatOps[op]; ok {
  4798  		switch op {
  4799  		case ssaop.OpLess32F,
  4800  			ssaop.OpLess64F,
  4801  			ssaop.OpLeq32F,
  4802  			ssaop.OpLeq64F:
  4803  			args[0], args[1] = args[1], args[0]
  4804  		case ssaop.OpSub32F,
  4805  			ssaop.OpSub64F:
  4806  			args[1] = s.newValue1(s.ssaOp(ir.ONEG, types.Types[callDef.rtype]), args[1].Type, args[1])
  4807  		}
  4808  
  4809  		// runtime functions take uints for floats and returns uints.
  4810  		// Convert to uints so we use the right calling convention.
  4811  		for i, a := range args {
  4812  			if a.Type.IsFloat() {
  4813  				args[i] = s.newValue1(ssaop.OpCopy, f2i(a.Type), a)
  4814  			}
  4815  		}
  4816  
  4817  		rt := types.Types[callDef.rtype]
  4818  		result := s.rtcall(callDef.rtfn, true, []*types.Type{f2i(rt)}, args...)[0]
  4819  		if rt.IsFloat() {
  4820  			result = s.newValue1(ssaop.OpCopy, rt, result)
  4821  		}
  4822  		if op == ssaop.OpNeq32F || op == ssaop.OpNeq64F {
  4823  			result = s.newValue1(ssaop.OpNot, result.Type, result)
  4824  		}
  4825  		return result, true
  4826  	}
  4827  	return nil, false
  4828  }
  4829  
  4830  // split breaks up a tuple-typed value into its 2 parts.
  4831  func (s *state) split(v *ssa.Value) (*ssa.Value, *ssa.Value) {
  4832  	p0 := s.newValue1(ssaop.OpSelect0, v.Type.FieldType(0), v)
  4833  	p1 := s.newValue1(ssaop.OpSelect1, v.Type.FieldType(1), v)
  4834  	return p0, p1
  4835  }
  4836  
  4837  // intrinsicCall converts a call to a recognized intrinsic function into the intrinsic SSA operation.
  4838  func (s *state) intrinsicCall(n *ir.CallExpr) *ssa.Value {
  4839  	v := findIntrinsic(n.Fun.Sym())(s, n, s.intrinsicArgs(n))
  4840  	if ssaconfig.IntrinsicsDebug > 0 {
  4841  		x := v
  4842  		if x == nil {
  4843  			x = s.mem()
  4844  		}
  4845  		if x.Op == ssaop.OpSelect0 || x.Op == ssaop.OpSelect1 {
  4846  			x = x.Args[0]
  4847  		}
  4848  		base.WarnfAt(n.Pos(), "intrinsic substitution for %v with %s", n.Fun.Sym().Name, x.LongString())
  4849  	}
  4850  	return v
  4851  }
  4852  
  4853  // intrinsicArgs extracts args from n, evaluates them to SSA values, and returns them.
  4854  func (s *state) intrinsicArgs(n *ir.CallExpr) []*ssa.Value {
  4855  	args := make([]*ssa.Value, len(n.Args))
  4856  	for i, n := range n.Args {
  4857  		args[i] = s.expr(n)
  4858  	}
  4859  	return args
  4860  }
  4861  
  4862  // openDeferRecord adds code to evaluate and store the function for an open-code defer
  4863  // call, and records info about the defer, so we can generate proper code on the
  4864  // exit paths. n is the sub-node of the defer node that is the actual function
  4865  // call. We will also record funcdata information on where the function is stored
  4866  // (as well as the deferBits variable), and this will enable us to run the proper
  4867  // defer calls during panics.
  4868  func (s *state) openDeferRecord(n *ir.CallExpr) {
  4869  	if len(n.Args) != 0 || n.Op() != ir.OCALLFUNC || n.Fun.Type().NumResults() != 0 {
  4870  		s.Fatalf("defer call with arguments or results: %v", n)
  4871  	}
  4872  
  4873  	opendefer := &openDeferInfo{
  4874  		n: n,
  4875  	}
  4876  	fn := n.Fun
  4877  	// We must always store the function value in a stack slot for the
  4878  	// runtime panic code to use. But in the defer exit code, we will
  4879  	// call the function directly if it is a static function.
  4880  	closureVal := s.expr(fn)
  4881  	closure := s.openDeferSave(fn.Type(), closureVal)
  4882  	opendefer.closureNode = closure.Aux.(*ir.Name)
  4883  	if !(fn.Op() == ir.ONAME && fn.(*ir.Name).Class == ir.PFUNC) {
  4884  		opendefer.closure = closure
  4885  	}
  4886  	index := len(s.openDefers)
  4887  	s.openDefers = append(s.openDefers, opendefer)
  4888  
  4889  	// Update deferBits only after evaluation and storage to stack of
  4890  	// the function is successful.
  4891  	bitvalue := s.constInt8(types.Types[types.TUINT8], 1<<uint(index))
  4892  	newDeferBits := s.newValue2(ssaop.OpOr8, types.Types[types.TUINT8], s.variable(deferBitsVar, types.Types[types.TUINT8]), bitvalue)
  4893  	s.vars[deferBitsVar] = newDeferBits
  4894  	s.store(types.Types[types.TUINT8], s.deferBitsAddr, newDeferBits)
  4895  }
  4896  
  4897  // openDeferSave generates SSA nodes to store a value (with type t) for an
  4898  // open-coded defer at an explicit autotmp location on the stack, so it can be
  4899  // reloaded and used for the appropriate call on exit. Type t must be a function type
  4900  // (therefore SSAable). val is the value to be stored. The function returns an SSA
  4901  // value representing a pointer to the autotmp location.
  4902  func (s *state) openDeferSave(t *types.Type, val *ssa.Value) *ssa.Value {
  4903  	if !ssa.CanSSA(t) {
  4904  		s.Fatalf("openDeferSave of non-SSA-able type %v val=%v", t, val)
  4905  	}
  4906  	if !t.HasPointers() {
  4907  		s.Fatalf("openDeferSave of pointerless type %v val=%v", t, val)
  4908  	}
  4909  	pos := val.Pos
  4910  	temp := typecheck.TempAt(pos.WithNotStmt(), s.curfn, t)
  4911  	temp.SetOpenDeferSlot(true)
  4912  	temp.SetFrameOffset(int64(len(s.openDefers))) // so cmpstackvarlt can order them
  4913  	var addrTemp *ssa.Value
  4914  	// Use OpVarLive to make sure stack slot for the closure is not removed by
  4915  	// dead-store elimination
  4916  	if s.curBlock.ID != s.f.Entry.ID {
  4917  		// Force the tmp storing this defer function to be declared in the entry
  4918  		// block, so that it will be live for the defer exit code (which will
  4919  		// actually access it only if the associated defer call has been activated).
  4920  		if t.HasPointers() {
  4921  			s.defvars[s.f.Entry.ID][memVar] = s.f.Entry.NewValue1A(src.NoXPos, ssaop.OpVarDef, types.TypeMem, temp, s.defvars[s.f.Entry.ID][memVar])
  4922  		}
  4923  		s.defvars[s.f.Entry.ID][memVar] = s.f.Entry.NewValue1A(src.NoXPos, ssaop.OpVarLive, types.TypeMem, temp, s.defvars[s.f.Entry.ID][memVar])
  4924  		addrTemp = s.f.Entry.NewValue2A(src.NoXPos, ssaop.OpLocalAddr, types.NewPtr(temp.Type()), temp, s.sp, s.defvars[s.f.Entry.ID][memVar])
  4925  	} else {
  4926  		// Special case if we're still in the entry block. We can't use
  4927  		// the above code, since s.defvars[s.f.Entry.ID] isn't defined
  4928  		// until we end the entry block with s.endBlock().
  4929  		if t.HasPointers() {
  4930  			s.vars[memVar] = s.newValue1Apos(ssaop.OpVarDef, types.TypeMem, temp, s.mem(), false)
  4931  		}
  4932  		s.vars[memVar] = s.newValue1Apos(ssaop.OpVarLive, types.TypeMem, temp, s.mem(), false)
  4933  		addrTemp = s.newValue2Apos(ssaop.OpLocalAddr, types.NewPtr(temp.Type()), temp, s.sp, s.mem(), false)
  4934  	}
  4935  	// Since we may use this temp during exit depending on the
  4936  	// deferBits, we must define it unconditionally on entry.
  4937  	// Therefore, we must make sure it is zeroed out in the entry
  4938  	// block if it contains pointers, else GC may wrongly follow an
  4939  	// uninitialized pointer value.
  4940  	temp.SetNeedzero(true)
  4941  	// We are storing to the stack, hence we can avoid the full checks in
  4942  	// storeType() (no write barrier) and do a simple store().
  4943  	s.store(t, addrTemp, val)
  4944  	return addrTemp
  4945  }
  4946  
  4947  // openDeferExit generates SSA for processing all the open coded defers at exit.
  4948  // The code involves loading deferBits, and checking each of the bits to see if
  4949  // the corresponding defer statement was executed. For each bit that is turned
  4950  // on, the associated defer call is made.
  4951  func (s *state) openDeferExit() {
  4952  	deferExit := s.f.NewBlock(block.BlockPlain)
  4953  	s.endBlock().AddEdgeTo(deferExit)
  4954  	s.startBlock(deferExit)
  4955  	s.lastDeferExit = deferExit
  4956  	s.lastDeferCount = len(s.openDefers)
  4957  	zeroval := s.constInt8(types.Types[types.TUINT8], 0)
  4958  	// Test for and run defers in reverse order
  4959  	for i := len(s.openDefers) - 1; i >= 0; i-- {
  4960  		r := s.openDefers[i]
  4961  		bCond := s.f.NewBlock(block.BlockPlain)
  4962  		bEnd := s.f.NewBlock(block.BlockPlain)
  4963  
  4964  		deferBits := s.variable(deferBitsVar, types.Types[types.TUINT8])
  4965  		// Generate code to check if the bit associated with the current
  4966  		// defer is set.
  4967  		bitval := s.constInt8(types.Types[types.TUINT8], 1<<uint(i))
  4968  		andval := s.newValue2(ssaop.OpAnd8, types.Types[types.TUINT8], deferBits, bitval)
  4969  		eqVal := s.newValue2(ssaop.OpEq8, types.Types[types.TBOOL], andval, zeroval)
  4970  		b := s.endBlock()
  4971  		b.Kind = block.BlockIf
  4972  		b.SetControl(eqVal)
  4973  		b.AddEdgeTo(bEnd)
  4974  		b.AddEdgeTo(bCond)
  4975  		bCond.AddEdgeTo(bEnd)
  4976  		s.startBlock(bCond)
  4977  
  4978  		// Clear this bit in deferBits and force store back to stack, so
  4979  		// we will not try to re-run this defer call if this defer call panics.
  4980  		nbitval := s.newValue1(ssaop.OpCom8, types.Types[types.TUINT8], bitval)
  4981  		maskedval := s.newValue2(ssaop.OpAnd8, types.Types[types.TUINT8], deferBits, nbitval)
  4982  		s.store(types.Types[types.TUINT8], s.deferBitsAddr, maskedval)
  4983  		// Use this value for following tests, so we keep previous
  4984  		// bits cleared.
  4985  		s.vars[deferBitsVar] = maskedval
  4986  
  4987  		// Generate code to call the function call of the defer, using the
  4988  		// closure that were stored in argtmps at the point of the defer
  4989  		// statement.
  4990  		fn := r.n.Fun
  4991  		stksize := fn.Type().ArgWidth()
  4992  		var callArgs []*ssa.Value
  4993  		var call *ssa.Value
  4994  		if r.closure != nil {
  4995  			t := r.closure.Type.Elem()
  4996  			v := s.load(t, r.closure)
  4997  			// The bit was cleared above and panic processing only reads a slot
  4998  			// whose bit is set, so the slot is dead from here.
  4999  			s.store(t, r.closure, s.zeroVal(t))
  5000  			s.maybeNilCheckClosure(v, callDefer)
  5001  			codeptr := s.rawLoad(types.Types[types.TUINTPTR], v)
  5002  			aux := ssa.ClosureAuxCall(s.f.ABIDefault.ABIAnalyzeTypes(nil, nil))
  5003  			call = s.newValue2A(ssaop.OpClosureLECall, aux.LateExpansionResultType(), aux, codeptr, v)
  5004  		} else {
  5005  			aux := ssa.StaticAuxCall(fn.(*ir.Name).Linksym(), s.f.ABIDefault.ABIAnalyzeTypes(nil, nil))
  5006  			call = s.newValue0A(ssaop.OpStaticLECall, aux.LateExpansionResultType(), aux)
  5007  		}
  5008  		callArgs = append(callArgs, s.mem())
  5009  		call.AddArgs(callArgs...)
  5010  		call.AuxInt = stksize
  5011  		s.vars[memVar] = s.newValue1I(ssaop.OpSelectN, types.TypeMem, 0, call)
  5012  		// Make sure that the stack slots with pointers are kept live
  5013  		// through the call (which is a pre-emption point). Also, we will
  5014  		// use the first call of the last defer exit to compute liveness
  5015  		// for the deferreturn, so we want all stack slots to be live.
  5016  		if r.closureNode != nil {
  5017  			s.vars[memVar] = s.newValue1Apos(ssaop.OpVarLive, types.TypeMem, r.closureNode, s.mem(), false)
  5018  		}
  5019  
  5020  		s.endBlock()
  5021  		s.startBlock(bEnd)
  5022  	}
  5023  }
  5024  
  5025  func (s *state) callResult(n *ir.CallExpr, k callKind) *ssa.Value {
  5026  	return s.call(n, k, false, nil)
  5027  }
  5028  
  5029  func (s *state) callAddr(n *ir.CallExpr, k callKind) *ssa.Value {
  5030  	return s.call(n, k, true, nil)
  5031  }
  5032  
  5033  // Calls the function n using the specified call type.
  5034  // Returns the address of the return value (or nil if none).
  5035  func (s *state) call(n *ir.CallExpr, k callKind, returnResultAddr bool, deferExtra ir.Expr) *ssa.Value {
  5036  	s.prevCall = nil
  5037  	var calleeLSym *obj.LSym // target function (if static)
  5038  	var closure *ssa.Value   // ptr to closure to run (if dynamic)
  5039  	var codeptr *ssa.Value   // ptr to target code (if dynamic)
  5040  	var dextra *ssa.Value    // defer extra arg
  5041  	var rcvr *ssa.Value      // receiver to set
  5042  	fn := n.Fun
  5043  	var ACArgs []*types.Type    // AuxCall args
  5044  	var ACResults []*types.Type // AuxCall results
  5045  	var callArgs []*ssa.Value   // For late-expansion, the args themselves (not stored, args to the call instead).
  5046  
  5047  	callABI := s.f.ABIDefault
  5048  
  5049  	if k != callNormal && k != callTail && (len(n.Args) != 0 || n.Op() == ir.OCALLINTER || n.Fun.Type().NumResults() != 0) {
  5050  		s.Fatalf("go/defer call with arguments: %v", n)
  5051  	}
  5052  
  5053  	isCallDeferRangeFunc := false
  5054  
  5055  	switch n.Op() {
  5056  	case ir.OCALLFUNC:
  5057  		if (k == callNormal || k == callTail) && fn.Op() == ir.ONAME && fn.(*ir.Name).Class == ir.PFUNC {
  5058  			fn := fn.(*ir.Name)
  5059  			calleeLSym = callTargetLSym(fn)
  5060  			if buildcfg.Experiment.RegabiArgs {
  5061  				// This is a static call, so it may be
  5062  				// a direct call to a non-ABIInternal
  5063  				// function. fn.Func may be nil for
  5064  				// some compiler-generated functions,
  5065  				// but those are all ABIInternal.
  5066  				if fn.Func != nil {
  5067  					callABI = abiForFunc(fn.Func, s.f.ABI0, s.f.ABI1)
  5068  				}
  5069  			} else {
  5070  				// TODO(register args) remove after register abi is working
  5071  				inRegistersImported := fn.Pragma()&ir.RegisterParams != 0
  5072  				inRegistersSamePackage := fn.Func != nil && fn.Func.Pragma&ir.RegisterParams != 0
  5073  				if inRegistersImported || inRegistersSamePackage {
  5074  					callABI = s.f.ABI1
  5075  				}
  5076  			}
  5077  			if fn := n.Fun.Sym().Name; n.Fun.Sym().Pkg == ir.Pkgs.Runtime && fn == "deferrangefunc" {
  5078  				isCallDeferRangeFunc = true
  5079  			}
  5080  			break
  5081  		}
  5082  		closure = s.expr(fn)
  5083  		if k != callDefer && k != callDeferStack {
  5084  			// Deferred nil function needs to panic when the function is invoked,
  5085  			// not the point of defer statement.
  5086  			s.maybeNilCheckClosure(closure, k)
  5087  		}
  5088  	case ir.OCALLINTER:
  5089  		if fn.Op() != ir.ODOTINTER {
  5090  			s.Fatalf("OCALLINTER: n.Left not an ODOTINTER: %v", fn.Op())
  5091  		}
  5092  		fn := fn.(*ir.SelectorExpr)
  5093  		var iclosure *ssa.Value
  5094  		iclosure, rcvr = s.getClosureAndRcvr(fn)
  5095  		if k == callNormal || k == callTail {
  5096  			codeptr = s.load(types.Types[types.TUINTPTR], iclosure)
  5097  		} else {
  5098  			closure = iclosure
  5099  		}
  5100  	}
  5101  	if deferExtra != nil {
  5102  		dextra = s.expr(deferExtra)
  5103  	}
  5104  
  5105  	params := callABI.ABIAnalyze(n.Fun.Type(), false /* Do not set (register) nNames from caller side -- can cause races. */)
  5106  	types.CalcSize(fn.Type())
  5107  	stksize := params.ArgWidth() // includes receiver, args, and results
  5108  
  5109  	res := n.Fun.Type().Results()
  5110  	if k == callNormal || k == callTail {
  5111  		for _, p := range params.OutParams() {
  5112  			ACResults = append(ACResults, p.Type)
  5113  		}
  5114  	}
  5115  
  5116  	var call *ssa.Value
  5117  	if k == callDeferStack {
  5118  		if stksize != 0 {
  5119  			s.Fatalf("deferprocStack with non-zero stack size %d: %v", stksize, n)
  5120  		}
  5121  		// Make a defer struct on the stack.
  5122  		t := deferstruct()
  5123  		n, addr := s.temp(n.Pos(), t)
  5124  		n.SetNonMergeable(true)
  5125  		s.store(closure.Type,
  5126  			s.newValue1I(ssaop.OpOffPtr, closure.Type.PtrTo(), t.FieldOff(deferStructFnField), addr),
  5127  			closure)
  5128  
  5129  		// Call runtime.deferprocStack with pointer to _defer record.
  5130  		ACArgs = append(ACArgs, types.Types[types.TUINTPTR])
  5131  		aux := ssa.StaticAuxCall(ir.Syms.DeferprocStack, s.f.ABIDefault.ABIAnalyzeTypes(ACArgs, ACResults))
  5132  		callArgs = append(callArgs, addr, s.mem())
  5133  		call = s.newValue0A(ssaop.OpStaticLECall, aux.LateExpansionResultType(), aux)
  5134  		call.AddArgs(callArgs...)
  5135  		call.AuxInt = int64(types.PtrSize) // deferprocStack takes a *_defer arg
  5136  	} else {
  5137  		// Store arguments to stack, including defer/go arguments and receiver for method calls.
  5138  		// These are written in SP-offset order.
  5139  		argStart := base.Ctxt.Arch.FixedFrameSize
  5140  		// Defer/go args.
  5141  		if k != callNormal && k != callTail {
  5142  			// Write closure (arg to newproc/deferproc).
  5143  			ACArgs = append(ACArgs, types.Types[types.TUINTPTR]) // not argExtra
  5144  			callArgs = append(callArgs, closure)
  5145  			stksize += int64(types.PtrSize)
  5146  			argStart += int64(types.PtrSize)
  5147  			if dextra != nil {
  5148  				// Extra token of type any for deferproc
  5149  				ACArgs = append(ACArgs, types.Types[types.TINTER])
  5150  				callArgs = append(callArgs, dextra)
  5151  				stksize += 2 * int64(types.PtrSize)
  5152  				argStart += 2 * int64(types.PtrSize)
  5153  			}
  5154  		}
  5155  
  5156  		// Set receiver (for interface calls).
  5157  		if rcvr != nil {
  5158  			callArgs = append(callArgs, rcvr)
  5159  		}
  5160  
  5161  		// Write args.
  5162  		t := n.Fun.Type()
  5163  		args := n.Args
  5164  
  5165  		for _, p := range params.InParams() { // includes receiver for interface calls
  5166  			ACArgs = append(ACArgs, p.Type)
  5167  		}
  5168  
  5169  		// Split the entry block if there are open defers, because later calls to
  5170  		// openDeferSave may cause a mismatch between the mem for an OpDereference
  5171  		// and the call site which uses it. See #49282.
  5172  		if s.curBlock.ID == s.f.Entry.ID && s.hasOpenDefers {
  5173  			b := s.endBlock()
  5174  			b.Kind = block.BlockPlain
  5175  			curb := s.f.NewBlock(block.BlockPlain)
  5176  			b.AddEdgeTo(curb)
  5177  			s.startBlock(curb)
  5178  		}
  5179  
  5180  		for i, n := range args {
  5181  			callArgs = append(callArgs, s.putArg(n, t.Param(i).Type))
  5182  		}
  5183  
  5184  		// In -race mode, we need to call racefuncexit before a tail call.
  5185  		// A tail call reuses our frame and returns directly to our caller,
  5186  		// so this is the last chance we get to tell the race detector that
  5187  		// this function is done. Note: this has to happen after the
  5188  		// arguments are evaluated, otherwise races in the argument
  5189  		// expressions would be attributed to the caller instead.
  5190  		if k == callTail && s.instrumentEnterExit {
  5191  			s.rtcall(ir.Syms.Racefuncexit, true, nil)
  5192  		}
  5193  
  5194  		callArgs = append(callArgs, s.mem())
  5195  
  5196  		// call target
  5197  		switch {
  5198  		case k == callDefer:
  5199  			sym := ir.Syms.Deferproc
  5200  			if dextra != nil {
  5201  				sym = ir.Syms.Deferprocat
  5202  			}
  5203  			aux := ssa.StaticAuxCall(sym, s.f.ABIDefault.ABIAnalyzeTypes(ACArgs, ACResults)) // TODO paramResultInfo for Deferproc(at)
  5204  			call = s.newValue0A(ssaop.OpStaticLECall, aux.LateExpansionResultType(), aux)
  5205  		case k == callGo:
  5206  			aux := ssa.StaticAuxCall(ir.Syms.Newproc, s.f.ABIDefault.ABIAnalyzeTypes(ACArgs, ACResults))
  5207  			call = s.newValue0A(ssaop.OpStaticLECall, aux.LateExpansionResultType(), aux) // TODO paramResultInfo for Newproc
  5208  		case closure != nil:
  5209  			// rawLoad because loading the code pointer from a
  5210  			// closure is always safe, but IsSanitizerSafeAddr
  5211  			// can't always figure that out currently, and it's
  5212  			// critical that we not clobber any arguments already
  5213  			// stored onto the stack.
  5214  			codeptr = s.rawLoad(types.Types[types.TUINTPTR], closure)
  5215  			aux := ssa.ClosureAuxCall(callABI.ABIAnalyzeTypes(ACArgs, ACResults))
  5216  			call = s.newValue2A(ssaop.OpClosureLECall, aux.LateExpansionResultType(), aux, codeptr, closure)
  5217  		case codeptr != nil:
  5218  			// Note that the "receiver" parameter is nil because the actual receiver is the first input parameter.
  5219  			aux := ssa.InterfaceAuxCall(params)
  5220  			call = s.newValue1A(ssaop.OpInterLECall, aux.LateExpansionResultType(), aux, codeptr)
  5221  			if k == callTail {
  5222  				call.Op = ssaop.OpTailLECallInter
  5223  				stksize = 0 // Tail call does not use stack. We reuse caller's frame.
  5224  			}
  5225  		case calleeLSym != nil:
  5226  			aux := ssa.StaticAuxCall(calleeLSym, params)
  5227  			call = s.newValue0A(ssaop.OpStaticLECall, aux.LateExpansionResultType(), aux)
  5228  			if k == callTail {
  5229  				call.Op = ssaop.OpTailLECall
  5230  				stksize = 0 // Tail call does not use stack. We reuse caller's frame.
  5231  			}
  5232  		default:
  5233  			s.Fatalf("bad call type %v %v", n.Op(), n)
  5234  		}
  5235  		call.AddArgs(callArgs...)
  5236  		call.AuxInt = stksize // Call operations carry the argsize of the callee along with them
  5237  	}
  5238  	s.prevCall = call
  5239  	s.vars[memVar] = s.newValue1I(ssaop.OpSelectN, types.TypeMem, int64(len(ACResults)), call)
  5240  	// Insert VarLive opcodes.
  5241  	for _, v := range n.KeepAlive {
  5242  		if !v.Addrtaken() {
  5243  			s.Fatalf("KeepAlive variable %v must have Addrtaken set", v)
  5244  		}
  5245  		switch v.Class {
  5246  		case ir.PAUTO, ir.PPARAM, ir.PPARAMOUT:
  5247  		default:
  5248  			s.Fatalf("KeepAlive variable %v must be Auto or Arg", v)
  5249  		}
  5250  		s.vars[memVar] = s.newValue1A(ssaop.OpVarLive, types.TypeMem, v, s.mem())
  5251  	}
  5252  
  5253  	// Build result value (before we might end the defer block, below).
  5254  	var result *ssa.Value
  5255  	if len(res) == 0 || k != callNormal {
  5256  		result = nil
  5257  	} else {
  5258  		fp := res[0]
  5259  		if returnResultAddr {
  5260  			result = s.resultAddrOfCall(call, 0, fp.Type)
  5261  		} else {
  5262  			result = s.newValue1I(ssaop.OpSelectN, fp.Type, 0, call)
  5263  		}
  5264  		if n.Reshape {
  5265  			result = s.newValue1(ssaop.OpCopy, n.Type(), result)
  5266  		}
  5267  	}
  5268  
  5269  	// Finish block for defers
  5270  	if k == callDefer || k == callDeferStack || isCallDeferRangeFunc {
  5271  		b := s.endBlock()
  5272  		b.Kind = block.BlockDefer
  5273  		b.SetControl(call)
  5274  		bNext := s.f.NewBlock(block.BlockPlain)
  5275  		b.AddEdgeTo(bNext)
  5276  		r := s.f.DeferReturn // Share a single deferreturn among all defers
  5277  		if r == nil {
  5278  			r = s.f.NewBlock(block.BlockPlain)
  5279  			s.startBlock(r)
  5280  			s.exit()
  5281  			s.f.DeferReturn = r
  5282  		}
  5283  		b.AddEdgeTo(r) // Add recover edge to exit code.  This is a fake edge to keep the block live.
  5284  		b.Likely = ssa.BranchLikely
  5285  		s.startBlock(bNext)
  5286  	}
  5287  
  5288  	return result
  5289  }
  5290  
  5291  // maybeNilCheckClosure checks if a nil check of a closure is needed in some
  5292  // architecture-dependent situations and, if so, emits the nil check.
  5293  func (s *state) maybeNilCheckClosure(closure *ssa.Value, k callKind) {
  5294  	if Arch.LinkArch.Family == sys.Wasm || buildcfg.GOOS == "aix" && k != callGo {
  5295  		// On AIX, the closure needs to be verified as fn can be nil, except if it's a call go. This needs to be handled by the runtime to have the "go of nil func value" error.
  5296  		// TODO(neelance): On other architectures this should be eliminated by the optimization steps
  5297  		s.nilCheck(closure)
  5298  	}
  5299  }
  5300  
  5301  // getClosureAndRcvr returns values for the appropriate closure and receiver of an
  5302  // interface call
  5303  func (s *state) getClosureAndRcvr(fn *ir.SelectorExpr) (*ssa.Value, *ssa.Value) {
  5304  	i := s.expr(fn.X)
  5305  	itab := s.newValue1(ssaop.OpITab, types.Types[types.TUINTPTR], i)
  5306  	s.nilCheck(itab)
  5307  	itabidx := fn.Offset() + rttype.ITab.OffsetOf("Fun")
  5308  	closure := s.newValue1I(ssaop.OpOffPtr, s.f.Config.Types.UintptrPtr, itabidx, itab)
  5309  	rcvr := s.newValue1(ssaop.OpIData, s.f.Config.Types.BytePtr, i)
  5310  	return closure, rcvr
  5311  }
  5312  
  5313  // etypesign returns the signed-ness of e, for integer/pointer etypes.
  5314  // -1 means signed, +1 means unsigned, 0 means non-integer/non-pointer.
  5315  func etypesign(e types.Kind) int8 {
  5316  	switch e {
  5317  	case types.TINT8, types.TINT16, types.TINT32, types.TINT64, types.TINT:
  5318  		return -1
  5319  	case types.TUINT8, types.TUINT16, types.TUINT32, types.TUINT64, types.TUINT, types.TUINTPTR, types.TUNSAFEPTR:
  5320  		return +1
  5321  	}
  5322  	return 0
  5323  }
  5324  
  5325  // addr converts the address of the expression n to SSA, adds it to s and returns the SSA result.
  5326  // The value that the returned Value represents is guaranteed to be non-nil.
  5327  func (s *state) addr(n ir.Node) *ssa.Value {
  5328  	if n.Op() != ir.ONAME {
  5329  		s.pushLine(n.Pos())
  5330  		defer s.popLine()
  5331  	}
  5332  
  5333  	if s.canSSA(n) {
  5334  		// This happens in weird, always-panics cases, like:
  5335  		//     var x [0][2]int
  5336  		//     x[i][j] = 5
  5337  		// The outer assignment, ...[j] = 5, is a fine
  5338  		// assignment to do, but requires computing the address
  5339  		// &x[i], which will always panic when evaluated.
  5340  		// We just return something reasonable in this case.
  5341  		// It will be dynamically unreachable. See issue 77635.
  5342  		s.boundsCheckArrayIndex(n)
  5343  		return s.newValue1A(ssaop.OpAddr, n.Type().PtrTo(), ir.Syms.Zerobase, s.sb)
  5344  	}
  5345  
  5346  	t := types.NewPtr(n.Type())
  5347  	linksymOffset := func(lsym *obj.LSym, offset int64) *ssa.Value {
  5348  		v := s.entryNewValue1A(ssaop.OpAddr, t, lsym, s.sb)
  5349  		// TODO: Make OpAddr use AuxInt as well as Aux.
  5350  		if offset != 0 {
  5351  			v = s.entryNewValue1I(ssaop.OpOffPtr, v.Type, offset, v)
  5352  		}
  5353  		return v
  5354  	}
  5355  	switch n.Op() {
  5356  	case ir.OLINKSYMOFFSET:
  5357  		no := n.(*ir.LinksymOffsetExpr)
  5358  		return linksymOffset(no.Linksym, no.Offset_)
  5359  	case ir.ONAME:
  5360  		n := n.(*ir.Name)
  5361  		if n.Heapaddr != nil {
  5362  			return s.expr(n.Heapaddr)
  5363  		}
  5364  		switch n.Class {
  5365  		case ir.PEXTERN:
  5366  			// global variable
  5367  			return linksymOffset(n.Linksym(), 0)
  5368  		case ir.PPARAM:
  5369  			// parameter slot
  5370  			v := s.decladdrs[n]
  5371  			if v != nil {
  5372  				return v
  5373  			}
  5374  			s.Fatalf("addr of undeclared ONAME %v. declared: %v", n, s.decladdrs)
  5375  			return nil
  5376  		case ir.PAUTO:
  5377  			return s.newValue2Apos(ssaop.OpLocalAddr, t, n, s.sp, s.mem(), !ir.IsAutoTmp(n))
  5378  
  5379  		case ir.PPARAMOUT: // Same as PAUTO -- cannot generate LEA early.
  5380  			// ensure that we reuse symbols for out parameters so
  5381  			// that cse works on their addresses
  5382  			return s.newValue2Apos(ssaop.OpLocalAddr, t, n, s.sp, s.mem(), true)
  5383  		default:
  5384  			s.Fatalf("variable address class %v not implemented", n.Class)
  5385  			return nil
  5386  		}
  5387  	case ir.ORESULT:
  5388  		// load return from callee
  5389  		n := n.(*ir.ResultExpr)
  5390  		return s.resultAddrOfCall(s.prevCall, n.Index, n.Type())
  5391  	case ir.OINDEX:
  5392  		n := n.(*ir.IndexExpr)
  5393  		if n.X.Type().IsSlice() {
  5394  			a := s.expr(n.X)
  5395  			i := s.expr(n.Index)
  5396  			len := s.newValue1(ssaop.OpSliceLen, types.Types[types.TINT], a)
  5397  			i = s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded())
  5398  			p := s.newValue1(ssaop.OpSlicePtr, t, a)
  5399  			return s.newValue2(ssaop.OpPtrIndex, t, p, i)
  5400  		} else { // array
  5401  			a := s.addr(n.X)
  5402  			i := s.expr(n.Index)
  5403  			len := s.constInt(types.Types[types.TINT], n.X.Type().NumElem())
  5404  			i = s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded())
  5405  			return s.newValue2(ssaop.OpPtrIndex, types.NewPtr(n.X.Type().Elem()), a, i)
  5406  		}
  5407  	case ir.ODEREF:
  5408  		n := n.(*ir.StarExpr)
  5409  		return s.exprPtr(n.X, n.Bounded(), n.Pos())
  5410  	case ir.ODOT:
  5411  		n := n.(*ir.SelectorExpr)
  5412  		p := s.addr(n.X)
  5413  		return s.newValue1I(ssaop.OpOffPtr, t, n.Offset(), p)
  5414  	case ir.ODOTPTR:
  5415  		n := n.(*ir.SelectorExpr)
  5416  		p := s.exprPtr(n.X, n.Bounded(), n.Pos())
  5417  		return s.newValue1I(ssaop.OpOffPtr, t, n.Offset(), p)
  5418  	case ir.OCONVNOP:
  5419  		n := n.(*ir.ConvExpr)
  5420  		if n.Type() == n.X.Type() {
  5421  			return s.addr(n.X)
  5422  		}
  5423  		addr := s.addr(n.X)
  5424  		return s.newValue1(ssaop.OpCopy, t, addr) // ensure that addr has the right type
  5425  	case ir.OCALLFUNC, ir.OCALLINTER:
  5426  		n := n.(*ir.CallExpr)
  5427  		return s.callAddr(n, callNormal)
  5428  	case ir.ODOTTYPE, ir.ODYNAMICDOTTYPE:
  5429  		var v *ssa.Value
  5430  		if n.Op() == ir.ODOTTYPE {
  5431  			v, _ = s.dottype(n.(*ir.TypeAssertExpr), false)
  5432  		} else {
  5433  			v, _ = s.dynamicDottype(n.(*ir.DynamicTypeAssertExpr), false)
  5434  		}
  5435  		if v.Op != ssaop.OpLoad {
  5436  			s.Fatalf("dottype of non-load")
  5437  		}
  5438  		if v.Args[1] != s.mem() {
  5439  			s.Fatalf("memory no longer live from dottype load")
  5440  		}
  5441  		return v.Args[0]
  5442  	default:
  5443  		s.Fatalf("unhandled addr %v", n.Op())
  5444  		return nil
  5445  	}
  5446  }
  5447  
  5448  // canSSA reports whether n is SSA-able.
  5449  // n must be an ONAME (or an ODOT sequence with an ONAME base).
  5450  func (s *state) canSSA(n ir.Node) bool {
  5451  	if base.Flag.N != 0 {
  5452  		return false
  5453  	}
  5454  	for {
  5455  		nn := n
  5456  		if nn.Op() == ir.ODOT {
  5457  			nn := nn.(*ir.SelectorExpr)
  5458  			n = nn.X
  5459  			continue
  5460  		}
  5461  		if nn.Op() == ir.OINDEX {
  5462  			nn := nn.(*ir.IndexExpr)
  5463  			if nn.X.Type().IsArray() {
  5464  				n = nn.X
  5465  				continue
  5466  			}
  5467  		}
  5468  		break
  5469  	}
  5470  	if n.Op() != ir.ONAME {
  5471  		return false
  5472  	}
  5473  	return s.canSSAName(n.(*ir.Name)) && ssa.CanSSA(n.Type())
  5474  }
  5475  
  5476  func (s *state) canSSAName(name *ir.Name) bool {
  5477  	if name.Addrtaken() || !name.OnStack() {
  5478  		return false
  5479  	}
  5480  	switch name.Class {
  5481  	case ir.PPARAMOUT:
  5482  		if s.hasdefer {
  5483  			// TODO: handle this case? Named return values must be
  5484  			// in memory so that the deferred function can see them.
  5485  			// Maybe do: if !strings.HasPrefix(n.String(), "~") { return false }
  5486  			// Or maybe not, see issue 18860.  Even unnamed return values
  5487  			// must be written back so if a defer recovers, the caller can see them.
  5488  			return false
  5489  		}
  5490  		if s.cgoUnsafeArgs {
  5491  			// Cgo effectively takes the address of all result args,
  5492  			// but the compiler can't see that.
  5493  			return false
  5494  		}
  5495  	}
  5496  	return true
  5497  	// TODO: try to make more variables SSAable?
  5498  }
  5499  
  5500  // exprPtr evaluates n to a pointer and nil-checks it.
  5501  func (s *state) exprPtr(n ir.Node, bounded bool, lineno src.XPos) *ssa.Value {
  5502  	p := s.expr(n)
  5503  	if bounded || n.NonNil() {
  5504  		if s.f.Frontend().Debug_checknil() && lineno.Line() > 1 {
  5505  			s.f.Warnl(lineno, "removed nil check")
  5506  		}
  5507  		return p
  5508  	}
  5509  	p = s.nilCheck(p)
  5510  	return p
  5511  }
  5512  
  5513  // nilCheck generates nil pointer checking code.
  5514  // Used only for automatically inserted nil checks,
  5515  // not for user code like 'x != nil'.
  5516  // Returns a "definitely not nil" copy of x to ensure proper ordering
  5517  // of the uses of the post-nilcheck pointer.
  5518  func (s *state) nilCheck(ptr *ssa.Value) *ssa.Value {
  5519  	if base.Debug.DisableNil != 0 || s.curfn.NilCheckDisabled() {
  5520  		return ptr
  5521  	}
  5522  	return s.newValue2(ssaop.OpNilCheck, ptr.Type, ptr, s.mem())
  5523  }
  5524  
  5525  // boundsCheckArrayIndex generates bounds checking code for array indexing operations.
  5526  func (s *state) boundsCheckArrayIndex(n ir.Node) {
  5527  	if n.Op() != ir.OINDEX {
  5528  		return
  5529  	}
  5530  	nn := n.(*ir.IndexExpr)
  5531  	typ := nn.X.Type()
  5532  	if typ.IsArray() {
  5533  		_ = s.expr(nn.X) // for side effects
  5534  		idx := s.expr(nn.Index)
  5535  		len := s.constInt(types.Types[types.TINT], typ.NumElem())
  5536  		s.boundsCheck(idx, len, ssa.BoundsIndex, nn.Bounded())
  5537  	}
  5538  }
  5539  
  5540  // boundsCheck generates bounds checking code. Checks if 0 <= idx <[=] len, branches to exit if not.
  5541  // Starts a new block on return.
  5542  // On input, len must be converted to full int width and be nonnegative.
  5543  // Returns idx converted to full int width.
  5544  // If bounded is true then caller guarantees the index is not out of bounds
  5545  // (but boundsCheck will still extend the index to full int width).
  5546  func (s *state) boundsCheck(idx, len *ssa.Value, kind ssa.BoundsKind, bounded bool) *ssa.Value {
  5547  	idx = s.extendIndex(idx, len, kind, bounded)
  5548  
  5549  	if bounded || base.Flag.B != 0 {
  5550  		// If bounded or bounds checking is flag-disabled, then no check necessary,
  5551  		// just return the extended index.
  5552  		//
  5553  		// Here, bounded == true if the compiler generated the index itself,
  5554  		// such as in the expansion of a slice initializer. These indexes are
  5555  		// compiler-generated, not Go program variables, so they cannot be
  5556  		// attacker-controlled, so we can omit Spectre masking as well.
  5557  		//
  5558  		// Note that we do not want to omit Spectre masking in code like:
  5559  		//
  5560  		//	if 0 <= i && i < len(x) {
  5561  		//		use(x[i])
  5562  		//	}
  5563  		//
  5564  		// Lucky for us, bounded==false for that code.
  5565  		// In that case (handled below), we emit a bound check (and Spectre mask)
  5566  		// and then the prove pass will remove the bounds check.
  5567  		// In theory the prove pass could potentially remove certain
  5568  		// Spectre masks, but it's very delicate and probably better
  5569  		// to be conservative and leave them all in.
  5570  		return idx
  5571  	}
  5572  
  5573  	bNext := s.f.NewBlock(block.BlockPlain)
  5574  	bPanic := s.f.NewBlock(block.BlockExit)
  5575  
  5576  	if !idx.Type.IsSigned() {
  5577  		switch kind {
  5578  		case ssa.BoundsIndex:
  5579  			kind = ssa.BoundsIndexU
  5580  		case ssa.BoundsSliceAlen:
  5581  			kind = ssa.BoundsSliceAlenU
  5582  		case ssa.BoundsSliceAcap:
  5583  			kind = ssa.BoundsSliceAcapU
  5584  		case ssa.BoundsSliceB:
  5585  			kind = ssa.BoundsSliceBU
  5586  		case ssa.BoundsSlice3Alen:
  5587  			kind = ssa.BoundsSlice3AlenU
  5588  		case ssa.BoundsSlice3Acap:
  5589  			kind = ssa.BoundsSlice3AcapU
  5590  		case ssa.BoundsSlice3B:
  5591  			kind = ssa.BoundsSlice3BU
  5592  		case ssa.BoundsSlice3C:
  5593  			kind = ssa.BoundsSlice3CU
  5594  		}
  5595  	}
  5596  
  5597  	var cmp *ssa.Value
  5598  	if kind == ssa.BoundsIndex || kind == ssa.BoundsIndexU {
  5599  		cmp = s.newValue2(ssaop.OpIsInBounds, types.Types[types.TBOOL], idx, len)
  5600  	} else {
  5601  		cmp = s.newValue2(ssaop.OpIsSliceInBounds, types.Types[types.TBOOL], idx, len)
  5602  	}
  5603  	b := s.endBlock()
  5604  	b.Kind = block.BlockIf
  5605  	b.SetControl(cmp)
  5606  	b.Likely = ssa.BranchLikely
  5607  	b.AddEdgeTo(bNext)
  5608  	b.AddEdgeTo(bPanic)
  5609  
  5610  	s.startBlock(bPanic)
  5611  	if Arch.LinkArch.Family == sys.Wasm {
  5612  		// TODO(khr): figure out how to do "register" based calling convention for bounds checks.
  5613  		// Should be similar to gcWriteBarrier, but I can't make it work.
  5614  		s.rtcall(BoundsCheckFunc[kind], false, nil, idx, len)
  5615  	} else {
  5616  		mem := s.newValue3I(ssaop.OpPanicBounds, types.TypeMem, int64(kind), idx, len, s.mem())
  5617  		s.endBlock().SetControl(mem)
  5618  	}
  5619  	s.startBlock(bNext)
  5620  
  5621  	// In Spectre index mode, apply an appropriate mask to avoid speculative out-of-bounds accesses.
  5622  	if base.Flag.Cfg.SpectreIndex {
  5623  		op := ssaop.OpSpectreIndex
  5624  		if kind != ssa.BoundsIndex && kind != ssa.BoundsIndexU {
  5625  			op = ssaop.OpSpectreSliceIndex
  5626  		}
  5627  		idx = s.newValue2(op, types.Types[types.TINT], idx, len)
  5628  	}
  5629  
  5630  	return idx
  5631  }
  5632  
  5633  // If cmp (a bool) is false, panic using the given function.
  5634  func (s *state) check(cmp *ssa.Value, fn *obj.LSym) {
  5635  	b := s.endBlock()
  5636  	b.Kind = block.BlockIf
  5637  	b.SetControl(cmp)
  5638  	b.Likely = ssa.BranchLikely
  5639  	bNext := s.f.NewBlock(block.BlockPlain)
  5640  	line := s.peekPos()
  5641  	pos := base.Ctxt.PosTable.Pos(line)
  5642  	fl := funcLine{f: fn, base: pos.Base(), line: pos.Line()}
  5643  	bPanic := s.panics[fl]
  5644  	if bPanic == nil {
  5645  		bPanic = s.f.NewBlock(block.BlockPlain)
  5646  		s.panics[fl] = bPanic
  5647  		s.startBlock(bPanic)
  5648  		// The panic call takes/returns memory to ensure that the right
  5649  		// memory state is observed if the panic happens.
  5650  		s.rtcall(fn, false, nil)
  5651  	}
  5652  	b.AddEdgeTo(bNext)
  5653  	b.AddEdgeTo(bPanic)
  5654  	s.startBlock(bNext)
  5655  }
  5656  
  5657  func (s *state) intDivide(n ir.Node, a, b *ssa.Value) *ssa.Value {
  5658  	needcheck := true
  5659  	switch b.Op {
  5660  	case ssaop.OpConst8, ssaop.OpConst16, ssaop.OpConst32, ssaop.OpConst64:
  5661  		if b.AuxInt != 0 {
  5662  			needcheck = false
  5663  		}
  5664  	}
  5665  	if needcheck {
  5666  		// do a size-appropriate check for zero
  5667  		cmp := s.newValue2(s.ssaOp(ir.ONE, n.Type()), types.Types[types.TBOOL], b, s.zeroVal(n.Type()))
  5668  		s.check(cmp, ir.Syms.Panicdivide)
  5669  	}
  5670  	return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
  5671  }
  5672  
  5673  // rtcall issues a call to the given runtime function fn with the listed args.
  5674  // Returns a slice of results of the given result types.
  5675  // The call is added to the end of the current block.
  5676  // If returns is false, the block is marked as an exit block.
  5677  func (s *state) rtcall(fn *obj.LSym, returns bool, results []*types.Type, args ...*ssa.Value) []*ssa.Value {
  5678  	s.prevCall = nil
  5679  	// Write args to the stack
  5680  	off := base.Ctxt.Arch.FixedFrameSize
  5681  	var callArgs []*ssa.Value
  5682  	var callArgTypes []*types.Type
  5683  
  5684  	for _, arg := range args {
  5685  		t := arg.Type
  5686  		off = types.RoundUp(off, t.Alignment())
  5687  		size := t.Size()
  5688  		callArgs = append(callArgs, arg)
  5689  		callArgTypes = append(callArgTypes, t)
  5690  		off += size
  5691  	}
  5692  	off = types.RoundUp(off, int64(types.RegSize))
  5693  
  5694  	// Issue call
  5695  	var call *ssa.Value
  5696  	aux := ssa.StaticAuxCall(fn, s.f.ABIDefault.ABIAnalyzeTypes(callArgTypes, results))
  5697  	callArgs = append(callArgs, s.mem())
  5698  	call = s.newValue0A(ssaop.OpStaticLECall, aux.LateExpansionResultType(), aux)
  5699  	call.AddArgs(callArgs...)
  5700  	s.vars[memVar] = s.newValue1I(ssaop.OpSelectN, types.TypeMem, int64(len(results)), call)
  5701  
  5702  	if !returns {
  5703  		// Finish block
  5704  		b := s.endBlock()
  5705  		b.Kind = block.BlockExit
  5706  		b.SetControl(call)
  5707  		call.AuxInt = off - base.Ctxt.Arch.FixedFrameSize
  5708  		if len(results) > 0 {
  5709  			s.Fatalf("panic call can't have results")
  5710  		}
  5711  		return nil
  5712  	}
  5713  
  5714  	// Load results
  5715  	res := make([]*ssa.Value, len(results))
  5716  	for i, t := range results {
  5717  		off = types.RoundUp(off, t.Alignment())
  5718  		res[i] = s.resultOfCall(call, int64(i), t)
  5719  		off += t.Size()
  5720  	}
  5721  	off = types.RoundUp(off, int64(types.PtrSize))
  5722  
  5723  	// Remember how much callee stack space we needed.
  5724  	call.AuxInt = off
  5725  
  5726  	return res
  5727  }
  5728  
  5729  // do *left = right for type t.
  5730  func (s *state) storeType(t *types.Type, left, right *ssa.Value, skip skipMask, leftIsStmt bool) {
  5731  	s.instrument(t, left, instrumentWrite)
  5732  
  5733  	if skip == 0 && (!t.HasPointers() || ssa.IsStackAddr(left)) {
  5734  		// Known to not have write barrier. Store the whole type.
  5735  		s.vars[memVar] = s.newValue3Apos(ssaop.OpStore, types.TypeMem, t, left, right, s.mem(), leftIsStmt)
  5736  		return
  5737  	}
  5738  
  5739  	// store scalar fields first, so write barrier stores for
  5740  	// pointer fields can be grouped together, and scalar values
  5741  	// don't need to be live across the write barrier call.
  5742  	// TODO: if the writebarrier pass knows how to reorder stores,
  5743  	// we can do a single store here as long as skip==0.
  5744  	s.storeTypeScalars(t, left, right, skip)
  5745  	if skip&skipPtr == 0 && t.HasPointers() {
  5746  		s.storeTypePtrs(t, left, right)
  5747  	}
  5748  }
  5749  
  5750  // do *left = right for all scalar (non-pointer) parts of t.
  5751  func (s *state) storeTypeScalars(t *types.Type, left, right *ssa.Value, skip skipMask) {
  5752  	switch {
  5753  	case t.IsBoolean() || t.IsInteger() || t.IsFloat() || t.IsComplex() || t.IsSIMD():
  5754  		s.store(t, left, right)
  5755  	case t.IsPtrShaped():
  5756  		if t.IsPtr() && t.Elem().NotInHeap() {
  5757  			s.store(t, left, right) // see issue 42032
  5758  		}
  5759  		// otherwise, no scalar fields.
  5760  	case t.IsString():
  5761  		if skip&skipLen != 0 {
  5762  			return
  5763  		}
  5764  		len := s.newValue1(ssaop.OpStringLen, types.Types[types.TINT], right)
  5765  		lenAddr := s.newValue1I(ssaop.OpOffPtr, s.f.Config.Types.IntPtr, s.config.PtrSize, left)
  5766  		s.store(types.Types[types.TINT], lenAddr, len)
  5767  	case t.IsSlice():
  5768  		if skip&skipLen == 0 {
  5769  			len := s.newValue1(ssaop.OpSliceLen, types.Types[types.TINT], right)
  5770  			lenAddr := s.newValue1I(ssaop.OpOffPtr, s.f.Config.Types.IntPtr, s.config.PtrSize, left)
  5771  			s.store(types.Types[types.TINT], lenAddr, len)
  5772  		}
  5773  		if skip&skipCap == 0 {
  5774  			cap := s.newValue1(ssaop.OpSliceCap, types.Types[types.TINT], right)
  5775  			capAddr := s.newValue1I(ssaop.OpOffPtr, s.f.Config.Types.IntPtr, 2*s.config.PtrSize, left)
  5776  			s.store(types.Types[types.TINT], capAddr, cap)
  5777  		}
  5778  	case t.IsInterface():
  5779  		// itab field doesn't need a write barrier (even though it is a pointer).
  5780  		itab := s.newValue1(ssaop.OpITab, s.f.Config.Types.BytePtr, right)
  5781  		s.store(types.Types[types.TUINTPTR], left, itab)
  5782  	case isStructNotSIMD(t):
  5783  		n := t.NumFields()
  5784  		for i := 0; i < n; i++ {
  5785  			ft := t.FieldType(i)
  5786  			addr := s.newValue1I(ssaop.OpOffPtr, ft.PtrTo(), t.FieldOff(i), left)
  5787  			val := s.newValue1I(ssaop.OpStructSelect, ft, int64(i), right)
  5788  			s.storeTypeScalars(ft, addr, val, 0)
  5789  		}
  5790  	case t.IsArray() && t.Size() == 0:
  5791  		// nothing
  5792  	case t.IsArray() && t.NumElem() == 1:
  5793  		s.storeTypeScalars(t.Elem(), left, s.newValue1I(ssaop.OpArraySelect, t.Elem(), 0, right), 0)
  5794  	default:
  5795  		s.Fatalf("bad write barrier type %v", t)
  5796  	}
  5797  }
  5798  
  5799  // do *left = right for all pointer parts of t.
  5800  func (s *state) storeTypePtrs(t *types.Type, left, right *ssa.Value) {
  5801  	switch {
  5802  	case t.IsPtrShaped():
  5803  		if t.IsPtr() && t.Elem().NotInHeap() {
  5804  			break // see issue 42032
  5805  		}
  5806  		s.store(t, left, right)
  5807  	case t.IsString():
  5808  		ptr := s.newValue1(ssaop.OpStringPtr, s.f.Config.Types.BytePtr, right)
  5809  		s.store(s.f.Config.Types.BytePtr, left, ptr)
  5810  	case t.IsSlice():
  5811  		elType := types.NewPtr(t.Elem())
  5812  		ptr := s.newValue1(ssaop.OpSlicePtr, elType, right)
  5813  		s.store(elType, left, ptr)
  5814  	case t.IsInterface():
  5815  		// itab field is treated as a scalar.
  5816  		idata := s.newValue1(ssaop.OpIData, s.f.Config.Types.BytePtr, right)
  5817  		idataAddr := s.newValue1I(ssaop.OpOffPtr, s.f.Config.Types.BytePtrPtr, s.config.PtrSize, left)
  5818  		s.store(s.f.Config.Types.BytePtr, idataAddr, idata)
  5819  	case isStructNotSIMD(t):
  5820  		n := t.NumFields()
  5821  		for i := 0; i < n; i++ {
  5822  			ft := t.FieldType(i)
  5823  			if !ft.HasPointers() {
  5824  				continue
  5825  			}
  5826  			addr := s.newValue1I(ssaop.OpOffPtr, ft.PtrTo(), t.FieldOff(i), left)
  5827  			val := s.newValue1I(ssaop.OpStructSelect, ft, int64(i), right)
  5828  			s.storeTypePtrs(ft, addr, val)
  5829  		}
  5830  	case t.IsArray() && t.Size() == 0:
  5831  		// nothing
  5832  	case t.IsArray() && t.NumElem() == 1:
  5833  		s.storeTypePtrs(t.Elem(), left, s.newValue1I(ssaop.OpArraySelect, t.Elem(), 0, right))
  5834  	default:
  5835  		s.Fatalf("bad write barrier type %v", t)
  5836  	}
  5837  }
  5838  
  5839  // putArg evaluates n for the purpose of passing it as an argument to a function and returns the value for the call.
  5840  func (s *state) putArg(n ir.Node, t *types.Type) *ssa.Value {
  5841  	var a *ssa.Value
  5842  	if !ssa.CanSSA(t) {
  5843  		a = s.newValue2(ssaop.OpDereference, t, s.addr(n), s.mem())
  5844  	} else {
  5845  		a = s.expr(n)
  5846  	}
  5847  	return a
  5848  }
  5849  
  5850  // slice computes the slice v[i:j:k] and returns ptr, len, and cap of result.
  5851  // i,j,k may be nil, in which case they are set to their default value.
  5852  // v may be a slice, string or pointer to an array.
  5853  func (s *state) slice(v, i, j, k *ssa.Value, bounded bool) (p, l, c *ssa.Value) {
  5854  	t := v.Type
  5855  	var ptr, len, cap *ssa.Value
  5856  	switch {
  5857  	case t.IsSlice():
  5858  		ptr = s.newValue1(ssaop.OpSlicePtr, types.NewPtr(t.Elem()), v)
  5859  		len = s.newValue1(ssaop.OpSliceLen, types.Types[types.TINT], v)
  5860  		cap = s.newValue1(ssaop.OpSliceCap, types.Types[types.TINT], v)
  5861  	case t.IsString():
  5862  		ptr = s.newValue1(ssaop.OpStringPtr, types.NewPtr(types.Types[types.TUINT8]), v)
  5863  		len = s.newValue1(ssaop.OpStringLen, types.Types[types.TINT], v)
  5864  		cap = len
  5865  	case t.IsPtr():
  5866  		if !t.Elem().IsArray() {
  5867  			s.Fatalf("bad ptr to array in slice %v\n", t)
  5868  		}
  5869  		nv := s.nilCheck(v)
  5870  		ptr = s.newValue1(ssaop.OpCopy, types.NewPtr(t.Elem().Elem()), nv)
  5871  		len = s.constInt(types.Types[types.TINT], t.Elem().NumElem())
  5872  		cap = len
  5873  	default:
  5874  		s.Fatalf("bad type in slice %v\n", t)
  5875  	}
  5876  
  5877  	// Set default values
  5878  	if i == nil {
  5879  		i = s.constInt(types.Types[types.TINT], 0)
  5880  	}
  5881  	if j == nil {
  5882  		j = len
  5883  	}
  5884  	three := true
  5885  	if k == nil {
  5886  		three = false
  5887  		k = cap
  5888  	}
  5889  
  5890  	// Panic if slice indices are not in bounds.
  5891  	// Make sure we check these in reverse order so that we're always
  5892  	// comparing against a value known to be nonnegative. See issue 28797.
  5893  	if three {
  5894  		if k != cap {
  5895  			kind := ssa.BoundsSlice3Alen
  5896  			if t.IsSlice() {
  5897  				kind = ssa.BoundsSlice3Acap
  5898  			}
  5899  			k = s.boundsCheck(k, cap, kind, bounded)
  5900  		}
  5901  		if j != k {
  5902  			j = s.boundsCheck(j, k, ssa.BoundsSlice3B, bounded)
  5903  		}
  5904  		i = s.boundsCheck(i, j, ssa.BoundsSlice3C, bounded)
  5905  	} else {
  5906  		if j != k {
  5907  			kind := ssa.BoundsSliceAlen
  5908  			if t.IsSlice() {
  5909  				kind = ssa.BoundsSliceAcap
  5910  			}
  5911  			j = s.boundsCheck(j, k, kind, bounded)
  5912  		}
  5913  		i = s.boundsCheck(i, j, ssa.BoundsSliceB, bounded)
  5914  	}
  5915  
  5916  	// Word-sized integer operations.
  5917  	subOp := s.ssaOp(ir.OSUB, types.Types[types.TINT])
  5918  	mulOp := s.ssaOp(ir.OMUL, types.Types[types.TINT])
  5919  	andOp := s.ssaOp(ir.OAND, types.Types[types.TINT])
  5920  
  5921  	// Calculate the length (rlen) and capacity (rcap) of the new slice.
  5922  	// For strings the capacity of the result is unimportant. However,
  5923  	// we use rcap to test if we've generated a zero-length slice.
  5924  	// Use length of strings for that.
  5925  	rlen := s.newValue2(subOp, types.Types[types.TINT], j, i)
  5926  	rcap := rlen
  5927  	if j != k && !t.IsString() {
  5928  		rcap = s.newValue2(subOp, types.Types[types.TINT], k, i)
  5929  	}
  5930  
  5931  	if (i.Op == ssaop.OpConst64 || i.Op == ssaop.OpConst32) && i.AuxInt == 0 {
  5932  		// No pointer arithmetic necessary.
  5933  		return ptr, rlen, rcap
  5934  	}
  5935  
  5936  	// Calculate the base pointer (rptr) for the new slice.
  5937  	//
  5938  	// Generate the following code assuming that indexes are in bounds.
  5939  	// The masking is to make sure that we don't generate a slice
  5940  	// that points to the next object in memory. We cannot just set
  5941  	// the pointer to nil because then we would create a nil slice or
  5942  	// string.
  5943  	//
  5944  	//     rcap = k - i
  5945  	//     rlen = j - i
  5946  	//     rptr = ptr + (mask(rcap) & (i * stride))
  5947  	//
  5948  	// Where mask(x) is 0 if x==0 and -1 if x>0 and stride is the width
  5949  	// of the element type.
  5950  	stride := s.constInt(types.Types[types.TINT], ptr.Type.Elem().Size())
  5951  
  5952  	// The delta is the number of bytes to offset ptr by.
  5953  	delta := s.newValue2(mulOp, types.Types[types.TINT], i, stride)
  5954  
  5955  	// If we're slicing to the point where the capacity is zero,
  5956  	// zero out the delta.
  5957  	mask := s.newValue1(ssaop.OpSlicemask, types.Types[types.TINT], rcap)
  5958  	delta = s.newValue2(andOp, types.Types[types.TINT], delta, mask)
  5959  
  5960  	// Compute rptr = ptr + delta.
  5961  	rptr := s.newValue2(ssaop.OpAddPtr, ptr.Type, ptr, delta)
  5962  
  5963  	return rptr, rlen, rcap
  5964  }
  5965  
  5966  type u642fcvtTab struct {
  5967  	leq, cvt2F, and, rsh, or, add ssaop.Op
  5968  	one                           func(*state, *types.Type, int64) *ssa.Value
  5969  }
  5970  
  5971  var u64_f64 = u642fcvtTab{
  5972  	leq:   ssaop.OpLeq64,
  5973  	cvt2F: ssaop.OpCvt64to64F,
  5974  	and:   ssaop.OpAnd64,
  5975  	rsh:   ssaop.OpRsh64Ux64,
  5976  	or:    ssaop.OpOr64,
  5977  	add:   ssaop.OpAdd64F,
  5978  	one:   (*state).constInt64,
  5979  }
  5980  
  5981  var u64_f32 = u642fcvtTab{
  5982  	leq:   ssaop.OpLeq64,
  5983  	cvt2F: ssaop.OpCvt64to32F,
  5984  	and:   ssaop.OpAnd64,
  5985  	rsh:   ssaop.OpRsh64Ux64,
  5986  	or:    ssaop.OpOr64,
  5987  	add:   ssaop.OpAdd32F,
  5988  	one:   (*state).constInt64,
  5989  }
  5990  
  5991  func (s *state) uint64Tofloat64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  5992  	return s.uint64Tofloat(&u64_f64, n, x, ft, tt)
  5993  }
  5994  
  5995  func (s *state) uint64Tofloat32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  5996  	return s.uint64Tofloat(&u64_f32, n, x, ft, tt)
  5997  }
  5998  
  5999  func (s *state) uint64Tofloat(cvttab *u642fcvtTab, n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  6000  	// if x >= 0 {
  6001  	//    result = (floatY) x
  6002  	// } else {
  6003  	// 	  y = uintX(x) ; y = x & 1
  6004  	// 	  z = uintX(x) ; z = z >> 1
  6005  	// 	  z = z | y
  6006  	// 	  result = floatY(z)
  6007  	// 	  result = result + result
  6008  	// }
  6009  	//
  6010  	// Code borrowed from old code generator.
  6011  	// What's going on: large 64-bit "unsigned" looks like
  6012  	// negative number to hardware's integer-to-float
  6013  	// conversion. However, because the mantissa is only
  6014  	// 63 bits, we don't need the LSB, so instead we do an
  6015  	// unsigned right shift (divide by two), convert, and
  6016  	// double. However, before we do that, we need to be
  6017  	// sure that we do not lose a "1" if that made the
  6018  	// difference in the resulting rounding. Therefore, we
  6019  	// preserve it, and OR (not ADD) it back in. The case
  6020  	// that matters is when the eleven discarded bits are
  6021  	// equal to 10000000001; that rounds up, and the 1 cannot
  6022  	// be lost else it would round down if the LSB of the
  6023  	// candidate mantissa is 0.
  6024  
  6025  	cmp := s.newValue2(cvttab.leq, types.Types[types.TBOOL], s.zeroVal(ft), x)
  6026  
  6027  	b := s.endBlock()
  6028  	b.Kind = block.BlockIf
  6029  	b.SetControl(cmp)
  6030  	b.Likely = ssa.BranchLikely
  6031  
  6032  	bThen := s.f.NewBlock(block.BlockPlain)
  6033  	bElse := s.f.NewBlock(block.BlockPlain)
  6034  	bAfter := s.f.NewBlock(block.BlockPlain)
  6035  
  6036  	b.AddEdgeTo(bThen)
  6037  	s.startBlock(bThen)
  6038  	a0 := s.newValue1(cvttab.cvt2F, tt, x)
  6039  	s.vars[n] = a0
  6040  	s.endBlock()
  6041  	bThen.AddEdgeTo(bAfter)
  6042  
  6043  	b.AddEdgeTo(bElse)
  6044  	s.startBlock(bElse)
  6045  	one := cvttab.one(s, ft, 1)
  6046  	y := s.newValue2(cvttab.and, ft, x, one)
  6047  	z := s.newValue2(cvttab.rsh, ft, x, one)
  6048  	z = s.newValue2(cvttab.or, ft, z, y)
  6049  	a := s.newValue1(cvttab.cvt2F, tt, z)
  6050  	a1 := s.newValue2(cvttab.add, tt, a, a)
  6051  	s.vars[n] = a1
  6052  	s.endBlock()
  6053  	bElse.AddEdgeTo(bAfter)
  6054  
  6055  	s.startBlock(bAfter)
  6056  	return s.variable(n, n.Type())
  6057  }
  6058  
  6059  type u322fcvtTab struct {
  6060  	cvtI2F, cvtF2F ssaop.Op
  6061  }
  6062  
  6063  var u32_f64 = u322fcvtTab{
  6064  	cvtI2F: ssaop.OpCvt32to64F,
  6065  	cvtF2F: ssaop.OpCopy,
  6066  }
  6067  
  6068  var u32_f32 = u322fcvtTab{
  6069  	cvtI2F: ssaop.OpCvt32to32F,
  6070  	cvtF2F: ssaop.OpCvt64Fto32F,
  6071  }
  6072  
  6073  func (s *state) uint32Tofloat64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  6074  	return s.uint32Tofloat(&u32_f64, n, x, ft, tt)
  6075  }
  6076  
  6077  func (s *state) uint32Tofloat32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  6078  	return s.uint32Tofloat(&u32_f32, n, x, ft, tt)
  6079  }
  6080  
  6081  func (s *state) uint32Tofloat(cvttab *u322fcvtTab, n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  6082  	// if x >= 0 {
  6083  	// 	result = floatY(x)
  6084  	// } else {
  6085  	// 	result = floatY(float64(x) + (1<<32))
  6086  	// }
  6087  	cmp := s.newValue2(ssaop.OpLeq32, types.Types[types.TBOOL], s.zeroVal(ft), x)
  6088  	b := s.endBlock()
  6089  	b.Kind = block.BlockIf
  6090  	b.SetControl(cmp)
  6091  	b.Likely = ssa.BranchLikely
  6092  
  6093  	bThen := s.f.NewBlock(block.BlockPlain)
  6094  	bElse := s.f.NewBlock(block.BlockPlain)
  6095  	bAfter := s.f.NewBlock(block.BlockPlain)
  6096  
  6097  	b.AddEdgeTo(bThen)
  6098  	s.startBlock(bThen)
  6099  	a0 := s.newValue1(cvttab.cvtI2F, tt, x)
  6100  	s.vars[n] = a0
  6101  	s.endBlock()
  6102  	bThen.AddEdgeTo(bAfter)
  6103  
  6104  	b.AddEdgeTo(bElse)
  6105  	s.startBlock(bElse)
  6106  	a1 := s.newValue1(ssaop.OpCvt32to64F, types.Types[types.TFLOAT64], x)
  6107  	twoToThe32 := s.constFloat64(types.Types[types.TFLOAT64], float64(1<<32))
  6108  	a2 := s.newValue2(ssaop.OpAdd64F, types.Types[types.TFLOAT64], a1, twoToThe32)
  6109  	a3 := s.newValue1(cvttab.cvtF2F, tt, a2)
  6110  
  6111  	s.vars[n] = a3
  6112  	s.endBlock()
  6113  	bElse.AddEdgeTo(bAfter)
  6114  
  6115  	s.startBlock(bAfter)
  6116  	return s.variable(n, n.Type())
  6117  }
  6118  
  6119  // referenceTypeBuiltin generates code for the len/cap builtins for maps and channels.
  6120  func (s *state) referenceTypeBuiltin(n *ir.UnaryExpr, x *ssa.Value) *ssa.Value {
  6121  	if !n.X.Type().IsMap() && !n.X.Type().IsChan() {
  6122  		s.Fatalf("node must be a map or a channel")
  6123  	}
  6124  	if n.X.Type().IsChan() && n.Op() == ir.OLEN {
  6125  		s.Fatalf("cannot inline len(chan)") // must use runtime.chanlen now
  6126  	}
  6127  	if n.X.Type().IsChan() && n.Op() == ir.OCAP {
  6128  		s.Fatalf("cannot inline cap(chan)") // must use runtime.chancap now
  6129  	}
  6130  	if n.X.Type().IsMap() && n.Op() == ir.OCAP {
  6131  		s.Fatalf("cannot inline cap(map)") // cap(map) does not exist
  6132  	}
  6133  	// if n == nil {
  6134  	//   return 0
  6135  	// } else {
  6136  	//   // len, the actual loadType depends
  6137  	//   return int(*((*loadType)n))
  6138  	//   // cap (chan only, not used for now)
  6139  	//   return *(((*int)n)+1)
  6140  	// }
  6141  	lenType := n.Type()
  6142  	nilValue := s.constNil(types.Types[types.TUINTPTR])
  6143  	cmp := s.newValue2(ssaop.OpEqPtr, types.Types[types.TBOOL], x, nilValue)
  6144  	b := s.endBlock()
  6145  	b.Kind = block.BlockIf
  6146  	b.SetControl(cmp)
  6147  	b.Likely = ssa.BranchUnlikely
  6148  
  6149  	bThen := s.f.NewBlock(block.BlockPlain)
  6150  	bElse := s.f.NewBlock(block.BlockPlain)
  6151  	bAfter := s.f.NewBlock(block.BlockPlain)
  6152  
  6153  	// length/capacity of a nil map/chan is zero
  6154  	b.AddEdgeTo(bThen)
  6155  	s.startBlock(bThen)
  6156  	s.vars[n] = s.zeroVal(lenType)
  6157  	s.endBlock()
  6158  	bThen.AddEdgeTo(bAfter)
  6159  
  6160  	b.AddEdgeTo(bElse)
  6161  	s.startBlock(bElse)
  6162  	switch n.Op() {
  6163  	case ir.OLEN:
  6164  		if n.X.Type().IsMap() {
  6165  			// length is stored in the first word, but needs conversion to int.
  6166  			loadType := reflectdata.MapType().Field(0).Type // uint64
  6167  			load := s.load(loadType, x)
  6168  			s.vars[n] = s.conv(nil, load, loadType, lenType) // integer conversion doesn't need Node
  6169  		} else {
  6170  			// length is stored in the first word for chan, no conversion needed.
  6171  			s.vars[n] = s.load(lenType, x)
  6172  		}
  6173  	case ir.OCAP:
  6174  		// capacity is stored in the second word for chan
  6175  		sw := s.newValue1I(ssaop.OpOffPtr, lenType.PtrTo(), lenType.Size(), x)
  6176  		s.vars[n] = s.load(lenType, sw)
  6177  	default:
  6178  		s.Fatalf("op must be OLEN or OCAP")
  6179  	}
  6180  	s.endBlock()
  6181  	bElse.AddEdgeTo(bAfter)
  6182  
  6183  	s.startBlock(bAfter)
  6184  	return s.variable(n, lenType)
  6185  }
  6186  
  6187  type f2uCvtTab struct {
  6188  	ltf, cvt2U, subf, or ssaop.Op
  6189  	floatValue           func(*state, *types.Type, float64) *ssa.Value
  6190  	intValue             func(*state, *types.Type, int64) *ssa.Value
  6191  	cutoff               uint64
  6192  }
  6193  
  6194  var f32_u64 = f2uCvtTab{
  6195  	ltf:        ssaop.OpLess32F,
  6196  	cvt2U:      ssaop.OpCvt32Fto64,
  6197  	subf:       ssaop.OpSub32F,
  6198  	or:         ssaop.OpOr64,
  6199  	floatValue: (*state).constFloat32,
  6200  	intValue:   (*state).constInt64,
  6201  	cutoff:     1 << 63,
  6202  }
  6203  
  6204  var f64_u64 = f2uCvtTab{
  6205  	ltf:        ssaop.OpLess64F,
  6206  	cvt2U:      ssaop.OpCvt64Fto64,
  6207  	subf:       ssaop.OpSub64F,
  6208  	or:         ssaop.OpOr64,
  6209  	floatValue: (*state).constFloat64,
  6210  	intValue:   (*state).constInt64,
  6211  	cutoff:     1 << 63,
  6212  }
  6213  
  6214  var f32_u32 = f2uCvtTab{
  6215  	ltf:        ssaop.OpLess32F,
  6216  	cvt2U:      ssaop.OpCvt32Fto32,
  6217  	subf:       ssaop.OpSub32F,
  6218  	or:         ssaop.OpOr32,
  6219  	floatValue: (*state).constFloat32,
  6220  	intValue:   func(s *state, t *types.Type, v int64) *ssa.Value { return s.constInt32(t, int32(v)) },
  6221  	cutoff:     1 << 31,
  6222  }
  6223  
  6224  var f64_u32 = f2uCvtTab{
  6225  	ltf:        ssaop.OpLess64F,
  6226  	cvt2U:      ssaop.OpCvt64Fto32,
  6227  	subf:       ssaop.OpSub64F,
  6228  	or:         ssaop.OpOr32,
  6229  	floatValue: (*state).constFloat64,
  6230  	intValue:   func(s *state, t *types.Type, v int64) *ssa.Value { return s.constInt32(t, int32(v)) },
  6231  	cutoff:     1 << 31,
  6232  }
  6233  
  6234  func (s *state) float32ToUint64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  6235  	return s.floatToUint(&f32_u64, n, x, ft, tt)
  6236  }
  6237  func (s *state) float64ToUint64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  6238  	return s.floatToUint(&f64_u64, n, x, ft, tt)
  6239  }
  6240  
  6241  func (s *state) float32ToUint32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  6242  	return s.floatToUint(&f32_u32, n, x, ft, tt)
  6243  }
  6244  
  6245  func (s *state) float64ToUint32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  6246  	return s.floatToUint(&f64_u32, n, x, ft, tt)
  6247  }
  6248  
  6249  func (s *state) floatToUint(cvttab *f2uCvtTab, n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
  6250  	// cutoff:=1<<(intY_Size-1)
  6251  	// if x < floatX(cutoff) {
  6252  	// 	result = uintY(x) // bThen
  6253  	//  // gated by ConvertHash, clamp negative inputs to zero
  6254  	// 	if x < 0 { // unlikely
  6255  	// 		result = 0 // bZero
  6256  	// 	}
  6257  	// } else {
  6258  	// 	y = x - floatX(cutoff) // bElse
  6259  	// 	z = uintY(y)
  6260  	// 	result = z | -(cutoff)
  6261  	// }
  6262  
  6263  	cutoff := cvttab.floatValue(s, ft, float64(cvttab.cutoff))
  6264  	cmp := s.newValueOrSfCall2(cvttab.ltf, types.Types[types.TBOOL], x, cutoff)
  6265  	b := s.endBlock()
  6266  	b.Kind = block.BlockIf
  6267  	b.SetControl(cmp)
  6268  	b.Likely = ssa.BranchLikely
  6269  
  6270  	var bThen, bZero *ssa.Block
  6271  	// use salted hash to distinguish unsigned convert at a Pos from signed convert at a Pos
  6272  	newConversion := base.ConvertHash.MatchPosWithInfo(n.Pos(), "U", nil)
  6273  	if newConversion {
  6274  		bZero = s.f.NewBlock(block.BlockPlain)
  6275  		bThen = s.f.NewBlock(block.BlockIf)
  6276  	} else {
  6277  		bThen = s.f.NewBlock(block.BlockPlain)
  6278  	}
  6279  
  6280  	bElse := s.f.NewBlock(block.BlockPlain)
  6281  	bAfter := s.f.NewBlock(block.BlockPlain)
  6282  
  6283  	b.AddEdgeTo(bThen)
  6284  	s.startBlock(bThen)
  6285  	a0 := s.newValueOrSfCall1(cvttab.cvt2U, tt, x)
  6286  	s.vars[n] = a0
  6287  
  6288  	if newConversion {
  6289  		cmpz := s.newValueOrSfCall2(cvttab.ltf, types.Types[types.TBOOL], x, cvttab.floatValue(s, ft, 0.0))
  6290  		s.endBlock()
  6291  		bThen.SetControl(cmpz)
  6292  		bThen.AddEdgeTo(bZero)
  6293  		bThen.Likely = ssa.BranchUnlikely
  6294  		bThen.AddEdgeTo(bAfter)
  6295  
  6296  		s.startBlock(bZero)
  6297  		s.vars[n] = cvttab.intValue(s, tt, 0)
  6298  		s.endBlock()
  6299  		bZero.AddEdgeTo(bAfter)
  6300  	} else {
  6301  		s.endBlock()
  6302  		bThen.AddEdgeTo(bAfter)
  6303  	}
  6304  
  6305  	b.AddEdgeTo(bElse)
  6306  	s.startBlock(bElse)
  6307  	y := s.newValueOrSfCall2(cvttab.subf, ft, x, cutoff)
  6308  	y = s.newValueOrSfCall1(cvttab.cvt2U, tt, y)
  6309  	z := cvttab.intValue(s, tt, int64(-cvttab.cutoff))
  6310  	a1 := s.newValue2(cvttab.or, tt, y, z)
  6311  	s.vars[n] = a1
  6312  	s.endBlock()
  6313  	bElse.AddEdgeTo(bAfter)
  6314  
  6315  	s.startBlock(bAfter)
  6316  	return s.variable(n, n.Type())
  6317  }
  6318  
  6319  // dottype generates SSA for a type assertion node.
  6320  // commaok indicates whether to panic or return a bool.
  6321  // If commaok is false, resok will be nil.
  6322  func (s *state) dottype(n *ir.TypeAssertExpr, commaok bool) (res, resok *ssa.Value) {
  6323  	iface := s.expr(n.X)              // input interface
  6324  	target := s.reflectType(n.Type()) // target type
  6325  	var targetItab *ssa.Value
  6326  	if n.ITab != nil {
  6327  		targetItab = s.expr(n.ITab)
  6328  	}
  6329  
  6330  	if n.UseNilPanic {
  6331  		if commaok {
  6332  			base.Fatalf("unexpected *ir.TypeAssertExpr with UseNilPanic == true && commaok == true")
  6333  		}
  6334  		if n.Type().IsInterface() {
  6335  			// Currently we do not expect the compiler to emit type assertions with UseNilPanic, that asserts to an interface type.
  6336  			// If needed, this can be relaxed in the future, but for now we can't assert that.
  6337  			base.Fatalf("unexpected *ir.TypeAssertExpr with UseNilPanic == true && Type().IsInterface() == true")
  6338  		}
  6339  		typs := s.f.Config.Types
  6340  		iface = s.newValue2(
  6341  			ssaop.OpIMake,
  6342  			iface.Type,
  6343  			s.nilCheck(s.newValue1(ssaop.OpITab, typs.BytePtr, iface)),
  6344  			s.newValue1(ssaop.OpIData, typs.BytePtr, iface),
  6345  		)
  6346  	}
  6347  
  6348  	return s.dottype1(n.Pos(), n.X.Type(), n.Type(), iface, nil, target, targetItab, commaok, n.Descriptor)
  6349  }
  6350  
  6351  func (s *state) dynamicDottype(n *ir.DynamicTypeAssertExpr, commaok bool) (res, resok *ssa.Value) {
  6352  	iface := s.expr(n.X)
  6353  	var source, target, targetItab *ssa.Value
  6354  	if n.SrcRType != nil {
  6355  		source = s.expr(n.SrcRType)
  6356  	}
  6357  	if !n.X.Type().IsEmptyInterface() && !n.Type().IsInterface() {
  6358  		byteptr := s.f.Config.Types.BytePtr
  6359  		targetItab = s.expr(n.ITab)
  6360  		// TODO(mdempsky): Investigate whether compiling n.RType could be
  6361  		// better than loading itab.typ.
  6362  		target = s.load(byteptr, s.newValue1I(ssaop.OpOffPtr, byteptr, rttype.ITab.OffsetOf("Type"), targetItab))
  6363  	} else {
  6364  		target = s.expr(n.RType)
  6365  	}
  6366  	return s.dottype1(n.Pos(), n.X.Type(), n.Type(), iface, source, target, targetItab, commaok, nil)
  6367  }
  6368  
  6369  // dottype1 implements a x.(T) operation. iface is the argument (x), dst is the type we're asserting to (T)
  6370  // and src is the type we're asserting from.
  6371  // source is the *runtime._type of src
  6372  // target is the *runtime._type of dst.
  6373  // If src is a nonempty interface and dst is not an interface, targetItab is an itab representing (dst, src). Otherwise it is nil.
  6374  // commaok is true if the caller wants a boolean success value. Otherwise, the generated code panics if the conversion fails.
  6375  // descriptor is a compiler-allocated internal/abi.TypeAssert whose address is passed to runtime.typeAssert when
  6376  // the target type is a compile-time-known non-empty interface. It may be nil.
  6377  func (s *state) dottype1(pos src.XPos, src, dst *types.Type, iface, source, target, targetItab *ssa.Value, commaok bool, descriptor *obj.LSym) (res, resok *ssa.Value) {
  6378  	typs := s.f.Config.Types
  6379  	byteptr := typs.BytePtr
  6380  	if dst.IsInterface() {
  6381  		if dst.IsEmptyInterface() {
  6382  			// Converting to an empty interface.
  6383  			// Input could be an empty or nonempty interface.
  6384  			if base.Debug.TypeAssert > 0 {
  6385  				base.WarnfAt(pos, "type assertion inlined")
  6386  			}
  6387  
  6388  			// Get itab/type field from input.
  6389  			itab := s.newValue1(ssaop.OpITab, byteptr, iface)
  6390  			// Conversion succeeds iff that field is not nil.
  6391  			cond := s.newValue2(ssaop.OpNeqPtr, types.Types[types.TBOOL], itab, s.constNil(byteptr))
  6392  
  6393  			if src.IsEmptyInterface() && commaok {
  6394  				// Converting empty interface to empty interface with ,ok is just a nil check.
  6395  				return iface, cond
  6396  			}
  6397  
  6398  			// Branch on nilness.
  6399  			b := s.endBlock()
  6400  			b.Kind = block.BlockIf
  6401  			b.SetControl(cond)
  6402  			b.Likely = ssa.BranchLikely
  6403  			bOk := s.f.NewBlock(block.BlockPlain)
  6404  			bFail := s.f.NewBlock(block.BlockPlain)
  6405  			b.AddEdgeTo(bOk)
  6406  			b.AddEdgeTo(bFail)
  6407  
  6408  			if !commaok {
  6409  				// On failure, panic by calling panicnildottype.
  6410  				s.startBlock(bFail)
  6411  				s.rtcall(ir.Syms.Panicnildottype, false, nil, target)
  6412  
  6413  				// On success, return (perhaps modified) input interface.
  6414  				s.startBlock(bOk)
  6415  				if src.IsEmptyInterface() {
  6416  					res = iface // Use input interface unchanged.
  6417  					return
  6418  				}
  6419  				// Load type out of itab, build interface with existing idata.
  6420  				off := s.newValue1I(ssaop.OpOffPtr, byteptr, rttype.ITab.OffsetOf("Type"), itab)
  6421  				typ := s.load(byteptr, off)
  6422  				idata := s.newValue1(ssaop.OpIData, byteptr, iface)
  6423  				res = s.newValue2(ssaop.OpIMake, dst, typ, idata)
  6424  				return
  6425  			}
  6426  
  6427  			s.startBlock(bOk)
  6428  			// nonempty -> empty
  6429  			// Need to load type from itab
  6430  			off := s.newValue1I(ssaop.OpOffPtr, byteptr, rttype.ITab.OffsetOf("Type"), itab)
  6431  			s.vars[typVar] = s.load(byteptr, off)
  6432  			s.endBlock()
  6433  
  6434  			// itab is nil, might as well use that as the nil result.
  6435  			s.startBlock(bFail)
  6436  			s.vars[typVar] = itab
  6437  			s.endBlock()
  6438  
  6439  			// Merge point.
  6440  			bEnd := s.f.NewBlock(block.BlockPlain)
  6441  			bOk.AddEdgeTo(bEnd)
  6442  			bFail.AddEdgeTo(bEnd)
  6443  			s.startBlock(bEnd)
  6444  			idata := s.newValue1(ssaop.OpIData, byteptr, iface)
  6445  			res = s.newValue2(ssaop.OpIMake, dst, s.variable(typVar, byteptr), idata)
  6446  			resok = cond
  6447  			delete(s.vars, typVar) // no practical effect, just to indicate typVar is no longer live.
  6448  			return
  6449  		}
  6450  		// converting to a nonempty interface needs a runtime call.
  6451  		if base.Debug.TypeAssert > 0 {
  6452  			base.WarnfAt(pos, "type assertion not inlined")
  6453  		}
  6454  
  6455  		itab := s.newValue1(ssaop.OpITab, byteptr, iface)
  6456  		data := s.newValue1(ssaop.OpIData, types.Types[types.TUNSAFEPTR], iface)
  6457  
  6458  		// First, check for nil.
  6459  		bNil := s.f.NewBlock(block.BlockPlain)
  6460  		bNonNil := s.f.NewBlock(block.BlockPlain)
  6461  		bMerge := s.f.NewBlock(block.BlockPlain)
  6462  		cond := s.newValue2(ssaop.OpNeqPtr, types.Types[types.TBOOL], itab, s.constNil(byteptr))
  6463  		b := s.endBlock()
  6464  		b.Kind = block.BlockIf
  6465  		b.SetControl(cond)
  6466  		b.Likely = ssa.BranchLikely
  6467  		b.AddEdgeTo(bNonNil)
  6468  		b.AddEdgeTo(bNil)
  6469  
  6470  		s.startBlock(bNil)
  6471  		if commaok {
  6472  			s.vars[typVar] = itab // which will be nil
  6473  			b := s.endBlock()
  6474  			b.AddEdgeTo(bMerge)
  6475  		} else {
  6476  			// Panic if input is nil.
  6477  			s.rtcall(ir.Syms.Panicnildottype, false, nil, target)
  6478  		}
  6479  
  6480  		// Get typ, possibly by loading out of itab.
  6481  		s.startBlock(bNonNil)
  6482  		typ := itab
  6483  		if !src.IsEmptyInterface() {
  6484  			typ = s.load(byteptr, s.newValue1I(ssaop.OpOffPtr, byteptr, rttype.ITab.OffsetOf("Type"), itab))
  6485  		}
  6486  
  6487  		// Check the cache first.
  6488  		var d *ssa.Value
  6489  		if descriptor != nil {
  6490  			d = s.newValue1A(ssaop.OpAddr, byteptr, descriptor, s.sb)
  6491  			if base.Flag.N == 0 && rtabi.UseInterfaceSwitchCache(Arch.LinkArch.Family) {
  6492  				// Note: we can only use the cache if we have the right atomic load instruction.
  6493  				// Double-check that here.
  6494  				if intrinsics.lookup(Arch.LinkArch.Arch, "internal/runtime/atomic", "Loadp") == nil {
  6495  					s.Fatalf("atomic load not available")
  6496  				}
  6497  				// Pick right size ops.
  6498  				var mul, and, add, zext ssaop.Op
  6499  				if s.config.PtrSize == 4 {
  6500  					mul = ssaop.OpMul32
  6501  					and = ssaop.OpAnd32
  6502  					add = ssaop.OpAdd32
  6503  					zext = ssaop.OpCopy
  6504  				} else {
  6505  					mul = ssaop.OpMul64
  6506  					and = ssaop.OpAnd64
  6507  					add = ssaop.OpAdd64
  6508  					zext = ssaop.OpZeroExt32to64
  6509  				}
  6510  
  6511  				loopHead := s.f.NewBlock(block.BlockPlain)
  6512  				loopBody := s.f.NewBlock(block.BlockPlain)
  6513  				cacheHit := s.f.NewBlock(block.BlockPlain)
  6514  				cacheMiss := s.f.NewBlock(block.BlockPlain)
  6515  
  6516  				// Load cache pointer out of descriptor, with an atomic load so
  6517  				// we ensure that we see a fully written cache.
  6518  				atomicLoad := s.newValue2(ssaop.OpAtomicLoadPtr, types.NewTuple(typs.BytePtr, types.TypeMem), d, s.mem())
  6519  				cache := s.newValue1(ssaop.OpSelect0, typs.BytePtr, atomicLoad)
  6520  				s.vars[memVar] = s.newValue1(ssaop.OpSelect1, types.TypeMem, atomicLoad)
  6521  
  6522  				// Load hash from type or itab.
  6523  				var hash *ssa.Value
  6524  				if src.IsEmptyInterface() {
  6525  					hash = s.newValue2(ssaop.OpLoad, typs.UInt32, s.newValue1I(ssaop.OpOffPtr, typs.UInt32Ptr, rttype.Type.OffsetOf("Hash"), typ), s.mem())
  6526  				} else {
  6527  					hash = s.newValue2(ssaop.OpLoad, typs.UInt32, s.newValue1I(ssaop.OpOffPtr, typs.UInt32Ptr, rttype.ITab.OffsetOf("Hash"), itab), s.mem())
  6528  				}
  6529  				hash = s.newValue1(zext, typs.Uintptr, hash)
  6530  				s.vars[hashVar] = hash
  6531  				// Load mask from cache.
  6532  				mask := s.newValue2(ssaop.OpLoad, typs.Uintptr, cache, s.mem())
  6533  				// Jump to loop head.
  6534  				b := s.endBlock()
  6535  				b.AddEdgeTo(loopHead)
  6536  
  6537  				// At loop head, get pointer to the cache entry.
  6538  				//   e := &cache.Entries[hash&mask]
  6539  				s.startBlock(loopHead)
  6540  				idx := s.newValue2(and, typs.Uintptr, s.variable(hashVar, typs.Uintptr), mask)
  6541  				idx = s.newValue2(mul, typs.Uintptr, idx, s.uintptrConstant(uint64(2*s.config.PtrSize)))
  6542  				idx = s.newValue2(add, typs.Uintptr, idx, s.uintptrConstant(uint64(s.config.PtrSize)))
  6543  				e := s.newValue2(ssaop.OpAddPtr, typs.UintptrPtr, cache, idx)
  6544  				//   hash++
  6545  				s.vars[hashVar] = s.newValue2(add, typs.Uintptr, s.variable(hashVar, typs.Uintptr), s.uintptrConstant(1))
  6546  
  6547  				// Look for a cache hit.
  6548  				//   if e.Typ == typ { goto hit }
  6549  				eTyp := s.newValue2(ssaop.OpLoad, typs.Uintptr, e, s.mem())
  6550  				cmp1 := s.newValue2(ssaop.OpEqPtr, typs.Bool, typ, eTyp)
  6551  				b = s.endBlock()
  6552  				b.Kind = block.BlockIf
  6553  				b.SetControl(cmp1)
  6554  				b.AddEdgeTo(cacheHit)
  6555  				b.AddEdgeTo(loopBody)
  6556  
  6557  				// Look for an empty entry, the tombstone for this hash table.
  6558  				//   if e.Typ == nil { goto miss }
  6559  				s.startBlock(loopBody)
  6560  				cmp2 := s.newValue2(ssaop.OpEqPtr, typs.Bool, eTyp, s.constNil(typs.BytePtr))
  6561  				b = s.endBlock()
  6562  				b.Kind = block.BlockIf
  6563  				b.SetControl(cmp2)
  6564  				b.AddEdgeTo(cacheMiss)
  6565  				b.AddEdgeTo(loopHead)
  6566  
  6567  				// On a hit, load the data fields of the cache entry.
  6568  				//   Itab = e.Itab
  6569  				s.startBlock(cacheHit)
  6570  				eItab := s.newValue2(ssaop.OpLoad, typs.BytePtr, s.newValue1I(ssaop.OpOffPtr, typs.BytePtrPtr, s.config.PtrSize, e), s.mem())
  6571  				s.vars[typVar] = eItab
  6572  				b = s.endBlock()
  6573  				b.AddEdgeTo(bMerge)
  6574  
  6575  				// On a miss, call into the runtime to get the answer.
  6576  				s.startBlock(cacheMiss)
  6577  			}
  6578  		}
  6579  
  6580  		// Call into runtime to get itab for result.
  6581  		if descriptor != nil {
  6582  			itab = s.rtcall(ir.Syms.TypeAssert, true, []*types.Type{byteptr}, d, typ)[0]
  6583  		} else {
  6584  			var fn *obj.LSym
  6585  			if commaok {
  6586  				fn = ir.Syms.AssertE2I2
  6587  			} else {
  6588  				fn = ir.Syms.AssertE2I
  6589  			}
  6590  			itab = s.rtcall(fn, true, []*types.Type{byteptr}, target, typ)[0]
  6591  		}
  6592  		s.vars[typVar] = itab
  6593  		b = s.endBlock()
  6594  		b.AddEdgeTo(bMerge)
  6595  
  6596  		// Build resulting interface.
  6597  		s.startBlock(bMerge)
  6598  		itab = s.variable(typVar, byteptr)
  6599  		var ok *ssa.Value
  6600  		if commaok {
  6601  			ok = s.newValue2(ssaop.OpNeqPtr, types.Types[types.TBOOL], itab, s.constNil(byteptr))
  6602  		}
  6603  		return s.newValue2(ssaop.OpIMake, dst, itab, data), ok
  6604  	}
  6605  
  6606  	if base.Debug.TypeAssert > 0 {
  6607  		base.WarnfAt(pos, "type assertion inlined")
  6608  	}
  6609  
  6610  	// Converting to a concrete type.
  6611  	direct := types.IsDirectIface(dst)
  6612  	itab := s.newValue1(ssaop.OpITab, byteptr, iface) // type word of interface
  6613  	if base.Debug.TypeAssert > 0 {
  6614  		base.WarnfAt(pos, "type assertion inlined")
  6615  	}
  6616  	var wantedFirstWord *ssa.Value
  6617  	if src.IsEmptyInterface() {
  6618  		// Looking for pointer to target type.
  6619  		wantedFirstWord = target
  6620  	} else {
  6621  		// Looking for pointer to itab for target type and source interface.
  6622  		wantedFirstWord = targetItab
  6623  	}
  6624  
  6625  	var tmp ir.Node     // temporary for use with large types
  6626  	var addr *ssa.Value // address of tmp
  6627  	if commaok && !ssa.CanSSA(dst) {
  6628  		// unSSAable type, use temporary.
  6629  		// TODO: get rid of some of these temporaries.
  6630  		tmp, addr = s.temp(pos, dst)
  6631  	}
  6632  
  6633  	cond := s.newValue2(ssaop.OpEqPtr, types.Types[types.TBOOL], itab, wantedFirstWord)
  6634  	b := s.endBlock()
  6635  	b.Kind = block.BlockIf
  6636  	b.SetControl(cond)
  6637  	b.Likely = ssa.BranchLikely
  6638  
  6639  	bOk := s.f.NewBlock(block.BlockPlain)
  6640  	bFail := s.f.NewBlock(block.BlockPlain)
  6641  	b.AddEdgeTo(bOk)
  6642  	b.AddEdgeTo(bFail)
  6643  
  6644  	if !commaok {
  6645  		// on failure, panic by calling panicdottype
  6646  		s.startBlock(bFail)
  6647  		taddr := source
  6648  		if taddr == nil {
  6649  			taddr = s.reflectType(src)
  6650  		}
  6651  		if src.IsEmptyInterface() {
  6652  			s.rtcall(ir.Syms.PanicdottypeE, false, nil, itab, target, taddr)
  6653  		} else {
  6654  			s.rtcall(ir.Syms.PanicdottypeI, false, nil, itab, target, taddr)
  6655  		}
  6656  
  6657  		// on success, return data from interface
  6658  		s.startBlock(bOk)
  6659  		if direct {
  6660  			return s.newValue1(ssaop.OpIData, dst, iface), nil
  6661  		}
  6662  		p := s.newValue1(ssaop.OpIData, types.NewPtr(dst), iface)
  6663  		return s.load(dst, p), nil
  6664  	}
  6665  
  6666  	// commaok is the more complicated case because we have
  6667  	// a control flow merge point.
  6668  	bEnd := s.f.NewBlock(block.BlockPlain)
  6669  	// Note that we need a new valVar each time (unlike okVar where we can
  6670  	// reuse the variable) because it might have a different type every time.
  6671  	valVar := ssaMarker("val")
  6672  
  6673  	// type assertion succeeded
  6674  	s.startBlock(bOk)
  6675  	if tmp == nil {
  6676  		if direct {
  6677  			s.vars[valVar] = s.newValue1(ssaop.OpIData, dst, iface)
  6678  		} else {
  6679  			p := s.newValue1(ssaop.OpIData, types.NewPtr(dst), iface)
  6680  			s.vars[valVar] = s.load(dst, p)
  6681  		}
  6682  	} else {
  6683  		p := s.newValue1(ssaop.OpIData, types.NewPtr(dst), iface)
  6684  		s.move(dst, addr, p)
  6685  	}
  6686  	s.vars[okVar] = s.constBool(true)
  6687  	s.endBlock()
  6688  	bOk.AddEdgeTo(bEnd)
  6689  
  6690  	// type assertion failed
  6691  	s.startBlock(bFail)
  6692  	if tmp == nil {
  6693  		s.vars[valVar] = s.zeroVal(dst)
  6694  	} else {
  6695  		s.zero(dst, addr)
  6696  	}
  6697  	s.vars[okVar] = s.constBool(false)
  6698  	s.endBlock()
  6699  	bFail.AddEdgeTo(bEnd)
  6700  
  6701  	// merge point
  6702  	s.startBlock(bEnd)
  6703  	if tmp == nil {
  6704  		res = s.variable(valVar, dst)
  6705  		delete(s.vars, valVar) // no practical effect, just to indicate typVar is no longer live.
  6706  	} else {
  6707  		res = s.load(dst, addr)
  6708  	}
  6709  	resok = s.variable(okVar, types.Types[types.TBOOL])
  6710  	delete(s.vars, okVar) // ditto
  6711  	return res, resok
  6712  }
  6713  
  6714  // temp allocates a temp of type t at position pos
  6715  func (s *state) temp(pos src.XPos, t *types.Type) (*ir.Name, *ssa.Value) {
  6716  	tmp := typecheck.TempAt(pos, s.curfn, t)
  6717  	if ssa.CanSSA(t) {
  6718  		// The whole point of this temporary is that we are about to take
  6719  		// its address (see the s.addr call below), so it must live on the
  6720  		// stack. typecheck.TempAt does not mark it addrtaken, and for an
  6721  		// SSA-able type that makes s.addr take its s.canSSA early-return
  6722  		// path and hand back &runtime.zerobase instead of the temporary's
  6723  		// stack slot, after which the caller writes the object into
  6724  		// runtime.zerobase.
  6725  		//
  6726  		// A type that is not SSA-able already gets a real stack slot, and
  6727  		// marking it here would only cost it its stack-slot merging
  6728  		// candidacy (see ssa.IsMergeCandidate below), so leave it alone.
  6729  		tmp.SetAddrtaken(true)
  6730  	}
  6731  	if t.HasPointers() || (ssa.IsMergeCandidate(tmp) && t != deferstruct()) {
  6732  		s.vars[memVar] = s.newValue1A(ssaop.OpVarDef, types.TypeMem, tmp, s.mem())
  6733  	}
  6734  	addr := s.addr(tmp)
  6735  	return tmp, addr
  6736  }
  6737  
  6738  // variable returns the value of a variable at the current location.
  6739  func (s *state) variable(n ir.Node, t *types.Type) *ssa.Value {
  6740  	v := s.vars[n]
  6741  	if v != nil {
  6742  		return v
  6743  	}
  6744  	v = s.fwdVars[n]
  6745  	if v != nil {
  6746  		return v
  6747  	}
  6748  
  6749  	if s.curBlock == s.f.Entry {
  6750  		// No variable should be live at entry.
  6751  		s.f.Fatalf("value %v (%v) incorrectly live at entry", n, v)
  6752  	}
  6753  	// Make a FwdRef, which records a value that's live on block input.
  6754  	// We'll find the matching definition as part of insertPhis.
  6755  	v = s.newValue0A(ssaop.OpFwdRef, t, fwdRefAux{N: n})
  6756  	s.fwdVars[n] = v
  6757  	if n.Op() == ir.ONAME {
  6758  		s.addNamedValue(n.(*ir.Name), v)
  6759  	}
  6760  	return v
  6761  }
  6762  
  6763  func (s *state) mem() *ssa.Value {
  6764  	return s.variable(memVar, types.TypeMem)
  6765  }
  6766  
  6767  func (s *state) addNamedValue(n *ir.Name, v *ssa.Value) {
  6768  	if n.Class == ir.Pxxx {
  6769  		// Don't track our marker nodes (memVar etc.).
  6770  		return
  6771  	}
  6772  	if ir.IsAutoTmp(n) {
  6773  		// Don't track temporary variables.
  6774  		return
  6775  	}
  6776  	if n.Class == ir.PPARAMOUT {
  6777  		// Don't track named output values.  This prevents return values
  6778  		// from being assigned too early. See #14591 and #14762. TODO: allow this.
  6779  		return
  6780  	}
  6781  	loc := ssa.LocalSlot{N: n, Type: n.Type(), Off: 0}
  6782  	values, ok := s.f.NamedValues[loc]
  6783  	if !ok {
  6784  		s.f.Names = append(s.f.Names, loc)
  6785  	}
  6786  	s.f.NamedValues[loc] = append(values, v)
  6787  }
  6788  
  6789  // Branch is an unresolved branch.
  6790  type Branch struct {
  6791  	P *obj.Prog  // branch instruction
  6792  	B *ssa.Block // target
  6793  }
  6794  
  6795  // State contains state needed during Prog generation.
  6796  type State struct {
  6797  	ABI obj.ABI
  6798  
  6799  	pp *objw.Progs
  6800  
  6801  	// Branches remembers all the branch instructions we've seen
  6802  	// and where they would like to go.
  6803  	Branches []Branch
  6804  
  6805  	// JumpTables remembers all the jump tables we've seen.
  6806  	JumpTables []*ssa.Block
  6807  
  6808  	// bstart remembers where each block starts (indexed by block ID)
  6809  	bstart []*obj.Prog
  6810  
  6811  	maxarg int64 // largest frame size for arguments to calls made by the function
  6812  
  6813  	// Map from GC safe points to liveness index, generated by
  6814  	// liveness analysis.
  6815  	livenessMap liveness.Map
  6816  
  6817  	// partLiveArgs includes arguments that may be partially live, for which we
  6818  	// need to generate instructions that spill the argument registers.
  6819  	partLiveArgs map[*ir.Name]bool
  6820  
  6821  	// lineRunStart records the beginning of the current run of instructions
  6822  	// within a single block sharing the same line number
  6823  	// Used to move statement marks to the beginning of such runs.
  6824  	lineRunStart *obj.Prog
  6825  
  6826  	// wasm: The number of values on the WebAssembly stack. This is only used as a safeguard.
  6827  	OnWasmStackSkipped int
  6828  }
  6829  
  6830  func (s *State) FuncInfo() *obj.FuncInfo {
  6831  	return s.pp.CurFunc.LSym.Func()
  6832  }
  6833  
  6834  // Prog appends a new Prog.
  6835  func (s *State) Prog(as obj.As) *obj.Prog {
  6836  	p := s.pp.Prog(as)
  6837  	if objw.LosesStmtMark(as) {
  6838  		return p
  6839  	}
  6840  	// Float a statement start to the beginning of any same-line run.
  6841  	// lineRunStart is reset at block boundaries, which appears to work well.
  6842  	if s.lineRunStart == nil || s.lineRunStart.Pos.Line() != p.Pos.Line() {
  6843  		s.lineRunStart = p
  6844  	} else if p.Pos.IsStmt() == src.PosIsStmt {
  6845  		s.lineRunStart.Pos = s.lineRunStart.Pos.WithIsStmt()
  6846  		p.Pos = p.Pos.WithNotStmt()
  6847  	}
  6848  	return p
  6849  }
  6850  
  6851  // Pc returns the current Prog.
  6852  func (s *State) Pc() *obj.Prog {
  6853  	return s.pp.Next
  6854  }
  6855  
  6856  // SetPos sets the current source position.
  6857  func (s *State) SetPos(pos src.XPos) {
  6858  	s.pp.Pos = pos
  6859  }
  6860  
  6861  // Br emits a single branch instruction and returns the instruction.
  6862  // Not all architectures need the returned instruction, but otherwise
  6863  // the boilerplate is common to all.
  6864  func (s *State) Br(op obj.As, target *ssa.Block) *obj.Prog {
  6865  	p := s.Prog(op)
  6866  	p.To.Type = obj.TYPE_BRANCH
  6867  	s.Branches = append(s.Branches, Branch{P: p, B: target})
  6868  	return p
  6869  }
  6870  
  6871  // DebugFriendlySetPosFrom adjusts Pos.IsStmt subject to heuristics
  6872  // that reduce "jumpy" line number churn when debugging.
  6873  // Spill/fill/copy instructions from the register allocator,
  6874  // phi functions, and instructions with a no-pos position
  6875  // are examples of instructions that can cause churn.
  6876  func (s *State) DebugFriendlySetPosFrom(v *ssa.Value) {
  6877  	switch v.Op {
  6878  	case ssaop.OpPhi, ssaop.OpCopy, ssaop.OpLoadReg, ssaop.OpStoreReg:
  6879  		// These are not statements
  6880  		s.SetPos(v.Pos.WithNotStmt())
  6881  	default:
  6882  		p := v.Pos
  6883  		if p != src.NoXPos {
  6884  			// If the position is defined, update the position.
  6885  			// Also convert default IsStmt to NotStmt; only
  6886  			// explicit statement boundaries should appear
  6887  			// in the generated code.
  6888  			if p.IsStmt() != src.PosIsStmt {
  6889  				if s.pp.Pos.IsStmt() == src.PosIsStmt && s.pp.Pos.SameFileAndLine(p) {
  6890  					// If s.pp.Pos already has a statement mark, then it was set here (below) for
  6891  					// the previous value.  If an actual instruction had been emitted for that
  6892  					// value, then the statement mark would have been reset.  Since the statement
  6893  					// mark of s.pp.Pos was not reset, this position (file/line) still needs a
  6894  					// statement mark on an instruction.  If file and line for this value are
  6895  					// the same as the previous value, then the first instruction for this
  6896  					// value will work to take the statement mark.  Return early to avoid
  6897  					// resetting the statement mark.
  6898  					//
  6899  					// The reset of s.pp.Pos occurs in (*Progs).Prog() -- if it emits
  6900  					// an instruction, and the instruction's statement mark was set,
  6901  					// and it is not one of the LosesStmtMark instructions,
  6902  					// then Prog() resets the statement mark on the (*Progs).Pos.
  6903  					return
  6904  				}
  6905  				p = p.WithNotStmt()
  6906  				// Calls use the pos attached to v, but copy the statement mark from State
  6907  			}
  6908  			s.SetPos(p)
  6909  		} else {
  6910  			s.SetPos(s.pp.Pos.WithNotStmt())
  6911  		}
  6912  	}
  6913  }
  6914  
  6915  // emit argument info (locations on stack) for traceback.
  6916  func emitArgInfo(e *ssafn, f *ssa.Func, pp *objw.Progs) {
  6917  	ft := e.curfn.Type()
  6918  	if ft.NumRecvs() == 0 && ft.NumParams() == 0 {
  6919  		return
  6920  	}
  6921  
  6922  	x := EmitArgInfo(e.curfn, f.OwnAux.ABIInfo())
  6923  	x.Set(obj.AttrContentAddressable, true)
  6924  	e.curfn.LSym.Func().ArgInfo = x
  6925  
  6926  	// Emit a funcdata pointing at the arg info data.
  6927  	p := pp.Prog(obj.AFUNCDATA)
  6928  	p.From.SetConst(rtabi.FUNCDATA_ArgInfo)
  6929  	p.To.Type = obj.TYPE_MEM
  6930  	p.To.Name = obj.NAME_EXTERN
  6931  	p.To.Sym = x
  6932  }
  6933  
  6934  // emit argument info (locations on stack) of f for traceback.
  6935  func EmitArgInfo(f *ir.Func, abiInfo *abi.ABIParamResultInfo) *obj.LSym {
  6936  	x := base.Ctxt.Lookup(fmt.Sprintf("%s.arginfo%d", f.LSym.Name, f.ABI))
  6937  	x.Align = 1
  6938  	// NOTE: do not set ContentAddressable here. This may be referenced from
  6939  	// assembly code by name (in this case f is a declaration).
  6940  	// Instead, set it in emitArgInfo above.
  6941  
  6942  	PtrSize := int64(types.PtrSize)
  6943  	uintptrTyp := types.Types[types.TUINTPTR]
  6944  
  6945  	isAggregate := func(t *types.Type) bool {
  6946  		return isStructNotSIMD(t) || t.IsArray() || t.IsComplex() || t.IsInterface() || t.IsString() || t.IsSlice()
  6947  	}
  6948  
  6949  	wOff := 0
  6950  	n := 0
  6951  	writebyte := func(o uint8) { wOff = objw.Uint8(x, wOff, o) }
  6952  
  6953  	// Write one non-aggregate arg/field/element.
  6954  	write1 := func(sz, offset int64) {
  6955  		if offset >= rtabi.TraceArgsSpecial {
  6956  			writebyte(rtabi.TraceArgsOffsetTooLarge)
  6957  		} else {
  6958  			writebyte(uint8(offset))
  6959  			writebyte(uint8(sz))
  6960  		}
  6961  		n++
  6962  	}
  6963  
  6964  	// Visit t recursively and write it out.
  6965  	// Returns whether to continue visiting.
  6966  	var visitType func(baseOffset int64, t *types.Type, depth int) bool
  6967  	visitType = func(baseOffset int64, t *types.Type, depth int) bool {
  6968  		if n >= rtabi.TraceArgsLimit {
  6969  			writebyte(rtabi.TraceArgsDotdotdot)
  6970  			return false
  6971  		}
  6972  		if !isAggregate(t) {
  6973  			write1(t.Size(), baseOffset)
  6974  			return true
  6975  		}
  6976  		writebyte(rtabi.TraceArgsStartAgg)
  6977  		depth++
  6978  		if depth >= rtabi.TraceArgsMaxDepth {
  6979  			writebyte(rtabi.TraceArgsDotdotdot)
  6980  			writebyte(rtabi.TraceArgsEndAgg)
  6981  			n++
  6982  			return true
  6983  		}
  6984  		switch {
  6985  		case t.IsInterface(), t.IsString():
  6986  			_ = visitType(baseOffset, uintptrTyp, depth) &&
  6987  				visitType(baseOffset+PtrSize, uintptrTyp, depth)
  6988  		case t.IsSlice():
  6989  			_ = visitType(baseOffset, uintptrTyp, depth) &&
  6990  				visitType(baseOffset+PtrSize, uintptrTyp, depth) &&
  6991  				visitType(baseOffset+PtrSize*2, uintptrTyp, depth)
  6992  		case t.IsComplex():
  6993  			_ = visitType(baseOffset, types.FloatForComplex(t), depth) &&
  6994  				visitType(baseOffset+t.Size()/2, types.FloatForComplex(t), depth)
  6995  		case t.IsArray():
  6996  			if t.NumElem() == 0 {
  6997  				n++ // {} counts as a component
  6998  				break
  6999  			}
  7000  			for i := int64(0); i < t.NumElem(); i++ {
  7001  				if !visitType(baseOffset, t.Elem(), depth) {
  7002  					break
  7003  				}
  7004  				baseOffset += t.Elem().Size()
  7005  			}
  7006  		case isStructNotSIMD(t):
  7007  			if t.NumFields() == 0 {
  7008  				n++ // {} counts as a component
  7009  				break
  7010  			}
  7011  			for _, field := range t.Fields() {
  7012  				if !visitType(baseOffset+field.Offset, field.Type, depth) {
  7013  					break
  7014  				}
  7015  			}
  7016  		}
  7017  		writebyte(rtabi.TraceArgsEndAgg)
  7018  		return true
  7019  	}
  7020  
  7021  	start := 0
  7022  	if strings.Contains(f.LSym.Name, "[") {
  7023  		// Skip the dictionary argument - it is implicit and the user doesn't need to see it.
  7024  		start = 1
  7025  	}
  7026  
  7027  	for _, a := range abiInfo.InParams()[start:] {
  7028  		if !visitType(a.FrameOffset(abiInfo), a.Type, 0) {
  7029  			break
  7030  		}
  7031  	}
  7032  	writebyte(rtabi.TraceArgsEndSeq)
  7033  	if wOff > rtabi.TraceArgsMaxLen {
  7034  		base.Fatalf("ArgInfo too large")
  7035  	}
  7036  
  7037  	return x
  7038  }
  7039  
  7040  // for wrapper, emit info of wrapped function.
  7041  func emitWrappedFuncInfo(e *ssafn, pp *objw.Progs) {
  7042  	if base.Ctxt.Flag_linkshared {
  7043  		// Relative reference (SymPtrOff) to another shared object doesn't work.
  7044  		// Unfortunate.
  7045  		return
  7046  	}
  7047  
  7048  	wfn := e.curfn.WrappedFunc
  7049  	if wfn == nil {
  7050  		return
  7051  	}
  7052  
  7053  	wsym := wfn.Linksym()
  7054  	x := base.Ctxt.LookupInit(fmt.Sprintf("%s.wrapinfo", wsym.Name), func(x *obj.LSym) {
  7055  		objw.SymPtrOff(x, 0, wsym)
  7056  		x.Set(obj.AttrContentAddressable, true)
  7057  		x.Align = 4
  7058  	})
  7059  	e.curfn.LSym.Func().WrapInfo = x
  7060  
  7061  	// Emit a funcdata pointing at the wrap info data.
  7062  	p := pp.Prog(obj.AFUNCDATA)
  7063  	p.From.SetConst(rtabi.FUNCDATA_WrapInfo)
  7064  	p.To.Type = obj.TYPE_MEM
  7065  	p.To.Name = obj.NAME_EXTERN
  7066  	p.To.Sym = x
  7067  }
  7068  
  7069  // genssa appends entries to pp for each instruction in f.
  7070  func genssa(htmlWriter ssa.HTMLWriter, f *ssa.Func, pp *objw.Progs) {
  7071  	var s State
  7072  	s.ABI = f.OwnAux.Fn.ABI()
  7073  
  7074  	e := f.Frontend().(*ssafn)
  7075  
  7076  	gatherPrintInfo := f.PrintOrHtmlSSA || ssaconfig.GenssaDump[f.Name]
  7077  
  7078  	var lv *liveness.Liveness
  7079  	s.livenessMap, s.partLiveArgs, lv = liveness.Compute(e.curfn, f, e.stkptrsize, pp, gatherPrintInfo)
  7080  	emitArgInfo(e, f, pp)
  7081  	argLiveBlockMap, argLiveValueMap := liveness.ArgLiveness(e.curfn, f, pp)
  7082  
  7083  	openDeferInfo := e.curfn.LSym.Func().OpenCodedDeferInfo
  7084  	if openDeferInfo != nil {
  7085  		// This function uses open-coded defers -- write out the funcdata
  7086  		// info that we computed at the end of genssa.
  7087  		p := pp.Prog(obj.AFUNCDATA)
  7088  		p.From.SetConst(rtabi.FUNCDATA_OpenCodedDeferInfo)
  7089  		p.To.Type = obj.TYPE_MEM
  7090  		p.To.Name = obj.NAME_EXTERN
  7091  		p.To.Sym = openDeferInfo
  7092  	}
  7093  
  7094  	emitWrappedFuncInfo(e, pp)
  7095  
  7096  	// Remember where each block starts.
  7097  	s.bstart = make([]*obj.Prog, f.NumBlocks())
  7098  	s.pp = pp
  7099  	var progToValue map[*obj.Prog]*ssa.Value
  7100  	var progToBlock map[*obj.Prog]*ssa.Block
  7101  	var valueToProgAfter []*obj.Prog // The first Prog following computation of a value v; v is visible at this point.
  7102  	if gatherPrintInfo {
  7103  		progToValue = make(map[*obj.Prog]*ssa.Value, f.NumValues())
  7104  		progToBlock = make(map[*obj.Prog]*ssa.Block, f.NumBlocks())
  7105  		f.Logf("genssa %s\n", f.Name)
  7106  		progToBlock[s.pp.Next] = f.Blocks[0]
  7107  	}
  7108  
  7109  	if base.Ctxt.Flag_locationlists {
  7110  		if cap(f.Cache.ValueToProgAfter) < f.NumValues() {
  7111  			f.Cache.ValueToProgAfter = make([]*obj.Prog, f.NumValues())
  7112  		}
  7113  		valueToProgAfter = f.Cache.ValueToProgAfter[:f.NumValues()]
  7114  		clear(valueToProgAfter)
  7115  	}
  7116  
  7117  	// If the very first instruction is not tagged as a statement,
  7118  	// debuggers may attribute it to previous function in program.
  7119  	firstPos := src.NoXPos
  7120  	for _, v := range f.Entry.Values {
  7121  		if v.Pos.IsStmt() == src.PosIsStmt && v.Op != ssaop.OpArg && v.Op != ssaop.OpArgIntReg && v.Op != ssaop.OpArgFloatReg && v.Op != ssaop.OpLoadReg && v.Op != ssaop.OpStoreReg {
  7122  			firstPos = v.Pos
  7123  			v.Pos = firstPos.WithDefaultStmt()
  7124  			break
  7125  		}
  7126  	}
  7127  
  7128  	// inlMarks has an entry for each Prog that implements an inline mark.
  7129  	// It maps from that Prog to the global inlining id of the inlined body
  7130  	// which should unwind to this Prog's location.
  7131  	var inlMarks map[*obj.Prog]int32
  7132  	var inlMarkList []*obj.Prog
  7133  
  7134  	// inlMarksByPos maps from a (column 1) source position to the set of
  7135  	// Progs that are in the set above and have that source position.
  7136  	var inlMarksByPos map[src.XPos][]*obj.Prog
  7137  
  7138  	var argLiveIdx int = -1 // argument liveness info index
  7139  
  7140  	// These control cache line alignment; if the required portion of
  7141  	// a cache line is not available, then pad to obtain cache line
  7142  	// alignment.  Not implemented on all architectures, may not be
  7143  	// useful on all architectures.
  7144  	var hotAlign, hotRequire int64
  7145  
  7146  	if base.Debug.AlignHot > 0 {
  7147  		switch base.Ctxt.Arch.Name {
  7148  		// enable this on a case-by-case basis, with benchmarking.
  7149  		// currently shown:
  7150  		//   good for amd64
  7151  		//   not helpful for Apple Silicon
  7152  		//
  7153  		case "amd64", "386":
  7154  			// Align to 64 if 31 or fewer bytes remain in a cache line
  7155  			// benchmarks a little better than always aligning, and also
  7156  			// adds slightly less to the (PGO-compiled) binary size.
  7157  			hotAlign = 64
  7158  			hotRequire = 31
  7159  		}
  7160  	}
  7161  
  7162  	// Emit basic blocks
  7163  	for i, b := range f.Blocks {
  7164  
  7165  		s.lineRunStart = nil
  7166  		s.SetPos(s.pp.Pos.WithNotStmt()) // It needs a non-empty Pos, but cannot be a statement boundary (yet).
  7167  
  7168  		if hotAlign > 0 && b.Hotness&ssa.HotPgoInitial == ssa.HotPgoInitial {
  7169  			// So far this has only been shown profitable for PGO-hot loop headers.
  7170  			// The Hotness values allows distinctions between initial blocks that are "hot" or not, and "flow-in" or not.
  7171  			// Currently only the initial blocks of loops are tagged in this way;
  7172  			// there are no blocks tagged "pgo-hot" that are not also tagged "initial".
  7173  			// TODO more heuristics, more architectures.
  7174  			p := s.pp.Prog(obj.APCALIGNMAX)
  7175  			p.From.SetConst(hotAlign)
  7176  			p.To.SetConst(hotRequire)
  7177  		}
  7178  
  7179  		s.bstart[b.ID] = s.pp.Next
  7180  
  7181  		if idx, ok := argLiveBlockMap[b.ID]; ok && idx != argLiveIdx {
  7182  			argLiveIdx = idx
  7183  			p := s.pp.Prog(obj.APCDATA)
  7184  			p.From.SetConst(rtabi.PCDATA_ArgLiveIndex)
  7185  			p.To.SetConst(int64(idx))
  7186  		}
  7187  
  7188  		// Emit values in block
  7189  		Arch.SSAMarkMoves(&s, b)
  7190  		for _, v := range b.Values {
  7191  			x := s.pp.Next
  7192  			s.DebugFriendlySetPosFrom(v)
  7193  
  7194  			if v.Op.ResultInArg0() && v.ResultReg() != v.Args[0].Reg() {
  7195  				v.Fatalf("input[0] and output not in same register %s", v.LongString())
  7196  			}
  7197  
  7198  			switch v.Op {
  7199  			case ssaop.OpInitMem:
  7200  				// memory arg needs no code
  7201  			case ssaop.OpArg:
  7202  				// input args need no code
  7203  			case ssaop.OpSP, ssaop.OpSB:
  7204  				// nothing to do
  7205  			case ssaop.OpSelect0, ssaop.OpSelect1, ssaop.OpSelectN, ssaop.OpMakeResult:
  7206  				// nothing to do
  7207  			case ssaop.OpGetG:
  7208  				// nothing to do when there's a g register,
  7209  				// and checkLower complains if there's not
  7210  			case ssaop.OpVarDef, ssaop.OpVarLive, ssaop.OpKeepAlive, ssaop.OpWBend:
  7211  				// nothing to do; already used by liveness
  7212  			case ssaop.OpPhi:
  7213  				CheckLoweredPhi(v)
  7214  			case ssaop.OpConvert:
  7215  				// nothing to do; no-op conversion for liveness
  7216  				if v.Args[0].Reg() != v.Reg() {
  7217  					v.Fatalf("OpConvert should be a no-op: %s; %s", v.Args[0].LongString(), v.LongString())
  7218  				}
  7219  			case ssaop.OpInlMark:
  7220  				// The nop may be scheduled inside an unsafe region,
  7221  				// such as between the write barrier flag load and its
  7222  				// test, so it needs its own unsafe-point mark.
  7223  				s.pp.NextUnsafe = s.livenessMap.GetUnsafe(v)
  7224  				p := Arch.Ginsnop(s.pp)
  7225  				if inlMarks == nil {
  7226  					inlMarks = map[*obj.Prog]int32{}
  7227  					inlMarksByPos = map[src.XPos][]*obj.Prog{}
  7228  				}
  7229  				inlMarks[p] = v.AuxInt32()
  7230  				inlMarkList = append(inlMarkList, p)
  7231  				pos := v.Pos.AtColumn1()
  7232  				inlMarksByPos[pos] = append(inlMarksByPos[pos], p)
  7233  				firstPos = src.NoXPos
  7234  
  7235  			default:
  7236  				// Special case for first line in function; move it to the start (which cannot be a register-valued instruction)
  7237  				if firstPos != src.NoXPos && v.Op != ssaop.OpArgIntReg && v.Op != ssaop.OpArgFloatReg && v.Op != ssaop.OpLoadReg && v.Op != ssaop.OpStoreReg {
  7238  					s.SetPos(firstPos)
  7239  					firstPos = src.NoXPos
  7240  				}
  7241  				// Attach this safe point to the next
  7242  				// instruction.
  7243  				s.pp.NextLive = s.livenessMap.Get(v)
  7244  				s.pp.NextUnsafe = s.livenessMap.GetUnsafe(v)
  7245  
  7246  				// let the backend handle it
  7247  				Arch.SSAGenValue(&s, v)
  7248  			}
  7249  
  7250  			if idx, ok := argLiveValueMap[v.ID]; ok && idx != argLiveIdx {
  7251  				argLiveIdx = idx
  7252  				p := s.pp.Prog(obj.APCDATA)
  7253  				p.From.SetConst(rtabi.PCDATA_ArgLiveIndex)
  7254  				p.To.SetConst(int64(idx))
  7255  			}
  7256  
  7257  			if base.Ctxt.Flag_locationlists {
  7258  				valueToProgAfter[v.ID] = s.pp.Next
  7259  			}
  7260  
  7261  			if gatherPrintInfo {
  7262  				for ; x != s.pp.Next; x = x.Link {
  7263  					progToValue[x] = v
  7264  				}
  7265  			}
  7266  		}
  7267  		// If this is an empty infinite loop, stick a hardware NOP in there so that debuggers are less confused.
  7268  		if s.bstart[b.ID] == s.pp.Next && len(b.Succs) == 1 && b.Succs[0].Block() == b {
  7269  			p := Arch.Ginsnop(s.pp)
  7270  			p.Pos = p.Pos.WithIsStmt()
  7271  			if b.Pos == src.NoXPos {
  7272  				b.Pos = p.Pos // It needs a file, otherwise a no-file non-zero line causes confusion.  See #35652.
  7273  				if b.Pos == src.NoXPos {
  7274  					b.Pos = s.pp.Text.Pos // Sometimes p.Pos is empty.  See #35695.
  7275  				}
  7276  			}
  7277  			b.Pos = b.Pos.WithBogusLine() // Debuggers are not good about infinite loops, force a change in line number
  7278  		}
  7279  
  7280  		// Set unsafe mark for any end-of-block generated instructions
  7281  		// (normally, conditional or unconditional branches).
  7282  		// This is particularly important for empty blocks, as there
  7283  		// are no values to inherit the unsafe mark from.
  7284  		s.pp.NextUnsafe = s.livenessMap.GetUnsafeBlock(b)
  7285  
  7286  		// Emit control flow instructions for block
  7287  		var next *ssa.Block
  7288  		if i < len(f.Blocks)-1 && base.Flag.N == 0 {
  7289  			// If -N, leave next==nil so every block with successors
  7290  			// ends in a JMP (except call blocks - plive doesn't like
  7291  			// select{send,recv} followed by a JMP call).  Helps keep
  7292  			// line numbers for otherwise empty blocks.
  7293  			next = f.Blocks[i+1]
  7294  		}
  7295  		x := s.pp.Next
  7296  		s.SetPos(b.Pos)
  7297  		Arch.SSAGenBlock(&s, b, next)
  7298  		if gatherPrintInfo {
  7299  			for ; x != s.pp.Next; x = x.Link {
  7300  				progToBlock[x] = b
  7301  			}
  7302  		}
  7303  	}
  7304  	if f.Blocks[len(f.Blocks)-1].Kind == block.BlockExit {
  7305  		// We need the return address of a panic call to
  7306  		// still be inside the function in question. So if
  7307  		// it ends in a call which doesn't return, add a
  7308  		// nop (which will never execute) after the call.
  7309  		Arch.Ginsnop(s.pp)
  7310  	}
  7311  	if openDeferInfo != nil {
  7312  		// When doing open-coded defers, generate a disconnected call to
  7313  		// deferreturn and a return. This will be used to during panic
  7314  		// recovery to unwind the stack and return back to the runtime.
  7315  
  7316  		// Note that this exit code doesn't work if a return parameter
  7317  		// is heap-allocated, but open defers aren't enabled in that case.
  7318  
  7319  		// TODO either make this handle heap-allocated return parameters or reuse the other-defers general-purpose code path.
  7320  		s.pp.NextLive = s.livenessMap.DeferReturn
  7321  		p := s.pp.Prog(obj.ACALL)
  7322  		p.To.Type = obj.TYPE_MEM
  7323  		p.To.Name = obj.NAME_EXTERN
  7324  		p.To.Sym = ir.Syms.Deferreturn
  7325  
  7326  		// Load results into registers. So when a deferred function
  7327  		// recovers a panic, it will return to caller with right results.
  7328  		// The results are already in memory, because they are not SSA'd
  7329  		// when the function has defers (see canSSAName).
  7330  		for _, o := range f.OwnAux.ABIInfo().OutParams() {
  7331  			n := o.Name
  7332  			rts, offs := o.RegisterTypesAndOffsets()
  7333  			for i := range o.Registers {
  7334  				Arch.LoadRegResult(&s, f, rts[i], ssa.ObjRegForAbiReg(o.Registers[i], f.Config), n, offs[i])
  7335  			}
  7336  		}
  7337  
  7338  		s.pp.Prog(obj.ARET)
  7339  	}
  7340  
  7341  	if inlMarks != nil {
  7342  		hasCall := false
  7343  
  7344  		// We have some inline marks. Try to find other instructions we're
  7345  		// going to emit anyway, and use those instructions instead of the
  7346  		// inline marks.
  7347  		for p := s.pp.Text; p != nil; p = p.Link {
  7348  			if p.As == obj.ANOP || p.As == obj.AFUNCDATA || p.As == obj.APCDATA || p.As == obj.ATEXT ||
  7349  				p.As == obj.APCALIGN || p.As == obj.APCALIGNMAX || Arch.LinkArch.Family == sys.Wasm {
  7350  				// Don't use 0-sized instructions as inline marks, because we need
  7351  				// to identify inline mark instructions by pc offset.
  7352  				// (Some of these instructions are sometimes zero-sized, sometimes not.
  7353  				// We must not use anything that even might be zero-sized.)
  7354  				// TODO: are there others?
  7355  				continue
  7356  			}
  7357  			if _, ok := inlMarks[p]; ok {
  7358  				// Don't use inline marks themselves. We don't know
  7359  				// whether they will be zero-sized or not yet.
  7360  				continue
  7361  			}
  7362  			if p.As == obj.ACALL || p.As == obj.ADUFFCOPY || p.As == obj.ADUFFZERO {
  7363  				hasCall = true
  7364  			}
  7365  			pos := p.Pos.AtColumn1()
  7366  			marks := inlMarksByPos[pos]
  7367  			if len(marks) == 0 {
  7368  				continue
  7369  			}
  7370  			for _, m := range marks {
  7371  				// We found an instruction with the same source position as
  7372  				// some of the inline marks.
  7373  				// Use this instruction instead.
  7374  				p.Pos = p.Pos.WithIsStmt() // promote position to a statement
  7375  				s.pp.CurFunc.LSym.Func().AddInlMark(p, inlMarks[m])
  7376  				// Make the inline mark a real nop, so it doesn't generate any code.
  7377  				m.As = obj.ANOP
  7378  				m.Pos = src.NoXPos
  7379  				m.From = obj.Addr{}
  7380  				m.To = obj.Addr{}
  7381  			}
  7382  			delete(inlMarksByPos, pos)
  7383  		}
  7384  		// Any unmatched inline marks now need to be added to the inlining tree (and will generate a nop instruction).
  7385  		for _, p := range inlMarkList {
  7386  			if p.As != obj.ANOP {
  7387  				s.pp.CurFunc.LSym.Func().AddInlMark(p, inlMarks[p])
  7388  			}
  7389  		}
  7390  
  7391  		if e.stksize == 0 && !hasCall {
  7392  			// Frameless leaf function. It doesn't need any preamble,
  7393  			// so make sure its first instruction isn't from an inlined callee.
  7394  			// If it is, add a nop at the start of the function with a position
  7395  			// equal to the start of the function.
  7396  			// This ensures that runtime.FuncForPC(uintptr(reflect.ValueOf(fn).Pointer())).Name()
  7397  			// returns the right answer. See issue 58300.
  7398  			for p := s.pp.Text; p != nil; p = p.Link {
  7399  				if p.As == obj.AFUNCDATA || p.As == obj.APCDATA || p.As == obj.ATEXT || p.As == obj.ANOP {
  7400  					continue
  7401  				}
  7402  				if base.Ctxt.PosTable.Pos(p.Pos).Base().InliningIndex() >= 0 {
  7403  					// Make a real (not 0-sized) nop.
  7404  					nop := Arch.Ginsnop(s.pp)
  7405  					nop.Pos = e.curfn.Pos().WithIsStmt()
  7406  
  7407  					// Unfortunately, Ginsnop puts the instruction at the
  7408  					// end of the list. Move it up to just before p.
  7409  
  7410  					// Unlink from the current list.
  7411  					for x := s.pp.Text; x != nil; x = x.Link {
  7412  						if x.Link == nop {
  7413  							x.Link = nop.Link
  7414  							break
  7415  						}
  7416  					}
  7417  					// Splice in right before p.
  7418  					for x := s.pp.Text; x != nil; x = x.Link {
  7419  						if x.Link == p {
  7420  							nop.Link = p
  7421  							x.Link = nop
  7422  							break
  7423  						}
  7424  					}
  7425  				}
  7426  				break
  7427  			}
  7428  		}
  7429  	}
  7430  
  7431  	if base.Ctxt.Flag_locationlists {
  7432  		var debugInfo *ssadebug.FuncDebug
  7433  		debugInfo = e.curfn.DebugInfo.(*ssadebug.FuncDebug)
  7434  		// Save off entry ID in case we need it later for DWARF generation
  7435  		// for return values promoted to the heap.
  7436  		debugInfo.EntryID = f.Entry.ID
  7437  		if e.curfn.ABI == obj.ABIInternal && base.Flag.N != 0 {
  7438  			ssadebug.BuildFuncDebugNoOptimized(base.Ctxt, f, base.Debug.LocationLists > 1, StackOffset, debugInfo)
  7439  		} else {
  7440  			ssadebug.BuildFuncDebug(base.Ctxt, f, base.Debug.LocationLists, StackOffset, debugInfo)
  7441  		}
  7442  		bstart := s.bstart
  7443  		idToIdx := make([]int, f.NumBlocks())
  7444  		for i, b := range f.Blocks {
  7445  			idToIdx[b.ID] = i
  7446  		}
  7447  		// Register a callback that will be used later to fill in PCs into location
  7448  		// lists. At the moment, Prog.Pc is a sequence number; it's not a real PC
  7449  		// until after assembly, so the translation needs to be deferred.
  7450  		debugInfo.GetPC = func(b, v ssa.ID) int64 {
  7451  			switch v {
  7452  			case ssa.BlockStart.ID:
  7453  				if b == f.Entry.ID {
  7454  					return 0 // Start at the very beginning, at the assembler-generated prologue.
  7455  					// this should only happen for function args (ssa.OpArg)
  7456  				}
  7457  				return bstart[b].Pc
  7458  			case ssa.BlockEnd.ID:
  7459  				blk := f.Blocks[idToIdx[b]]
  7460  				nv := len(blk.Values)
  7461  				return valueToProgAfter[blk.Values[nv-1].ID].Pc
  7462  			case ssa.FuncEnd.ID:
  7463  				return e.curfn.LSym.Size
  7464  			default:
  7465  				return valueToProgAfter[v].Pc
  7466  			}
  7467  		}
  7468  	}
  7469  
  7470  	// Resolve branches, and relax DefaultStmt into NotStmt
  7471  	for _, br := range s.Branches {
  7472  		br.P.To.SetTarget(s.bstart[br.B.ID])
  7473  		if br.P.Pos.IsStmt() != src.PosIsStmt {
  7474  			br.P.Pos = br.P.Pos.WithNotStmt()
  7475  		} else if v0 := br.B.FirstPossibleStmtValue(); v0 != nil && v0.Pos.Line() == br.P.Pos.Line() && v0.Pos.IsStmt() == src.PosIsStmt {
  7476  			br.P.Pos = br.P.Pos.WithNotStmt()
  7477  		}
  7478  
  7479  	}
  7480  
  7481  	// Resolve jump table destinations.
  7482  	for _, jt := range s.JumpTables {
  7483  		// Convert from *Block targets to *Prog targets.
  7484  		targets := make([]*obj.Prog, len(jt.Succs))
  7485  		for i, e := range jt.Succs {
  7486  			targets[i] = s.bstart[e.Block().ID]
  7487  		}
  7488  		// Add to list of jump tables to be resolved at assembly time.
  7489  		// The assembler converts from *Prog entries to absolute addresses
  7490  		// once it knows instruction byte offsets.
  7491  		fi := s.pp.CurFunc.LSym.Func()
  7492  		fi.JumpTables = append(fi.JumpTables, obj.JumpTable{Sym: jt.Aux.(*obj.LSym), Targets: targets})
  7493  	}
  7494  
  7495  	// Finalize the frame, then let the backend run a final pass over the
  7496  	// generated Progs (e.g. arm64 fuses adjacent spill/reload MOVDs into
  7497  	// STP/LDP). Branch and jump-table targets are resolved at this point.
  7498  	// Doing this before the debug dumps below means -S and GOSSAFUNC's genssa
  7499  	// output reflect the instructions that are actually assembled. defframe
  7500  	// must run first: it finalizes the frame size, which the backend pass
  7501  	// depends on.
  7502  	defframe(&s, e, f)
  7503  	if Arch.SSAGenFinish != nil {
  7504  		Arch.SSAGenFinish(s.pp)
  7505  	}
  7506  
  7507  	if e.log { // spew to stdout
  7508  		filename := ""
  7509  		for p := s.pp.Text; p != nil; p = p.Link {
  7510  			if p.Pos.IsKnown() && p.InnermostFilename() != filename {
  7511  				filename = p.InnermostFilename()
  7512  				f.Logf("# %s\n", filename)
  7513  			}
  7514  
  7515  			var s string
  7516  			if v, ok := progToValue[p]; ok {
  7517  				s = v.String()
  7518  			} else if b, ok := progToBlock[p]; ok {
  7519  				s = b.String()
  7520  			} else {
  7521  				s = "   " // most value and branch strings are 2-3 characters long
  7522  			}
  7523  			f.Logf(" %-6s\t%.5d (%s)\t%s\n", s, p.Pc, p.InnermostLineNumber(), p.InstructionString())
  7524  		}
  7525  	}
  7526  	if htmlWriter.Enabled() { // spew to ssa.html
  7527  		var buf strings.Builder
  7528  		buf.WriteString("<code>")
  7529  		buf.WriteString("<dl class=\"ssa-gen\">")
  7530  		filename := ""
  7531  
  7532  		liveness := lv.Format(nil)
  7533  		if liveness != "" {
  7534  			buf.WriteString("<dt class=\"ssa-prog-src\"></dt><dd class=\"ssa-prog\">")
  7535  			buf.WriteString(html.EscapeString("# " + liveness))
  7536  			buf.WriteString("</dd>")
  7537  		}
  7538  
  7539  		for p := s.pp.Text; p != nil; p = p.Link {
  7540  			// Don't spam every line with the file name, which is often huge.
  7541  			// Only print changes, and "unknown" is not a change.
  7542  			if p.Pos.IsKnown() && p.InnermostFilename() != filename {
  7543  				filename = p.InnermostFilename()
  7544  				buf.WriteString("<dt class=\"ssa-prog-src\"></dt><dd class=\"ssa-prog\">")
  7545  				buf.WriteString(html.EscapeString("# " + filename))
  7546  				buf.WriteString("</dd>")
  7547  			}
  7548  
  7549  			buf.WriteString("<dt class=\"ssa-prog-src\">")
  7550  			if v, ok := progToValue[p]; ok {
  7551  
  7552  				// Prefix calls with their liveness, if any
  7553  				if p.As != obj.APCDATA {
  7554  					if liveness := lv.Format(v); liveness != "" {
  7555  						// Steal this line, and restart a line
  7556  						buf.WriteString("</dt><dd class=\"ssa-prog\">")
  7557  						buf.WriteString(html.EscapeString("# " + liveness))
  7558  						buf.WriteString("</dd>")
  7559  						// restarting a line
  7560  						buf.WriteString("<dt class=\"ssa-prog-src\">")
  7561  					}
  7562  				}
  7563  
  7564  				buf.WriteString(v.HTML())
  7565  			} else if b, ok := progToBlock[p]; ok {
  7566  				buf.WriteString("<b>" + b.HTML() + "</b>")
  7567  			}
  7568  			buf.WriteString("</dt>")
  7569  			buf.WriteString("<dd class=\"ssa-prog\">")
  7570  			fmt.Fprintf(&buf, "%.5d <span class=\"l%v line-number\">(%s)</span> %s", p.Pc, p.InnermostLineNumber(), p.InnermostLineNumberHTML(), html.EscapeString(p.InstructionString()))
  7571  			buf.WriteString("</dd>")
  7572  		}
  7573  		buf.WriteString("</dl>")
  7574  		buf.WriteString("</code>")
  7575  		htmlWriter.WriteColumn("genssa", "genssa", "ssa-prog", buf.String())
  7576  	}
  7577  	if ssaconfig.GenssaDump[f.Name] {
  7578  		fi := f.DumpFileForPhase("genssa")
  7579  		if fi != nil {
  7580  
  7581  			// inliningDiffers if any filename changes or if any line number except the innermost (last index) changes.
  7582  			inliningDiffers := func(a, b []src.Pos) bool {
  7583  				if len(a) != len(b) {
  7584  					return true
  7585  				}
  7586  				for i := range a {
  7587  					if a[i].Filename() != b[i].Filename() {
  7588  						return true
  7589  					}
  7590  					if i != len(a)-1 && a[i].Line() != b[i].Line() {
  7591  						return true
  7592  					}
  7593  				}
  7594  				return false
  7595  			}
  7596  
  7597  			var allPosOld []src.Pos
  7598  			var allPos []src.Pos
  7599  
  7600  			for p := s.pp.Text; p != nil; p = p.Link {
  7601  				if p.Pos.IsKnown() {
  7602  					allPos = allPos[:0]
  7603  					p.Ctxt.AllPos(p.Pos, func(pos src.Pos) { allPos = append(allPos, pos) })
  7604  					if inliningDiffers(allPos, allPosOld) {
  7605  						for _, pos := range allPos {
  7606  							fmt.Fprintf(fi, "# %s:%d\n", pos.Filename(), pos.Line())
  7607  						}
  7608  						allPos, allPosOld = allPosOld, allPos // swap, not copy, so that they do not share slice storage.
  7609  					}
  7610  				}
  7611  
  7612  				var s string
  7613  				if v, ok := progToValue[p]; ok {
  7614  					s = v.String()
  7615  				} else if b, ok := progToBlock[p]; ok {
  7616  					s = b.String()
  7617  				} else {
  7618  					s = "   " // most value and branch strings are 2-3 characters long
  7619  				}
  7620  				fmt.Fprintf(fi, " %-6s\t%.5d %s\t%s\n", s, p.Pc, ssa.StmtString(p.Pos), p.InstructionString())
  7621  			}
  7622  			fi.Close()
  7623  		}
  7624  	}
  7625  
  7626  	htmlWriter.Close()
  7627  	htmlWriter = nil
  7628  }
  7629  
  7630  func defframe(s *State, e *ssafn, f *ssa.Func) {
  7631  	pp := s.pp
  7632  
  7633  	s.maxarg = types.RoundUp(s.maxarg, e.stkalign)
  7634  	frame := s.maxarg + e.stksize
  7635  	if Arch.PadFrame != nil {
  7636  		frame = Arch.PadFrame(frame)
  7637  	}
  7638  
  7639  	// Fill in argument and frame size.
  7640  	pp.Text.To.Type = obj.TYPE_TEXTSIZE
  7641  	pp.Text.To.Val = int32(types.RoundUp(f.OwnAux.ArgWidth(), int64(types.RegSize)))
  7642  	pp.Text.To.Offset = frame
  7643  
  7644  	p := pp.Text
  7645  
  7646  	// Insert code to spill argument registers if the named slot may be partially
  7647  	// live. That is, the named slot is considered live by liveness analysis,
  7648  	// (because a part of it is live), but we may not spill all parts into the
  7649  	// slot. This can only happen with aggregate-typed arguments that are SSA-able
  7650  	// and not address-taken (for non-SSA-able or address-taken arguments we always
  7651  	// spill upfront).
  7652  	// Note: spilling is unnecessary in the -N/no-optimize case, since all values
  7653  	// will be considered non-SSAable and spilled up front.
  7654  	// TODO(register args) Make liveness more fine-grained to that partial spilling is okay.
  7655  	if f.OwnAux.ABIInfo().InRegistersUsed() != 0 && base.Flag.N == 0 {
  7656  		// First, see if it is already spilled before it may be live. Look for a spill
  7657  		// in the entry block up to the first safepoint.
  7658  		type nameOff struct {
  7659  			n   *ir.Name
  7660  			off int64
  7661  		}
  7662  		partLiveArgsSpilled := make(map[nameOff]bool)
  7663  		for _, v := range f.Entry.Values {
  7664  			if v.Op.IsCall() {
  7665  				break
  7666  			}
  7667  			if v.Op != ssaop.OpStoreReg || v.Args[0].Op != ssaop.OpArgIntReg {
  7668  				continue
  7669  			}
  7670  			n, off := ssa.AutoVar(v)
  7671  			if n.Class != ir.PPARAM || n.Addrtaken() || !ssa.CanSSA(n.Type()) || !s.partLiveArgs[n] {
  7672  				continue
  7673  			}
  7674  			partLiveArgsSpilled[nameOff{n, off}] = true
  7675  		}
  7676  
  7677  		// Then, insert code to spill registers if not already.
  7678  		for _, a := range f.OwnAux.ABIInfo().InParams() {
  7679  			n := a.Name
  7680  			if n == nil || n.Addrtaken() || !ssa.CanSSA(n.Type()) || !s.partLiveArgs[n] || len(a.Registers) <= 1 {
  7681  				continue
  7682  			}
  7683  			rts, offs := a.RegisterTypesAndOffsets()
  7684  			for i := range a.Registers {
  7685  				if !rts[i].HasPointers() {
  7686  					continue
  7687  				}
  7688  				if partLiveArgsSpilled[nameOff{n, offs[i]}] {
  7689  					continue // already spilled
  7690  				}
  7691  				reg := ssa.ObjRegForAbiReg(a.Registers[i], f.Config)
  7692  				p = Arch.SpillArgReg(pp, p, f, rts[i], reg, n, offs[i])
  7693  			}
  7694  		}
  7695  	}
  7696  
  7697  	// Insert code to zero ambiguously live variables so that the
  7698  	// garbage collector only sees initialized values when it
  7699  	// looks for pointers.
  7700  	var lo, hi int64
  7701  
  7702  	// Opaque state for backend to use. Current backends use it to
  7703  	// keep track of which helper registers have been zeroed.
  7704  	var state uint32
  7705  
  7706  	// Iterate through declarations. Autos are sorted in decreasing
  7707  	// frame offset order.
  7708  	for _, n := range e.curfn.Dcl {
  7709  		if !n.Needzero() {
  7710  			continue
  7711  		}
  7712  		if n.Class != ir.PAUTO {
  7713  			e.Fatalf(n.Pos(), "needzero class %d", n.Class)
  7714  		}
  7715  		if n.Type().Size()%int64(types.PtrSize) != 0 || n.FrameOffset()%int64(types.PtrSize) != 0 || n.Type().Size() == 0 {
  7716  			e.Fatalf(n.Pos(), "var %L has size %d offset %d", n, n.Type().Size(), n.Offset_)
  7717  		}
  7718  
  7719  		if lo != hi && n.FrameOffset()+n.Type().Size() >= lo-int64(2*types.RegSize) {
  7720  			// Merge with range we already have.
  7721  			lo = n.FrameOffset()
  7722  			continue
  7723  		}
  7724  
  7725  		// Zero old range
  7726  		p = Arch.ZeroRange(pp, p, frame+lo, hi-lo, &state)
  7727  
  7728  		// Set new range.
  7729  		lo = n.FrameOffset()
  7730  		hi = lo + n.Type().Size()
  7731  	}
  7732  
  7733  	// Zero final range.
  7734  	Arch.ZeroRange(pp, p, frame+lo, hi-lo, &state)
  7735  }
  7736  
  7737  // For generating consecutive jump instructions to model a specific branching
  7738  type IndexJump struct {
  7739  	Jump  obj.As
  7740  	Index int
  7741  }
  7742  
  7743  func (s *State) oneJump(b *ssa.Block, jump *IndexJump) {
  7744  	p := s.Br(jump.Jump, b.Succs[jump.Index].Block())
  7745  	p.Pos = b.Pos
  7746  }
  7747  
  7748  // CombJump generates combinational instructions (2 at present) for a block jump,
  7749  // thereby the behaviour of non-standard condition codes could be simulated
  7750  func (s *State) CombJump(b, next *ssa.Block, jumps *[2][2]IndexJump) {
  7751  	switch next {
  7752  	case b.Succs[0].Block():
  7753  		s.oneJump(b, &jumps[0][0])
  7754  		s.oneJump(b, &jumps[0][1])
  7755  	case b.Succs[1].Block():
  7756  		s.oneJump(b, &jumps[1][0])
  7757  		s.oneJump(b, &jumps[1][1])
  7758  	default:
  7759  		var q *obj.Prog
  7760  		if b.Likely != ssa.BranchUnlikely {
  7761  			s.oneJump(b, &jumps[1][0])
  7762  			s.oneJump(b, &jumps[1][1])
  7763  			q = s.Br(obj.AJMP, b.Succs[1].Block())
  7764  		} else {
  7765  			s.oneJump(b, &jumps[0][0])
  7766  			s.oneJump(b, &jumps[0][1])
  7767  			q = s.Br(obj.AJMP, b.Succs[0].Block())
  7768  		}
  7769  		q.Pos = b.Pos
  7770  	}
  7771  }
  7772  
  7773  // AddAux adds the offset in the aux fields (AuxInt and Aux) of v to a.
  7774  func AddAux(a *obj.Addr, v *ssa.Value) {
  7775  	AddAux2(a, v, v.AuxInt)
  7776  }
  7777  func AddAux2(a *obj.Addr, v *ssa.Value, offset int64) {
  7778  	if a.Type != obj.TYPE_MEM && a.Type != obj.TYPE_ADDR {
  7779  		v.Fatalf("bad AddAux addr %v", a)
  7780  	}
  7781  	// add integer offset
  7782  	a.Offset += offset
  7783  
  7784  	// If no additional symbol offset, we're done.
  7785  	if v.Aux == nil {
  7786  		return
  7787  	}
  7788  	// Add symbol's offset from its base register.
  7789  	switch n := v.Aux.(type) {
  7790  	case *ssa.AuxCall:
  7791  		a.Name = obj.NAME_EXTERN
  7792  		a.Sym = n.Fn
  7793  	case *obj.LSym:
  7794  		a.Name = obj.NAME_EXTERN
  7795  		a.Sym = n
  7796  	case *ir.Name:
  7797  		if n.Class == ir.PPARAM || (n.Class == ir.PPARAMOUT && !n.IsOutputParamInRegisters()) {
  7798  			a.Name = obj.NAME_PARAM
  7799  		} else {
  7800  			a.Name = obj.NAME_AUTO
  7801  		}
  7802  		a.Sym = n.Linksym()
  7803  		a.Offset += n.FrameOffset()
  7804  	default:
  7805  		v.Fatalf("aux in %s not implemented %#v", v, v.Aux)
  7806  	}
  7807  }
  7808  
  7809  // extendIndex extends v to a full int width.
  7810  // panic with the given kind if v does not fit in an int (only on 32-bit archs).
  7811  func (s *state) extendIndex(idx, len *ssa.Value, kind ssa.BoundsKind, bounded bool) *ssa.Value {
  7812  	size := idx.Type.Size()
  7813  	if size == s.config.PtrSize {
  7814  		return idx
  7815  	}
  7816  	if size > s.config.PtrSize {
  7817  		// truncate 64-bit indexes on 32-bit pointer archs. Test the
  7818  		// high word and branch to out-of-bounds failure if it is not 0.
  7819  		var lo *ssa.Value
  7820  		if idx.Type.IsSigned() {
  7821  			lo = s.newValue1(ssaop.OpInt64Lo, types.Types[types.TINT], idx)
  7822  		} else {
  7823  			lo = s.newValue1(ssaop.OpInt64Lo, types.Types[types.TUINT], idx)
  7824  		}
  7825  		if bounded || base.Flag.B != 0 {
  7826  			return lo
  7827  		}
  7828  		bNext := s.f.NewBlock(block.BlockPlain)
  7829  		bPanic := s.f.NewBlock(block.BlockExit)
  7830  		hi := s.newValue1(ssaop.OpInt64Hi, types.Types[types.TUINT32], idx)
  7831  		cmp := s.newValue2(ssaop.OpEq32, types.Types[types.TBOOL], hi, s.constInt32(types.Types[types.TUINT32], 0))
  7832  		if !idx.Type.IsSigned() {
  7833  			switch kind {
  7834  			case ssa.BoundsIndex:
  7835  				kind = ssa.BoundsIndexU
  7836  			case ssa.BoundsSliceAlen:
  7837  				kind = ssa.BoundsSliceAlenU
  7838  			case ssa.BoundsSliceAcap:
  7839  				kind = ssa.BoundsSliceAcapU
  7840  			case ssa.BoundsSliceB:
  7841  				kind = ssa.BoundsSliceBU
  7842  			case ssa.BoundsSlice3Alen:
  7843  				kind = ssa.BoundsSlice3AlenU
  7844  			case ssa.BoundsSlice3Acap:
  7845  				kind = ssa.BoundsSlice3AcapU
  7846  			case ssa.BoundsSlice3B:
  7847  				kind = ssa.BoundsSlice3BU
  7848  			case ssa.BoundsSlice3C:
  7849  				kind = ssa.BoundsSlice3CU
  7850  			}
  7851  		}
  7852  		b := s.endBlock()
  7853  		b.Kind = block.BlockIf
  7854  		b.SetControl(cmp)
  7855  		b.Likely = ssa.BranchLikely
  7856  		b.AddEdgeTo(bNext)
  7857  		b.AddEdgeTo(bPanic)
  7858  
  7859  		s.startBlock(bPanic)
  7860  		mem := s.newValue4I(ssaop.OpPanicExtend, types.TypeMem, int64(kind), hi, lo, len, s.mem())
  7861  		s.endBlock().SetControl(mem)
  7862  		s.startBlock(bNext)
  7863  
  7864  		return lo
  7865  	}
  7866  
  7867  	// Extend value to the required size
  7868  	var op ssaop.Op
  7869  	if idx.Type.IsSigned() {
  7870  		switch 10*size + s.config.PtrSize {
  7871  		case 14:
  7872  			op = ssaop.OpSignExt8to32
  7873  		case 18:
  7874  			op = ssaop.OpSignExt8to64
  7875  		case 24:
  7876  			op = ssaop.OpSignExt16to32
  7877  		case 28:
  7878  			op = ssaop.OpSignExt16to64
  7879  		case 48:
  7880  			op = ssaop.OpSignExt32to64
  7881  		default:
  7882  			s.Fatalf("bad signed index extension %s", idx.Type)
  7883  		}
  7884  	} else {
  7885  		switch 10*size + s.config.PtrSize {
  7886  		case 14:
  7887  			op = ssaop.OpZeroExt8to32
  7888  		case 18:
  7889  			op = ssaop.OpZeroExt8to64
  7890  		case 24:
  7891  			op = ssaop.OpZeroExt16to32
  7892  		case 28:
  7893  			op = ssaop.OpZeroExt16to64
  7894  		case 48:
  7895  			op = ssaop.OpZeroExt32to64
  7896  		default:
  7897  			s.Fatalf("bad unsigned index extension %s", idx.Type)
  7898  		}
  7899  	}
  7900  	return s.newValue1(op, types.Types[types.TINT], idx)
  7901  }
  7902  
  7903  // CheckLoweredPhi checks that regalloc and stackalloc correctly handled phi values.
  7904  // Called during ssaGenValue.
  7905  func CheckLoweredPhi(v *ssa.Value) {
  7906  	if v.Op != ssaop.OpPhi {
  7907  		v.Fatalf("CheckLoweredPhi called with non-phi value: %v", v.LongString())
  7908  	}
  7909  	if v.Type.IsMemory() {
  7910  		return
  7911  	}
  7912  	f := v.Block.Func
  7913  	loc := f.RegAlloc[v.ID]
  7914  	for _, a := range v.Args {
  7915  		if aloc := f.RegAlloc[a.ID]; aloc != loc { // TODO: .Equal() instead?
  7916  			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)
  7917  		}
  7918  	}
  7919  }
  7920  
  7921  // CheckLoweredGetClosurePtr checks that v is the first instruction in the function's entry block,
  7922  // except for incoming in-register arguments.
  7923  // The output of LoweredGetClosurePtr is generally hardwired to the correct register.
  7924  // That register contains the closure pointer on closure entry.
  7925  func CheckLoweredGetClosurePtr(v *ssa.Value) {
  7926  	entry := v.Block.Func.Entry
  7927  	if entry != v.Block {
  7928  		base.Fatalf("in %s, badly placed LoweredGetClosurePtr: %v %v", v.Block.Func.Name, v.Block, v)
  7929  	}
  7930  	for _, w := range entry.Values {
  7931  		if w == v {
  7932  			break
  7933  		}
  7934  		switch w.Op {
  7935  		case ssaop.OpArgIntReg, ssaop.OpArgFloatReg:
  7936  			// okay
  7937  		default:
  7938  			base.Fatalf("in %s, badly placed LoweredGetClosurePtr: %v %v", v.Block.Func.Name, v.Block, v)
  7939  		}
  7940  	}
  7941  }
  7942  
  7943  // CheckArgReg ensures that v is in the function's entry block.
  7944  func CheckArgReg(v *ssa.Value) {
  7945  	entry := v.Block.Func.Entry
  7946  	if entry != v.Block {
  7947  		base.Fatalf("in %s, badly placed ArgIReg or ArgFReg: %v %v", v.Block.Func.Name, v.Block, v)
  7948  	}
  7949  }
  7950  
  7951  func AddrAuto(a *obj.Addr, v *ssa.Value) {
  7952  	n, off := ssa.AutoVar(v)
  7953  	a.Type = obj.TYPE_MEM
  7954  	a.Sym = n.Linksym()
  7955  	a.Reg = int16(Arch.REGSP)
  7956  	a.Offset = n.FrameOffset() + off
  7957  	if n.Class == ir.PPARAM || (n.Class == ir.PPARAMOUT && !n.IsOutputParamInRegisters()) {
  7958  		a.Name = obj.NAME_PARAM
  7959  	} else {
  7960  		a.Name = obj.NAME_AUTO
  7961  	}
  7962  }
  7963  
  7964  // Call returns a new CALL instruction for the SSA value v.
  7965  // It uses PrepareCall to prepare the call.
  7966  func (s *State) Call(v *ssa.Value) *obj.Prog {
  7967  	pPosIsStmt := s.pp.Pos.IsStmt() // The statement-ness of the call comes from ssaGenState
  7968  	s.PrepareCall(v)
  7969  
  7970  	p := s.Prog(obj.ACALL)
  7971  	if pPosIsStmt == src.PosIsStmt {
  7972  		p.Pos = v.Pos.WithIsStmt()
  7973  	} else {
  7974  		p.Pos = v.Pos.WithNotStmt()
  7975  	}
  7976  	if sym, ok := v.Aux.(*ssa.AuxCall); ok && sym.Fn != nil {
  7977  		p.To.Type = obj.TYPE_MEM
  7978  		p.To.Name = obj.NAME_EXTERN
  7979  		p.To.Sym = sym.Fn
  7980  	} else {
  7981  		// TODO(mdempsky): Can these differences be eliminated?
  7982  		switch Arch.LinkArch.Family {
  7983  		case sys.AMD64, sys.I386, sys.PPC64, sys.RISCV64, sys.S390X, sys.Wasm:
  7984  			p.To.Type = obj.TYPE_REG
  7985  		case sys.ARM, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64:
  7986  			p.To.Type = obj.TYPE_MEM
  7987  		default:
  7988  			base.Fatalf("unknown indirect call family")
  7989  		}
  7990  		p.To.Reg = v.Args[0].Reg()
  7991  	}
  7992  	return p
  7993  }
  7994  
  7995  // TailCall returns a new tail call instruction for the SSA value v.
  7996  // It is like Call, but for a tail call.
  7997  func (s *State) TailCall(v *ssa.Value) *obj.Prog {
  7998  	p := s.Call(v)
  7999  	p.As = obj.ARET
  8000  	return p
  8001  }
  8002  
  8003  // PrepareCall prepares to emit a CALL instruction for v and does call-related bookkeeping.
  8004  // It must be called immediately before emitting the actual CALL instruction,
  8005  // since it emits PCDATA for the stack map at the call (calls are safe points).
  8006  func (s *State) PrepareCall(v *ssa.Value) {
  8007  	idx := s.livenessMap.Get(v)
  8008  	if !idx.StackMapValid() {
  8009  		// See Liveness.hasStackMap.
  8010  		if sym, ok := v.Aux.(*ssa.AuxCall); !ok || !(sym.Fn == ir.Syms.WBZero || sym.Fn == ir.Syms.WBMove) {
  8011  			base.Fatalf("missing stack map index for %v", v.LongString())
  8012  		}
  8013  	}
  8014  
  8015  	call, ok := v.Aux.(*ssa.AuxCall)
  8016  
  8017  	if ok {
  8018  		// Record call graph information for nowritebarrierrec
  8019  		// analysis.
  8020  		if nowritebarrierrecCheck != nil {
  8021  			nowritebarrierrecCheck.recordCall(s.pp.CurFunc, call.Fn, v.Pos)
  8022  		}
  8023  	}
  8024  
  8025  	if s.maxarg < v.AuxInt {
  8026  		s.maxarg = v.AuxInt
  8027  	}
  8028  }
  8029  
  8030  // UseArgs records the fact that an instruction needs a certain amount of
  8031  // callee args space for its use.
  8032  func (s *State) UseArgs(n int64) {
  8033  	if s.maxarg < n {
  8034  		s.maxarg = n
  8035  	}
  8036  }
  8037  
  8038  // fieldIdx finds the index of the field referred to by the ODOT node n.
  8039  func fieldIdx(n *ir.SelectorExpr) int {
  8040  	t := n.X.Type()
  8041  	if !isStructNotSIMD(t) {
  8042  		panic("ODOT's LHS is not a struct")
  8043  	}
  8044  
  8045  	for i, f := range t.Fields() {
  8046  		if f.Sym == n.Sel {
  8047  			if f.Offset != n.Offset() {
  8048  				panic("field offset doesn't match")
  8049  			}
  8050  			return i
  8051  		}
  8052  	}
  8053  	panic(fmt.Sprintf("can't find field in expr %v\n", n))
  8054  
  8055  	// TODO: keep the result of this function somewhere in the ODOT Node
  8056  	// so we don't have to recompute it each time we need it.
  8057  }
  8058  
  8059  // ssafn holds frontend information about a function that the backend is processing.
  8060  // It also exports a bunch of compiler services for the ssa backend.
  8061  type ssafn struct {
  8062  	curfn      *ir.Func
  8063  	strings    map[string]*obj.LSym // map from constant string to data symbols
  8064  	stksize    int64                // stack size for current frame
  8065  	stkptrsize int64                // prefix of stack containing pointers
  8066  
  8067  	// alignment for current frame.
  8068  	// NOTE: when stkalign > PtrSize, currently this only ensures the offsets of
  8069  	// objects in the stack frame are aligned. The stack pointer is still aligned
  8070  	// only PtrSize.
  8071  	stkalign int64
  8072  
  8073  	log bool // print ssa debug to the stdout
  8074  }
  8075  
  8076  // StringData returns a symbol which
  8077  // is the data component of a global string constant containing s.
  8078  func (e *ssafn) StringData(s string) *obj.LSym {
  8079  	if aux, ok := e.strings[s]; ok {
  8080  		return aux
  8081  	}
  8082  	if e.strings == nil {
  8083  		e.strings = make(map[string]*obj.LSym)
  8084  	}
  8085  	data := staticdata.StringSym(e.curfn.Pos(), s)
  8086  	e.strings[s] = data
  8087  	return data
  8088  }
  8089  
  8090  // SplitSlot returns a slot representing the data of parent starting at offset.
  8091  func (e *ssafn) SplitSlot(parent *ssa.LocalSlot, suffix string, offset int64, t *types.Type) ssa.LocalSlot {
  8092  	node := parent.N
  8093  
  8094  	if node.Class != ir.PAUTO || node.Addrtaken() {
  8095  		// addressed things and non-autos retain their parents (i.e., cannot truly be split)
  8096  		return ssa.LocalSlot{N: node, Type: t, Off: parent.Off + offset}
  8097  	}
  8098  
  8099  	sym := &types.Sym{Name: node.Sym().Name + suffix, Pkg: types.LocalPkg}
  8100  	n := e.curfn.NewLocal(parent.N.Pos(), sym, t)
  8101  	n.SetUsed(true)
  8102  	n.SetEsc(ir.EscNever)
  8103  	types.CalcSize(t)
  8104  	return ssa.LocalSlot{N: n, Type: t, Off: 0, SplitOf: parent, SplitOffset: offset}
  8105  }
  8106  
  8107  // Logf logs a message from the compiler.
  8108  func (e *ssafn) Logf(msg string, args ...any) {
  8109  	if e.log {
  8110  		fmt.Printf(msg, args...)
  8111  	}
  8112  }
  8113  
  8114  func (e *ssafn) Log() bool {
  8115  	return e.log
  8116  }
  8117  
  8118  // Fatalf reports a compiler error and exits.
  8119  func (e *ssafn) Fatalf(pos src.XPos, msg string, args ...any) {
  8120  	base.Pos = pos
  8121  	nargs := append([]any{ir.FuncName(e.curfn)}, args...)
  8122  	base.Fatalf("'%s': "+msg, nargs...)
  8123  }
  8124  
  8125  // Warnl reports a "warning", which is usually flag-triggered
  8126  // logging output for the benefit of tests.
  8127  func (e *ssafn) Warnl(pos src.XPos, fmt_ string, args ...any) {
  8128  	base.WarnfAt(pos, fmt_, args...)
  8129  }
  8130  
  8131  func (e *ssafn) Debug_checknil() bool {
  8132  	return base.Debug.Nil != 0
  8133  }
  8134  
  8135  func (e *ssafn) UseWriteBarrier() bool {
  8136  	return base.Flag.WB
  8137  }
  8138  
  8139  func (e *ssafn) Syslook(name string) *obj.LSym {
  8140  	switch name {
  8141  	case "goschedguarded":
  8142  		return ir.Syms.Goschedguarded
  8143  	case "writeBarrier":
  8144  		return ir.Syms.WriteBarrier
  8145  	case "wbZero":
  8146  		return ir.Syms.WBZero
  8147  	case "wbMove":
  8148  		return ir.Syms.WBMove
  8149  	case "cgoCheckMemmove":
  8150  		return ir.Syms.CgoCheckMemmove
  8151  	case "cgoCheckPtrWrite":
  8152  		return ir.Syms.CgoCheckPtrWrite
  8153  	}
  8154  	e.Fatalf(src.NoXPos, "unknown Syslook func %v", name)
  8155  	return nil
  8156  }
  8157  
  8158  func (e *ssafn) Func() *ir.Func {
  8159  	return e.curfn
  8160  }
  8161  
  8162  func clobberBase(n ir.Node) ir.Node {
  8163  	if n.Op() == ir.ODOT {
  8164  		n := n.(*ir.SelectorExpr)
  8165  		if n.X.Type().NumFields() == 1 {
  8166  			return clobberBase(n.X)
  8167  		}
  8168  	}
  8169  	if n.Op() == ir.OINDEX {
  8170  		n := n.(*ir.IndexExpr)
  8171  		if n.X.Type().IsArray() && n.X.Type().NumElem() == 1 {
  8172  			return clobberBase(n.X)
  8173  		}
  8174  	}
  8175  	return n
  8176  }
  8177  
  8178  // callTargetLSym returns the correct LSym to call 'callee' using its ABI.
  8179  func callTargetLSym(callee *ir.Name) *obj.LSym {
  8180  	if callee.Func == nil {
  8181  		// TODO(austin): This happens in case of interface method I.M from imported package.
  8182  		// It's ABIInternal, and would be better if callee.Func was never nil and we didn't
  8183  		// need this case.
  8184  		return callee.Linksym()
  8185  	}
  8186  
  8187  	return callee.LinksymABI(callee.Func.ABI)
  8188  }
  8189  
  8190  // deferStructFnField is the field index of _defer.fn.
  8191  const deferStructFnField = 4
  8192  
  8193  var deferType *types.Type
  8194  
  8195  // deferstruct returns a type interchangeable with runtime._defer.
  8196  // Make sure this stays in sync with runtime/runtime2.go:_defer.
  8197  func deferstruct() *types.Type {
  8198  	if deferType != nil {
  8199  		return deferType
  8200  	}
  8201  
  8202  	makefield := func(name string, t *types.Type) *types.Field {
  8203  		sym := (*types.Pkg)(nil).Lookup(name)
  8204  		return types.NewField(src.NoXPos, sym, t)
  8205  	}
  8206  
  8207  	fields := []*types.Field{
  8208  		makefield("heap", types.Types[types.TBOOL]),
  8209  		makefield("rangefunc", types.Types[types.TBOOL]),
  8210  		makefield("sp", types.Types[types.TUINTPTR]),
  8211  		makefield("pc", types.Types[types.TUINTPTR]),
  8212  		// Note: the types here don't really matter. Defer structures
  8213  		// are always scanned explicitly during stack copying and GC,
  8214  		// so we make them uintptr type even though they are real pointers.
  8215  		makefield("fn", types.Types[types.TUINTPTR]),
  8216  		makefield("link", types.Types[types.TUINTPTR]),
  8217  		makefield("head", types.Types[types.TUINTPTR]),
  8218  	}
  8219  	if name := fields[deferStructFnField].Sym.Name; name != "fn" {
  8220  		base.Fatalf("deferStructFnField is %q, not fn", name)
  8221  	}
  8222  
  8223  	n := ir.NewDeclNameAt(src.NoXPos, ir.OTYPE, ir.Pkgs.Runtime.Lookup("_defer"))
  8224  	typ := types.NewNamed(n)
  8225  	n.SetType(typ)
  8226  	n.SetTypecheck(1)
  8227  
  8228  	// build struct holding the above fields
  8229  	typ.SetUnderlying(types.NewStruct(fields))
  8230  	types.CalcStructSize(typ)
  8231  
  8232  	deferType = typ
  8233  	return typ
  8234  }
  8235  
  8236  // SpillSlotAddr uses LocalSlot information to initialize an obj.Addr
  8237  // The resulting addr is used in a non-standard context -- in the prologue
  8238  // of a function, before the frame has been constructed, so the standard
  8239  // addressing for the parameters will be wrong.
  8240  func SpillSlotAddr(spill ssa.Spill, baseReg int16, extraOffset int64) obj.Addr {
  8241  	return obj.Addr{
  8242  		Name:   obj.NAME_NONE,
  8243  		Type:   obj.TYPE_MEM,
  8244  		Reg:    baseReg,
  8245  		Offset: spill.Offset + extraOffset,
  8246  	}
  8247  }
  8248  
  8249  func isStructNotSIMD(t *types.Type) bool {
  8250  	return t.IsStruct() && !t.IsSIMD()
  8251  }
  8252  
  8253  var BoundsCheckFunc [ssa.BoundsKindCount]*obj.LSym
  8254  

View as plain text