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