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