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