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