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