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