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.
19 "cmd/compile/internal/abi"
20 "cmd/compile/internal/base"
21 "cmd/compile/internal/ir"
22 "cmd/compile/internal/liveness"
23 "cmd/compile/internal/objw"
24 "cmd/compile/internal/reflectdata"
25 "cmd/compile/internal/ssa"
26 "cmd/compile/internal/staticdata"
27 "cmd/compile/internal/typecheck"
28 "cmd/compile/internal/types"
37 var ssaConfig *ssa.Config
38 var ssaCaches []ssa.Cache
40 var ssaDump string // early copy of $GOSSAFUNC; the func name to dump output for
41 var ssaDir string // optional destination for ssa dump file
42 var ssaDumpStdout bool // whether to dump to stdout
43 var ssaDumpCFG string // generate CFGs for these phases
44 const ssaDumpFile = "ssa.html"
46 // ssaDumpInlined holds all inlined functions when ssaDump contains a function name.
47 var ssaDumpInlined []*ir.Func
49 func DumpInline(fn *ir.Func) {
50 if ssaDump != "" && ssaDump == ir.FuncName(fn) {
51 ssaDumpInlined = append(ssaDumpInlined, fn)
56 ssaDump = os.Getenv("GOSSAFUNC")
57 ssaDir = os.Getenv("GOSSADIR")
59 if strings.HasSuffix(ssaDump, "+") {
60 ssaDump = ssaDump[:len(ssaDump)-1]
63 spl := strings.Split(ssaDump, ":")
72 types_ := ssa.NewTypes()
78 // Generate a few pointer types that are uncommon in the frontend but common in the backend.
79 // Caching is disabled in the backend, so generating these here avoids allocations.
80 _ = types.NewPtr(types.Types[types.TINTER]) // *interface{}
81 _ = types.NewPtr(types.NewPtr(types.Types[types.TSTRING])) // **string
82 _ = types.NewPtr(types.NewSlice(types.Types[types.TINTER])) // *[]interface{}
83 _ = types.NewPtr(types.NewPtr(types.ByteType)) // **byte
84 _ = types.NewPtr(types.NewSlice(types.ByteType)) // *[]byte
85 _ = types.NewPtr(types.NewSlice(types.Types[types.TSTRING])) // *[]string
86 _ = types.NewPtr(types.NewPtr(types.NewPtr(types.Types[types.TUINT8]))) // ***uint8
87 _ = types.NewPtr(types.Types[types.TINT16]) // *int16
88 _ = types.NewPtr(types.Types[types.TINT64]) // *int64
89 _ = types.NewPtr(types.ErrorType) // *error
90 _ = types.NewPtr(reflectdata.MapType()) // *runtime.hmap
91 _ = types.NewPtr(deferstruct()) // *runtime._defer
92 types.NewPtrCacheEnabled = false
93 ssaConfig = ssa.NewConfig(base.Ctxt.Arch.Name, *types_, base.Ctxt, base.Flag.N == 0, Arch.SoftFloat)
94 ssaConfig.Race = base.Flag.Race
95 ssaCaches = make([]ssa.Cache, base.Flag.LowerC)
97 // Set up some runtime functions we'll need to call.
98 ir.Syms.AssertE2I = typecheck.LookupRuntimeFunc("assertE2I")
99 ir.Syms.AssertE2I2 = typecheck.LookupRuntimeFunc("assertE2I2")
100 ir.Syms.AssertI2I = typecheck.LookupRuntimeFunc("assertI2I")
101 ir.Syms.AssertI2I2 = typecheck.LookupRuntimeFunc("assertI2I2")
102 ir.Syms.CgoCheckMemmove = typecheck.LookupRuntimeFunc("cgoCheckMemmove")
103 ir.Syms.CgoCheckPtrWrite = typecheck.LookupRuntimeFunc("cgoCheckPtrWrite")
104 ir.Syms.CheckPtrAlignment = typecheck.LookupRuntimeFunc("checkptrAlignment")
105 ir.Syms.Deferproc = typecheck.LookupRuntimeFunc("deferproc")
106 ir.Syms.Deferprocat = typecheck.LookupRuntimeFunc("deferprocat")
107 ir.Syms.DeferprocStack = typecheck.LookupRuntimeFunc("deferprocStack")
108 ir.Syms.Deferreturn = typecheck.LookupRuntimeFunc("deferreturn")
109 ir.Syms.Duffcopy = typecheck.LookupRuntimeFunc("duffcopy")
110 ir.Syms.Duffzero = typecheck.LookupRuntimeFunc("duffzero")
111 ir.Syms.GCWriteBarrier[0] = typecheck.LookupRuntimeFunc("gcWriteBarrier1")
112 ir.Syms.GCWriteBarrier[1] = typecheck.LookupRuntimeFunc("gcWriteBarrier2")
113 ir.Syms.GCWriteBarrier[2] = typecheck.LookupRuntimeFunc("gcWriteBarrier3")
114 ir.Syms.GCWriteBarrier[3] = typecheck.LookupRuntimeFunc("gcWriteBarrier4")
115 ir.Syms.GCWriteBarrier[4] = typecheck.LookupRuntimeFunc("gcWriteBarrier5")
116 ir.Syms.GCWriteBarrier[5] = typecheck.LookupRuntimeFunc("gcWriteBarrier6")
117 ir.Syms.GCWriteBarrier[6] = typecheck.LookupRuntimeFunc("gcWriteBarrier7")
118 ir.Syms.GCWriteBarrier[7] = typecheck.LookupRuntimeFunc("gcWriteBarrier8")
119 ir.Syms.Goschedguarded = typecheck.LookupRuntimeFunc("goschedguarded")
120 ir.Syms.Growslice = typecheck.LookupRuntimeFunc("growslice")
121 ir.Syms.InterfaceSwitch = typecheck.LookupRuntimeFunc("interfaceSwitch")
122 ir.Syms.Memmove = typecheck.LookupRuntimeFunc("memmove")
123 ir.Syms.Msanread = typecheck.LookupRuntimeFunc("msanread")
124 ir.Syms.Msanwrite = typecheck.LookupRuntimeFunc("msanwrite")
125 ir.Syms.Msanmove = typecheck.LookupRuntimeFunc("msanmove")
126 ir.Syms.Asanread = typecheck.LookupRuntimeFunc("asanread")
127 ir.Syms.Asanwrite = typecheck.LookupRuntimeFunc("asanwrite")
128 ir.Syms.Newobject = typecheck.LookupRuntimeFunc("newobject")
129 ir.Syms.Newproc = typecheck.LookupRuntimeFunc("newproc")
130 ir.Syms.Panicdivide = typecheck.LookupRuntimeFunc("panicdivide")
131 ir.Syms.PanicdottypeE = typecheck.LookupRuntimeFunc("panicdottypeE")
132 ir.Syms.PanicdottypeI = typecheck.LookupRuntimeFunc("panicdottypeI")
133 ir.Syms.Panicnildottype = typecheck.LookupRuntimeFunc("panicnildottype")
134 ir.Syms.Panicoverflow = typecheck.LookupRuntimeFunc("panicoverflow")
135 ir.Syms.Panicshift = typecheck.LookupRuntimeFunc("panicshift")
136 ir.Syms.Racefuncenter = typecheck.LookupRuntimeFunc("racefuncenter")
137 ir.Syms.Racefuncexit = typecheck.LookupRuntimeFunc("racefuncexit")
138 ir.Syms.Raceread = typecheck.LookupRuntimeFunc("raceread")
139 ir.Syms.Racereadrange = typecheck.LookupRuntimeFunc("racereadrange")
140 ir.Syms.Racewrite = typecheck.LookupRuntimeFunc("racewrite")
141 ir.Syms.Racewriterange = typecheck.LookupRuntimeFunc("racewriterange")
142 ir.Syms.TypeAssert = typecheck.LookupRuntimeFunc("typeAssert")
143 ir.Syms.WBZero = typecheck.LookupRuntimeFunc("wbZero")
144 ir.Syms.WBMove = typecheck.LookupRuntimeFunc("wbMove")
145 ir.Syms.X86HasPOPCNT = typecheck.LookupRuntimeVar("x86HasPOPCNT") // bool
146 ir.Syms.X86HasSSE41 = typecheck.LookupRuntimeVar("x86HasSSE41") // bool
147 ir.Syms.X86HasFMA = typecheck.LookupRuntimeVar("x86HasFMA") // bool
148 ir.Syms.ARMHasVFPv4 = typecheck.LookupRuntimeVar("armHasVFPv4") // bool
149 ir.Syms.ARM64HasATOMICS = typecheck.LookupRuntimeVar("arm64HasATOMICS") // bool
150 ir.Syms.Staticuint64s = typecheck.LookupRuntimeVar("staticuint64s")
151 ir.Syms.Typedmemmove = typecheck.LookupRuntimeFunc("typedmemmove")
152 ir.Syms.Udiv = typecheck.LookupRuntimeVar("udiv") // asm func with special ABI
153 ir.Syms.WriteBarrier = typecheck.LookupRuntimeVar("writeBarrier") // struct { bool; ... }
154 ir.Syms.Zerobase = typecheck.LookupRuntimeVar("zerobase")
156 if Arch.LinkArch.Family == sys.Wasm {
157 BoundsCheckFunc[ssa.BoundsIndex] = typecheck.LookupRuntimeFunc("goPanicIndex")
158 BoundsCheckFunc[ssa.BoundsIndexU] = typecheck.LookupRuntimeFunc("goPanicIndexU")
159 BoundsCheckFunc[ssa.BoundsSliceAlen] = typecheck.LookupRuntimeFunc("goPanicSliceAlen")
160 BoundsCheckFunc[ssa.BoundsSliceAlenU] = typecheck.LookupRuntimeFunc("goPanicSliceAlenU")
161 BoundsCheckFunc[ssa.BoundsSliceAcap] = typecheck.LookupRuntimeFunc("goPanicSliceAcap")
162 BoundsCheckFunc[ssa.BoundsSliceAcapU] = typecheck.LookupRuntimeFunc("goPanicSliceAcapU")
163 BoundsCheckFunc[ssa.BoundsSliceB] = typecheck.LookupRuntimeFunc("goPanicSliceB")
164 BoundsCheckFunc[ssa.BoundsSliceBU] = typecheck.LookupRuntimeFunc("goPanicSliceBU")
165 BoundsCheckFunc[ssa.BoundsSlice3Alen] = typecheck.LookupRuntimeFunc("goPanicSlice3Alen")
166 BoundsCheckFunc[ssa.BoundsSlice3AlenU] = typecheck.LookupRuntimeFunc("goPanicSlice3AlenU")
167 BoundsCheckFunc[ssa.BoundsSlice3Acap] = typecheck.LookupRuntimeFunc("goPanicSlice3Acap")
168 BoundsCheckFunc[ssa.BoundsSlice3AcapU] = typecheck.LookupRuntimeFunc("goPanicSlice3AcapU")
169 BoundsCheckFunc[ssa.BoundsSlice3B] = typecheck.LookupRuntimeFunc("goPanicSlice3B")
170 BoundsCheckFunc[ssa.BoundsSlice3BU] = typecheck.LookupRuntimeFunc("goPanicSlice3BU")
171 BoundsCheckFunc[ssa.BoundsSlice3C] = typecheck.LookupRuntimeFunc("goPanicSlice3C")
172 BoundsCheckFunc[ssa.BoundsSlice3CU] = typecheck.LookupRuntimeFunc("goPanicSlice3CU")
173 BoundsCheckFunc[ssa.BoundsConvert] = typecheck.LookupRuntimeFunc("goPanicSliceConvert")
175 BoundsCheckFunc[ssa.BoundsIndex] = typecheck.LookupRuntimeFunc("panicIndex")
176 BoundsCheckFunc[ssa.BoundsIndexU] = typecheck.LookupRuntimeFunc("panicIndexU")
177 BoundsCheckFunc[ssa.BoundsSliceAlen] = typecheck.LookupRuntimeFunc("panicSliceAlen")
178 BoundsCheckFunc[ssa.BoundsSliceAlenU] = typecheck.LookupRuntimeFunc("panicSliceAlenU")
179 BoundsCheckFunc[ssa.BoundsSliceAcap] = typecheck.LookupRuntimeFunc("panicSliceAcap")
180 BoundsCheckFunc[ssa.BoundsSliceAcapU] = typecheck.LookupRuntimeFunc("panicSliceAcapU")
181 BoundsCheckFunc[ssa.BoundsSliceB] = typecheck.LookupRuntimeFunc("panicSliceB")
182 BoundsCheckFunc[ssa.BoundsSliceBU] = typecheck.LookupRuntimeFunc("panicSliceBU")
183 BoundsCheckFunc[ssa.BoundsSlice3Alen] = typecheck.LookupRuntimeFunc("panicSlice3Alen")
184 BoundsCheckFunc[ssa.BoundsSlice3AlenU] = typecheck.LookupRuntimeFunc("panicSlice3AlenU")
185 BoundsCheckFunc[ssa.BoundsSlice3Acap] = typecheck.LookupRuntimeFunc("panicSlice3Acap")
186 BoundsCheckFunc[ssa.BoundsSlice3AcapU] = typecheck.LookupRuntimeFunc("panicSlice3AcapU")
187 BoundsCheckFunc[ssa.BoundsSlice3B] = typecheck.LookupRuntimeFunc("panicSlice3B")
188 BoundsCheckFunc[ssa.BoundsSlice3BU] = typecheck.LookupRuntimeFunc("panicSlice3BU")
189 BoundsCheckFunc[ssa.BoundsSlice3C] = typecheck.LookupRuntimeFunc("panicSlice3C")
190 BoundsCheckFunc[ssa.BoundsSlice3CU] = typecheck.LookupRuntimeFunc("panicSlice3CU")
191 BoundsCheckFunc[ssa.BoundsConvert] = typecheck.LookupRuntimeFunc("panicSliceConvert")
193 if Arch.LinkArch.PtrSize == 4 {
194 ExtendCheckFunc[ssa.BoundsIndex] = typecheck.LookupRuntimeVar("panicExtendIndex")
195 ExtendCheckFunc[ssa.BoundsIndexU] = typecheck.LookupRuntimeVar("panicExtendIndexU")
196 ExtendCheckFunc[ssa.BoundsSliceAlen] = typecheck.LookupRuntimeVar("panicExtendSliceAlen")
197 ExtendCheckFunc[ssa.BoundsSliceAlenU] = typecheck.LookupRuntimeVar("panicExtendSliceAlenU")
198 ExtendCheckFunc[ssa.BoundsSliceAcap] = typecheck.LookupRuntimeVar("panicExtendSliceAcap")
199 ExtendCheckFunc[ssa.BoundsSliceAcapU] = typecheck.LookupRuntimeVar("panicExtendSliceAcapU")
200 ExtendCheckFunc[ssa.BoundsSliceB] = typecheck.LookupRuntimeVar("panicExtendSliceB")
201 ExtendCheckFunc[ssa.BoundsSliceBU] = typecheck.LookupRuntimeVar("panicExtendSliceBU")
202 ExtendCheckFunc[ssa.BoundsSlice3Alen] = typecheck.LookupRuntimeVar("panicExtendSlice3Alen")
203 ExtendCheckFunc[ssa.BoundsSlice3AlenU] = typecheck.LookupRuntimeVar("panicExtendSlice3AlenU")
204 ExtendCheckFunc[ssa.BoundsSlice3Acap] = typecheck.LookupRuntimeVar("panicExtendSlice3Acap")
205 ExtendCheckFunc[ssa.BoundsSlice3AcapU] = typecheck.LookupRuntimeVar("panicExtendSlice3AcapU")
206 ExtendCheckFunc[ssa.BoundsSlice3B] = typecheck.LookupRuntimeVar("panicExtendSlice3B")
207 ExtendCheckFunc[ssa.BoundsSlice3BU] = typecheck.LookupRuntimeVar("panicExtendSlice3BU")
208 ExtendCheckFunc[ssa.BoundsSlice3C] = typecheck.LookupRuntimeVar("panicExtendSlice3C")
209 ExtendCheckFunc[ssa.BoundsSlice3CU] = typecheck.LookupRuntimeVar("panicExtendSlice3CU")
212 // Wasm (all asm funcs with special ABIs)
213 ir.Syms.WasmDiv = typecheck.LookupRuntimeVar("wasmDiv")
214 ir.Syms.WasmTruncS = typecheck.LookupRuntimeVar("wasmTruncS")
215 ir.Syms.WasmTruncU = typecheck.LookupRuntimeVar("wasmTruncU")
216 ir.Syms.SigPanic = typecheck.LookupRuntimeFunc("sigpanic")
219 // AbiForBodylessFuncStackMap returns the ABI for a bodyless function's stack map.
220 // This is not necessarily the ABI used to call it.
221 // Currently (1.17 dev) such a stack map is always ABI0;
222 // any ABI wrapper that is present is nosplit, hence a precise
223 // stack map is not needed there (the parameters survive only long
224 // enough to call the wrapped assembly function).
225 // This always returns a freshly copied ABI.
226 func AbiForBodylessFuncStackMap(fn *ir.Func) *abi.ABIConfig {
227 return ssaConfig.ABI0.Copy() // No idea what races will result, be safe
230 // abiForFunc implements ABI policy for a function, but does not return a copy of the ABI.
231 // Passing a nil function returns the default ABI based on experiment configuration.
232 func abiForFunc(fn *ir.Func, abi0, abi1 *abi.ABIConfig) *abi.ABIConfig {
233 if buildcfg.Experiment.RegabiArgs {
234 // Select the ABI based on the function's defining ABI.
241 case obj.ABIInternal:
242 // TODO(austin): Clean up the nomenclature here.
243 // It's not clear that "abi1" is ABIInternal.
246 base.Fatalf("function %v has unknown ABI %v", fn, fn.ABI)
247 panic("not reachable")
252 if fn.Pragma&ir.RegisterParams != 0 { // TODO(register args) remove after register abi is working
259 // dvarint writes a varint v to the funcdata in symbol x and returns the new offset.
260 func dvarint(x *obj.LSym, off int, v int64) int {
261 if v < 0 || v > 1e9 {
262 panic(fmt.Sprintf("dvarint: bad offset for funcdata - %v", v))
265 return objw.Uint8(x, off, uint8(v))
267 off = objw.Uint8(x, off, uint8((v&127)|128))
269 return objw.Uint8(x, off, uint8(v>>7))
271 off = objw.Uint8(x, off, uint8(((v>>7)&127)|128))
273 return objw.Uint8(x, off, uint8(v>>14))
275 off = objw.Uint8(x, off, uint8(((v>>14)&127)|128))
277 return objw.Uint8(x, off, uint8(v>>21))
279 off = objw.Uint8(x, off, uint8(((v>>21)&127)|128))
280 return objw.Uint8(x, off, uint8(v>>28))
283 // emitOpenDeferInfo emits FUNCDATA information about the defers in a function
284 // that is using open-coded defers. This funcdata is used to determine the active
285 // defers in a function and execute those defers during panic processing.
287 // The funcdata is all encoded in varints (since values will almost always be less than
288 // 128, but stack offsets could potentially be up to 2Gbyte). All "locations" (offsets)
289 // for stack variables are specified as the number of bytes below varp (pointer to the
290 // top of the local variables) for their starting address. The format is:
292 // - Offset of the deferBits variable
293 // - Offset of the first closure slot (the rest are laid out consecutively).
294 func (s *state) emitOpenDeferInfo() {
295 firstOffset := s.openDefers[0].closureNode.FrameOffset()
297 // Verify that cmpstackvarlt laid out the slots in order.
298 for i, r := range s.openDefers {
299 have := r.closureNode.FrameOffset()
300 want := firstOffset + int64(i)*int64(types.PtrSize)
302 base.FatalfAt(s.curfn.Pos(), "unexpected frame offset for open-coded defer slot #%v: have %v, want %v", i, have, want)
306 x := base.Ctxt.Lookup(s.curfn.LSym.Name + ".opendefer")
307 x.Set(obj.AttrContentAddressable, true)
308 s.curfn.LSym.Func().OpenCodedDeferInfo = x
311 off = dvarint(x, off, -s.deferBitsTemp.FrameOffset())
312 off = dvarint(x, off, -firstOffset)
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)
320 abiSelf := abiForFunc(fn, ssaConfig.ABI0, ssaConfig.ABI1)
323 // match either a simple name e.g. "(*Reader).Reset", package.name e.g. "compress/gzip.(*Reader).Reset", or subpackage name "gzip.(*Reader).Reset"
324 // optionally allows an ABI suffix specification in the GOSSAHASH, e.g. "(*Reader).Reset<0>" etc
325 if strings.Contains(ssaDump, name) { // in all the cases the function name is entirely contained within the GOSSAFUNC string.
327 if strings.Contains(ssaDump, ",") { // ABI specification
328 nameOptABI = ssa.FuncNameABI(name, abiSelf.Which())
329 } else if strings.HasSuffix(ssaDump, ">") { // if they use the linker syntax instead....
331 if l >= 3 && ssaDump[l-3] == '<' {
332 nameOptABI = ssa.FuncNameABI(name, abiSelf.Which())
333 ssaDump = ssaDump[:l-3] + "," + ssaDump[l-2:l-1]
336 pkgDotName := base.Ctxt.Pkgpath + "." + nameOptABI
337 printssa = nameOptABI == ssaDump || // "(*Reader).Reset"
338 pkgDotName == ssaDump || // "compress/gzip.(*Reader).Reset"
339 strings.HasSuffix(pkgDotName, ssaDump) && strings.HasSuffix(pkgDotName, "/"+ssaDump) // "gzip.(*Reader).Reset"
342 var astBuf *bytes.Buffer
344 astBuf = &bytes.Buffer{}
345 ir.FDumpList(astBuf, "buildssa-body", fn.Body)
347 fmt.Println("generating SSA for", name)
348 fmt.Print(astBuf.String())
356 s.hasdefer = fn.HasDefer()
357 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
358 s.cgoUnsafeArgs = true
360 s.checkPtrEnabled = ir.ShouldCheckPtr(fn, 1)
362 if base.Flag.Cfg.Instrumenting && fn.Pragma&ir.Norace == 0 && !fn.Linksym().ABIWrapper() {
363 if !base.Flag.Race || !objabi.LookupPkgSpecial(fn.Sym().Pkg.Path).NoRaceFunc {
364 s.instrumentMemory = true
367 s.instrumentEnterExit = true
373 log: printssa && ssaDumpStdout,
377 cache := &ssaCaches[worker]
380 s.f = ssaConfig.NewFunc(&fe, cache)
384 s.f.PrintOrHtmlSSA = printssa
385 if fn.Pragma&ir.Nosplit != 0 {
388 s.f.ABI0 = ssaConfig.ABI0
389 s.f.ABI1 = ssaConfig.ABI1
390 s.f.ABIDefault = abiForFunc(nil, ssaConfig.ABI0, ssaConfig.ABI1)
391 s.f.ABISelf = abiSelf
393 s.panics = map[funcLine]*ssa.Block{}
394 s.softFloat = s.config.SoftFloat
396 // Allocate starting block
397 s.f.Entry = s.f.NewBlock(ssa.BlockPlain)
398 s.f.Entry.Pos = fn.Pos()
403 ssaDF = filepath.Join(ssaDir, base.Ctxt.Pkgpath+"."+s.f.NameABI()+".html")
404 ssaD := filepath.Dir(ssaDF)
405 os.MkdirAll(ssaD, 0755)
407 s.f.HTMLWriter = ssa.NewHTMLWriter(ssaDF, s.f, ssaDumpCFG)
408 // TODO: generate and print a mapping from nodes to values and blocks
409 dumpSourcesColumn(s.f.HTMLWriter, fn)
410 s.f.HTMLWriter.WriteAST("AST", astBuf)
413 // Allocate starting values
414 s.labels = map[string]*ssaLabel{}
415 s.fwdVars = map[ir.Node]*ssa.Value{}
416 s.startmem = s.entryNewValue0(ssa.OpInitMem, types.TypeMem)
418 s.hasOpenDefers = base.Flag.N == 0 && s.hasdefer && !s.curfn.OpenCodedDeferDisallowed()
420 case base.Debug.NoOpenDefer != 0:
421 s.hasOpenDefers = false
422 case s.hasOpenDefers && (base.Ctxt.Flag_shared || base.Ctxt.Flag_dynlink) && base.Ctxt.Arch.Name == "386":
423 // Don't support open-coded defers for 386 ONLY when using shared
424 // libraries, because there is extra code (added by rewriteToUseGot())
425 // preceding the deferreturn/ret code that we don't track correctly.
426 s.hasOpenDefers = false
428 if s.hasOpenDefers && s.instrumentEnterExit {
429 // Skip doing open defers if we need to instrument function
430 // returns for the race detector, since we will not generate that
431 // code in the case of the extra deferreturn/ret segment.
432 s.hasOpenDefers = false
435 // Similarly, skip if there are any heap-allocated result
436 // parameters that need to be copied back to their stack slots.
437 for _, f := range s.curfn.Type().Results() {
438 if !f.Nname.(*ir.Name).OnStack() {
439 s.hasOpenDefers = false
444 if s.hasOpenDefers &&
445 s.curfn.NumReturns*s.curfn.NumDefers > 15 {
446 // Since we are generating defer calls at every exit for
447 // open-coded defers, skip doing open-coded defers if there are
448 // too many returns (especially if there are multiple defers).
449 // Open-coded defers are most important for improving performance
450 // for smaller functions (which don't have many returns).
451 s.hasOpenDefers = false
454 s.sp = s.entryNewValue0(ssa.OpSP, types.Types[types.TUINTPTR]) // TODO: use generic pointer type (unsafe.Pointer?) instead
455 s.sb = s.entryNewValue0(ssa.OpSB, types.Types[types.TUINTPTR])
457 s.startBlock(s.f.Entry)
458 s.vars[memVar] = s.startmem
460 // Create the deferBits variable and stack slot. deferBits is a
461 // bitmask showing which of the open-coded defers in this function
462 // have been activated.
463 deferBitsTemp := typecheck.TempAt(src.NoXPos, s.curfn, types.Types[types.TUINT8])
464 deferBitsTemp.SetAddrtaken(true)
465 s.deferBitsTemp = deferBitsTemp
466 // For this value, AuxInt is initialized to zero by default
467 startDeferBits := s.entryNewValue0(ssa.OpConst8, types.Types[types.TUINT8])
468 s.vars[deferBitsVar] = startDeferBits
469 s.deferBitsAddr = s.addr(deferBitsTemp)
470 s.store(types.Types[types.TUINT8], s.deferBitsAddr, startDeferBits)
471 // Make sure that the deferBits stack slot is kept alive (for use
472 // by panics) and stores to deferBits are not eliminated, even if
473 // all checking code on deferBits in the function exit can be
474 // eliminated, because the defer statements were all
476 s.vars[memVar] = s.newValue1Apos(ssa.OpVarLive, types.TypeMem, deferBitsTemp, s.mem(), false)
479 var params *abi.ABIParamResultInfo
480 params = s.f.ABISelf.ABIAnalyze(fn.Type(), true)
482 // The backend's stackframe pass prunes away entries from the fn's
483 // Dcl list, including PARAMOUT nodes that correspond to output
484 // params passed in registers. Walk the Dcl list and capture these
485 // nodes to a side list, so that we'll have them available during
486 // DWARF-gen later on. See issue 48573 for more details.
487 var debugInfo ssa.FuncDebug
488 for _, n := range fn.Dcl {
489 if n.Class == ir.PPARAMOUT && n.IsOutputParamInRegisters() {
490 debugInfo.RegOutputParams = append(debugInfo.RegOutputParams, n)
493 fn.DebugInfo = &debugInfo
495 // Generate addresses of local declarations
496 s.decladdrs = map[*ir.Name]*ssa.Value{}
497 for _, n := range fn.Dcl {
500 // Be aware that blank and unnamed input parameters will not appear here, but do appear in the type
501 s.decladdrs[n] = s.entryNewValue2A(ssa.OpLocalAddr, types.NewPtr(n.Type()), n, s.sp, s.startmem)
503 s.decladdrs[n] = s.entryNewValue2A(ssa.OpLocalAddr, types.NewPtr(n.Type()), n, s.sp, s.startmem)
505 // processed at each use, to prevent Addr coming
508 s.Fatalf("local variable with class %v unimplemented", n.Class)
512 s.f.OwnAux = ssa.OwnAuxCall(fn.LSym, params)
514 // Populate SSAable arguments.
515 for _, n := range fn.Dcl {
516 if n.Class == ir.PPARAM {
518 v := s.newValue0A(ssa.OpArg, n.Type(), n)
520 s.addNamedValue(n, v) // This helps with debugging information, not needed for compilation itself.
521 } else { // address was taken AND/OR too large for SSA
522 paramAssignment := ssa.ParamAssignmentForArgName(s.f, n)
523 if len(paramAssignment.Registers) > 0 {
524 if ssa.CanSSA(n.Type()) { // SSA-able type, so address was taken -- receive value in OpArg, DO NOT bind to var, store immediately to memory.
525 v := s.newValue0A(ssa.OpArg, n.Type(), n)
526 s.store(n.Type(), s.decladdrs[n], v)
527 } else { // Too big for SSA.
528 // Brute force, and early, do a bunch of stores from registers
529 // TODO fix the nasty storeArgOrLoad recursion in ssa/expand_calls.go so this Just Works with store of a big Arg.
530 s.storeParameterRegsToStack(s.f.ABISelf, paramAssignment, n, s.decladdrs[n], false)
537 // Populate closure variables.
539 clo := s.entryNewValue0(ssa.OpGetClosurePtr, s.f.Config.Types.BytePtr)
540 offset := int64(types.PtrSize) // PtrSize to skip past function entry PC field
541 for _, n := range fn.ClosureVars {
544 typ = types.NewPtr(typ)
547 offset = types.RoundUp(offset, typ.Alignment())
548 ptr := s.newValue1I(ssa.OpOffPtr, types.NewPtr(typ), offset, clo)
551 // If n is a small variable captured by value, promote
552 // it to PAUTO so it can be converted to SSA.
554 // Note: While we never capture a variable by value if
555 // the user took its address, we may have generated
556 // runtime calls that did (#43701). Since we don't
557 // convert Addrtaken variables to SSA anyway, no point
558 // in promoting them either.
559 if n.Byval() && !n.Addrtaken() && ssa.CanSSA(n.Type()) {
561 fn.Dcl = append(fn.Dcl, n)
562 s.assign(n, s.load(n.Type(), ptr), false, 0)
567 ptr = s.load(typ, ptr)
569 s.setHeapaddr(fn.Pos(), n, ptr)
573 // Convert the AST-based IR to the SSA-based IR
574 if s.instrumentEnterExit {
575 s.rtcall(ir.Syms.Racefuncenter, true, nil, s.newValue0(ssa.OpGetCallerPC, types.Types[types.TUINTPTR]))
581 // fallthrough to exit
582 if s.curBlock != nil {
583 s.pushLine(fn.Endlineno)
588 for _, b := range s.f.Blocks {
589 if b.Pos != src.NoXPos {
590 s.updateUnsetPredPos(b)
594 s.f.HTMLWriter.WritePhase("before insert phis", "before insert phis")
598 // Main call to ssa package to compile function
603 if len(s.openDefers) != 0 {
604 s.emitOpenDeferInfo()
607 // Record incoming parameter spill information for morestack calls emitted in the assembler.
608 // This is done here, using all the parameters (used, partially used, and unused) because
609 // it mimics the behavior of the former ABI (everything stored) and because it's not 100%
610 // clear if naming conventions are respected in autogenerated code.
611 // TODO figure out exactly what's unused, don't spill it. Make liveness fine-grained, also.
612 for _, p := range params.InParams() {
613 typs, offs := p.RegisterTypesAndOffsets()
614 for i, t := range typs {
615 o := offs[i] // offset within parameter
616 fo := p.FrameOffset(params) // offset of parameter in frame
617 reg := ssa.ObjRegForAbiReg(p.Registers[i], s.f.Config)
618 s.f.RegArgs = append(s.f.RegArgs, ssa.Spill{Reg: reg, Offset: fo + o, Type: t})
625 func (s *state) storeParameterRegsToStack(abi *abi.ABIConfig, paramAssignment *abi.ABIParamAssignment, n *ir.Name, addr *ssa.Value, pointersOnly bool) {
626 typs, offs := paramAssignment.RegisterTypesAndOffsets()
627 for i, t := range typs {
628 if pointersOnly && !t.IsPtrShaped() {
631 r := paramAssignment.Registers[i]
633 op, reg := ssa.ArgOpAndRegisterFor(r, abi)
634 aux := &ssa.AuxNameOffset{Name: n, Offset: o}
635 v := s.newValue0I(op, t, reg)
637 p := s.newValue1I(ssa.OpOffPtr, types.NewPtr(t), o, addr)
642 // zeroResults zeros the return values at the start of the function.
643 // We need to do this very early in the function. Defer might stop a
644 // panic and show the return values as they exist at the time of
645 // panic. For precise stacks, the garbage collector assumes results
646 // are always live, so we need to zero them before any allocations,
647 // even allocations to move params/results to the heap.
648 func (s *state) zeroResults() {
649 for _, f := range s.curfn.Type().Results() {
650 n := f.Nname.(*ir.Name)
652 // The local which points to the return value is the
653 // thing that needs zeroing. This is already handled
654 // by a Needzero annotation in plive.go:(*liveness).epilogue.
657 // Zero the stack location containing f.
658 if typ := n.Type(); ssa.CanSSA(typ) {
659 s.assign(n, s.zeroVal(typ), false, 0)
661 if typ.HasPointers() {
662 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, n, s.mem())
664 s.zero(n.Type(), s.decladdrs[n])
669 // paramsToHeap produces code to allocate memory for heap-escaped parameters
670 // and to copy non-result parameters' values from the stack.
671 func (s *state) paramsToHeap() {
672 do := func(params []*types.Field) {
673 for _, f := range params {
675 continue // anonymous or blank parameter
677 n := f.Nname.(*ir.Name)
678 if ir.IsBlank(n) || n.OnStack() {
682 if n.Class == ir.PPARAM {
683 s.move(n.Type(), s.expr(n.Heapaddr), s.decladdrs[n])
688 typ := s.curfn.Type()
694 // newHeapaddr allocates heap memory for n and sets its heap address.
695 func (s *state) newHeapaddr(n *ir.Name) {
696 s.setHeapaddr(n.Pos(), n, s.newObject(n.Type(), nil))
699 // setHeapaddr allocates a new PAUTO variable to store ptr (which must be non-nil)
700 // and then sets it as n's heap address.
701 func (s *state) setHeapaddr(pos src.XPos, n *ir.Name, ptr *ssa.Value) {
702 if !ptr.Type.IsPtr() || !types.Identical(n.Type(), ptr.Type.Elem()) {
703 base.FatalfAt(n.Pos(), "setHeapaddr %L with type %v", n, ptr.Type)
706 // Declare variable to hold address.
707 sym := &types.Sym{Name: "&" + n.Sym().Name, Pkg: types.LocalPkg}
708 addr := s.curfn.NewLocal(pos, sym, types.NewPtr(n.Type()))
710 types.CalcSize(addr.Type())
712 if n.Class == ir.PPARAMOUT {
713 addr.SetIsOutputParamHeapAddr(true)
717 s.assign(addr, ptr, false, 0)
720 // newObject returns an SSA value denoting new(typ).
721 func (s *state) newObject(typ *types.Type, rtype *ssa.Value) *ssa.Value {
723 return s.newValue1A(ssa.OpAddr, types.NewPtr(typ), ir.Syms.Zerobase, s.sb)
726 rtype = s.reflectType(typ)
728 return s.rtcall(ir.Syms.Newobject, true, []*types.Type{types.NewPtr(typ)}, rtype)[0]
731 func (s *state) checkPtrAlignment(n *ir.ConvExpr, v *ssa.Value, count *ssa.Value) {
732 if !n.Type().IsPtr() {
733 s.Fatalf("expected pointer type: %v", n.Type())
735 elem, rtypeExpr := n.Type().Elem(), n.ElemRType
738 s.Fatalf("expected array type: %v", elem)
740 elem, rtypeExpr = elem.Elem(), n.ElemElemRType
743 // Casting from larger type to smaller one is ok, so for smallest type, do nothing.
744 if elem.Alignment() == 1 && (size == 0 || size == 1 || count == nil) {
748 count = s.constInt(types.Types[types.TUINTPTR], 1)
750 if count.Type.Size() != s.config.PtrSize {
751 s.Fatalf("expected count fit to a uintptr size, have: %d, want: %d", count.Type.Size(), s.config.PtrSize)
754 if rtypeExpr != nil {
755 rtype = s.expr(rtypeExpr)
757 rtype = s.reflectType(elem)
759 s.rtcall(ir.Syms.CheckPtrAlignment, true, nil, v, rtype, count)
762 // reflectType returns an SSA value representing a pointer to typ's
763 // reflection type descriptor.
764 func (s *state) reflectType(typ *types.Type) *ssa.Value {
765 // TODO(mdempsky): Make this Fatalf under Unified IR; frontend needs
766 // to supply RType expressions.
767 lsym := reflectdata.TypeLinksym(typ)
768 return s.entryNewValue1A(ssa.OpAddr, types.NewPtr(types.Types[types.TUINT8]), lsym, s.sb)
771 func dumpSourcesColumn(writer *ssa.HTMLWriter, fn *ir.Func) {
772 // Read sources of target function fn.
773 fname := base.Ctxt.PosTable.Pos(fn.Pos()).Filename()
774 targetFn, err := readFuncLines(fname, fn.Pos().Line(), fn.Endlineno.Line())
776 writer.Logf("cannot read sources for function %v: %v", fn, err)
779 // Read sources of inlined functions.
780 var inlFns []*ssa.FuncLines
781 for _, fi := range ssaDumpInlined {
783 fname := base.Ctxt.PosTable.Pos(fi.Pos()).Filename()
784 fnLines, err := readFuncLines(fname, fi.Pos().Line(), elno.Line())
786 writer.Logf("cannot read sources for inlined function %v: %v", fi, err)
789 inlFns = append(inlFns, fnLines)
792 sort.Sort(ssa.ByTopo(inlFns))
794 inlFns = append([]*ssa.FuncLines{targetFn}, inlFns...)
797 writer.WriteSources("sources", inlFns)
800 func readFuncLines(file string, start, end uint) (*ssa.FuncLines, error) {
801 f, err := os.Open(os.ExpandEnv(file))
808 scanner := bufio.NewScanner(f)
809 for scanner.Scan() && ln <= end {
811 lines = append(lines, scanner.Text())
815 return &ssa.FuncLines{Filename: file, StartLineno: start, Lines: lines}, nil
818 // updateUnsetPredPos propagates the earliest-value position information for b
819 // towards all of b's predecessors that need a position, and recurs on that
820 // predecessor if its position is updated. B should have a non-empty position.
821 func (s *state) updateUnsetPredPos(b *ssa.Block) {
822 if b.Pos == src.NoXPos {
823 s.Fatalf("Block %s should have a position", b)
825 bestPos := src.NoXPos
826 for _, e := range b.Preds {
831 if bestPos == src.NoXPos {
833 for _, v := range b.Values {
837 if v.Pos != src.NoXPos {
838 // Assume values are still in roughly textual order;
839 // TODO: could also seek minimum position?
846 s.updateUnsetPredPos(p) // We do not expect long chains of these, thus recursion is okay.
850 // Information about each open-coded defer.
851 type openDeferInfo struct {
852 // The node representing the call of the defer
854 // If defer call is closure call, the address of the argtmp where the
855 // closure is stored.
857 // The node representing the argtmp where the closure is stored - used for
858 // function, method, or interface call, to store a closure that panic
859 // processing can use for this defer.
864 // configuration (arch) information
867 // function we're building
874 labels map[string]*ssaLabel
876 // unlabeled break and continue statement tracking
877 breakTo *ssa.Block // current target for plain break statement
878 continueTo *ssa.Block // current target for plain continue statement
880 // current location where we're interpreting the AST
883 // variable assignments in the current block (map from variable symbol to ssa value)
884 // *Node is the unique identifier (an ONAME Node) for the variable.
885 // TODO: keep a single varnum map, then make all of these maps slices instead?
886 vars map[ir.Node]*ssa.Value
888 // fwdVars are variables that are used before they are defined in the current block.
889 // This map exists just to coalesce multiple references into a single FwdRef op.
890 // *Node is the unique identifier (an ONAME Node) for the variable.
891 fwdVars map[ir.Node]*ssa.Value
893 // all defined variables at the end of each block. Indexed by block ID.
894 defvars []map[ir.Node]*ssa.Value
896 // addresses of PPARAM and PPARAMOUT variables on the stack.
897 decladdrs map[*ir.Name]*ssa.Value
899 // starting values. Memory, stack pointer, and globals pointer
903 // value representing address of where deferBits autotmp is stored
904 deferBitsAddr *ssa.Value
905 deferBitsTemp *ir.Name
907 // line number stack. The current line number is top of stack
909 // the last line number processed; it may have been popped
912 // list of panic calls by function name and line number.
913 // Used to deduplicate panic calls.
914 panics map[funcLine]*ssa.Block
917 hasdefer bool // whether the function contains a defer statement
919 hasOpenDefers bool // whether we are doing open-coded defers
920 checkPtrEnabled bool // whether to insert checkptr instrumentation
921 instrumentEnterExit bool // whether to instrument function enter/exit
922 instrumentMemory bool // whether to instrument memory operations
924 // If doing open-coded defers, list of info about the defer calls in
925 // scanning order. Hence, at exit we should run these defers in reverse
926 // order of this list
927 openDefers []*openDeferInfo
928 // For open-coded defers, this is the beginning and end blocks of the last
929 // defer exit code that we have generated so far. We use these to share
930 // code between exits if the shareDeferExits option (disabled by default)
932 lastDeferExit *ssa.Block // Entry block of last defer exit code we generated
933 lastDeferFinalBlock *ssa.Block // Final block of last defer exit code we generated
934 lastDeferCount int // Number of defers encountered at that point
936 prevCall *ssa.Value // the previous call; use this to tie results to the call op.
939 type funcLine struct {
945 type ssaLabel struct {
946 target *ssa.Block // block identified by this label
947 breakTarget *ssa.Block // block to break to in control flow node identified by this label
948 continueTarget *ssa.Block // block to continue to in control flow node identified by this label
951 // label returns the label associated with sym, creating it if necessary.
952 func (s *state) label(sym *types.Sym) *ssaLabel {
953 lab := s.labels[sym.Name]
956 s.labels[sym.Name] = lab
961 func (s *state) Logf(msg string, args ...interface{}) { s.f.Logf(msg, args...) }
962 func (s *state) Log() bool { return s.f.Log() }
963 func (s *state) Fatalf(msg string, args ...interface{}) {
964 s.f.Frontend().Fatalf(s.peekPos(), msg, args...)
966 func (s *state) Warnl(pos src.XPos, msg string, args ...interface{}) { s.f.Warnl(pos, msg, args...) }
967 func (s *state) Debug_checknil() bool { return s.f.Frontend().Debug_checknil() }
969 func ssaMarker(name string) *ir.Name {
970 return ir.NewNameAt(base.Pos, &types.Sym{Name: name}, nil)
974 // marker node for the memory variable
975 memVar = ssaMarker("mem")
977 // marker nodes for temporary variables
978 ptrVar = ssaMarker("ptr")
979 lenVar = ssaMarker("len")
980 capVar = ssaMarker("cap")
981 typVar = ssaMarker("typ")
982 okVar = ssaMarker("ok")
983 deferBitsVar = ssaMarker("deferBits")
984 hashVar = ssaMarker("hash")
987 // startBlock sets the current block we're generating code in to b.
988 func (s *state) startBlock(b *ssa.Block) {
989 if s.curBlock != nil {
990 s.Fatalf("starting block %v when block %v has not ended", b, s.curBlock)
993 s.vars = map[ir.Node]*ssa.Value{}
994 for n := range s.fwdVars {
999 // endBlock marks the end of generating code for the current block.
1000 // Returns the (former) current block. Returns nil if there is no current
1001 // block, i.e. if no code flows to the current execution point.
1002 func (s *state) endBlock() *ssa.Block {
1007 for len(s.defvars) <= int(b.ID) {
1008 s.defvars = append(s.defvars, nil)
1010 s.defvars[b.ID] = s.vars
1014 // Empty plain blocks get the line of their successor (handled after all blocks created),
1015 // except for increment blocks in For statements (handled in ssa conversion of OFOR),
1016 // and for blocks ending in GOTO/BREAK/CONTINUE.
1024 // pushLine pushes a line number on the line number stack.
1025 func (s *state) pushLine(line src.XPos) {
1026 if !line.IsKnown() {
1027 // the frontend may emit node with line number missing,
1028 // use the parent line number in this case.
1030 if base.Flag.K != 0 {
1031 base.Warn("buildssa: unknown position (line 0)")
1037 s.line = append(s.line, line)
1040 // popLine pops the top of the line number stack.
1041 func (s *state) popLine() {
1042 s.line = s.line[:len(s.line)-1]
1045 // peekPos peeks the top of the line number stack.
1046 func (s *state) peekPos() src.XPos {
1047 return s.line[len(s.line)-1]
1050 // newValue0 adds a new value with no arguments to the current block.
1051 func (s *state) newValue0(op ssa.Op, t *types.Type) *ssa.Value {
1052 return s.curBlock.NewValue0(s.peekPos(), op, t)
1055 // newValue0A adds a new value with no arguments and an aux value to the current block.
1056 func (s *state) newValue0A(op ssa.Op, t *types.Type, aux ssa.Aux) *ssa.Value {
1057 return s.curBlock.NewValue0A(s.peekPos(), op, t, aux)
1060 // newValue0I adds a new value with no arguments and an auxint value to the current block.
1061 func (s *state) newValue0I(op ssa.Op, t *types.Type, auxint int64) *ssa.Value {
1062 return s.curBlock.NewValue0I(s.peekPos(), op, t, auxint)
1065 // newValue1 adds a new value with one argument to the current block.
1066 func (s *state) newValue1(op ssa.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
1067 return s.curBlock.NewValue1(s.peekPos(), op, t, arg)
1070 // newValue1A adds a new value with one argument and an aux value to the current block.
1071 func (s *state) newValue1A(op ssa.Op, t *types.Type, aux ssa.Aux, arg *ssa.Value) *ssa.Value {
1072 return s.curBlock.NewValue1A(s.peekPos(), op, t, aux, arg)
1075 // newValue1Apos adds a new value with one argument and an aux value to the current block.
1076 // isStmt determines whether the created values may be a statement or not
1077 // (i.e., false means never, yes means maybe).
1078 func (s *state) newValue1Apos(op ssa.Op, t *types.Type, aux ssa.Aux, arg *ssa.Value, isStmt bool) *ssa.Value {
1080 return s.curBlock.NewValue1A(s.peekPos(), op, t, aux, arg)
1082 return s.curBlock.NewValue1A(s.peekPos().WithNotStmt(), op, t, aux, arg)
1085 // newValue1I adds a new value with one argument and an auxint value to the current block.
1086 func (s *state) newValue1I(op ssa.Op, t *types.Type, aux int64, arg *ssa.Value) *ssa.Value {
1087 return s.curBlock.NewValue1I(s.peekPos(), op, t, aux, arg)
1090 // newValue2 adds a new value with two arguments to the current block.
1091 func (s *state) newValue2(op ssa.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
1092 return s.curBlock.NewValue2(s.peekPos(), op, t, arg0, arg1)
1095 // newValue2A adds a new value with two arguments and an aux value to the current block.
1096 func (s *state) newValue2A(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1 *ssa.Value) *ssa.Value {
1097 return s.curBlock.NewValue2A(s.peekPos(), op, t, aux, arg0, arg1)
1100 // newValue2Apos adds a new value with two arguments and an aux value to the current block.
1101 // isStmt determines whether the created values may be a statement or not
1102 // (i.e., false means never, yes means maybe).
1103 func (s *state) newValue2Apos(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1 *ssa.Value, isStmt bool) *ssa.Value {
1105 return s.curBlock.NewValue2A(s.peekPos(), op, t, aux, arg0, arg1)
1107 return s.curBlock.NewValue2A(s.peekPos().WithNotStmt(), op, t, aux, arg0, arg1)
1110 // newValue2I adds a new value with two arguments and an auxint value to the current block.
1111 func (s *state) newValue2I(op ssa.Op, t *types.Type, aux int64, arg0, arg1 *ssa.Value) *ssa.Value {
1112 return s.curBlock.NewValue2I(s.peekPos(), op, t, aux, arg0, arg1)
1115 // newValue3 adds a new value with three arguments to the current block.
1116 func (s *state) newValue3(op ssa.Op, t *types.Type, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
1117 return s.curBlock.NewValue3(s.peekPos(), op, t, arg0, arg1, arg2)
1120 // newValue3I adds a new value with three arguments and an auxint value to the current block.
1121 func (s *state) newValue3I(op ssa.Op, t *types.Type, aux int64, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
1122 return s.curBlock.NewValue3I(s.peekPos(), op, t, aux, arg0, arg1, arg2)
1125 // newValue3A adds a new value with three arguments and an aux value to the current block.
1126 func (s *state) newValue3A(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
1127 return s.curBlock.NewValue3A(s.peekPos(), op, t, aux, arg0, arg1, arg2)
1130 // newValue3Apos adds a new value with three arguments and an aux value to the current block.
1131 // isStmt determines whether the created values may be a statement or not
1132 // (i.e., false means never, yes means maybe).
1133 func (s *state) newValue3Apos(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1, arg2 *ssa.Value, isStmt bool) *ssa.Value {
1135 return s.curBlock.NewValue3A(s.peekPos(), op, t, aux, arg0, arg1, arg2)
1137 return s.curBlock.NewValue3A(s.peekPos().WithNotStmt(), op, t, aux, arg0, arg1, arg2)
1140 // newValue4 adds a new value with four arguments to the current block.
1141 func (s *state) newValue4(op ssa.Op, t *types.Type, arg0, arg1, arg2, arg3 *ssa.Value) *ssa.Value {
1142 return s.curBlock.NewValue4(s.peekPos(), op, t, arg0, arg1, arg2, arg3)
1145 // newValue4I adds a new value with four arguments and an auxint value to the current block.
1146 func (s *state) newValue4I(op ssa.Op, t *types.Type, aux int64, arg0, arg1, arg2, arg3 *ssa.Value) *ssa.Value {
1147 return s.curBlock.NewValue4I(s.peekPos(), op, t, aux, arg0, arg1, arg2, arg3)
1150 func (s *state) entryBlock() *ssa.Block {
1152 if base.Flag.N > 0 && s.curBlock != nil {
1153 // If optimizations are off, allocate in current block instead. Since with -N
1154 // we're not doing the CSE or tighten passes, putting lots of stuff in the
1155 // entry block leads to O(n^2) entries in the live value map during regalloc.
1162 // entryNewValue0 adds a new value with no arguments to the entry block.
1163 func (s *state) entryNewValue0(op ssa.Op, t *types.Type) *ssa.Value {
1164 return s.entryBlock().NewValue0(src.NoXPos, op, t)
1167 // entryNewValue0A adds a new value with no arguments and an aux value to the entry block.
1168 func (s *state) entryNewValue0A(op ssa.Op, t *types.Type, aux ssa.Aux) *ssa.Value {
1169 return s.entryBlock().NewValue0A(src.NoXPos, op, t, aux)
1172 // entryNewValue1 adds a new value with one argument to the entry block.
1173 func (s *state) entryNewValue1(op ssa.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
1174 return s.entryBlock().NewValue1(src.NoXPos, op, t, arg)
1177 // entryNewValue1I adds a new value with one argument and an auxint value to the entry block.
1178 func (s *state) entryNewValue1I(op ssa.Op, t *types.Type, auxint int64, arg *ssa.Value) *ssa.Value {
1179 return s.entryBlock().NewValue1I(src.NoXPos, op, t, auxint, arg)
1182 // entryNewValue1A adds a new value with one argument and an aux value to the entry block.
1183 func (s *state) entryNewValue1A(op ssa.Op, t *types.Type, aux ssa.Aux, arg *ssa.Value) *ssa.Value {
1184 return s.entryBlock().NewValue1A(src.NoXPos, op, t, aux, arg)
1187 // entryNewValue2 adds a new value with two arguments to the entry block.
1188 func (s *state) entryNewValue2(op ssa.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
1189 return s.entryBlock().NewValue2(src.NoXPos, op, t, arg0, arg1)
1192 // entryNewValue2A adds a new value with two arguments and an aux value to the entry block.
1193 func (s *state) entryNewValue2A(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1 *ssa.Value) *ssa.Value {
1194 return s.entryBlock().NewValue2A(src.NoXPos, op, t, aux, arg0, arg1)
1197 // const* routines add a new const value to the entry block.
1198 func (s *state) constSlice(t *types.Type) *ssa.Value {
1199 return s.f.ConstSlice(t)
1201 func (s *state) constInterface(t *types.Type) *ssa.Value {
1202 return s.f.ConstInterface(t)
1204 func (s *state) constNil(t *types.Type) *ssa.Value { return s.f.ConstNil(t) }
1205 func (s *state) constEmptyString(t *types.Type) *ssa.Value {
1206 return s.f.ConstEmptyString(t)
1208 func (s *state) constBool(c bool) *ssa.Value {
1209 return s.f.ConstBool(types.Types[types.TBOOL], c)
1211 func (s *state) constInt8(t *types.Type, c int8) *ssa.Value {
1212 return s.f.ConstInt8(t, c)
1214 func (s *state) constInt16(t *types.Type, c int16) *ssa.Value {
1215 return s.f.ConstInt16(t, c)
1217 func (s *state) constInt32(t *types.Type, c int32) *ssa.Value {
1218 return s.f.ConstInt32(t, c)
1220 func (s *state) constInt64(t *types.Type, c int64) *ssa.Value {
1221 return s.f.ConstInt64(t, c)
1223 func (s *state) constFloat32(t *types.Type, c float64) *ssa.Value {
1224 return s.f.ConstFloat32(t, c)
1226 func (s *state) constFloat64(t *types.Type, c float64) *ssa.Value {
1227 return s.f.ConstFloat64(t, c)
1229 func (s *state) constInt(t *types.Type, c int64) *ssa.Value {
1230 if s.config.PtrSize == 8 {
1231 return s.constInt64(t, c)
1233 if int64(int32(c)) != c {
1234 s.Fatalf("integer constant too big %d", c)
1236 return s.constInt32(t, int32(c))
1238 func (s *state) constOffPtrSP(t *types.Type, c int64) *ssa.Value {
1239 return s.f.ConstOffPtrSP(t, c, s.sp)
1242 // newValueOrSfCall* are wrappers around newValue*, which may create a call to a
1243 // soft-float runtime function instead (when emitting soft-float code).
1244 func (s *state) newValueOrSfCall1(op ssa.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
1246 if c, ok := s.sfcall(op, arg); ok {
1250 return s.newValue1(op, t, arg)
1252 func (s *state) newValueOrSfCall2(op ssa.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
1254 if c, ok := s.sfcall(op, arg0, arg1); ok {
1258 return s.newValue2(op, t, arg0, arg1)
1261 type instrumentKind uint8
1264 instrumentRead = iota
1269 func (s *state) instrument(t *types.Type, addr *ssa.Value, kind instrumentKind) {
1270 s.instrument2(t, addr, nil, kind)
1273 // instrumentFields instruments a read/write operation on addr.
1274 // If it is instrumenting for MSAN or ASAN and t is a struct type, it instruments
1275 // operation for each field, instead of for the whole struct.
1276 func (s *state) instrumentFields(t *types.Type, addr *ssa.Value, kind instrumentKind) {
1277 if !(base.Flag.MSan || base.Flag.ASan) || !t.IsStruct() {
1278 s.instrument(t, addr, kind)
1281 for _, f := range t.Fields() {
1282 if f.Sym.IsBlank() {
1285 offptr := s.newValue1I(ssa.OpOffPtr, types.NewPtr(f.Type), f.Offset, addr)
1286 s.instrumentFields(f.Type, offptr, kind)
1290 func (s *state) instrumentMove(t *types.Type, dst, src *ssa.Value) {
1292 s.instrument2(t, dst, src, instrumentMove)
1294 s.instrument(t, src, instrumentRead)
1295 s.instrument(t, dst, instrumentWrite)
1299 func (s *state) instrument2(t *types.Type, addr, addr2 *ssa.Value, kind instrumentKind) {
1300 if !s.instrumentMemory {
1306 return // can't race on zero-sized things
1309 if ssa.IsSanitizerSafeAddr(addr) {
1316 if addr2 != nil && kind != instrumentMove {
1317 panic("instrument2: non-nil addr2 for non-move instrumentation")
1322 case instrumentRead:
1323 fn = ir.Syms.Msanread
1324 case instrumentWrite:
1325 fn = ir.Syms.Msanwrite
1326 case instrumentMove:
1327 fn = ir.Syms.Msanmove
1329 panic("unreachable")
1332 } else if base.Flag.Race && t.NumComponents(types.CountBlankFields) > 1 {
1333 // for composite objects we have to write every address
1334 // because a write might happen to any subobject.
1335 // composites with only one element don't have subobjects, though.
1337 case instrumentRead:
1338 fn = ir.Syms.Racereadrange
1339 case instrumentWrite:
1340 fn = ir.Syms.Racewriterange
1342 panic("unreachable")
1345 } else if base.Flag.Race {
1346 // for non-composite objects we can write just the start
1347 // address, as any write must write the first byte.
1349 case instrumentRead:
1350 fn = ir.Syms.Raceread
1351 case instrumentWrite:
1352 fn = ir.Syms.Racewrite
1354 panic("unreachable")
1356 } else if base.Flag.ASan {
1358 case instrumentRead:
1359 fn = ir.Syms.Asanread
1360 case instrumentWrite:
1361 fn = ir.Syms.Asanwrite
1363 panic("unreachable")
1367 panic("unreachable")
1370 args := []*ssa.Value{addr}
1372 args = append(args, addr2)
1375 args = append(args, s.constInt(types.Types[types.TUINTPTR], w))
1377 s.rtcall(fn, true, nil, args...)
1380 func (s *state) load(t *types.Type, src *ssa.Value) *ssa.Value {
1381 s.instrumentFields(t, src, instrumentRead)
1382 return s.rawLoad(t, src)
1385 func (s *state) rawLoad(t *types.Type, src *ssa.Value) *ssa.Value {
1386 return s.newValue2(ssa.OpLoad, t, src, s.mem())
1389 func (s *state) store(t *types.Type, dst, val *ssa.Value) {
1390 s.vars[memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, t, dst, val, s.mem())
1393 func (s *state) zero(t *types.Type, dst *ssa.Value) {
1394 s.instrument(t, dst, instrumentWrite)
1395 store := s.newValue2I(ssa.OpZero, types.TypeMem, t.Size(), dst, s.mem())
1397 s.vars[memVar] = store
1400 func (s *state) move(t *types.Type, dst, src *ssa.Value) {
1401 s.moveWhichMayOverlap(t, dst, src, false)
1403 func (s *state) moveWhichMayOverlap(t *types.Type, dst, src *ssa.Value, mayOverlap bool) {
1404 s.instrumentMove(t, dst, src)
1405 if mayOverlap && t.IsArray() && t.NumElem() > 1 && !ssa.IsInlinableMemmove(dst, src, t.Size(), s.f.Config) {
1406 // Normally, when moving Go values of type T from one location to another,
1407 // we don't need to worry about partial overlaps. The two Ts must either be
1408 // in disjoint (nonoverlapping) memory or in exactly the same location.
1409 // There are 2 cases where this isn't true:
1410 // 1) Using unsafe you can arrange partial overlaps.
1411 // 2) Since Go 1.17, you can use a cast from a slice to a ptr-to-array.
1412 // https://go.dev/ref/spec#Conversions_from_slice_to_array_pointer
1413 // This feature can be used to construct partial overlaps of array types.
1415 // p := (*[2]int)(a[:])
1416 // q := (*[2]int)(a[1:])
1418 // We don't care about solving 1. Or at least, we haven't historically
1419 // and no one has complained.
1420 // For 2, we need to ensure that if there might be partial overlap,
1421 // then we can't use OpMove; we must use memmove instead.
1422 // (memmove handles partial overlap by copying in the correct
1423 // direction. OpMove does not.)
1425 // Note that we have to be careful here not to introduce a call when
1426 // we're marshaling arguments to a call or unmarshaling results from a call.
1427 // Cases where this is happening must pass mayOverlap to false.
1428 // (Currently this only happens when unmarshaling results of a call.)
1429 if t.HasPointers() {
1430 s.rtcall(ir.Syms.Typedmemmove, true, nil, s.reflectType(t), dst, src)
1431 // We would have otherwise implemented this move with straightline code,
1432 // including a write barrier. Pretend we issue a write barrier here,
1433 // so that the write barrier tests work. (Otherwise they'd need to know
1434 // the details of IsInlineableMemmove.)
1435 s.curfn.SetWBPos(s.peekPos())
1437 s.rtcall(ir.Syms.Memmove, true, nil, dst, src, s.constInt(types.Types[types.TUINTPTR], t.Size()))
1439 ssa.LogLargeCopy(s.f.Name, s.peekPos(), t.Size())
1442 store := s.newValue3I(ssa.OpMove, types.TypeMem, t.Size(), dst, src, s.mem())
1444 s.vars[memVar] = store
1447 // stmtList converts the statement list n to SSA and adds it to s.
1448 func (s *state) stmtList(l ir.Nodes) {
1449 for _, n := range l {
1454 // stmt converts the statement n to SSA and adds it to s.
1455 func (s *state) stmt(n ir.Node) {
1459 // If s.curBlock is nil, and n isn't a label (which might have an associated goto somewhere),
1460 // then this code is dead. Stop here.
1461 if s.curBlock == nil && n.Op() != ir.OLABEL {
1465 s.stmtList(n.Init())
1469 n := n.(*ir.BlockStmt)
1472 case ir.OFALL: // no-op
1474 // Expression statements
1476 n := n.(*ir.CallExpr)
1477 if ir.IsIntrinsicCall(n) {
1484 n := n.(*ir.CallExpr)
1485 s.callResult(n, callNormal)
1486 if n.Op() == ir.OCALLFUNC && n.Fun.Op() == ir.ONAME && n.Fun.(*ir.Name).Class == ir.PFUNC {
1487 if fn := n.Fun.Sym().Name; base.Flag.CompilingRuntime && fn == "throw" ||
1488 n.Fun.Sym().Pkg == ir.Pkgs.Runtime && (fn == "throwinit" || fn == "gopanic" || fn == "panicwrap" || fn == "block" || fn == "panicmakeslicelen" || fn == "panicmakeslicecap" || fn == "panicunsafeslicelen" || fn == "panicunsafeslicenilptr" || fn == "panicunsafestringlen" || fn == "panicunsafestringnilptr") {
1491 b.Kind = ssa.BlockExit
1493 // TODO: never rewrite OPANIC to OCALLFUNC in the
1494 // first place. Need to wait until all backends
1499 n := n.(*ir.GoDeferStmt)
1500 if base.Debug.Defer > 0 {
1501 var defertype string
1502 if s.hasOpenDefers {
1503 defertype = "open-coded"
1504 } else if n.Esc() == ir.EscNever {
1505 defertype = "stack-allocated"
1507 defertype = "heap-allocated"
1509 base.WarnfAt(n.Pos(), "%s defer", defertype)
1511 if s.hasOpenDefers {
1512 s.openDeferRecord(n.Call.(*ir.CallExpr))
1515 if n.Esc() == ir.EscNever && n.DeferAt == nil {
1518 s.call(n.Call.(*ir.CallExpr), d, false, n.DeferAt)
1521 n := n.(*ir.GoDeferStmt)
1522 s.callResult(n.Call.(*ir.CallExpr), callGo)
1524 case ir.OAS2DOTTYPE:
1525 n := n.(*ir.AssignListStmt)
1526 var res, resok *ssa.Value
1527 if n.Rhs[0].Op() == ir.ODOTTYPE2 {
1528 res, resok = s.dottype(n.Rhs[0].(*ir.TypeAssertExpr), true)
1530 res, resok = s.dynamicDottype(n.Rhs[0].(*ir.DynamicTypeAssertExpr), true)
1533 if !ssa.CanSSA(n.Rhs[0].Type()) {
1534 if res.Op != ssa.OpLoad {
1535 s.Fatalf("dottype of non-load")
1538 if res.Args[1] != mem {
1539 s.Fatalf("memory no longer live from 2-result dottype load")
1544 s.assign(n.Lhs[0], res, deref, 0)
1545 s.assign(n.Lhs[1], resok, false, 0)
1549 // We come here only when it is an intrinsic call returning two values.
1550 n := n.(*ir.AssignListStmt)
1551 call := n.Rhs[0].(*ir.CallExpr)
1552 if !ir.IsIntrinsicCall(call) {
1553 s.Fatalf("non-intrinsic AS2FUNC not expanded %v", call)
1555 v := s.intrinsicCall(call)
1556 v1 := s.newValue1(ssa.OpSelect0, n.Lhs[0].Type(), v)
1557 v2 := s.newValue1(ssa.OpSelect1, n.Lhs[1].Type(), v)
1558 s.assign(n.Lhs[0], v1, false, 0)
1559 s.assign(n.Lhs[1], v2, false, 0)
1564 if v := n.X; v.Esc() == ir.EscHeap {
1569 n := n.(*ir.LabelStmt)
1572 // Nothing to do because the label isn't targetable. See issue 52278.
1577 // The label might already have a target block via a goto.
1578 if lab.target == nil {
1579 lab.target = s.f.NewBlock(ssa.BlockPlain)
1582 // Go to that label.
1583 // (We pretend "label:" is preceded by "goto label", unless the predecessor is unreachable.)
1584 if s.curBlock != nil {
1586 b.AddEdgeTo(lab.target)
1588 s.startBlock(lab.target)
1591 n := n.(*ir.BranchStmt)
1595 if lab.target == nil {
1596 lab.target = s.f.NewBlock(ssa.BlockPlain)
1600 b.Pos = s.lastPos.WithIsStmt() // Do this even if b is an empty block.
1601 b.AddEdgeTo(lab.target)
1604 n := n.(*ir.AssignStmt)
1605 if n.X == n.Y && n.X.Op() == ir.ONAME {
1606 // An x=x assignment. No point in doing anything
1607 // here. In addition, skipping this assignment
1608 // prevents generating:
1611 // which is bad because x is incorrectly considered
1612 // dead before the vardef. See issue #14904.
1616 // mayOverlap keeps track of whether the LHS and RHS might
1617 // refer to partially overlapping memory. Partial overlapping can
1618 // only happen for arrays, see the comment in moveWhichMayOverlap.
1620 // If both sides of the assignment are not dereferences, then partial
1621 // overlap can't happen. Partial overlap can only occur only when the
1622 // arrays referenced are strictly smaller parts of the same base array.
1623 // If one side of the assignment is a full array, then partial overlap
1624 // can't happen. (The arrays are either disjoint or identical.)
1625 mayOverlap := n.X.Op() == ir.ODEREF && (n.Y != nil && n.Y.Op() == ir.ODEREF)
1626 if n.Y != nil && n.Y.Op() == ir.ODEREF {
1627 p := n.Y.(*ir.StarExpr).X
1628 for p.Op() == ir.OCONVNOP {
1629 p = p.(*ir.ConvExpr).X
1631 if p.Op() == ir.OSPTR && p.(*ir.UnaryExpr).X.Type().IsString() {
1632 // Pointer fields of strings point to unmodifiable memory.
1633 // That memory can't overlap with the memory being written.
1642 case ir.OSTRUCTLIT, ir.OARRAYLIT, ir.OSLICELIT:
1643 // All literals with nonzero fields have already been
1644 // rewritten during walk. Any that remain are just T{}
1645 // or equivalents. Use the zero value.
1646 if !ir.IsZero(rhs) {
1647 s.Fatalf("literal with nonzero value in SSA: %v", rhs)
1651 rhs := rhs.(*ir.CallExpr)
1652 // Check whether we're writing the result of an append back to the same slice.
1653 // If so, we handle it specially to avoid write barriers on the fast
1654 // (non-growth) path.
1655 if !ir.SameSafeExpr(n.X, rhs.Args[0]) || base.Flag.N != 0 {
1658 // If the slice can be SSA'd, it'll be on the stack,
1659 // so there will be no write barriers,
1660 // so there's no need to attempt to prevent them.
1662 if base.Debug.Append > 0 { // replicating old diagnostic message
1663 base.WarnfAt(n.Pos(), "append: len-only update (in local slice)")
1667 if base.Debug.Append > 0 {
1668 base.WarnfAt(n.Pos(), "append: len-only update")
1675 if ir.IsBlank(n.X) {
1677 // Just evaluate rhs for side-effects.
1692 deref := !ssa.CanSSA(t)
1695 r = nil // Signal assign to use OpZero.
1708 if rhs != nil && (rhs.Op() == ir.OSLICE || rhs.Op() == ir.OSLICE3 || rhs.Op() == ir.OSLICESTR) && ir.SameSafeExpr(rhs.(*ir.SliceExpr).X, n.X) {
1709 // We're assigning a slicing operation back to its source.
1710 // Don't write back fields we aren't changing. See issue #14855.
1711 rhs := rhs.(*ir.SliceExpr)
1712 i, j, k := rhs.Low, rhs.High, rhs.Max
1713 if i != nil && (i.Op() == ir.OLITERAL && i.Val().Kind() == constant.Int && ir.Int64Val(i) == 0) {
1714 // [0:...] is the same as [:...]
1717 // TODO: detect defaults for len/cap also.
1718 // Currently doesn't really work because (*p)[:len(*p)] appears here as:
1721 // if j != nil && (j.Op == OLEN && SameSafeExpr(j.Left, n.Left)) {
1724 // if k != nil && (k.Op == OCAP && SameSafeExpr(k.Left, n.Left)) {
1738 s.assignWhichMayOverlap(n.X, r, deref, skip, mayOverlap)
1742 if ir.IsConst(n.Cond, constant.Bool) {
1743 s.stmtList(n.Cond.Init())
1744 if ir.BoolVal(n.Cond) {
1752 bEnd := s.f.NewBlock(ssa.BlockPlain)
1757 var bThen *ssa.Block
1758 if len(n.Body) != 0 {
1759 bThen = s.f.NewBlock(ssa.BlockPlain)
1763 var bElse *ssa.Block
1764 if len(n.Else) != 0 {
1765 bElse = s.f.NewBlock(ssa.BlockPlain)
1769 s.condBranch(n.Cond, bThen, bElse, likely)
1771 if len(n.Body) != 0 {
1774 if b := s.endBlock(); b != nil {
1778 if len(n.Else) != 0 {
1781 if b := s.endBlock(); b != nil {
1788 n := n.(*ir.ReturnStmt)
1789 s.stmtList(n.Results)
1791 b.Pos = s.lastPos.WithIsStmt()
1794 n := n.(*ir.TailCallStmt)
1795 s.callResult(n.Call, callTail)
1798 b.Kind = ssa.BlockRetJmp // could use BlockExit. BlockRetJmp is mostly for clarity.
1801 case ir.OCONTINUE, ir.OBREAK:
1802 n := n.(*ir.BranchStmt)
1805 // plain break/continue
1813 // labeled break/continue; look up the target
1818 to = lab.continueTarget
1820 to = lab.breakTarget
1825 b.Pos = s.lastPos.WithIsStmt() // Do this even if b is an empty block.
1829 // OFOR: for Ninit; Left; Right { Nbody }
1830 // cond (Left); body (Nbody); incr (Right)
1831 n := n.(*ir.ForStmt)
1832 base.Assert(!n.DistinctVars) // Should all be rewritten before escape analysis
1833 bCond := s.f.NewBlock(ssa.BlockPlain)
1834 bBody := s.f.NewBlock(ssa.BlockPlain)
1835 bIncr := s.f.NewBlock(ssa.BlockPlain)
1836 bEnd := s.f.NewBlock(ssa.BlockPlain)
1838 // ensure empty for loops have correct position; issue #30167
1841 // first, jump to condition test
1845 // generate code to test condition
1848 s.condBranch(n.Cond, bBody, bEnd, 1)
1851 b.Kind = ssa.BlockPlain
1855 // set up for continue/break in body
1856 prevContinue := s.continueTo
1857 prevBreak := s.breakTo
1858 s.continueTo = bIncr
1861 if sym := n.Label; sym != nil {
1864 lab.continueTarget = bIncr
1865 lab.breakTarget = bEnd
1872 // tear down continue/break
1873 s.continueTo = prevContinue
1874 s.breakTo = prevBreak
1876 lab.continueTarget = nil
1877 lab.breakTarget = nil
1880 // done with body, goto incr
1881 if b := s.endBlock(); b != nil {
1890 if b := s.endBlock(); b != nil {
1892 // It can happen that bIncr ends in a block containing only VARKILL,
1893 // and that muddles the debugging experience.
1894 if b.Pos == src.NoXPos {
1901 case ir.OSWITCH, ir.OSELECT:
1902 // These have been mostly rewritten by the front end into their Nbody fields.
1903 // Our main task is to correctly hook up any break statements.
1904 bEnd := s.f.NewBlock(ssa.BlockPlain)
1906 prevBreak := s.breakTo
1910 if n.Op() == ir.OSWITCH {
1911 n := n.(*ir.SwitchStmt)
1915 n := n.(*ir.SelectStmt)
1924 lab.breakTarget = bEnd
1927 // generate body code
1930 s.breakTo = prevBreak
1932 lab.breakTarget = nil
1935 // walk adds explicit OBREAK nodes to the end of all reachable code paths.
1936 // If we still have a current block here, then mark it unreachable.
1937 if s.curBlock != nil {
1940 b.Kind = ssa.BlockExit
1946 n := n.(*ir.JumpTableStmt)
1948 // Make blocks we'll need.
1949 jt := s.f.NewBlock(ssa.BlockJumpTable)
1950 bEnd := s.f.NewBlock(ssa.BlockPlain)
1952 // The only thing that needs evaluating is the index we're looking up.
1953 idx := s.expr(n.Idx)
1954 unsigned := idx.Type.IsUnsigned()
1956 // Extend so we can do everything in uintptr arithmetic.
1957 t := types.Types[types.TUINTPTR]
1958 idx = s.conv(nil, idx, idx.Type, t)
1960 // The ending condition for the current block decides whether we'll use
1961 // the jump table at all.
1962 // We check that min <= idx <= max and jump around the jump table
1963 // if that test fails.
1964 // We implement min <= idx <= max with 0 <= idx-min <= max-min, because
1965 // we'll need idx-min anyway as the control value for the jump table.
1968 min, _ = constant.Uint64Val(n.Cases[0])
1969 max, _ = constant.Uint64Val(n.Cases[len(n.Cases)-1])
1971 mn, _ := constant.Int64Val(n.Cases[0])
1972 mx, _ := constant.Int64Val(n.Cases[len(n.Cases)-1])
1976 // Compare idx-min with max-min, to see if we can use the jump table.
1977 idx = s.newValue2(s.ssaOp(ir.OSUB, t), t, idx, s.uintptrConstant(min))
1978 width := s.uintptrConstant(max - min)
1979 cmp := s.newValue2(s.ssaOp(ir.OLE, t), types.Types[types.TBOOL], idx, width)
1981 b.Kind = ssa.BlockIf
1983 b.AddEdgeTo(jt) // in range - use jump table
1984 b.AddEdgeTo(bEnd) // out of range - no case in the jump table will trigger
1985 b.Likely = ssa.BranchLikely // TODO: assumes missing the table entirely is unlikely. True?
1987 // Build jump table block.
1990 if base.Flag.Cfg.SpectreIndex {
1991 idx = s.newValue2(ssa.OpSpectreSliceIndex, t, idx, width)
1995 // Figure out where we should go for each index in the table.
1996 table := make([]*ssa.Block, max-min+1)
1997 for i := range table {
1998 table[i] = bEnd // default target
2000 for i := range n.Targets {
2002 lab := s.label(n.Targets[i])
2003 if lab.target == nil {
2004 lab.target = s.f.NewBlock(ssa.BlockPlain)
2008 val, _ = constant.Uint64Val(c)
2010 vl, _ := constant.Int64Val(c)
2013 // Overwrite the default target.
2014 table[val-min] = lab.target
2016 for _, t := range table {
2023 case ir.OINTERFACESWITCH:
2024 n := n.(*ir.InterfaceSwitchStmt)
2025 typs := s.f.Config.Types
2027 t := s.expr(n.RuntimeType)
2028 d := s.newValue1A(ssa.OpAddr, typs.BytePtr, n.Descriptor, s.sb)
2030 // Check the cache first.
2031 var merge *ssa.Block
2032 if base.Flag.N == 0 && rtabi.UseInterfaceSwitchCache(Arch.LinkArch.Name) {
2033 // Note: we can only use the cache if we have the right atomic load instruction.
2034 // Double-check that here.
2035 if _, ok := intrinsics[intrinsicKey{Arch.LinkArch.Arch, "runtime/internal/atomic", "Loadp"}]; !ok {
2036 s.Fatalf("atomic load not available")
2038 merge = s.f.NewBlock(ssa.BlockPlain)
2039 cacheHit := s.f.NewBlock(ssa.BlockPlain)
2040 cacheMiss := s.f.NewBlock(ssa.BlockPlain)
2041 loopHead := s.f.NewBlock(ssa.BlockPlain)
2042 loopBody := s.f.NewBlock(ssa.BlockPlain)
2044 // Pick right size ops.
2045 var mul, and, add, zext ssa.Op
2046 if s.config.PtrSize == 4 {
2055 zext = ssa.OpZeroExt32to64
2058 // Load cache pointer out of descriptor, with an atomic load so
2059 // we ensure that we see a fully written cache.
2060 atomicLoad := s.newValue2(ssa.OpAtomicLoadPtr, types.NewTuple(typs.BytePtr, types.TypeMem), d, s.mem())
2061 cache := s.newValue1(ssa.OpSelect0, typs.BytePtr, atomicLoad)
2062 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, atomicLoad)
2064 // Load hash from type.
2065 hash := s.newValue2(ssa.OpLoad, typs.UInt32, s.newValue1I(ssa.OpOffPtr, typs.UInt32Ptr, 2*s.config.PtrSize, t), s.mem())
2066 hash = s.newValue1(zext, typs.Uintptr, hash)
2067 s.vars[hashVar] = hash
2068 // Load mask from cache.
2069 mask := s.newValue2(ssa.OpLoad, typs.Uintptr, cache, s.mem())
2070 // Jump to loop head.
2072 b.AddEdgeTo(loopHead)
2074 // At loop head, get pointer to the cache entry.
2075 // e := &cache.Entries[hash&mask]
2076 s.startBlock(loopHead)
2077 entries := s.newValue2(ssa.OpAddPtr, typs.UintptrPtr, cache, s.uintptrConstant(uint64(s.config.PtrSize)))
2078 idx := s.newValue2(and, typs.Uintptr, s.variable(hashVar, typs.Uintptr), mask)
2079 idx = s.newValue2(mul, typs.Uintptr, idx, s.uintptrConstant(uint64(3*s.config.PtrSize)))
2080 e := s.newValue2(ssa.OpAddPtr, typs.UintptrPtr, entries, idx)
2082 s.vars[hashVar] = s.newValue2(add, typs.Uintptr, s.variable(hashVar, typs.Uintptr), s.uintptrConstant(1))
2084 // Look for a cache hit.
2085 // if e.Typ == t { goto hit }
2086 eTyp := s.newValue2(ssa.OpLoad, typs.Uintptr, e, s.mem())
2087 cmp1 := s.newValue2(ssa.OpEqPtr, typs.Bool, t, eTyp)
2089 b.Kind = ssa.BlockIf
2091 b.AddEdgeTo(cacheHit)
2092 b.AddEdgeTo(loopBody)
2094 // Look for an empty entry, the tombstone for this hash table.
2095 // if e.Typ == nil { goto miss }
2096 s.startBlock(loopBody)
2097 cmp2 := s.newValue2(ssa.OpEqPtr, typs.Bool, eTyp, s.constNil(typs.BytePtr))
2099 b.Kind = ssa.BlockIf
2101 b.AddEdgeTo(cacheMiss)
2102 b.AddEdgeTo(loopHead)
2104 // On a hit, load the data fields of the cache entry.
2107 s.startBlock(cacheHit)
2108 eCase := s.newValue2(ssa.OpLoad, typs.Int, s.newValue1I(ssa.OpOffPtr, typs.IntPtr, s.config.PtrSize, e), s.mem())
2109 eItab := s.newValue2(ssa.OpLoad, typs.BytePtr, s.newValue1I(ssa.OpOffPtr, typs.BytePtrPtr, 2*s.config.PtrSize, e), s.mem())
2110 s.assign(n.Case, eCase, false, 0)
2111 s.assign(n.Itab, eItab, false, 0)
2115 // On a miss, call into the runtime to get the answer.
2116 s.startBlock(cacheMiss)
2119 r := s.rtcall(ir.Syms.InterfaceSwitch, true, []*types.Type{typs.Int, typs.BytePtr}, d, t)
2120 s.assign(n.Case, r[0], false, 0)
2121 s.assign(n.Itab, r[1], false, 0)
2124 // Cache hits merge in here.
2126 b.Kind = ssa.BlockPlain
2132 n := n.(*ir.UnaryExpr)
2137 n := n.(*ir.InlineMarkStmt)
2138 s.newValue1I(ssa.OpInlMark, types.TypeVoid, n.Index, s.mem())
2141 s.Fatalf("unhandled stmt %v", n.Op())
2145 // If true, share as many open-coded defer exits as possible (with the downside of
2146 // worse line-number information)
2147 const shareDeferExits = false
2149 // exit processes any code that needs to be generated just before returning.
2150 // It returns a BlockRet block that ends the control flow. Its control value
2151 // will be set to the final memory state.
2152 func (s *state) exit() *ssa.Block {
2154 if s.hasOpenDefers {
2155 if shareDeferExits && s.lastDeferExit != nil && len(s.openDefers) == s.lastDeferCount {
2156 if s.curBlock.Kind != ssa.BlockPlain {
2157 panic("Block for an exit should be BlockPlain")
2159 s.curBlock.AddEdgeTo(s.lastDeferExit)
2161 return s.lastDeferFinalBlock
2165 s.rtcall(ir.Syms.Deferreturn, true, nil)
2169 // Do actual return.
2170 // These currently turn into self-copies (in many cases).
2171 resultFields := s.curfn.Type().Results()
2172 results := make([]*ssa.Value, len(resultFields)+1, len(resultFields)+1)
2173 // Store SSAable and heap-escaped PPARAMOUT variables back to stack locations.
2174 for i, f := range resultFields {
2175 n := f.Nname.(*ir.Name)
2176 if s.canSSA(n) { // result is in some SSA variable
2177 if !n.IsOutputParamInRegisters() && n.Type().HasPointers() {
2178 // We are about to store to the result slot.
2179 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, n, s.mem())
2181 results[i] = s.variable(n, n.Type())
2182 } else if !n.OnStack() { // result is actually heap allocated
2183 // We are about to copy the in-heap result to the result slot.
2184 if n.Type().HasPointers() {
2185 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, n, s.mem())
2187 ha := s.expr(n.Heapaddr)
2188 s.instrumentFields(n.Type(), ha, instrumentRead)
2189 results[i] = s.newValue2(ssa.OpDereference, n.Type(), ha, s.mem())
2190 } else { // result is not SSA-able; not escaped, so not on heap, but too large for SSA.
2191 // Before register ABI this ought to be a self-move, home=dest,
2192 // With register ABI, it's still a self-move if parameter is on stack (i.e., too big or overflowed)
2193 // No VarDef, as the result slot is already holding live value.
2194 results[i] = s.newValue2(ssa.OpDereference, n.Type(), s.addr(n), s.mem())
2198 // In -race mode, we need to call racefuncexit.
2199 // Note: This has to happen after we load any heap-allocated results,
2200 // otherwise races will be attributed to the caller instead.
2201 if s.instrumentEnterExit {
2202 s.rtcall(ir.Syms.Racefuncexit, true, nil)
2205 results[len(results)-1] = s.mem()
2206 m := s.newValue0(ssa.OpMakeResult, s.f.OwnAux.LateExpansionResultType())
2207 m.AddArgs(results...)
2210 b.Kind = ssa.BlockRet
2212 if s.hasdefer && s.hasOpenDefers {
2213 s.lastDeferFinalBlock = b
2218 type opAndType struct {
2223 var opToSSA = map[opAndType]ssa.Op{
2224 {ir.OADD, types.TINT8}: ssa.OpAdd8,
2225 {ir.OADD, types.TUINT8}: ssa.OpAdd8,
2226 {ir.OADD, types.TINT16}: ssa.OpAdd16,
2227 {ir.OADD, types.TUINT16}: ssa.OpAdd16,
2228 {ir.OADD, types.TINT32}: ssa.OpAdd32,
2229 {ir.OADD, types.TUINT32}: ssa.OpAdd32,
2230 {ir.OADD, types.TINT64}: ssa.OpAdd64,
2231 {ir.OADD, types.TUINT64}: ssa.OpAdd64,
2232 {ir.OADD, types.TFLOAT32}: ssa.OpAdd32F,
2233 {ir.OADD, types.TFLOAT64}: ssa.OpAdd64F,
2235 {ir.OSUB, types.TINT8}: ssa.OpSub8,
2236 {ir.OSUB, types.TUINT8}: ssa.OpSub8,
2237 {ir.OSUB, types.TINT16}: ssa.OpSub16,
2238 {ir.OSUB, types.TUINT16}: ssa.OpSub16,
2239 {ir.OSUB, types.TINT32}: ssa.OpSub32,
2240 {ir.OSUB, types.TUINT32}: ssa.OpSub32,
2241 {ir.OSUB, types.TINT64}: ssa.OpSub64,
2242 {ir.OSUB, types.TUINT64}: ssa.OpSub64,
2243 {ir.OSUB, types.TFLOAT32}: ssa.OpSub32F,
2244 {ir.OSUB, types.TFLOAT64}: ssa.OpSub64F,
2246 {ir.ONOT, types.TBOOL}: ssa.OpNot,
2248 {ir.ONEG, types.TINT8}: ssa.OpNeg8,
2249 {ir.ONEG, types.TUINT8}: ssa.OpNeg8,
2250 {ir.ONEG, types.TINT16}: ssa.OpNeg16,
2251 {ir.ONEG, types.TUINT16}: ssa.OpNeg16,
2252 {ir.ONEG, types.TINT32}: ssa.OpNeg32,
2253 {ir.ONEG, types.TUINT32}: ssa.OpNeg32,
2254 {ir.ONEG, types.TINT64}: ssa.OpNeg64,
2255 {ir.ONEG, types.TUINT64}: ssa.OpNeg64,
2256 {ir.ONEG, types.TFLOAT32}: ssa.OpNeg32F,
2257 {ir.ONEG, types.TFLOAT64}: ssa.OpNeg64F,
2259 {ir.OBITNOT, types.TINT8}: ssa.OpCom8,
2260 {ir.OBITNOT, types.TUINT8}: ssa.OpCom8,
2261 {ir.OBITNOT, types.TINT16}: ssa.OpCom16,
2262 {ir.OBITNOT, types.TUINT16}: ssa.OpCom16,
2263 {ir.OBITNOT, types.TINT32}: ssa.OpCom32,
2264 {ir.OBITNOT, types.TUINT32}: ssa.OpCom32,
2265 {ir.OBITNOT, types.TINT64}: ssa.OpCom64,
2266 {ir.OBITNOT, types.TUINT64}: ssa.OpCom64,
2268 {ir.OIMAG, types.TCOMPLEX64}: ssa.OpComplexImag,
2269 {ir.OIMAG, types.TCOMPLEX128}: ssa.OpComplexImag,
2270 {ir.OREAL, types.TCOMPLEX64}: ssa.OpComplexReal,
2271 {ir.OREAL, types.TCOMPLEX128}: ssa.OpComplexReal,
2273 {ir.OMUL, types.TINT8}: ssa.OpMul8,
2274 {ir.OMUL, types.TUINT8}: ssa.OpMul8,
2275 {ir.OMUL, types.TINT16}: ssa.OpMul16,
2276 {ir.OMUL, types.TUINT16}: ssa.OpMul16,
2277 {ir.OMUL, types.TINT32}: ssa.OpMul32,
2278 {ir.OMUL, types.TUINT32}: ssa.OpMul32,
2279 {ir.OMUL, types.TINT64}: ssa.OpMul64,
2280 {ir.OMUL, types.TUINT64}: ssa.OpMul64,
2281 {ir.OMUL, types.TFLOAT32}: ssa.OpMul32F,
2282 {ir.OMUL, types.TFLOAT64}: ssa.OpMul64F,
2284 {ir.ODIV, types.TFLOAT32}: ssa.OpDiv32F,
2285 {ir.ODIV, types.TFLOAT64}: ssa.OpDiv64F,
2287 {ir.ODIV, types.TINT8}: ssa.OpDiv8,
2288 {ir.ODIV, types.TUINT8}: ssa.OpDiv8u,
2289 {ir.ODIV, types.TINT16}: ssa.OpDiv16,
2290 {ir.ODIV, types.TUINT16}: ssa.OpDiv16u,
2291 {ir.ODIV, types.TINT32}: ssa.OpDiv32,
2292 {ir.ODIV, types.TUINT32}: ssa.OpDiv32u,
2293 {ir.ODIV, types.TINT64}: ssa.OpDiv64,
2294 {ir.ODIV, types.TUINT64}: ssa.OpDiv64u,
2296 {ir.OMOD, types.TINT8}: ssa.OpMod8,
2297 {ir.OMOD, types.TUINT8}: ssa.OpMod8u,
2298 {ir.OMOD, types.TINT16}: ssa.OpMod16,
2299 {ir.OMOD, types.TUINT16}: ssa.OpMod16u,
2300 {ir.OMOD, types.TINT32}: ssa.OpMod32,
2301 {ir.OMOD, types.TUINT32}: ssa.OpMod32u,
2302 {ir.OMOD, types.TINT64}: ssa.OpMod64,
2303 {ir.OMOD, types.TUINT64}: ssa.OpMod64u,
2305 {ir.OAND, types.TINT8}: ssa.OpAnd8,
2306 {ir.OAND, types.TUINT8}: ssa.OpAnd8,
2307 {ir.OAND, types.TINT16}: ssa.OpAnd16,
2308 {ir.OAND, types.TUINT16}: ssa.OpAnd16,
2309 {ir.OAND, types.TINT32}: ssa.OpAnd32,
2310 {ir.OAND, types.TUINT32}: ssa.OpAnd32,
2311 {ir.OAND, types.TINT64}: ssa.OpAnd64,
2312 {ir.OAND, types.TUINT64}: ssa.OpAnd64,
2314 {ir.OOR, types.TINT8}: ssa.OpOr8,
2315 {ir.OOR, types.TUINT8}: ssa.OpOr8,
2316 {ir.OOR, types.TINT16}: ssa.OpOr16,
2317 {ir.OOR, types.TUINT16}: ssa.OpOr16,
2318 {ir.OOR, types.TINT32}: ssa.OpOr32,
2319 {ir.OOR, types.TUINT32}: ssa.OpOr32,
2320 {ir.OOR, types.TINT64}: ssa.OpOr64,
2321 {ir.OOR, types.TUINT64}: ssa.OpOr64,
2323 {ir.OXOR, types.TINT8}: ssa.OpXor8,
2324 {ir.OXOR, types.TUINT8}: ssa.OpXor8,
2325 {ir.OXOR, types.TINT16}: ssa.OpXor16,
2326 {ir.OXOR, types.TUINT16}: ssa.OpXor16,
2327 {ir.OXOR, types.TINT32}: ssa.OpXor32,
2328 {ir.OXOR, types.TUINT32}: ssa.OpXor32,
2329 {ir.OXOR, types.TINT64}: ssa.OpXor64,
2330 {ir.OXOR, types.TUINT64}: ssa.OpXor64,
2332 {ir.OEQ, types.TBOOL}: ssa.OpEqB,
2333 {ir.OEQ, types.TINT8}: ssa.OpEq8,
2334 {ir.OEQ, types.TUINT8}: ssa.OpEq8,
2335 {ir.OEQ, types.TINT16}: ssa.OpEq16,
2336 {ir.OEQ, types.TUINT16}: ssa.OpEq16,
2337 {ir.OEQ, types.TINT32}: ssa.OpEq32,
2338 {ir.OEQ, types.TUINT32}: ssa.OpEq32,
2339 {ir.OEQ, types.TINT64}: ssa.OpEq64,
2340 {ir.OEQ, types.TUINT64}: ssa.OpEq64,
2341 {ir.OEQ, types.TINTER}: ssa.OpEqInter,
2342 {ir.OEQ, types.TSLICE}: ssa.OpEqSlice,
2343 {ir.OEQ, types.TFUNC}: ssa.OpEqPtr,
2344 {ir.OEQ, types.TMAP}: ssa.OpEqPtr,
2345 {ir.OEQ, types.TCHAN}: ssa.OpEqPtr,
2346 {ir.OEQ, types.TPTR}: ssa.OpEqPtr,
2347 {ir.OEQ, types.TUINTPTR}: ssa.OpEqPtr,
2348 {ir.OEQ, types.TUNSAFEPTR}: ssa.OpEqPtr,
2349 {ir.OEQ, types.TFLOAT64}: ssa.OpEq64F,
2350 {ir.OEQ, types.TFLOAT32}: ssa.OpEq32F,
2352 {ir.ONE, types.TBOOL}: ssa.OpNeqB,
2353 {ir.ONE, types.TINT8}: ssa.OpNeq8,
2354 {ir.ONE, types.TUINT8}: ssa.OpNeq8,
2355 {ir.ONE, types.TINT16}: ssa.OpNeq16,
2356 {ir.ONE, types.TUINT16}: ssa.OpNeq16,
2357 {ir.ONE, types.TINT32}: ssa.OpNeq32,
2358 {ir.ONE, types.TUINT32}: ssa.OpNeq32,
2359 {ir.ONE, types.TINT64}: ssa.OpNeq64,
2360 {ir.ONE, types.TUINT64}: ssa.OpNeq64,
2361 {ir.ONE, types.TINTER}: ssa.OpNeqInter,
2362 {ir.ONE, types.TSLICE}: ssa.OpNeqSlice,
2363 {ir.ONE, types.TFUNC}: ssa.OpNeqPtr,
2364 {ir.ONE, types.TMAP}: ssa.OpNeqPtr,
2365 {ir.ONE, types.TCHAN}: ssa.OpNeqPtr,
2366 {ir.ONE, types.TPTR}: ssa.OpNeqPtr,
2367 {ir.ONE, types.TUINTPTR}: ssa.OpNeqPtr,
2368 {ir.ONE, types.TUNSAFEPTR}: ssa.OpNeqPtr,
2369 {ir.ONE, types.TFLOAT64}: ssa.OpNeq64F,
2370 {ir.ONE, types.TFLOAT32}: ssa.OpNeq32F,
2372 {ir.OLT, types.TINT8}: ssa.OpLess8,
2373 {ir.OLT, types.TUINT8}: ssa.OpLess8U,
2374 {ir.OLT, types.TINT16}: ssa.OpLess16,
2375 {ir.OLT, types.TUINT16}: ssa.OpLess16U,
2376 {ir.OLT, types.TINT32}: ssa.OpLess32,
2377 {ir.OLT, types.TUINT32}: ssa.OpLess32U,
2378 {ir.OLT, types.TINT64}: ssa.OpLess64,
2379 {ir.OLT, types.TUINT64}: ssa.OpLess64U,
2380 {ir.OLT, types.TFLOAT64}: ssa.OpLess64F,
2381 {ir.OLT, types.TFLOAT32}: ssa.OpLess32F,
2383 {ir.OLE, types.TINT8}: ssa.OpLeq8,
2384 {ir.OLE, types.TUINT8}: ssa.OpLeq8U,
2385 {ir.OLE, types.TINT16}: ssa.OpLeq16,
2386 {ir.OLE, types.TUINT16}: ssa.OpLeq16U,
2387 {ir.OLE, types.TINT32}: ssa.OpLeq32,
2388 {ir.OLE, types.TUINT32}: ssa.OpLeq32U,
2389 {ir.OLE, types.TINT64}: ssa.OpLeq64,
2390 {ir.OLE, types.TUINT64}: ssa.OpLeq64U,
2391 {ir.OLE, types.TFLOAT64}: ssa.OpLeq64F,
2392 {ir.OLE, types.TFLOAT32}: ssa.OpLeq32F,
2395 func (s *state) concreteEtype(t *types.Type) types.Kind {
2401 if s.config.PtrSize == 8 {
2406 if s.config.PtrSize == 8 {
2407 return types.TUINT64
2409 return types.TUINT32
2410 case types.TUINTPTR:
2411 if s.config.PtrSize == 8 {
2412 return types.TUINT64
2414 return types.TUINT32
2418 func (s *state) ssaOp(op ir.Op, t *types.Type) ssa.Op {
2419 etype := s.concreteEtype(t)
2420 x, ok := opToSSA[opAndType{op, etype}]
2422 s.Fatalf("unhandled binary op %v %s", op, etype)
2427 type opAndTwoTypes struct {
2433 type twoTypes struct {
2438 type twoOpsAndType struct {
2441 intermediateType types.Kind
2444 var fpConvOpToSSA = map[twoTypes]twoOpsAndType{
2446 {types.TINT8, types.TFLOAT32}: {ssa.OpSignExt8to32, ssa.OpCvt32to32F, types.TINT32},
2447 {types.TINT16, types.TFLOAT32}: {ssa.OpSignExt16to32, ssa.OpCvt32to32F, types.TINT32},
2448 {types.TINT32, types.TFLOAT32}: {ssa.OpCopy, ssa.OpCvt32to32F, types.TINT32},
2449 {types.TINT64, types.TFLOAT32}: {ssa.OpCopy, ssa.OpCvt64to32F, types.TINT64},
2451 {types.TINT8, types.TFLOAT64}: {ssa.OpSignExt8to32, ssa.OpCvt32to64F, types.TINT32},
2452 {types.TINT16, types.TFLOAT64}: {ssa.OpSignExt16to32, ssa.OpCvt32to64F, types.TINT32},
2453 {types.TINT32, types.TFLOAT64}: {ssa.OpCopy, ssa.OpCvt32to64F, types.TINT32},
2454 {types.TINT64, types.TFLOAT64}: {ssa.OpCopy, ssa.OpCvt64to64F, types.TINT64},
2456 {types.TFLOAT32, types.TINT8}: {ssa.OpCvt32Fto32, ssa.OpTrunc32to8, types.TINT32},
2457 {types.TFLOAT32, types.TINT16}: {ssa.OpCvt32Fto32, ssa.OpTrunc32to16, types.TINT32},
2458 {types.TFLOAT32, types.TINT32}: {ssa.OpCvt32Fto32, ssa.OpCopy, types.TINT32},
2459 {types.TFLOAT32, types.TINT64}: {ssa.OpCvt32Fto64, ssa.OpCopy, types.TINT64},
2461 {types.TFLOAT64, types.TINT8}: {ssa.OpCvt64Fto32, ssa.OpTrunc32to8, types.TINT32},
2462 {types.TFLOAT64, types.TINT16}: {ssa.OpCvt64Fto32, ssa.OpTrunc32to16, types.TINT32},
2463 {types.TFLOAT64, types.TINT32}: {ssa.OpCvt64Fto32, ssa.OpCopy, types.TINT32},
2464 {types.TFLOAT64, types.TINT64}: {ssa.OpCvt64Fto64, ssa.OpCopy, types.TINT64},
2466 {types.TUINT8, types.TFLOAT32}: {ssa.OpZeroExt8to32, ssa.OpCvt32to32F, types.TINT32},
2467 {types.TUINT16, types.TFLOAT32}: {ssa.OpZeroExt16to32, ssa.OpCvt32to32F, types.TINT32},
2468 {types.TUINT32, types.TFLOAT32}: {ssa.OpZeroExt32to64, ssa.OpCvt64to32F, types.TINT64}, // go wide to dodge unsigned
2469 {types.TUINT64, types.TFLOAT32}: {ssa.OpCopy, ssa.OpInvalid, types.TUINT64}, // Cvt64Uto32F, branchy code expansion instead
2471 {types.TUINT8, types.TFLOAT64}: {ssa.OpZeroExt8to32, ssa.OpCvt32to64F, types.TINT32},
2472 {types.TUINT16, types.TFLOAT64}: {ssa.OpZeroExt16to32, ssa.OpCvt32to64F, types.TINT32},
2473 {types.TUINT32, types.TFLOAT64}: {ssa.OpZeroExt32to64, ssa.OpCvt64to64F, types.TINT64}, // go wide to dodge unsigned
2474 {types.TUINT64, types.TFLOAT64}: {ssa.OpCopy, ssa.OpInvalid, types.TUINT64}, // Cvt64Uto64F, branchy code expansion instead
2476 {types.TFLOAT32, types.TUINT8}: {ssa.OpCvt32Fto32, ssa.OpTrunc32to8, types.TINT32},
2477 {types.TFLOAT32, types.TUINT16}: {ssa.OpCvt32Fto32, ssa.OpTrunc32to16, types.TINT32},
2478 {types.TFLOAT32, types.TUINT32}: {ssa.OpCvt32Fto64, ssa.OpTrunc64to32, types.TINT64}, // go wide to dodge unsigned
2479 {types.TFLOAT32, types.TUINT64}: {ssa.OpInvalid, ssa.OpCopy, types.TUINT64}, // Cvt32Fto64U, branchy code expansion instead
2481 {types.TFLOAT64, types.TUINT8}: {ssa.OpCvt64Fto32, ssa.OpTrunc32to8, types.TINT32},
2482 {types.TFLOAT64, types.TUINT16}: {ssa.OpCvt64Fto32, ssa.OpTrunc32to16, types.TINT32},
2483 {types.TFLOAT64, types.TUINT32}: {ssa.OpCvt64Fto64, ssa.OpTrunc64to32, types.TINT64}, // go wide to dodge unsigned
2484 {types.TFLOAT64, types.TUINT64}: {ssa.OpInvalid, ssa.OpCopy, types.TUINT64}, // Cvt64Fto64U, branchy code expansion instead
2487 {types.TFLOAT64, types.TFLOAT32}: {ssa.OpCvt64Fto32F, ssa.OpCopy, types.TFLOAT32},
2488 {types.TFLOAT64, types.TFLOAT64}: {ssa.OpRound64F, ssa.OpCopy, types.TFLOAT64},
2489 {types.TFLOAT32, types.TFLOAT32}: {ssa.OpRound32F, ssa.OpCopy, types.TFLOAT32},
2490 {types.TFLOAT32, types.TFLOAT64}: {ssa.OpCvt32Fto64F, ssa.OpCopy, types.TFLOAT64},
2493 // this map is used only for 32-bit arch, and only includes the difference
2494 // on 32-bit arch, don't use int64<->float conversion for uint32
2495 var fpConvOpToSSA32 = map[twoTypes]twoOpsAndType{
2496 {types.TUINT32, types.TFLOAT32}: {ssa.OpCopy, ssa.OpCvt32Uto32F, types.TUINT32},
2497 {types.TUINT32, types.TFLOAT64}: {ssa.OpCopy, ssa.OpCvt32Uto64F, types.TUINT32},
2498 {types.TFLOAT32, types.TUINT32}: {ssa.OpCvt32Fto32U, ssa.OpCopy, types.TUINT32},
2499 {types.TFLOAT64, types.TUINT32}: {ssa.OpCvt64Fto32U, ssa.OpCopy, types.TUINT32},
2502 // uint64<->float conversions, only on machines that have instructions for that
2503 var uint64fpConvOpToSSA = map[twoTypes]twoOpsAndType{
2504 {types.TUINT64, types.TFLOAT32}: {ssa.OpCopy, ssa.OpCvt64Uto32F, types.TUINT64},
2505 {types.TUINT64, types.TFLOAT64}: {ssa.OpCopy, ssa.OpCvt64Uto64F, types.TUINT64},
2506 {types.TFLOAT32, types.TUINT64}: {ssa.OpCvt32Fto64U, ssa.OpCopy, types.TUINT64},
2507 {types.TFLOAT64, types.TUINT64}: {ssa.OpCvt64Fto64U, ssa.OpCopy, types.TUINT64},
2510 var shiftOpToSSA = map[opAndTwoTypes]ssa.Op{
2511 {ir.OLSH, types.TINT8, types.TUINT8}: ssa.OpLsh8x8,
2512 {ir.OLSH, types.TUINT8, types.TUINT8}: ssa.OpLsh8x8,
2513 {ir.OLSH, types.TINT8, types.TUINT16}: ssa.OpLsh8x16,
2514 {ir.OLSH, types.TUINT8, types.TUINT16}: ssa.OpLsh8x16,
2515 {ir.OLSH, types.TINT8, types.TUINT32}: ssa.OpLsh8x32,
2516 {ir.OLSH, types.TUINT8, types.TUINT32}: ssa.OpLsh8x32,
2517 {ir.OLSH, types.TINT8, types.TUINT64}: ssa.OpLsh8x64,
2518 {ir.OLSH, types.TUINT8, types.TUINT64}: ssa.OpLsh8x64,
2520 {ir.OLSH, types.TINT16, types.TUINT8}: ssa.OpLsh16x8,
2521 {ir.OLSH, types.TUINT16, types.TUINT8}: ssa.OpLsh16x8,
2522 {ir.OLSH, types.TINT16, types.TUINT16}: ssa.OpLsh16x16,
2523 {ir.OLSH, types.TUINT16, types.TUINT16}: ssa.OpLsh16x16,
2524 {ir.OLSH, types.TINT16, types.TUINT32}: ssa.OpLsh16x32,
2525 {ir.OLSH, types.TUINT16, types.TUINT32}: ssa.OpLsh16x32,
2526 {ir.OLSH, types.TINT16, types.TUINT64}: ssa.OpLsh16x64,
2527 {ir.OLSH, types.TUINT16, types.TUINT64}: ssa.OpLsh16x64,
2529 {ir.OLSH, types.TINT32, types.TUINT8}: ssa.OpLsh32x8,
2530 {ir.OLSH, types.TUINT32, types.TUINT8}: ssa.OpLsh32x8,
2531 {ir.OLSH, types.TINT32, types.TUINT16}: ssa.OpLsh32x16,
2532 {ir.OLSH, types.TUINT32, types.TUINT16}: ssa.OpLsh32x16,
2533 {ir.OLSH, types.TINT32, types.TUINT32}: ssa.OpLsh32x32,
2534 {ir.OLSH, types.TUINT32, types.TUINT32}: ssa.OpLsh32x32,
2535 {ir.OLSH, types.TINT32, types.TUINT64}: ssa.OpLsh32x64,
2536 {ir.OLSH, types.TUINT32, types.TUINT64}: ssa.OpLsh32x64,
2538 {ir.OLSH, types.TINT64, types.TUINT8}: ssa.OpLsh64x8,
2539 {ir.OLSH, types.TUINT64, types.TUINT8}: ssa.OpLsh64x8,
2540 {ir.OLSH, types.TINT64, types.TUINT16}: ssa.OpLsh64x16,
2541 {ir.OLSH, types.TUINT64, types.TUINT16}: ssa.OpLsh64x16,
2542 {ir.OLSH, types.TINT64, types.TUINT32}: ssa.OpLsh64x32,
2543 {ir.OLSH, types.TUINT64, types.TUINT32}: ssa.OpLsh64x32,
2544 {ir.OLSH, types.TINT64, types.TUINT64}: ssa.OpLsh64x64,
2545 {ir.OLSH, types.TUINT64, types.TUINT64}: ssa.OpLsh64x64,
2547 {ir.ORSH, types.TINT8, types.TUINT8}: ssa.OpRsh8x8,
2548 {ir.ORSH, types.TUINT8, types.TUINT8}: ssa.OpRsh8Ux8,
2549 {ir.ORSH, types.TINT8, types.TUINT16}: ssa.OpRsh8x16,
2550 {ir.ORSH, types.TUINT8, types.TUINT16}: ssa.OpRsh8Ux16,
2551 {ir.ORSH, types.TINT8, types.TUINT32}: ssa.OpRsh8x32,
2552 {ir.ORSH, types.TUINT8, types.TUINT32}: ssa.OpRsh8Ux32,
2553 {ir.ORSH, types.TINT8, types.TUINT64}: ssa.OpRsh8x64,
2554 {ir.ORSH, types.TUINT8, types.TUINT64}: ssa.OpRsh8Ux64,
2556 {ir.ORSH, types.TINT16, types.TUINT8}: ssa.OpRsh16x8,
2557 {ir.ORSH, types.TUINT16, types.TUINT8}: ssa.OpRsh16Ux8,
2558 {ir.ORSH, types.TINT16, types.TUINT16}: ssa.OpRsh16x16,
2559 {ir.ORSH, types.TUINT16, types.TUINT16}: ssa.OpRsh16Ux16,
2560 {ir.ORSH, types.TINT16, types.TUINT32}: ssa.OpRsh16x32,
2561 {ir.ORSH, types.TUINT16, types.TUINT32}: ssa.OpRsh16Ux32,
2562 {ir.ORSH, types.TINT16, types.TUINT64}: ssa.OpRsh16x64,
2563 {ir.ORSH, types.TUINT16, types.TUINT64}: ssa.OpRsh16Ux64,
2565 {ir.ORSH, types.TINT32, types.TUINT8}: ssa.OpRsh32x8,
2566 {ir.ORSH, types.TUINT32, types.TUINT8}: ssa.OpRsh32Ux8,
2567 {ir.ORSH, types.TINT32, types.TUINT16}: ssa.OpRsh32x16,
2568 {ir.ORSH, types.TUINT32, types.TUINT16}: ssa.OpRsh32Ux16,
2569 {ir.ORSH, types.TINT32, types.TUINT32}: ssa.OpRsh32x32,
2570 {ir.ORSH, types.TUINT32, types.TUINT32}: ssa.OpRsh32Ux32,
2571 {ir.ORSH, types.TINT32, types.TUINT64}: ssa.OpRsh32x64,
2572 {ir.ORSH, types.TUINT32, types.TUINT64}: ssa.OpRsh32Ux64,
2574 {ir.ORSH, types.TINT64, types.TUINT8}: ssa.OpRsh64x8,
2575 {ir.ORSH, types.TUINT64, types.TUINT8}: ssa.OpRsh64Ux8,
2576 {ir.ORSH, types.TINT64, types.TUINT16}: ssa.OpRsh64x16,
2577 {ir.ORSH, types.TUINT64, types.TUINT16}: ssa.OpRsh64Ux16,
2578 {ir.ORSH, types.TINT64, types.TUINT32}: ssa.OpRsh64x32,
2579 {ir.ORSH, types.TUINT64, types.TUINT32}: ssa.OpRsh64Ux32,
2580 {ir.ORSH, types.TINT64, types.TUINT64}: ssa.OpRsh64x64,
2581 {ir.ORSH, types.TUINT64, types.TUINT64}: ssa.OpRsh64Ux64,
2584 func (s *state) ssaShiftOp(op ir.Op, t *types.Type, u *types.Type) ssa.Op {
2585 etype1 := s.concreteEtype(t)
2586 etype2 := s.concreteEtype(u)
2587 x, ok := shiftOpToSSA[opAndTwoTypes{op, etype1, etype2}]
2589 s.Fatalf("unhandled shift op %v etype=%s/%s", op, etype1, etype2)
2594 func (s *state) uintptrConstant(v uint64) *ssa.Value {
2595 if s.config.PtrSize == 4 {
2596 return s.newValue0I(ssa.OpConst32, types.Types[types.TUINTPTR], int64(v))
2598 return s.newValue0I(ssa.OpConst64, types.Types[types.TUINTPTR], int64(v))
2601 func (s *state) conv(n ir.Node, v *ssa.Value, ft, tt *types.Type) *ssa.Value {
2602 if ft.IsBoolean() && tt.IsKind(types.TUINT8) {
2603 // Bool -> uint8 is generated internally when indexing into runtime.staticbyte.
2604 return s.newValue1(ssa.OpCvtBoolToUint8, tt, v)
2606 if ft.IsInteger() && tt.IsInteger() {
2608 if tt.Size() == ft.Size() {
2610 } else if tt.Size() < ft.Size() {
2612 switch 10*ft.Size() + tt.Size() {
2614 op = ssa.OpTrunc16to8
2616 op = ssa.OpTrunc32to8
2618 op = ssa.OpTrunc32to16
2620 op = ssa.OpTrunc64to8
2622 op = ssa.OpTrunc64to16
2624 op = ssa.OpTrunc64to32
2626 s.Fatalf("weird integer truncation %v -> %v", ft, tt)
2628 } else if ft.IsSigned() {
2630 switch 10*ft.Size() + tt.Size() {
2632 op = ssa.OpSignExt8to16
2634 op = ssa.OpSignExt8to32
2636 op = ssa.OpSignExt8to64
2638 op = ssa.OpSignExt16to32
2640 op = ssa.OpSignExt16to64
2642 op = ssa.OpSignExt32to64
2644 s.Fatalf("bad integer sign extension %v -> %v", ft, tt)
2648 switch 10*ft.Size() + tt.Size() {
2650 op = ssa.OpZeroExt8to16
2652 op = ssa.OpZeroExt8to32
2654 op = ssa.OpZeroExt8to64
2656 op = ssa.OpZeroExt16to32
2658 op = ssa.OpZeroExt16to64
2660 op = ssa.OpZeroExt32to64
2662 s.Fatalf("weird integer sign extension %v -> %v", ft, tt)
2665 return s.newValue1(op, tt, v)
2668 if ft.IsComplex() && tt.IsComplex() {
2670 if ft.Size() == tt.Size() {
2677 s.Fatalf("weird complex conversion %v -> %v", ft, tt)
2679 } else if ft.Size() == 8 && tt.Size() == 16 {
2680 op = ssa.OpCvt32Fto64F
2681 } else if ft.Size() == 16 && tt.Size() == 8 {
2682 op = ssa.OpCvt64Fto32F
2684 s.Fatalf("weird complex conversion %v -> %v", ft, tt)
2686 ftp := types.FloatForComplex(ft)
2687 ttp := types.FloatForComplex(tt)
2688 return s.newValue2(ssa.OpComplexMake, tt,
2689 s.newValueOrSfCall1(op, ttp, s.newValue1(ssa.OpComplexReal, ftp, v)),
2690 s.newValueOrSfCall1(op, ttp, s.newValue1(ssa.OpComplexImag, ftp, v)))
2693 if tt.IsComplex() { // and ft is not complex
2694 // Needed for generics support - can't happen in normal Go code.
2695 et := types.FloatForComplex(tt)
2696 v = s.conv(n, v, ft, et)
2697 return s.newValue2(ssa.OpComplexMake, tt, v, s.zeroVal(et))
2700 if ft.IsFloat() || tt.IsFloat() {
2701 conv, ok := fpConvOpToSSA[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]
2702 if s.config.RegSize == 4 && Arch.LinkArch.Family != sys.MIPS && !s.softFloat {
2703 if conv1, ok1 := fpConvOpToSSA32[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]; ok1 {
2707 if Arch.LinkArch.Family == sys.ARM64 || Arch.LinkArch.Family == sys.Wasm || Arch.LinkArch.Family == sys.S390X || s.softFloat {
2708 if conv1, ok1 := uint64fpConvOpToSSA[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]; ok1 {
2713 if Arch.LinkArch.Family == sys.MIPS && !s.softFloat {
2714 if ft.Size() == 4 && ft.IsInteger() && !ft.IsSigned() {
2715 // tt is float32 or float64, and ft is also unsigned
2717 return s.uint32Tofloat32(n, v, ft, tt)
2720 return s.uint32Tofloat64(n, v, ft, tt)
2722 } else if tt.Size() == 4 && tt.IsInteger() && !tt.IsSigned() {
2723 // ft is float32 or float64, and tt is unsigned integer
2725 return s.float32ToUint32(n, v, ft, tt)
2728 return s.float64ToUint32(n, v, ft, tt)
2734 s.Fatalf("weird float conversion %v -> %v", ft, tt)
2736 op1, op2, it := conv.op1, conv.op2, conv.intermediateType
2738 if op1 != ssa.OpInvalid && op2 != ssa.OpInvalid {
2739 // normal case, not tripping over unsigned 64
2740 if op1 == ssa.OpCopy {
2741 if op2 == ssa.OpCopy {
2744 return s.newValueOrSfCall1(op2, tt, v)
2746 if op2 == ssa.OpCopy {
2747 return s.newValueOrSfCall1(op1, tt, v)
2749 return s.newValueOrSfCall1(op2, tt, s.newValueOrSfCall1(op1, types.Types[it], v))
2751 // Tricky 64-bit unsigned cases.
2753 // tt is float32 or float64, and ft is also unsigned
2755 return s.uint64Tofloat32(n, v, ft, tt)
2758 return s.uint64Tofloat64(n, v, ft, tt)
2760 s.Fatalf("weird unsigned integer to float conversion %v -> %v", ft, tt)
2762 // ft is float32 or float64, and tt is unsigned integer
2764 return s.float32ToUint64(n, v, ft, tt)
2767 return s.float64ToUint64(n, v, ft, tt)
2769 s.Fatalf("weird float to unsigned integer conversion %v -> %v", ft, tt)
2773 s.Fatalf("unhandled OCONV %s -> %s", ft.Kind(), tt.Kind())
2777 // expr converts the expression n to ssa, adds it to s and returns the ssa result.
2778 func (s *state) expr(n ir.Node) *ssa.Value {
2779 return s.exprCheckPtr(n, true)
2782 func (s *state) exprCheckPtr(n ir.Node, checkPtrOK bool) *ssa.Value {
2783 if ir.HasUniquePos(n) {
2784 // ONAMEs and named OLITERALs have the line number
2785 // of the decl, not the use. See issue 14742.
2790 s.stmtList(n.Init())
2792 case ir.OBYTES2STRTMP:
2793 n := n.(*ir.ConvExpr)
2794 slice := s.expr(n.X)
2795 ptr := s.newValue1(ssa.OpSlicePtr, s.f.Config.Types.BytePtr, slice)
2796 len := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], slice)
2797 return s.newValue2(ssa.OpStringMake, n.Type(), ptr, len)
2798 case ir.OSTR2BYTESTMP:
2799 n := n.(*ir.ConvExpr)
2801 ptr := s.newValue1(ssa.OpStringPtr, s.f.Config.Types.BytePtr, str)
2803 // We need to ensure []byte("") evaluates to []byte{}, and not []byte(nil).
2805 // TODO(mdempsky): Investigate using "len != 0" instead of "ptr != nil".
2806 cond := s.newValue2(ssa.OpNeqPtr, types.Types[types.TBOOL], ptr, s.constNil(ptr.Type))
2807 zerobase := s.newValue1A(ssa.OpAddr, ptr.Type, ir.Syms.Zerobase, s.sb)
2808 ptr = s.ternary(cond, ptr, zerobase)
2810 len := s.newValue1(ssa.OpStringLen, types.Types[types.TINT], str)
2811 return s.newValue3(ssa.OpSliceMake, n.Type(), ptr, len, len)
2813 n := n.(*ir.UnaryExpr)
2814 aux := n.X.(*ir.Name).Linksym()
2815 // OCFUNC is used to build function values, which must
2816 // always reference ABIInternal entry points.
2817 if aux.ABI() != obj.ABIInternal {
2818 s.Fatalf("expected ABIInternal: %v", aux.ABI())
2820 return s.entryNewValue1A(ssa.OpAddr, n.Type(), aux, s.sb)
2823 if n.Class == ir.PFUNC {
2824 // "value" of a function is the address of the function's closure
2825 sym := staticdata.FuncLinksym(n)
2826 return s.entryNewValue1A(ssa.OpAddr, types.NewPtr(n.Type()), sym, s.sb)
2829 return s.variable(n, n.Type())
2831 return s.load(n.Type(), s.addr(n))
2832 case ir.OLINKSYMOFFSET:
2833 n := n.(*ir.LinksymOffsetExpr)
2834 return s.load(n.Type(), s.addr(n))
2836 n := n.(*ir.NilExpr)
2840 return s.constSlice(t)
2841 case t.IsInterface():
2842 return s.constInterface(t)
2844 return s.constNil(t)
2847 switch u := n.Val(); u.Kind() {
2849 i := ir.IntVal(n.Type(), u)
2850 switch n.Type().Size() {
2852 return s.constInt8(n.Type(), int8(i))
2854 return s.constInt16(n.Type(), int16(i))
2856 return s.constInt32(n.Type(), int32(i))
2858 return s.constInt64(n.Type(), i)
2860 s.Fatalf("bad integer size %d", n.Type().Size())
2863 case constant.String:
2864 i := constant.StringVal(u)
2866 return s.constEmptyString(n.Type())
2868 return s.entryNewValue0A(ssa.OpConstString, n.Type(), ssa.StringToAux(i))
2870 return s.constBool(constant.BoolVal(u))
2871 case constant.Float:
2872 f, _ := constant.Float64Val(u)
2873 switch n.Type().Size() {
2875 return s.constFloat32(n.Type(), f)
2877 return s.constFloat64(n.Type(), f)
2879 s.Fatalf("bad float size %d", n.Type().Size())
2882 case constant.Complex:
2883 re, _ := constant.Float64Val(constant.Real(u))
2884 im, _ := constant.Float64Val(constant.Imag(u))
2885 switch n.Type().Size() {
2887 pt := types.Types[types.TFLOAT32]
2888 return s.newValue2(ssa.OpComplexMake, n.Type(),
2889 s.constFloat32(pt, re),
2890 s.constFloat32(pt, im))
2892 pt := types.Types[types.TFLOAT64]
2893 return s.newValue2(ssa.OpComplexMake, n.Type(),
2894 s.constFloat64(pt, re),
2895 s.constFloat64(pt, im))
2897 s.Fatalf("bad complex size %d", n.Type().Size())
2901 s.Fatalf("unhandled OLITERAL %v", u.Kind())
2905 n := n.(*ir.ConvExpr)
2909 // Assume everything will work out, so set up our return value.
2910 // Anything interesting that happens from here is a fatal.
2916 // Special case for not confusing GC and liveness.
2917 // We don't want pointers accidentally classified
2918 // as not-pointers or vice-versa because of copy
2920 if to.IsPtrShaped() != from.IsPtrShaped() {
2921 return s.newValue2(ssa.OpConvert, to, x, s.mem())
2924 v := s.newValue1(ssa.OpCopy, to, x) // ensure that v has the right type
2927 if to.Kind() == types.TFUNC && from.IsPtrShaped() {
2931 // named <--> unnamed type or typed <--> untyped const
2932 if from.Kind() == to.Kind() {
2936 // unsafe.Pointer <--> *T
2937 if to.IsUnsafePtr() && from.IsPtrShaped() || from.IsUnsafePtr() && to.IsPtrShaped() {
2938 if s.checkPtrEnabled && checkPtrOK && to.IsPtr() && from.IsUnsafePtr() {
2939 s.checkPtrAlignment(n, v, nil)
2945 if to.Kind() == types.TMAP && from == types.NewPtr(reflectdata.MapType()) {
2949 types.CalcSize(from)
2951 if from.Size() != to.Size() {
2952 s.Fatalf("CONVNOP width mismatch %v (%d) -> %v (%d)\n", from, from.Size(), to, to.Size())
2955 if etypesign(from.Kind()) != etypesign(to.Kind()) {
2956 s.Fatalf("CONVNOP sign mismatch %v (%s) -> %v (%s)\n", from, from.Kind(), to, to.Kind())
2960 if base.Flag.Cfg.Instrumenting {
2961 // These appear to be fine, but they fail the
2962 // integer constraint below, so okay them here.
2963 // Sample non-integer conversion: map[string]string -> *uint8
2967 if etypesign(from.Kind()) == 0 {
2968 s.Fatalf("CONVNOP unrecognized non-integer %v -> %v\n", from, to)
2972 // integer, same width, same sign
2976 n := n.(*ir.ConvExpr)
2978 return s.conv(n, x, n.X.Type(), n.Type())
2981 n := n.(*ir.TypeAssertExpr)
2982 res, _ := s.dottype(n, false)
2985 case ir.ODYNAMICDOTTYPE:
2986 n := n.(*ir.DynamicTypeAssertExpr)
2987 res, _ := s.dynamicDottype(n, false)
2991 case ir.OLT, ir.OEQ, ir.ONE, ir.OLE, ir.OGE, ir.OGT:
2992 n := n.(*ir.BinaryExpr)
2995 if n.X.Type().IsComplex() {
2996 pt := types.FloatForComplex(n.X.Type())
2997 op := s.ssaOp(ir.OEQ, pt)
2998 r := s.newValueOrSfCall2(op, types.Types[types.TBOOL], s.newValue1(ssa.OpComplexReal, pt, a), s.newValue1(ssa.OpComplexReal, pt, b))
2999 i := s.newValueOrSfCall2(op, types.Types[types.TBOOL], s.newValue1(ssa.OpComplexImag, pt, a), s.newValue1(ssa.OpComplexImag, pt, b))
3000 c := s.newValue2(ssa.OpAndB, types.Types[types.TBOOL], r, i)
3005 return s.newValue1(ssa.OpNot, types.Types[types.TBOOL], c)
3007 s.Fatalf("ordered complex compare %v", n.Op())
3011 // Convert OGE and OGT into OLE and OLT.
3015 op, a, b = ir.OLE, b, a
3017 op, a, b = ir.OLT, b, a
3019 if n.X.Type().IsFloat() {
3021 return s.newValueOrSfCall2(s.ssaOp(op, n.X.Type()), types.Types[types.TBOOL], a, b)
3023 // integer comparison
3024 return s.newValue2(s.ssaOp(op, n.X.Type()), types.Types[types.TBOOL], a, b)
3026 n := n.(*ir.BinaryExpr)
3029 if n.Type().IsComplex() {
3030 mulop := ssa.OpMul64F
3031 addop := ssa.OpAdd64F
3032 subop := ssa.OpSub64F
3033 pt := types.FloatForComplex(n.Type()) // Could be Float32 or Float64
3034 wt := types.Types[types.TFLOAT64] // Compute in Float64 to minimize cancellation error
3036 areal := s.newValue1(ssa.OpComplexReal, pt, a)
3037 breal := s.newValue1(ssa.OpComplexReal, pt, b)
3038 aimag := s.newValue1(ssa.OpComplexImag, pt, a)
3039 bimag := s.newValue1(ssa.OpComplexImag, pt, b)
3041 if pt != wt { // Widen for calculation
3042 areal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, areal)
3043 breal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, breal)
3044 aimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, aimag)
3045 bimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, bimag)
3048 xreal := s.newValueOrSfCall2(subop, wt, s.newValueOrSfCall2(mulop, wt, areal, breal), s.newValueOrSfCall2(mulop, wt, aimag, bimag))
3049 ximag := s.newValueOrSfCall2(addop, wt, s.newValueOrSfCall2(mulop, wt, areal, bimag), s.newValueOrSfCall2(mulop, wt, aimag, breal))
3051 if pt != wt { // Narrow to store back
3052 xreal = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, xreal)
3053 ximag = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, ximag)
3056 return s.newValue2(ssa.OpComplexMake, n.Type(), xreal, ximag)
3059 if n.Type().IsFloat() {
3060 return s.newValueOrSfCall2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
3063 return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
3066 n := n.(*ir.BinaryExpr)
3069 if n.Type().IsComplex() {
3070 // TODO this is not executed because the front-end substitutes a runtime call.
3071 // That probably ought to change; with modest optimization the widen/narrow
3072 // conversions could all be elided in larger expression trees.
3073 mulop := ssa.OpMul64F
3074 addop := ssa.OpAdd64F
3075 subop := ssa.OpSub64F
3076 divop := ssa.OpDiv64F
3077 pt := types.FloatForComplex(n.Type()) // Could be Float32 or Float64
3078 wt := types.Types[types.TFLOAT64] // Compute in Float64 to minimize cancellation error
3080 areal := s.newValue1(ssa.OpComplexReal, pt, a)
3081 breal := s.newValue1(ssa.OpComplexReal, pt, b)
3082 aimag := s.newValue1(ssa.OpComplexImag, pt, a)
3083 bimag := s.newValue1(ssa.OpComplexImag, pt, b)
3085 if pt != wt { // Widen for calculation
3086 areal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, areal)
3087 breal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, breal)
3088 aimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, aimag)
3089 bimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, bimag)
3092 denom := s.newValueOrSfCall2(addop, wt, s.newValueOrSfCall2(mulop, wt, breal, breal), s.newValueOrSfCall2(mulop, wt, bimag, bimag))
3093 xreal := s.newValueOrSfCall2(addop, wt, s.newValueOrSfCall2(mulop, wt, areal, breal), s.newValueOrSfCall2(mulop, wt, aimag, bimag))
3094 ximag := s.newValueOrSfCall2(subop, wt, s.newValueOrSfCall2(mulop, wt, aimag, breal), s.newValueOrSfCall2(mulop, wt, areal, bimag))
3096 // TODO not sure if this is best done in wide precision or narrow
3097 // Double-rounding might be an issue.
3098 // Note that the pre-SSA implementation does the entire calculation
3099 // in wide format, so wide is compatible.
3100 xreal = s.newValueOrSfCall2(divop, wt, xreal, denom)
3101 ximag = s.newValueOrSfCall2(divop, wt, ximag, denom)
3103 if pt != wt { // Narrow to store back
3104 xreal = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, xreal)
3105 ximag = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, ximag)
3107 return s.newValue2(ssa.OpComplexMake, n.Type(), xreal, ximag)
3109 if n.Type().IsFloat() {
3110 return s.newValueOrSfCall2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
3112 return s.intDivide(n, a, b)
3114 n := n.(*ir.BinaryExpr)
3117 return s.intDivide(n, a, b)
3118 case ir.OADD, ir.OSUB:
3119 n := n.(*ir.BinaryExpr)
3122 if n.Type().IsComplex() {
3123 pt := types.FloatForComplex(n.Type())
3124 op := s.ssaOp(n.Op(), pt)
3125 return s.newValue2(ssa.OpComplexMake, n.Type(),
3126 s.newValueOrSfCall2(op, pt, s.newValue1(ssa.OpComplexReal, pt, a), s.newValue1(ssa.OpComplexReal, pt, b)),
3127 s.newValueOrSfCall2(op, pt, s.newValue1(ssa.OpComplexImag, pt, a), s.newValue1(ssa.OpComplexImag, pt, b)))
3129 if n.Type().IsFloat() {
3130 return s.newValueOrSfCall2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
3132 return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
3133 case ir.OAND, ir.OOR, ir.OXOR:
3134 n := n.(*ir.BinaryExpr)
3137 return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
3139 n := n.(*ir.BinaryExpr)
3142 b = s.newValue1(s.ssaOp(ir.OBITNOT, b.Type), b.Type, b)
3143 return s.newValue2(s.ssaOp(ir.OAND, n.Type()), a.Type, a, b)
3144 case ir.OLSH, ir.ORSH:
3145 n := n.(*ir.BinaryExpr)
3150 cmp := s.newValue2(s.ssaOp(ir.OLE, bt), types.Types[types.TBOOL], s.zeroVal(bt), b)
3151 s.check(cmp, ir.Syms.Panicshift)
3152 bt = bt.ToUnsigned()
3154 return s.newValue2(s.ssaShiftOp(n.Op(), n.Type(), bt), a.Type, a, b)
3155 case ir.OANDAND, ir.OOROR:
3156 // To implement OANDAND (and OOROR), we introduce a
3157 // new temporary variable to hold the result. The
3158 // variable is associated with the OANDAND node in the
3159 // s.vars table (normally variables are only
3160 // associated with ONAME nodes). We convert
3167 // Using var in the subsequent block introduces the
3168 // necessary phi variable.
3169 n := n.(*ir.LogicalExpr)
3174 b.Kind = ssa.BlockIf
3176 // In theory, we should set b.Likely here based on context.
3177 // However, gc only gives us likeliness hints
3178 // in a single place, for plain OIF statements,
3179 // and passing around context is finnicky, so don't bother for now.
3181 bRight := s.f.NewBlock(ssa.BlockPlain)
3182 bResult := s.f.NewBlock(ssa.BlockPlain)
3183 if n.Op() == ir.OANDAND {
3185 b.AddEdgeTo(bResult)
3186 } else if n.Op() == ir.OOROR {
3187 b.AddEdgeTo(bResult)
3191 s.startBlock(bRight)
3196 b.AddEdgeTo(bResult)
3198 s.startBlock(bResult)
3199 return s.variable(n, types.Types[types.TBOOL])
3201 n := n.(*ir.BinaryExpr)
3204 return s.newValue2(ssa.OpComplexMake, n.Type(), r, i)
3208 n := n.(*ir.UnaryExpr)
3210 if n.Type().IsComplex() {
3211 tp := types.FloatForComplex(n.Type())
3212 negop := s.ssaOp(n.Op(), tp)
3213 return s.newValue2(ssa.OpComplexMake, n.Type(),
3214 s.newValue1(negop, tp, s.newValue1(ssa.OpComplexReal, tp, a)),
3215 s.newValue1(negop, tp, s.newValue1(ssa.OpComplexImag, tp, a)))
3217 return s.newValue1(s.ssaOp(n.Op(), n.Type()), a.Type, a)
3218 case ir.ONOT, ir.OBITNOT:
3219 n := n.(*ir.UnaryExpr)
3221 return s.newValue1(s.ssaOp(n.Op(), n.Type()), a.Type, a)
3222 case ir.OIMAG, ir.OREAL:
3223 n := n.(*ir.UnaryExpr)
3225 return s.newValue1(s.ssaOp(n.Op(), n.X.Type()), n.Type(), a)
3227 n := n.(*ir.UnaryExpr)
3231 n := n.(*ir.AddrExpr)
3235 n := n.(*ir.ResultExpr)
3236 if s.prevCall == nil || s.prevCall.Op != ssa.OpStaticLECall && s.prevCall.Op != ssa.OpInterLECall && s.prevCall.Op != ssa.OpClosureLECall {
3237 panic("Expected to see a previous call")
3241 panic(fmt.Errorf("ORESULT %v does not match call %s", n, s.prevCall))
3243 return s.resultOfCall(s.prevCall, which, n.Type())
3246 n := n.(*ir.StarExpr)
3247 p := s.exprPtr(n.X, n.Bounded(), n.Pos())
3248 return s.load(n.Type(), p)
3251 n := n.(*ir.SelectorExpr)
3252 if n.X.Op() == ir.OSTRUCTLIT {
3253 // All literals with nonzero fields have already been
3254 // rewritten during walk. Any that remain are just T{}
3255 // or equivalents. Use the zero value.
3256 if !ir.IsZero(n.X) {
3257 s.Fatalf("literal with nonzero value in SSA: %v", n.X)
3259 return s.zeroVal(n.Type())
3261 // If n is addressable and can't be represented in
3262 // SSA, then load just the selected field. This
3263 // prevents false memory dependencies in race/msan/asan
3265 if ir.IsAddressable(n) && !s.canSSA(n) {
3267 return s.load(n.Type(), p)
3270 return s.newValue1I(ssa.OpStructSelect, n.Type(), int64(fieldIdx(n)), v)
3273 n := n.(*ir.SelectorExpr)
3274 p := s.exprPtr(n.X, n.Bounded(), n.Pos())
3275 p = s.newValue1I(ssa.OpOffPtr, types.NewPtr(n.Type()), n.Offset(), p)
3276 return s.load(n.Type(), p)
3279 n := n.(*ir.IndexExpr)
3281 case n.X.Type().IsString():
3282 if n.Bounded() && ir.IsConst(n.X, constant.String) && ir.IsConst(n.Index, constant.Int) {
3283 // Replace "abc"[1] with 'b'.
3284 // Delayed until now because "abc"[1] is not an ideal constant.
3285 // See test/fixedbugs/issue11370.go.
3286 return s.newValue0I(ssa.OpConst8, types.Types[types.TUINT8], int64(int8(ir.StringVal(n.X)[ir.Int64Val(n.Index)])))
3289 i := s.expr(n.Index)
3290 len := s.newValue1(ssa.OpStringLen, types.Types[types.TINT], a)
3291 i = s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded())
3292 ptrtyp := s.f.Config.Types.BytePtr
3293 ptr := s.newValue1(ssa.OpStringPtr, ptrtyp, a)
3294 if ir.IsConst(n.Index, constant.Int) {
3295 ptr = s.newValue1I(ssa.OpOffPtr, ptrtyp, ir.Int64Val(n.Index), ptr)
3297 ptr = s.newValue2(ssa.OpAddPtr, ptrtyp, ptr, i)
3299 return s.load(types.Types[types.TUINT8], ptr)
3300 case n.X.Type().IsSlice():
3302 return s.load(n.X.Type().Elem(), p)
3303 case n.X.Type().IsArray():
3304 if ssa.CanSSA(n.X.Type()) {
3305 // SSA can handle arrays of length at most 1.
3306 bound := n.X.Type().NumElem()
3308 i := s.expr(n.Index)
3310 // Bounds check will never succeed. Might as well
3311 // use constants for the bounds check.
3312 z := s.constInt(types.Types[types.TINT], 0)
3313 s.boundsCheck(z, z, ssa.BoundsIndex, false)
3314 // The return value won't be live, return junk.
3315 // But not quite junk, in case bounds checks are turned off. See issue 48092.
3316 return s.zeroVal(n.Type())
3318 len := s.constInt(types.Types[types.TINT], bound)
3319 s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded()) // checks i == 0
3320 return s.newValue1I(ssa.OpArraySelect, n.Type(), 0, a)
3323 return s.load(n.X.Type().Elem(), p)
3325 s.Fatalf("bad type for index %v", n.X.Type())
3329 case ir.OLEN, ir.OCAP:
3330 n := n.(*ir.UnaryExpr)
3332 case n.X.Type().IsSlice():
3333 op := ssa.OpSliceLen
3334 if n.Op() == ir.OCAP {
3337 return s.newValue1(op, types.Types[types.TINT], s.expr(n.X))
3338 case n.X.Type().IsString(): // string; not reachable for OCAP
3339 return s.newValue1(ssa.OpStringLen, types.Types[types.TINT], s.expr(n.X))
3340 case n.X.Type().IsMap(), n.X.Type().IsChan():
3341 return s.referenceTypeBuiltin(n, s.expr(n.X))
3343 return s.constInt(types.Types[types.TINT], n.X.Type().NumElem())
3347 n := n.(*ir.UnaryExpr)
3349 if n.X.Type().IsSlice() {
3351 return s.newValue1(ssa.OpSlicePtr, n.Type(), a)
3353 return s.newValue1(ssa.OpSlicePtrUnchecked, n.Type(), a)
3355 return s.newValue1(ssa.OpStringPtr, n.Type(), a)
3359 n := n.(*ir.UnaryExpr)
3361 return s.newValue1(ssa.OpITab, n.Type(), a)
3364 n := n.(*ir.UnaryExpr)
3366 return s.newValue1(ssa.OpIData, n.Type(), a)
3369 n := n.(*ir.BinaryExpr)
3372 return s.newValue2(ssa.OpIMake, n.Type(), tab, data)
3374 case ir.OSLICEHEADER:
3375 n := n.(*ir.SliceHeaderExpr)
3379 return s.newValue3(ssa.OpSliceMake, n.Type(), p, l, c)
3381 case ir.OSTRINGHEADER:
3382 n := n.(*ir.StringHeaderExpr)
3385 return s.newValue2(ssa.OpStringMake, n.Type(), p, l)
3387 case ir.OSLICE, ir.OSLICEARR, ir.OSLICE3, ir.OSLICE3ARR:
3388 n := n.(*ir.SliceExpr)
3389 check := s.checkPtrEnabled && n.Op() == ir.OSLICE3ARR && n.X.Op() == ir.OCONVNOP && n.X.(*ir.ConvExpr).X.Type().IsUnsafePtr()
3390 v := s.exprCheckPtr(n.X, !check)
3391 var i, j, k *ssa.Value
3401 p, l, c := s.slice(v, i, j, k, n.Bounded())
3403 // Emit checkptr instrumentation after bound check to prevent false positive, see #46938.
3404 s.checkPtrAlignment(n.X.(*ir.ConvExpr), v, s.conv(n.Max, k, k.Type, types.Types[types.TUINTPTR]))
3406 return s.newValue3(ssa.OpSliceMake, n.Type(), p, l, c)
3409 n := n.(*ir.SliceExpr)
3418 p, l, _ := s.slice(v, i, j, nil, n.Bounded())
3419 return s.newValue2(ssa.OpStringMake, n.Type(), p, l)
3421 case ir.OSLICE2ARRPTR:
3422 // if arrlen > slice.len {
3426 n := n.(*ir.ConvExpr)
3428 nelem := n.Type().Elem().NumElem()
3429 arrlen := s.constInt(types.Types[types.TINT], nelem)
3430 cap := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], v)
3431 s.boundsCheck(arrlen, cap, ssa.BoundsConvert, false)
3432 op := ssa.OpSlicePtr
3434 op = ssa.OpSlicePtrUnchecked
3436 return s.newValue1(op, n.Type(), v)
3439 n := n.(*ir.CallExpr)
3440 if ir.IsIntrinsicCall(n) {
3441 return s.intrinsicCall(n)
3446 n := n.(*ir.CallExpr)
3447 return s.callResult(n, callNormal)
3450 n := n.(*ir.CallExpr)
3451 return s.newValue1(ssa.OpGetG, n.Type(), s.mem())
3453 case ir.OGETCALLERPC:
3454 n := n.(*ir.CallExpr)
3455 return s.newValue0(ssa.OpGetCallerPC, n.Type())
3457 case ir.OGETCALLERSP:
3458 n := n.(*ir.CallExpr)
3459 return s.newValue1(ssa.OpGetCallerSP, n.Type(), s.mem())
3462 return s.append(n.(*ir.CallExpr), false)
3464 case ir.OMIN, ir.OMAX:
3465 return s.minMax(n.(*ir.CallExpr))
3467 case ir.OSTRUCTLIT, ir.OARRAYLIT:
3468 // All literals with nonzero fields have already been
3469 // rewritten during walk. Any that remain are just T{}
3470 // or equivalents. Use the zero value.
3471 n := n.(*ir.CompLitExpr)
3473 s.Fatalf("literal with nonzero value in SSA: %v", n)
3475 return s.zeroVal(n.Type())
3478 n := n.(*ir.UnaryExpr)
3479 var rtype *ssa.Value
3480 if x, ok := n.X.(*ir.DynamicType); ok && x.Op() == ir.ODYNAMICTYPE {
3481 rtype = s.expr(x.RType)
3483 return s.newObject(n.Type().Elem(), rtype)
3486 n := n.(*ir.BinaryExpr)
3490 // Force len to uintptr to prevent misuse of garbage bits in the
3491 // upper part of the register (#48536).
3492 len = s.conv(n, len, len.Type, types.Types[types.TUINTPTR])
3494 return s.newValue2(ssa.OpAddPtr, n.Type(), ptr, len)
3497 s.Fatalf("unhandled expr %v", n.Op())
3502 func (s *state) resultOfCall(c *ssa.Value, which int64, t *types.Type) *ssa.Value {
3503 aux := c.Aux.(*ssa.AuxCall)
3504 pa := aux.ParamAssignmentForResult(which)
3505 // TODO(register args) determine if in-memory TypeOK is better loaded early from SelectNAddr or later when SelectN is expanded.
3506 // SelectN is better for pattern-matching and possible call-aware analysis we might want to do in the future.
3507 if len(pa.Registers) == 0 && !ssa.CanSSA(t) {
3508 addr := s.newValue1I(ssa.OpSelectNAddr, types.NewPtr(t), which, c)
3509 return s.rawLoad(t, addr)
3511 return s.newValue1I(ssa.OpSelectN, t, which, c)
3514 func (s *state) resultAddrOfCall(c *ssa.Value, which int64, t *types.Type) *ssa.Value {
3515 aux := c.Aux.(*ssa.AuxCall)
3516 pa := aux.ParamAssignmentForResult(which)
3517 if len(pa.Registers) == 0 {
3518 return s.newValue1I(ssa.OpSelectNAddr, types.NewPtr(t), which, c)
3520 _, addr := s.temp(c.Pos, t)
3521 rval := s.newValue1I(ssa.OpSelectN, t, which, c)
3522 s.vars[memVar] = s.newValue3Apos(ssa.OpStore, types.TypeMem, t, addr, rval, s.mem(), false)
3526 // append converts an OAPPEND node to SSA.
3527 // If inplace is false, it converts the OAPPEND expression n to an ssa.Value,
3528 // adds it to s, and returns the Value.
3529 // If inplace is true, it writes the result of the OAPPEND expression n
3530 // back to the slice being appended to, and returns nil.
3531 // inplace MUST be set to false if the slice can be SSA'd.
3532 // Note: this code only handles fixed-count appends. Dotdotdot appends
3533 // have already been rewritten at this point (by walk).
3534 func (s *state) append(n *ir.CallExpr, inplace bool) *ssa.Value {
3535 // If inplace is false, process as expression "append(s, e1, e2, e3)":
3537 // ptr, len, cap := s
3539 // if uint(len) > uint(cap) {
3540 // ptr, len, cap = growslice(ptr, len, cap, 3, typ)
3541 // Note that len is unmodified by growslice.
3543 // // with write barriers, if needed:
3544 // *(ptr+(len-3)) = e1
3545 // *(ptr+(len-2)) = e2
3546 // *(ptr+(len-1)) = e3
3547 // return makeslice(ptr, len, cap)
3550 // If inplace is true, process as statement "s = append(s, e1, e2, e3)":
3553 // ptr, len, cap := s
3555 // if uint(len) > uint(cap) {
3556 // ptr, len, cap = growslice(ptr, len, cap, 3, typ)
3557 // vardef(a) // if necessary, advise liveness we are writing a new a
3558 // *a.cap = cap // write before ptr to avoid a spill
3559 // *a.ptr = ptr // with write barrier
3562 // // with write barriers, if needed:
3563 // *(ptr+(len-3)) = e1
3564 // *(ptr+(len-2)) = e2
3565 // *(ptr+(len-1)) = e3
3567 et := n.Type().Elem()
3568 pt := types.NewPtr(et)
3571 sn := n.Args[0] // the slice node is the first in the list
3572 var slice, addr *ssa.Value
3575 slice = s.load(n.Type(), addr)
3580 // Allocate new blocks
3581 grow := s.f.NewBlock(ssa.BlockPlain)
3582 assign := s.f.NewBlock(ssa.BlockPlain)
3584 // Decomposse input slice.
3585 p := s.newValue1(ssa.OpSlicePtr, pt, slice)
3586 l := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], slice)
3587 c := s.newValue1(ssa.OpSliceCap, types.Types[types.TINT], slice)
3589 // Add number of new elements to length.
3590 nargs := s.constInt(types.Types[types.TINT], int64(len(n.Args)-1))
3591 l = s.newValue2(s.ssaOp(ir.OADD, types.Types[types.TINT]), types.Types[types.TINT], l, nargs)
3593 // Decide if we need to grow
3594 cmp := s.newValue2(s.ssaOp(ir.OLT, types.Types[types.TUINT]), types.Types[types.TBOOL], c, l)
3596 // Record values of ptr/len/cap before branch.
3604 b.Kind = ssa.BlockIf
3605 b.Likely = ssa.BranchUnlikely
3612 taddr := s.expr(n.Fun)
3613 r := s.rtcall(ir.Syms.Growslice, true, []*types.Type{n.Type()}, p, l, c, nargs, taddr)
3615 // Decompose output slice
3616 p = s.newValue1(ssa.OpSlicePtr, pt, r[0])
3617 l = s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], r[0])
3618 c = s.newValue1(ssa.OpSliceCap, types.Types[types.TINT], r[0])
3624 if sn.Op() == ir.ONAME {
3626 if sn.Class != ir.PEXTERN {
3627 // Tell liveness we're about to build a new slice
3628 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, sn, s.mem())
3631 capaddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, types.SliceCapOffset, addr)
3632 s.store(types.Types[types.TINT], capaddr, c)
3633 s.store(pt, addr, p)
3639 // assign new elements to slots
3640 s.startBlock(assign)
3641 p = s.variable(ptrVar, pt) // generates phi for ptr
3642 l = s.variable(lenVar, types.Types[types.TINT]) // generates phi for len
3644 c = s.variable(capVar, types.Types[types.TINT]) // generates phi for cap
3648 // Update length in place.
3649 // We have to wait until here to make sure growslice succeeded.
3650 lenaddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, types.SliceLenOffset, addr)
3651 s.store(types.Types[types.TINT], lenaddr, l)
3655 type argRec struct {
3656 // if store is true, we're appending the value v. If false, we're appending the
3661 args := make([]argRec, 0, len(n.Args[1:]))
3662 for _, n := range n.Args[1:] {
3663 if ssa.CanSSA(n.Type()) {
3664 args = append(args, argRec{v: s.expr(n), store: true})
3667 args = append(args, argRec{v: v})
3671 // Write args into slice.
3672 oldLen := s.newValue2(s.ssaOp(ir.OSUB, types.Types[types.TINT]), types.Types[types.TINT], l, nargs)
3673 p2 := s.newValue2(ssa.OpPtrIndex, pt, p, oldLen)
3674 for i, arg := range args {
3675 addr := s.newValue2(ssa.OpPtrIndex, pt, p2, s.constInt(types.Types[types.TINT], int64(i)))
3677 s.storeType(et, addr, arg.v, 0, true)
3679 s.move(et, addr, arg.v)
3683 // The following deletions have no practical effect at this time
3684 // because state.vars has been reset by the preceding state.startBlock.
3685 // They only enforce the fact that these variables are no longer need in
3686 // the current scope.
3687 delete(s.vars, ptrVar)
3688 delete(s.vars, lenVar)
3690 delete(s.vars, capVar)
3697 return s.newValue3(ssa.OpSliceMake, n.Type(), p, l, c)
3700 // minMax converts an OMIN/OMAX builtin call into SSA.
3701 func (s *state) minMax(n *ir.CallExpr) *ssa.Value {
3702 // The OMIN/OMAX builtin is variadic, but its semantics are
3703 // equivalent to left-folding a binary min/max operation across the
3705 fold := func(op func(x, a *ssa.Value) *ssa.Value) *ssa.Value {
3706 x := s.expr(n.Args[0])
3707 for _, arg := range n.Args[1:] {
3708 x = op(x, s.expr(arg))
3715 if typ.IsFloat() || typ.IsString() {
3716 // min/max semantics for floats are tricky because of NaNs and
3717 // negative zero. Some architectures have instructions which
3718 // we can use to generate the right result. For others we must
3719 // call into the runtime instead.
3721 // Strings are conceptually simpler, but we currently desugar
3722 // string comparisons during walk, not ssagen.
3725 switch Arch.LinkArch.Family {
3726 case sys.AMD64, sys.ARM64:
3729 case typ.Kind() == types.TFLOAT64 && n.Op() == ir.OMIN:
3731 case typ.Kind() == types.TFLOAT64 && n.Op() == ir.OMAX:
3733 case typ.Kind() == types.TFLOAT32 && n.Op() == ir.OMIN:
3735 case typ.Kind() == types.TFLOAT32 && n.Op() == ir.OMAX:
3738 return fold(func(x, a *ssa.Value) *ssa.Value {
3739 return s.newValue2(op, typ, x, a)
3745 case types.TFLOAT32:
3752 case types.TFLOAT64:
3767 fn := typecheck.LookupRuntimeFunc(name)
3769 return fold(func(x, a *ssa.Value) *ssa.Value {
3770 return s.rtcall(fn, true, []*types.Type{typ}, x, a)[0]
3774 lt := s.ssaOp(ir.OLT, typ)
3776 return fold(func(x, a *ssa.Value) *ssa.Value {
3780 return s.ternary(s.newValue2(lt, types.Types[types.TBOOL], a, x), a, x)
3783 return s.ternary(s.newValue2(lt, types.Types[types.TBOOL], x, a), a, x)
3785 panic("unreachable")
3789 // ternary emits code to evaluate cond ? x : y.
3790 func (s *state) ternary(cond, x, y *ssa.Value) *ssa.Value {
3791 // Note that we need a new ternaryVar each time (unlike okVar where we can
3792 // reuse the variable) because it might have a different type every time.
3793 ternaryVar := ssaMarker("ternary")
3795 bThen := s.f.NewBlock(ssa.BlockPlain)
3796 bElse := s.f.NewBlock(ssa.BlockPlain)
3797 bEnd := s.f.NewBlock(ssa.BlockPlain)
3800 b.Kind = ssa.BlockIf
3806 s.vars[ternaryVar] = x
3807 s.endBlock().AddEdgeTo(bEnd)
3810 s.vars[ternaryVar] = y
3811 s.endBlock().AddEdgeTo(bEnd)
3814 r := s.variable(ternaryVar, x.Type)
3815 delete(s.vars, ternaryVar)
3819 // condBranch evaluates the boolean expression cond and branches to yes
3820 // if cond is true and no if cond is false.
3821 // This function is intended to handle && and || better than just calling
3822 // s.expr(cond) and branching on the result.
3823 func (s *state) condBranch(cond ir.Node, yes, no *ssa.Block, likely int8) {
3826 cond := cond.(*ir.LogicalExpr)
3827 mid := s.f.NewBlock(ssa.BlockPlain)
3828 s.stmtList(cond.Init())
3829 s.condBranch(cond.X, mid, no, max8(likely, 0))
3831 s.condBranch(cond.Y, yes, no, likely)
3833 // Note: if likely==1, then both recursive calls pass 1.
3834 // If likely==-1, then we don't have enough information to decide
3835 // whether the first branch is likely or not. So we pass 0 for
3836 // the likeliness of the first branch.
3837 // TODO: have the frontend give us branch prediction hints for
3838 // OANDAND and OOROR nodes (if it ever has such info).
3840 cond := cond.(*ir.LogicalExpr)
3841 mid := s.f.NewBlock(ssa.BlockPlain)
3842 s.stmtList(cond.Init())
3843 s.condBranch(cond.X, yes, mid, min8(likely, 0))
3845 s.condBranch(cond.Y, yes, no, likely)
3847 // Note: if likely==-1, then both recursive calls pass -1.
3848 // If likely==1, then we don't have enough info to decide
3849 // the likelihood of the first branch.
3851 cond := cond.(*ir.UnaryExpr)
3852 s.stmtList(cond.Init())
3853 s.condBranch(cond.X, no, yes, -likely)
3856 cond := cond.(*ir.ConvExpr)
3857 s.stmtList(cond.Init())
3858 s.condBranch(cond.X, yes, no, likely)
3863 b.Kind = ssa.BlockIf
3865 b.Likely = ssa.BranchPrediction(likely) // gc and ssa both use -1/0/+1 for likeliness
3873 skipPtr skipMask = 1 << iota
3878 // assign does left = right.
3879 // Right has already been evaluated to ssa, left has not.
3880 // If deref is true, then we do left = *right instead (and right has already been nil-checked).
3881 // If deref is true and right == nil, just do left = 0.
3882 // skip indicates assignments (at the top level) that can be avoided.
3883 // mayOverlap indicates whether left&right might partially overlap in memory. Default is false.
3884 func (s *state) assign(left ir.Node, right *ssa.Value, deref bool, skip skipMask) {
3885 s.assignWhichMayOverlap(left, right, deref, skip, false)
3887 func (s *state) assignWhichMayOverlap(left ir.Node, right *ssa.Value, deref bool, skip skipMask, mayOverlap bool) {
3888 if left.Op() == ir.ONAME && ir.IsBlank(left) {
3895 s.Fatalf("can SSA LHS %v but not RHS %s", left, right)
3897 if left.Op() == ir.ODOT {
3898 // We're assigning to a field of an ssa-able value.
3899 // We need to build a new structure with the new value for the
3900 // field we're assigning and the old values for the other fields.
3902 // type T struct {a, b, c int}
3905 // For the x.b = 5 assignment we want to generate x = T{x.a, 5, x.c}
3907 // Grab information about the structure type.
3908 left := left.(*ir.SelectorExpr)
3911 idx := fieldIdx(left)
3913 // Grab old value of structure.
3914 old := s.expr(left.X)
3916 // Make new structure.
3917 new := s.newValue0(ssa.StructMakeOp(t.NumFields()), t)
3919 // Add fields as args.
3920 for i := 0; i < nf; i++ {
3924 new.AddArg(s.newValue1I(ssa.OpStructSelect, t.FieldType(i), int64(i), old))
3928 // Recursively assign the new value we've made to the base of the dot op.
3929 s.assign(left.X, new, false, 0)
3930 // TODO: do we need to update named values here?
3933 if left.Op() == ir.OINDEX && left.(*ir.IndexExpr).X.Type().IsArray() {
3934 left := left.(*ir.IndexExpr)
3935 s.pushLine(left.Pos())
3937 // We're assigning to an element of an ssa-able array.
3942 i := s.expr(left.Index) // index
3944 // The bounds check must fail. Might as well
3945 // ignore the actual index and just use zeros.
3946 z := s.constInt(types.Types[types.TINT], 0)
3947 s.boundsCheck(z, z, ssa.BoundsIndex, false)
3951 s.Fatalf("assigning to non-1-length array")
3953 // Rewrite to a = [1]{v}
3954 len := s.constInt(types.Types[types.TINT], 1)
3955 s.boundsCheck(i, len, ssa.BoundsIndex, false) // checks i == 0
3956 v := s.newValue1(ssa.OpArrayMake1, t, right)
3957 s.assign(left.X, v, false, 0)
3960 left := left.(*ir.Name)
3961 // Update variable assignment.
3962 s.vars[left] = right
3963 s.addNamedValue(left, right)
3967 // If this assignment clobbers an entire local variable, then emit
3968 // OpVarDef so liveness analysis knows the variable is redefined.
3969 if base, ok := clobberBase(left).(*ir.Name); ok && base.OnStack() && skip == 0 && t.HasPointers() {
3970 s.vars[memVar] = s.newValue1Apos(ssa.OpVarDef, types.TypeMem, base, s.mem(), !ir.IsAutoTmp(base))
3973 // Left is not ssa-able. Compute its address.
3974 addr := s.addr(left)
3975 if ir.IsReflectHeaderDataField(left) {
3976 // Package unsafe's documentation says storing pointers into
3977 // reflect.SliceHeader and reflect.StringHeader's Data fields
3978 // is valid, even though they have type uintptr (#19168).
3979 // Mark it pointer type to signal the writebarrier pass to
3980 // insert a write barrier.
3981 t = types.Types[types.TUNSAFEPTR]
3984 // Treat as a mem->mem move.
3988 s.moveWhichMayOverlap(t, addr, right, mayOverlap)
3992 // Treat as a store.
3993 s.storeType(t, addr, right, skip, !ir.IsAutoTmp(left))
3996 // zeroVal returns the zero value for type t.
3997 func (s *state) zeroVal(t *types.Type) *ssa.Value {
4002 return s.constInt8(t, 0)
4004 return s.constInt16(t, 0)
4006 return s.constInt32(t, 0)
4008 return s.constInt64(t, 0)
4010 s.Fatalf("bad sized integer type %v", t)
4015 return s.constFloat32(t, 0)
4017 return s.constFloat64(t, 0)
4019 s.Fatalf("bad sized float type %v", t)
4024 z := s.constFloat32(types.Types[types.TFLOAT32], 0)
4025 return s.entryNewValue2(ssa.OpComplexMake, t, z, z)
4027 z := s.constFloat64(types.Types[types.TFLOAT64], 0)
4028 return s.entryNewValue2(ssa.OpComplexMake, t, z, z)
4030 s.Fatalf("bad sized complex type %v", t)
4034 return s.constEmptyString(t)
4035 case t.IsPtrShaped():
4036 return s.constNil(t)
4038 return s.constBool(false)
4039 case t.IsInterface():
4040 return s.constInterface(t)
4042 return s.constSlice(t)
4045 v := s.entryNewValue0(ssa.StructMakeOp(t.NumFields()), t)
4046 for i := 0; i < n; i++ {
4047 v.AddArg(s.zeroVal(t.FieldType(i)))
4051 switch t.NumElem() {
4053 return s.entryNewValue0(ssa.OpArrayMake0, t)
4055 return s.entryNewValue1(ssa.OpArrayMake1, t, s.zeroVal(t.Elem()))
4058 s.Fatalf("zero for type %v not implemented", t)
4065 callNormal callKind = iota
4072 type sfRtCallDef struct {
4077 var softFloatOps map[ssa.Op]sfRtCallDef
4079 func softfloatInit() {
4080 // Some of these operations get transformed by sfcall.
4081 softFloatOps = map[ssa.Op]sfRtCallDef{
4082 ssa.OpAdd32F: {typecheck.LookupRuntimeFunc("fadd32"), types.TFLOAT32},
4083 ssa.OpAdd64F: {typecheck.LookupRuntimeFunc("fadd64"), types.TFLOAT64},
4084 ssa.OpSub32F: {typecheck.LookupRuntimeFunc("fadd32"), types.TFLOAT32},
4085 ssa.OpSub64F: {typecheck.LookupRuntimeFunc("fadd64"), types.TFLOAT64},
4086 ssa.OpMul32F: {typecheck.LookupRuntimeFunc("fmul32"), types.TFLOAT32},
4087 ssa.OpMul64F: {typecheck.LookupRuntimeFunc("fmul64"), types.TFLOAT64},
4088 ssa.OpDiv32F: {typecheck.LookupRuntimeFunc("fdiv32"), types.TFLOAT32},
4089 ssa.OpDiv64F: {typecheck.LookupRuntimeFunc("fdiv64"), types.TFLOAT64},
4091 ssa.OpEq64F: {typecheck.LookupRuntimeFunc("feq64"), types.TBOOL},
4092 ssa.OpEq32F: {typecheck.LookupRuntimeFunc("feq32"), types.TBOOL},
4093 ssa.OpNeq64F: {typecheck.LookupRuntimeFunc("feq64"), types.TBOOL},
4094 ssa.OpNeq32F: {typecheck.LookupRuntimeFunc("feq32"), types.TBOOL},
4095 ssa.OpLess64F: {typecheck.LookupRuntimeFunc("fgt64"), types.TBOOL},
4096 ssa.OpLess32F: {typecheck.LookupRuntimeFunc("fgt32"), types.TBOOL},
4097 ssa.OpLeq64F: {typecheck.LookupRuntimeFunc("fge64"), types.TBOOL},
4098 ssa.OpLeq32F: {typecheck.LookupRuntimeFunc("fge32"), types.TBOOL},
4100 ssa.OpCvt32to32F: {typecheck.LookupRuntimeFunc("fint32to32"), types.TFLOAT32},
4101 ssa.OpCvt32Fto32: {typecheck.LookupRuntimeFunc("f32toint32"), types.TINT32},
4102 ssa.OpCvt64to32F: {typecheck.LookupRuntimeFunc("fint64to32"), types.TFLOAT32},
4103 ssa.OpCvt32Fto64: {typecheck.LookupRuntimeFunc("f32toint64"), types.TINT64},
4104 ssa.OpCvt64Uto32F: {typecheck.LookupRuntimeFunc("fuint64to32"), types.TFLOAT32},
4105 ssa.OpCvt32Fto64U: {typecheck.LookupRuntimeFunc("f32touint64"), types.TUINT64},
4106 ssa.OpCvt32to64F: {typecheck.LookupRuntimeFunc("fint32to64"), types.TFLOAT64},
4107 ssa.OpCvt64Fto32: {typecheck.LookupRuntimeFunc("f64toint32"), types.TINT32},
4108 ssa.OpCvt64to64F: {typecheck.LookupRuntimeFunc("fint64to64"), types.TFLOAT64},
4109 ssa.OpCvt64Fto64: {typecheck.LookupRuntimeFunc("f64toint64"), types.TINT64},
4110 ssa.OpCvt64Uto64F: {typecheck.LookupRuntimeFunc("fuint64to64"), types.TFLOAT64},
4111 ssa.OpCvt64Fto64U: {typecheck.LookupRuntimeFunc("f64touint64"), types.TUINT64},
4112 ssa.OpCvt32Fto64F: {typecheck.LookupRuntimeFunc("f32to64"), types.TFLOAT64},
4113 ssa.OpCvt64Fto32F: {typecheck.LookupRuntimeFunc("f64to32"), types.TFLOAT32},
4117 // TODO: do not emit sfcall if operation can be optimized to constant in later
4119 func (s *state) sfcall(op ssa.Op, args ...*ssa.Value) (*ssa.Value, bool) {
4120 f2i := func(t *types.Type) *types.Type {
4122 case types.TFLOAT32:
4123 return types.Types[types.TUINT32]
4124 case types.TFLOAT64:
4125 return types.Types[types.TUINT64]
4130 if callDef, ok := softFloatOps[op]; ok {
4136 args[0], args[1] = args[1], args[0]
4139 args[1] = s.newValue1(s.ssaOp(ir.ONEG, types.Types[callDef.rtype]), args[1].Type, args[1])
4142 // runtime functions take uints for floats and returns uints.
4143 // Convert to uints so we use the right calling convention.
4144 for i, a := range args {
4145 if a.Type.IsFloat() {
4146 args[i] = s.newValue1(ssa.OpCopy, f2i(a.Type), a)
4150 rt := types.Types[callDef.rtype]
4151 result := s.rtcall(callDef.rtfn, true, []*types.Type{f2i(rt)}, args...)[0]
4153 result = s.newValue1(ssa.OpCopy, rt, result)
4155 if op == ssa.OpNeq32F || op == ssa.OpNeq64F {
4156 result = s.newValue1(ssa.OpNot, result.Type, result)
4163 var intrinsics map[intrinsicKey]intrinsicBuilder
4165 // An intrinsicBuilder converts a call node n into an ssa value that
4166 // implements that call as an intrinsic. args is a list of arguments to the func.
4167 type intrinsicBuilder func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value
4169 type intrinsicKey struct {
4176 intrinsics = map[intrinsicKey]intrinsicBuilder{}
4181 var lwatomics []*sys.Arch
4182 for _, a := range &sys.Archs {
4183 all = append(all, a)
4189 if a.Family != sys.PPC64 {
4190 lwatomics = append(lwatomics, a)
4194 // add adds the intrinsic b for pkg.fn for the given list of architectures.
4195 add := func(pkg, fn string, b intrinsicBuilder, archs ...*sys.Arch) {
4196 for _, a := range archs {
4197 intrinsics[intrinsicKey{a, pkg, fn}] = b
4200 // addF does the same as add but operates on architecture families.
4201 addF := func(pkg, fn string, b intrinsicBuilder, archFamilies ...sys.ArchFamily) {
4203 for _, f := range archFamilies {
4205 panic("too many architecture families")
4209 for _, a := range all {
4210 if m>>uint(a.Family)&1 != 0 {
4211 intrinsics[intrinsicKey{a, pkg, fn}] = b
4215 // alias defines pkg.fn = pkg2.fn2 for all architectures in archs for which pkg2.fn2 exists.
4216 alias := func(pkg, fn, pkg2, fn2 string, archs ...*sys.Arch) {
4218 for _, a := range archs {
4219 if b, ok := intrinsics[intrinsicKey{a, pkg2, fn2}]; ok {
4220 intrinsics[intrinsicKey{a, pkg, fn}] = b
4225 panic(fmt.Sprintf("attempted to alias undefined intrinsic: %s.%s", pkg, fn))
4229 /******** runtime ********/
4230 if !base.Flag.Cfg.Instrumenting {
4231 add("runtime", "slicebytetostringtmp",
4232 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4233 // Compiler frontend optimizations emit OBYTES2STRTMP nodes
4234 // for the backend instead of slicebytetostringtmp calls
4235 // when not instrumenting.
4236 return s.newValue2(ssa.OpStringMake, n.Type(), args[0], args[1])
4240 addF("runtime/internal/math", "MulUintptr",
4241 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4242 if s.config.PtrSize == 4 {
4243 return s.newValue2(ssa.OpMul32uover, types.NewTuple(types.Types[types.TUINT], types.Types[types.TUINT]), args[0], args[1])
4245 return s.newValue2(ssa.OpMul64uover, types.NewTuple(types.Types[types.TUINT], types.Types[types.TUINT]), args[0], args[1])
4247 sys.AMD64, sys.I386, sys.Loong64, sys.MIPS64, sys.RISCV64, sys.ARM64)
4248 add("runtime", "KeepAlive",
4249 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4250 data := s.newValue1(ssa.OpIData, s.f.Config.Types.BytePtr, args[0])
4251 s.vars[memVar] = s.newValue2(ssa.OpKeepAlive, types.TypeMem, data, s.mem())
4255 add("runtime", "getclosureptr",
4256 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4257 return s.newValue0(ssa.OpGetClosurePtr, s.f.Config.Types.Uintptr)
4261 add("runtime", "getcallerpc",
4262 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4263 return s.newValue0(ssa.OpGetCallerPC, s.f.Config.Types.Uintptr)
4267 add("runtime", "getcallersp",
4268 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4269 return s.newValue1(ssa.OpGetCallerSP, s.f.Config.Types.Uintptr, s.mem())
4273 addF("runtime", "publicationBarrier",
4274 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4275 s.vars[memVar] = s.newValue1(ssa.OpPubBarrier, types.TypeMem, s.mem())
4278 sys.ARM64, sys.PPC64, sys.RISCV64)
4280 brev_arch := []sys.ArchFamily{sys.AMD64, sys.I386, sys.ARM64, sys.ARM, sys.S390X}
4281 if buildcfg.GOPPC64 >= 10 {
4282 // Use only on Power10 as the new byte reverse instructions that Power10 provide
4283 // make it worthwhile as an intrinsic
4284 brev_arch = append(brev_arch, sys.PPC64)
4286 /******** runtime/internal/sys ********/
4287 addF("runtime/internal/sys", "Bswap32",
4288 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4289 return s.newValue1(ssa.OpBswap32, types.Types[types.TUINT32], args[0])
4292 addF("runtime/internal/sys", "Bswap64",
4293 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4294 return s.newValue1(ssa.OpBswap64, types.Types[types.TUINT64], args[0])
4298 /****** Prefetch ******/
4299 makePrefetchFunc := func(op ssa.Op) func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4300 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4301 s.vars[memVar] = s.newValue2(op, types.TypeMem, args[0], s.mem())
4306 // Make Prefetch intrinsics for supported platforms
4307 // On the unsupported platforms stub function will be eliminated
4308 addF("runtime/internal/sys", "Prefetch", makePrefetchFunc(ssa.OpPrefetchCache),
4309 sys.AMD64, sys.ARM64, sys.PPC64)
4310 addF("runtime/internal/sys", "PrefetchStreamed", makePrefetchFunc(ssa.OpPrefetchCacheStreamed),
4311 sys.AMD64, sys.ARM64, sys.PPC64)
4313 /******** runtime/internal/atomic ********/
4314 addF("runtime/internal/atomic", "Load",
4315 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4316 v := s.newValue2(ssa.OpAtomicLoad32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], s.mem())
4317 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4318 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4320 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4321 addF("runtime/internal/atomic", "Load8",
4322 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4323 v := s.newValue2(ssa.OpAtomicLoad8, types.NewTuple(types.Types[types.TUINT8], types.TypeMem), args[0], s.mem())
4324 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4325 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT8], v)
4327 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4328 addF("runtime/internal/atomic", "Load64",
4329 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4330 v := s.newValue2(ssa.OpAtomicLoad64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], s.mem())
4331 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4332 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4334 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4335 addF("runtime/internal/atomic", "LoadAcq",
4336 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4337 v := s.newValue2(ssa.OpAtomicLoadAcq32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], s.mem())
4338 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4339 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4341 sys.PPC64, sys.S390X)
4342 addF("runtime/internal/atomic", "LoadAcq64",
4343 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4344 v := s.newValue2(ssa.OpAtomicLoadAcq64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], s.mem())
4345 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4346 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4349 addF("runtime/internal/atomic", "Loadp",
4350 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4351 v := s.newValue2(ssa.OpAtomicLoadPtr, types.NewTuple(s.f.Config.Types.BytePtr, types.TypeMem), args[0], s.mem())
4352 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4353 return s.newValue1(ssa.OpSelect0, s.f.Config.Types.BytePtr, v)
4355 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4357 addF("runtime/internal/atomic", "Store",
4358 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4359 s.vars[memVar] = s.newValue3(ssa.OpAtomicStore32, types.TypeMem, args[0], args[1], s.mem())
4362 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4363 addF("runtime/internal/atomic", "Store8",
4364 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4365 s.vars[memVar] = s.newValue3(ssa.OpAtomicStore8, types.TypeMem, args[0], args[1], s.mem())
4368 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4369 addF("runtime/internal/atomic", "Store64",
4370 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4371 s.vars[memVar] = s.newValue3(ssa.OpAtomicStore64, types.TypeMem, args[0], args[1], s.mem())
4374 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4375 addF("runtime/internal/atomic", "StorepNoWB",
4376 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4377 s.vars[memVar] = s.newValue3(ssa.OpAtomicStorePtrNoWB, types.TypeMem, args[0], args[1], s.mem())
4380 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.RISCV64, sys.S390X)
4381 addF("runtime/internal/atomic", "StoreRel",
4382 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4383 s.vars[memVar] = s.newValue3(ssa.OpAtomicStoreRel32, types.TypeMem, args[0], args[1], s.mem())
4386 sys.PPC64, sys.S390X)
4387 addF("runtime/internal/atomic", "StoreRel64",
4388 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4389 s.vars[memVar] = s.newValue3(ssa.OpAtomicStoreRel64, types.TypeMem, args[0], args[1], s.mem())
4394 addF("runtime/internal/atomic", "Xchg",
4395 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4396 v := s.newValue3(ssa.OpAtomicExchange32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], args[1], s.mem())
4397 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4398 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4400 sys.AMD64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4401 addF("runtime/internal/atomic", "Xchg64",
4402 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4403 v := s.newValue3(ssa.OpAtomicExchange64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], args[1], s.mem())
4404 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4405 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4407 sys.AMD64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4409 type atomicOpEmitter func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind)
4411 makeAtomicGuardedIntrinsicARM64 := func(op0, op1 ssa.Op, typ, rtyp types.Kind, emit atomicOpEmitter) intrinsicBuilder {
4413 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4414 // Target Atomic feature is identified by dynamic detection
4415 addr := s.entryNewValue1A(ssa.OpAddr, types.Types[types.TBOOL].PtrTo(), ir.Syms.ARM64HasATOMICS, s.sb)
4416 v := s.load(types.Types[types.TBOOL], addr)
4418 b.Kind = ssa.BlockIf
4420 bTrue := s.f.NewBlock(ssa.BlockPlain)
4421 bFalse := s.f.NewBlock(ssa.BlockPlain)
4422 bEnd := s.f.NewBlock(ssa.BlockPlain)
4425 b.Likely = ssa.BranchLikely
4427 // We have atomic instructions - use it directly.
4429 emit(s, n, args, op1, typ)
4430 s.endBlock().AddEdgeTo(bEnd)
4432 // Use original instruction sequence.
4433 s.startBlock(bFalse)
4434 emit(s, n, args, op0, typ)
4435 s.endBlock().AddEdgeTo(bEnd)
4439 if rtyp == types.TNIL {
4442 return s.variable(n, types.Types[rtyp])
4447 atomicXchgXaddEmitterARM64 := func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind) {
4448 v := s.newValue3(op, types.NewTuple(types.Types[typ], types.TypeMem), args[0], args[1], s.mem())
4449 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4450 s.vars[n] = s.newValue1(ssa.OpSelect0, types.Types[typ], v)
4452 addF("runtime/internal/atomic", "Xchg",
4453 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicExchange32, ssa.OpAtomicExchange32Variant, types.TUINT32, types.TUINT32, atomicXchgXaddEmitterARM64),
4455 addF("runtime/internal/atomic", "Xchg64",
4456 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicExchange64, ssa.OpAtomicExchange64Variant, types.TUINT64, types.TUINT64, atomicXchgXaddEmitterARM64),
4459 addF("runtime/internal/atomic", "Xadd",
4460 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4461 v := s.newValue3(ssa.OpAtomicAdd32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], args[1], s.mem())
4462 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4463 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4465 sys.AMD64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4466 addF("runtime/internal/atomic", "Xadd64",
4467 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4468 v := s.newValue3(ssa.OpAtomicAdd64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], args[1], s.mem())
4469 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4470 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4472 sys.AMD64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4474 addF("runtime/internal/atomic", "Xadd",
4475 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAdd32, ssa.OpAtomicAdd32Variant, types.TUINT32, types.TUINT32, atomicXchgXaddEmitterARM64),
4477 addF("runtime/internal/atomic", "Xadd64",
4478 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAdd64, ssa.OpAtomicAdd64Variant, types.TUINT64, types.TUINT64, atomicXchgXaddEmitterARM64),
4481 addF("runtime/internal/atomic", "Cas",
4482 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4483 v := s.newValue4(ssa.OpAtomicCompareAndSwap32, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4484 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4485 return s.newValue1(ssa.OpSelect0, types.Types[types.TBOOL], v)
4487 sys.AMD64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4488 addF("runtime/internal/atomic", "Cas64",
4489 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4490 v := s.newValue4(ssa.OpAtomicCompareAndSwap64, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4491 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4492 return s.newValue1(ssa.OpSelect0, types.Types[types.TBOOL], v)
4494 sys.AMD64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4495 addF("runtime/internal/atomic", "CasRel",
4496 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4497 v := s.newValue4(ssa.OpAtomicCompareAndSwap32, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4498 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4499 return s.newValue1(ssa.OpSelect0, types.Types[types.TBOOL], v)
4503 atomicCasEmitterARM64 := func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind) {
4504 v := s.newValue4(op, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4505 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4506 s.vars[n] = s.newValue1(ssa.OpSelect0, types.Types[typ], v)
4509 addF("runtime/internal/atomic", "Cas",
4510 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicCompareAndSwap32, ssa.OpAtomicCompareAndSwap32Variant, types.TUINT32, types.TBOOL, atomicCasEmitterARM64),
4512 addF("runtime/internal/atomic", "Cas64",
4513 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicCompareAndSwap64, ssa.OpAtomicCompareAndSwap64Variant, types.TUINT64, types.TBOOL, atomicCasEmitterARM64),
4516 addF("runtime/internal/atomic", "And8",
4517 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4518 s.vars[memVar] = s.newValue3(ssa.OpAtomicAnd8, types.TypeMem, args[0], args[1], s.mem())
4521 sys.AMD64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4522 addF("runtime/internal/atomic", "And",
4523 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4524 s.vars[memVar] = s.newValue3(ssa.OpAtomicAnd32, types.TypeMem, args[0], args[1], s.mem())
4527 sys.AMD64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4528 addF("runtime/internal/atomic", "Or8",
4529 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4530 s.vars[memVar] = s.newValue3(ssa.OpAtomicOr8, types.TypeMem, args[0], args[1], s.mem())
4533 sys.AMD64, sys.ARM64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4534 addF("runtime/internal/atomic", "Or",
4535 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4536 s.vars[memVar] = s.newValue3(ssa.OpAtomicOr32, types.TypeMem, args[0], args[1], s.mem())
4539 sys.AMD64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4541 atomicAndOrEmitterARM64 := func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind) {
4542 s.vars[memVar] = s.newValue3(op, types.TypeMem, args[0], args[1], s.mem())
4545 addF("runtime/internal/atomic", "And8",
4546 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAnd8, ssa.OpAtomicAnd8Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4548 addF("runtime/internal/atomic", "And",
4549 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAnd32, ssa.OpAtomicAnd32Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4551 addF("runtime/internal/atomic", "Or8",
4552 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicOr8, ssa.OpAtomicOr8Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4554 addF("runtime/internal/atomic", "Or",
4555 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicOr32, ssa.OpAtomicOr32Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4558 // Aliases for atomic load operations
4559 alias("runtime/internal/atomic", "Loadint32", "runtime/internal/atomic", "Load", all...)
4560 alias("runtime/internal/atomic", "Loadint64", "runtime/internal/atomic", "Load64", all...)
4561 alias("runtime/internal/atomic", "Loaduintptr", "runtime/internal/atomic", "Load", p4...)
4562 alias("runtime/internal/atomic", "Loaduintptr", "runtime/internal/atomic", "Load64", p8...)
4563 alias("runtime/internal/atomic", "Loaduint", "runtime/internal/atomic", "Load", p4...)
4564 alias("runtime/internal/atomic", "Loaduint", "runtime/internal/atomic", "Load64", p8...)
4565 alias("runtime/internal/atomic", "LoadAcq", "runtime/internal/atomic", "Load", lwatomics...)
4566 alias("runtime/internal/atomic", "LoadAcq64", "runtime/internal/atomic", "Load64", lwatomics...)
4567 alias("runtime/internal/atomic", "LoadAcquintptr", "runtime/internal/atomic", "LoadAcq", p4...)
4568 alias("sync", "runtime_LoadAcquintptr", "runtime/internal/atomic", "LoadAcq", p4...) // linknamed
4569 alias("runtime/internal/atomic", "LoadAcquintptr", "runtime/internal/atomic", "LoadAcq64", p8...)
4570 alias("sync", "runtime_LoadAcquintptr", "runtime/internal/atomic", "LoadAcq64", p8...) // linknamed
4572 // Aliases for atomic store operations
4573 alias("runtime/internal/atomic", "Storeint32", "runtime/internal/atomic", "Store", all...)
4574 alias("runtime/internal/atomic", "Storeint64", "runtime/internal/atomic", "Store64", all...)
4575 alias("runtime/internal/atomic", "Storeuintptr", "runtime/internal/atomic", "Store", p4...)
4576 alias("runtime/internal/atomic", "Storeuintptr", "runtime/internal/atomic", "Store64", p8...)
4577 alias("runtime/internal/atomic", "StoreRel", "runtime/internal/atomic", "Store", lwatomics...)
4578 alias("runtime/internal/atomic", "StoreRel64", "runtime/internal/atomic", "Store64", lwatomics...)
4579 alias("runtime/internal/atomic", "StoreReluintptr", "runtime/internal/atomic", "StoreRel", p4...)
4580 alias("sync", "runtime_StoreReluintptr", "runtime/internal/atomic", "StoreRel", p4...) // linknamed
4581 alias("runtime/internal/atomic", "StoreReluintptr", "runtime/internal/atomic", "StoreRel64", p8...)
4582 alias("sync", "runtime_StoreReluintptr", "runtime/internal/atomic", "StoreRel64", p8...) // linknamed
4584 // Aliases for atomic swap operations
4585 alias("runtime/internal/atomic", "Xchgint32", "runtime/internal/atomic", "Xchg", all...)
4586 alias("runtime/internal/atomic", "Xchgint64", "runtime/internal/atomic", "Xchg64", all...)
4587 alias("runtime/internal/atomic", "Xchguintptr", "runtime/internal/atomic", "Xchg", p4...)
4588 alias("runtime/internal/atomic", "Xchguintptr", "runtime/internal/atomic", "Xchg64", p8...)
4590 // Aliases for atomic add operations
4591 alias("runtime/internal/atomic", "Xaddint32", "runtime/internal/atomic", "Xadd", all...)
4592 alias("runtime/internal/atomic", "Xaddint64", "runtime/internal/atomic", "Xadd64", all...)
4593 alias("runtime/internal/atomic", "Xadduintptr", "runtime/internal/atomic", "Xadd", p4...)
4594 alias("runtime/internal/atomic", "Xadduintptr", "runtime/internal/atomic", "Xadd64", p8...)
4596 // Aliases for atomic CAS operations
4597 alias("runtime/internal/atomic", "Casint32", "runtime/internal/atomic", "Cas", all...)
4598 alias("runtime/internal/atomic", "Casint64", "runtime/internal/atomic", "Cas64", all...)
4599 alias("runtime/internal/atomic", "Casuintptr", "runtime/internal/atomic", "Cas", p4...)
4600 alias("runtime/internal/atomic", "Casuintptr", "runtime/internal/atomic", "Cas64", p8...)
4601 alias("runtime/internal/atomic", "Casp1", "runtime/internal/atomic", "Cas", p4...)
4602 alias("runtime/internal/atomic", "Casp1", "runtime/internal/atomic", "Cas64", p8...)
4603 alias("runtime/internal/atomic", "CasRel", "runtime/internal/atomic", "Cas", lwatomics...)
4605 /******** math ********/
4606 addF("math", "sqrt",
4607 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4608 return s.newValue1(ssa.OpSqrt, types.Types[types.TFLOAT64], args[0])
4610 sys.I386, sys.AMD64, sys.ARM, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X, sys.Wasm)
4611 addF("math", "Trunc",
4612 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4613 return s.newValue1(ssa.OpTrunc, types.Types[types.TFLOAT64], args[0])
4615 sys.ARM64, sys.PPC64, sys.S390X, sys.Wasm)
4616 addF("math", "Ceil",
4617 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4618 return s.newValue1(ssa.OpCeil, types.Types[types.TFLOAT64], args[0])
4620 sys.ARM64, sys.PPC64, sys.S390X, sys.Wasm)
4621 addF("math", "Floor",
4622 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4623 return s.newValue1(ssa.OpFloor, types.Types[types.TFLOAT64], args[0])
4625 sys.ARM64, sys.PPC64, sys.S390X, sys.Wasm)
4626 addF("math", "Round",
4627 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4628 return s.newValue1(ssa.OpRound, types.Types[types.TFLOAT64], args[0])
4630 sys.ARM64, sys.PPC64, sys.S390X)
4631 addF("math", "RoundToEven",
4632 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4633 return s.newValue1(ssa.OpRoundToEven, types.Types[types.TFLOAT64], args[0])
4635 sys.ARM64, sys.S390X, sys.Wasm)
4637 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4638 return s.newValue1(ssa.OpAbs, types.Types[types.TFLOAT64], args[0])
4640 sys.ARM64, sys.ARM, sys.PPC64, sys.RISCV64, sys.Wasm, sys.MIPS, sys.MIPS64)
4641 addF("math", "Copysign",
4642 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4643 return s.newValue2(ssa.OpCopysign, types.Types[types.TFLOAT64], args[0], args[1])
4645 sys.PPC64, sys.RISCV64, sys.Wasm)
4647 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4648 return s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4650 sys.ARM64, sys.PPC64, sys.RISCV64, sys.S390X)
4652 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4653 if !s.config.UseFMA {
4654 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4655 return s.variable(n, types.Types[types.TFLOAT64])
4658 if buildcfg.GOAMD64 >= 3 {
4659 return s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4662 v := s.entryNewValue0A(ssa.OpHasCPUFeature, types.Types[types.TBOOL], ir.Syms.X86HasFMA)
4664 b.Kind = ssa.BlockIf
4666 bTrue := s.f.NewBlock(ssa.BlockPlain)
4667 bFalse := s.f.NewBlock(ssa.BlockPlain)
4668 bEnd := s.f.NewBlock(ssa.BlockPlain)
4671 b.Likely = ssa.BranchLikely // >= haswell cpus are common
4673 // We have the intrinsic - use it directly.
4675 s.vars[n] = s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4676 s.endBlock().AddEdgeTo(bEnd)
4678 // Call the pure Go version.
4679 s.startBlock(bFalse)
4680 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4681 s.endBlock().AddEdgeTo(bEnd)
4685 return s.variable(n, types.Types[types.TFLOAT64])
4689 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4690 if !s.config.UseFMA {
4691 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4692 return s.variable(n, types.Types[types.TFLOAT64])
4694 addr := s.entryNewValue1A(ssa.OpAddr, types.Types[types.TBOOL].PtrTo(), ir.Syms.ARMHasVFPv4, s.sb)
4695 v := s.load(types.Types[types.TBOOL], addr)
4697 b.Kind = ssa.BlockIf
4699 bTrue := s.f.NewBlock(ssa.BlockPlain)
4700 bFalse := s.f.NewBlock(ssa.BlockPlain)
4701 bEnd := s.f.NewBlock(ssa.BlockPlain)
4704 b.Likely = ssa.BranchLikely
4706 // We have the intrinsic - use it directly.
4708 s.vars[n] = s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4709 s.endBlock().AddEdgeTo(bEnd)
4711 // Call the pure Go version.
4712 s.startBlock(bFalse)
4713 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4714 s.endBlock().AddEdgeTo(bEnd)
4718 return s.variable(n, types.Types[types.TFLOAT64])
4722 makeRoundAMD64 := func(op ssa.Op) func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4723 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4724 if buildcfg.GOAMD64 >= 2 {
4725 return s.newValue1(op, types.Types[types.TFLOAT64], args[0])
4728 v := s.entryNewValue0A(ssa.OpHasCPUFeature, types.Types[types.TBOOL], ir.Syms.X86HasSSE41)
4730 b.Kind = ssa.BlockIf
4732 bTrue := s.f.NewBlock(ssa.BlockPlain)
4733 bFalse := s.f.NewBlock(ssa.BlockPlain)
4734 bEnd := s.f.NewBlock(ssa.BlockPlain)
4737 b.Likely = ssa.BranchLikely // most machines have sse4.1 nowadays
4739 // We have the intrinsic - use it directly.
4741 s.vars[n] = s.newValue1(op, types.Types[types.TFLOAT64], args[0])
4742 s.endBlock().AddEdgeTo(bEnd)
4744 // Call the pure Go version.
4745 s.startBlock(bFalse)
4746 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4747 s.endBlock().AddEdgeTo(bEnd)
4751 return s.variable(n, types.Types[types.TFLOAT64])
4754 addF("math", "RoundToEven",
4755 makeRoundAMD64(ssa.OpRoundToEven),
4757 addF("math", "Floor",
4758 makeRoundAMD64(ssa.OpFloor),
4760 addF("math", "Ceil",
4761 makeRoundAMD64(ssa.OpCeil),
4763 addF("math", "Trunc",
4764 makeRoundAMD64(ssa.OpTrunc),
4767 /******** math/bits ********/
4768 addF("math/bits", "TrailingZeros64",
4769 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4770 return s.newValue1(ssa.OpCtz64, types.Types[types.TINT], args[0])
4772 sys.AMD64, sys.I386, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4773 addF("math/bits", "TrailingZeros32",
4774 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4775 return s.newValue1(ssa.OpCtz32, types.Types[types.TINT], args[0])
4777 sys.AMD64, sys.I386, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4778 addF("math/bits", "TrailingZeros16",
4779 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4780 x := s.newValue1(ssa.OpZeroExt16to32, types.Types[types.TUINT32], args[0])
4781 c := s.constInt32(types.Types[types.TUINT32], 1<<16)
4782 y := s.newValue2(ssa.OpOr32, types.Types[types.TUINT32], x, c)
4783 return s.newValue1(ssa.OpCtz32, types.Types[types.TINT], y)
4786 addF("math/bits", "TrailingZeros16",
4787 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4788 return s.newValue1(ssa.OpCtz16, types.Types[types.TINT], args[0])
4790 sys.AMD64, sys.I386, sys.ARM, sys.ARM64, sys.Wasm)
4791 addF("math/bits", "TrailingZeros16",
4792 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4793 x := s.newValue1(ssa.OpZeroExt16to64, types.Types[types.TUINT64], args[0])
4794 c := s.constInt64(types.Types[types.TUINT64], 1<<16)
4795 y := s.newValue2(ssa.OpOr64, types.Types[types.TUINT64], x, c)
4796 return s.newValue1(ssa.OpCtz64, types.Types[types.TINT], y)
4798 sys.S390X, sys.PPC64)
4799 addF("math/bits", "TrailingZeros8",
4800 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4801 x := s.newValue1(ssa.OpZeroExt8to32, types.Types[types.TUINT32], args[0])
4802 c := s.constInt32(types.Types[types.TUINT32], 1<<8)
4803 y := s.newValue2(ssa.OpOr32, types.Types[types.TUINT32], x, c)
4804 return s.newValue1(ssa.OpCtz32, types.Types[types.TINT], y)
4807 addF("math/bits", "TrailingZeros8",
4808 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4809 return s.newValue1(ssa.OpCtz8, types.Types[types.TINT], args[0])
4811 sys.AMD64, sys.I386, sys.ARM, sys.ARM64, sys.Wasm)
4812 addF("math/bits", "TrailingZeros8",
4813 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4814 x := s.newValue1(ssa.OpZeroExt8to64, types.Types[types.TUINT64], args[0])
4815 c := s.constInt64(types.Types[types.TUINT64], 1<<8)
4816 y := s.newValue2(ssa.OpOr64, types.Types[types.TUINT64], x, c)
4817 return s.newValue1(ssa.OpCtz64, types.Types[types.TINT], y)
4820 alias("math/bits", "ReverseBytes64", "runtime/internal/sys", "Bswap64", all...)
4821 alias("math/bits", "ReverseBytes32", "runtime/internal/sys", "Bswap32", all...)
4822 // ReverseBytes inlines correctly, no need to intrinsify it.
4823 // Nothing special is needed for targets where ReverseBytes16 lowers to a rotate
4824 // On Power10, 16-bit rotate is not available so use BRH instruction
4825 if buildcfg.GOPPC64 >= 10 {
4826 addF("math/bits", "ReverseBytes16",
4827 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4828 return s.newValue1(ssa.OpBswap16, types.Types[types.TUINT], args[0])
4833 addF("math/bits", "Len64",
4834 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4835 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], args[0])
4837 sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4838 addF("math/bits", "Len32",
4839 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4840 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], args[0])
4842 sys.AMD64, sys.ARM64, sys.PPC64)
4843 addF("math/bits", "Len32",
4844 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4845 if s.config.PtrSize == 4 {
4846 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], args[0])
4848 x := s.newValue1(ssa.OpZeroExt32to64, types.Types[types.TUINT64], args[0])
4849 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], x)
4851 sys.ARM, sys.S390X, sys.MIPS, sys.Wasm)
4852 addF("math/bits", "Len16",
4853 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4854 if s.config.PtrSize == 4 {
4855 x := s.newValue1(ssa.OpZeroExt16to32, types.Types[types.TUINT32], args[0])
4856 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], x)
4858 x := s.newValue1(ssa.OpZeroExt16to64, types.Types[types.TUINT64], args[0])
4859 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], x)
4861 sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4862 addF("math/bits", "Len16",
4863 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4864 return s.newValue1(ssa.OpBitLen16, types.Types[types.TINT], args[0])
4867 addF("math/bits", "Len8",
4868 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4869 if s.config.PtrSize == 4 {
4870 x := s.newValue1(ssa.OpZeroExt8to32, types.Types[types.TUINT32], args[0])
4871 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], x)
4873 x := s.newValue1(ssa.OpZeroExt8to64, types.Types[types.TUINT64], args[0])
4874 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], x)
4876 sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4877 addF("math/bits", "Len8",
4878 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4879 return s.newValue1(ssa.OpBitLen8, types.Types[types.TINT], args[0])
4882 addF("math/bits", "Len",
4883 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4884 if s.config.PtrSize == 4 {
4885 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], args[0])
4887 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], args[0])
4889 sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4890 // LeadingZeros is handled because it trivially calls Len.
4891 addF("math/bits", "Reverse64",
4892 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4893 return s.newValue1(ssa.OpBitRev64, types.Types[types.TINT], args[0])
4896 addF("math/bits", "Reverse32",
4897 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4898 return s.newValue1(ssa.OpBitRev32, types.Types[types.TINT], args[0])
4901 addF("math/bits", "Reverse16",
4902 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4903 return s.newValue1(ssa.OpBitRev16, types.Types[types.TINT], args[0])
4906 addF("math/bits", "Reverse8",
4907 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4908 return s.newValue1(ssa.OpBitRev8, types.Types[types.TINT], args[0])
4911 addF("math/bits", "Reverse",
4912 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4913 return s.newValue1(ssa.OpBitRev64, types.Types[types.TINT], args[0])
4916 addF("math/bits", "RotateLeft8",
4917 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4918 return s.newValue2(ssa.OpRotateLeft8, types.Types[types.TUINT8], args[0], args[1])
4921 addF("math/bits", "RotateLeft16",
4922 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4923 return s.newValue2(ssa.OpRotateLeft16, types.Types[types.TUINT16], args[0], args[1])
4926 addF("math/bits", "RotateLeft32",
4927 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4928 return s.newValue2(ssa.OpRotateLeft32, types.Types[types.TUINT32], args[0], args[1])
4930 sys.AMD64, sys.ARM, sys.ARM64, sys.S390X, sys.PPC64, sys.Wasm, sys.Loong64)
4931 addF("math/bits", "RotateLeft64",
4932 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4933 return s.newValue2(ssa.OpRotateLeft64, types.Types[types.TUINT64], args[0], args[1])
4935 sys.AMD64, sys.ARM64, sys.S390X, sys.PPC64, sys.Wasm, sys.Loong64)
4936 alias("math/bits", "RotateLeft", "math/bits", "RotateLeft64", p8...)
4938 makeOnesCountAMD64 := func(op ssa.Op) func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4939 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4940 if buildcfg.GOAMD64 >= 2 {
4941 return s.newValue1(op, types.Types[types.TINT], args[0])
4944 v := s.entryNewValue0A(ssa.OpHasCPUFeature, types.Types[types.TBOOL], ir.Syms.X86HasPOPCNT)
4946 b.Kind = ssa.BlockIf
4948 bTrue := s.f.NewBlock(ssa.BlockPlain)
4949 bFalse := s.f.NewBlock(ssa.BlockPlain)
4950 bEnd := s.f.NewBlock(ssa.BlockPlain)
4953 b.Likely = ssa.BranchLikely // most machines have popcnt nowadays
4955 // We have the intrinsic - use it directly.
4957 s.vars[n] = s.newValue1(op, types.Types[types.TINT], args[0])
4958 s.endBlock().AddEdgeTo(bEnd)
4960 // Call the pure Go version.
4961 s.startBlock(bFalse)
4962 s.vars[n] = s.callResult(n, callNormal) // types.Types[TINT]
4963 s.endBlock().AddEdgeTo(bEnd)
4967 return s.variable(n, types.Types[types.TINT])
4970 addF("math/bits", "OnesCount64",
4971 makeOnesCountAMD64(ssa.OpPopCount64),
4973 addF("math/bits", "OnesCount64",
4974 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4975 return s.newValue1(ssa.OpPopCount64, types.Types[types.TINT], args[0])
4977 sys.PPC64, sys.ARM64, sys.S390X, sys.Wasm)
4978 addF("math/bits", "OnesCount32",
4979 makeOnesCountAMD64(ssa.OpPopCount32),
4981 addF("math/bits", "OnesCount32",
4982 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4983 return s.newValue1(ssa.OpPopCount32, types.Types[types.TINT], args[0])
4985 sys.PPC64, sys.ARM64, sys.S390X, sys.Wasm)
4986 addF("math/bits", "OnesCount16",
4987 makeOnesCountAMD64(ssa.OpPopCount16),
4989 addF("math/bits", "OnesCount16",
4990 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4991 return s.newValue1(ssa.OpPopCount16, types.Types[types.TINT], args[0])
4993 sys.ARM64, sys.S390X, sys.PPC64, sys.Wasm)
4994 addF("math/bits", "OnesCount8",
4995 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4996 return s.newValue1(ssa.OpPopCount8, types.Types[types.TINT], args[0])
4998 sys.S390X, sys.PPC64, sys.Wasm)
4999 addF("math/bits", "OnesCount",
5000 makeOnesCountAMD64(ssa.OpPopCount64),
5002 addF("math/bits", "Mul64",
5003 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
5004 return s.newValue2(ssa.OpMul64uhilo, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1])
5006 sys.AMD64, sys.ARM64, sys.PPC64, sys.S390X, sys.MIPS64, sys.RISCV64, sys.Loong64)
5007 alias("math/bits", "Mul", "math/bits", "Mul64", p8...)
5008 alias("runtime/internal/math", "Mul64", "math/bits", "Mul64", p8...)
5009 addF("math/bits", "Add64",
5010 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
5011 return s.newValue3(ssa.OpAdd64carry, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1], args[2])
5013 sys.AMD64, sys.ARM64, sys.PPC64, sys.S390X, sys.RISCV64, sys.Loong64, sys.MIPS64)
5014 alias("math/bits", "Add", "math/bits", "Add64", p8...)
5015 alias("runtime/internal/math", "Add64", "math/bits", "Add64", all...)
5016 addF("math/bits", "Sub64",
5017 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
5018 return s.newValue3(ssa.OpSub64borrow, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1], args[2])
5020 sys.AMD64, sys.ARM64, sys.PPC64, sys.S390X, sys.RISCV64, sys.Loong64, sys.MIPS64)
5021 alias("math/bits", "Sub", "math/bits", "Sub64", p8...)
5022 addF("math/bits", "Div64",
5023 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
5024 // check for divide-by-zero/overflow and panic with appropriate message
5025 cmpZero := s.newValue2(s.ssaOp(ir.ONE, types.Types[types.TUINT64]), types.Types[types.TBOOL], args[2], s.zeroVal(types.Types[types.TUINT64]))
5026 s.check(cmpZero, ir.Syms.Panicdivide)
5027 cmpOverflow := s.newValue2(s.ssaOp(ir.OLT, types.Types[types.TUINT64]), types.Types[types.TBOOL], args[0], args[2])
5028 s.check(cmpOverflow, ir.Syms.Panicoverflow)
5029 return s.newValue3(ssa.OpDiv128u, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1], args[2])
5032 alias("math/bits", "Div", "math/bits", "Div64", sys.ArchAMD64)
5034 alias("runtime/internal/sys", "TrailingZeros8", "math/bits", "TrailingZeros8", all...)
5035 alias("runtime/internal/sys", "TrailingZeros32", "math/bits", "TrailingZeros32", all...)
5036 alias("runtime/internal/sys", "TrailingZeros64", "math/bits", "TrailingZeros64", all...)
5037 alias("runtime/internal/sys", "Len8", "math/bits", "Len8", all...)
5038 alias("runtime/internal/sys", "Len64", "math/bits", "Len64", all...)
5039 alias("runtime/internal/sys", "OnesCount64", "math/bits", "OnesCount64", all...)
5041 /******** sync/atomic ********/
5043 // Note: these are disabled by flag_race in findIntrinsic below.
5044 alias("sync/atomic", "LoadInt32", "runtime/internal/atomic", "Load", all...)
5045 alias("sync/atomic", "LoadInt64", "runtime/internal/atomic", "Load64", all...)
5046 alias("sync/atomic", "LoadPointer", "runtime/internal/atomic", "Loadp", all...)
5047 alias("sync/atomic", "LoadUint32", "runtime/internal/atomic", "Load", all...)
5048 alias("sync/atomic", "LoadUint64", "runtime/internal/atomic", "Load64", all...)
5049 alias("sync/atomic", "LoadUintptr", "runtime/internal/atomic", "Load", p4...)
5050 alias("sync/atomic", "LoadUintptr", "runtime/internal/atomic", "Load64", p8...)
5052 alias("sync/atomic", "StoreInt32", "runtime/internal/atomic", "Store", all...)
5053 alias("sync/atomic", "StoreInt64", "runtime/internal/atomic", "Store64", all...)
5054 // Note: not StorePointer, that needs a write barrier. Same below for {CompareAnd}Swap.
5055 alias("sync/atomic", "StoreUint32", "runtime/internal/atomic", "Store", all...)
5056 alias("sync/atomic", "StoreUint64", "runtime/internal/atomic", "Store64", all...)
5057 alias("sync/atomic", "StoreUintptr", "runtime/internal/atomic", "Store", p4...)
5058 alias("sync/atomic", "StoreUintptr", "runtime/internal/atomic", "Store64", p8...)
5060 alias("sync/atomic", "SwapInt32", "runtime/internal/atomic", "Xchg", all...)
5061 alias("sync/atomic", "SwapInt64", "runtime/internal/atomic", "Xchg64", all...)
5062 alias("sync/atomic", "SwapUint32", "runtime/internal/atomic", "Xchg", all...)
5063 alias("sync/atomic", "SwapUint64", "runtime/internal/atomic", "Xchg64", all...)
5064 alias("sync/atomic", "SwapUintptr", "runtime/internal/atomic", "Xchg", p4...)
5065 alias("sync/atomic", "SwapUintptr", "runtime/internal/atomic", "Xchg64", p8...)
5067 alias("sync/atomic", "CompareAndSwapInt32", "runtime/internal/atomic", "Cas", all...)
5068 alias("sync/atomic", "CompareAndSwapInt64", "runtime/internal/atomic", "Cas64", all...)
5069 alias("sync/atomic", "CompareAndSwapUint32", "runtime/internal/atomic", "Cas", all...)
5070 alias("sync/atomic", "CompareAndSwapUint64", "runtime/internal/atomic", "Cas64", all...)
5071 alias("sync/atomic", "CompareAndSwapUintptr", "runtime/internal/atomic", "Cas", p4...)
5072 alias("sync/atomic", "CompareAndSwapUintptr", "runtime/internal/atomic", "Cas64", p8...)
5074 alias("sync/atomic", "AddInt32", "runtime/internal/atomic", "Xadd", all...)
5075 alias("sync/atomic", "AddInt64", "runtime/internal/atomic", "Xadd64", all...)
5076 alias("sync/atomic", "AddUint32", "runtime/internal/atomic", "Xadd", all...)
5077 alias("sync/atomic", "AddUint64", "runtime/internal/atomic", "Xadd64", all...)
5078 alias("sync/atomic", "AddUintptr", "runtime/internal/atomic", "Xadd", p4...)
5079 alias("sync/atomic", "AddUintptr", "runtime/internal/atomic", "Xadd64", p8...)
5081 /******** math/big ********/
5082 alias("math/big", "mulWW", "math/bits", "Mul64", p8...)
5085 // findIntrinsic returns a function which builds the SSA equivalent of the
5086 // function identified by the symbol sym. If sym is not an intrinsic call, returns nil.
5087 func findIntrinsic(sym *types.Sym) intrinsicBuilder {
5088 if sym == nil || sym.Pkg == nil {
5092 if sym.Pkg == ir.Pkgs.Runtime {
5095 if base.Flag.Race && pkg == "sync/atomic" {
5096 // The race detector needs to be able to intercept these calls.
5097 // We can't intrinsify them.
5100 // Skip intrinsifying math functions (which may contain hard-float
5101 // instructions) when soft-float
5102 if Arch.SoftFloat && pkg == "math" {
5107 if ssa.IntrinsicsDisable {
5108 if pkg == "runtime" && (fn == "getcallerpc" || fn == "getcallersp" || fn == "getclosureptr") {
5109 // These runtime functions don't have definitions, must be intrinsics.
5114 return intrinsics[intrinsicKey{Arch.LinkArch.Arch, pkg, fn}]
5117 func IsIntrinsicCall(n *ir.CallExpr) bool {
5121 name, ok := n.Fun.(*ir.Name)
5125 return findIntrinsic(name.Sym()) != nil
5128 // intrinsicCall converts a call to a recognized intrinsic function into the intrinsic SSA operation.
5129 func (s *state) intrinsicCall(n *ir.CallExpr) *ssa.Value {
5130 v := findIntrinsic(n.Fun.Sym())(s, n, s.intrinsicArgs(n))
5131 if ssa.IntrinsicsDebug > 0 {
5136 if x.Op == ssa.OpSelect0 || x.Op == ssa.OpSelect1 {
5139 base.WarnfAt(n.Pos(), "intrinsic substitution for %v with %s", n.Fun.Sym().Name, x.LongString())
5144 // intrinsicArgs extracts args from n, evaluates them to SSA values, and returns them.
5145 func (s *state) intrinsicArgs(n *ir.CallExpr) []*ssa.Value {
5146 args := make([]*ssa.Value, len(n.Args))
5147 for i, n := range n.Args {
5153 // openDeferRecord adds code to evaluate and store the function for an open-code defer
5154 // call, and records info about the defer, so we can generate proper code on the
5155 // exit paths. n is the sub-node of the defer node that is the actual function
5156 // call. We will also record funcdata information on where the function is stored
5157 // (as well as the deferBits variable), and this will enable us to run the proper
5158 // defer calls during panics.
5159 func (s *state) openDeferRecord(n *ir.CallExpr) {
5160 if len(n.Args) != 0 || n.Op() != ir.OCALLFUNC || n.Fun.Type().NumResults() != 0 {
5161 s.Fatalf("defer call with arguments or results: %v", n)
5164 opendefer := &openDeferInfo{
5168 // We must always store the function value in a stack slot for the
5169 // runtime panic code to use. But in the defer exit code, we will
5170 // call the function directly if it is a static function.
5171 closureVal := s.expr(fn)
5172 closure := s.openDeferSave(fn.Type(), closureVal)
5173 opendefer.closureNode = closure.Aux.(*ir.Name)
5174 if !(fn.Op() == ir.ONAME && fn.(*ir.Name).Class == ir.PFUNC) {
5175 opendefer.closure = closure
5177 index := len(s.openDefers)
5178 s.openDefers = append(s.openDefers, opendefer)
5180 // Update deferBits only after evaluation and storage to stack of
5181 // the function is successful.
5182 bitvalue := s.constInt8(types.Types[types.TUINT8], 1<<uint(index))
5183 newDeferBits := s.newValue2(ssa.OpOr8, types.Types[types.TUINT8], s.variable(deferBitsVar, types.Types[types.TUINT8]), bitvalue)
5184 s.vars[deferBitsVar] = newDeferBits
5185 s.store(types.Types[types.TUINT8], s.deferBitsAddr, newDeferBits)
5188 // openDeferSave generates SSA nodes to store a value (with type t) for an
5189 // open-coded defer at an explicit autotmp location on the stack, so it can be
5190 // reloaded and used for the appropriate call on exit. Type t must be a function type
5191 // (therefore SSAable). val is the value to be stored. The function returns an SSA
5192 // value representing a pointer to the autotmp location.
5193 func (s *state) openDeferSave(t *types.Type, val *ssa.Value) *ssa.Value {
5195 s.Fatalf("openDeferSave of non-SSA-able type %v val=%v", t, val)
5197 if !t.HasPointers() {
5198 s.Fatalf("openDeferSave of pointerless type %v val=%v", t, val)
5201 temp := typecheck.TempAt(pos.WithNotStmt(), s.curfn, t)
5202 temp.SetOpenDeferSlot(true)
5203 temp.SetFrameOffset(int64(len(s.openDefers))) // so cmpstackvarlt can order them
5204 var addrTemp *ssa.Value
5205 // Use OpVarLive to make sure stack slot for the closure is not removed by
5206 // dead-store elimination
5207 if s.curBlock.ID != s.f.Entry.ID {
5208 // Force the tmp storing this defer function to be declared in the entry
5209 // block, so that it will be live for the defer exit code (which will
5210 // actually access it only if the associated defer call has been activated).
5211 if t.HasPointers() {
5212 s.defvars[s.f.Entry.ID][memVar] = s.f.Entry.NewValue1A(src.NoXPos, ssa.OpVarDef, types.TypeMem, temp, s.defvars[s.f.Entry.ID][memVar])
5214 s.defvars[s.f.Entry.ID][memVar] = s.f.Entry.NewValue1A(src.NoXPos, ssa.OpVarLive, types.TypeMem, temp, s.defvars[s.f.Entry.ID][memVar])
5215 addrTemp = s.f.Entry.NewValue2A(src.NoXPos, ssa.OpLocalAddr, types.NewPtr(temp.Type()), temp, s.sp, s.defvars[s.f.Entry.ID][memVar])
5217 // Special case if we're still in the entry block. We can't use
5218 // the above code, since s.defvars[s.f.Entry.ID] isn't defined
5219 // until we end the entry block with s.endBlock().
5220 if t.HasPointers() {
5221 s.vars[memVar] = s.newValue1Apos(ssa.OpVarDef, types.TypeMem, temp, s.mem(), false)
5223 s.vars[memVar] = s.newValue1Apos(ssa.OpVarLive, types.TypeMem, temp, s.mem(), false)
5224 addrTemp = s.newValue2Apos(ssa.OpLocalAddr, types.NewPtr(temp.Type()), temp, s.sp, s.mem(), false)
5226 // Since we may use this temp during exit depending on the
5227 // deferBits, we must define it unconditionally on entry.
5228 // Therefore, we must make sure it is zeroed out in the entry
5229 // block if it contains pointers, else GC may wrongly follow an
5230 // uninitialized pointer value.
5231 temp.SetNeedzero(true)
5232 // We are storing to the stack, hence we can avoid the full checks in
5233 // storeType() (no write barrier) and do a simple store().
5234 s.store(t, addrTemp, val)
5238 // openDeferExit generates SSA for processing all the open coded defers at exit.
5239 // The code involves loading deferBits, and checking each of the bits to see if
5240 // the corresponding defer statement was executed. For each bit that is turned
5241 // on, the associated defer call is made.
5242 func (s *state) openDeferExit() {
5243 deferExit := s.f.NewBlock(ssa.BlockPlain)
5244 s.endBlock().AddEdgeTo(deferExit)
5245 s.startBlock(deferExit)
5246 s.lastDeferExit = deferExit
5247 s.lastDeferCount = len(s.openDefers)
5248 zeroval := s.constInt8(types.Types[types.TUINT8], 0)
5249 // Test for and run defers in reverse order
5250 for i := len(s.openDefers) - 1; i >= 0; i-- {
5251 r := s.openDefers[i]
5252 bCond := s.f.NewBlock(ssa.BlockPlain)
5253 bEnd := s.f.NewBlock(ssa.BlockPlain)
5255 deferBits := s.variable(deferBitsVar, types.Types[types.TUINT8])
5256 // Generate code to check if the bit associated with the current
5258 bitval := s.constInt8(types.Types[types.TUINT8], 1<<uint(i))
5259 andval := s.newValue2(ssa.OpAnd8, types.Types[types.TUINT8], deferBits, bitval)
5260 eqVal := s.newValue2(ssa.OpEq8, types.Types[types.TBOOL], andval, zeroval)
5262 b.Kind = ssa.BlockIf
5266 bCond.AddEdgeTo(bEnd)
5269 // Clear this bit in deferBits and force store back to stack, so
5270 // we will not try to re-run this defer call if this defer call panics.
5271 nbitval := s.newValue1(ssa.OpCom8, types.Types[types.TUINT8], bitval)
5272 maskedval := s.newValue2(ssa.OpAnd8, types.Types[types.TUINT8], deferBits, nbitval)
5273 s.store(types.Types[types.TUINT8], s.deferBitsAddr, maskedval)
5274 // Use this value for following tests, so we keep previous
5276 s.vars[deferBitsVar] = maskedval
5278 // Generate code to call the function call of the defer, using the
5279 // closure that were stored in argtmps at the point of the defer
5282 stksize := fn.Type().ArgWidth()
5283 var callArgs []*ssa.Value
5285 if r.closure != nil {
5286 v := s.load(r.closure.Type.Elem(), r.closure)
5287 s.maybeNilCheckClosure(v, callDefer)
5288 codeptr := s.rawLoad(types.Types[types.TUINTPTR], v)
5289 aux := ssa.ClosureAuxCall(s.f.ABIDefault.ABIAnalyzeTypes(nil, nil))
5290 call = s.newValue2A(ssa.OpClosureLECall, aux.LateExpansionResultType(), aux, codeptr, v)
5292 aux := ssa.StaticAuxCall(fn.(*ir.Name).Linksym(), s.f.ABIDefault.ABIAnalyzeTypes(nil, nil))
5293 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5295 callArgs = append(callArgs, s.mem())
5296 call.AddArgs(callArgs...)
5297 call.AuxInt = stksize
5298 s.vars[memVar] = s.newValue1I(ssa.OpSelectN, types.TypeMem, 0, call)
5299 // Make sure that the stack slots with pointers are kept live
5300 // through the call (which is a pre-emption point). Also, we will
5301 // use the first call of the last defer exit to compute liveness
5302 // for the deferreturn, so we want all stack slots to be live.
5303 if r.closureNode != nil {
5304 s.vars[memVar] = s.newValue1Apos(ssa.OpVarLive, types.TypeMem, r.closureNode, s.mem(), false)
5312 func (s *state) callResult(n *ir.CallExpr, k callKind) *ssa.Value {
5313 return s.call(n, k, false, nil)
5316 func (s *state) callAddr(n *ir.CallExpr, k callKind) *ssa.Value {
5317 return s.call(n, k, true, nil)
5320 // Calls the function n using the specified call type.
5321 // Returns the address of the return value (or nil if none).
5322 func (s *state) call(n *ir.CallExpr, k callKind, returnResultAddr bool, deferExtra ir.Expr) *ssa.Value {
5324 var callee *ir.Name // target function (if static)
5325 var closure *ssa.Value // ptr to closure to run (if dynamic)
5326 var codeptr *ssa.Value // ptr to target code (if dynamic)
5327 var dextra *ssa.Value // defer extra arg
5328 var rcvr *ssa.Value // receiver to set
5330 var ACArgs []*types.Type // AuxCall args
5331 var ACResults []*types.Type // AuxCall results
5332 var callArgs []*ssa.Value // For late-expansion, the args themselves (not stored, args to the call instead).
5334 callABI := s.f.ABIDefault
5336 if k != callNormal && k != callTail && (len(n.Args) != 0 || n.Op() == ir.OCALLINTER || n.Fun.Type().NumResults() != 0) {
5337 s.Fatalf("go/defer call with arguments: %v", n)
5342 if (k == callNormal || k == callTail) && fn.Op() == ir.ONAME && fn.(*ir.Name).Class == ir.PFUNC {
5345 if buildcfg.Experiment.RegabiArgs {
5346 // This is a static call, so it may be
5347 // a direct call to a non-ABIInternal
5348 // function. fn.Func may be nil for
5349 // some compiler-generated functions,
5350 // but those are all ABIInternal.
5352 callABI = abiForFunc(fn.Func, s.f.ABI0, s.f.ABI1)
5355 // TODO(register args) remove after register abi is working
5356 inRegistersImported := fn.Pragma()&ir.RegisterParams != 0
5357 inRegistersSamePackage := fn.Func != nil && fn.Func.Pragma&ir.RegisterParams != 0
5358 if inRegistersImported || inRegistersSamePackage {
5364 closure = s.expr(fn)
5365 if k != callDefer && k != callDeferStack {
5366 // Deferred nil function needs to panic when the function is invoked,
5367 // not the point of defer statement.
5368 s.maybeNilCheckClosure(closure, k)
5371 if fn.Op() != ir.ODOTINTER {
5372 s.Fatalf("OCALLINTER: n.Left not an ODOTINTER: %v", fn.Op())
5374 fn := fn.(*ir.SelectorExpr)
5375 var iclosure *ssa.Value
5376 iclosure, rcvr = s.getClosureAndRcvr(fn)
5377 if k == callNormal {
5378 codeptr = s.load(types.Types[types.TUINTPTR], iclosure)
5383 if deferExtra != nil {
5384 dextra = s.expr(deferExtra)
5387 params := callABI.ABIAnalyze(n.Fun.Type(), false /* Do not set (register) nNames from caller side -- can cause races. */)
5388 types.CalcSize(fn.Type())
5389 stksize := params.ArgWidth() // includes receiver, args, and results
5391 res := n.Fun.Type().Results()
5392 if k == callNormal || k == callTail {
5393 for _, p := range params.OutParams() {
5394 ACResults = append(ACResults, p.Type)
5399 if k == callDeferStack {
5401 s.Fatalf("deferprocStack with non-zero stack size %d: %v", stksize, n)
5403 // Make a defer struct on the stack.
5405 _, addr := s.temp(n.Pos(), t)
5406 s.store(closure.Type,
5407 s.newValue1I(ssa.OpOffPtr, closure.Type.PtrTo(), t.FieldOff(deferStructFnField), addr),
5410 // Call runtime.deferprocStack with pointer to _defer record.
5411 ACArgs = append(ACArgs, types.Types[types.TUINTPTR])
5412 aux := ssa.StaticAuxCall(ir.Syms.DeferprocStack, s.f.ABIDefault.ABIAnalyzeTypes(ACArgs, ACResults))
5413 callArgs = append(callArgs, addr, s.mem())
5414 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5415 call.AddArgs(callArgs...)
5416 call.AuxInt = int64(types.PtrSize) // deferprocStack takes a *_defer arg
5418 // Store arguments to stack, including defer/go arguments and receiver for method calls.
5419 // These are written in SP-offset order.
5420 argStart := base.Ctxt.Arch.FixedFrameSize
5422 if k != callNormal && k != callTail {
5423 // Write closure (arg to newproc/deferproc).
5424 ACArgs = append(ACArgs, types.Types[types.TUINTPTR]) // not argExtra
5425 callArgs = append(callArgs, closure)
5426 stksize += int64(types.PtrSize)
5427 argStart += int64(types.PtrSize)
5429 // Extra token of type any for deferproc
5430 ACArgs = append(ACArgs, types.Types[types.TINTER])
5431 callArgs = append(callArgs, dextra)
5432 stksize += 2 * int64(types.PtrSize)
5433 argStart += 2 * int64(types.PtrSize)
5437 // Set receiver (for interface calls).
5439 callArgs = append(callArgs, rcvr)
5446 for _, p := range params.InParams() { // includes receiver for interface calls
5447 ACArgs = append(ACArgs, p.Type)
5450 // Split the entry block if there are open defers, because later calls to
5451 // openDeferSave may cause a mismatch between the mem for an OpDereference
5452 // and the call site which uses it. See #49282.
5453 if s.curBlock.ID == s.f.Entry.ID && s.hasOpenDefers {
5455 b.Kind = ssa.BlockPlain
5456 curb := s.f.NewBlock(ssa.BlockPlain)
5461 for i, n := range args {
5462 callArgs = append(callArgs, s.putArg(n, t.Param(i).Type))
5465 callArgs = append(callArgs, s.mem())
5469 case k == callDefer:
5470 sym := ir.Syms.Deferproc
5472 sym = ir.Syms.Deferprocat
5474 aux := ssa.StaticAuxCall(sym, s.f.ABIDefault.ABIAnalyzeTypes(ACArgs, ACResults)) // TODO paramResultInfo for Deferproc(at)
5475 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5477 aux := ssa.StaticAuxCall(ir.Syms.Newproc, s.f.ABIDefault.ABIAnalyzeTypes(ACArgs, ACResults))
5478 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux) // TODO paramResultInfo for Newproc
5479 case closure != nil:
5480 // rawLoad because loading the code pointer from a
5481 // closure is always safe, but IsSanitizerSafeAddr
5482 // can't always figure that out currently, and it's
5483 // critical that we not clobber any arguments already
5484 // stored onto the stack.
5485 codeptr = s.rawLoad(types.Types[types.TUINTPTR], closure)
5486 aux := ssa.ClosureAuxCall(callABI.ABIAnalyzeTypes(ACArgs, ACResults))
5487 call = s.newValue2A(ssa.OpClosureLECall, aux.LateExpansionResultType(), aux, codeptr, closure)
5488 case codeptr != nil:
5489 // Note that the "receiver" parameter is nil because the actual receiver is the first input parameter.
5490 aux := ssa.InterfaceAuxCall(params)
5491 call = s.newValue1A(ssa.OpInterLECall, aux.LateExpansionResultType(), aux, codeptr)
5493 aux := ssa.StaticAuxCall(callTargetLSym(callee), params)
5494 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5496 call.Op = ssa.OpTailLECall
5497 stksize = 0 // Tail call does not use stack. We reuse caller's frame.
5500 s.Fatalf("bad call type %v %v", n.Op(), n)
5502 call.AddArgs(callArgs...)
5503 call.AuxInt = stksize // Call operations carry the argsize of the callee along with them
5506 s.vars[memVar] = s.newValue1I(ssa.OpSelectN, types.TypeMem, int64(len(ACResults)), call)
5507 // Insert VarLive opcodes.
5508 for _, v := range n.KeepAlive {
5510 s.Fatalf("KeepAlive variable %v must have Addrtaken set", v)
5513 case ir.PAUTO, ir.PPARAM, ir.PPARAMOUT:
5515 s.Fatalf("KeepAlive variable %v must be Auto or Arg", v)
5517 s.vars[memVar] = s.newValue1A(ssa.OpVarLive, types.TypeMem, v, s.mem())
5520 // Finish block for defers
5521 if k == callDefer || k == callDeferStack {
5523 b.Kind = ssa.BlockDefer
5525 bNext := s.f.NewBlock(ssa.BlockPlain)
5527 // Add recover edge to exit code.
5528 r := s.f.NewBlock(ssa.BlockPlain)
5532 b.Likely = ssa.BranchLikely
5536 if len(res) == 0 || k != callNormal {
5537 // call has no return value. Continue with the next statement.
5541 if returnResultAddr {
5542 return s.resultAddrOfCall(call, 0, fp.Type)
5544 return s.newValue1I(ssa.OpSelectN, fp.Type, 0, call)
5547 // maybeNilCheckClosure checks if a nil check of a closure is needed in some
5548 // architecture-dependent situations and, if so, emits the nil check.
5549 func (s *state) maybeNilCheckClosure(closure *ssa.Value, k callKind) {
5550 if Arch.LinkArch.Family == sys.Wasm || buildcfg.GOOS == "aix" && k != callGo {
5551 // On AIX, the closure needs to be verified as fn can be nil, except if it's a call go. This needs to be handled by the runtime to have the "go of nil func value" error.
5552 // TODO(neelance): On other architectures this should be eliminated by the optimization steps
5557 // getClosureAndRcvr returns values for the appropriate closure and receiver of an
5559 func (s *state) getClosureAndRcvr(fn *ir.SelectorExpr) (*ssa.Value, *ssa.Value) {
5561 itab := s.newValue1(ssa.OpITab, types.Types[types.TUINTPTR], i)
5563 itabidx := fn.Offset() + 2*int64(types.PtrSize) + 8 // offset of fun field in runtime.itab
5564 closure := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.UintptrPtr, itabidx, itab)
5565 rcvr := s.newValue1(ssa.OpIData, s.f.Config.Types.BytePtr, i)
5566 return closure, rcvr
5569 // etypesign returns the signed-ness of e, for integer/pointer etypes.
5570 // -1 means signed, +1 means unsigned, 0 means non-integer/non-pointer.
5571 func etypesign(e types.Kind) int8 {
5573 case types.TINT8, types.TINT16, types.TINT32, types.TINT64, types.TINT:
5575 case types.TUINT8, types.TUINT16, types.TUINT32, types.TUINT64, types.TUINT, types.TUINTPTR, types.TUNSAFEPTR:
5581 // addr converts the address of the expression n to SSA, adds it to s and returns the SSA result.
5582 // The value that the returned Value represents is guaranteed to be non-nil.
5583 func (s *state) addr(n ir.Node) *ssa.Value {
5584 if n.Op() != ir.ONAME {
5590 s.Fatalf("addr of canSSA expression: %+v", n)
5593 t := types.NewPtr(n.Type())
5594 linksymOffset := func(lsym *obj.LSym, offset int64) *ssa.Value {
5595 v := s.entryNewValue1A(ssa.OpAddr, t, lsym, s.sb)
5596 // TODO: Make OpAddr use AuxInt as well as Aux.
5598 v = s.entryNewValue1I(ssa.OpOffPtr, v.Type, offset, v)
5603 case ir.OLINKSYMOFFSET:
5604 no := n.(*ir.LinksymOffsetExpr)
5605 return linksymOffset(no.Linksym, no.Offset_)
5608 if n.Heapaddr != nil {
5609 return s.expr(n.Heapaddr)
5614 return linksymOffset(n.Linksym(), 0)
5621 s.Fatalf("addr of undeclared ONAME %v. declared: %v", n, s.decladdrs)
5624 return s.newValue2Apos(ssa.OpLocalAddr, t, n, s.sp, s.mem(), !ir.IsAutoTmp(n))
5626 case ir.PPARAMOUT: // Same as PAUTO -- cannot generate LEA early.
5627 // ensure that we reuse symbols for out parameters so
5628 // that cse works on their addresses
5629 return s.newValue2Apos(ssa.OpLocalAddr, t, n, s.sp, s.mem(), true)
5631 s.Fatalf("variable address class %v not implemented", n.Class)
5635 // load return from callee
5636 n := n.(*ir.ResultExpr)
5637 return s.resultAddrOfCall(s.prevCall, n.Index, n.Type())
5639 n := n.(*ir.IndexExpr)
5640 if n.X.Type().IsSlice() {
5642 i := s.expr(n.Index)
5643 len := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], a)
5644 i = s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded())
5645 p := s.newValue1(ssa.OpSlicePtr, t, a)
5646 return s.newValue2(ssa.OpPtrIndex, t, p, i)
5649 i := s.expr(n.Index)
5650 len := s.constInt(types.Types[types.TINT], n.X.Type().NumElem())
5651 i = s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded())
5652 return s.newValue2(ssa.OpPtrIndex, types.NewPtr(n.X.Type().Elem()), a, i)
5655 n := n.(*ir.StarExpr)
5656 return s.exprPtr(n.X, n.Bounded(), n.Pos())
5658 n := n.(*ir.SelectorExpr)
5660 return s.newValue1I(ssa.OpOffPtr, t, n.Offset(), p)
5662 n := n.(*ir.SelectorExpr)
5663 p := s.exprPtr(n.X, n.Bounded(), n.Pos())
5664 return s.newValue1I(ssa.OpOffPtr, t, n.Offset(), p)
5666 n := n.(*ir.ConvExpr)
5667 if n.Type() == n.X.Type() {
5671 return s.newValue1(ssa.OpCopy, t, addr) // ensure that addr has the right type
5672 case ir.OCALLFUNC, ir.OCALLINTER:
5673 n := n.(*ir.CallExpr)
5674 return s.callAddr(n, callNormal)
5675 case ir.ODOTTYPE, ir.ODYNAMICDOTTYPE:
5677 if n.Op() == ir.ODOTTYPE {
5678 v, _ = s.dottype(n.(*ir.TypeAssertExpr), false)
5680 v, _ = s.dynamicDottype(n.(*ir.DynamicTypeAssertExpr), false)
5682 if v.Op != ssa.OpLoad {
5683 s.Fatalf("dottype of non-load")
5685 if v.Args[1] != s.mem() {
5686 s.Fatalf("memory no longer live from dottype load")
5690 s.Fatalf("unhandled addr %v", n.Op())
5695 // canSSA reports whether n is SSA-able.
5696 // n must be an ONAME (or an ODOT sequence with an ONAME base).
5697 func (s *state) canSSA(n ir.Node) bool {
5698 if base.Flag.N != 0 {
5703 if nn.Op() == ir.ODOT {
5704 nn := nn.(*ir.SelectorExpr)
5708 if nn.Op() == ir.OINDEX {
5709 nn := nn.(*ir.IndexExpr)
5710 if nn.X.Type().IsArray() {
5717 if n.Op() != ir.ONAME {
5720 return s.canSSAName(n.(*ir.Name)) && ssa.CanSSA(n.Type())
5723 func (s *state) canSSAName(name *ir.Name) bool {
5724 if name.Addrtaken() || !name.OnStack() {
5730 // TODO: handle this case? Named return values must be
5731 // in memory so that the deferred function can see them.
5732 // Maybe do: if !strings.HasPrefix(n.String(), "~") { return false }
5733 // Or maybe not, see issue 18860. Even unnamed return values
5734 // must be written back so if a defer recovers, the caller can see them.
5737 if s.cgoUnsafeArgs {
5738 // Cgo effectively takes the address of all result args,
5739 // but the compiler can't see that.
5744 // TODO: try to make more variables SSAable?
5747 // exprPtr evaluates n to a pointer and nil-checks it.
5748 func (s *state) exprPtr(n ir.Node, bounded bool, lineno src.XPos) *ssa.Value {
5750 if bounded || n.NonNil() {
5751 if s.f.Frontend().Debug_checknil() && lineno.Line() > 1 {
5752 s.f.Warnl(lineno, "removed nil check")
5760 // nilCheck generates nil pointer checking code.
5761 // Used only for automatically inserted nil checks,
5762 // not for user code like 'x != nil'.
5763 func (s *state) nilCheck(ptr *ssa.Value) {
5764 if base.Debug.DisableNil != 0 || s.curfn.NilCheckDisabled() {
5767 s.newValue2(ssa.OpNilCheck, types.TypeVoid, ptr, s.mem())
5770 // boundsCheck generates bounds checking code. Checks if 0 <= idx <[=] len, branches to exit if not.
5771 // Starts a new block on return.
5772 // On input, len must be converted to full int width and be nonnegative.
5773 // Returns idx converted to full int width.
5774 // If bounded is true then caller guarantees the index is not out of bounds
5775 // (but boundsCheck will still extend the index to full int width).
5776 func (s *state) boundsCheck(idx, len *ssa.Value, kind ssa.BoundsKind, bounded bool) *ssa.Value {
5777 idx = s.extendIndex(idx, len, kind, bounded)
5779 if bounded || base.Flag.B != 0 {
5780 // If bounded or bounds checking is flag-disabled, then no check necessary,
5781 // just return the extended index.
5783 // Here, bounded == true if the compiler generated the index itself,
5784 // such as in the expansion of a slice initializer. These indexes are
5785 // compiler-generated, not Go program variables, so they cannot be
5786 // attacker-controlled, so we can omit Spectre masking as well.
5788 // Note that we do not want to omit Spectre masking in code like:
5790 // if 0 <= i && i < len(x) {
5794 // Lucky for us, bounded==false for that code.
5795 // In that case (handled below), we emit a bound check (and Spectre mask)
5796 // and then the prove pass will remove the bounds check.
5797 // In theory the prove pass could potentially remove certain
5798 // Spectre masks, but it's very delicate and probably better
5799 // to be conservative and leave them all in.
5803 bNext := s.f.NewBlock(ssa.BlockPlain)
5804 bPanic := s.f.NewBlock(ssa.BlockExit)
5806 if !idx.Type.IsSigned() {
5808 case ssa.BoundsIndex:
5809 kind = ssa.BoundsIndexU
5810 case ssa.BoundsSliceAlen:
5811 kind = ssa.BoundsSliceAlenU
5812 case ssa.BoundsSliceAcap:
5813 kind = ssa.BoundsSliceAcapU
5814 case ssa.BoundsSliceB:
5815 kind = ssa.BoundsSliceBU
5816 case ssa.BoundsSlice3Alen:
5817 kind = ssa.BoundsSlice3AlenU
5818 case ssa.BoundsSlice3Acap:
5819 kind = ssa.BoundsSlice3AcapU
5820 case ssa.BoundsSlice3B:
5821 kind = ssa.BoundsSlice3BU
5822 case ssa.BoundsSlice3C:
5823 kind = ssa.BoundsSlice3CU
5828 if kind == ssa.BoundsIndex || kind == ssa.BoundsIndexU {
5829 cmp = s.newValue2(ssa.OpIsInBounds, types.Types[types.TBOOL], idx, len)
5831 cmp = s.newValue2(ssa.OpIsSliceInBounds, types.Types[types.TBOOL], idx, len)
5834 b.Kind = ssa.BlockIf
5836 b.Likely = ssa.BranchLikely
5840 s.startBlock(bPanic)
5841 if Arch.LinkArch.Family == sys.Wasm {
5842 // TODO(khr): figure out how to do "register" based calling convention for bounds checks.
5843 // Should be similar to gcWriteBarrier, but I can't make it work.
5844 s.rtcall(BoundsCheckFunc[kind], false, nil, idx, len)
5846 mem := s.newValue3I(ssa.OpPanicBounds, types.TypeMem, int64(kind), idx, len, s.mem())
5847 s.endBlock().SetControl(mem)
5851 // In Spectre index mode, apply an appropriate mask to avoid speculative out-of-bounds accesses.
5852 if base.Flag.Cfg.SpectreIndex {
5853 op := ssa.OpSpectreIndex
5854 if kind != ssa.BoundsIndex && kind != ssa.BoundsIndexU {
5855 op = ssa.OpSpectreSliceIndex
5857 idx = s.newValue2(op, types.Types[types.TINT], idx, len)
5863 // If cmp (a bool) is false, panic using the given function.
5864 func (s *state) check(cmp *ssa.Value, fn *obj.LSym) {
5866 b.Kind = ssa.BlockIf
5868 b.Likely = ssa.BranchLikely
5869 bNext := s.f.NewBlock(ssa.BlockPlain)
5871 pos := base.Ctxt.PosTable.Pos(line)
5872 fl := funcLine{f: fn, base: pos.Base(), line: pos.Line()}
5873 bPanic := s.panics[fl]
5875 bPanic = s.f.NewBlock(ssa.BlockPlain)
5876 s.panics[fl] = bPanic
5877 s.startBlock(bPanic)
5878 // The panic call takes/returns memory to ensure that the right
5879 // memory state is observed if the panic happens.
5880 s.rtcall(fn, false, nil)
5887 func (s *state) intDivide(n ir.Node, a, b *ssa.Value) *ssa.Value {
5890 case ssa.OpConst8, ssa.OpConst16, ssa.OpConst32, ssa.OpConst64:
5896 // do a size-appropriate check for zero
5897 cmp := s.newValue2(s.ssaOp(ir.ONE, n.Type()), types.Types[types.TBOOL], b, s.zeroVal(n.Type()))
5898 s.check(cmp, ir.Syms.Panicdivide)
5900 return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
5903 // rtcall issues a call to the given runtime function fn with the listed args.
5904 // Returns a slice of results of the given result types.
5905 // The call is added to the end of the current block.
5906 // If returns is false, the block is marked as an exit block.
5907 func (s *state) rtcall(fn *obj.LSym, returns bool, results []*types.Type, args ...*ssa.Value) []*ssa.Value {
5909 // Write args to the stack
5910 off := base.Ctxt.Arch.FixedFrameSize
5911 var callArgs []*ssa.Value
5912 var callArgTypes []*types.Type
5914 for _, arg := range args {
5916 off = types.RoundUp(off, t.Alignment())
5918 callArgs = append(callArgs, arg)
5919 callArgTypes = append(callArgTypes, t)
5922 off = types.RoundUp(off, int64(types.RegSize))
5926 aux := ssa.StaticAuxCall(fn, s.f.ABIDefault.ABIAnalyzeTypes(callArgTypes, results))
5927 callArgs = append(callArgs, s.mem())
5928 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5929 call.AddArgs(callArgs...)
5930 s.vars[memVar] = s.newValue1I(ssa.OpSelectN, types.TypeMem, int64(len(results)), call)
5935 b.Kind = ssa.BlockExit
5937 call.AuxInt = off - base.Ctxt.Arch.FixedFrameSize
5938 if len(results) > 0 {
5939 s.Fatalf("panic call can't have results")
5945 res := make([]*ssa.Value, len(results))
5946 for i, t := range results {
5947 off = types.RoundUp(off, t.Alignment())
5948 res[i] = s.resultOfCall(call, int64(i), t)
5951 off = types.RoundUp(off, int64(types.PtrSize))
5953 // Remember how much callee stack space we needed.
5959 // do *left = right for type t.
5960 func (s *state) storeType(t *types.Type, left, right *ssa.Value, skip skipMask, leftIsStmt bool) {
5961 s.instrument(t, left, instrumentWrite)
5963 if skip == 0 && (!t.HasPointers() || ssa.IsStackAddr(left)) {
5964 // Known to not have write barrier. Store the whole type.
5965 s.vars[memVar] = s.newValue3Apos(ssa.OpStore, types.TypeMem, t, left, right, s.mem(), leftIsStmt)
5969 // store scalar fields first, so write barrier stores for
5970 // pointer fields can be grouped together, and scalar values
5971 // don't need to be live across the write barrier call.
5972 // TODO: if the writebarrier pass knows how to reorder stores,
5973 // we can do a single store here as long as skip==0.
5974 s.storeTypeScalars(t, left, right, skip)
5975 if skip&skipPtr == 0 && t.HasPointers() {
5976 s.storeTypePtrs(t, left, right)
5980 // do *left = right for all scalar (non-pointer) parts of t.
5981 func (s *state) storeTypeScalars(t *types.Type, left, right *ssa.Value, skip skipMask) {
5983 case t.IsBoolean() || t.IsInteger() || t.IsFloat() || t.IsComplex():
5984 s.store(t, left, right)
5985 case t.IsPtrShaped():
5986 if t.IsPtr() && t.Elem().NotInHeap() {
5987 s.store(t, left, right) // see issue 42032
5989 // otherwise, no scalar fields.
5991 if skip&skipLen != 0 {
5994 len := s.newValue1(ssa.OpStringLen, types.Types[types.TINT], right)
5995 lenAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, s.config.PtrSize, left)
5996 s.store(types.Types[types.TINT], lenAddr, len)
5998 if skip&skipLen == 0 {
5999 len := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], right)
6000 lenAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, s.config.PtrSize, left)
6001 s.store(types.Types[types.TINT], lenAddr, len)
6003 if skip&skipCap == 0 {
6004 cap := s.newValue1(ssa.OpSliceCap, types.Types[types.TINT], right)
6005 capAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, 2*s.config.PtrSize, left)
6006 s.store(types.Types[types.TINT], capAddr, cap)
6008 case t.IsInterface():
6009 // itab field doesn't need a write barrier (even though it is a pointer).
6010 itab := s.newValue1(ssa.OpITab, s.f.Config.Types.BytePtr, right)
6011 s.store(types.Types[types.TUINTPTR], left, itab)
6014 for i := 0; i < n; i++ {
6015 ft := t.FieldType(i)
6016 addr := s.newValue1I(ssa.OpOffPtr, ft.PtrTo(), t.FieldOff(i), left)
6017 val := s.newValue1I(ssa.OpStructSelect, ft, int64(i), right)
6018 s.storeTypeScalars(ft, addr, val, 0)
6020 case t.IsArray() && t.NumElem() == 0:
6022 case t.IsArray() && t.NumElem() == 1:
6023 s.storeTypeScalars(t.Elem(), left, s.newValue1I(ssa.OpArraySelect, t.Elem(), 0, right), 0)
6025 s.Fatalf("bad write barrier type %v", t)
6029 // do *left = right for all pointer parts of t.
6030 func (s *state) storeTypePtrs(t *types.Type, left, right *ssa.Value) {
6032 case t.IsPtrShaped():
6033 if t.IsPtr() && t.Elem().NotInHeap() {
6034 break // see issue 42032
6036 s.store(t, left, right)
6038 ptr := s.newValue1(ssa.OpStringPtr, s.f.Config.Types.BytePtr, right)
6039 s.store(s.f.Config.Types.BytePtr, left, ptr)
6041 elType := types.NewPtr(t.Elem())
6042 ptr := s.newValue1(ssa.OpSlicePtr, elType, right)
6043 s.store(elType, left, ptr)
6044 case t.IsInterface():
6045 // itab field is treated as a scalar.
6046 idata := s.newValue1(ssa.OpIData, s.f.Config.Types.BytePtr, right)
6047 idataAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.BytePtrPtr, s.config.PtrSize, left)
6048 s.store(s.f.Config.Types.BytePtr, idataAddr, idata)
6051 for i := 0; i < n; i++ {
6052 ft := t.FieldType(i)
6053 if !ft.HasPointers() {
6056 addr := s.newValue1I(ssa.OpOffPtr, ft.PtrTo(), t.FieldOff(i), left)
6057 val := s.newValue1I(ssa.OpStructSelect, ft, int64(i), right)
6058 s.storeTypePtrs(ft, addr, val)
6060 case t.IsArray() && t.NumElem() == 0:
6062 case t.IsArray() && t.NumElem() == 1:
6063 s.storeTypePtrs(t.Elem(), left, s.newValue1I(ssa.OpArraySelect, t.Elem(), 0, right))
6065 s.Fatalf("bad write barrier type %v", t)
6069 // putArg evaluates n for the purpose of passing it as an argument to a function and returns the value for the call.
6070 func (s *state) putArg(n ir.Node, t *types.Type) *ssa.Value {
6073 a = s.newValue2(ssa.OpDereference, t, s.addr(n), s.mem())
6080 func (s *state) storeArgWithBase(n ir.Node, t *types.Type, base *ssa.Value, off int64) {
6081 pt := types.NewPtr(t)
6084 // Use special routine that avoids allocation on duplicate offsets.
6085 addr = s.constOffPtrSP(pt, off)
6087 addr = s.newValue1I(ssa.OpOffPtr, pt, off, base)
6097 s.storeType(t, addr, a, 0, false)
6100 // slice computes the slice v[i:j:k] and returns ptr, len, and cap of result.
6101 // i,j,k may be nil, in which case they are set to their default value.
6102 // v may be a slice, string or pointer to an array.
6103 func (s *state) slice(v, i, j, k *ssa.Value, bounded bool) (p, l, c *ssa.Value) {
6105 var ptr, len, cap *ssa.Value
6108 ptr = s.newValue1(ssa.OpSlicePtr, types.NewPtr(t.Elem()), v)
6109 len = s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], v)
6110 cap = s.newValue1(ssa.OpSliceCap, types.Types[types.TINT], v)
6112 ptr = s.newValue1(ssa.OpStringPtr, types.NewPtr(types.Types[types.TUINT8]), v)
6113 len = s.newValue1(ssa.OpStringLen, types.Types[types.TINT], v)
6116 if !t.Elem().IsArray() {
6117 s.Fatalf("bad ptr to array in slice %v\n", t)
6120 ptr = s.newValue1(ssa.OpCopy, types.NewPtr(t.Elem().Elem()), v)
6121 len = s.constInt(types.Types[types.TINT], t.Elem().NumElem())
6124 s.Fatalf("bad type in slice %v\n", t)
6127 // Set default values
6129 i = s.constInt(types.Types[types.TINT], 0)
6140 // Panic if slice indices are not in bounds.
6141 // Make sure we check these in reverse order so that we're always
6142 // comparing against a value known to be nonnegative. See issue 28797.
6145 kind := ssa.BoundsSlice3Alen
6147 kind = ssa.BoundsSlice3Acap
6149 k = s.boundsCheck(k, cap, kind, bounded)
6152 j = s.boundsCheck(j, k, ssa.BoundsSlice3B, bounded)
6154 i = s.boundsCheck(i, j, ssa.BoundsSlice3C, bounded)
6157 kind := ssa.BoundsSliceAlen
6159 kind = ssa.BoundsSliceAcap
6161 j = s.boundsCheck(j, k, kind, bounded)
6163 i = s.boundsCheck(i, j, ssa.BoundsSliceB, bounded)
6166 // Word-sized integer operations.
6167 subOp := s.ssaOp(ir.OSUB, types.Types[types.TINT])
6168 mulOp := s.ssaOp(ir.OMUL, types.Types[types.TINT])
6169 andOp := s.ssaOp(ir.OAND, types.Types[types.TINT])
6171 // Calculate the length (rlen) and capacity (rcap) of the new slice.
6172 // For strings the capacity of the result is unimportant. However,
6173 // we use rcap to test if we've generated a zero-length slice.
6174 // Use length of strings for that.
6175 rlen := s.newValue2(subOp, types.Types[types.TINT], j, i)
6177 if j != k && !t.IsString() {
6178 rcap = s.newValue2(subOp, types.Types[types.TINT], k, i)
6181 if (i.Op == ssa.OpConst64 || i.Op == ssa.OpConst32) && i.AuxInt == 0 {
6182 // No pointer arithmetic necessary.
6183 return ptr, rlen, rcap
6186 // Calculate the base pointer (rptr) for the new slice.
6188 // Generate the following code assuming that indexes are in bounds.
6189 // The masking is to make sure that we don't generate a slice
6190 // that points to the next object in memory. We cannot just set
6191 // the pointer to nil because then we would create a nil slice or
6196 // rptr = ptr + (mask(rcap) & (i * stride))
6198 // Where mask(x) is 0 if x==0 and -1 if x>0 and stride is the width
6199 // of the element type.
6200 stride := s.constInt(types.Types[types.TINT], ptr.Type.Elem().Size())
6202 // The delta is the number of bytes to offset ptr by.
6203 delta := s.newValue2(mulOp, types.Types[types.TINT], i, stride)
6205 // If we're slicing to the point where the capacity is zero,
6206 // zero out the delta.
6207 mask := s.newValue1(ssa.OpSlicemask, types.Types[types.TINT], rcap)
6208 delta = s.newValue2(andOp, types.Types[types.TINT], delta, mask)
6210 // Compute rptr = ptr + delta.
6211 rptr := s.newValue2(ssa.OpAddPtr, ptr.Type, ptr, delta)
6213 return rptr, rlen, rcap
6216 type u642fcvtTab struct {
6217 leq, cvt2F, and, rsh, or, add ssa.Op
6218 one func(*state, *types.Type, int64) *ssa.Value
6221 var u64_f64 = u642fcvtTab{
6223 cvt2F: ssa.OpCvt64to64F,
6225 rsh: ssa.OpRsh64Ux64,
6228 one: (*state).constInt64,
6231 var u64_f32 = u642fcvtTab{
6233 cvt2F: ssa.OpCvt64to32F,
6235 rsh: ssa.OpRsh64Ux64,
6238 one: (*state).constInt64,
6241 func (s *state) uint64Tofloat64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6242 return s.uint64Tofloat(&u64_f64, n, x, ft, tt)
6245 func (s *state) uint64Tofloat32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6246 return s.uint64Tofloat(&u64_f32, n, x, ft, tt)
6249 func (s *state) uint64Tofloat(cvttab *u642fcvtTab, n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6251 // result = (floatY) x
6253 // y = uintX(x) ; y = x & 1
6254 // z = uintX(x) ; z = z >> 1
6256 // result = floatY(z)
6257 // result = result + result
6260 // Code borrowed from old code generator.
6261 // What's going on: large 64-bit "unsigned" looks like
6262 // negative number to hardware's integer-to-float
6263 // conversion. However, because the mantissa is only
6264 // 63 bits, we don't need the LSB, so instead we do an
6265 // unsigned right shift (divide by two), convert, and
6266 // double. However, before we do that, we need to be
6267 // sure that we do not lose a "1" if that made the
6268 // difference in the resulting rounding. Therefore, we
6269 // preserve it, and OR (not ADD) it back in. The case
6270 // that matters is when the eleven discarded bits are
6271 // equal to 10000000001; that rounds up, and the 1 cannot
6272 // be lost else it would round down if the LSB of the
6273 // candidate mantissa is 0.
6274 cmp := s.newValue2(cvttab.leq, types.Types[types.TBOOL], s.zeroVal(ft), x)
6276 b.Kind = ssa.BlockIf
6278 b.Likely = ssa.BranchLikely
6280 bThen := s.f.NewBlock(ssa.BlockPlain)
6281 bElse := s.f.NewBlock(ssa.BlockPlain)
6282 bAfter := s.f.NewBlock(ssa.BlockPlain)
6286 a0 := s.newValue1(cvttab.cvt2F, tt, x)
6289 bThen.AddEdgeTo(bAfter)
6293 one := cvttab.one(s, ft, 1)
6294 y := s.newValue2(cvttab.and, ft, x, one)
6295 z := s.newValue2(cvttab.rsh, ft, x, one)
6296 z = s.newValue2(cvttab.or, ft, z, y)
6297 a := s.newValue1(cvttab.cvt2F, tt, z)
6298 a1 := s.newValue2(cvttab.add, tt, a, a)
6301 bElse.AddEdgeTo(bAfter)
6303 s.startBlock(bAfter)
6304 return s.variable(n, n.Type())
6307 type u322fcvtTab struct {
6308 cvtI2F, cvtF2F ssa.Op
6311 var u32_f64 = u322fcvtTab{
6312 cvtI2F: ssa.OpCvt32to64F,
6316 var u32_f32 = u322fcvtTab{
6317 cvtI2F: ssa.OpCvt32to32F,
6318 cvtF2F: ssa.OpCvt64Fto32F,
6321 func (s *state) uint32Tofloat64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6322 return s.uint32Tofloat(&u32_f64, n, x, ft, tt)
6325 func (s *state) uint32Tofloat32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6326 return s.uint32Tofloat(&u32_f32, n, x, ft, tt)
6329 func (s *state) uint32Tofloat(cvttab *u322fcvtTab, n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6331 // result = floatY(x)
6333 // result = floatY(float64(x) + (1<<32))
6335 cmp := s.newValue2(ssa.OpLeq32, types.Types[types.TBOOL], s.zeroVal(ft), x)
6337 b.Kind = ssa.BlockIf
6339 b.Likely = ssa.BranchLikely
6341 bThen := s.f.NewBlock(ssa.BlockPlain)
6342 bElse := s.f.NewBlock(ssa.BlockPlain)
6343 bAfter := s.f.NewBlock(ssa.BlockPlain)
6347 a0 := s.newValue1(cvttab.cvtI2F, tt, x)
6350 bThen.AddEdgeTo(bAfter)
6354 a1 := s.newValue1(ssa.OpCvt32to64F, types.Types[types.TFLOAT64], x)
6355 twoToThe32 := s.constFloat64(types.Types[types.TFLOAT64], float64(1<<32))
6356 a2 := s.newValue2(ssa.OpAdd64F, types.Types[types.TFLOAT64], a1, twoToThe32)
6357 a3 := s.newValue1(cvttab.cvtF2F, tt, a2)
6361 bElse.AddEdgeTo(bAfter)
6363 s.startBlock(bAfter)
6364 return s.variable(n, n.Type())
6367 // referenceTypeBuiltin generates code for the len/cap builtins for maps and channels.
6368 func (s *state) referenceTypeBuiltin(n *ir.UnaryExpr, x *ssa.Value) *ssa.Value {
6369 if !n.X.Type().IsMap() && !n.X.Type().IsChan() {
6370 s.Fatalf("node must be a map or a channel")
6376 // return *((*int)n)
6378 // return *(((*int)n)+1)
6381 nilValue := s.constNil(types.Types[types.TUINTPTR])
6382 cmp := s.newValue2(ssa.OpEqPtr, types.Types[types.TBOOL], x, nilValue)
6384 b.Kind = ssa.BlockIf
6386 b.Likely = ssa.BranchUnlikely
6388 bThen := s.f.NewBlock(ssa.BlockPlain)
6389 bElse := s.f.NewBlock(ssa.BlockPlain)
6390 bAfter := s.f.NewBlock(ssa.BlockPlain)
6392 // length/capacity of a nil map/chan is zero
6395 s.vars[n] = s.zeroVal(lenType)
6397 bThen.AddEdgeTo(bAfter)
6403 // length is stored in the first word for map/chan
6404 s.vars[n] = s.load(lenType, x)
6406 // capacity is stored in the second word for chan
6407 sw := s.newValue1I(ssa.OpOffPtr, lenType.PtrTo(), lenType.Size(), x)
6408 s.vars[n] = s.load(lenType, sw)
6410 s.Fatalf("op must be OLEN or OCAP")
6413 bElse.AddEdgeTo(bAfter)
6415 s.startBlock(bAfter)
6416 return s.variable(n, lenType)
6419 type f2uCvtTab struct {
6420 ltf, cvt2U, subf, or ssa.Op
6421 floatValue func(*state, *types.Type, float64) *ssa.Value
6422 intValue func(*state, *types.Type, int64) *ssa.Value
6426 var f32_u64 = f2uCvtTab{
6428 cvt2U: ssa.OpCvt32Fto64,
6431 floatValue: (*state).constFloat32,
6432 intValue: (*state).constInt64,
6436 var f64_u64 = f2uCvtTab{
6438 cvt2U: ssa.OpCvt64Fto64,
6441 floatValue: (*state).constFloat64,
6442 intValue: (*state).constInt64,
6446 var f32_u32 = f2uCvtTab{
6448 cvt2U: ssa.OpCvt32Fto32,
6451 floatValue: (*state).constFloat32,
6452 intValue: func(s *state, t *types.Type, v int64) *ssa.Value { return s.constInt32(t, int32(v)) },
6456 var f64_u32 = f2uCvtTab{
6458 cvt2U: ssa.OpCvt64Fto32,
6461 floatValue: (*state).constFloat64,
6462 intValue: func(s *state, t *types.Type, v int64) *ssa.Value { return s.constInt32(t, int32(v)) },
6466 func (s *state) float32ToUint64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6467 return s.floatToUint(&f32_u64, n, x, ft, tt)
6469 func (s *state) float64ToUint64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6470 return s.floatToUint(&f64_u64, n, x, ft, tt)
6473 func (s *state) float32ToUint32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6474 return s.floatToUint(&f32_u32, n, x, ft, tt)
6477 func (s *state) float64ToUint32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6478 return s.floatToUint(&f64_u32, n, x, ft, tt)
6481 func (s *state) floatToUint(cvttab *f2uCvtTab, n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6482 // cutoff:=1<<(intY_Size-1)
6483 // if x < floatX(cutoff) {
6484 // result = uintY(x)
6486 // y = x - floatX(cutoff)
6488 // result = z | -(cutoff)
6490 cutoff := cvttab.floatValue(s, ft, float64(cvttab.cutoff))
6491 cmp := s.newValue2(cvttab.ltf, types.Types[types.TBOOL], x, cutoff)
6493 b.Kind = ssa.BlockIf
6495 b.Likely = ssa.BranchLikely
6497 bThen := s.f.NewBlock(ssa.BlockPlain)
6498 bElse := s.f.NewBlock(ssa.BlockPlain)
6499 bAfter := s.f.NewBlock(ssa.BlockPlain)
6503 a0 := s.newValue1(cvttab.cvt2U, tt, x)
6506 bThen.AddEdgeTo(bAfter)
6510 y := s.newValue2(cvttab.subf, ft, x, cutoff)
6511 y = s.newValue1(cvttab.cvt2U, tt, y)
6512 z := cvttab.intValue(s, tt, int64(-cvttab.cutoff))
6513 a1 := s.newValue2(cvttab.or, tt, y, z)
6516 bElse.AddEdgeTo(bAfter)
6518 s.startBlock(bAfter)
6519 return s.variable(n, n.Type())
6522 // dottype generates SSA for a type assertion node.
6523 // commaok indicates whether to panic or return a bool.
6524 // If commaok is false, resok will be nil.
6525 func (s *state) dottype(n *ir.TypeAssertExpr, commaok bool) (res, resok *ssa.Value) {
6526 iface := s.expr(n.X) // input interface
6527 target := s.reflectType(n.Type()) // target type
6528 var targetItab *ssa.Value
6530 targetItab = s.expr(n.ITab)
6532 return s.dottype1(n.Pos(), n.X.Type(), n.Type(), iface, nil, target, targetItab, commaok, n.Descriptor)
6535 func (s *state) dynamicDottype(n *ir.DynamicTypeAssertExpr, commaok bool) (res, resok *ssa.Value) {
6536 iface := s.expr(n.X)
6537 var source, target, targetItab *ssa.Value
6538 if n.SrcRType != nil {
6539 source = s.expr(n.SrcRType)
6541 if !n.X.Type().IsEmptyInterface() && !n.Type().IsInterface() {
6542 byteptr := s.f.Config.Types.BytePtr
6543 targetItab = s.expr(n.ITab)
6544 // TODO(mdempsky): Investigate whether compiling n.RType could be
6545 // better than loading itab.typ.
6546 target = s.load(byteptr, s.newValue1I(ssa.OpOffPtr, byteptr, int64(types.PtrSize), targetItab)) // itab.typ
6548 target = s.expr(n.RType)
6550 return s.dottype1(n.Pos(), n.X.Type(), n.Type(), iface, source, target, targetItab, commaok, nil)
6553 // dottype1 implements a x.(T) operation. iface is the argument (x), dst is the type we're asserting to (T)
6554 // and src is the type we're asserting from.
6555 // source is the *runtime._type of src
6556 // target is the *runtime._type of dst.
6557 // If src is a nonempty interface and dst is not an interface, targetItab is an itab representing (dst, src). Otherwise it is nil.
6558 // commaok is true if the caller wants a boolean success value. Otherwise, the generated code panics if the conversion fails.
6559 // descriptor is a compiler-allocated internal/abi.TypeAssert whose address is passed to runtime.typeAssert when
6560 // the target type is a compile-time-known non-empty interface. It may be nil.
6561 func (s *state) dottype1(pos src.XPos, src, dst *types.Type, iface, source, target, targetItab *ssa.Value, commaok bool, descriptor *obj.LSym) (res, resok *ssa.Value) {
6562 typs := s.f.Config.Types
6563 byteptr := typs.BytePtr
6564 if dst.IsInterface() {
6565 if dst.IsEmptyInterface() {
6566 // Converting to an empty interface.
6567 // Input could be an empty or nonempty interface.
6568 if base.Debug.TypeAssert > 0 {
6569 base.WarnfAt(pos, "type assertion inlined")
6572 // Get itab/type field from input.
6573 itab := s.newValue1(ssa.OpITab, byteptr, iface)
6574 // Conversion succeeds iff that field is not nil.
6575 cond := s.newValue2(ssa.OpNeqPtr, types.Types[types.TBOOL], itab, s.constNil(byteptr))
6577 if src.IsEmptyInterface() && commaok {
6578 // Converting empty interface to empty interface with ,ok is just a nil check.
6582 // Branch on nilness.
6584 b.Kind = ssa.BlockIf
6586 b.Likely = ssa.BranchLikely
6587 bOk := s.f.NewBlock(ssa.BlockPlain)
6588 bFail := s.f.NewBlock(ssa.BlockPlain)
6593 // On failure, panic by calling panicnildottype.
6595 s.rtcall(ir.Syms.Panicnildottype, false, nil, target)
6597 // On success, return (perhaps modified) input interface.
6599 if src.IsEmptyInterface() {
6600 res = iface // Use input interface unchanged.
6603 // Load type out of itab, build interface with existing idata.
6604 off := s.newValue1I(ssa.OpOffPtr, byteptr, int64(types.PtrSize), itab)
6605 typ := s.load(byteptr, off)
6606 idata := s.newValue1(ssa.OpIData, byteptr, iface)
6607 res = s.newValue2(ssa.OpIMake, dst, typ, idata)
6612 // nonempty -> empty
6613 // Need to load type from itab
6614 off := s.newValue1I(ssa.OpOffPtr, byteptr, int64(types.PtrSize), itab)
6615 s.vars[typVar] = s.load(byteptr, off)
6618 // itab is nil, might as well use that as the nil result.
6620 s.vars[typVar] = itab
6624 bEnd := s.f.NewBlock(ssa.BlockPlain)
6626 bFail.AddEdgeTo(bEnd)
6628 idata := s.newValue1(ssa.OpIData, byteptr, iface)
6629 res = s.newValue2(ssa.OpIMake, dst, s.variable(typVar, byteptr), idata)
6631 delete(s.vars, typVar) // no practical effect, just to indicate typVar is no longer live.
6634 // converting to a nonempty interface needs a runtime call.
6635 if base.Debug.TypeAssert > 0 {
6636 base.WarnfAt(pos, "type assertion not inlined")
6639 itab := s.newValue1(ssa.OpITab, byteptr, iface)
6640 data := s.newValue1(ssa.OpIData, types.Types[types.TUNSAFEPTR], iface)
6642 // First, check for nil.
6643 bNil := s.f.NewBlock(ssa.BlockPlain)
6644 bNonNil := s.f.NewBlock(ssa.BlockPlain)
6645 bMerge := s.f.NewBlock(ssa.BlockPlain)
6646 cond := s.newValue2(ssa.OpNeqPtr, types.Types[types.TBOOL], itab, s.constNil(byteptr))
6648 b.Kind = ssa.BlockIf
6650 b.Likely = ssa.BranchLikely
6651 b.AddEdgeTo(bNonNil)
6656 s.vars[typVar] = itab // which will be nil
6660 // Panic if input is nil.
6661 s.rtcall(ir.Syms.Panicnildottype, false, nil, target)
6664 // Get typ, possibly by loading out of itab.
6665 s.startBlock(bNonNil)
6667 if !src.IsEmptyInterface() {
6668 typ = s.load(byteptr, s.newValue1I(ssa.OpOffPtr, byteptr, int64(types.PtrSize), itab))
6671 // Check the cache first.
6673 if descriptor != nil {
6674 d = s.newValue1A(ssa.OpAddr, byteptr, descriptor, s.sb)
6675 if base.Flag.N == 0 && rtabi.UseInterfaceSwitchCache(Arch.LinkArch.Name) {
6676 // Note: we can only use the cache if we have the right atomic load instruction.
6677 // Double-check that here.
6678 if _, ok := intrinsics[intrinsicKey{Arch.LinkArch.Arch, "runtime/internal/atomic", "Loadp"}]; !ok {
6679 s.Fatalf("atomic load not available")
6681 // Pick right size ops.
6682 var mul, and, add, zext ssa.Op
6683 if s.config.PtrSize == 4 {
6692 zext = ssa.OpZeroExt32to64
6695 loopHead := s.f.NewBlock(ssa.BlockPlain)
6696 loopBody := s.f.NewBlock(ssa.BlockPlain)
6697 cacheHit := s.f.NewBlock(ssa.BlockPlain)
6698 cacheMiss := s.f.NewBlock(ssa.BlockPlain)
6700 // Load cache pointer out of descriptor, with an atomic load so
6701 // we ensure that we see a fully written cache.
6702 atomicLoad := s.newValue2(ssa.OpAtomicLoadPtr, types.NewTuple(typs.BytePtr, types.TypeMem), d, s.mem())
6703 cache := s.newValue1(ssa.OpSelect0, typs.BytePtr, atomicLoad)
6704 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, atomicLoad)
6706 // Load hash from type.
6707 hash := s.newValue2(ssa.OpLoad, typs.UInt32, s.newValue1I(ssa.OpOffPtr, typs.UInt32Ptr, 2*s.config.PtrSize, typ), s.mem())
6708 hash = s.newValue1(zext, typs.Uintptr, hash)
6709 s.vars[hashVar] = hash
6710 // Load mask from cache.
6711 mask := s.newValue2(ssa.OpLoad, typs.Uintptr, cache, s.mem())
6712 // Jump to loop head.
6714 b.AddEdgeTo(loopHead)
6716 // At loop head, get pointer to the cache entry.
6717 // e := &cache.Entries[hash&mask]
6718 s.startBlock(loopHead)
6719 idx := s.newValue2(and, typs.Uintptr, s.variable(hashVar, typs.Uintptr), mask)
6720 idx = s.newValue2(mul, typs.Uintptr, idx, s.uintptrConstant(uint64(2*s.config.PtrSize)))
6721 idx = s.newValue2(add, typs.Uintptr, idx, s.uintptrConstant(uint64(s.config.PtrSize)))
6722 e := s.newValue2(ssa.OpAddPtr, typs.UintptrPtr, cache, idx)
6724 s.vars[hashVar] = s.newValue2(add, typs.Uintptr, s.variable(hashVar, typs.Uintptr), s.uintptrConstant(1))
6726 // Look for a cache hit.
6727 // if e.Typ == typ { goto hit }
6728 eTyp := s.newValue2(ssa.OpLoad, typs.Uintptr, e, s.mem())
6729 cmp1 := s.newValue2(ssa.OpEqPtr, typs.Bool, typ, eTyp)
6731 b.Kind = ssa.BlockIf
6733 b.AddEdgeTo(cacheHit)
6734 b.AddEdgeTo(loopBody)
6736 // Look for an empty entry, the tombstone for this hash table.
6737 // if e.Typ == nil { goto miss }
6738 s.startBlock(loopBody)
6739 cmp2 := s.newValue2(ssa.OpEqPtr, typs.Bool, eTyp, s.constNil(typs.BytePtr))
6741 b.Kind = ssa.BlockIf
6743 b.AddEdgeTo(cacheMiss)
6744 b.AddEdgeTo(loopHead)
6746 // On a hit, load the data fields of the cache entry.
6748 s.startBlock(cacheHit)
6749 eItab := s.newValue2(ssa.OpLoad, typs.BytePtr, s.newValue1I(ssa.OpOffPtr, typs.BytePtrPtr, s.config.PtrSize, e), s.mem())
6750 s.vars[typVar] = eItab
6754 // On a miss, call into the runtime to get the answer.
6755 s.startBlock(cacheMiss)
6759 // Call into runtime to get itab for result.
6760 if descriptor != nil {
6761 itab = s.rtcall(ir.Syms.TypeAssert, true, []*types.Type{byteptr}, d, typ)[0]
6765 fn = ir.Syms.AssertE2I2
6767 fn = ir.Syms.AssertE2I
6769 itab = s.rtcall(fn, true, []*types.Type{byteptr}, target, typ)[0]
6771 s.vars[typVar] = itab
6775 // Build resulting interface.
6776 s.startBlock(bMerge)
6777 itab = s.variable(typVar, byteptr)
6780 ok = s.newValue2(ssa.OpNeqPtr, types.Types[types.TBOOL], itab, s.constNil(byteptr))
6782 return s.newValue2(ssa.OpIMake, dst, itab, data), ok
6785 if base.Debug.TypeAssert > 0 {
6786 base.WarnfAt(pos, "type assertion inlined")
6789 // Converting to a concrete type.
6790 direct := types.IsDirectIface(dst)
6791 itab := s.newValue1(ssa.OpITab, byteptr, iface) // type word of interface
6792 if base.Debug.TypeAssert > 0 {
6793 base.WarnfAt(pos, "type assertion inlined")
6795 var wantedFirstWord *ssa.Value
6796 if src.IsEmptyInterface() {
6797 // Looking for pointer to target type.
6798 wantedFirstWord = target
6800 // Looking for pointer to itab for target type and source interface.
6801 wantedFirstWord = targetItab
6804 var tmp ir.Node // temporary for use with large types
6805 var addr *ssa.Value // address of tmp
6806 if commaok && !ssa.CanSSA(dst) {
6807 // unSSAable type, use temporary.
6808 // TODO: get rid of some of these temporaries.
6809 tmp, addr = s.temp(pos, dst)
6812 cond := s.newValue2(ssa.OpEqPtr, types.Types[types.TBOOL], itab, wantedFirstWord)
6814 b.Kind = ssa.BlockIf
6816 b.Likely = ssa.BranchLikely
6818 bOk := s.f.NewBlock(ssa.BlockPlain)
6819 bFail := s.f.NewBlock(ssa.BlockPlain)
6824 // on failure, panic by calling panicdottype
6828 taddr = s.reflectType(src)
6830 if src.IsEmptyInterface() {
6831 s.rtcall(ir.Syms.PanicdottypeE, false, nil, itab, target, taddr)
6833 s.rtcall(ir.Syms.PanicdottypeI, false, nil, itab, target, taddr)
6836 // on success, return data from interface
6839 return s.newValue1(ssa.OpIData, dst, iface), nil
6841 p := s.newValue1(ssa.OpIData, types.NewPtr(dst), iface)
6842 return s.load(dst, p), nil
6845 // commaok is the more complicated case because we have
6846 // a control flow merge point.
6847 bEnd := s.f.NewBlock(ssa.BlockPlain)
6848 // Note that we need a new valVar each time (unlike okVar where we can
6849 // reuse the variable) because it might have a different type every time.
6850 valVar := ssaMarker("val")
6852 // type assertion succeeded
6856 s.vars[valVar] = s.newValue1(ssa.OpIData, dst, iface)
6858 p := s.newValue1(ssa.OpIData, types.NewPtr(dst), iface)
6859 s.vars[valVar] = s.load(dst, p)
6862 p := s.newValue1(ssa.OpIData, types.NewPtr(dst), iface)
6863 s.move(dst, addr, p)
6865 s.vars[okVar] = s.constBool(true)
6869 // type assertion failed
6872 s.vars[valVar] = s.zeroVal(dst)
6876 s.vars[okVar] = s.constBool(false)
6878 bFail.AddEdgeTo(bEnd)
6883 res = s.variable(valVar, dst)
6884 delete(s.vars, valVar) // no practical effect, just to indicate typVar is no longer live.
6886 res = s.load(dst, addr)
6888 resok = s.variable(okVar, types.Types[types.TBOOL])
6889 delete(s.vars, okVar) // ditto
6893 // temp allocates a temp of type t at position pos
6894 func (s *state) temp(pos src.XPos, t *types.Type) (*ir.Name, *ssa.Value) {
6895 tmp := typecheck.TempAt(pos, s.curfn, t)
6896 if t.HasPointers() {
6897 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, tmp, s.mem())
6903 // variable returns the value of a variable at the current location.
6904 func (s *state) variable(n ir.Node, t *types.Type) *ssa.Value {
6914 if s.curBlock == s.f.Entry {
6915 // No variable should be live at entry.
6916 s.f.Fatalf("value %v (%v) incorrectly live at entry", n, v)
6918 // Make a FwdRef, which records a value that's live on block input.
6919 // We'll find the matching definition as part of insertPhis.
6920 v = s.newValue0A(ssa.OpFwdRef, t, fwdRefAux{N: n})
6922 if n.Op() == ir.ONAME {
6923 s.addNamedValue(n.(*ir.Name), v)
6928 func (s *state) mem() *ssa.Value {
6929 return s.variable(memVar, types.TypeMem)
6932 func (s *state) addNamedValue(n *ir.Name, v *ssa.Value) {
6933 if n.Class == ir.Pxxx {
6934 // Don't track our marker nodes (memVar etc.).
6937 if ir.IsAutoTmp(n) {
6938 // Don't track temporary variables.
6941 if n.Class == ir.PPARAMOUT {
6942 // Don't track named output values. This prevents return values
6943 // from being assigned too early. See #14591 and #14762. TODO: allow this.
6946 loc := ssa.LocalSlot{N: n, Type: n.Type(), Off: 0}
6947 values, ok := s.f.NamedValues[loc]
6949 s.f.Names = append(s.f.Names, &loc)
6950 s.f.CanonicalLocalSlots[loc] = &loc
6952 s.f.NamedValues[loc] = append(values, v)
6955 // Branch is an unresolved branch.
6956 type Branch struct {
6957 P *obj.Prog // branch instruction
6958 B *ssa.Block // target
6961 // State contains state needed during Prog generation.
6967 // Branches remembers all the branch instructions we've seen
6968 // and where they would like to go.
6971 // JumpTables remembers all the jump tables we've seen.
6972 JumpTables []*ssa.Block
6974 // bstart remembers where each block starts (indexed by block ID)
6977 maxarg int64 // largest frame size for arguments to calls made by the function
6979 // Map from GC safe points to liveness index, generated by
6980 // liveness analysis.
6981 livenessMap liveness.Map
6983 // partLiveArgs includes arguments that may be partially live, for which we
6984 // need to generate instructions that spill the argument registers.
6985 partLiveArgs map[*ir.Name]bool
6987 // lineRunStart records the beginning of the current run of instructions
6988 // within a single block sharing the same line number
6989 // Used to move statement marks to the beginning of such runs.
6990 lineRunStart *obj.Prog
6992 // wasm: The number of values on the WebAssembly stack. This is only used as a safeguard.
6993 OnWasmStackSkipped int
6996 func (s *State) FuncInfo() *obj.FuncInfo {
6997 return s.pp.CurFunc.LSym.Func()
7000 // Prog appends a new Prog.
7001 func (s *State) Prog(as obj.As) *obj.Prog {
7003 if objw.LosesStmtMark(as) {
7006 // Float a statement start to the beginning of any same-line run.
7007 // lineRunStart is reset at block boundaries, which appears to work well.
7008 if s.lineRunStart == nil || s.lineRunStart.Pos.Line() != p.Pos.Line() {
7010 } else if p.Pos.IsStmt() == src.PosIsStmt {
7011 s.lineRunStart.Pos = s.lineRunStart.Pos.WithIsStmt()
7012 p.Pos = p.Pos.WithNotStmt()
7017 // Pc returns the current Prog.
7018 func (s *State) Pc() *obj.Prog {
7022 // SetPos sets the current source position.
7023 func (s *State) SetPos(pos src.XPos) {
7027 // Br emits a single branch instruction and returns the instruction.
7028 // Not all architectures need the returned instruction, but otherwise
7029 // the boilerplate is common to all.
7030 func (s *State) Br(op obj.As, target *ssa.Block) *obj.Prog {
7032 p.To.Type = obj.TYPE_BRANCH
7033 s.Branches = append(s.Branches, Branch{P: p, B: target})
7037 // DebugFriendlySetPosFrom adjusts Pos.IsStmt subject to heuristics
7038 // that reduce "jumpy" line number churn when debugging.
7039 // Spill/fill/copy instructions from the register allocator,
7040 // phi functions, and instructions with a no-pos position
7041 // are examples of instructions that can cause churn.
7042 func (s *State) DebugFriendlySetPosFrom(v *ssa.Value) {
7044 case ssa.OpPhi, ssa.OpCopy, ssa.OpLoadReg, ssa.OpStoreReg:
7045 // These are not statements
7046 s.SetPos(v.Pos.WithNotStmt())
7049 if p != src.NoXPos {
7050 // If the position is defined, update the position.
7051 // Also convert default IsStmt to NotStmt; only
7052 // explicit statement boundaries should appear
7053 // in the generated code.
7054 if p.IsStmt() != src.PosIsStmt {
7055 if s.pp.Pos.IsStmt() == src.PosIsStmt && s.pp.Pos.SameFileAndLine(p) {
7056 // If s.pp.Pos already has a statement mark, then it was set here (below) for
7057 // the previous value. If an actual instruction had been emitted for that
7058 // value, then the statement mark would have been reset. Since the statement
7059 // mark of s.pp.Pos was not reset, this position (file/line) still needs a
7060 // statement mark on an instruction. If file and line for this value are
7061 // the same as the previous value, then the first instruction for this
7062 // value will work to take the statement mark. Return early to avoid
7063 // resetting the statement mark.
7065 // The reset of s.pp.Pos occurs in (*Progs).Prog() -- if it emits
7066 // an instruction, and the instruction's statement mark was set,
7067 // and it is not one of the LosesStmtMark instructions,
7068 // then Prog() resets the statement mark on the (*Progs).Pos.
7072 // Calls use the pos attached to v, but copy the statement mark from State
7076 s.SetPos(s.pp.Pos.WithNotStmt())
7081 // emit argument info (locations on stack) for traceback.
7082 func emitArgInfo(e *ssafn, f *ssa.Func, pp *objw.Progs) {
7083 ft := e.curfn.Type()
7084 if ft.NumRecvs() == 0 && ft.NumParams() == 0 {
7088 x := EmitArgInfo(e.curfn, f.OwnAux.ABIInfo())
7089 x.Set(obj.AttrContentAddressable, true)
7090 e.curfn.LSym.Func().ArgInfo = x
7092 // Emit a funcdata pointing at the arg info data.
7093 p := pp.Prog(obj.AFUNCDATA)
7094 p.From.SetConst(rtabi.FUNCDATA_ArgInfo)
7095 p.To.Type = obj.TYPE_MEM
7096 p.To.Name = obj.NAME_EXTERN
7100 // emit argument info (locations on stack) of f for traceback.
7101 func EmitArgInfo(f *ir.Func, abiInfo *abi.ABIParamResultInfo) *obj.LSym {
7102 x := base.Ctxt.Lookup(fmt.Sprintf("%s.arginfo%d", f.LSym.Name, f.ABI))
7103 // NOTE: do not set ContentAddressable here. This may be referenced from
7104 // assembly code by name (in this case f is a declaration).
7105 // Instead, set it in emitArgInfo above.
7107 PtrSize := int64(types.PtrSize)
7108 uintptrTyp := types.Types[types.TUINTPTR]
7110 isAggregate := func(t *types.Type) bool {
7111 return t.IsStruct() || t.IsArray() || t.IsComplex() || t.IsInterface() || t.IsString() || t.IsSlice()
7114 // Populate the data.
7115 // The data is a stream of bytes, which contains the offsets and sizes of the
7116 // non-aggregate arguments or non-aggregate fields/elements of aggregate-typed
7117 // arguments, along with special "operators". Specifically,
7118 // - for each non-aggrgate arg/field/element, its offset from FP (1 byte) and
7120 // - special operators:
7121 // - 0xff - end of sequence
7122 // - 0xfe - print { (at the start of an aggregate-typed argument)
7123 // - 0xfd - print } (at the end of an aggregate-typed argument)
7124 // - 0xfc - print ... (more args/fields/elements)
7125 // - 0xfb - print _ (offset too large)
7126 // These constants need to be in sync with runtime.traceback.go:printArgs.
7132 _offsetTooLarge = 0xfb
7133 _special = 0xf0 // above this are operators, below this are ordinary offsets
7137 limit = 10 // print no more than 10 args/components
7138 maxDepth = 5 // no more than 5 layers of nesting
7140 // maxLen is a (conservative) upper bound of the byte stream length. For
7141 // each arg/component, it has no more than 2 bytes of data (size, offset),
7142 // and no more than one {, }, ... at each level (it cannot have both the
7143 // data and ... unless it is the last one, just be conservative). Plus 1
7145 maxLen = (maxDepth*3+2)*limit + 1
7150 writebyte := func(o uint8) { wOff = objw.Uint8(x, wOff, o) }
7152 // Write one non-aggrgate arg/field/element.
7153 write1 := func(sz, offset int64) {
7154 if offset >= _special {
7155 writebyte(_offsetTooLarge)
7157 writebyte(uint8(offset))
7158 writebyte(uint8(sz))
7163 // Visit t recursively and write it out.
7164 // Returns whether to continue visiting.
7165 var visitType func(baseOffset int64, t *types.Type, depth int) bool
7166 visitType = func(baseOffset int64, t *types.Type, depth int) bool {
7168 writebyte(_dotdotdot)
7171 if !isAggregate(t) {
7172 write1(t.Size(), baseOffset)
7175 writebyte(_startAgg)
7177 if depth >= maxDepth {
7178 writebyte(_dotdotdot)
7184 case t.IsInterface(), t.IsString():
7185 _ = visitType(baseOffset, uintptrTyp, depth) &&
7186 visitType(baseOffset+PtrSize, uintptrTyp, depth)
7188 _ = visitType(baseOffset, uintptrTyp, depth) &&
7189 visitType(baseOffset+PtrSize, uintptrTyp, depth) &&
7190 visitType(baseOffset+PtrSize*2, uintptrTyp, depth)
7192 _ = visitType(baseOffset, types.FloatForComplex(t), depth) &&
7193 visitType(baseOffset+t.Size()/2, types.FloatForComplex(t), depth)
7195 if t.NumElem() == 0 {
7196 n++ // {} counts as a component
7199 for i := int64(0); i < t.NumElem(); i++ {
7200 if !visitType(baseOffset, t.Elem(), depth) {
7203 baseOffset += t.Elem().Size()
7206 if t.NumFields() == 0 {
7207 n++ // {} counts as a component
7210 for _, field := range t.Fields() {
7211 if !visitType(baseOffset+field.Offset, field.Type, depth) {
7221 if strings.Contains(f.LSym.Name, "[") {
7222 // Skip the dictionary argument - it is implicit and the user doesn't need to see it.
7226 for _, a := range abiInfo.InParams()[start:] {
7227 if !visitType(a.FrameOffset(abiInfo), a.Type, 0) {
7233 base.Fatalf("ArgInfo too large")
7239 // for wrapper, emit info of wrapped function.
7240 func emitWrappedFuncInfo(e *ssafn, pp *objw.Progs) {
7241 if base.Ctxt.Flag_linkshared {
7242 // Relative reference (SymPtrOff) to another shared object doesn't work.
7247 wfn := e.curfn.WrappedFunc
7252 wsym := wfn.Linksym()
7253 x := base.Ctxt.LookupInit(fmt.Sprintf("%s.wrapinfo", wsym.Name), func(x *obj.LSym) {
7254 objw.SymPtrOff(x, 0, wsym)
7255 x.Set(obj.AttrContentAddressable, true)
7257 e.curfn.LSym.Func().WrapInfo = x
7259 // Emit a funcdata pointing at the wrap info data.
7260 p := pp.Prog(obj.AFUNCDATA)
7261 p.From.SetConst(rtabi.FUNCDATA_WrapInfo)
7262 p.To.Type = obj.TYPE_MEM
7263 p.To.Name = obj.NAME_EXTERN
7267 // genssa appends entries to pp for each instruction in f.
7268 func genssa(f *ssa.Func, pp *objw.Progs) {
7270 s.ABI = f.OwnAux.Fn.ABI()
7272 e := f.Frontend().(*ssafn)
7274 s.livenessMap, s.partLiveArgs = liveness.Compute(e.curfn, f, e.stkptrsize, pp)
7275 emitArgInfo(e, f, pp)
7276 argLiveBlockMap, argLiveValueMap := liveness.ArgLiveness(e.curfn, f, pp)
7278 openDeferInfo := e.curfn.LSym.Func().OpenCodedDeferInfo
7279 if openDeferInfo != nil {
7280 // This function uses open-coded defers -- write out the funcdata
7281 // info that we computed at the end of genssa.
7282 p := pp.Prog(obj.AFUNCDATA)
7283 p.From.SetConst(rtabi.FUNCDATA_OpenCodedDeferInfo)
7284 p.To.Type = obj.TYPE_MEM
7285 p.To.Name = obj.NAME_EXTERN
7286 p.To.Sym = openDeferInfo
7289 emitWrappedFuncInfo(e, pp)
7291 // Remember where each block starts.
7292 s.bstart = make([]*obj.Prog, f.NumBlocks())
7294 var progToValue map[*obj.Prog]*ssa.Value
7295 var progToBlock map[*obj.Prog]*ssa.Block
7296 var valueToProgAfter []*obj.Prog // The first Prog following computation of a value v; v is visible at this point.
7297 gatherPrintInfo := f.PrintOrHtmlSSA || ssa.GenssaDump[f.Name]
7298 if gatherPrintInfo {
7299 progToValue = make(map[*obj.Prog]*ssa.Value, f.NumValues())
7300 progToBlock = make(map[*obj.Prog]*ssa.Block, f.NumBlocks())
7301 f.Logf("genssa %s\n", f.Name)
7302 progToBlock[s.pp.Next] = f.Blocks[0]
7305 if base.Ctxt.Flag_locationlists {
7306 if cap(f.Cache.ValueToProgAfter) < f.NumValues() {
7307 f.Cache.ValueToProgAfter = make([]*obj.Prog, f.NumValues())
7309 valueToProgAfter = f.Cache.ValueToProgAfter[:f.NumValues()]
7310 for i := range valueToProgAfter {
7311 valueToProgAfter[i] = nil
7315 // If the very first instruction is not tagged as a statement,
7316 // debuggers may attribute it to previous function in program.
7317 firstPos := src.NoXPos
7318 for _, v := range f.Entry.Values {
7319 if v.Pos.IsStmt() == src.PosIsStmt && v.Op != ssa.OpArg && v.Op != ssa.OpArgIntReg && v.Op != ssa.OpArgFloatReg && v.Op != ssa.OpLoadReg && v.Op != ssa.OpStoreReg {
7321 v.Pos = firstPos.WithDefaultStmt()
7326 // inlMarks has an entry for each Prog that implements an inline mark.
7327 // It maps from that Prog to the global inlining id of the inlined body
7328 // which should unwind to this Prog's location.
7329 var inlMarks map[*obj.Prog]int32
7330 var inlMarkList []*obj.Prog
7332 // inlMarksByPos maps from a (column 1) source position to the set of
7333 // Progs that are in the set above and have that source position.
7334 var inlMarksByPos map[src.XPos][]*obj.Prog
7336 var argLiveIdx int = -1 // argument liveness info index
7338 // Emit basic blocks
7339 for i, b := range f.Blocks {
7340 s.bstart[b.ID] = s.pp.Next
7341 s.lineRunStart = nil
7342 s.SetPos(s.pp.Pos.WithNotStmt()) // It needs a non-empty Pos, but cannot be a statement boundary (yet).
7344 if idx, ok := argLiveBlockMap[b.ID]; ok && idx != argLiveIdx {
7346 p := s.pp.Prog(obj.APCDATA)
7347 p.From.SetConst(rtabi.PCDATA_ArgLiveIndex)
7348 p.To.SetConst(int64(idx))
7351 // Emit values in block
7352 Arch.SSAMarkMoves(&s, b)
7353 for _, v := range b.Values {
7355 s.DebugFriendlySetPosFrom(v)
7357 if v.Op.ResultInArg0() && v.ResultReg() != v.Args[0].Reg() {
7358 v.Fatalf("input[0] and output not in same register %s", v.LongString())
7363 // memory arg needs no code
7365 // input args need no code
7366 case ssa.OpSP, ssa.OpSB:
7368 case ssa.OpSelect0, ssa.OpSelect1, ssa.OpSelectN, ssa.OpMakeResult:
7371 // nothing to do when there's a g register,
7372 // and checkLower complains if there's not
7373 case ssa.OpVarDef, ssa.OpVarLive, ssa.OpKeepAlive, ssa.OpWBend:
7374 // nothing to do; already used by liveness
7378 // nothing to do; no-op conversion for liveness
7379 if v.Args[0].Reg() != v.Reg() {
7380 v.Fatalf("OpConvert should be a no-op: %s; %s", v.Args[0].LongString(), v.LongString())
7383 p := Arch.Ginsnop(s.pp)
7384 if inlMarks == nil {
7385 inlMarks = map[*obj.Prog]int32{}
7386 inlMarksByPos = map[src.XPos][]*obj.Prog{}
7388 inlMarks[p] = v.AuxInt32()
7389 inlMarkList = append(inlMarkList, p)
7390 pos := v.Pos.AtColumn1()
7391 inlMarksByPos[pos] = append(inlMarksByPos[pos], p)
7392 firstPos = src.NoXPos
7395 // Special case for first line in function; move it to the start (which cannot be a register-valued instruction)
7396 if firstPos != src.NoXPos && v.Op != ssa.OpArgIntReg && v.Op != ssa.OpArgFloatReg && v.Op != ssa.OpLoadReg && v.Op != ssa.OpStoreReg {
7398 firstPos = src.NoXPos
7400 // Attach this safe point to the next
7402 s.pp.NextLive = s.livenessMap.Get(v)
7403 s.pp.NextUnsafe = s.livenessMap.GetUnsafe(v)
7405 // let the backend handle it
7406 Arch.SSAGenValue(&s, v)
7409 if idx, ok := argLiveValueMap[v.ID]; ok && idx != argLiveIdx {
7411 p := s.pp.Prog(obj.APCDATA)
7412 p.From.SetConst(rtabi.PCDATA_ArgLiveIndex)
7413 p.To.SetConst(int64(idx))
7416 if base.Ctxt.Flag_locationlists {
7417 valueToProgAfter[v.ID] = s.pp.Next
7420 if gatherPrintInfo {
7421 for ; x != s.pp.Next; x = x.Link {
7426 // If this is an empty infinite loop, stick a hardware NOP in there so that debuggers are less confused.
7427 if s.bstart[b.ID] == s.pp.Next && len(b.Succs) == 1 && b.Succs[0].Block() == b {
7428 p := Arch.Ginsnop(s.pp)
7429 p.Pos = p.Pos.WithIsStmt()
7430 if b.Pos == src.NoXPos {
7431 b.Pos = p.Pos // It needs a file, otherwise a no-file non-zero line causes confusion. See #35652.
7432 if b.Pos == src.NoXPos {
7433 b.Pos = pp.Text.Pos // Sometimes p.Pos is empty. See #35695.
7436 b.Pos = b.Pos.WithBogusLine() // Debuggers are not good about infinite loops, force a change in line number
7439 // Set unsafe mark for any end-of-block generated instructions
7440 // (normally, conditional or unconditional branches).
7441 // This is particularly important for empty blocks, as there
7442 // are no values to inherit the unsafe mark from.
7443 s.pp.NextUnsafe = s.livenessMap.GetUnsafeBlock(b)
7445 // Emit control flow instructions for block
7447 if i < len(f.Blocks)-1 && base.Flag.N == 0 {
7448 // If -N, leave next==nil so every block with successors
7449 // ends in a JMP (except call blocks - plive doesn't like
7450 // select{send,recv} followed by a JMP call). Helps keep
7451 // line numbers for otherwise empty blocks.
7452 next = f.Blocks[i+1]
7456 Arch.SSAGenBlock(&s, b, next)
7457 if gatherPrintInfo {
7458 for ; x != s.pp.Next; x = x.Link {
7463 if f.Blocks[len(f.Blocks)-1].Kind == ssa.BlockExit {
7464 // We need the return address of a panic call to
7465 // still be inside the function in question. So if
7466 // it ends in a call which doesn't return, add a
7467 // nop (which will never execute) after the call.
7470 if openDeferInfo != nil {
7471 // When doing open-coded defers, generate a disconnected call to
7472 // deferreturn and a return. This will be used to during panic
7473 // recovery to unwind the stack and return back to the runtime.
7474 s.pp.NextLive = s.livenessMap.DeferReturn
7475 p := pp.Prog(obj.ACALL)
7476 p.To.Type = obj.TYPE_MEM
7477 p.To.Name = obj.NAME_EXTERN
7478 p.To.Sym = ir.Syms.Deferreturn
7480 // Load results into registers. So when a deferred function
7481 // recovers a panic, it will return to caller with right results.
7482 // The results are already in memory, because they are not SSA'd
7483 // when the function has defers (see canSSAName).
7484 for _, o := range f.OwnAux.ABIInfo().OutParams() {
7486 rts, offs := o.RegisterTypesAndOffsets()
7487 for i := range o.Registers {
7488 Arch.LoadRegResult(&s, f, rts[i], ssa.ObjRegForAbiReg(o.Registers[i], f.Config), n, offs[i])
7495 if inlMarks != nil {
7498 // We have some inline marks. Try to find other instructions we're
7499 // going to emit anyway, and use those instructions instead of the
7501 for p := pp.Text; p != nil; p = p.Link {
7502 if p.As == obj.ANOP || p.As == obj.AFUNCDATA || p.As == obj.APCDATA || p.As == obj.ATEXT || p.As == obj.APCALIGN || Arch.LinkArch.Family == sys.Wasm {
7503 // Don't use 0-sized instructions as inline marks, because we need
7504 // to identify inline mark instructions by pc offset.
7505 // (Some of these instructions are sometimes zero-sized, sometimes not.
7506 // We must not use anything that even might be zero-sized.)
7507 // TODO: are there others?
7510 if _, ok := inlMarks[p]; ok {
7511 // Don't use inline marks themselves. We don't know
7512 // whether they will be zero-sized or not yet.
7515 if p.As == obj.ACALL || p.As == obj.ADUFFCOPY || p.As == obj.ADUFFZERO {
7518 pos := p.Pos.AtColumn1()
7519 s := inlMarksByPos[pos]
7523 for _, m := range s {
7524 // We found an instruction with the same source position as
7525 // some of the inline marks.
7526 // Use this instruction instead.
7527 p.Pos = p.Pos.WithIsStmt() // promote position to a statement
7528 pp.CurFunc.LSym.Func().AddInlMark(p, inlMarks[m])
7529 // Make the inline mark a real nop, so it doesn't generate any code.
7535 delete(inlMarksByPos, pos)
7537 // Any unmatched inline marks now need to be added to the inlining tree (and will generate a nop instruction).
7538 for _, p := range inlMarkList {
7539 if p.As != obj.ANOP {
7540 pp.CurFunc.LSym.Func().AddInlMark(p, inlMarks[p])
7544 if e.stksize == 0 && !hasCall {
7545 // Frameless leaf function. It doesn't need any preamble,
7546 // so make sure its first instruction isn't from an inlined callee.
7547 // If it is, add a nop at the start of the function with a position
7548 // equal to the start of the function.
7549 // This ensures that runtime.FuncForPC(uintptr(reflect.ValueOf(fn).Pointer())).Name()
7550 // returns the right answer. See issue 58300.
7551 for p := pp.Text; p != nil; p = p.Link {
7552 if p.As == obj.AFUNCDATA || p.As == obj.APCDATA || p.As == obj.ATEXT || p.As == obj.ANOP {
7555 if base.Ctxt.PosTable.Pos(p.Pos).Base().InliningIndex() >= 0 {
7556 // Make a real (not 0-sized) nop.
7557 nop := Arch.Ginsnop(pp)
7558 nop.Pos = e.curfn.Pos().WithIsStmt()
7560 // Unfortunately, Ginsnop puts the instruction at the
7561 // end of the list. Move it up to just before p.
7563 // Unlink from the current list.
7564 for x := pp.Text; x != nil; x = x.Link {
7570 // Splice in right before p.
7571 for x := pp.Text; x != nil; x = x.Link {
7584 if base.Ctxt.Flag_locationlists {
7585 var debugInfo *ssa.FuncDebug
7586 debugInfo = e.curfn.DebugInfo.(*ssa.FuncDebug)
7587 if e.curfn.ABI == obj.ABIInternal && base.Flag.N != 0 {
7588 ssa.BuildFuncDebugNoOptimized(base.Ctxt, f, base.Debug.LocationLists > 1, StackOffset, debugInfo)
7590 ssa.BuildFuncDebug(base.Ctxt, f, base.Debug.LocationLists, StackOffset, debugInfo)
7593 idToIdx := make([]int, f.NumBlocks())
7594 for i, b := range f.Blocks {
7597 // Note that at this moment, Prog.Pc is a sequence number; it's
7598 // not a real PC until after assembly, so this mapping has to
7600 debugInfo.GetPC = func(b, v ssa.ID) int64 {
7602 case ssa.BlockStart.ID:
7603 if b == f.Entry.ID {
7604 return 0 // Start at the very beginning, at the assembler-generated prologue.
7605 // this should only happen for function args (ssa.OpArg)
7608 case ssa.BlockEnd.ID:
7609 blk := f.Blocks[idToIdx[b]]
7610 nv := len(blk.Values)
7611 return valueToProgAfter[blk.Values[nv-1].ID].Pc
7612 case ssa.FuncEnd.ID:
7613 return e.curfn.LSym.Size
7615 return valueToProgAfter[v].Pc
7620 // Resolve branches, and relax DefaultStmt into NotStmt
7621 for _, br := range s.Branches {
7622 br.P.To.SetTarget(s.bstart[br.B.ID])
7623 if br.P.Pos.IsStmt() != src.PosIsStmt {
7624 br.P.Pos = br.P.Pos.WithNotStmt()
7625 } else if v0 := br.B.FirstPossibleStmtValue(); v0 != nil && v0.Pos.Line() == br.P.Pos.Line() && v0.Pos.IsStmt() == src.PosIsStmt {
7626 br.P.Pos = br.P.Pos.WithNotStmt()
7631 // Resolve jump table destinations.
7632 for _, jt := range s.JumpTables {
7633 // Convert from *Block targets to *Prog targets.
7634 targets := make([]*obj.Prog, len(jt.Succs))
7635 for i, e := range jt.Succs {
7636 targets[i] = s.bstart[e.Block().ID]
7638 // Add to list of jump tables to be resolved at assembly time.
7639 // The assembler converts from *Prog entries to absolute addresses
7640 // once it knows instruction byte offsets.
7641 fi := pp.CurFunc.LSym.Func()
7642 fi.JumpTables = append(fi.JumpTables, obj.JumpTable{Sym: jt.Aux.(*obj.LSym), Targets: targets})
7645 if e.log { // spew to stdout
7647 for p := pp.Text; p != nil; p = p.Link {
7648 if p.Pos.IsKnown() && p.InnermostFilename() != filename {
7649 filename = p.InnermostFilename()
7650 f.Logf("# %s\n", filename)
7654 if v, ok := progToValue[p]; ok {
7656 } else if b, ok := progToBlock[p]; ok {
7659 s = " " // most value and branch strings are 2-3 characters long
7661 f.Logf(" %-6s\t%.5d (%s)\t%s\n", s, p.Pc, p.InnermostLineNumber(), p.InstructionString())
7664 if f.HTMLWriter != nil { // spew to ssa.html
7665 var buf strings.Builder
7666 buf.WriteString("<code>")
7667 buf.WriteString("<dl class=\"ssa-gen\">")
7669 for p := pp.Text; p != nil; p = p.Link {
7670 // Don't spam every line with the file name, which is often huge.
7671 // Only print changes, and "unknown" is not a change.
7672 if p.Pos.IsKnown() && p.InnermostFilename() != filename {
7673 filename = p.InnermostFilename()
7674 buf.WriteString("<dt class=\"ssa-prog-src\"></dt><dd class=\"ssa-prog\">")
7675 buf.WriteString(html.EscapeString("# " + filename))
7676 buf.WriteString("</dd>")
7679 buf.WriteString("<dt class=\"ssa-prog-src\">")
7680 if v, ok := progToValue[p]; ok {
7681 buf.WriteString(v.HTML())
7682 } else if b, ok := progToBlock[p]; ok {
7683 buf.WriteString("<b>" + b.HTML() + "</b>")
7685 buf.WriteString("</dt>")
7686 buf.WriteString("<dd class=\"ssa-prog\">")
7687 fmt.Fprintf(&buf, "%.5d <span class=\"l%v line-number\">(%s)</span> %s", p.Pc, p.InnermostLineNumber(), p.InnermostLineNumberHTML(), html.EscapeString(p.InstructionString()))
7688 buf.WriteString("</dd>")
7690 buf.WriteString("</dl>")
7691 buf.WriteString("</code>")
7692 f.HTMLWriter.WriteColumn("genssa", "genssa", "ssa-prog", buf.String())
7694 if ssa.GenssaDump[f.Name] {
7695 fi := f.DumpFileForPhase("genssa")
7698 // inliningDiffers if any filename changes or if any line number except the innermost (last index) changes.
7699 inliningDiffers := func(a, b []src.Pos) bool {
7700 if len(a) != len(b) {
7704 if a[i].Filename() != b[i].Filename() {
7707 if i != len(a)-1 && a[i].Line() != b[i].Line() {
7714 var allPosOld []src.Pos
7715 var allPos []src.Pos
7717 for p := pp.Text; p != nil; p = p.Link {
7718 if p.Pos.IsKnown() {
7720 p.Ctxt.AllPos(p.Pos, func(pos src.Pos) { allPos = append(allPos, pos) })
7721 if inliningDiffers(allPos, allPosOld) {
7722 for _, pos := range allPos {
7723 fmt.Fprintf(fi, "# %s:%d\n", pos.Filename(), pos.Line())
7725 allPos, allPosOld = allPosOld, allPos // swap, not copy, so that they do not share slice storage.
7730 if v, ok := progToValue[p]; ok {
7732 } else if b, ok := progToBlock[p]; ok {
7735 s = " " // most value and branch strings are 2-3 characters long
7737 fmt.Fprintf(fi, " %-6s\t%.5d %s\t%s\n", s, p.Pc, ssa.StmtString(p.Pos), p.InstructionString())
7745 f.HTMLWriter.Close()
7749 func defframe(s *State, e *ssafn, f *ssa.Func) {
7752 s.maxarg = types.RoundUp(s.maxarg, e.stkalign)
7753 frame := s.maxarg + e.stksize
7754 if Arch.PadFrame != nil {
7755 frame = Arch.PadFrame(frame)
7758 // Fill in argument and frame size.
7759 pp.Text.To.Type = obj.TYPE_TEXTSIZE
7760 pp.Text.To.Val = int32(types.RoundUp(f.OwnAux.ArgWidth(), int64(types.RegSize)))
7761 pp.Text.To.Offset = frame
7765 // Insert code to spill argument registers if the named slot may be partially
7766 // live. That is, the named slot is considered live by liveness analysis,
7767 // (because a part of it is live), but we may not spill all parts into the
7768 // slot. This can only happen with aggregate-typed arguments that are SSA-able
7769 // and not address-taken (for non-SSA-able or address-taken arguments we always
7771 // Note: spilling is unnecessary in the -N/no-optimize case, since all values
7772 // will be considered non-SSAable and spilled up front.
7773 // TODO(register args) Make liveness more fine-grained to that partial spilling is okay.
7774 if f.OwnAux.ABIInfo().InRegistersUsed() != 0 && base.Flag.N == 0 {
7775 // First, see if it is already spilled before it may be live. Look for a spill
7776 // in the entry block up to the first safepoint.
7777 type nameOff struct {
7781 partLiveArgsSpilled := make(map[nameOff]bool)
7782 for _, v := range f.Entry.Values {
7786 if v.Op != ssa.OpStoreReg || v.Args[0].Op != ssa.OpArgIntReg {
7789 n, off := ssa.AutoVar(v)
7790 if n.Class != ir.PPARAM || n.Addrtaken() || !ssa.CanSSA(n.Type()) || !s.partLiveArgs[n] {
7793 partLiveArgsSpilled[nameOff{n, off}] = true
7796 // Then, insert code to spill registers if not already.
7797 for _, a := range f.OwnAux.ABIInfo().InParams() {
7799 if n == nil || n.Addrtaken() || !ssa.CanSSA(n.Type()) || !s.partLiveArgs[n] || len(a.Registers) <= 1 {
7802 rts, offs := a.RegisterTypesAndOffsets()
7803 for i := range a.Registers {
7804 if !rts[i].HasPointers() {
7807 if partLiveArgsSpilled[nameOff{n, offs[i]}] {
7808 continue // already spilled
7810 reg := ssa.ObjRegForAbiReg(a.Registers[i], f.Config)
7811 p = Arch.SpillArgReg(pp, p, f, rts[i], reg, n, offs[i])
7816 // Insert code to zero ambiguously live variables so that the
7817 // garbage collector only sees initialized values when it
7818 // looks for pointers.
7821 // Opaque state for backend to use. Current backends use it to
7822 // keep track of which helper registers have been zeroed.
7825 // Iterate through declarations. Autos are sorted in decreasing
7826 // frame offset order.
7827 for _, n := range e.curfn.Dcl {
7831 if n.Class != ir.PAUTO {
7832 e.Fatalf(n.Pos(), "needzero class %d", n.Class)
7834 if n.Type().Size()%int64(types.PtrSize) != 0 || n.FrameOffset()%int64(types.PtrSize) != 0 || n.Type().Size() == 0 {
7835 e.Fatalf(n.Pos(), "var %L has size %d offset %d", n, n.Type().Size(), n.Offset_)
7838 if lo != hi && n.FrameOffset()+n.Type().Size() >= lo-int64(2*types.RegSize) {
7839 // Merge with range we already have.
7840 lo = n.FrameOffset()
7845 p = Arch.ZeroRange(pp, p, frame+lo, hi-lo, &state)
7848 lo = n.FrameOffset()
7849 hi = lo + n.Type().Size()
7852 // Zero final range.
7853 Arch.ZeroRange(pp, p, frame+lo, hi-lo, &state)
7856 // For generating consecutive jump instructions to model a specific branching
7857 type IndexJump struct {
7862 func (s *State) oneJump(b *ssa.Block, jump *IndexJump) {
7863 p := s.Br(jump.Jump, b.Succs[jump.Index].Block())
7867 // CombJump generates combinational instructions (2 at present) for a block jump,
7868 // thereby the behaviour of non-standard condition codes could be simulated
7869 func (s *State) CombJump(b, next *ssa.Block, jumps *[2][2]IndexJump) {
7871 case b.Succs[0].Block():
7872 s.oneJump(b, &jumps[0][0])
7873 s.oneJump(b, &jumps[0][1])
7874 case b.Succs[1].Block():
7875 s.oneJump(b, &jumps[1][0])
7876 s.oneJump(b, &jumps[1][1])
7879 if b.Likely != ssa.BranchUnlikely {
7880 s.oneJump(b, &jumps[1][0])
7881 s.oneJump(b, &jumps[1][1])
7882 q = s.Br(obj.AJMP, b.Succs[1].Block())
7884 s.oneJump(b, &jumps[0][0])
7885 s.oneJump(b, &jumps[0][1])
7886 q = s.Br(obj.AJMP, b.Succs[0].Block())
7892 // AddAux adds the offset in the aux fields (AuxInt and Aux) of v to a.
7893 func AddAux(a *obj.Addr, v *ssa.Value) {
7894 AddAux2(a, v, v.AuxInt)
7896 func AddAux2(a *obj.Addr, v *ssa.Value, offset int64) {
7897 if a.Type != obj.TYPE_MEM && a.Type != obj.TYPE_ADDR {
7898 v.Fatalf("bad AddAux addr %v", a)
7900 // add integer offset
7903 // If no additional symbol offset, we're done.
7907 // Add symbol's offset from its base register.
7908 switch n := v.Aux.(type) {
7910 a.Name = obj.NAME_EXTERN
7913 a.Name = obj.NAME_EXTERN
7916 if n.Class == ir.PPARAM || (n.Class == ir.PPARAMOUT && !n.IsOutputParamInRegisters()) {
7917 a.Name = obj.NAME_PARAM
7919 a.Name = obj.NAME_AUTO
7922 a.Offset += n.FrameOffset()
7924 v.Fatalf("aux in %s not implemented %#v", v, v.Aux)
7928 // extendIndex extends v to a full int width.
7929 // panic with the given kind if v does not fit in an int (only on 32-bit archs).
7930 func (s *state) extendIndex(idx, len *ssa.Value, kind ssa.BoundsKind, bounded bool) *ssa.Value {
7931 size := idx.Type.Size()
7932 if size == s.config.PtrSize {
7935 if size > s.config.PtrSize {
7936 // truncate 64-bit indexes on 32-bit pointer archs. Test the
7937 // high word and branch to out-of-bounds failure if it is not 0.
7939 if idx.Type.IsSigned() {
7940 lo = s.newValue1(ssa.OpInt64Lo, types.Types[types.TINT], idx)
7942 lo = s.newValue1(ssa.OpInt64Lo, types.Types[types.TUINT], idx)
7944 if bounded || base.Flag.B != 0 {
7947 bNext := s.f.NewBlock(ssa.BlockPlain)
7948 bPanic := s.f.NewBlock(ssa.BlockExit)
7949 hi := s.newValue1(ssa.OpInt64Hi, types.Types[types.TUINT32], idx)
7950 cmp := s.newValue2(ssa.OpEq32, types.Types[types.TBOOL], hi, s.constInt32(types.Types[types.TUINT32], 0))
7951 if !idx.Type.IsSigned() {
7953 case ssa.BoundsIndex:
7954 kind = ssa.BoundsIndexU
7955 case ssa.BoundsSliceAlen:
7956 kind = ssa.BoundsSliceAlenU
7957 case ssa.BoundsSliceAcap:
7958 kind = ssa.BoundsSliceAcapU
7959 case ssa.BoundsSliceB:
7960 kind = ssa.BoundsSliceBU
7961 case ssa.BoundsSlice3Alen:
7962 kind = ssa.BoundsSlice3AlenU
7963 case ssa.BoundsSlice3Acap:
7964 kind = ssa.BoundsSlice3AcapU
7965 case ssa.BoundsSlice3B:
7966 kind = ssa.BoundsSlice3BU
7967 case ssa.BoundsSlice3C:
7968 kind = ssa.BoundsSlice3CU
7972 b.Kind = ssa.BlockIf
7974 b.Likely = ssa.BranchLikely
7978 s.startBlock(bPanic)
7979 mem := s.newValue4I(ssa.OpPanicExtend, types.TypeMem, int64(kind), hi, lo, len, s.mem())
7980 s.endBlock().SetControl(mem)
7986 // Extend value to the required size
7988 if idx.Type.IsSigned() {
7989 switch 10*size + s.config.PtrSize {
7991 op = ssa.OpSignExt8to32
7993 op = ssa.OpSignExt8to64
7995 op = ssa.OpSignExt16to32
7997 op = ssa.OpSignExt16to64
7999 op = ssa.OpSignExt32to64
8001 s.Fatalf("bad signed index extension %s", idx.Type)
8004 switch 10*size + s.config.PtrSize {
8006 op = ssa.OpZeroExt8to32
8008 op = ssa.OpZeroExt8to64
8010 op = ssa.OpZeroExt16to32
8012 op = ssa.OpZeroExt16to64
8014 op = ssa.OpZeroExt32to64
8016 s.Fatalf("bad unsigned index extension %s", idx.Type)
8019 return s.newValue1(op, types.Types[types.TINT], idx)
8022 // CheckLoweredPhi checks that regalloc and stackalloc correctly handled phi values.
8023 // Called during ssaGenValue.
8024 func CheckLoweredPhi(v *ssa.Value) {
8025 if v.Op != ssa.OpPhi {
8026 v.Fatalf("CheckLoweredPhi called with non-phi value: %v", v.LongString())
8028 if v.Type.IsMemory() {
8032 loc := f.RegAlloc[v.ID]
8033 for _, a := range v.Args {
8034 if aloc := f.RegAlloc[a.ID]; aloc != loc { // TODO: .Equal() instead?
8035 v.Fatalf("phi arg at different location than phi: %v @ %s, but arg %v @ %s\n%s\n", v, loc, a, aloc, v.Block.Func)
8040 // CheckLoweredGetClosurePtr checks that v is the first instruction in the function's entry block,
8041 // except for incoming in-register arguments.
8042 // The output of LoweredGetClosurePtr is generally hardwired to the correct register.
8043 // That register contains the closure pointer on closure entry.
8044 func CheckLoweredGetClosurePtr(v *ssa.Value) {
8045 entry := v.Block.Func.Entry
8046 if entry != v.Block {
8047 base.Fatalf("in %s, badly placed LoweredGetClosurePtr: %v %v", v.Block.Func.Name, v.Block, v)
8049 for _, w := range entry.Values {
8054 case ssa.OpArgIntReg, ssa.OpArgFloatReg:
8057 base.Fatalf("in %s, badly placed LoweredGetClosurePtr: %v %v", v.Block.Func.Name, v.Block, v)
8062 // CheckArgReg ensures that v is in the function's entry block.
8063 func CheckArgReg(v *ssa.Value) {
8064 entry := v.Block.Func.Entry
8065 if entry != v.Block {
8066 base.Fatalf("in %s, badly placed ArgIReg or ArgFReg: %v %v", v.Block.Func.Name, v.Block, v)
8070 func AddrAuto(a *obj.Addr, v *ssa.Value) {
8071 n, off := ssa.AutoVar(v)
8072 a.Type = obj.TYPE_MEM
8074 a.Reg = int16(Arch.REGSP)
8075 a.Offset = n.FrameOffset() + off
8076 if n.Class == ir.PPARAM || (n.Class == ir.PPARAMOUT && !n.IsOutputParamInRegisters()) {
8077 a.Name = obj.NAME_PARAM
8079 a.Name = obj.NAME_AUTO
8083 // Call returns a new CALL instruction for the SSA value v.
8084 // It uses PrepareCall to prepare the call.
8085 func (s *State) Call(v *ssa.Value) *obj.Prog {
8086 pPosIsStmt := s.pp.Pos.IsStmt() // The statement-ness fo the call comes from ssaGenState
8089 p := s.Prog(obj.ACALL)
8090 if pPosIsStmt == src.PosIsStmt {
8091 p.Pos = v.Pos.WithIsStmt()
8093 p.Pos = v.Pos.WithNotStmt()
8095 if sym, ok := v.Aux.(*ssa.AuxCall); ok && sym.Fn != nil {
8096 p.To.Type = obj.TYPE_MEM
8097 p.To.Name = obj.NAME_EXTERN
8100 // TODO(mdempsky): Can these differences be eliminated?
8101 switch Arch.LinkArch.Family {
8102 case sys.AMD64, sys.I386, sys.PPC64, sys.RISCV64, sys.S390X, sys.Wasm:
8103 p.To.Type = obj.TYPE_REG
8104 case sys.ARM, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64:
8105 p.To.Type = obj.TYPE_MEM
8107 base.Fatalf("unknown indirect call family")
8109 p.To.Reg = v.Args[0].Reg()
8114 // TailCall returns a new tail call instruction for the SSA value v.
8115 // It is like Call, but for a tail call.
8116 func (s *State) TailCall(v *ssa.Value) *obj.Prog {
8122 // PrepareCall prepares to emit a CALL instruction for v and does call-related bookkeeping.
8123 // It must be called immediately before emitting the actual CALL instruction,
8124 // since it emits PCDATA for the stack map at the call (calls are safe points).
8125 func (s *State) PrepareCall(v *ssa.Value) {
8126 idx := s.livenessMap.Get(v)
8127 if !idx.StackMapValid() {
8128 // See Liveness.hasStackMap.
8129 if sym, ok := v.Aux.(*ssa.AuxCall); !ok || !(sym.Fn == ir.Syms.WBZero || sym.Fn == ir.Syms.WBMove) {
8130 base.Fatalf("missing stack map index for %v", v.LongString())
8134 call, ok := v.Aux.(*ssa.AuxCall)
8137 // Record call graph information for nowritebarrierrec
8139 if nowritebarrierrecCheck != nil {
8140 nowritebarrierrecCheck.recordCall(s.pp.CurFunc, call.Fn, v.Pos)
8144 if s.maxarg < v.AuxInt {
8149 // UseArgs records the fact that an instruction needs a certain amount of
8150 // callee args space for its use.
8151 func (s *State) UseArgs(n int64) {
8157 // fieldIdx finds the index of the field referred to by the ODOT node n.
8158 func fieldIdx(n *ir.SelectorExpr) int {
8161 panic("ODOT's LHS is not a struct")
8164 for i, f := range t.Fields() {
8166 if f.Offset != n.Offset() {
8167 panic("field offset doesn't match")
8172 panic(fmt.Sprintf("can't find field in expr %v\n", n))
8174 // TODO: keep the result of this function somewhere in the ODOT Node
8175 // so we don't have to recompute it each time we need it.
8178 // ssafn holds frontend information about a function that the backend is processing.
8179 // It also exports a bunch of compiler services for the ssa backend.
8182 strings map[string]*obj.LSym // map from constant string to data symbols
8183 stksize int64 // stack size for current frame
8184 stkptrsize int64 // prefix of stack containing pointers
8186 // alignment for current frame.
8187 // NOTE: when stkalign > PtrSize, currently this only ensures the offsets of
8188 // objects in the stack frame are aligned. The stack pointer is still aligned
8192 log bool // print ssa debug to the stdout
8195 // StringData returns a symbol which
8196 // is the data component of a global string constant containing s.
8197 func (e *ssafn) StringData(s string) *obj.LSym {
8198 if aux, ok := e.strings[s]; ok {
8201 if e.strings == nil {
8202 e.strings = make(map[string]*obj.LSym)
8204 data := staticdata.StringSym(e.curfn.Pos(), s)
8209 // SplitSlot returns a slot representing the data of parent starting at offset.
8210 func (e *ssafn) SplitSlot(parent *ssa.LocalSlot, suffix string, offset int64, t *types.Type) ssa.LocalSlot {
8213 if node.Class != ir.PAUTO || node.Addrtaken() {
8214 // addressed things and non-autos retain their parents (i.e., cannot truly be split)
8215 return ssa.LocalSlot{N: node, Type: t, Off: parent.Off + offset}
8218 sym := &types.Sym{Name: node.Sym().Name + suffix, Pkg: types.LocalPkg}
8219 n := e.curfn.NewLocal(parent.N.Pos(), sym, t)
8221 n.SetEsc(ir.EscNever)
8223 return ssa.LocalSlot{N: n, Type: t, Off: 0, SplitOf: parent, SplitOffset: offset}
8226 // Logf logs a message from the compiler.
8227 func (e *ssafn) Logf(msg string, args ...interface{}) {
8229 fmt.Printf(msg, args...)
8233 func (e *ssafn) Log() bool {
8237 // Fatalf reports a compiler error and exits.
8238 func (e *ssafn) Fatalf(pos src.XPos, msg string, args ...interface{}) {
8240 nargs := append([]interface{}{ir.FuncName(e.curfn)}, args...)
8241 base.Fatalf("'%s': "+msg, nargs...)
8244 // Warnl reports a "warning", which is usually flag-triggered
8245 // logging output for the benefit of tests.
8246 func (e *ssafn) Warnl(pos src.XPos, fmt_ string, args ...interface{}) {
8247 base.WarnfAt(pos, fmt_, args...)
8250 func (e *ssafn) Debug_checknil() bool {
8251 return base.Debug.Nil != 0
8254 func (e *ssafn) UseWriteBarrier() bool {
8258 func (e *ssafn) Syslook(name string) *obj.LSym {
8260 case "goschedguarded":
8261 return ir.Syms.Goschedguarded
8262 case "writeBarrier":
8263 return ir.Syms.WriteBarrier
8265 return ir.Syms.WBZero
8267 return ir.Syms.WBMove
8268 case "cgoCheckMemmove":
8269 return ir.Syms.CgoCheckMemmove
8270 case "cgoCheckPtrWrite":
8271 return ir.Syms.CgoCheckPtrWrite
8273 e.Fatalf(src.NoXPos, "unknown Syslook func %v", name)
8277 func (e *ssafn) Func() *ir.Func {
8281 func clobberBase(n ir.Node) ir.Node {
8282 if n.Op() == ir.ODOT {
8283 n := n.(*ir.SelectorExpr)
8284 if n.X.Type().NumFields() == 1 {
8285 return clobberBase(n.X)
8288 if n.Op() == ir.OINDEX {
8289 n := n.(*ir.IndexExpr)
8290 if n.X.Type().IsArray() && n.X.Type().NumElem() == 1 {
8291 return clobberBase(n.X)
8297 // callTargetLSym returns the correct LSym to call 'callee' using its ABI.
8298 func callTargetLSym(callee *ir.Name) *obj.LSym {
8299 if callee.Func == nil {
8300 // TODO(austin): This happens in case of interface method I.M from imported package.
8301 // It's ABIInternal, and would be better if callee.Func was never nil and we didn't
8303 return callee.Linksym()
8306 return callee.LinksymABI(callee.Func.ABI)
8309 func min8(a, b int8) int8 {
8316 func max8(a, b int8) int8 {
8323 // deferStructFnField is the field index of _defer.fn.
8324 const deferStructFnField = 4
8326 var deferType *types.Type
8328 // deferstruct returns a type interchangeable with runtime._defer.
8329 // Make sure this stays in sync with runtime/runtime2.go:_defer.
8330 func deferstruct() *types.Type {
8331 if deferType != nil {
8335 makefield := func(name string, t *types.Type) *types.Field {
8336 sym := (*types.Pkg)(nil).Lookup(name)
8337 return types.NewField(src.NoXPos, sym, t)
8340 fields := []*types.Field{
8341 makefield("heap", types.Types[types.TBOOL]),
8342 makefield("rangefunc", types.Types[types.TBOOL]),
8343 makefield("sp", types.Types[types.TUINTPTR]),
8344 makefield("pc", types.Types[types.TUINTPTR]),
8345 // Note: the types here don't really matter. Defer structures
8346 // are always scanned explicitly during stack copying and GC,
8347 // so we make them uintptr type even though they are real pointers.
8348 makefield("fn", types.Types[types.TUINTPTR]),
8349 makefield("link", types.Types[types.TUINTPTR]),
8350 makefield("head", types.Types[types.TUINTPTR]),
8352 if name := fields[deferStructFnField].Sym.Name; name != "fn" {
8353 base.Fatalf("deferStructFnField is %q, not fn", name)
8356 n := ir.NewDeclNameAt(src.NoXPos, ir.OTYPE, ir.Pkgs.Runtime.Lookup("_defer"))
8357 typ := types.NewNamed(n)
8361 // build struct holding the above fields
8362 typ.SetUnderlying(types.NewStruct(fields))
8363 types.CalcStructSize(typ)
8369 // SpillSlotAddr uses LocalSlot information to initialize an obj.Addr
8370 // The resulting addr is used in a non-standard context -- in the prologue
8371 // of a function, before the frame has been constructed, so the standard
8372 // addressing for the parameters will be wrong.
8373 func SpillSlotAddr(spill ssa.Spill, baseReg int16, extraOffset int64) obj.Addr {
8375 Name: obj.NAME_NONE,
8378 Offset: spill.Offset + extraOffset,
8383 BoundsCheckFunc [ssa.BoundsKindCount]*obj.LSym
8384 ExtendCheckFunc [ssa.BoundsKindCount]*obj.LSym