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.
10 "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"
30 "cmd/internal/obj/x86"
36 var ssaConfig *ssa.Config
37 var ssaCaches []ssa.Cache
39 var ssaDump string // early copy of $GOSSAFUNC; the func name to dump output for
40 var ssaDir string // optional destination for ssa dump file
41 var ssaDumpStdout bool // whether to dump to stdout
42 var ssaDumpCFG string // generate CFGs for these phases
43 const ssaDumpFile = "ssa.html"
45 // ssaDumpInlined holds all inlined functions when ssaDump contains a function name.
46 var ssaDumpInlined []*ir.Func
48 func DumpInline(fn *ir.Func) {
49 if ssaDump != "" && ssaDump == ir.FuncName(fn) {
50 ssaDumpInlined = append(ssaDumpInlined, fn)
55 ssaDump = os.Getenv("GOSSAFUNC")
56 ssaDir = os.Getenv("GOSSADIR")
58 if strings.HasSuffix(ssaDump, "+") {
59 ssaDump = ssaDump[:len(ssaDump)-1]
62 spl := strings.Split(ssaDump, ":")
71 types_ := ssa.NewTypes()
77 // Generate a few pointer types that are uncommon in the frontend but common in the backend.
78 // Caching is disabled in the backend, so generating these here avoids allocations.
79 _ = types.NewPtr(types.Types[types.TINTER]) // *interface{}
80 _ = types.NewPtr(types.NewPtr(types.Types[types.TSTRING])) // **string
81 _ = types.NewPtr(types.NewSlice(types.Types[types.TINTER])) // *[]interface{}
82 _ = types.NewPtr(types.NewPtr(types.ByteType)) // **byte
83 _ = types.NewPtr(types.NewSlice(types.ByteType)) // *[]byte
84 _ = types.NewPtr(types.NewSlice(types.Types[types.TSTRING])) // *[]string
85 _ = types.NewPtr(types.NewPtr(types.NewPtr(types.Types[types.TUINT8]))) // ***uint8
86 _ = types.NewPtr(types.Types[types.TINT16]) // *int16
87 _ = types.NewPtr(types.Types[types.TINT64]) // *int64
88 _ = types.NewPtr(types.ErrorType) // *error
89 types.NewPtrCacheEnabled = false
90 ssaConfig = ssa.NewConfig(base.Ctxt.Arch.Name, *types_, base.Ctxt, base.Flag.N == 0, Arch.SoftFloat)
91 ssaConfig.Race = base.Flag.Race
92 ssaCaches = make([]ssa.Cache, base.Flag.LowerC)
94 // Set up some runtime functions we'll need to call.
95 ir.Syms.AssertE2I = typecheck.LookupRuntimeFunc("assertE2I")
96 ir.Syms.AssertE2I2 = typecheck.LookupRuntimeFunc("assertE2I2")
97 ir.Syms.AssertI2I = typecheck.LookupRuntimeFunc("assertI2I")
98 ir.Syms.AssertI2I2 = typecheck.LookupRuntimeFunc("assertI2I2")
99 ir.Syms.CheckPtrAlignment = typecheck.LookupRuntimeFunc("checkptrAlignment")
100 ir.Syms.Deferproc = typecheck.LookupRuntimeFunc("deferproc")
101 ir.Syms.DeferprocStack = typecheck.LookupRuntimeFunc("deferprocStack")
102 ir.Syms.Deferreturn = typecheck.LookupRuntimeFunc("deferreturn")
103 ir.Syms.Duffcopy = typecheck.LookupRuntimeFunc("duffcopy")
104 ir.Syms.Duffzero = typecheck.LookupRuntimeFunc("duffzero")
105 ir.Syms.GCWriteBarrier = typecheck.LookupRuntimeFunc("gcWriteBarrier")
106 ir.Syms.Goschedguarded = typecheck.LookupRuntimeFunc("goschedguarded")
107 ir.Syms.Growslice = typecheck.LookupRuntimeFunc("growslice")
108 ir.Syms.Msanread = typecheck.LookupRuntimeFunc("msanread")
109 ir.Syms.Msanwrite = typecheck.LookupRuntimeFunc("msanwrite")
110 ir.Syms.Msanmove = typecheck.LookupRuntimeFunc("msanmove")
111 ir.Syms.Asanread = typecheck.LookupRuntimeFunc("asanread")
112 ir.Syms.Asanwrite = typecheck.LookupRuntimeFunc("asanwrite")
113 ir.Syms.Newobject = typecheck.LookupRuntimeFunc("newobject")
114 ir.Syms.Newproc = typecheck.LookupRuntimeFunc("newproc")
115 ir.Syms.Panicdivide = typecheck.LookupRuntimeFunc("panicdivide")
116 ir.Syms.PanicdottypeE = typecheck.LookupRuntimeFunc("panicdottypeE")
117 ir.Syms.PanicdottypeI = typecheck.LookupRuntimeFunc("panicdottypeI")
118 ir.Syms.Panicnildottype = typecheck.LookupRuntimeFunc("panicnildottype")
119 ir.Syms.Panicoverflow = typecheck.LookupRuntimeFunc("panicoverflow")
120 ir.Syms.Panicshift = typecheck.LookupRuntimeFunc("panicshift")
121 ir.Syms.Raceread = typecheck.LookupRuntimeFunc("raceread")
122 ir.Syms.Racereadrange = typecheck.LookupRuntimeFunc("racereadrange")
123 ir.Syms.Racewrite = typecheck.LookupRuntimeFunc("racewrite")
124 ir.Syms.Racewriterange = typecheck.LookupRuntimeFunc("racewriterange")
125 ir.Syms.X86HasPOPCNT = typecheck.LookupRuntimeVar("x86HasPOPCNT") // bool
126 ir.Syms.X86HasSSE41 = typecheck.LookupRuntimeVar("x86HasSSE41") // bool
127 ir.Syms.X86HasFMA = typecheck.LookupRuntimeVar("x86HasFMA") // bool
128 ir.Syms.ARMHasVFPv4 = typecheck.LookupRuntimeVar("armHasVFPv4") // bool
129 ir.Syms.ARM64HasATOMICS = typecheck.LookupRuntimeVar("arm64HasATOMICS") // bool
130 ir.Syms.Staticuint64s = typecheck.LookupRuntimeVar("staticuint64s")
131 ir.Syms.Typedmemclr = typecheck.LookupRuntimeFunc("typedmemclr")
132 ir.Syms.Typedmemmove = typecheck.LookupRuntimeFunc("typedmemmove")
133 ir.Syms.Udiv = typecheck.LookupRuntimeVar("udiv") // asm func with special ABI
134 ir.Syms.WriteBarrier = typecheck.LookupRuntimeVar("writeBarrier") // struct { bool; ... }
135 ir.Syms.Zerobase = typecheck.LookupRuntimeVar("zerobase")
137 // asm funcs with special ABI
138 if base.Ctxt.Arch.Name == "amd64" {
139 GCWriteBarrierReg = map[int16]*obj.LSym{
140 x86.REG_AX: typecheck.LookupRuntimeFunc("gcWriteBarrier"),
141 x86.REG_CX: typecheck.LookupRuntimeFunc("gcWriteBarrierCX"),
142 x86.REG_DX: typecheck.LookupRuntimeFunc("gcWriteBarrierDX"),
143 x86.REG_BX: typecheck.LookupRuntimeFunc("gcWriteBarrierBX"),
144 x86.REG_BP: typecheck.LookupRuntimeFunc("gcWriteBarrierBP"),
145 x86.REG_SI: typecheck.LookupRuntimeFunc("gcWriteBarrierSI"),
146 x86.REG_R8: typecheck.LookupRuntimeFunc("gcWriteBarrierR8"),
147 x86.REG_R9: typecheck.LookupRuntimeFunc("gcWriteBarrierR9"),
151 if Arch.LinkArch.Family == sys.Wasm {
152 BoundsCheckFunc[ssa.BoundsIndex] = typecheck.LookupRuntimeFunc("goPanicIndex")
153 BoundsCheckFunc[ssa.BoundsIndexU] = typecheck.LookupRuntimeFunc("goPanicIndexU")
154 BoundsCheckFunc[ssa.BoundsSliceAlen] = typecheck.LookupRuntimeFunc("goPanicSliceAlen")
155 BoundsCheckFunc[ssa.BoundsSliceAlenU] = typecheck.LookupRuntimeFunc("goPanicSliceAlenU")
156 BoundsCheckFunc[ssa.BoundsSliceAcap] = typecheck.LookupRuntimeFunc("goPanicSliceAcap")
157 BoundsCheckFunc[ssa.BoundsSliceAcapU] = typecheck.LookupRuntimeFunc("goPanicSliceAcapU")
158 BoundsCheckFunc[ssa.BoundsSliceB] = typecheck.LookupRuntimeFunc("goPanicSliceB")
159 BoundsCheckFunc[ssa.BoundsSliceBU] = typecheck.LookupRuntimeFunc("goPanicSliceBU")
160 BoundsCheckFunc[ssa.BoundsSlice3Alen] = typecheck.LookupRuntimeFunc("goPanicSlice3Alen")
161 BoundsCheckFunc[ssa.BoundsSlice3AlenU] = typecheck.LookupRuntimeFunc("goPanicSlice3AlenU")
162 BoundsCheckFunc[ssa.BoundsSlice3Acap] = typecheck.LookupRuntimeFunc("goPanicSlice3Acap")
163 BoundsCheckFunc[ssa.BoundsSlice3AcapU] = typecheck.LookupRuntimeFunc("goPanicSlice3AcapU")
164 BoundsCheckFunc[ssa.BoundsSlice3B] = typecheck.LookupRuntimeFunc("goPanicSlice3B")
165 BoundsCheckFunc[ssa.BoundsSlice3BU] = typecheck.LookupRuntimeFunc("goPanicSlice3BU")
166 BoundsCheckFunc[ssa.BoundsSlice3C] = typecheck.LookupRuntimeFunc("goPanicSlice3C")
167 BoundsCheckFunc[ssa.BoundsSlice3CU] = typecheck.LookupRuntimeFunc("goPanicSlice3CU")
168 BoundsCheckFunc[ssa.BoundsConvert] = typecheck.LookupRuntimeFunc("goPanicSliceConvert")
170 BoundsCheckFunc[ssa.BoundsIndex] = typecheck.LookupRuntimeFunc("panicIndex")
171 BoundsCheckFunc[ssa.BoundsIndexU] = typecheck.LookupRuntimeFunc("panicIndexU")
172 BoundsCheckFunc[ssa.BoundsSliceAlen] = typecheck.LookupRuntimeFunc("panicSliceAlen")
173 BoundsCheckFunc[ssa.BoundsSliceAlenU] = typecheck.LookupRuntimeFunc("panicSliceAlenU")
174 BoundsCheckFunc[ssa.BoundsSliceAcap] = typecheck.LookupRuntimeFunc("panicSliceAcap")
175 BoundsCheckFunc[ssa.BoundsSliceAcapU] = typecheck.LookupRuntimeFunc("panicSliceAcapU")
176 BoundsCheckFunc[ssa.BoundsSliceB] = typecheck.LookupRuntimeFunc("panicSliceB")
177 BoundsCheckFunc[ssa.BoundsSliceBU] = typecheck.LookupRuntimeFunc("panicSliceBU")
178 BoundsCheckFunc[ssa.BoundsSlice3Alen] = typecheck.LookupRuntimeFunc("panicSlice3Alen")
179 BoundsCheckFunc[ssa.BoundsSlice3AlenU] = typecheck.LookupRuntimeFunc("panicSlice3AlenU")
180 BoundsCheckFunc[ssa.BoundsSlice3Acap] = typecheck.LookupRuntimeFunc("panicSlice3Acap")
181 BoundsCheckFunc[ssa.BoundsSlice3AcapU] = typecheck.LookupRuntimeFunc("panicSlice3AcapU")
182 BoundsCheckFunc[ssa.BoundsSlice3B] = typecheck.LookupRuntimeFunc("panicSlice3B")
183 BoundsCheckFunc[ssa.BoundsSlice3BU] = typecheck.LookupRuntimeFunc("panicSlice3BU")
184 BoundsCheckFunc[ssa.BoundsSlice3C] = typecheck.LookupRuntimeFunc("panicSlice3C")
185 BoundsCheckFunc[ssa.BoundsSlice3CU] = typecheck.LookupRuntimeFunc("panicSlice3CU")
186 BoundsCheckFunc[ssa.BoundsConvert] = typecheck.LookupRuntimeFunc("panicSliceConvert")
188 if Arch.LinkArch.PtrSize == 4 {
189 ExtendCheckFunc[ssa.BoundsIndex] = typecheck.LookupRuntimeVar("panicExtendIndex")
190 ExtendCheckFunc[ssa.BoundsIndexU] = typecheck.LookupRuntimeVar("panicExtendIndexU")
191 ExtendCheckFunc[ssa.BoundsSliceAlen] = typecheck.LookupRuntimeVar("panicExtendSliceAlen")
192 ExtendCheckFunc[ssa.BoundsSliceAlenU] = typecheck.LookupRuntimeVar("panicExtendSliceAlenU")
193 ExtendCheckFunc[ssa.BoundsSliceAcap] = typecheck.LookupRuntimeVar("panicExtendSliceAcap")
194 ExtendCheckFunc[ssa.BoundsSliceAcapU] = typecheck.LookupRuntimeVar("panicExtendSliceAcapU")
195 ExtendCheckFunc[ssa.BoundsSliceB] = typecheck.LookupRuntimeVar("panicExtendSliceB")
196 ExtendCheckFunc[ssa.BoundsSliceBU] = typecheck.LookupRuntimeVar("panicExtendSliceBU")
197 ExtendCheckFunc[ssa.BoundsSlice3Alen] = typecheck.LookupRuntimeVar("panicExtendSlice3Alen")
198 ExtendCheckFunc[ssa.BoundsSlice3AlenU] = typecheck.LookupRuntimeVar("panicExtendSlice3AlenU")
199 ExtendCheckFunc[ssa.BoundsSlice3Acap] = typecheck.LookupRuntimeVar("panicExtendSlice3Acap")
200 ExtendCheckFunc[ssa.BoundsSlice3AcapU] = typecheck.LookupRuntimeVar("panicExtendSlice3AcapU")
201 ExtendCheckFunc[ssa.BoundsSlice3B] = typecheck.LookupRuntimeVar("panicExtendSlice3B")
202 ExtendCheckFunc[ssa.BoundsSlice3BU] = typecheck.LookupRuntimeVar("panicExtendSlice3BU")
203 ExtendCheckFunc[ssa.BoundsSlice3C] = typecheck.LookupRuntimeVar("panicExtendSlice3C")
204 ExtendCheckFunc[ssa.BoundsSlice3CU] = typecheck.LookupRuntimeVar("panicExtendSlice3CU")
207 // Wasm (all asm funcs with special ABIs)
208 ir.Syms.WasmMove = typecheck.LookupRuntimeVar("wasmMove")
209 ir.Syms.WasmZero = typecheck.LookupRuntimeVar("wasmZero")
210 ir.Syms.WasmDiv = typecheck.LookupRuntimeVar("wasmDiv")
211 ir.Syms.WasmTruncS = typecheck.LookupRuntimeVar("wasmTruncS")
212 ir.Syms.WasmTruncU = typecheck.LookupRuntimeVar("wasmTruncU")
213 ir.Syms.SigPanic = typecheck.LookupRuntimeFunc("sigpanic")
216 // AbiForBodylessFuncStackMap returns the ABI for a bodyless function's stack map.
217 // This is not necessarily the ABI used to call it.
218 // Currently (1.17 dev) such a stack map is always ABI0;
219 // any ABI wrapper that is present is nosplit, hence a precise
220 // stack map is not needed there (the parameters survive only long
221 // enough to call the wrapped assembly function).
222 // This always returns a freshly copied ABI.
223 func AbiForBodylessFuncStackMap(fn *ir.Func) *abi.ABIConfig {
224 return ssaConfig.ABI0.Copy() // No idea what races will result, be safe
227 // abiForFunc implements ABI policy for a function, but does not return a copy of the ABI.
228 // Passing a nil function returns the default ABI based on experiment configuration.
229 func abiForFunc(fn *ir.Func, abi0, abi1 *abi.ABIConfig) *abi.ABIConfig {
230 if buildcfg.Experiment.RegabiArgs {
231 // Select the ABI based on the function's defining ABI.
238 case obj.ABIInternal:
239 // TODO(austin): Clean up the nomenclature here.
240 // It's not clear that "abi1" is ABIInternal.
243 base.Fatalf("function %v has unknown ABI %v", fn, fn.ABI)
244 panic("not reachable")
249 if fn.Pragma&ir.RegisterParams != 0 { // TODO(register args) remove after register abi is working
256 // dvarint writes a varint v to the funcdata in symbol x and returns the new offset
257 func dvarint(x *obj.LSym, off int, v int64) int {
258 if v < 0 || v > 1e9 {
259 panic(fmt.Sprintf("dvarint: bad offset for funcdata - %v", v))
262 return objw.Uint8(x, off, uint8(v))
264 off = objw.Uint8(x, off, uint8((v&127)|128))
266 return objw.Uint8(x, off, uint8(v>>7))
268 off = objw.Uint8(x, off, uint8(((v>>7)&127)|128))
270 return objw.Uint8(x, off, uint8(v>>14))
272 off = objw.Uint8(x, off, uint8(((v>>14)&127)|128))
274 return objw.Uint8(x, off, uint8(v>>21))
276 off = objw.Uint8(x, off, uint8(((v>>21)&127)|128))
277 return objw.Uint8(x, off, uint8(v>>28))
280 // emitOpenDeferInfo emits FUNCDATA information about the defers in a function
281 // that is using open-coded defers. This funcdata is used to determine the active
282 // defers in a function and execute those defers during panic processing.
284 // The funcdata is all encoded in varints (since values will almost always be less than
285 // 128, but stack offsets could potentially be up to 2Gbyte). All "locations" (offsets)
286 // for stack variables are specified as the number of bytes below varp (pointer to the
287 // top of the local variables) for their starting address. The format is:
289 // - Offset of the deferBits variable
290 // - Number of defers in the function
291 // - Information about each defer call, in reverse order of appearance in the function:
292 // - Offset of the closure value to call
293 func (s *state) emitOpenDeferInfo() {
294 x := base.Ctxt.Lookup(s.curfn.LSym.Name + ".opendefer")
295 x.Set(obj.AttrContentAddressable, true)
296 s.curfn.LSym.Func().OpenCodedDeferInfo = x
298 off = dvarint(x, off, -s.deferBitsTemp.FrameOffset())
299 off = dvarint(x, off, int64(len(s.openDefers)))
301 // Write in reverse-order, for ease of running in that order at runtime
302 for i := len(s.openDefers) - 1; i >= 0; i-- {
304 off = dvarint(x, off, -r.closureNode.FrameOffset())
308 func okOffset(offset int64) int64 {
309 if offset == types.BOGUS_FUNARG_OFFSET {
310 panic(fmt.Errorf("Bogus offset %d", offset))
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 if ssaDump != "" { // match either a simple name e.g. "(*Reader).Reset", package.name e.g. "compress/gzip.(*Reader).Reset", or subpackage name "gzip.(*Reader).Reset"
321 pkgDotName := base.Ctxt.Pkgpath + "." + name
322 printssa = name == ssaDump ||
323 strings.HasSuffix(pkgDotName, ssaDump) && (pkgDotName == ssaDump || strings.HasSuffix(pkgDotName, "/"+ssaDump))
325 var astBuf *bytes.Buffer
327 astBuf = &bytes.Buffer{}
328 ir.FDumpList(astBuf, "buildssa-enter", fn.Enter)
329 ir.FDumpList(astBuf, "buildssa-body", fn.Body)
330 ir.FDumpList(astBuf, "buildssa-exit", fn.Exit)
332 fmt.Println("generating SSA for", name)
333 fmt.Print(astBuf.String())
341 s.hasdefer = fn.HasDefer()
342 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
343 s.cgoUnsafeArgs = true
345 s.checkPtrEnabled = ir.ShouldCheckPtr(fn, 1)
349 log: printssa && ssaDumpStdout,
353 s.f = ssa.NewFunc(&fe)
356 s.f.Config = ssaConfig
357 s.f.Cache = &ssaCaches[worker]
360 s.f.DebugTest = s.f.DebugHashMatch("GOSSAHASH")
361 s.f.PrintOrHtmlSSA = printssa
362 if fn.Pragma&ir.Nosplit != 0 {
365 s.f.ABI0 = ssaConfig.ABI0.Copy() // Make a copy to avoid racy map operations in type-register-width cache.
366 s.f.ABI1 = ssaConfig.ABI1.Copy()
367 s.f.ABIDefault = abiForFunc(nil, s.f.ABI0, s.f.ABI1)
368 s.f.ABISelf = abiForFunc(fn, s.f.ABI0, s.f.ABI1)
370 s.panics = map[funcLine]*ssa.Block{}
371 s.softFloat = s.config.SoftFloat
373 // Allocate starting block
374 s.f.Entry = s.f.NewBlock(ssa.BlockPlain)
375 s.f.Entry.Pos = fn.Pos()
380 ssaDF = filepath.Join(ssaDir, base.Ctxt.Pkgpath+"."+name+".html")
381 ssaD := filepath.Dir(ssaDF)
382 os.MkdirAll(ssaD, 0755)
384 s.f.HTMLWriter = ssa.NewHTMLWriter(ssaDF, s.f, ssaDumpCFG)
385 // TODO: generate and print a mapping from nodes to values and blocks
386 dumpSourcesColumn(s.f.HTMLWriter, fn)
387 s.f.HTMLWriter.WriteAST("AST", astBuf)
390 // Allocate starting values
391 s.labels = map[string]*ssaLabel{}
392 s.fwdVars = map[ir.Node]*ssa.Value{}
393 s.startmem = s.entryNewValue0(ssa.OpInitMem, types.TypeMem)
395 s.hasOpenDefers = base.Flag.N == 0 && s.hasdefer && !s.curfn.OpenCodedDeferDisallowed()
397 case base.Debug.NoOpenDefer != 0:
398 s.hasOpenDefers = false
399 case s.hasOpenDefers && (base.Ctxt.Flag_shared || base.Ctxt.Flag_dynlink) && base.Ctxt.Arch.Name == "386":
400 // Don't support open-coded defers for 386 ONLY when using shared
401 // libraries, because there is extra code (added by rewriteToUseGot())
402 // preceding the deferreturn/ret code that we don't track correctly.
403 s.hasOpenDefers = false
405 if s.hasOpenDefers && len(s.curfn.Exit) > 0 {
406 // Skip doing open defers if there is any extra exit code (likely
407 // race detection), since we will not generate that code in the
408 // case of the extra deferreturn/ret segment.
409 s.hasOpenDefers = false
412 // Similarly, skip if there are any heap-allocated result
413 // parameters that need to be copied back to their stack slots.
414 for _, f := range s.curfn.Type().Results().FieldSlice() {
415 if !f.Nname.(*ir.Name).OnStack() {
416 s.hasOpenDefers = false
421 if s.hasOpenDefers &&
422 s.curfn.NumReturns*s.curfn.NumDefers > 15 {
423 // Since we are generating defer calls at every exit for
424 // open-coded defers, skip doing open-coded defers if there are
425 // too many returns (especially if there are multiple defers).
426 // Open-coded defers are most important for improving performance
427 // for smaller functions (which don't have many returns).
428 s.hasOpenDefers = false
431 s.sp = s.entryNewValue0(ssa.OpSP, types.Types[types.TUINTPTR]) // TODO: use generic pointer type (unsafe.Pointer?) instead
432 s.sb = s.entryNewValue0(ssa.OpSB, types.Types[types.TUINTPTR])
434 s.startBlock(s.f.Entry)
435 s.vars[memVar] = s.startmem
437 // Create the deferBits variable and stack slot. deferBits is a
438 // bitmask showing which of the open-coded defers in this function
439 // have been activated.
440 deferBitsTemp := typecheck.TempAt(src.NoXPos, s.curfn, types.Types[types.TUINT8])
441 deferBitsTemp.SetAddrtaken(true)
442 s.deferBitsTemp = deferBitsTemp
443 // For this value, AuxInt is initialized to zero by default
444 startDeferBits := s.entryNewValue0(ssa.OpConst8, types.Types[types.TUINT8])
445 s.vars[deferBitsVar] = startDeferBits
446 s.deferBitsAddr = s.addr(deferBitsTemp)
447 s.store(types.Types[types.TUINT8], s.deferBitsAddr, startDeferBits)
448 // Make sure that the deferBits stack slot is kept alive (for use
449 // by panics) and stores to deferBits are not eliminated, even if
450 // all checking code on deferBits in the function exit can be
451 // eliminated, because the defer statements were all
453 s.vars[memVar] = s.newValue1Apos(ssa.OpVarLive, types.TypeMem, deferBitsTemp, s.mem(), false)
456 var params *abi.ABIParamResultInfo
457 params = s.f.ABISelf.ABIAnalyze(fn.Type(), true)
459 // The backend's stackframe pass prunes away entries from the fn's
460 // Dcl list, including PARAMOUT nodes that correspond to output
461 // params passed in registers. Walk the Dcl list and capture these
462 // nodes to a side list, so that we'll have them available during
463 // DWARF-gen later on. See issue 48573 for more details.
464 var debugInfo ssa.FuncDebug
465 for _, n := range fn.Dcl {
466 if n.Class == ir.PPARAMOUT && n.IsOutputParamInRegisters() {
467 debugInfo.RegOutputParams = append(debugInfo.RegOutputParams, n)
470 fn.DebugInfo = &debugInfo
472 // Generate addresses of local declarations
473 s.decladdrs = map[*ir.Name]*ssa.Value{}
474 for _, n := range fn.Dcl {
477 // Be aware that blank and unnamed input parameters will not appear here, but do appear in the type
478 s.decladdrs[n] = s.entryNewValue2A(ssa.OpLocalAddr, types.NewPtr(n.Type()), n, s.sp, s.startmem)
480 s.decladdrs[n] = s.entryNewValue2A(ssa.OpLocalAddr, types.NewPtr(n.Type()), n, s.sp, s.startmem)
482 // processed at each use, to prevent Addr coming
485 s.Fatalf("local variable with class %v unimplemented", n.Class)
489 s.f.OwnAux = ssa.OwnAuxCall(fn.LSym, params)
491 // Populate SSAable arguments.
492 for _, n := range fn.Dcl {
493 if n.Class == ir.PPARAM {
495 v := s.newValue0A(ssa.OpArg, n.Type(), n)
497 s.addNamedValue(n, v) // This helps with debugging information, not needed for compilation itself.
498 } else { // address was taken AND/OR too large for SSA
499 paramAssignment := ssa.ParamAssignmentForArgName(s.f, n)
500 if len(paramAssignment.Registers) > 0 {
501 if TypeOK(n.Type()) { // SSA-able type, so address was taken -- receive value in OpArg, DO NOT bind to var, store immediately to memory.
502 v := s.newValue0A(ssa.OpArg, n.Type(), n)
503 s.store(n.Type(), s.decladdrs[n], v)
504 } else { // Too big for SSA.
505 // Brute force, and early, do a bunch of stores from registers
506 // TODO fix the nasty storeArgOrLoad recursion in ssa/expand_calls.go so this Just Works with store of a big Arg.
507 s.storeParameterRegsToStack(s.f.ABISelf, paramAssignment, n, s.decladdrs[n], false)
514 // Populate closure variables.
516 clo := s.entryNewValue0(ssa.OpGetClosurePtr, s.f.Config.Types.BytePtr)
517 offset := int64(types.PtrSize) // PtrSize to skip past function entry PC field
518 for _, n := range fn.ClosureVars {
521 typ = types.NewPtr(typ)
524 offset = types.Rnd(offset, typ.Alignment())
525 ptr := s.newValue1I(ssa.OpOffPtr, types.NewPtr(typ), offset, clo)
528 // If n is a small variable captured by value, promote
529 // it to PAUTO so it can be converted to SSA.
531 // Note: While we never capture a variable by value if
532 // the user took its address, we may have generated
533 // runtime calls that did (#43701). Since we don't
534 // convert Addrtaken variables to SSA anyway, no point
535 // in promoting them either.
536 if n.Byval() && !n.Addrtaken() && TypeOK(n.Type()) {
538 fn.Dcl = append(fn.Dcl, n)
539 s.assign(n, s.load(n.Type(), ptr), false, 0)
544 ptr = s.load(typ, ptr)
546 s.setHeapaddr(fn.Pos(), n, ptr)
550 // Convert the AST-based IR to the SSA-based IR
556 // fallthrough to exit
557 if s.curBlock != nil {
558 s.pushLine(fn.Endlineno)
563 for _, b := range s.f.Blocks {
564 if b.Pos != src.NoXPos {
565 s.updateUnsetPredPos(b)
569 s.f.HTMLWriter.WritePhase("before insert phis", "before insert phis")
573 // Main call to ssa package to compile function
577 s.emitOpenDeferInfo()
580 // Record incoming parameter spill information for morestack calls emitted in the assembler.
581 // This is done here, using all the parameters (used, partially used, and unused) because
582 // it mimics the behavior of the former ABI (everything stored) and because it's not 100%
583 // clear if naming conventions are respected in autogenerated code.
584 // TODO figure out exactly what's unused, don't spill it. Make liveness fine-grained, also.
585 for _, p := range params.InParams() {
586 typs, offs := p.RegisterTypesAndOffsets()
587 for i, t := range typs {
588 o := offs[i] // offset within parameter
589 fo := p.FrameOffset(params) // offset of parameter in frame
590 reg := ssa.ObjRegForAbiReg(p.Registers[i], s.f.Config)
591 s.f.RegArgs = append(s.f.RegArgs, ssa.Spill{Reg: reg, Offset: fo + o, Type: t})
598 func (s *state) storeParameterRegsToStack(abi *abi.ABIConfig, paramAssignment *abi.ABIParamAssignment, n *ir.Name, addr *ssa.Value, pointersOnly bool) {
599 typs, offs := paramAssignment.RegisterTypesAndOffsets()
600 for i, t := range typs {
601 if pointersOnly && !t.IsPtrShaped() {
604 r := paramAssignment.Registers[i]
606 op, reg := ssa.ArgOpAndRegisterFor(r, abi)
607 aux := &ssa.AuxNameOffset{Name: n, Offset: o}
608 v := s.newValue0I(op, t, reg)
610 p := s.newValue1I(ssa.OpOffPtr, types.NewPtr(t), o, addr)
615 // zeroResults zeros the return values at the start of the function.
616 // We need to do this very early in the function. Defer might stop a
617 // panic and show the return values as they exist at the time of
618 // panic. For precise stacks, the garbage collector assumes results
619 // are always live, so we need to zero them before any allocations,
620 // even allocations to move params/results to the heap.
621 func (s *state) zeroResults() {
622 for _, f := range s.curfn.Type().Results().FieldSlice() {
623 n := f.Nname.(*ir.Name)
625 // The local which points to the return value is the
626 // thing that needs zeroing. This is already handled
627 // by a Needzero annotation in plive.go:(*liveness).epilogue.
630 // Zero the stack location containing f.
631 if typ := n.Type(); TypeOK(typ) {
632 s.assign(n, s.zeroVal(typ), false, 0)
634 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, n, s.mem())
635 s.zero(n.Type(), s.decladdrs[n])
640 // paramsToHeap produces code to allocate memory for heap-escaped parameters
641 // and to copy non-result parameters' values from the stack.
642 func (s *state) paramsToHeap() {
643 do := func(params *types.Type) {
644 for _, f := range params.FieldSlice() {
646 continue // anonymous or blank parameter
648 n := f.Nname.(*ir.Name)
649 if ir.IsBlank(n) || n.OnStack() {
653 if n.Class == ir.PPARAM {
654 s.move(n.Type(), s.expr(n.Heapaddr), s.decladdrs[n])
659 typ := s.curfn.Type()
665 // newHeapaddr allocates heap memory for n and sets its heap address.
666 func (s *state) newHeapaddr(n *ir.Name) {
667 s.setHeapaddr(n.Pos(), n, s.newObject(n.Type(), nil))
670 // setHeapaddr allocates a new PAUTO variable to store ptr (which must be non-nil)
671 // and then sets it as n's heap address.
672 func (s *state) setHeapaddr(pos src.XPos, n *ir.Name, ptr *ssa.Value) {
673 if !ptr.Type.IsPtr() || !types.Identical(n.Type(), ptr.Type.Elem()) {
674 base.FatalfAt(n.Pos(), "setHeapaddr %L with type %v", n, ptr.Type)
677 // Declare variable to hold address.
678 addr := ir.NewNameAt(pos, &types.Sym{Name: "&" + n.Sym().Name, Pkg: types.LocalPkg})
679 addr.SetType(types.NewPtr(n.Type()))
680 addr.Class = ir.PAUTO
683 s.curfn.Dcl = append(s.curfn.Dcl, addr)
684 types.CalcSize(addr.Type())
686 if n.Class == ir.PPARAMOUT {
687 addr.SetIsOutputParamHeapAddr(true)
691 s.assign(addr, ptr, false, 0)
694 // newObject returns an SSA value denoting new(typ).
695 func (s *state) newObject(typ *types.Type, rtype *ssa.Value) *ssa.Value {
697 return s.newValue1A(ssa.OpAddr, types.NewPtr(typ), ir.Syms.Zerobase, s.sb)
700 rtype = s.reflectType(typ)
702 return s.rtcall(ir.Syms.Newobject, true, []*types.Type{types.NewPtr(typ)}, rtype)[0]
705 func (s *state) checkPtrAlignment(n *ir.ConvExpr, v *ssa.Value, count *ssa.Value) {
706 if !n.Type().IsPtr() {
707 s.Fatalf("expected pointer type: %v", n.Type())
709 elem, rtypeExpr := n.Type().Elem(), n.ElemRType
712 s.Fatalf("expected array type: %v", elem)
714 elem, rtypeExpr = elem.Elem(), n.ElemElemRType
717 // Casting from larger type to smaller one is ok, so for smallest type, do nothing.
718 if elem.Alignment() == 1 && (size == 0 || size == 1 || count == nil) {
722 count = s.constInt(types.Types[types.TUINTPTR], 1)
724 if count.Type.Size() != s.config.PtrSize {
725 s.Fatalf("expected count fit to an uintptr size, have: %d, want: %d", count.Type.Size(), s.config.PtrSize)
728 if rtypeExpr != nil {
729 rtype = s.expr(rtypeExpr)
731 rtype = s.reflectType(elem)
733 s.rtcall(ir.Syms.CheckPtrAlignment, true, nil, v, rtype, count)
736 // reflectType returns an SSA value representing a pointer to typ's
737 // reflection type descriptor.
738 func (s *state) reflectType(typ *types.Type) *ssa.Value {
739 // TODO(mdempsky): Make this Fatalf under Unified IR; frontend needs
740 // to supply RType expressions.
741 lsym := reflectdata.TypeLinksym(typ)
742 return s.entryNewValue1A(ssa.OpAddr, types.NewPtr(types.Types[types.TUINT8]), lsym, s.sb)
745 func dumpSourcesColumn(writer *ssa.HTMLWriter, fn *ir.Func) {
746 // Read sources of target function fn.
747 fname := base.Ctxt.PosTable.Pos(fn.Pos()).Filename()
748 targetFn, err := readFuncLines(fname, fn.Pos().Line(), fn.Endlineno.Line())
750 writer.Logf("cannot read sources for function %v: %v", fn, err)
753 // Read sources of inlined functions.
754 var inlFns []*ssa.FuncLines
755 for _, fi := range ssaDumpInlined {
757 fname := base.Ctxt.PosTable.Pos(fi.Pos()).Filename()
758 fnLines, err := readFuncLines(fname, fi.Pos().Line(), elno.Line())
760 writer.Logf("cannot read sources for inlined function %v: %v", fi, err)
763 inlFns = append(inlFns, fnLines)
766 sort.Sort(ssa.ByTopo(inlFns))
768 inlFns = append([]*ssa.FuncLines{targetFn}, inlFns...)
771 writer.WriteSources("sources", inlFns)
774 func readFuncLines(file string, start, end uint) (*ssa.FuncLines, error) {
775 f, err := os.Open(os.ExpandEnv(file))
782 scanner := bufio.NewScanner(f)
783 for scanner.Scan() && ln <= end {
785 lines = append(lines, scanner.Text())
789 return &ssa.FuncLines{Filename: file, StartLineno: start, Lines: lines}, nil
792 // updateUnsetPredPos propagates the earliest-value position information for b
793 // towards all of b's predecessors that need a position, and recurs on that
794 // predecessor if its position is updated. B should have a non-empty position.
795 func (s *state) updateUnsetPredPos(b *ssa.Block) {
796 if b.Pos == src.NoXPos {
797 s.Fatalf("Block %s should have a position", b)
799 bestPos := src.NoXPos
800 for _, e := range b.Preds {
805 if bestPos == src.NoXPos {
807 for _, v := range b.Values {
811 if v.Pos != src.NoXPos {
812 // Assume values are still in roughly textual order;
813 // TODO: could also seek minimum position?
820 s.updateUnsetPredPos(p) // We do not expect long chains of these, thus recursion is okay.
824 // Information about each open-coded defer.
825 type openDeferInfo struct {
826 // The node representing the call of the defer
828 // If defer call is closure call, the address of the argtmp where the
829 // closure is stored.
831 // The node representing the argtmp where the closure is stored - used for
832 // function, method, or interface call, to store a closure that panic
833 // processing can use for this defer.
838 // configuration (arch) information
841 // function we're building
848 labels map[string]*ssaLabel
850 // unlabeled break and continue statement tracking
851 breakTo *ssa.Block // current target for plain break statement
852 continueTo *ssa.Block // current target for plain continue statement
854 // current location where we're interpreting the AST
857 // variable assignments in the current block (map from variable symbol to ssa value)
858 // *Node is the unique identifier (an ONAME Node) for the variable.
859 // TODO: keep a single varnum map, then make all of these maps slices instead?
860 vars map[ir.Node]*ssa.Value
862 // fwdVars are variables that are used before they are defined in the current block.
863 // This map exists just to coalesce multiple references into a single FwdRef op.
864 // *Node is the unique identifier (an ONAME Node) for the variable.
865 fwdVars map[ir.Node]*ssa.Value
867 // all defined variables at the end of each block. Indexed by block ID.
868 defvars []map[ir.Node]*ssa.Value
870 // addresses of PPARAM and PPARAMOUT variables on the stack.
871 decladdrs map[*ir.Name]*ssa.Value
873 // starting values. Memory, stack pointer, and globals pointer
877 // value representing address of where deferBits autotmp is stored
878 deferBitsAddr *ssa.Value
879 deferBitsTemp *ir.Name
881 // line number stack. The current line number is top of stack
883 // the last line number processed; it may have been popped
886 // list of panic calls by function name and line number.
887 // Used to deduplicate panic calls.
888 panics map[funcLine]*ssa.Block
891 hasdefer bool // whether the function contains a defer statement
893 hasOpenDefers bool // whether we are doing open-coded defers
894 checkPtrEnabled bool // whether to insert checkptr instrumentation
896 // If doing open-coded defers, list of info about the defer calls in
897 // scanning order. Hence, at exit we should run these defers in reverse
898 // order of this list
899 openDefers []*openDeferInfo
900 // For open-coded defers, this is the beginning and end blocks of the last
901 // defer exit code that we have generated so far. We use these to share
902 // code between exits if the shareDeferExits option (disabled by default)
904 lastDeferExit *ssa.Block // Entry block of last defer exit code we generated
905 lastDeferFinalBlock *ssa.Block // Final block of last defer exit code we generated
906 lastDeferCount int // Number of defers encountered at that point
908 prevCall *ssa.Value // the previous call; use this to tie results to the call op.
911 type funcLine struct {
917 type ssaLabel struct {
918 target *ssa.Block // block identified by this label
919 breakTarget *ssa.Block // block to break to in control flow node identified by this label
920 continueTarget *ssa.Block // block to continue to in control flow node identified by this label
923 // label returns the label associated with sym, creating it if necessary.
924 func (s *state) label(sym *types.Sym) *ssaLabel {
925 lab := s.labels[sym.Name]
928 s.labels[sym.Name] = lab
933 func (s *state) Logf(msg string, args ...interface{}) { s.f.Logf(msg, args...) }
934 func (s *state) Log() bool { return s.f.Log() }
935 func (s *state) Fatalf(msg string, args ...interface{}) {
936 s.f.Frontend().Fatalf(s.peekPos(), msg, args...)
938 func (s *state) Warnl(pos src.XPos, msg string, args ...interface{}) { s.f.Warnl(pos, msg, args...) }
939 func (s *state) Debug_checknil() bool { return s.f.Frontend().Debug_checknil() }
941 func ssaMarker(name string) *ir.Name {
942 return typecheck.NewName(&types.Sym{Name: name})
946 // marker node for the memory variable
947 memVar = ssaMarker("mem")
949 // marker nodes for temporary variables
950 ptrVar = ssaMarker("ptr")
951 lenVar = ssaMarker("len")
952 newlenVar = ssaMarker("newlen")
953 capVar = ssaMarker("cap")
954 typVar = ssaMarker("typ")
955 okVar = ssaMarker("ok")
956 deferBitsVar = ssaMarker("deferBits")
959 // startBlock sets the current block we're generating code in to b.
960 func (s *state) startBlock(b *ssa.Block) {
961 if s.curBlock != nil {
962 s.Fatalf("starting block %v when block %v has not ended", b, s.curBlock)
965 s.vars = map[ir.Node]*ssa.Value{}
966 for n := range s.fwdVars {
971 // endBlock marks the end of generating code for the current block.
972 // Returns the (former) current block. Returns nil if there is no current
973 // block, i.e. if no code flows to the current execution point.
974 func (s *state) endBlock() *ssa.Block {
979 for len(s.defvars) <= int(b.ID) {
980 s.defvars = append(s.defvars, nil)
982 s.defvars[b.ID] = s.vars
986 // Empty plain blocks get the line of their successor (handled after all blocks created),
987 // except for increment blocks in For statements (handled in ssa conversion of OFOR),
988 // and for blocks ending in GOTO/BREAK/CONTINUE.
996 // pushLine pushes a line number on the line number stack.
997 func (s *state) pushLine(line src.XPos) {
999 // the frontend may emit node with line number missing,
1000 // use the parent line number in this case.
1002 if base.Flag.K != 0 {
1003 base.Warn("buildssa: unknown position (line 0)")
1009 s.line = append(s.line, line)
1012 // popLine pops the top of the line number stack.
1013 func (s *state) popLine() {
1014 s.line = s.line[:len(s.line)-1]
1017 // peekPos peeks the top of the line number stack.
1018 func (s *state) peekPos() src.XPos {
1019 return s.line[len(s.line)-1]
1022 // newValue0 adds a new value with no arguments to the current block.
1023 func (s *state) newValue0(op ssa.Op, t *types.Type) *ssa.Value {
1024 return s.curBlock.NewValue0(s.peekPos(), op, t)
1027 // newValue0A adds a new value with no arguments and an aux value to the current block.
1028 func (s *state) newValue0A(op ssa.Op, t *types.Type, aux ssa.Aux) *ssa.Value {
1029 return s.curBlock.NewValue0A(s.peekPos(), op, t, aux)
1032 // newValue0I adds a new value with no arguments and an auxint value to the current block.
1033 func (s *state) newValue0I(op ssa.Op, t *types.Type, auxint int64) *ssa.Value {
1034 return s.curBlock.NewValue0I(s.peekPos(), op, t, auxint)
1037 // newValue1 adds a new value with one argument to the current block.
1038 func (s *state) newValue1(op ssa.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
1039 return s.curBlock.NewValue1(s.peekPos(), op, t, arg)
1042 // newValue1A adds a new value with one argument and an aux value to the current block.
1043 func (s *state) newValue1A(op ssa.Op, t *types.Type, aux ssa.Aux, arg *ssa.Value) *ssa.Value {
1044 return s.curBlock.NewValue1A(s.peekPos(), op, t, aux, arg)
1047 // newValue1Apos adds a new value with one argument and an aux value to the current block.
1048 // isStmt determines whether the created values may be a statement or not
1049 // (i.e., false means never, yes means maybe).
1050 func (s *state) newValue1Apos(op ssa.Op, t *types.Type, aux ssa.Aux, arg *ssa.Value, isStmt bool) *ssa.Value {
1052 return s.curBlock.NewValue1A(s.peekPos(), op, t, aux, arg)
1054 return s.curBlock.NewValue1A(s.peekPos().WithNotStmt(), op, t, aux, arg)
1057 // newValue1I adds a new value with one argument and an auxint value to the current block.
1058 func (s *state) newValue1I(op ssa.Op, t *types.Type, aux int64, arg *ssa.Value) *ssa.Value {
1059 return s.curBlock.NewValue1I(s.peekPos(), op, t, aux, arg)
1062 // newValue2 adds a new value with two arguments to the current block.
1063 func (s *state) newValue2(op ssa.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
1064 return s.curBlock.NewValue2(s.peekPos(), op, t, arg0, arg1)
1067 // newValue2A adds a new value with two arguments and an aux value to the current block.
1068 func (s *state) newValue2A(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1 *ssa.Value) *ssa.Value {
1069 return s.curBlock.NewValue2A(s.peekPos(), op, t, aux, arg0, arg1)
1072 // newValue2Apos adds a new value with two arguments and an aux value to the current block.
1073 // isStmt determines whether the created values may be a statement or not
1074 // (i.e., false means never, yes means maybe).
1075 func (s *state) newValue2Apos(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1 *ssa.Value, isStmt bool) *ssa.Value {
1077 return s.curBlock.NewValue2A(s.peekPos(), op, t, aux, arg0, arg1)
1079 return s.curBlock.NewValue2A(s.peekPos().WithNotStmt(), op, t, aux, arg0, arg1)
1082 // newValue2I adds a new value with two arguments and an auxint value to the current block.
1083 func (s *state) newValue2I(op ssa.Op, t *types.Type, aux int64, arg0, arg1 *ssa.Value) *ssa.Value {
1084 return s.curBlock.NewValue2I(s.peekPos(), op, t, aux, arg0, arg1)
1087 // newValue3 adds a new value with three arguments to the current block.
1088 func (s *state) newValue3(op ssa.Op, t *types.Type, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
1089 return s.curBlock.NewValue3(s.peekPos(), op, t, arg0, arg1, arg2)
1092 // newValue3I adds a new value with three arguments and an auxint value to the current block.
1093 func (s *state) newValue3I(op ssa.Op, t *types.Type, aux int64, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
1094 return s.curBlock.NewValue3I(s.peekPos(), op, t, aux, arg0, arg1, arg2)
1097 // newValue3A adds a new value with three arguments and an aux value to the current block.
1098 func (s *state) newValue3A(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
1099 return s.curBlock.NewValue3A(s.peekPos(), op, t, aux, arg0, arg1, arg2)
1102 // newValue3Apos adds a new value with three arguments and an aux value to the current block.
1103 // isStmt determines whether the created values may be a statement or not
1104 // (i.e., false means never, yes means maybe).
1105 func (s *state) newValue3Apos(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1, arg2 *ssa.Value, isStmt bool) *ssa.Value {
1107 return s.curBlock.NewValue3A(s.peekPos(), op, t, aux, arg0, arg1, arg2)
1109 return s.curBlock.NewValue3A(s.peekPos().WithNotStmt(), op, t, aux, arg0, arg1, arg2)
1112 // newValue4 adds a new value with four arguments to the current block.
1113 func (s *state) newValue4(op ssa.Op, t *types.Type, arg0, arg1, arg2, arg3 *ssa.Value) *ssa.Value {
1114 return s.curBlock.NewValue4(s.peekPos(), op, t, arg0, arg1, arg2, arg3)
1117 // newValue4 adds a new value with four arguments and an auxint value to the current block.
1118 func (s *state) newValue4I(op ssa.Op, t *types.Type, aux int64, arg0, arg1, arg2, arg3 *ssa.Value) *ssa.Value {
1119 return s.curBlock.NewValue4I(s.peekPos(), op, t, aux, arg0, arg1, arg2, arg3)
1122 func (s *state) entryBlock() *ssa.Block {
1124 if base.Flag.N > 0 && s.curBlock != nil {
1125 // If optimizations are off, allocate in current block instead. Since with -N
1126 // we're not doing the CSE or tighten passes, putting lots of stuff in the
1127 // entry block leads to O(n^2) entries in the live value map during regalloc.
1134 // entryNewValue0 adds a new value with no arguments to the entry block.
1135 func (s *state) entryNewValue0(op ssa.Op, t *types.Type) *ssa.Value {
1136 return s.entryBlock().NewValue0(src.NoXPos, op, t)
1139 // entryNewValue0A adds a new value with no arguments and an aux value to the entry block.
1140 func (s *state) entryNewValue0A(op ssa.Op, t *types.Type, aux ssa.Aux) *ssa.Value {
1141 return s.entryBlock().NewValue0A(src.NoXPos, op, t, aux)
1144 // entryNewValue1 adds a new value with one argument to the entry block.
1145 func (s *state) entryNewValue1(op ssa.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
1146 return s.entryBlock().NewValue1(src.NoXPos, op, t, arg)
1149 // entryNewValue1 adds a new value with one argument and an auxint value to the entry block.
1150 func (s *state) entryNewValue1I(op ssa.Op, t *types.Type, auxint int64, arg *ssa.Value) *ssa.Value {
1151 return s.entryBlock().NewValue1I(src.NoXPos, op, t, auxint, arg)
1154 // entryNewValue1A adds a new value with one argument and an aux value to the entry block.
1155 func (s *state) entryNewValue1A(op ssa.Op, t *types.Type, aux ssa.Aux, arg *ssa.Value) *ssa.Value {
1156 return s.entryBlock().NewValue1A(src.NoXPos, op, t, aux, arg)
1159 // entryNewValue2 adds a new value with two arguments to the entry block.
1160 func (s *state) entryNewValue2(op ssa.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
1161 return s.entryBlock().NewValue2(src.NoXPos, op, t, arg0, arg1)
1164 // entryNewValue2A adds a new value with two arguments and an aux value to the entry block.
1165 func (s *state) entryNewValue2A(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1 *ssa.Value) *ssa.Value {
1166 return s.entryBlock().NewValue2A(src.NoXPos, op, t, aux, arg0, arg1)
1169 // const* routines add a new const value to the entry block.
1170 func (s *state) constSlice(t *types.Type) *ssa.Value {
1171 return s.f.ConstSlice(t)
1173 func (s *state) constInterface(t *types.Type) *ssa.Value {
1174 return s.f.ConstInterface(t)
1176 func (s *state) constNil(t *types.Type) *ssa.Value { return s.f.ConstNil(t) }
1177 func (s *state) constEmptyString(t *types.Type) *ssa.Value {
1178 return s.f.ConstEmptyString(t)
1180 func (s *state) constBool(c bool) *ssa.Value {
1181 return s.f.ConstBool(types.Types[types.TBOOL], c)
1183 func (s *state) constInt8(t *types.Type, c int8) *ssa.Value {
1184 return s.f.ConstInt8(t, c)
1186 func (s *state) constInt16(t *types.Type, c int16) *ssa.Value {
1187 return s.f.ConstInt16(t, c)
1189 func (s *state) constInt32(t *types.Type, c int32) *ssa.Value {
1190 return s.f.ConstInt32(t, c)
1192 func (s *state) constInt64(t *types.Type, c int64) *ssa.Value {
1193 return s.f.ConstInt64(t, c)
1195 func (s *state) constFloat32(t *types.Type, c float64) *ssa.Value {
1196 return s.f.ConstFloat32(t, c)
1198 func (s *state) constFloat64(t *types.Type, c float64) *ssa.Value {
1199 return s.f.ConstFloat64(t, c)
1201 func (s *state) constInt(t *types.Type, c int64) *ssa.Value {
1202 if s.config.PtrSize == 8 {
1203 return s.constInt64(t, c)
1205 if int64(int32(c)) != c {
1206 s.Fatalf("integer constant too big %d", c)
1208 return s.constInt32(t, int32(c))
1210 func (s *state) constOffPtrSP(t *types.Type, c int64) *ssa.Value {
1211 return s.f.ConstOffPtrSP(t, c, s.sp)
1214 // newValueOrSfCall* are wrappers around newValue*, which may create a call to a
1215 // soft-float runtime function instead (when emitting soft-float code).
1216 func (s *state) newValueOrSfCall1(op ssa.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
1218 if c, ok := s.sfcall(op, arg); ok {
1222 return s.newValue1(op, t, arg)
1224 func (s *state) newValueOrSfCall2(op ssa.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
1226 if c, ok := s.sfcall(op, arg0, arg1); ok {
1230 return s.newValue2(op, t, arg0, arg1)
1233 type instrumentKind uint8
1236 instrumentRead = iota
1241 func (s *state) instrument(t *types.Type, addr *ssa.Value, kind instrumentKind) {
1242 s.instrument2(t, addr, nil, kind)
1245 // instrumentFields instruments a read/write operation on addr.
1246 // If it is instrumenting for MSAN or ASAN and t is a struct type, it instruments
1247 // operation for each field, instead of for the whole struct.
1248 func (s *state) instrumentFields(t *types.Type, addr *ssa.Value, kind instrumentKind) {
1249 if !(base.Flag.MSan || base.Flag.ASan) || !t.IsStruct() {
1250 s.instrument(t, addr, kind)
1253 for _, f := range t.Fields().Slice() {
1254 if f.Sym.IsBlank() {
1257 offptr := s.newValue1I(ssa.OpOffPtr, types.NewPtr(f.Type), f.Offset, addr)
1258 s.instrumentFields(f.Type, offptr, kind)
1262 func (s *state) instrumentMove(t *types.Type, dst, src *ssa.Value) {
1264 s.instrument2(t, dst, src, instrumentMove)
1266 s.instrument(t, src, instrumentRead)
1267 s.instrument(t, dst, instrumentWrite)
1271 func (s *state) instrument2(t *types.Type, addr, addr2 *ssa.Value, kind instrumentKind) {
1272 if !s.curfn.InstrumentBody() {
1278 return // can't race on zero-sized things
1281 if ssa.IsSanitizerSafeAddr(addr) {
1288 if addr2 != nil && kind != instrumentMove {
1289 panic("instrument2: non-nil addr2 for non-move instrumentation")
1294 case instrumentRead:
1295 fn = ir.Syms.Msanread
1296 case instrumentWrite:
1297 fn = ir.Syms.Msanwrite
1298 case instrumentMove:
1299 fn = ir.Syms.Msanmove
1301 panic("unreachable")
1304 } else if base.Flag.Race && t.NumComponents(types.CountBlankFields) > 1 {
1305 // for composite objects we have to write every address
1306 // because a write might happen to any subobject.
1307 // composites with only one element don't have subobjects, though.
1309 case instrumentRead:
1310 fn = ir.Syms.Racereadrange
1311 case instrumentWrite:
1312 fn = ir.Syms.Racewriterange
1314 panic("unreachable")
1317 } else if base.Flag.Race {
1318 // for non-composite objects we can write just the start
1319 // address, as any write must write the first byte.
1321 case instrumentRead:
1322 fn = ir.Syms.Raceread
1323 case instrumentWrite:
1324 fn = ir.Syms.Racewrite
1326 panic("unreachable")
1328 } else if base.Flag.ASan {
1330 case instrumentRead:
1331 fn = ir.Syms.Asanread
1332 case instrumentWrite:
1333 fn = ir.Syms.Asanwrite
1335 panic("unreachable")
1339 panic("unreachable")
1342 args := []*ssa.Value{addr}
1344 args = append(args, addr2)
1347 args = append(args, s.constInt(types.Types[types.TUINTPTR], w))
1349 s.rtcall(fn, true, nil, args...)
1352 func (s *state) load(t *types.Type, src *ssa.Value) *ssa.Value {
1353 s.instrumentFields(t, src, instrumentRead)
1354 return s.rawLoad(t, src)
1357 func (s *state) rawLoad(t *types.Type, src *ssa.Value) *ssa.Value {
1358 return s.newValue2(ssa.OpLoad, t, src, s.mem())
1361 func (s *state) store(t *types.Type, dst, val *ssa.Value) {
1362 s.vars[memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, t, dst, val, s.mem())
1365 func (s *state) zero(t *types.Type, dst *ssa.Value) {
1366 s.instrument(t, dst, instrumentWrite)
1367 store := s.newValue2I(ssa.OpZero, types.TypeMem, t.Size(), dst, s.mem())
1369 s.vars[memVar] = store
1372 func (s *state) move(t *types.Type, dst, src *ssa.Value) {
1373 s.instrumentMove(t, dst, src)
1374 store := s.newValue3I(ssa.OpMove, types.TypeMem, t.Size(), dst, src, s.mem())
1376 s.vars[memVar] = store
1379 // stmtList converts the statement list n to SSA and adds it to s.
1380 func (s *state) stmtList(l ir.Nodes) {
1381 for _, n := range l {
1386 // stmt converts the statement n to SSA and adds it to s.
1387 func (s *state) stmt(n ir.Node) {
1388 if !(n.Op() == ir.OVARKILL || n.Op() == ir.OVARLIVE || n.Op() == ir.OVARDEF) {
1389 // OVARKILL, OVARLIVE, and OVARDEF are invisible to the programmer, so we don't use their line numbers to avoid confusion in debugging.
1394 // If s.curBlock is nil, and n isn't a label (which might have an associated goto somewhere),
1395 // then this code is dead. Stop here.
1396 if s.curBlock == nil && n.Op() != ir.OLABEL {
1400 s.stmtList(n.Init())
1404 n := n.(*ir.BlockStmt)
1408 case ir.ODCLCONST, ir.ODCLTYPE, ir.OFALL:
1410 // Expression statements
1412 n := n.(*ir.CallExpr)
1413 if ir.IsIntrinsicCall(n) {
1420 n := n.(*ir.CallExpr)
1421 s.callResult(n, callNormal)
1422 if n.Op() == ir.OCALLFUNC && n.X.Op() == ir.ONAME && n.X.(*ir.Name).Class == ir.PFUNC {
1423 if fn := n.X.Sym().Name; base.Flag.CompilingRuntime && fn == "throw" ||
1424 n.X.Sym().Pkg == ir.Pkgs.Runtime && (fn == "throwinit" || fn == "gopanic" || fn == "panicwrap" || fn == "block" || fn == "panicmakeslicelen" || fn == "panicmakeslicecap") {
1427 b.Kind = ssa.BlockExit
1429 // TODO: never rewrite OPANIC to OCALLFUNC in the
1430 // first place. Need to wait until all backends
1435 n := n.(*ir.GoDeferStmt)
1436 if base.Debug.Defer > 0 {
1437 var defertype string
1438 if s.hasOpenDefers {
1439 defertype = "open-coded"
1440 } else if n.Esc() == ir.EscNever {
1441 defertype = "stack-allocated"
1443 defertype = "heap-allocated"
1445 base.WarnfAt(n.Pos(), "%s defer", defertype)
1447 if s.hasOpenDefers {
1448 s.openDeferRecord(n.Call.(*ir.CallExpr))
1451 if n.Esc() == ir.EscNever {
1454 s.callResult(n.Call.(*ir.CallExpr), d)
1457 n := n.(*ir.GoDeferStmt)
1458 s.callResult(n.Call.(*ir.CallExpr), callGo)
1460 case ir.OAS2DOTTYPE:
1461 n := n.(*ir.AssignListStmt)
1462 var res, resok *ssa.Value
1463 if n.Rhs[0].Op() == ir.ODOTTYPE2 {
1464 res, resok = s.dottype(n.Rhs[0].(*ir.TypeAssertExpr), true)
1466 res, resok = s.dynamicDottype(n.Rhs[0].(*ir.DynamicTypeAssertExpr), true)
1469 if !TypeOK(n.Rhs[0].Type()) {
1470 if res.Op != ssa.OpLoad {
1471 s.Fatalf("dottype of non-load")
1474 if mem.Op == ssa.OpVarKill {
1477 if res.Args[1] != mem {
1478 s.Fatalf("memory no longer live from 2-result dottype load")
1483 s.assign(n.Lhs[0], res, deref, 0)
1484 s.assign(n.Lhs[1], resok, false, 0)
1488 // We come here only when it is an intrinsic call returning two values.
1489 n := n.(*ir.AssignListStmt)
1490 call := n.Rhs[0].(*ir.CallExpr)
1491 if !ir.IsIntrinsicCall(call) {
1492 s.Fatalf("non-intrinsic AS2FUNC not expanded %v", call)
1494 v := s.intrinsicCall(call)
1495 v1 := s.newValue1(ssa.OpSelect0, n.Lhs[0].Type(), v)
1496 v2 := s.newValue1(ssa.OpSelect1, n.Lhs[1].Type(), v)
1497 s.assign(n.Lhs[0], v1, false, 0)
1498 s.assign(n.Lhs[1], v2, false, 0)
1503 if v := n.X; v.Esc() == ir.EscHeap {
1508 n := n.(*ir.LabelStmt)
1511 // Nothing to do because the label isn't targetable. See issue 52278.
1516 // The label might already have a target block via a goto.
1517 if lab.target == nil {
1518 lab.target = s.f.NewBlock(ssa.BlockPlain)
1521 // Go to that label.
1522 // (We pretend "label:" is preceded by "goto label", unless the predecessor is unreachable.)
1523 if s.curBlock != nil {
1525 b.AddEdgeTo(lab.target)
1527 s.startBlock(lab.target)
1530 n := n.(*ir.BranchStmt)
1534 if lab.target == nil {
1535 lab.target = s.f.NewBlock(ssa.BlockPlain)
1539 b.Pos = s.lastPos.WithIsStmt() // Do this even if b is an empty block.
1540 b.AddEdgeTo(lab.target)
1543 n := n.(*ir.AssignStmt)
1544 if n.X == n.Y && n.X.Op() == ir.ONAME {
1545 // An x=x assignment. No point in doing anything
1546 // here. In addition, skipping this assignment
1547 // prevents generating:
1550 // which is bad because x is incorrectly considered
1551 // dead before the vardef. See issue #14904.
1559 case ir.OSTRUCTLIT, ir.OARRAYLIT, ir.OSLICELIT:
1560 // All literals with nonzero fields have already been
1561 // rewritten during walk. Any that remain are just T{}
1562 // or equivalents. Use the zero value.
1563 if !ir.IsZero(rhs) {
1564 s.Fatalf("literal with nonzero value in SSA: %v", rhs)
1568 rhs := rhs.(*ir.CallExpr)
1569 // Check whether we're writing the result of an append back to the same slice.
1570 // If so, we handle it specially to avoid write barriers on the fast
1571 // (non-growth) path.
1572 if !ir.SameSafeExpr(n.X, rhs.Args[0]) || base.Flag.N != 0 {
1575 // If the slice can be SSA'd, it'll be on the stack,
1576 // so there will be no write barriers,
1577 // so there's no need to attempt to prevent them.
1579 if base.Debug.Append > 0 { // replicating old diagnostic message
1580 base.WarnfAt(n.Pos(), "append: len-only update (in local slice)")
1584 if base.Debug.Append > 0 {
1585 base.WarnfAt(n.Pos(), "append: len-only update")
1592 if ir.IsBlank(n.X) {
1594 // Just evaluate rhs for side-effects.
1612 r = nil // Signal assign to use OpZero.
1625 if rhs != nil && (rhs.Op() == ir.OSLICE || rhs.Op() == ir.OSLICE3 || rhs.Op() == ir.OSLICESTR) && ir.SameSafeExpr(rhs.(*ir.SliceExpr).X, n.X) {
1626 // We're assigning a slicing operation back to its source.
1627 // Don't write back fields we aren't changing. See issue #14855.
1628 rhs := rhs.(*ir.SliceExpr)
1629 i, j, k := rhs.Low, rhs.High, rhs.Max
1630 if i != nil && (i.Op() == ir.OLITERAL && i.Val().Kind() == constant.Int && ir.Int64Val(i) == 0) {
1631 // [0:...] is the same as [:...]
1634 // TODO: detect defaults for len/cap also.
1635 // Currently doesn't really work because (*p)[:len(*p)] appears here as:
1638 //if j != nil && (j.Op == OLEN && SameSafeExpr(j.Left, n.Left)) {
1641 //if k != nil && (k.Op == OCAP && SameSafeExpr(k.Left, n.Left)) {
1655 s.assign(n.X, r, deref, skip)
1659 if ir.IsConst(n.Cond, constant.Bool) {
1660 s.stmtList(n.Cond.Init())
1661 if ir.BoolVal(n.Cond) {
1669 bEnd := s.f.NewBlock(ssa.BlockPlain)
1674 var bThen *ssa.Block
1675 if len(n.Body) != 0 {
1676 bThen = s.f.NewBlock(ssa.BlockPlain)
1680 var bElse *ssa.Block
1681 if len(n.Else) != 0 {
1682 bElse = s.f.NewBlock(ssa.BlockPlain)
1686 s.condBranch(n.Cond, bThen, bElse, likely)
1688 if len(n.Body) != 0 {
1691 if b := s.endBlock(); b != nil {
1695 if len(n.Else) != 0 {
1698 if b := s.endBlock(); b != nil {
1705 n := n.(*ir.ReturnStmt)
1706 s.stmtList(n.Results)
1708 b.Pos = s.lastPos.WithIsStmt()
1711 n := n.(*ir.TailCallStmt)
1712 s.callResult(n.Call, callTail)
1715 b.Kind = ssa.BlockRetJmp // could use BlockExit. BlockRetJmp is mostly for clarity.
1718 case ir.OCONTINUE, ir.OBREAK:
1719 n := n.(*ir.BranchStmt)
1722 // plain break/continue
1730 // labeled break/continue; look up the target
1735 to = lab.continueTarget
1737 to = lab.breakTarget
1742 b.Pos = s.lastPos.WithIsStmt() // Do this even if b is an empty block.
1745 case ir.OFOR, ir.OFORUNTIL:
1746 // OFOR: for Ninit; Left; Right { Nbody }
1747 // cond (Left); body (Nbody); incr (Right)
1749 // OFORUNTIL: for Ninit; Left; Right; List { Nbody }
1750 // => body: { Nbody }; incr: Right; if Left { lateincr: List; goto body }; end:
1751 n := n.(*ir.ForStmt)
1752 bCond := s.f.NewBlock(ssa.BlockPlain)
1753 bBody := s.f.NewBlock(ssa.BlockPlain)
1754 bIncr := s.f.NewBlock(ssa.BlockPlain)
1755 bEnd := s.f.NewBlock(ssa.BlockPlain)
1757 // ensure empty for loops have correct position; issue #30167
1760 // first, jump to condition test (OFOR) or body (OFORUNTIL)
1762 if n.Op() == ir.OFOR {
1764 // generate code to test condition
1767 s.condBranch(n.Cond, bBody, bEnd, 1)
1770 b.Kind = ssa.BlockPlain
1778 // set up for continue/break in body
1779 prevContinue := s.continueTo
1780 prevBreak := s.breakTo
1781 s.continueTo = bIncr
1784 if sym := n.Label; sym != nil {
1787 lab.continueTarget = bIncr
1788 lab.breakTarget = bEnd
1795 // tear down continue/break
1796 s.continueTo = prevContinue
1797 s.breakTo = prevBreak
1799 lab.continueTarget = nil
1800 lab.breakTarget = nil
1803 // done with body, goto incr
1804 if b := s.endBlock(); b != nil {
1808 // generate incr (and, for OFORUNTIL, condition)
1813 if n.Op() == ir.OFOR {
1814 if b := s.endBlock(); b != nil {
1816 // It can happen that bIncr ends in a block containing only VARKILL,
1817 // and that muddles the debugging experience.
1818 if b.Pos == src.NoXPos {
1823 // bCond is unused in OFORUNTIL, so repurpose it.
1826 s.condBranch(n.Cond, bLateIncr, bEnd, 1)
1827 // generate late increment
1828 s.startBlock(bLateIncr)
1830 s.endBlock().AddEdgeTo(bBody)
1835 case ir.OSWITCH, ir.OSELECT:
1836 // These have been mostly rewritten by the front end into their Nbody fields.
1837 // Our main task is to correctly hook up any break statements.
1838 bEnd := s.f.NewBlock(ssa.BlockPlain)
1840 prevBreak := s.breakTo
1844 if n.Op() == ir.OSWITCH {
1845 n := n.(*ir.SwitchStmt)
1849 n := n.(*ir.SelectStmt)
1858 lab.breakTarget = bEnd
1861 // generate body code
1864 s.breakTo = prevBreak
1866 lab.breakTarget = nil
1869 // walk adds explicit OBREAK nodes to the end of all reachable code paths.
1870 // If we still have a current block here, then mark it unreachable.
1871 if s.curBlock != nil {
1874 b.Kind = ssa.BlockExit
1880 n := n.(*ir.JumpTableStmt)
1882 // Make blocks we'll need.
1883 jt := s.f.NewBlock(ssa.BlockJumpTable)
1884 bEnd := s.f.NewBlock(ssa.BlockPlain)
1886 // The only thing that needs evaluating is the index we're looking up.
1887 idx := s.expr(n.Idx)
1888 unsigned := idx.Type.IsUnsigned()
1890 // Extend so we can do everything in uintptr arithmetic.
1891 t := types.Types[types.TUINTPTR]
1892 idx = s.conv(nil, idx, idx.Type, t)
1894 // The ending condition for the current block decides whether we'll use
1895 // the jump table at all.
1896 // We check that min <= idx <= max and jump around the jump table
1897 // if that test fails.
1898 // We implement min <= idx <= max with 0 <= idx-min <= max-min, because
1899 // we'll need idx-min anyway as the control value for the jump table.
1902 min, _ = constant.Uint64Val(n.Cases[0])
1903 max, _ = constant.Uint64Val(n.Cases[len(n.Cases)-1])
1905 mn, _ := constant.Int64Val(n.Cases[0])
1906 mx, _ := constant.Int64Val(n.Cases[len(n.Cases)-1])
1910 // Compare idx-min with max-min, to see if we can use the jump table.
1911 idx = s.newValue2(s.ssaOp(ir.OSUB, t), t, idx, s.uintptrConstant(min))
1912 width := s.uintptrConstant(max - min)
1913 cmp := s.newValue2(s.ssaOp(ir.OLE, t), types.Types[types.TBOOL], idx, width)
1915 b.Kind = ssa.BlockIf
1917 b.AddEdgeTo(jt) // in range - use jump table
1918 b.AddEdgeTo(bEnd) // out of range - no case in the jump table will trigger
1919 b.Likely = ssa.BranchLikely // TODO: assumes missing the table entirely is unlikely. True?
1921 // Build jump table block.
1924 if base.Flag.Cfg.SpectreIndex {
1925 idx = s.newValue2(ssa.OpSpectreSliceIndex, t, idx, width)
1929 // Figure out where we should go for each index in the table.
1930 table := make([]*ssa.Block, max-min+1)
1931 for i := range table {
1932 table[i] = bEnd // default target
1934 for i := range n.Targets {
1936 lab := s.label(n.Targets[i])
1937 if lab.target == nil {
1938 lab.target = s.f.NewBlock(ssa.BlockPlain)
1942 val, _ = constant.Uint64Val(c)
1944 vl, _ := constant.Int64Val(c)
1947 // Overwrite the default target.
1948 table[val-min] = lab.target
1950 for _, t := range table {
1958 n := n.(*ir.UnaryExpr)
1960 s.vars[memVar] = s.newValue1Apos(ssa.OpVarDef, types.TypeMem, n.X.(*ir.Name), s.mem(), false)
1963 // Insert a varkill op to record that a variable is no longer live.
1964 // We only care about liveness info at call sites, so putting the
1965 // varkill in the store chain is enough to keep it correctly ordered
1966 // with respect to call ops.
1967 n := n.(*ir.UnaryExpr)
1969 s.vars[memVar] = s.newValue1Apos(ssa.OpVarKill, types.TypeMem, n.X.(*ir.Name), s.mem(), false)
1973 // Insert a varlive op to record that a variable is still live.
1974 n := n.(*ir.UnaryExpr)
1977 s.Fatalf("VARLIVE variable %v must have Addrtaken set", v)
1980 case ir.PAUTO, ir.PPARAM, ir.PPARAMOUT:
1982 s.Fatalf("VARLIVE variable %v must be Auto or Arg", v)
1984 s.vars[memVar] = s.newValue1A(ssa.OpVarLive, types.TypeMem, v, s.mem())
1987 n := n.(*ir.UnaryExpr)
1992 n := n.(*ir.InlineMarkStmt)
1993 s.newValue1I(ssa.OpInlMark, types.TypeVoid, n.Index, s.mem())
1996 s.Fatalf("unhandled stmt %v", n.Op())
2000 // If true, share as many open-coded defer exits as possible (with the downside of
2001 // worse line-number information)
2002 const shareDeferExits = false
2004 // exit processes any code that needs to be generated just before returning.
2005 // It returns a BlockRet block that ends the control flow. Its control value
2006 // will be set to the final memory state.
2007 func (s *state) exit() *ssa.Block {
2009 if s.hasOpenDefers {
2010 if shareDeferExits && s.lastDeferExit != nil && len(s.openDefers) == s.lastDeferCount {
2011 if s.curBlock.Kind != ssa.BlockPlain {
2012 panic("Block for an exit should be BlockPlain")
2014 s.curBlock.AddEdgeTo(s.lastDeferExit)
2016 return s.lastDeferFinalBlock
2020 s.rtcall(ir.Syms.Deferreturn, true, nil)
2026 // Do actual return.
2027 // These currently turn into self-copies (in many cases).
2028 resultFields := s.curfn.Type().Results().FieldSlice()
2029 results := make([]*ssa.Value, len(resultFields)+1, len(resultFields)+1)
2030 m = s.newValue0(ssa.OpMakeResult, s.f.OwnAux.LateExpansionResultType())
2031 // Store SSAable and heap-escaped PPARAMOUT variables back to stack locations.
2032 for i, f := range resultFields {
2033 n := f.Nname.(*ir.Name)
2034 if s.canSSA(n) { // result is in some SSA variable
2035 if !n.IsOutputParamInRegisters() {
2036 // We are about to store to the result slot.
2037 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, n, s.mem())
2039 results[i] = s.variable(n, n.Type())
2040 } else if !n.OnStack() { // result is actually heap allocated
2041 // We are about to copy the in-heap result to the result slot.
2042 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, n, s.mem())
2043 ha := s.expr(n.Heapaddr)
2044 s.instrumentFields(n.Type(), ha, instrumentRead)
2045 results[i] = s.newValue2(ssa.OpDereference, n.Type(), ha, s.mem())
2046 } else { // result is not SSA-able; not escaped, so not on heap, but too large for SSA.
2047 // Before register ABI this ought to be a self-move, home=dest,
2048 // With register ABI, it's still a self-move if parameter is on stack (i.e., too big or overflowed)
2049 // No VarDef, as the result slot is already holding live value.
2050 results[i] = s.newValue2(ssa.OpDereference, n.Type(), s.addr(n), s.mem())
2054 // Run exit code. Today, this is just racefuncexit, in -race mode.
2055 // TODO(register args) this seems risky here with a register-ABI, but not clear it is right to do it earlier either.
2056 // Spills in register allocation might just fix it.
2057 s.stmtList(s.curfn.Exit)
2059 results[len(results)-1] = s.mem()
2060 m.AddArgs(results...)
2063 b.Kind = ssa.BlockRet
2065 if s.hasdefer && s.hasOpenDefers {
2066 s.lastDeferFinalBlock = b
2071 type opAndType struct {
2076 var opToSSA = map[opAndType]ssa.Op{
2077 opAndType{ir.OADD, types.TINT8}: ssa.OpAdd8,
2078 opAndType{ir.OADD, types.TUINT8}: ssa.OpAdd8,
2079 opAndType{ir.OADD, types.TINT16}: ssa.OpAdd16,
2080 opAndType{ir.OADD, types.TUINT16}: ssa.OpAdd16,
2081 opAndType{ir.OADD, types.TINT32}: ssa.OpAdd32,
2082 opAndType{ir.OADD, types.TUINT32}: ssa.OpAdd32,
2083 opAndType{ir.OADD, types.TINT64}: ssa.OpAdd64,
2084 opAndType{ir.OADD, types.TUINT64}: ssa.OpAdd64,
2085 opAndType{ir.OADD, types.TFLOAT32}: ssa.OpAdd32F,
2086 opAndType{ir.OADD, types.TFLOAT64}: ssa.OpAdd64F,
2088 opAndType{ir.OSUB, types.TINT8}: ssa.OpSub8,
2089 opAndType{ir.OSUB, types.TUINT8}: ssa.OpSub8,
2090 opAndType{ir.OSUB, types.TINT16}: ssa.OpSub16,
2091 opAndType{ir.OSUB, types.TUINT16}: ssa.OpSub16,
2092 opAndType{ir.OSUB, types.TINT32}: ssa.OpSub32,
2093 opAndType{ir.OSUB, types.TUINT32}: ssa.OpSub32,
2094 opAndType{ir.OSUB, types.TINT64}: ssa.OpSub64,
2095 opAndType{ir.OSUB, types.TUINT64}: ssa.OpSub64,
2096 opAndType{ir.OSUB, types.TFLOAT32}: ssa.OpSub32F,
2097 opAndType{ir.OSUB, types.TFLOAT64}: ssa.OpSub64F,
2099 opAndType{ir.ONOT, types.TBOOL}: ssa.OpNot,
2101 opAndType{ir.ONEG, types.TINT8}: ssa.OpNeg8,
2102 opAndType{ir.ONEG, types.TUINT8}: ssa.OpNeg8,
2103 opAndType{ir.ONEG, types.TINT16}: ssa.OpNeg16,
2104 opAndType{ir.ONEG, types.TUINT16}: ssa.OpNeg16,
2105 opAndType{ir.ONEG, types.TINT32}: ssa.OpNeg32,
2106 opAndType{ir.ONEG, types.TUINT32}: ssa.OpNeg32,
2107 opAndType{ir.ONEG, types.TINT64}: ssa.OpNeg64,
2108 opAndType{ir.ONEG, types.TUINT64}: ssa.OpNeg64,
2109 opAndType{ir.ONEG, types.TFLOAT32}: ssa.OpNeg32F,
2110 opAndType{ir.ONEG, types.TFLOAT64}: ssa.OpNeg64F,
2112 opAndType{ir.OBITNOT, types.TINT8}: ssa.OpCom8,
2113 opAndType{ir.OBITNOT, types.TUINT8}: ssa.OpCom8,
2114 opAndType{ir.OBITNOT, types.TINT16}: ssa.OpCom16,
2115 opAndType{ir.OBITNOT, types.TUINT16}: ssa.OpCom16,
2116 opAndType{ir.OBITNOT, types.TINT32}: ssa.OpCom32,
2117 opAndType{ir.OBITNOT, types.TUINT32}: ssa.OpCom32,
2118 opAndType{ir.OBITNOT, types.TINT64}: ssa.OpCom64,
2119 opAndType{ir.OBITNOT, types.TUINT64}: ssa.OpCom64,
2121 opAndType{ir.OIMAG, types.TCOMPLEX64}: ssa.OpComplexImag,
2122 opAndType{ir.OIMAG, types.TCOMPLEX128}: ssa.OpComplexImag,
2123 opAndType{ir.OREAL, types.TCOMPLEX64}: ssa.OpComplexReal,
2124 opAndType{ir.OREAL, types.TCOMPLEX128}: ssa.OpComplexReal,
2126 opAndType{ir.OMUL, types.TINT8}: ssa.OpMul8,
2127 opAndType{ir.OMUL, types.TUINT8}: ssa.OpMul8,
2128 opAndType{ir.OMUL, types.TINT16}: ssa.OpMul16,
2129 opAndType{ir.OMUL, types.TUINT16}: ssa.OpMul16,
2130 opAndType{ir.OMUL, types.TINT32}: ssa.OpMul32,
2131 opAndType{ir.OMUL, types.TUINT32}: ssa.OpMul32,
2132 opAndType{ir.OMUL, types.TINT64}: ssa.OpMul64,
2133 opAndType{ir.OMUL, types.TUINT64}: ssa.OpMul64,
2134 opAndType{ir.OMUL, types.TFLOAT32}: ssa.OpMul32F,
2135 opAndType{ir.OMUL, types.TFLOAT64}: ssa.OpMul64F,
2137 opAndType{ir.ODIV, types.TFLOAT32}: ssa.OpDiv32F,
2138 opAndType{ir.ODIV, types.TFLOAT64}: ssa.OpDiv64F,
2140 opAndType{ir.ODIV, types.TINT8}: ssa.OpDiv8,
2141 opAndType{ir.ODIV, types.TUINT8}: ssa.OpDiv8u,
2142 opAndType{ir.ODIV, types.TINT16}: ssa.OpDiv16,
2143 opAndType{ir.ODIV, types.TUINT16}: ssa.OpDiv16u,
2144 opAndType{ir.ODIV, types.TINT32}: ssa.OpDiv32,
2145 opAndType{ir.ODIV, types.TUINT32}: ssa.OpDiv32u,
2146 opAndType{ir.ODIV, types.TINT64}: ssa.OpDiv64,
2147 opAndType{ir.ODIV, types.TUINT64}: ssa.OpDiv64u,
2149 opAndType{ir.OMOD, types.TINT8}: ssa.OpMod8,
2150 opAndType{ir.OMOD, types.TUINT8}: ssa.OpMod8u,
2151 opAndType{ir.OMOD, types.TINT16}: ssa.OpMod16,
2152 opAndType{ir.OMOD, types.TUINT16}: ssa.OpMod16u,
2153 opAndType{ir.OMOD, types.TINT32}: ssa.OpMod32,
2154 opAndType{ir.OMOD, types.TUINT32}: ssa.OpMod32u,
2155 opAndType{ir.OMOD, types.TINT64}: ssa.OpMod64,
2156 opAndType{ir.OMOD, types.TUINT64}: ssa.OpMod64u,
2158 opAndType{ir.OAND, types.TINT8}: ssa.OpAnd8,
2159 opAndType{ir.OAND, types.TUINT8}: ssa.OpAnd8,
2160 opAndType{ir.OAND, types.TINT16}: ssa.OpAnd16,
2161 opAndType{ir.OAND, types.TUINT16}: ssa.OpAnd16,
2162 opAndType{ir.OAND, types.TINT32}: ssa.OpAnd32,
2163 opAndType{ir.OAND, types.TUINT32}: ssa.OpAnd32,
2164 opAndType{ir.OAND, types.TINT64}: ssa.OpAnd64,
2165 opAndType{ir.OAND, types.TUINT64}: ssa.OpAnd64,
2167 opAndType{ir.OOR, types.TINT8}: ssa.OpOr8,
2168 opAndType{ir.OOR, types.TUINT8}: ssa.OpOr8,
2169 opAndType{ir.OOR, types.TINT16}: ssa.OpOr16,
2170 opAndType{ir.OOR, types.TUINT16}: ssa.OpOr16,
2171 opAndType{ir.OOR, types.TINT32}: ssa.OpOr32,
2172 opAndType{ir.OOR, types.TUINT32}: ssa.OpOr32,
2173 opAndType{ir.OOR, types.TINT64}: ssa.OpOr64,
2174 opAndType{ir.OOR, types.TUINT64}: ssa.OpOr64,
2176 opAndType{ir.OXOR, types.TINT8}: ssa.OpXor8,
2177 opAndType{ir.OXOR, types.TUINT8}: ssa.OpXor8,
2178 opAndType{ir.OXOR, types.TINT16}: ssa.OpXor16,
2179 opAndType{ir.OXOR, types.TUINT16}: ssa.OpXor16,
2180 opAndType{ir.OXOR, types.TINT32}: ssa.OpXor32,
2181 opAndType{ir.OXOR, types.TUINT32}: ssa.OpXor32,
2182 opAndType{ir.OXOR, types.TINT64}: ssa.OpXor64,
2183 opAndType{ir.OXOR, types.TUINT64}: ssa.OpXor64,
2185 opAndType{ir.OEQ, types.TBOOL}: ssa.OpEqB,
2186 opAndType{ir.OEQ, types.TINT8}: ssa.OpEq8,
2187 opAndType{ir.OEQ, types.TUINT8}: ssa.OpEq8,
2188 opAndType{ir.OEQ, types.TINT16}: ssa.OpEq16,
2189 opAndType{ir.OEQ, types.TUINT16}: ssa.OpEq16,
2190 opAndType{ir.OEQ, types.TINT32}: ssa.OpEq32,
2191 opAndType{ir.OEQ, types.TUINT32}: ssa.OpEq32,
2192 opAndType{ir.OEQ, types.TINT64}: ssa.OpEq64,
2193 opAndType{ir.OEQ, types.TUINT64}: ssa.OpEq64,
2194 opAndType{ir.OEQ, types.TINTER}: ssa.OpEqInter,
2195 opAndType{ir.OEQ, types.TSLICE}: ssa.OpEqSlice,
2196 opAndType{ir.OEQ, types.TFUNC}: ssa.OpEqPtr,
2197 opAndType{ir.OEQ, types.TMAP}: ssa.OpEqPtr,
2198 opAndType{ir.OEQ, types.TCHAN}: ssa.OpEqPtr,
2199 opAndType{ir.OEQ, types.TPTR}: ssa.OpEqPtr,
2200 opAndType{ir.OEQ, types.TUINTPTR}: ssa.OpEqPtr,
2201 opAndType{ir.OEQ, types.TUNSAFEPTR}: ssa.OpEqPtr,
2202 opAndType{ir.OEQ, types.TFLOAT64}: ssa.OpEq64F,
2203 opAndType{ir.OEQ, types.TFLOAT32}: ssa.OpEq32F,
2205 opAndType{ir.ONE, types.TBOOL}: ssa.OpNeqB,
2206 opAndType{ir.ONE, types.TINT8}: ssa.OpNeq8,
2207 opAndType{ir.ONE, types.TUINT8}: ssa.OpNeq8,
2208 opAndType{ir.ONE, types.TINT16}: ssa.OpNeq16,
2209 opAndType{ir.ONE, types.TUINT16}: ssa.OpNeq16,
2210 opAndType{ir.ONE, types.TINT32}: ssa.OpNeq32,
2211 opAndType{ir.ONE, types.TUINT32}: ssa.OpNeq32,
2212 opAndType{ir.ONE, types.TINT64}: ssa.OpNeq64,
2213 opAndType{ir.ONE, types.TUINT64}: ssa.OpNeq64,
2214 opAndType{ir.ONE, types.TINTER}: ssa.OpNeqInter,
2215 opAndType{ir.ONE, types.TSLICE}: ssa.OpNeqSlice,
2216 opAndType{ir.ONE, types.TFUNC}: ssa.OpNeqPtr,
2217 opAndType{ir.ONE, types.TMAP}: ssa.OpNeqPtr,
2218 opAndType{ir.ONE, types.TCHAN}: ssa.OpNeqPtr,
2219 opAndType{ir.ONE, types.TPTR}: ssa.OpNeqPtr,
2220 opAndType{ir.ONE, types.TUINTPTR}: ssa.OpNeqPtr,
2221 opAndType{ir.ONE, types.TUNSAFEPTR}: ssa.OpNeqPtr,
2222 opAndType{ir.ONE, types.TFLOAT64}: ssa.OpNeq64F,
2223 opAndType{ir.ONE, types.TFLOAT32}: ssa.OpNeq32F,
2225 opAndType{ir.OLT, types.TINT8}: ssa.OpLess8,
2226 opAndType{ir.OLT, types.TUINT8}: ssa.OpLess8U,
2227 opAndType{ir.OLT, types.TINT16}: ssa.OpLess16,
2228 opAndType{ir.OLT, types.TUINT16}: ssa.OpLess16U,
2229 opAndType{ir.OLT, types.TINT32}: ssa.OpLess32,
2230 opAndType{ir.OLT, types.TUINT32}: ssa.OpLess32U,
2231 opAndType{ir.OLT, types.TINT64}: ssa.OpLess64,
2232 opAndType{ir.OLT, types.TUINT64}: ssa.OpLess64U,
2233 opAndType{ir.OLT, types.TFLOAT64}: ssa.OpLess64F,
2234 opAndType{ir.OLT, types.TFLOAT32}: ssa.OpLess32F,
2236 opAndType{ir.OLE, types.TINT8}: ssa.OpLeq8,
2237 opAndType{ir.OLE, types.TUINT8}: ssa.OpLeq8U,
2238 opAndType{ir.OLE, types.TINT16}: ssa.OpLeq16,
2239 opAndType{ir.OLE, types.TUINT16}: ssa.OpLeq16U,
2240 opAndType{ir.OLE, types.TINT32}: ssa.OpLeq32,
2241 opAndType{ir.OLE, types.TUINT32}: ssa.OpLeq32U,
2242 opAndType{ir.OLE, types.TINT64}: ssa.OpLeq64,
2243 opAndType{ir.OLE, types.TUINT64}: ssa.OpLeq64U,
2244 opAndType{ir.OLE, types.TFLOAT64}: ssa.OpLeq64F,
2245 opAndType{ir.OLE, types.TFLOAT32}: ssa.OpLeq32F,
2248 func (s *state) concreteEtype(t *types.Type) types.Kind {
2254 if s.config.PtrSize == 8 {
2259 if s.config.PtrSize == 8 {
2260 return types.TUINT64
2262 return types.TUINT32
2263 case types.TUINTPTR:
2264 if s.config.PtrSize == 8 {
2265 return types.TUINT64
2267 return types.TUINT32
2271 func (s *state) ssaOp(op ir.Op, t *types.Type) ssa.Op {
2272 etype := s.concreteEtype(t)
2273 x, ok := opToSSA[opAndType{op, etype}]
2275 s.Fatalf("unhandled binary op %v %s", op, etype)
2280 type opAndTwoTypes struct {
2286 type twoTypes struct {
2291 type twoOpsAndType struct {
2294 intermediateType types.Kind
2297 var fpConvOpToSSA = map[twoTypes]twoOpsAndType{
2299 twoTypes{types.TINT8, types.TFLOAT32}: twoOpsAndType{ssa.OpSignExt8to32, ssa.OpCvt32to32F, types.TINT32},
2300 twoTypes{types.TINT16, types.TFLOAT32}: twoOpsAndType{ssa.OpSignExt16to32, ssa.OpCvt32to32F, types.TINT32},
2301 twoTypes{types.TINT32, types.TFLOAT32}: twoOpsAndType{ssa.OpCopy, ssa.OpCvt32to32F, types.TINT32},
2302 twoTypes{types.TINT64, types.TFLOAT32}: twoOpsAndType{ssa.OpCopy, ssa.OpCvt64to32F, types.TINT64},
2304 twoTypes{types.TINT8, types.TFLOAT64}: twoOpsAndType{ssa.OpSignExt8to32, ssa.OpCvt32to64F, types.TINT32},
2305 twoTypes{types.TINT16, types.TFLOAT64}: twoOpsAndType{ssa.OpSignExt16to32, ssa.OpCvt32to64F, types.TINT32},
2306 twoTypes{types.TINT32, types.TFLOAT64}: twoOpsAndType{ssa.OpCopy, ssa.OpCvt32to64F, types.TINT32},
2307 twoTypes{types.TINT64, types.TFLOAT64}: twoOpsAndType{ssa.OpCopy, ssa.OpCvt64to64F, types.TINT64},
2309 twoTypes{types.TFLOAT32, types.TINT8}: twoOpsAndType{ssa.OpCvt32Fto32, ssa.OpTrunc32to8, types.TINT32},
2310 twoTypes{types.TFLOAT32, types.TINT16}: twoOpsAndType{ssa.OpCvt32Fto32, ssa.OpTrunc32to16, types.TINT32},
2311 twoTypes{types.TFLOAT32, types.TINT32}: twoOpsAndType{ssa.OpCvt32Fto32, ssa.OpCopy, types.TINT32},
2312 twoTypes{types.TFLOAT32, types.TINT64}: twoOpsAndType{ssa.OpCvt32Fto64, ssa.OpCopy, types.TINT64},
2314 twoTypes{types.TFLOAT64, types.TINT8}: twoOpsAndType{ssa.OpCvt64Fto32, ssa.OpTrunc32to8, types.TINT32},
2315 twoTypes{types.TFLOAT64, types.TINT16}: twoOpsAndType{ssa.OpCvt64Fto32, ssa.OpTrunc32to16, types.TINT32},
2316 twoTypes{types.TFLOAT64, types.TINT32}: twoOpsAndType{ssa.OpCvt64Fto32, ssa.OpCopy, types.TINT32},
2317 twoTypes{types.TFLOAT64, types.TINT64}: twoOpsAndType{ssa.OpCvt64Fto64, ssa.OpCopy, types.TINT64},
2319 twoTypes{types.TUINT8, types.TFLOAT32}: twoOpsAndType{ssa.OpZeroExt8to32, ssa.OpCvt32to32F, types.TINT32},
2320 twoTypes{types.TUINT16, types.TFLOAT32}: twoOpsAndType{ssa.OpZeroExt16to32, ssa.OpCvt32to32F, types.TINT32},
2321 twoTypes{types.TUINT32, types.TFLOAT32}: twoOpsAndType{ssa.OpZeroExt32to64, ssa.OpCvt64to32F, types.TINT64}, // go wide to dodge unsigned
2322 twoTypes{types.TUINT64, types.TFLOAT32}: twoOpsAndType{ssa.OpCopy, ssa.OpInvalid, types.TUINT64}, // Cvt64Uto32F, branchy code expansion instead
2324 twoTypes{types.TUINT8, types.TFLOAT64}: twoOpsAndType{ssa.OpZeroExt8to32, ssa.OpCvt32to64F, types.TINT32},
2325 twoTypes{types.TUINT16, types.TFLOAT64}: twoOpsAndType{ssa.OpZeroExt16to32, ssa.OpCvt32to64F, types.TINT32},
2326 twoTypes{types.TUINT32, types.TFLOAT64}: twoOpsAndType{ssa.OpZeroExt32to64, ssa.OpCvt64to64F, types.TINT64}, // go wide to dodge unsigned
2327 twoTypes{types.TUINT64, types.TFLOAT64}: twoOpsAndType{ssa.OpCopy, ssa.OpInvalid, types.TUINT64}, // Cvt64Uto64F, branchy code expansion instead
2329 twoTypes{types.TFLOAT32, types.TUINT8}: twoOpsAndType{ssa.OpCvt32Fto32, ssa.OpTrunc32to8, types.TINT32},
2330 twoTypes{types.TFLOAT32, types.TUINT16}: twoOpsAndType{ssa.OpCvt32Fto32, ssa.OpTrunc32to16, types.TINT32},
2331 twoTypes{types.TFLOAT32, types.TUINT32}: twoOpsAndType{ssa.OpCvt32Fto64, ssa.OpTrunc64to32, types.TINT64}, // go wide to dodge unsigned
2332 twoTypes{types.TFLOAT32, types.TUINT64}: twoOpsAndType{ssa.OpInvalid, ssa.OpCopy, types.TUINT64}, // Cvt32Fto64U, branchy code expansion instead
2334 twoTypes{types.TFLOAT64, types.TUINT8}: twoOpsAndType{ssa.OpCvt64Fto32, ssa.OpTrunc32to8, types.TINT32},
2335 twoTypes{types.TFLOAT64, types.TUINT16}: twoOpsAndType{ssa.OpCvt64Fto32, ssa.OpTrunc32to16, types.TINT32},
2336 twoTypes{types.TFLOAT64, types.TUINT32}: twoOpsAndType{ssa.OpCvt64Fto64, ssa.OpTrunc64to32, types.TINT64}, // go wide to dodge unsigned
2337 twoTypes{types.TFLOAT64, types.TUINT64}: twoOpsAndType{ssa.OpInvalid, ssa.OpCopy, types.TUINT64}, // Cvt64Fto64U, branchy code expansion instead
2340 twoTypes{types.TFLOAT64, types.TFLOAT32}: twoOpsAndType{ssa.OpCvt64Fto32F, ssa.OpCopy, types.TFLOAT32},
2341 twoTypes{types.TFLOAT64, types.TFLOAT64}: twoOpsAndType{ssa.OpRound64F, ssa.OpCopy, types.TFLOAT64},
2342 twoTypes{types.TFLOAT32, types.TFLOAT32}: twoOpsAndType{ssa.OpRound32F, ssa.OpCopy, types.TFLOAT32},
2343 twoTypes{types.TFLOAT32, types.TFLOAT64}: twoOpsAndType{ssa.OpCvt32Fto64F, ssa.OpCopy, types.TFLOAT64},
2346 // this map is used only for 32-bit arch, and only includes the difference
2347 // on 32-bit arch, don't use int64<->float conversion for uint32
2348 var fpConvOpToSSA32 = map[twoTypes]twoOpsAndType{
2349 twoTypes{types.TUINT32, types.TFLOAT32}: twoOpsAndType{ssa.OpCopy, ssa.OpCvt32Uto32F, types.TUINT32},
2350 twoTypes{types.TUINT32, types.TFLOAT64}: twoOpsAndType{ssa.OpCopy, ssa.OpCvt32Uto64F, types.TUINT32},
2351 twoTypes{types.TFLOAT32, types.TUINT32}: twoOpsAndType{ssa.OpCvt32Fto32U, ssa.OpCopy, types.TUINT32},
2352 twoTypes{types.TFLOAT64, types.TUINT32}: twoOpsAndType{ssa.OpCvt64Fto32U, ssa.OpCopy, types.TUINT32},
2355 // uint64<->float conversions, only on machines that have instructions for that
2356 var uint64fpConvOpToSSA = map[twoTypes]twoOpsAndType{
2357 twoTypes{types.TUINT64, types.TFLOAT32}: twoOpsAndType{ssa.OpCopy, ssa.OpCvt64Uto32F, types.TUINT64},
2358 twoTypes{types.TUINT64, types.TFLOAT64}: twoOpsAndType{ssa.OpCopy, ssa.OpCvt64Uto64F, types.TUINT64},
2359 twoTypes{types.TFLOAT32, types.TUINT64}: twoOpsAndType{ssa.OpCvt32Fto64U, ssa.OpCopy, types.TUINT64},
2360 twoTypes{types.TFLOAT64, types.TUINT64}: twoOpsAndType{ssa.OpCvt64Fto64U, ssa.OpCopy, types.TUINT64},
2363 var shiftOpToSSA = map[opAndTwoTypes]ssa.Op{
2364 opAndTwoTypes{ir.OLSH, types.TINT8, types.TUINT8}: ssa.OpLsh8x8,
2365 opAndTwoTypes{ir.OLSH, types.TUINT8, types.TUINT8}: ssa.OpLsh8x8,
2366 opAndTwoTypes{ir.OLSH, types.TINT8, types.TUINT16}: ssa.OpLsh8x16,
2367 opAndTwoTypes{ir.OLSH, types.TUINT8, types.TUINT16}: ssa.OpLsh8x16,
2368 opAndTwoTypes{ir.OLSH, types.TINT8, types.TUINT32}: ssa.OpLsh8x32,
2369 opAndTwoTypes{ir.OLSH, types.TUINT8, types.TUINT32}: ssa.OpLsh8x32,
2370 opAndTwoTypes{ir.OLSH, types.TINT8, types.TUINT64}: ssa.OpLsh8x64,
2371 opAndTwoTypes{ir.OLSH, types.TUINT8, types.TUINT64}: ssa.OpLsh8x64,
2373 opAndTwoTypes{ir.OLSH, types.TINT16, types.TUINT8}: ssa.OpLsh16x8,
2374 opAndTwoTypes{ir.OLSH, types.TUINT16, types.TUINT8}: ssa.OpLsh16x8,
2375 opAndTwoTypes{ir.OLSH, types.TINT16, types.TUINT16}: ssa.OpLsh16x16,
2376 opAndTwoTypes{ir.OLSH, types.TUINT16, types.TUINT16}: ssa.OpLsh16x16,
2377 opAndTwoTypes{ir.OLSH, types.TINT16, types.TUINT32}: ssa.OpLsh16x32,
2378 opAndTwoTypes{ir.OLSH, types.TUINT16, types.TUINT32}: ssa.OpLsh16x32,
2379 opAndTwoTypes{ir.OLSH, types.TINT16, types.TUINT64}: ssa.OpLsh16x64,
2380 opAndTwoTypes{ir.OLSH, types.TUINT16, types.TUINT64}: ssa.OpLsh16x64,
2382 opAndTwoTypes{ir.OLSH, types.TINT32, types.TUINT8}: ssa.OpLsh32x8,
2383 opAndTwoTypes{ir.OLSH, types.TUINT32, types.TUINT8}: ssa.OpLsh32x8,
2384 opAndTwoTypes{ir.OLSH, types.TINT32, types.TUINT16}: ssa.OpLsh32x16,
2385 opAndTwoTypes{ir.OLSH, types.TUINT32, types.TUINT16}: ssa.OpLsh32x16,
2386 opAndTwoTypes{ir.OLSH, types.TINT32, types.TUINT32}: ssa.OpLsh32x32,
2387 opAndTwoTypes{ir.OLSH, types.TUINT32, types.TUINT32}: ssa.OpLsh32x32,
2388 opAndTwoTypes{ir.OLSH, types.TINT32, types.TUINT64}: ssa.OpLsh32x64,
2389 opAndTwoTypes{ir.OLSH, types.TUINT32, types.TUINT64}: ssa.OpLsh32x64,
2391 opAndTwoTypes{ir.OLSH, types.TINT64, types.TUINT8}: ssa.OpLsh64x8,
2392 opAndTwoTypes{ir.OLSH, types.TUINT64, types.TUINT8}: ssa.OpLsh64x8,
2393 opAndTwoTypes{ir.OLSH, types.TINT64, types.TUINT16}: ssa.OpLsh64x16,
2394 opAndTwoTypes{ir.OLSH, types.TUINT64, types.TUINT16}: ssa.OpLsh64x16,
2395 opAndTwoTypes{ir.OLSH, types.TINT64, types.TUINT32}: ssa.OpLsh64x32,
2396 opAndTwoTypes{ir.OLSH, types.TUINT64, types.TUINT32}: ssa.OpLsh64x32,
2397 opAndTwoTypes{ir.OLSH, types.TINT64, types.TUINT64}: ssa.OpLsh64x64,
2398 opAndTwoTypes{ir.OLSH, types.TUINT64, types.TUINT64}: ssa.OpLsh64x64,
2400 opAndTwoTypes{ir.ORSH, types.TINT8, types.TUINT8}: ssa.OpRsh8x8,
2401 opAndTwoTypes{ir.ORSH, types.TUINT8, types.TUINT8}: ssa.OpRsh8Ux8,
2402 opAndTwoTypes{ir.ORSH, types.TINT8, types.TUINT16}: ssa.OpRsh8x16,
2403 opAndTwoTypes{ir.ORSH, types.TUINT8, types.TUINT16}: ssa.OpRsh8Ux16,
2404 opAndTwoTypes{ir.ORSH, types.TINT8, types.TUINT32}: ssa.OpRsh8x32,
2405 opAndTwoTypes{ir.ORSH, types.TUINT8, types.TUINT32}: ssa.OpRsh8Ux32,
2406 opAndTwoTypes{ir.ORSH, types.TINT8, types.TUINT64}: ssa.OpRsh8x64,
2407 opAndTwoTypes{ir.ORSH, types.TUINT8, types.TUINT64}: ssa.OpRsh8Ux64,
2409 opAndTwoTypes{ir.ORSH, types.TINT16, types.TUINT8}: ssa.OpRsh16x8,
2410 opAndTwoTypes{ir.ORSH, types.TUINT16, types.TUINT8}: ssa.OpRsh16Ux8,
2411 opAndTwoTypes{ir.ORSH, types.TINT16, types.TUINT16}: ssa.OpRsh16x16,
2412 opAndTwoTypes{ir.ORSH, types.TUINT16, types.TUINT16}: ssa.OpRsh16Ux16,
2413 opAndTwoTypes{ir.ORSH, types.TINT16, types.TUINT32}: ssa.OpRsh16x32,
2414 opAndTwoTypes{ir.ORSH, types.TUINT16, types.TUINT32}: ssa.OpRsh16Ux32,
2415 opAndTwoTypes{ir.ORSH, types.TINT16, types.TUINT64}: ssa.OpRsh16x64,
2416 opAndTwoTypes{ir.ORSH, types.TUINT16, types.TUINT64}: ssa.OpRsh16Ux64,
2418 opAndTwoTypes{ir.ORSH, types.TINT32, types.TUINT8}: ssa.OpRsh32x8,
2419 opAndTwoTypes{ir.ORSH, types.TUINT32, types.TUINT8}: ssa.OpRsh32Ux8,
2420 opAndTwoTypes{ir.ORSH, types.TINT32, types.TUINT16}: ssa.OpRsh32x16,
2421 opAndTwoTypes{ir.ORSH, types.TUINT32, types.TUINT16}: ssa.OpRsh32Ux16,
2422 opAndTwoTypes{ir.ORSH, types.TINT32, types.TUINT32}: ssa.OpRsh32x32,
2423 opAndTwoTypes{ir.ORSH, types.TUINT32, types.TUINT32}: ssa.OpRsh32Ux32,
2424 opAndTwoTypes{ir.ORSH, types.TINT32, types.TUINT64}: ssa.OpRsh32x64,
2425 opAndTwoTypes{ir.ORSH, types.TUINT32, types.TUINT64}: ssa.OpRsh32Ux64,
2427 opAndTwoTypes{ir.ORSH, types.TINT64, types.TUINT8}: ssa.OpRsh64x8,
2428 opAndTwoTypes{ir.ORSH, types.TUINT64, types.TUINT8}: ssa.OpRsh64Ux8,
2429 opAndTwoTypes{ir.ORSH, types.TINT64, types.TUINT16}: ssa.OpRsh64x16,
2430 opAndTwoTypes{ir.ORSH, types.TUINT64, types.TUINT16}: ssa.OpRsh64Ux16,
2431 opAndTwoTypes{ir.ORSH, types.TINT64, types.TUINT32}: ssa.OpRsh64x32,
2432 opAndTwoTypes{ir.ORSH, types.TUINT64, types.TUINT32}: ssa.OpRsh64Ux32,
2433 opAndTwoTypes{ir.ORSH, types.TINT64, types.TUINT64}: ssa.OpRsh64x64,
2434 opAndTwoTypes{ir.ORSH, types.TUINT64, types.TUINT64}: ssa.OpRsh64Ux64,
2437 func (s *state) ssaShiftOp(op ir.Op, t *types.Type, u *types.Type) ssa.Op {
2438 etype1 := s.concreteEtype(t)
2439 etype2 := s.concreteEtype(u)
2440 x, ok := shiftOpToSSA[opAndTwoTypes{op, etype1, etype2}]
2442 s.Fatalf("unhandled shift op %v etype=%s/%s", op, etype1, etype2)
2447 func (s *state) uintptrConstant(v uint64) *ssa.Value {
2448 if s.config.PtrSize == 4 {
2449 return s.newValue0I(ssa.OpConst32, types.Types[types.TUINTPTR], int64(v))
2451 return s.newValue0I(ssa.OpConst64, types.Types[types.TUINTPTR], int64(v))
2454 func (s *state) conv(n ir.Node, v *ssa.Value, ft, tt *types.Type) *ssa.Value {
2455 if ft.IsBoolean() && tt.IsKind(types.TUINT8) {
2456 // Bool -> uint8 is generated internally when indexing into runtime.staticbyte.
2457 return s.newValue1(ssa.OpCvtBoolToUint8, tt, v)
2459 if ft.IsInteger() && tt.IsInteger() {
2461 if tt.Size() == ft.Size() {
2463 } else if tt.Size() < ft.Size() {
2465 switch 10*ft.Size() + tt.Size() {
2467 op = ssa.OpTrunc16to8
2469 op = ssa.OpTrunc32to8
2471 op = ssa.OpTrunc32to16
2473 op = ssa.OpTrunc64to8
2475 op = ssa.OpTrunc64to16
2477 op = ssa.OpTrunc64to32
2479 s.Fatalf("weird integer truncation %v -> %v", ft, tt)
2481 } else if ft.IsSigned() {
2483 switch 10*ft.Size() + tt.Size() {
2485 op = ssa.OpSignExt8to16
2487 op = ssa.OpSignExt8to32
2489 op = ssa.OpSignExt8to64
2491 op = ssa.OpSignExt16to32
2493 op = ssa.OpSignExt16to64
2495 op = ssa.OpSignExt32to64
2497 s.Fatalf("bad integer sign extension %v -> %v", ft, tt)
2501 switch 10*ft.Size() + tt.Size() {
2503 op = ssa.OpZeroExt8to16
2505 op = ssa.OpZeroExt8to32
2507 op = ssa.OpZeroExt8to64
2509 op = ssa.OpZeroExt16to32
2511 op = ssa.OpZeroExt16to64
2513 op = ssa.OpZeroExt32to64
2515 s.Fatalf("weird integer sign extension %v -> %v", ft, tt)
2518 return s.newValue1(op, tt, v)
2521 if ft.IsComplex() && tt.IsComplex() {
2523 if ft.Size() == tt.Size() {
2530 s.Fatalf("weird complex conversion %v -> %v", ft, tt)
2532 } else if ft.Size() == 8 && tt.Size() == 16 {
2533 op = ssa.OpCvt32Fto64F
2534 } else if ft.Size() == 16 && tt.Size() == 8 {
2535 op = ssa.OpCvt64Fto32F
2537 s.Fatalf("weird complex conversion %v -> %v", ft, tt)
2539 ftp := types.FloatForComplex(ft)
2540 ttp := types.FloatForComplex(tt)
2541 return s.newValue2(ssa.OpComplexMake, tt,
2542 s.newValueOrSfCall1(op, ttp, s.newValue1(ssa.OpComplexReal, ftp, v)),
2543 s.newValueOrSfCall1(op, ttp, s.newValue1(ssa.OpComplexImag, ftp, v)))
2546 if tt.IsComplex() { // and ft is not complex
2547 // Needed for generics support - can't happen in normal Go code.
2548 et := types.FloatForComplex(tt)
2549 v = s.conv(n, v, ft, et)
2550 return s.newValue2(ssa.OpComplexMake, tt, v, s.zeroVal(et))
2553 if ft.IsFloat() || tt.IsFloat() {
2554 conv, ok := fpConvOpToSSA[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]
2555 if s.config.RegSize == 4 && Arch.LinkArch.Family != sys.MIPS && !s.softFloat {
2556 if conv1, ok1 := fpConvOpToSSA32[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]; ok1 {
2560 if Arch.LinkArch.Family == sys.ARM64 || Arch.LinkArch.Family == sys.Wasm || Arch.LinkArch.Family == sys.S390X || s.softFloat {
2561 if conv1, ok1 := uint64fpConvOpToSSA[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]; ok1 {
2566 if Arch.LinkArch.Family == sys.MIPS && !s.softFloat {
2567 if ft.Size() == 4 && ft.IsInteger() && !ft.IsSigned() {
2568 // tt is float32 or float64, and ft is also unsigned
2570 return s.uint32Tofloat32(n, v, ft, tt)
2573 return s.uint32Tofloat64(n, v, ft, tt)
2575 } else if tt.Size() == 4 && tt.IsInteger() && !tt.IsSigned() {
2576 // ft is float32 or float64, and tt is unsigned integer
2578 return s.float32ToUint32(n, v, ft, tt)
2581 return s.float64ToUint32(n, v, ft, tt)
2587 s.Fatalf("weird float conversion %v -> %v", ft, tt)
2589 op1, op2, it := conv.op1, conv.op2, conv.intermediateType
2591 if op1 != ssa.OpInvalid && op2 != ssa.OpInvalid {
2592 // normal case, not tripping over unsigned 64
2593 if op1 == ssa.OpCopy {
2594 if op2 == ssa.OpCopy {
2597 return s.newValueOrSfCall1(op2, tt, v)
2599 if op2 == ssa.OpCopy {
2600 return s.newValueOrSfCall1(op1, tt, v)
2602 return s.newValueOrSfCall1(op2, tt, s.newValueOrSfCall1(op1, types.Types[it], v))
2604 // Tricky 64-bit unsigned cases.
2606 // tt is float32 or float64, and ft is also unsigned
2608 return s.uint64Tofloat32(n, v, ft, tt)
2611 return s.uint64Tofloat64(n, v, ft, tt)
2613 s.Fatalf("weird unsigned integer to float conversion %v -> %v", ft, tt)
2615 // ft is float32 or float64, and tt is unsigned integer
2617 return s.float32ToUint64(n, v, ft, tt)
2620 return s.float64ToUint64(n, v, ft, tt)
2622 s.Fatalf("weird float to unsigned integer conversion %v -> %v", ft, tt)
2626 s.Fatalf("unhandled OCONV %s -> %s", ft.Kind(), tt.Kind())
2630 // expr converts the expression n to ssa, adds it to s and returns the ssa result.
2631 func (s *state) expr(n ir.Node) *ssa.Value {
2632 return s.exprCheckPtr(n, true)
2635 func (s *state) exprCheckPtr(n ir.Node, checkPtrOK bool) *ssa.Value {
2636 if ir.HasUniquePos(n) {
2637 // ONAMEs and named OLITERALs have the line number
2638 // of the decl, not the use. See issue 14742.
2643 s.stmtList(n.Init())
2645 case ir.OBYTES2STRTMP:
2646 n := n.(*ir.ConvExpr)
2647 slice := s.expr(n.X)
2648 ptr := s.newValue1(ssa.OpSlicePtr, s.f.Config.Types.BytePtr, slice)
2649 len := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], slice)
2650 return s.newValue2(ssa.OpStringMake, n.Type(), ptr, len)
2651 case ir.OSTR2BYTESTMP:
2652 n := n.(*ir.ConvExpr)
2654 ptr := s.newValue1(ssa.OpStringPtr, s.f.Config.Types.BytePtr, str)
2655 len := s.newValue1(ssa.OpStringLen, types.Types[types.TINT], str)
2656 return s.newValue3(ssa.OpSliceMake, n.Type(), ptr, len, len)
2658 n := n.(*ir.UnaryExpr)
2659 aux := n.X.(*ir.Name).Linksym()
2660 // OCFUNC is used to build function values, which must
2661 // always reference ABIInternal entry points.
2662 if aux.ABI() != obj.ABIInternal {
2663 s.Fatalf("expected ABIInternal: %v", aux.ABI())
2665 return s.entryNewValue1A(ssa.OpAddr, n.Type(), aux, s.sb)
2668 if n.Class == ir.PFUNC {
2669 // "value" of a function is the address of the function's closure
2670 sym := staticdata.FuncLinksym(n)
2671 return s.entryNewValue1A(ssa.OpAddr, types.NewPtr(n.Type()), sym, s.sb)
2674 return s.variable(n, n.Type())
2676 return s.load(n.Type(), s.addr(n))
2677 case ir.OLINKSYMOFFSET:
2678 n := n.(*ir.LinksymOffsetExpr)
2679 return s.load(n.Type(), s.addr(n))
2681 n := n.(*ir.NilExpr)
2685 return s.constSlice(t)
2686 case t.IsInterface():
2687 return s.constInterface(t)
2689 return s.constNil(t)
2692 switch u := n.Val(); u.Kind() {
2694 i := ir.IntVal(n.Type(), u)
2695 switch n.Type().Size() {
2697 return s.constInt8(n.Type(), int8(i))
2699 return s.constInt16(n.Type(), int16(i))
2701 return s.constInt32(n.Type(), int32(i))
2703 return s.constInt64(n.Type(), i)
2705 s.Fatalf("bad integer size %d", n.Type().Size())
2708 case constant.String:
2709 i := constant.StringVal(u)
2711 return s.constEmptyString(n.Type())
2713 return s.entryNewValue0A(ssa.OpConstString, n.Type(), ssa.StringToAux(i))
2715 return s.constBool(constant.BoolVal(u))
2716 case constant.Float:
2717 f, _ := constant.Float64Val(u)
2718 switch n.Type().Size() {
2720 return s.constFloat32(n.Type(), f)
2722 return s.constFloat64(n.Type(), f)
2724 s.Fatalf("bad float size %d", n.Type().Size())
2727 case constant.Complex:
2728 re, _ := constant.Float64Val(constant.Real(u))
2729 im, _ := constant.Float64Val(constant.Imag(u))
2730 switch n.Type().Size() {
2732 pt := types.Types[types.TFLOAT32]
2733 return s.newValue2(ssa.OpComplexMake, n.Type(),
2734 s.constFloat32(pt, re),
2735 s.constFloat32(pt, im))
2737 pt := types.Types[types.TFLOAT64]
2738 return s.newValue2(ssa.OpComplexMake, n.Type(),
2739 s.constFloat64(pt, re),
2740 s.constFloat64(pt, im))
2742 s.Fatalf("bad complex size %d", n.Type().Size())
2746 s.Fatalf("unhandled OLITERAL %v", u.Kind())
2750 n := n.(*ir.ConvExpr)
2754 // Assume everything will work out, so set up our return value.
2755 // Anything interesting that happens from here is a fatal.
2761 // Special case for not confusing GC and liveness.
2762 // We don't want pointers accidentally classified
2763 // as not-pointers or vice-versa because of copy
2765 if to.IsPtrShaped() != from.IsPtrShaped() {
2766 return s.newValue2(ssa.OpConvert, to, x, s.mem())
2769 v := s.newValue1(ssa.OpCopy, to, x) // ensure that v has the right type
2772 if to.Kind() == types.TFUNC && from.IsPtrShaped() {
2776 // named <--> unnamed type or typed <--> untyped const
2777 if from.Kind() == to.Kind() {
2781 // unsafe.Pointer <--> *T
2782 if to.IsUnsafePtr() && from.IsPtrShaped() || from.IsUnsafePtr() && to.IsPtrShaped() {
2783 if s.checkPtrEnabled && checkPtrOK && to.IsPtr() && from.IsUnsafePtr() {
2784 s.checkPtrAlignment(n, v, nil)
2790 if to.Kind() == types.TMAP && from.IsPtr() &&
2791 to.MapType().Hmap == from.Elem() {
2795 types.CalcSize(from)
2797 if from.Size() != to.Size() {
2798 s.Fatalf("CONVNOP width mismatch %v (%d) -> %v (%d)\n", from, from.Size(), to, to.Size())
2801 if etypesign(from.Kind()) != etypesign(to.Kind()) {
2802 s.Fatalf("CONVNOP sign mismatch %v (%s) -> %v (%s)\n", from, from.Kind(), to, to.Kind())
2806 if base.Flag.Cfg.Instrumenting {
2807 // These appear to be fine, but they fail the
2808 // integer constraint below, so okay them here.
2809 // Sample non-integer conversion: map[string]string -> *uint8
2813 if etypesign(from.Kind()) == 0 {
2814 s.Fatalf("CONVNOP unrecognized non-integer %v -> %v\n", from, to)
2818 // integer, same width, same sign
2822 n := n.(*ir.ConvExpr)
2824 return s.conv(n, x, n.X.Type(), n.Type())
2827 n := n.(*ir.TypeAssertExpr)
2828 res, _ := s.dottype(n, false)
2831 case ir.ODYNAMICDOTTYPE:
2832 n := n.(*ir.DynamicTypeAssertExpr)
2833 res, _ := s.dynamicDottype(n, false)
2837 case ir.OLT, ir.OEQ, ir.ONE, ir.OLE, ir.OGE, ir.OGT:
2838 n := n.(*ir.BinaryExpr)
2841 if n.X.Type().IsComplex() {
2842 pt := types.FloatForComplex(n.X.Type())
2843 op := s.ssaOp(ir.OEQ, pt)
2844 r := s.newValueOrSfCall2(op, types.Types[types.TBOOL], s.newValue1(ssa.OpComplexReal, pt, a), s.newValue1(ssa.OpComplexReal, pt, b))
2845 i := s.newValueOrSfCall2(op, types.Types[types.TBOOL], s.newValue1(ssa.OpComplexImag, pt, a), s.newValue1(ssa.OpComplexImag, pt, b))
2846 c := s.newValue2(ssa.OpAndB, types.Types[types.TBOOL], r, i)
2851 return s.newValue1(ssa.OpNot, types.Types[types.TBOOL], c)
2853 s.Fatalf("ordered complex compare %v", n.Op())
2857 // Convert OGE and OGT into OLE and OLT.
2861 op, a, b = ir.OLE, b, a
2863 op, a, b = ir.OLT, b, a
2865 if n.X.Type().IsFloat() {
2867 return s.newValueOrSfCall2(s.ssaOp(op, n.X.Type()), types.Types[types.TBOOL], a, b)
2869 // integer comparison
2870 return s.newValue2(s.ssaOp(op, n.X.Type()), types.Types[types.TBOOL], a, b)
2872 n := n.(*ir.BinaryExpr)
2875 if n.Type().IsComplex() {
2876 mulop := ssa.OpMul64F
2877 addop := ssa.OpAdd64F
2878 subop := ssa.OpSub64F
2879 pt := types.FloatForComplex(n.Type()) // Could be Float32 or Float64
2880 wt := types.Types[types.TFLOAT64] // Compute in Float64 to minimize cancellation error
2882 areal := s.newValue1(ssa.OpComplexReal, pt, a)
2883 breal := s.newValue1(ssa.OpComplexReal, pt, b)
2884 aimag := s.newValue1(ssa.OpComplexImag, pt, a)
2885 bimag := s.newValue1(ssa.OpComplexImag, pt, b)
2887 if pt != wt { // Widen for calculation
2888 areal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, areal)
2889 breal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, breal)
2890 aimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, aimag)
2891 bimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, bimag)
2894 xreal := s.newValueOrSfCall2(subop, wt, s.newValueOrSfCall2(mulop, wt, areal, breal), s.newValueOrSfCall2(mulop, wt, aimag, bimag))
2895 ximag := s.newValueOrSfCall2(addop, wt, s.newValueOrSfCall2(mulop, wt, areal, bimag), s.newValueOrSfCall2(mulop, wt, aimag, breal))
2897 if pt != wt { // Narrow to store back
2898 xreal = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, xreal)
2899 ximag = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, ximag)
2902 return s.newValue2(ssa.OpComplexMake, n.Type(), xreal, ximag)
2905 if n.Type().IsFloat() {
2906 return s.newValueOrSfCall2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
2909 return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
2912 n := n.(*ir.BinaryExpr)
2915 if n.Type().IsComplex() {
2916 // TODO this is not executed because the front-end substitutes a runtime call.
2917 // That probably ought to change; with modest optimization the widen/narrow
2918 // conversions could all be elided in larger expression trees.
2919 mulop := ssa.OpMul64F
2920 addop := ssa.OpAdd64F
2921 subop := ssa.OpSub64F
2922 divop := ssa.OpDiv64F
2923 pt := types.FloatForComplex(n.Type()) // Could be Float32 or Float64
2924 wt := types.Types[types.TFLOAT64] // Compute in Float64 to minimize cancellation error
2926 areal := s.newValue1(ssa.OpComplexReal, pt, a)
2927 breal := s.newValue1(ssa.OpComplexReal, pt, b)
2928 aimag := s.newValue1(ssa.OpComplexImag, pt, a)
2929 bimag := s.newValue1(ssa.OpComplexImag, pt, b)
2931 if pt != wt { // Widen for calculation
2932 areal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, areal)
2933 breal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, breal)
2934 aimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, aimag)
2935 bimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, bimag)
2938 denom := s.newValueOrSfCall2(addop, wt, s.newValueOrSfCall2(mulop, wt, breal, breal), s.newValueOrSfCall2(mulop, wt, bimag, bimag))
2939 xreal := s.newValueOrSfCall2(addop, wt, s.newValueOrSfCall2(mulop, wt, areal, breal), s.newValueOrSfCall2(mulop, wt, aimag, bimag))
2940 ximag := s.newValueOrSfCall2(subop, wt, s.newValueOrSfCall2(mulop, wt, aimag, breal), s.newValueOrSfCall2(mulop, wt, areal, bimag))
2942 // TODO not sure if this is best done in wide precision or narrow
2943 // Double-rounding might be an issue.
2944 // Note that the pre-SSA implementation does the entire calculation
2945 // in wide format, so wide is compatible.
2946 xreal = s.newValueOrSfCall2(divop, wt, xreal, denom)
2947 ximag = s.newValueOrSfCall2(divop, wt, ximag, denom)
2949 if pt != wt { // Narrow to store back
2950 xreal = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, xreal)
2951 ximag = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, ximag)
2953 return s.newValue2(ssa.OpComplexMake, n.Type(), xreal, ximag)
2955 if n.Type().IsFloat() {
2956 return s.newValueOrSfCall2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
2958 return s.intDivide(n, a, b)
2960 n := n.(*ir.BinaryExpr)
2963 return s.intDivide(n, a, b)
2964 case ir.OADD, ir.OSUB:
2965 n := n.(*ir.BinaryExpr)
2968 if n.Type().IsComplex() {
2969 pt := types.FloatForComplex(n.Type())
2970 op := s.ssaOp(n.Op(), pt)
2971 return s.newValue2(ssa.OpComplexMake, n.Type(),
2972 s.newValueOrSfCall2(op, pt, s.newValue1(ssa.OpComplexReal, pt, a), s.newValue1(ssa.OpComplexReal, pt, b)),
2973 s.newValueOrSfCall2(op, pt, s.newValue1(ssa.OpComplexImag, pt, a), s.newValue1(ssa.OpComplexImag, pt, b)))
2975 if n.Type().IsFloat() {
2976 return s.newValueOrSfCall2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
2978 return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
2979 case ir.OAND, ir.OOR, ir.OXOR:
2980 n := n.(*ir.BinaryExpr)
2983 return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
2985 n := n.(*ir.BinaryExpr)
2988 b = s.newValue1(s.ssaOp(ir.OBITNOT, b.Type), b.Type, b)
2989 return s.newValue2(s.ssaOp(ir.OAND, n.Type()), a.Type, a, b)
2990 case ir.OLSH, ir.ORSH:
2991 n := n.(*ir.BinaryExpr)
2996 cmp := s.newValue2(s.ssaOp(ir.OLE, bt), types.Types[types.TBOOL], s.zeroVal(bt), b)
2997 s.check(cmp, ir.Syms.Panicshift)
2998 bt = bt.ToUnsigned()
3000 return s.newValue2(s.ssaShiftOp(n.Op(), n.Type(), bt), a.Type, a, b)
3001 case ir.OANDAND, ir.OOROR:
3002 // To implement OANDAND (and OOROR), we introduce a
3003 // new temporary variable to hold the result. The
3004 // variable is associated with the OANDAND node in the
3005 // s.vars table (normally variables are only
3006 // associated with ONAME nodes). We convert
3013 // Using var in the subsequent block introduces the
3014 // necessary phi variable.
3015 n := n.(*ir.LogicalExpr)
3020 b.Kind = ssa.BlockIf
3022 // In theory, we should set b.Likely here based on context.
3023 // However, gc only gives us likeliness hints
3024 // in a single place, for plain OIF statements,
3025 // and passing around context is finnicky, so don't bother for now.
3027 bRight := s.f.NewBlock(ssa.BlockPlain)
3028 bResult := s.f.NewBlock(ssa.BlockPlain)
3029 if n.Op() == ir.OANDAND {
3031 b.AddEdgeTo(bResult)
3032 } else if n.Op() == ir.OOROR {
3033 b.AddEdgeTo(bResult)
3037 s.startBlock(bRight)
3042 b.AddEdgeTo(bResult)
3044 s.startBlock(bResult)
3045 return s.variable(n, types.Types[types.TBOOL])
3047 n := n.(*ir.BinaryExpr)
3050 return s.newValue2(ssa.OpComplexMake, n.Type(), r, i)
3054 n := n.(*ir.UnaryExpr)
3056 if n.Type().IsComplex() {
3057 tp := types.FloatForComplex(n.Type())
3058 negop := s.ssaOp(n.Op(), tp)
3059 return s.newValue2(ssa.OpComplexMake, n.Type(),
3060 s.newValue1(negop, tp, s.newValue1(ssa.OpComplexReal, tp, a)),
3061 s.newValue1(negop, tp, s.newValue1(ssa.OpComplexImag, tp, a)))
3063 return s.newValue1(s.ssaOp(n.Op(), n.Type()), a.Type, a)
3064 case ir.ONOT, ir.OBITNOT:
3065 n := n.(*ir.UnaryExpr)
3067 return s.newValue1(s.ssaOp(n.Op(), n.Type()), a.Type, a)
3068 case ir.OIMAG, ir.OREAL:
3069 n := n.(*ir.UnaryExpr)
3071 return s.newValue1(s.ssaOp(n.Op(), n.X.Type()), n.Type(), a)
3073 n := n.(*ir.UnaryExpr)
3077 n := n.(*ir.AddrExpr)
3081 n := n.(*ir.ResultExpr)
3082 if s.prevCall == nil || s.prevCall.Op != ssa.OpStaticLECall && s.prevCall.Op != ssa.OpInterLECall && s.prevCall.Op != ssa.OpClosureLECall {
3083 panic("Expected to see a previous call")
3087 panic(fmt.Errorf("ORESULT %v does not match call %s", n, s.prevCall))
3089 return s.resultOfCall(s.prevCall, which, n.Type())
3092 n := n.(*ir.StarExpr)
3093 p := s.exprPtr(n.X, n.Bounded(), n.Pos())
3094 return s.load(n.Type(), p)
3097 n := n.(*ir.SelectorExpr)
3098 if n.X.Op() == ir.OSTRUCTLIT {
3099 // All literals with nonzero fields have already been
3100 // rewritten during walk. Any that remain are just T{}
3101 // or equivalents. Use the zero value.
3102 if !ir.IsZero(n.X) {
3103 s.Fatalf("literal with nonzero value in SSA: %v", n.X)
3105 return s.zeroVal(n.Type())
3107 // If n is addressable and can't be represented in
3108 // SSA, then load just the selected field. This
3109 // prevents false memory dependencies in race/msan/asan
3111 if ir.IsAddressable(n) && !s.canSSA(n) {
3113 return s.load(n.Type(), p)
3116 return s.newValue1I(ssa.OpStructSelect, n.Type(), int64(fieldIdx(n)), v)
3119 n := n.(*ir.SelectorExpr)
3120 p := s.exprPtr(n.X, n.Bounded(), n.Pos())
3121 p = s.newValue1I(ssa.OpOffPtr, types.NewPtr(n.Type()), n.Offset(), p)
3122 return s.load(n.Type(), p)
3125 n := n.(*ir.IndexExpr)
3127 case n.X.Type().IsString():
3128 if n.Bounded() && ir.IsConst(n.X, constant.String) && ir.IsConst(n.Index, constant.Int) {
3129 // Replace "abc"[1] with 'b'.
3130 // Delayed until now because "abc"[1] is not an ideal constant.
3131 // See test/fixedbugs/issue11370.go.
3132 return s.newValue0I(ssa.OpConst8, types.Types[types.TUINT8], int64(int8(ir.StringVal(n.X)[ir.Int64Val(n.Index)])))
3135 i := s.expr(n.Index)
3136 len := s.newValue1(ssa.OpStringLen, types.Types[types.TINT], a)
3137 i = s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded())
3138 ptrtyp := s.f.Config.Types.BytePtr
3139 ptr := s.newValue1(ssa.OpStringPtr, ptrtyp, a)
3140 if ir.IsConst(n.Index, constant.Int) {
3141 ptr = s.newValue1I(ssa.OpOffPtr, ptrtyp, ir.Int64Val(n.Index), ptr)
3143 ptr = s.newValue2(ssa.OpAddPtr, ptrtyp, ptr, i)
3145 return s.load(types.Types[types.TUINT8], ptr)
3146 case n.X.Type().IsSlice():
3148 return s.load(n.X.Type().Elem(), p)
3149 case n.X.Type().IsArray():
3150 if TypeOK(n.X.Type()) {
3151 // SSA can handle arrays of length at most 1.
3152 bound := n.X.Type().NumElem()
3154 i := s.expr(n.Index)
3156 // Bounds check will never succeed. Might as well
3157 // use constants for the bounds check.
3158 z := s.constInt(types.Types[types.TINT], 0)
3159 s.boundsCheck(z, z, ssa.BoundsIndex, false)
3160 // The return value won't be live, return junk.
3161 // But not quite junk, in case bounds checks are turned off. See issue 48092.
3162 return s.zeroVal(n.Type())
3164 len := s.constInt(types.Types[types.TINT], bound)
3165 s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded()) // checks i == 0
3166 return s.newValue1I(ssa.OpArraySelect, n.Type(), 0, a)
3169 return s.load(n.X.Type().Elem(), p)
3171 s.Fatalf("bad type for index %v", n.X.Type())
3175 case ir.OLEN, ir.OCAP:
3176 n := n.(*ir.UnaryExpr)
3178 case n.X.Type().IsSlice():
3179 op := ssa.OpSliceLen
3180 if n.Op() == ir.OCAP {
3183 return s.newValue1(op, types.Types[types.TINT], s.expr(n.X))
3184 case n.X.Type().IsString(): // string; not reachable for OCAP
3185 return s.newValue1(ssa.OpStringLen, types.Types[types.TINT], s.expr(n.X))
3186 case n.X.Type().IsMap(), n.X.Type().IsChan():
3187 return s.referenceTypeBuiltin(n, s.expr(n.X))
3189 return s.constInt(types.Types[types.TINT], n.X.Type().NumElem())
3193 n := n.(*ir.UnaryExpr)
3195 if n.X.Type().IsSlice() {
3196 return s.newValue1(ssa.OpSlicePtr, n.Type(), a)
3198 return s.newValue1(ssa.OpStringPtr, n.Type(), a)
3202 n := n.(*ir.UnaryExpr)
3204 return s.newValue1(ssa.OpITab, n.Type(), a)
3207 n := n.(*ir.UnaryExpr)
3209 return s.newValue1(ssa.OpIData, n.Type(), a)
3212 n := n.(*ir.BinaryExpr)
3215 return s.newValue2(ssa.OpIMake, n.Type(), tab, data)
3217 case ir.OSLICEHEADER:
3218 n := n.(*ir.SliceHeaderExpr)
3222 return s.newValue3(ssa.OpSliceMake, n.Type(), p, l, c)
3224 case ir.OSLICE, ir.OSLICEARR, ir.OSLICE3, ir.OSLICE3ARR:
3225 n := n.(*ir.SliceExpr)
3226 check := s.checkPtrEnabled && n.Op() == ir.OSLICE3ARR && n.X.Op() == ir.OCONVNOP && n.X.(*ir.ConvExpr).X.Type().IsUnsafePtr()
3227 v := s.exprCheckPtr(n.X, !check)
3228 var i, j, k *ssa.Value
3238 p, l, c := s.slice(v, i, j, k, n.Bounded())
3240 // Emit checkptr instrumentation after bound check to prevent false positive, see #46938.
3241 s.checkPtrAlignment(n.X.(*ir.ConvExpr), v, s.conv(n.Max, k, k.Type, types.Types[types.TUINTPTR]))
3243 return s.newValue3(ssa.OpSliceMake, n.Type(), p, l, c)
3246 n := n.(*ir.SliceExpr)
3255 p, l, _ := s.slice(v, i, j, nil, n.Bounded())
3256 return s.newValue2(ssa.OpStringMake, n.Type(), p, l)
3258 case ir.OSLICE2ARRPTR:
3259 // if arrlen > slice.len {
3263 n := n.(*ir.ConvExpr)
3265 arrlen := s.constInt(types.Types[types.TINT], n.Type().Elem().NumElem())
3266 cap := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], v)
3267 s.boundsCheck(arrlen, cap, ssa.BoundsConvert, false)
3268 return s.newValue1(ssa.OpSlicePtrUnchecked, n.Type(), v)
3271 n := n.(*ir.CallExpr)
3272 if ir.IsIntrinsicCall(n) {
3273 return s.intrinsicCall(n)
3278 n := n.(*ir.CallExpr)
3279 return s.callResult(n, callNormal)
3282 n := n.(*ir.CallExpr)
3283 return s.newValue1(ssa.OpGetG, n.Type(), s.mem())
3285 case ir.OGETCALLERPC:
3286 n := n.(*ir.CallExpr)
3287 return s.newValue0(ssa.OpGetCallerPC, n.Type())
3289 case ir.OGETCALLERSP:
3290 n := n.(*ir.CallExpr)
3291 return s.newValue0(ssa.OpGetCallerSP, n.Type())
3294 return s.append(n.(*ir.CallExpr), false)
3296 case ir.OSTRUCTLIT, ir.OARRAYLIT:
3297 // All literals with nonzero fields have already been
3298 // rewritten during walk. Any that remain are just T{}
3299 // or equivalents. Use the zero value.
3300 n := n.(*ir.CompLitExpr)
3302 s.Fatalf("literal with nonzero value in SSA: %v", n)
3304 return s.zeroVal(n.Type())
3307 n := n.(*ir.UnaryExpr)
3308 var rtype *ssa.Value
3309 if x, ok := n.X.(*ir.DynamicType); ok && x.Op() == ir.ODYNAMICTYPE {
3310 rtype = s.expr(x.RType)
3312 return s.newObject(n.Type().Elem(), rtype)
3315 n := n.(*ir.BinaryExpr)
3319 // Force len to uintptr to prevent misuse of garbage bits in the
3320 // upper part of the register (#48536).
3321 len = s.conv(n, len, len.Type, types.Types[types.TUINTPTR])
3323 return s.newValue2(ssa.OpAddPtr, n.Type(), ptr, len)
3326 s.Fatalf("unhandled expr %v", n.Op())
3331 func (s *state) resultOfCall(c *ssa.Value, which int64, t *types.Type) *ssa.Value {
3332 aux := c.Aux.(*ssa.AuxCall)
3333 pa := aux.ParamAssignmentForResult(which)
3334 // TODO(register args) determine if in-memory TypeOK is better loaded early from SelectNAddr or later when SelectN is expanded.
3335 // SelectN is better for pattern-matching and possible call-aware analysis we might want to do in the future.
3336 if len(pa.Registers) == 0 && !TypeOK(t) {
3337 addr := s.newValue1I(ssa.OpSelectNAddr, types.NewPtr(t), which, c)
3338 return s.rawLoad(t, addr)
3340 return s.newValue1I(ssa.OpSelectN, t, which, c)
3343 func (s *state) resultAddrOfCall(c *ssa.Value, which int64, t *types.Type) *ssa.Value {
3344 aux := c.Aux.(*ssa.AuxCall)
3345 pa := aux.ParamAssignmentForResult(which)
3346 if len(pa.Registers) == 0 {
3347 return s.newValue1I(ssa.OpSelectNAddr, types.NewPtr(t), which, c)
3349 _, addr := s.temp(c.Pos, t)
3350 rval := s.newValue1I(ssa.OpSelectN, t, which, c)
3351 s.vars[memVar] = s.newValue3Apos(ssa.OpStore, types.TypeMem, t, addr, rval, s.mem(), false)
3355 // append converts an OAPPEND node to SSA.
3356 // If inplace is false, it converts the OAPPEND expression n to an ssa.Value,
3357 // adds it to s, and returns the Value.
3358 // If inplace is true, it writes the result of the OAPPEND expression n
3359 // back to the slice being appended to, and returns nil.
3360 // inplace MUST be set to false if the slice can be SSA'd.
3361 func (s *state) append(n *ir.CallExpr, inplace bool) *ssa.Value {
3362 // If inplace is false, process as expression "append(s, e1, e2, e3)":
3364 // ptr, len, cap := s
3365 // newlen := len + 3
3366 // if newlen > cap {
3367 // ptr, len, cap = growslice(s, newlen)
3368 // newlen = len + 3 // recalculate to avoid a spill
3370 // // with write barriers, if needed:
3372 // *(ptr+len+1) = e2
3373 // *(ptr+len+2) = e3
3374 // return makeslice(ptr, newlen, cap)
3377 // If inplace is true, process as statement "s = append(s, e1, e2, e3)":
3380 // ptr, len, cap := s
3381 // newlen := len + 3
3382 // if uint(newlen) > uint(cap) {
3383 // newptr, len, newcap = growslice(ptr, len, cap, newlen)
3384 // vardef(a) // if necessary, advise liveness we are writing a new a
3385 // *a.cap = newcap // write before ptr to avoid a spill
3386 // *a.ptr = newptr // with write barrier
3388 // newlen = len + 3 // recalculate to avoid a spill
3390 // // with write barriers, if needed:
3392 // *(ptr+len+1) = e2
3393 // *(ptr+len+2) = e3
3395 et := n.Type().Elem()
3396 pt := types.NewPtr(et)
3399 sn := n.Args[0] // the slice node is the first in the list
3401 var slice, addr *ssa.Value
3404 slice = s.load(n.Type(), addr)
3409 // Allocate new blocks
3410 grow := s.f.NewBlock(ssa.BlockPlain)
3411 assign := s.f.NewBlock(ssa.BlockPlain)
3413 // Decide if we need to grow
3414 nargs := int64(len(n.Args) - 1)
3415 p := s.newValue1(ssa.OpSlicePtr, pt, slice)
3416 l := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], slice)
3417 c := s.newValue1(ssa.OpSliceCap, types.Types[types.TINT], slice)
3418 nl := s.newValue2(s.ssaOp(ir.OADD, types.Types[types.TINT]), types.Types[types.TINT], l, s.constInt(types.Types[types.TINT], nargs))
3420 cmp := s.newValue2(s.ssaOp(ir.OLT, types.Types[types.TUINT]), types.Types[types.TBOOL], c, nl)
3424 s.vars[newlenVar] = nl
3431 b.Kind = ssa.BlockIf
3432 b.Likely = ssa.BranchUnlikely
3439 taddr := s.expr(n.X)
3440 r := s.rtcall(ir.Syms.Growslice, true, []*types.Type{pt, types.Types[types.TINT], types.Types[types.TINT]}, taddr, p, l, c, nl)
3443 if sn.Op() == ir.ONAME {
3445 if sn.Class != ir.PEXTERN {
3446 // Tell liveness we're about to build a new slice
3447 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, sn, s.mem())
3450 capaddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, types.SliceCapOffset, addr)
3451 s.store(types.Types[types.TINT], capaddr, r[2])
3452 s.store(pt, addr, r[0])
3453 // load the value we just stored to avoid having to spill it
3454 s.vars[ptrVar] = s.load(pt, addr)
3455 s.vars[lenVar] = r[1] // avoid a spill in the fast path
3457 s.vars[ptrVar] = r[0]
3458 s.vars[newlenVar] = s.newValue2(s.ssaOp(ir.OADD, types.Types[types.TINT]), types.Types[types.TINT], r[1], s.constInt(types.Types[types.TINT], nargs))
3459 s.vars[capVar] = r[2]
3465 // assign new elements to slots
3466 s.startBlock(assign)
3469 l = s.variable(lenVar, types.Types[types.TINT]) // generates phi for len
3470 nl = s.newValue2(s.ssaOp(ir.OADD, types.Types[types.TINT]), types.Types[types.TINT], l, s.constInt(types.Types[types.TINT], nargs))
3471 lenaddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, types.SliceLenOffset, addr)
3472 s.store(types.Types[types.TINT], lenaddr, nl)
3476 type argRec struct {
3477 // if store is true, we're appending the value v. If false, we're appending the
3482 args := make([]argRec, 0, nargs)
3483 for _, n := range n.Args[1:] {
3484 if TypeOK(n.Type()) {
3485 args = append(args, argRec{v: s.expr(n), store: true})
3488 args = append(args, argRec{v: v})
3492 p = s.variable(ptrVar, pt) // generates phi for ptr
3494 nl = s.variable(newlenVar, types.Types[types.TINT]) // generates phi for nl
3495 c = s.variable(capVar, types.Types[types.TINT]) // generates phi for cap
3497 p2 := s.newValue2(ssa.OpPtrIndex, pt, p, l)
3498 for i, arg := range args {
3499 addr := s.newValue2(ssa.OpPtrIndex, pt, p2, s.constInt(types.Types[types.TINT], int64(i)))
3501 s.storeType(et, addr, arg.v, 0, true)
3503 s.move(et, addr, arg.v)
3507 delete(s.vars, ptrVar)
3509 delete(s.vars, lenVar)
3512 delete(s.vars, newlenVar)
3513 delete(s.vars, capVar)
3515 return s.newValue3(ssa.OpSliceMake, n.Type(), p, nl, c)
3518 // condBranch evaluates the boolean expression cond and branches to yes
3519 // if cond is true and no if cond is false.
3520 // This function is intended to handle && and || better than just calling
3521 // s.expr(cond) and branching on the result.
3522 func (s *state) condBranch(cond ir.Node, yes, no *ssa.Block, likely int8) {
3525 cond := cond.(*ir.LogicalExpr)
3526 mid := s.f.NewBlock(ssa.BlockPlain)
3527 s.stmtList(cond.Init())
3528 s.condBranch(cond.X, mid, no, max8(likely, 0))
3530 s.condBranch(cond.Y, yes, no, likely)
3532 // Note: if likely==1, then both recursive calls pass 1.
3533 // If likely==-1, then we don't have enough information to decide
3534 // whether the first branch is likely or not. So we pass 0 for
3535 // the likeliness of the first branch.
3536 // TODO: have the frontend give us branch prediction hints for
3537 // OANDAND and OOROR nodes (if it ever has such info).
3539 cond := cond.(*ir.LogicalExpr)
3540 mid := s.f.NewBlock(ssa.BlockPlain)
3541 s.stmtList(cond.Init())
3542 s.condBranch(cond.X, yes, mid, min8(likely, 0))
3544 s.condBranch(cond.Y, yes, no, likely)
3546 // Note: if likely==-1, then both recursive calls pass -1.
3547 // If likely==1, then we don't have enough info to decide
3548 // the likelihood of the first branch.
3550 cond := cond.(*ir.UnaryExpr)
3551 s.stmtList(cond.Init())
3552 s.condBranch(cond.X, no, yes, -likely)
3555 cond := cond.(*ir.ConvExpr)
3556 s.stmtList(cond.Init())
3557 s.condBranch(cond.X, yes, no, likely)
3562 b.Kind = ssa.BlockIf
3564 b.Likely = ssa.BranchPrediction(likely) // gc and ssa both use -1/0/+1 for likeliness
3572 skipPtr skipMask = 1 << iota
3577 // assign does left = right.
3578 // Right has already been evaluated to ssa, left has not.
3579 // If deref is true, then we do left = *right instead (and right has already been nil-checked).
3580 // If deref is true and right == nil, just do left = 0.
3581 // skip indicates assignments (at the top level) that can be avoided.
3582 func (s *state) assign(left ir.Node, right *ssa.Value, deref bool, skip skipMask) {
3583 if left.Op() == ir.ONAME && ir.IsBlank(left) {
3590 s.Fatalf("can SSA LHS %v but not RHS %s", left, right)
3592 if left.Op() == ir.ODOT {
3593 // We're assigning to a field of an ssa-able value.
3594 // We need to build a new structure with the new value for the
3595 // field we're assigning and the old values for the other fields.
3597 // type T struct {a, b, c int}
3600 // For the x.b = 5 assignment we want to generate x = T{x.a, 5, x.c}
3602 // Grab information about the structure type.
3603 left := left.(*ir.SelectorExpr)
3606 idx := fieldIdx(left)
3608 // Grab old value of structure.
3609 old := s.expr(left.X)
3611 // Make new structure.
3612 new := s.newValue0(ssa.StructMakeOp(t.NumFields()), t)
3614 // Add fields as args.
3615 for i := 0; i < nf; i++ {
3619 new.AddArg(s.newValue1I(ssa.OpStructSelect, t.FieldType(i), int64(i), old))
3623 // Recursively assign the new value we've made to the base of the dot op.
3624 s.assign(left.X, new, false, 0)
3625 // TODO: do we need to update named values here?
3628 if left.Op() == ir.OINDEX && left.(*ir.IndexExpr).X.Type().IsArray() {
3629 left := left.(*ir.IndexExpr)
3630 s.pushLine(left.Pos())
3632 // We're assigning to an element of an ssa-able array.
3637 i := s.expr(left.Index) // index
3639 // The bounds check must fail. Might as well
3640 // ignore the actual index and just use zeros.
3641 z := s.constInt(types.Types[types.TINT], 0)
3642 s.boundsCheck(z, z, ssa.BoundsIndex, false)
3646 s.Fatalf("assigning to non-1-length array")
3648 // Rewrite to a = [1]{v}
3649 len := s.constInt(types.Types[types.TINT], 1)
3650 s.boundsCheck(i, len, ssa.BoundsIndex, false) // checks i == 0
3651 v := s.newValue1(ssa.OpArrayMake1, t, right)
3652 s.assign(left.X, v, false, 0)
3655 left := left.(*ir.Name)
3656 // Update variable assignment.
3657 s.vars[left] = right
3658 s.addNamedValue(left, right)
3662 // If this assignment clobbers an entire local variable, then emit
3663 // OpVarDef so liveness analysis knows the variable is redefined.
3664 if base, ok := clobberBase(left).(*ir.Name); ok && base.OnStack() && skip == 0 {
3665 s.vars[memVar] = s.newValue1Apos(ssa.OpVarDef, types.TypeMem, base, s.mem(), !ir.IsAutoTmp(base))
3668 // Left is not ssa-able. Compute its address.
3669 addr := s.addr(left)
3670 if ir.IsReflectHeaderDataField(left) {
3671 // Package unsafe's documentation says storing pointers into
3672 // reflect.SliceHeader and reflect.StringHeader's Data fields
3673 // is valid, even though they have type uintptr (#19168).
3674 // Mark it pointer type to signal the writebarrier pass to
3675 // insert a write barrier.
3676 t = types.Types[types.TUNSAFEPTR]
3679 // Treat as a mem->mem move.
3683 s.move(t, addr, right)
3687 // Treat as a store.
3688 s.storeType(t, addr, right, skip, !ir.IsAutoTmp(left))
3691 // zeroVal returns the zero value for type t.
3692 func (s *state) zeroVal(t *types.Type) *ssa.Value {
3697 return s.constInt8(t, 0)
3699 return s.constInt16(t, 0)
3701 return s.constInt32(t, 0)
3703 return s.constInt64(t, 0)
3705 s.Fatalf("bad sized integer type %v", t)
3710 return s.constFloat32(t, 0)
3712 return s.constFloat64(t, 0)
3714 s.Fatalf("bad sized float type %v", t)
3719 z := s.constFloat32(types.Types[types.TFLOAT32], 0)
3720 return s.entryNewValue2(ssa.OpComplexMake, t, z, z)
3722 z := s.constFloat64(types.Types[types.TFLOAT64], 0)
3723 return s.entryNewValue2(ssa.OpComplexMake, t, z, z)
3725 s.Fatalf("bad sized complex type %v", t)
3729 return s.constEmptyString(t)
3730 case t.IsPtrShaped():
3731 return s.constNil(t)
3733 return s.constBool(false)
3734 case t.IsInterface():
3735 return s.constInterface(t)
3737 return s.constSlice(t)
3740 v := s.entryNewValue0(ssa.StructMakeOp(t.NumFields()), t)
3741 for i := 0; i < n; i++ {
3742 v.AddArg(s.zeroVal(t.FieldType(i)))
3746 switch t.NumElem() {
3748 return s.entryNewValue0(ssa.OpArrayMake0, t)
3750 return s.entryNewValue1(ssa.OpArrayMake1, t, s.zeroVal(t.Elem()))
3753 s.Fatalf("zero for type %v not implemented", t)
3760 callNormal callKind = iota
3767 type sfRtCallDef struct {
3772 var softFloatOps map[ssa.Op]sfRtCallDef
3774 func softfloatInit() {
3775 // Some of these operations get transformed by sfcall.
3776 softFloatOps = map[ssa.Op]sfRtCallDef{
3777 ssa.OpAdd32F: sfRtCallDef{typecheck.LookupRuntimeFunc("fadd32"), types.TFLOAT32},
3778 ssa.OpAdd64F: sfRtCallDef{typecheck.LookupRuntimeFunc("fadd64"), types.TFLOAT64},
3779 ssa.OpSub32F: sfRtCallDef{typecheck.LookupRuntimeFunc("fadd32"), types.TFLOAT32},
3780 ssa.OpSub64F: sfRtCallDef{typecheck.LookupRuntimeFunc("fadd64"), types.TFLOAT64},
3781 ssa.OpMul32F: sfRtCallDef{typecheck.LookupRuntimeFunc("fmul32"), types.TFLOAT32},
3782 ssa.OpMul64F: sfRtCallDef{typecheck.LookupRuntimeFunc("fmul64"), types.TFLOAT64},
3783 ssa.OpDiv32F: sfRtCallDef{typecheck.LookupRuntimeFunc("fdiv32"), types.TFLOAT32},
3784 ssa.OpDiv64F: sfRtCallDef{typecheck.LookupRuntimeFunc("fdiv64"), types.TFLOAT64},
3786 ssa.OpEq64F: sfRtCallDef{typecheck.LookupRuntimeFunc("feq64"), types.TBOOL},
3787 ssa.OpEq32F: sfRtCallDef{typecheck.LookupRuntimeFunc("feq32"), types.TBOOL},
3788 ssa.OpNeq64F: sfRtCallDef{typecheck.LookupRuntimeFunc("feq64"), types.TBOOL},
3789 ssa.OpNeq32F: sfRtCallDef{typecheck.LookupRuntimeFunc("feq32"), types.TBOOL},
3790 ssa.OpLess64F: sfRtCallDef{typecheck.LookupRuntimeFunc("fgt64"), types.TBOOL},
3791 ssa.OpLess32F: sfRtCallDef{typecheck.LookupRuntimeFunc("fgt32"), types.TBOOL},
3792 ssa.OpLeq64F: sfRtCallDef{typecheck.LookupRuntimeFunc("fge64"), types.TBOOL},
3793 ssa.OpLeq32F: sfRtCallDef{typecheck.LookupRuntimeFunc("fge32"), types.TBOOL},
3795 ssa.OpCvt32to32F: sfRtCallDef{typecheck.LookupRuntimeFunc("fint32to32"), types.TFLOAT32},
3796 ssa.OpCvt32Fto32: sfRtCallDef{typecheck.LookupRuntimeFunc("f32toint32"), types.TINT32},
3797 ssa.OpCvt64to32F: sfRtCallDef{typecheck.LookupRuntimeFunc("fint64to32"), types.TFLOAT32},
3798 ssa.OpCvt32Fto64: sfRtCallDef{typecheck.LookupRuntimeFunc("f32toint64"), types.TINT64},
3799 ssa.OpCvt64Uto32F: sfRtCallDef{typecheck.LookupRuntimeFunc("fuint64to32"), types.TFLOAT32},
3800 ssa.OpCvt32Fto64U: sfRtCallDef{typecheck.LookupRuntimeFunc("f32touint64"), types.TUINT64},
3801 ssa.OpCvt32to64F: sfRtCallDef{typecheck.LookupRuntimeFunc("fint32to64"), types.TFLOAT64},
3802 ssa.OpCvt64Fto32: sfRtCallDef{typecheck.LookupRuntimeFunc("f64toint32"), types.TINT32},
3803 ssa.OpCvt64to64F: sfRtCallDef{typecheck.LookupRuntimeFunc("fint64to64"), types.TFLOAT64},
3804 ssa.OpCvt64Fto64: sfRtCallDef{typecheck.LookupRuntimeFunc("f64toint64"), types.TINT64},
3805 ssa.OpCvt64Uto64F: sfRtCallDef{typecheck.LookupRuntimeFunc("fuint64to64"), types.TFLOAT64},
3806 ssa.OpCvt64Fto64U: sfRtCallDef{typecheck.LookupRuntimeFunc("f64touint64"), types.TUINT64},
3807 ssa.OpCvt32Fto64F: sfRtCallDef{typecheck.LookupRuntimeFunc("f32to64"), types.TFLOAT64},
3808 ssa.OpCvt64Fto32F: sfRtCallDef{typecheck.LookupRuntimeFunc("f64to32"), types.TFLOAT32},
3812 // TODO: do not emit sfcall if operation can be optimized to constant in later
3814 func (s *state) sfcall(op ssa.Op, args ...*ssa.Value) (*ssa.Value, bool) {
3815 f2i := func(t *types.Type) *types.Type {
3817 case types.TFLOAT32:
3818 return types.Types[types.TUINT32]
3819 case types.TFLOAT64:
3820 return types.Types[types.TUINT64]
3825 if callDef, ok := softFloatOps[op]; ok {
3831 args[0], args[1] = args[1], args[0]
3834 args[1] = s.newValue1(s.ssaOp(ir.ONEG, types.Types[callDef.rtype]), args[1].Type, args[1])
3837 // runtime functions take uints for floats and returns uints.
3838 // Convert to uints so we use the right calling convention.
3839 for i, a := range args {
3840 if a.Type.IsFloat() {
3841 args[i] = s.newValue1(ssa.OpCopy, f2i(a.Type), a)
3845 rt := types.Types[callDef.rtype]
3846 result := s.rtcall(callDef.rtfn, true, []*types.Type{f2i(rt)}, args...)[0]
3848 result = s.newValue1(ssa.OpCopy, rt, result)
3850 if op == ssa.OpNeq32F || op == ssa.OpNeq64F {
3851 result = s.newValue1(ssa.OpNot, result.Type, result)
3858 var intrinsics map[intrinsicKey]intrinsicBuilder
3860 // An intrinsicBuilder converts a call node n into an ssa value that
3861 // implements that call as an intrinsic. args is a list of arguments to the func.
3862 type intrinsicBuilder func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value
3864 type intrinsicKey struct {
3871 intrinsics = map[intrinsicKey]intrinsicBuilder{}
3876 var lwatomics []*sys.Arch
3877 for _, a := range &sys.Archs {
3878 all = append(all, a)
3884 if a.Family != sys.PPC64 {
3885 lwatomics = append(lwatomics, a)
3889 // add adds the intrinsic b for pkg.fn for the given list of architectures.
3890 add := func(pkg, fn string, b intrinsicBuilder, archs ...*sys.Arch) {
3891 for _, a := range archs {
3892 intrinsics[intrinsicKey{a, pkg, fn}] = b
3895 // addF does the same as add but operates on architecture families.
3896 addF := func(pkg, fn string, b intrinsicBuilder, archFamilies ...sys.ArchFamily) {
3898 for _, f := range archFamilies {
3900 panic("too many architecture families")
3904 for _, a := range all {
3905 if m>>uint(a.Family)&1 != 0 {
3906 intrinsics[intrinsicKey{a, pkg, fn}] = b
3910 // alias defines pkg.fn = pkg2.fn2 for all architectures in archs for which pkg2.fn2 exists.
3911 alias := func(pkg, fn, pkg2, fn2 string, archs ...*sys.Arch) {
3913 for _, a := range archs {
3914 if b, ok := intrinsics[intrinsicKey{a, pkg2, fn2}]; ok {
3915 intrinsics[intrinsicKey{a, pkg, fn}] = b
3920 panic(fmt.Sprintf("attempted to alias undefined intrinsic: %s.%s", pkg, fn))
3924 /******** runtime ********/
3925 if !base.Flag.Cfg.Instrumenting {
3926 add("runtime", "slicebytetostringtmp",
3927 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
3928 // Compiler frontend optimizations emit OBYTES2STRTMP nodes
3929 // for the backend instead of slicebytetostringtmp calls
3930 // when not instrumenting.
3931 return s.newValue2(ssa.OpStringMake, n.Type(), args[0], args[1])
3935 addF("runtime/internal/math", "MulUintptr",
3936 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
3937 if s.config.PtrSize == 4 {
3938 return s.newValue2(ssa.OpMul32uover, types.NewTuple(types.Types[types.TUINT], types.Types[types.TUINT]), args[0], args[1])
3940 return s.newValue2(ssa.OpMul64uover, types.NewTuple(types.Types[types.TUINT], types.Types[types.TUINT]), args[0], args[1])
3942 sys.AMD64, sys.I386, sys.Loong64, sys.MIPS64, sys.RISCV64)
3943 alias("runtime", "mulUintptr", "runtime/internal/math", "MulUintptr", all...)
3944 add("runtime", "KeepAlive",
3945 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
3946 data := s.newValue1(ssa.OpIData, s.f.Config.Types.BytePtr, args[0])
3947 s.vars[memVar] = s.newValue2(ssa.OpKeepAlive, types.TypeMem, data, s.mem())
3951 add("runtime", "getclosureptr",
3952 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
3953 return s.newValue0(ssa.OpGetClosurePtr, s.f.Config.Types.Uintptr)
3957 add("runtime", "getcallerpc",
3958 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
3959 return s.newValue0(ssa.OpGetCallerPC, s.f.Config.Types.Uintptr)
3963 add("runtime", "getcallersp",
3964 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
3965 return s.newValue0(ssa.OpGetCallerSP, s.f.Config.Types.Uintptr)
3969 addF("runtime", "publicationBarrier",
3970 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
3971 s.vars[memVar] = s.newValue1(ssa.OpPubBarrier, types.TypeMem, s.mem())
3974 sys.ARM64, sys.PPC64)
3976 /******** runtime/internal/sys ********/
3977 addF("runtime/internal/sys", "Ctz32",
3978 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
3979 return s.newValue1(ssa.OpCtz32, types.Types[types.TINT], args[0])
3981 sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64)
3982 addF("runtime/internal/sys", "Ctz64",
3983 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
3984 return s.newValue1(ssa.OpCtz64, types.Types[types.TINT], args[0])
3986 sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64)
3987 addF("runtime/internal/sys", "Bswap32",
3988 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
3989 return s.newValue1(ssa.OpBswap32, types.Types[types.TUINT32], args[0])
3991 sys.AMD64, sys.ARM64, sys.ARM, sys.S390X)
3992 addF("runtime/internal/sys", "Bswap64",
3993 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
3994 return s.newValue1(ssa.OpBswap64, types.Types[types.TUINT64], args[0])
3996 sys.AMD64, sys.ARM64, sys.ARM, sys.S390X)
3998 /****** Prefetch ******/
3999 makePrefetchFunc := func(op ssa.Op) func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4000 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4001 s.vars[memVar] = s.newValue2(op, types.TypeMem, args[0], s.mem())
4006 // Make Prefetch intrinsics for supported platforms
4007 // On the unsupported platforms stub function will be eliminated
4008 addF("runtime/internal/sys", "Prefetch", makePrefetchFunc(ssa.OpPrefetchCache),
4009 sys.AMD64, sys.ARM64, sys.PPC64)
4010 addF("runtime/internal/sys", "PrefetchStreamed", makePrefetchFunc(ssa.OpPrefetchCacheStreamed),
4011 sys.AMD64, sys.ARM64, sys.PPC64)
4013 /******** runtime/internal/atomic ********/
4014 addF("runtime/internal/atomic", "Load",
4015 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4016 v := s.newValue2(ssa.OpAtomicLoad32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], s.mem())
4017 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4018 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4020 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4021 addF("runtime/internal/atomic", "Load8",
4022 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4023 v := s.newValue2(ssa.OpAtomicLoad8, types.NewTuple(types.Types[types.TUINT8], types.TypeMem), args[0], s.mem())
4024 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4025 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT8], v)
4027 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4028 addF("runtime/internal/atomic", "Load64",
4029 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4030 v := s.newValue2(ssa.OpAtomicLoad64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], s.mem())
4031 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4032 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4034 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4035 addF("runtime/internal/atomic", "LoadAcq",
4036 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4037 v := s.newValue2(ssa.OpAtomicLoadAcq32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], s.mem())
4038 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4039 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4041 sys.PPC64, sys.S390X)
4042 addF("runtime/internal/atomic", "LoadAcq64",
4043 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4044 v := s.newValue2(ssa.OpAtomicLoadAcq64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], s.mem())
4045 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4046 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4049 addF("runtime/internal/atomic", "Loadp",
4050 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4051 v := s.newValue2(ssa.OpAtomicLoadPtr, types.NewTuple(s.f.Config.Types.BytePtr, types.TypeMem), args[0], s.mem())
4052 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4053 return s.newValue1(ssa.OpSelect0, s.f.Config.Types.BytePtr, v)
4055 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4057 addF("runtime/internal/atomic", "Store",
4058 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4059 s.vars[memVar] = s.newValue3(ssa.OpAtomicStore32, types.TypeMem, args[0], args[1], s.mem())
4062 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4063 addF("runtime/internal/atomic", "Store8",
4064 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4065 s.vars[memVar] = s.newValue3(ssa.OpAtomicStore8, types.TypeMem, args[0], args[1], s.mem())
4068 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4069 addF("runtime/internal/atomic", "Store64",
4070 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4071 s.vars[memVar] = s.newValue3(ssa.OpAtomicStore64, types.TypeMem, args[0], args[1], s.mem())
4074 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4075 addF("runtime/internal/atomic", "StorepNoWB",
4076 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4077 s.vars[memVar] = s.newValue3(ssa.OpAtomicStorePtrNoWB, types.TypeMem, args[0], args[1], s.mem())
4080 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.RISCV64, sys.S390X)
4081 addF("runtime/internal/atomic", "StoreRel",
4082 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4083 s.vars[memVar] = s.newValue3(ssa.OpAtomicStoreRel32, types.TypeMem, args[0], args[1], s.mem())
4086 sys.PPC64, sys.S390X)
4087 addF("runtime/internal/atomic", "StoreRel64",
4088 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4089 s.vars[memVar] = s.newValue3(ssa.OpAtomicStoreRel64, types.TypeMem, args[0], args[1], s.mem())
4094 addF("runtime/internal/atomic", "Xchg",
4095 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4096 v := s.newValue3(ssa.OpAtomicExchange32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], args[1], s.mem())
4097 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4098 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4100 sys.AMD64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4101 addF("runtime/internal/atomic", "Xchg64",
4102 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4103 v := s.newValue3(ssa.OpAtomicExchange64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], args[1], s.mem())
4104 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4105 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4107 sys.AMD64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4109 type atomicOpEmitter func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind)
4111 makeAtomicGuardedIntrinsicARM64 := func(op0, op1 ssa.Op, typ, rtyp types.Kind, emit atomicOpEmitter) intrinsicBuilder {
4113 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4114 // Target Atomic feature is identified by dynamic detection
4115 addr := s.entryNewValue1A(ssa.OpAddr, types.Types[types.TBOOL].PtrTo(), ir.Syms.ARM64HasATOMICS, s.sb)
4116 v := s.load(types.Types[types.TBOOL], addr)
4118 b.Kind = ssa.BlockIf
4120 bTrue := s.f.NewBlock(ssa.BlockPlain)
4121 bFalse := s.f.NewBlock(ssa.BlockPlain)
4122 bEnd := s.f.NewBlock(ssa.BlockPlain)
4125 b.Likely = ssa.BranchLikely
4127 // We have atomic instructions - use it directly.
4129 emit(s, n, args, op1, typ)
4130 s.endBlock().AddEdgeTo(bEnd)
4132 // Use original instruction sequence.
4133 s.startBlock(bFalse)
4134 emit(s, n, args, op0, typ)
4135 s.endBlock().AddEdgeTo(bEnd)
4139 if rtyp == types.TNIL {
4142 return s.variable(n, types.Types[rtyp])
4147 atomicXchgXaddEmitterARM64 := func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind) {
4148 v := s.newValue3(op, types.NewTuple(types.Types[typ], types.TypeMem), args[0], args[1], s.mem())
4149 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4150 s.vars[n] = s.newValue1(ssa.OpSelect0, types.Types[typ], v)
4152 addF("runtime/internal/atomic", "Xchg",
4153 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicExchange32, ssa.OpAtomicExchange32Variant, types.TUINT32, types.TUINT32, atomicXchgXaddEmitterARM64),
4155 addF("runtime/internal/atomic", "Xchg64",
4156 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicExchange64, ssa.OpAtomicExchange64Variant, types.TUINT64, types.TUINT64, atomicXchgXaddEmitterARM64),
4159 addF("runtime/internal/atomic", "Xadd",
4160 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4161 v := s.newValue3(ssa.OpAtomicAdd32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], args[1], s.mem())
4162 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4163 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4165 sys.AMD64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4166 addF("runtime/internal/atomic", "Xadd64",
4167 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4168 v := s.newValue3(ssa.OpAtomicAdd64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], args[1], s.mem())
4169 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4170 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4172 sys.AMD64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4174 addF("runtime/internal/atomic", "Xadd",
4175 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAdd32, ssa.OpAtomicAdd32Variant, types.TUINT32, types.TUINT32, atomicXchgXaddEmitterARM64),
4177 addF("runtime/internal/atomic", "Xadd64",
4178 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAdd64, ssa.OpAtomicAdd64Variant, types.TUINT64, types.TUINT64, atomicXchgXaddEmitterARM64),
4181 addF("runtime/internal/atomic", "Cas",
4182 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4183 v := s.newValue4(ssa.OpAtomicCompareAndSwap32, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4184 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4185 return s.newValue1(ssa.OpSelect0, types.Types[types.TBOOL], v)
4187 sys.AMD64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4188 addF("runtime/internal/atomic", "Cas64",
4189 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4190 v := s.newValue4(ssa.OpAtomicCompareAndSwap64, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4191 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4192 return s.newValue1(ssa.OpSelect0, types.Types[types.TBOOL], v)
4194 sys.AMD64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4195 addF("runtime/internal/atomic", "CasRel",
4196 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4197 v := s.newValue4(ssa.OpAtomicCompareAndSwap32, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4198 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4199 return s.newValue1(ssa.OpSelect0, types.Types[types.TBOOL], v)
4203 atomicCasEmitterARM64 := func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind) {
4204 v := s.newValue4(op, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4205 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4206 s.vars[n] = s.newValue1(ssa.OpSelect0, types.Types[typ], v)
4209 addF("runtime/internal/atomic", "Cas",
4210 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicCompareAndSwap32, ssa.OpAtomicCompareAndSwap32Variant, types.TUINT32, types.TBOOL, atomicCasEmitterARM64),
4212 addF("runtime/internal/atomic", "Cas64",
4213 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicCompareAndSwap64, ssa.OpAtomicCompareAndSwap64Variant, types.TUINT64, types.TBOOL, atomicCasEmitterARM64),
4216 addF("runtime/internal/atomic", "And8",
4217 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4218 s.vars[memVar] = s.newValue3(ssa.OpAtomicAnd8, types.TypeMem, args[0], args[1], s.mem())
4221 sys.AMD64, sys.MIPS, sys.PPC64, sys.RISCV64, sys.S390X)
4222 addF("runtime/internal/atomic", "And",
4223 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4224 s.vars[memVar] = s.newValue3(ssa.OpAtomicAnd32, types.TypeMem, args[0], args[1], s.mem())
4227 sys.AMD64, sys.MIPS, sys.PPC64, sys.RISCV64, sys.S390X)
4228 addF("runtime/internal/atomic", "Or8",
4229 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4230 s.vars[memVar] = s.newValue3(ssa.OpAtomicOr8, types.TypeMem, args[0], args[1], s.mem())
4233 sys.AMD64, sys.ARM64, sys.MIPS, sys.PPC64, sys.RISCV64, sys.S390X)
4234 addF("runtime/internal/atomic", "Or",
4235 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4236 s.vars[memVar] = s.newValue3(ssa.OpAtomicOr32, types.TypeMem, args[0], args[1], s.mem())
4239 sys.AMD64, sys.MIPS, sys.PPC64, sys.RISCV64, sys.S390X)
4241 atomicAndOrEmitterARM64 := func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind) {
4242 s.vars[memVar] = s.newValue3(op, types.TypeMem, args[0], args[1], s.mem())
4245 addF("runtime/internal/atomic", "And8",
4246 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAnd8, ssa.OpAtomicAnd8Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4248 addF("runtime/internal/atomic", "And",
4249 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAnd32, ssa.OpAtomicAnd32Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4251 addF("runtime/internal/atomic", "Or8",
4252 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicOr8, ssa.OpAtomicOr8Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4254 addF("runtime/internal/atomic", "Or",
4255 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicOr32, ssa.OpAtomicOr32Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4258 // Aliases for atomic load operations
4259 alias("runtime/internal/atomic", "Loadint32", "runtime/internal/atomic", "Load", all...)
4260 alias("runtime/internal/atomic", "Loadint64", "runtime/internal/atomic", "Load64", all...)
4261 alias("runtime/internal/atomic", "Loaduintptr", "runtime/internal/atomic", "Load", p4...)
4262 alias("runtime/internal/atomic", "Loaduintptr", "runtime/internal/atomic", "Load64", p8...)
4263 alias("runtime/internal/atomic", "Loaduint", "runtime/internal/atomic", "Load", p4...)
4264 alias("runtime/internal/atomic", "Loaduint", "runtime/internal/atomic", "Load64", p8...)
4265 alias("runtime/internal/atomic", "LoadAcq", "runtime/internal/atomic", "Load", lwatomics...)
4266 alias("runtime/internal/atomic", "LoadAcq64", "runtime/internal/atomic", "Load64", lwatomics...)
4267 alias("runtime/internal/atomic", "LoadAcquintptr", "runtime/internal/atomic", "LoadAcq", p4...)
4268 alias("sync", "runtime_LoadAcquintptr", "runtime/internal/atomic", "LoadAcq", p4...) // linknamed
4269 alias("runtime/internal/atomic", "LoadAcquintptr", "runtime/internal/atomic", "LoadAcq64", p8...)
4270 alias("sync", "runtime_LoadAcquintptr", "runtime/internal/atomic", "LoadAcq64", p8...) // linknamed
4272 // Aliases for atomic store operations
4273 alias("runtime/internal/atomic", "Storeint32", "runtime/internal/atomic", "Store", all...)
4274 alias("runtime/internal/atomic", "Storeint64", "runtime/internal/atomic", "Store64", all...)
4275 alias("runtime/internal/atomic", "Storeuintptr", "runtime/internal/atomic", "Store", p4...)
4276 alias("runtime/internal/atomic", "Storeuintptr", "runtime/internal/atomic", "Store64", p8...)
4277 alias("runtime/internal/atomic", "StoreRel", "runtime/internal/atomic", "Store", lwatomics...)
4278 alias("runtime/internal/atomic", "StoreRel64", "runtime/internal/atomic", "Store64", lwatomics...)
4279 alias("runtime/internal/atomic", "StoreReluintptr", "runtime/internal/atomic", "StoreRel", p4...)
4280 alias("sync", "runtime_StoreReluintptr", "runtime/internal/atomic", "StoreRel", p4...) // linknamed
4281 alias("runtime/internal/atomic", "StoreReluintptr", "runtime/internal/atomic", "StoreRel64", p8...)
4282 alias("sync", "runtime_StoreReluintptr", "runtime/internal/atomic", "StoreRel64", p8...) // linknamed
4284 // Aliases for atomic swap operations
4285 alias("runtime/internal/atomic", "Xchgint32", "runtime/internal/atomic", "Xchg", all...)
4286 alias("runtime/internal/atomic", "Xchgint64", "runtime/internal/atomic", "Xchg64", all...)
4287 alias("runtime/internal/atomic", "Xchguintptr", "runtime/internal/atomic", "Xchg", p4...)
4288 alias("runtime/internal/atomic", "Xchguintptr", "runtime/internal/atomic", "Xchg64", p8...)
4290 // Aliases for atomic add operations
4291 alias("runtime/internal/atomic", "Xaddint32", "runtime/internal/atomic", "Xadd", all...)
4292 alias("runtime/internal/atomic", "Xaddint64", "runtime/internal/atomic", "Xadd64", all...)
4293 alias("runtime/internal/atomic", "Xadduintptr", "runtime/internal/atomic", "Xadd", p4...)
4294 alias("runtime/internal/atomic", "Xadduintptr", "runtime/internal/atomic", "Xadd64", p8...)
4296 // Aliases for atomic CAS operations
4297 alias("runtime/internal/atomic", "Casint32", "runtime/internal/atomic", "Cas", all...)
4298 alias("runtime/internal/atomic", "Casint64", "runtime/internal/atomic", "Cas64", all...)
4299 alias("runtime/internal/atomic", "Casuintptr", "runtime/internal/atomic", "Cas", p4...)
4300 alias("runtime/internal/atomic", "Casuintptr", "runtime/internal/atomic", "Cas64", p8...)
4301 alias("runtime/internal/atomic", "Casp1", "runtime/internal/atomic", "Cas", p4...)
4302 alias("runtime/internal/atomic", "Casp1", "runtime/internal/atomic", "Cas64", p8...)
4303 alias("runtime/internal/atomic", "CasRel", "runtime/internal/atomic", "Cas", lwatomics...)
4305 /******** math ********/
4306 addF("math", "Sqrt",
4307 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4308 return s.newValue1(ssa.OpSqrt, types.Types[types.TFLOAT64], args[0])
4310 sys.I386, sys.AMD64, sys.ARM, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X, sys.Wasm)
4311 addF("math", "Trunc",
4312 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4313 return s.newValue1(ssa.OpTrunc, types.Types[types.TFLOAT64], args[0])
4315 sys.ARM64, sys.PPC64, sys.S390X, sys.Wasm)
4316 addF("math", "Ceil",
4317 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4318 return s.newValue1(ssa.OpCeil, types.Types[types.TFLOAT64], args[0])
4320 sys.ARM64, sys.PPC64, sys.S390X, sys.Wasm)
4321 addF("math", "Floor",
4322 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4323 return s.newValue1(ssa.OpFloor, types.Types[types.TFLOAT64], args[0])
4325 sys.ARM64, sys.PPC64, sys.S390X, sys.Wasm)
4326 addF("math", "Round",
4327 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4328 return s.newValue1(ssa.OpRound, types.Types[types.TFLOAT64], args[0])
4330 sys.ARM64, sys.PPC64, sys.S390X)
4331 addF("math", "RoundToEven",
4332 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4333 return s.newValue1(ssa.OpRoundToEven, types.Types[types.TFLOAT64], args[0])
4335 sys.ARM64, sys.S390X, sys.Wasm)
4337 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4338 return s.newValue1(ssa.OpAbs, types.Types[types.TFLOAT64], args[0])
4340 sys.ARM64, sys.ARM, sys.PPC64, sys.RISCV64, sys.Wasm)
4341 addF("math", "Copysign",
4342 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4343 return s.newValue2(ssa.OpCopysign, types.Types[types.TFLOAT64], args[0], args[1])
4345 sys.PPC64, sys.RISCV64, sys.Wasm)
4347 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4348 return s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4350 sys.ARM64, sys.PPC64, sys.RISCV64, sys.S390X)
4352 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4353 if !s.config.UseFMA {
4354 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4355 return s.variable(n, types.Types[types.TFLOAT64])
4358 if buildcfg.GOAMD64 >= 3 {
4359 return s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4362 v := s.entryNewValue0A(ssa.OpHasCPUFeature, types.Types[types.TBOOL], ir.Syms.X86HasFMA)
4364 b.Kind = ssa.BlockIf
4366 bTrue := s.f.NewBlock(ssa.BlockPlain)
4367 bFalse := s.f.NewBlock(ssa.BlockPlain)
4368 bEnd := s.f.NewBlock(ssa.BlockPlain)
4371 b.Likely = ssa.BranchLikely // >= haswell cpus are common
4373 // We have the intrinsic - use it directly.
4375 s.vars[n] = s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4376 s.endBlock().AddEdgeTo(bEnd)
4378 // Call the pure Go version.
4379 s.startBlock(bFalse)
4380 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4381 s.endBlock().AddEdgeTo(bEnd)
4385 return s.variable(n, types.Types[types.TFLOAT64])
4389 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4390 if !s.config.UseFMA {
4391 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4392 return s.variable(n, types.Types[types.TFLOAT64])
4394 addr := s.entryNewValue1A(ssa.OpAddr, types.Types[types.TBOOL].PtrTo(), ir.Syms.ARMHasVFPv4, s.sb)
4395 v := s.load(types.Types[types.TBOOL], addr)
4397 b.Kind = ssa.BlockIf
4399 bTrue := s.f.NewBlock(ssa.BlockPlain)
4400 bFalse := s.f.NewBlock(ssa.BlockPlain)
4401 bEnd := s.f.NewBlock(ssa.BlockPlain)
4404 b.Likely = ssa.BranchLikely
4406 // We have the intrinsic - use it directly.
4408 s.vars[n] = s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4409 s.endBlock().AddEdgeTo(bEnd)
4411 // Call the pure Go version.
4412 s.startBlock(bFalse)
4413 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4414 s.endBlock().AddEdgeTo(bEnd)
4418 return s.variable(n, types.Types[types.TFLOAT64])
4422 makeRoundAMD64 := func(op ssa.Op) func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4423 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4424 if buildcfg.GOAMD64 >= 2 {
4425 return s.newValue1(op, types.Types[types.TFLOAT64], args[0])
4428 v := s.entryNewValue0A(ssa.OpHasCPUFeature, types.Types[types.TBOOL], ir.Syms.X86HasSSE41)
4430 b.Kind = ssa.BlockIf
4432 bTrue := s.f.NewBlock(ssa.BlockPlain)
4433 bFalse := s.f.NewBlock(ssa.BlockPlain)
4434 bEnd := s.f.NewBlock(ssa.BlockPlain)
4437 b.Likely = ssa.BranchLikely // most machines have sse4.1 nowadays
4439 // We have the intrinsic - use it directly.
4441 s.vars[n] = s.newValue1(op, types.Types[types.TFLOAT64], args[0])
4442 s.endBlock().AddEdgeTo(bEnd)
4444 // Call the pure Go version.
4445 s.startBlock(bFalse)
4446 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4447 s.endBlock().AddEdgeTo(bEnd)
4451 return s.variable(n, types.Types[types.TFLOAT64])
4454 addF("math", "RoundToEven",
4455 makeRoundAMD64(ssa.OpRoundToEven),
4457 addF("math", "Floor",
4458 makeRoundAMD64(ssa.OpFloor),
4460 addF("math", "Ceil",
4461 makeRoundAMD64(ssa.OpCeil),
4463 addF("math", "Trunc",
4464 makeRoundAMD64(ssa.OpTrunc),
4467 /******** math/bits ********/
4468 addF("math/bits", "TrailingZeros64",
4469 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4470 return s.newValue1(ssa.OpCtz64, types.Types[types.TINT], args[0])
4472 sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4473 addF("math/bits", "TrailingZeros32",
4474 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4475 return s.newValue1(ssa.OpCtz32, types.Types[types.TINT], args[0])
4477 sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4478 addF("math/bits", "TrailingZeros16",
4479 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4480 x := s.newValue1(ssa.OpZeroExt16to32, types.Types[types.TUINT32], args[0])
4481 c := s.constInt32(types.Types[types.TUINT32], 1<<16)
4482 y := s.newValue2(ssa.OpOr32, types.Types[types.TUINT32], x, c)
4483 return s.newValue1(ssa.OpCtz32, types.Types[types.TINT], y)
4486 addF("math/bits", "TrailingZeros16",
4487 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4488 return s.newValue1(ssa.OpCtz16, types.Types[types.TINT], args[0])
4490 sys.AMD64, sys.I386, sys.ARM, sys.ARM64, sys.Wasm)
4491 addF("math/bits", "TrailingZeros16",
4492 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4493 x := s.newValue1(ssa.OpZeroExt16to64, types.Types[types.TUINT64], args[0])
4494 c := s.constInt64(types.Types[types.TUINT64], 1<<16)
4495 y := s.newValue2(ssa.OpOr64, types.Types[types.TUINT64], x, c)
4496 return s.newValue1(ssa.OpCtz64, types.Types[types.TINT], y)
4498 sys.S390X, sys.PPC64)
4499 addF("math/bits", "TrailingZeros8",
4500 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4501 x := s.newValue1(ssa.OpZeroExt8to32, types.Types[types.TUINT32], args[0])
4502 c := s.constInt32(types.Types[types.TUINT32], 1<<8)
4503 y := s.newValue2(ssa.OpOr32, types.Types[types.TUINT32], x, c)
4504 return s.newValue1(ssa.OpCtz32, types.Types[types.TINT], y)
4507 addF("math/bits", "TrailingZeros8",
4508 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4509 return s.newValue1(ssa.OpCtz8, types.Types[types.TINT], args[0])
4511 sys.AMD64, sys.ARM, sys.ARM64, sys.Wasm)
4512 addF("math/bits", "TrailingZeros8",
4513 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4514 x := s.newValue1(ssa.OpZeroExt8to64, types.Types[types.TUINT64], args[0])
4515 c := s.constInt64(types.Types[types.TUINT64], 1<<8)
4516 y := s.newValue2(ssa.OpOr64, types.Types[types.TUINT64], x, c)
4517 return s.newValue1(ssa.OpCtz64, types.Types[types.TINT], y)
4520 alias("math/bits", "ReverseBytes64", "runtime/internal/sys", "Bswap64", all...)
4521 alias("math/bits", "ReverseBytes32", "runtime/internal/sys", "Bswap32", all...)
4522 // ReverseBytes inlines correctly, no need to intrinsify it.
4523 // ReverseBytes16 lowers to a rotate, no need for anything special here.
4524 addF("math/bits", "Len64",
4525 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4526 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], args[0])
4528 sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4529 addF("math/bits", "Len32",
4530 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4531 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], args[0])
4533 sys.AMD64, sys.ARM64, sys.PPC64)
4534 addF("math/bits", "Len32",
4535 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4536 if s.config.PtrSize == 4 {
4537 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], args[0])
4539 x := s.newValue1(ssa.OpZeroExt32to64, types.Types[types.TUINT64], args[0])
4540 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], x)
4542 sys.ARM, sys.S390X, sys.MIPS, sys.Wasm)
4543 addF("math/bits", "Len16",
4544 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4545 if s.config.PtrSize == 4 {
4546 x := s.newValue1(ssa.OpZeroExt16to32, types.Types[types.TUINT32], args[0])
4547 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], x)
4549 x := s.newValue1(ssa.OpZeroExt16to64, types.Types[types.TUINT64], args[0])
4550 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], x)
4552 sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4553 addF("math/bits", "Len16",
4554 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4555 return s.newValue1(ssa.OpBitLen16, types.Types[types.TINT], args[0])
4558 addF("math/bits", "Len8",
4559 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4560 if s.config.PtrSize == 4 {
4561 x := s.newValue1(ssa.OpZeroExt8to32, types.Types[types.TUINT32], args[0])
4562 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], x)
4564 x := s.newValue1(ssa.OpZeroExt8to64, types.Types[types.TUINT64], args[0])
4565 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], x)
4567 sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4568 addF("math/bits", "Len8",
4569 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4570 return s.newValue1(ssa.OpBitLen8, types.Types[types.TINT], args[0])
4573 addF("math/bits", "Len",
4574 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4575 if s.config.PtrSize == 4 {
4576 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], args[0])
4578 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], args[0])
4580 sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4581 // LeadingZeros is handled because it trivially calls Len.
4582 addF("math/bits", "Reverse64",
4583 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4584 return s.newValue1(ssa.OpBitRev64, types.Types[types.TINT], args[0])
4587 addF("math/bits", "Reverse32",
4588 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4589 return s.newValue1(ssa.OpBitRev32, types.Types[types.TINT], args[0])
4592 addF("math/bits", "Reverse16",
4593 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4594 return s.newValue1(ssa.OpBitRev16, types.Types[types.TINT], args[0])
4597 addF("math/bits", "Reverse8",
4598 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4599 return s.newValue1(ssa.OpBitRev8, types.Types[types.TINT], args[0])
4602 addF("math/bits", "Reverse",
4603 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4604 return s.newValue1(ssa.OpBitRev64, types.Types[types.TINT], args[0])
4607 addF("math/bits", "RotateLeft8",
4608 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4609 return s.newValue2(ssa.OpRotateLeft8, types.Types[types.TUINT8], args[0], args[1])
4612 addF("math/bits", "RotateLeft16",
4613 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4614 return s.newValue2(ssa.OpRotateLeft16, types.Types[types.TUINT16], args[0], args[1])
4617 addF("math/bits", "RotateLeft32",
4618 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4619 return s.newValue2(ssa.OpRotateLeft32, types.Types[types.TUINT32], args[0], args[1])
4621 sys.AMD64, sys.ARM, sys.ARM64, sys.S390X, sys.PPC64, sys.Wasm)
4622 addF("math/bits", "RotateLeft64",
4623 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4624 return s.newValue2(ssa.OpRotateLeft64, types.Types[types.TUINT64], args[0], args[1])
4626 sys.AMD64, sys.ARM64, sys.S390X, sys.PPC64, sys.Wasm)
4627 alias("math/bits", "RotateLeft", "math/bits", "RotateLeft64", p8...)
4629 makeOnesCountAMD64 := func(op ssa.Op) func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4630 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4631 if buildcfg.GOAMD64 >= 2 {
4632 return s.newValue1(op, types.Types[types.TINT], args[0])
4635 v := s.entryNewValue0A(ssa.OpHasCPUFeature, types.Types[types.TBOOL], ir.Syms.X86HasPOPCNT)
4637 b.Kind = ssa.BlockIf
4639 bTrue := s.f.NewBlock(ssa.BlockPlain)
4640 bFalse := s.f.NewBlock(ssa.BlockPlain)
4641 bEnd := s.f.NewBlock(ssa.BlockPlain)
4644 b.Likely = ssa.BranchLikely // most machines have popcnt nowadays
4646 // We have the intrinsic - use it directly.
4648 s.vars[n] = s.newValue1(op, types.Types[types.TINT], args[0])
4649 s.endBlock().AddEdgeTo(bEnd)
4651 // Call the pure Go version.
4652 s.startBlock(bFalse)
4653 s.vars[n] = s.callResult(n, callNormal) // types.Types[TINT]
4654 s.endBlock().AddEdgeTo(bEnd)
4658 return s.variable(n, types.Types[types.TINT])
4661 addF("math/bits", "OnesCount64",
4662 makeOnesCountAMD64(ssa.OpPopCount64),
4664 addF("math/bits", "OnesCount64",
4665 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4666 return s.newValue1(ssa.OpPopCount64, types.Types[types.TINT], args[0])
4668 sys.PPC64, sys.ARM64, sys.S390X, sys.Wasm)
4669 addF("math/bits", "OnesCount32",
4670 makeOnesCountAMD64(ssa.OpPopCount32),
4672 addF("math/bits", "OnesCount32",
4673 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4674 return s.newValue1(ssa.OpPopCount32, types.Types[types.TINT], args[0])
4676 sys.PPC64, sys.ARM64, sys.S390X, sys.Wasm)
4677 addF("math/bits", "OnesCount16",
4678 makeOnesCountAMD64(ssa.OpPopCount16),
4680 addF("math/bits", "OnesCount16",
4681 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4682 return s.newValue1(ssa.OpPopCount16, types.Types[types.TINT], args[0])
4684 sys.ARM64, sys.S390X, sys.PPC64, sys.Wasm)
4685 addF("math/bits", "OnesCount8",
4686 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4687 return s.newValue1(ssa.OpPopCount8, types.Types[types.TINT], args[0])
4689 sys.S390X, sys.PPC64, sys.Wasm)
4690 addF("math/bits", "OnesCount",
4691 makeOnesCountAMD64(ssa.OpPopCount64),
4693 addF("math/bits", "Mul64",
4694 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4695 return s.newValue2(ssa.OpMul64uhilo, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1])
4697 sys.AMD64, sys.ARM64, sys.PPC64, sys.S390X, sys.MIPS64, sys.RISCV64, sys.Loong64)
4698 alias("math/bits", "Mul", "math/bits", "Mul64", p8...)
4699 alias("runtime/internal/math", "Mul64", "math/bits", "Mul64", p8...)
4700 addF("math/bits", "Add64",
4701 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4702 return s.newValue3(ssa.OpAdd64carry, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1], args[2])
4704 sys.AMD64, sys.ARM64, sys.PPC64, sys.S390X)
4705 alias("math/bits", "Add", "math/bits", "Add64", sys.ArchAMD64, sys.ArchARM64, sys.ArchPPC64, sys.ArchPPC64LE, sys.ArchS390X)
4706 addF("math/bits", "Sub64",
4707 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4708 return s.newValue3(ssa.OpSub64borrow, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1], args[2])
4710 sys.AMD64, sys.ARM64, sys.PPC64, sys.S390X)
4711 alias("math/bits", "Sub", "math/bits", "Sub64", sys.ArchAMD64, sys.ArchARM64, sys.ArchS390X)
4712 addF("math/bits", "Div64",
4713 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4714 // check for divide-by-zero/overflow and panic with appropriate message
4715 cmpZero := s.newValue2(s.ssaOp(ir.ONE, types.Types[types.TUINT64]), types.Types[types.TBOOL], args[2], s.zeroVal(types.Types[types.TUINT64]))
4716 s.check(cmpZero, ir.Syms.Panicdivide)
4717 cmpOverflow := s.newValue2(s.ssaOp(ir.OLT, types.Types[types.TUINT64]), types.Types[types.TBOOL], args[0], args[2])
4718 s.check(cmpOverflow, ir.Syms.Panicoverflow)
4719 return s.newValue3(ssa.OpDiv128u, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1], args[2])
4722 alias("math/bits", "Div", "math/bits", "Div64", sys.ArchAMD64)
4724 alias("runtime/internal/sys", "Ctz8", "math/bits", "TrailingZeros8", all...)
4725 alias("runtime/internal/sys", "TrailingZeros8", "math/bits", "TrailingZeros8", all...)
4726 alias("runtime/internal/sys", "TrailingZeros64", "math/bits", "TrailingZeros64", all...)
4727 alias("runtime/internal/sys", "Len8", "math/bits", "Len8", all...)
4728 alias("runtime/internal/sys", "Len64", "math/bits", "Len64", all...)
4729 alias("runtime/internal/sys", "OnesCount64", "math/bits", "OnesCount64", all...)
4731 /******** sync/atomic ********/
4733 // Note: these are disabled by flag_race in findIntrinsic below.
4734 alias("sync/atomic", "LoadInt32", "runtime/internal/atomic", "Load", all...)
4735 alias("sync/atomic", "LoadInt64", "runtime/internal/atomic", "Load64", all...)
4736 alias("sync/atomic", "LoadPointer", "runtime/internal/atomic", "Loadp", all...)
4737 alias("sync/atomic", "LoadUint32", "runtime/internal/atomic", "Load", all...)
4738 alias("sync/atomic", "LoadUint64", "runtime/internal/atomic", "Load64", all...)
4739 alias("sync/atomic", "LoadUintptr", "runtime/internal/atomic", "Load", p4...)
4740 alias("sync/atomic", "LoadUintptr", "runtime/internal/atomic", "Load64", p8...)
4742 alias("sync/atomic", "StoreInt32", "runtime/internal/atomic", "Store", all...)
4743 alias("sync/atomic", "StoreInt64", "runtime/internal/atomic", "Store64", all...)
4744 // Note: not StorePointer, that needs a write barrier. Same below for {CompareAnd}Swap.
4745 alias("sync/atomic", "StoreUint32", "runtime/internal/atomic", "Store", all...)
4746 alias("sync/atomic", "StoreUint64", "runtime/internal/atomic", "Store64", all...)
4747 alias("sync/atomic", "StoreUintptr", "runtime/internal/atomic", "Store", p4...)
4748 alias("sync/atomic", "StoreUintptr", "runtime/internal/atomic", "Store64", p8...)
4750 alias("sync/atomic", "SwapInt32", "runtime/internal/atomic", "Xchg", all...)
4751 alias("sync/atomic", "SwapInt64", "runtime/internal/atomic", "Xchg64", all...)
4752 alias("sync/atomic", "SwapUint32", "runtime/internal/atomic", "Xchg", all...)
4753 alias("sync/atomic", "SwapUint64", "runtime/internal/atomic", "Xchg64", all...)
4754 alias("sync/atomic", "SwapUintptr", "runtime/internal/atomic", "Xchg", p4...)
4755 alias("sync/atomic", "SwapUintptr", "runtime/internal/atomic", "Xchg64", p8...)
4757 alias("sync/atomic", "CompareAndSwapInt32", "runtime/internal/atomic", "Cas", all...)
4758 alias("sync/atomic", "CompareAndSwapInt64", "runtime/internal/atomic", "Cas64", all...)
4759 alias("sync/atomic", "CompareAndSwapUint32", "runtime/internal/atomic", "Cas", all...)
4760 alias("sync/atomic", "CompareAndSwapUint64", "runtime/internal/atomic", "Cas64", all...)
4761 alias("sync/atomic", "CompareAndSwapUintptr", "runtime/internal/atomic", "Cas", p4...)
4762 alias("sync/atomic", "CompareAndSwapUintptr", "runtime/internal/atomic", "Cas64", p8...)
4764 alias("sync/atomic", "AddInt32", "runtime/internal/atomic", "Xadd", all...)
4765 alias("sync/atomic", "AddInt64", "runtime/internal/atomic", "Xadd64", all...)
4766 alias("sync/atomic", "AddUint32", "runtime/internal/atomic", "Xadd", all...)
4767 alias("sync/atomic", "AddUint64", "runtime/internal/atomic", "Xadd64", all...)
4768 alias("sync/atomic", "AddUintptr", "runtime/internal/atomic", "Xadd", p4...)
4769 alias("sync/atomic", "AddUintptr", "runtime/internal/atomic", "Xadd64", p8...)
4771 /******** math/big ********/
4772 alias("math/big", "mulWW", "math/bits", "Mul64", p8...)
4775 // findIntrinsic returns a function which builds the SSA equivalent of the
4776 // function identified by the symbol sym. If sym is not an intrinsic call, returns nil.
4777 func findIntrinsic(sym *types.Sym) intrinsicBuilder {
4778 if sym == nil || sym.Pkg == nil {
4782 if sym.Pkg == ir.Pkgs.Runtime {
4785 if base.Flag.Race && pkg == "sync/atomic" {
4786 // The race detector needs to be able to intercept these calls.
4787 // We can't intrinsify them.
4790 // Skip intrinsifying math functions (which may contain hard-float
4791 // instructions) when soft-float
4792 if Arch.SoftFloat && pkg == "math" {
4797 if ssa.IntrinsicsDisable {
4798 if pkg == "runtime" && (fn == "getcallerpc" || fn == "getcallersp" || fn == "getclosureptr") {
4799 // These runtime functions don't have definitions, must be intrinsics.
4804 return intrinsics[intrinsicKey{Arch.LinkArch.Arch, pkg, fn}]
4807 func IsIntrinsicCall(n *ir.CallExpr) bool {
4811 name, ok := n.X.(*ir.Name)
4815 return findIntrinsic(name.Sym()) != nil
4818 // intrinsicCall converts a call to a recognized intrinsic function into the intrinsic SSA operation.
4819 func (s *state) intrinsicCall(n *ir.CallExpr) *ssa.Value {
4820 v := findIntrinsic(n.X.Sym())(s, n, s.intrinsicArgs(n))
4821 if ssa.IntrinsicsDebug > 0 {
4826 if x.Op == ssa.OpSelect0 || x.Op == ssa.OpSelect1 {
4829 base.WarnfAt(n.Pos(), "intrinsic substitution for %v with %s", n.X.Sym().Name, x.LongString())
4834 // intrinsicArgs extracts args from n, evaluates them to SSA values, and returns them.
4835 func (s *state) intrinsicArgs(n *ir.CallExpr) []*ssa.Value {
4836 args := make([]*ssa.Value, len(n.Args))
4837 for i, n := range n.Args {
4843 // openDeferRecord adds code to evaluate and store the function for an open-code defer
4844 // call, and records info about the defer, so we can generate proper code on the
4845 // exit paths. n is the sub-node of the defer node that is the actual function
4846 // call. We will also record funcdata information on where the function is stored
4847 // (as well as the deferBits variable), and this will enable us to run the proper
4848 // defer calls during panics.
4849 func (s *state) openDeferRecord(n *ir.CallExpr) {
4850 if len(n.Args) != 0 || n.Op() != ir.OCALLFUNC || n.X.Type().NumResults() != 0 {
4851 s.Fatalf("defer call with arguments or results: %v", n)
4854 opendefer := &openDeferInfo{
4858 // We must always store the function value in a stack slot for the
4859 // runtime panic code to use. But in the defer exit code, we will
4860 // call the function directly if it is a static function.
4861 closureVal := s.expr(fn)
4862 closure := s.openDeferSave(fn.Type(), closureVal)
4863 opendefer.closureNode = closure.Aux.(*ir.Name)
4864 if !(fn.Op() == ir.ONAME && fn.(*ir.Name).Class == ir.PFUNC) {
4865 opendefer.closure = closure
4867 index := len(s.openDefers)
4868 s.openDefers = append(s.openDefers, opendefer)
4870 // Update deferBits only after evaluation and storage to stack of
4871 // the function is successful.
4872 bitvalue := s.constInt8(types.Types[types.TUINT8], 1<<uint(index))
4873 newDeferBits := s.newValue2(ssa.OpOr8, types.Types[types.TUINT8], s.variable(deferBitsVar, types.Types[types.TUINT8]), bitvalue)
4874 s.vars[deferBitsVar] = newDeferBits
4875 s.store(types.Types[types.TUINT8], s.deferBitsAddr, newDeferBits)
4878 // openDeferSave generates SSA nodes to store a value (with type t) for an
4879 // open-coded defer at an explicit autotmp location on the stack, so it can be
4880 // reloaded and used for the appropriate call on exit. Type t must be a function type
4881 // (therefore SSAable). val is the value to be stored. The function returns an SSA
4882 // value representing a pointer to the autotmp location.
4883 func (s *state) openDeferSave(t *types.Type, val *ssa.Value) *ssa.Value {
4885 s.Fatalf("openDeferSave of non-SSA-able type %v val=%v", t, val)
4887 if !t.HasPointers() {
4888 s.Fatalf("openDeferSave of pointerless type %v val=%v", t, val)
4891 temp := typecheck.TempAt(pos.WithNotStmt(), s.curfn, t)
4892 temp.SetOpenDeferSlot(true)
4893 var addrTemp *ssa.Value
4894 // Use OpVarLive to make sure stack slot for the closure is not removed by
4895 // dead-store elimination
4896 if s.curBlock.ID != s.f.Entry.ID {
4897 // Force the tmp storing this defer function to be declared in the entry
4898 // block, so that it will be live for the defer exit code (which will
4899 // actually access it only if the associated defer call has been activated).
4900 s.defvars[s.f.Entry.ID][memVar] = s.f.Entry.NewValue1A(src.NoXPos, ssa.OpVarDef, types.TypeMem, temp, s.defvars[s.f.Entry.ID][memVar])
4901 s.defvars[s.f.Entry.ID][memVar] = s.f.Entry.NewValue1A(src.NoXPos, ssa.OpVarLive, types.TypeMem, temp, s.defvars[s.f.Entry.ID][memVar])
4902 addrTemp = s.f.Entry.NewValue2A(src.NoXPos, ssa.OpLocalAddr, types.NewPtr(temp.Type()), temp, s.sp, s.defvars[s.f.Entry.ID][memVar])
4904 // Special case if we're still in the entry block. We can't use
4905 // the above code, since s.defvars[s.f.Entry.ID] isn't defined
4906 // until we end the entry block with s.endBlock().
4907 s.vars[memVar] = s.newValue1Apos(ssa.OpVarDef, types.TypeMem, temp, s.mem(), false)
4908 s.vars[memVar] = s.newValue1Apos(ssa.OpVarLive, types.TypeMem, temp, s.mem(), false)
4909 addrTemp = s.newValue2Apos(ssa.OpLocalAddr, types.NewPtr(temp.Type()), temp, s.sp, s.mem(), false)
4911 // Since we may use this temp during exit depending on the
4912 // deferBits, we must define it unconditionally on entry.
4913 // Therefore, we must make sure it is zeroed out in the entry
4914 // block if it contains pointers, else GC may wrongly follow an
4915 // uninitialized pointer value.
4916 temp.SetNeedzero(true)
4917 // We are storing to the stack, hence we can avoid the full checks in
4918 // storeType() (no write barrier) and do a simple store().
4919 s.store(t, addrTemp, val)
4923 // openDeferExit generates SSA for processing all the open coded defers at exit.
4924 // The code involves loading deferBits, and checking each of the bits to see if
4925 // the corresponding defer statement was executed. For each bit that is turned
4926 // on, the associated defer call is made.
4927 func (s *state) openDeferExit() {
4928 deferExit := s.f.NewBlock(ssa.BlockPlain)
4929 s.endBlock().AddEdgeTo(deferExit)
4930 s.startBlock(deferExit)
4931 s.lastDeferExit = deferExit
4932 s.lastDeferCount = len(s.openDefers)
4933 zeroval := s.constInt8(types.Types[types.TUINT8], 0)
4934 // Test for and run defers in reverse order
4935 for i := len(s.openDefers) - 1; i >= 0; i-- {
4936 r := s.openDefers[i]
4937 bCond := s.f.NewBlock(ssa.BlockPlain)
4938 bEnd := s.f.NewBlock(ssa.BlockPlain)
4940 deferBits := s.variable(deferBitsVar, types.Types[types.TUINT8])
4941 // Generate code to check if the bit associated with the current
4943 bitval := s.constInt8(types.Types[types.TUINT8], 1<<uint(i))
4944 andval := s.newValue2(ssa.OpAnd8, types.Types[types.TUINT8], deferBits, bitval)
4945 eqVal := s.newValue2(ssa.OpEq8, types.Types[types.TBOOL], andval, zeroval)
4947 b.Kind = ssa.BlockIf
4951 bCond.AddEdgeTo(bEnd)
4954 // Clear this bit in deferBits and force store back to stack, so
4955 // we will not try to re-run this defer call if this defer call panics.
4956 nbitval := s.newValue1(ssa.OpCom8, types.Types[types.TUINT8], bitval)
4957 maskedval := s.newValue2(ssa.OpAnd8, types.Types[types.TUINT8], deferBits, nbitval)
4958 s.store(types.Types[types.TUINT8], s.deferBitsAddr, maskedval)
4959 // Use this value for following tests, so we keep previous
4961 s.vars[deferBitsVar] = maskedval
4963 // Generate code to call the function call of the defer, using the
4964 // closure that were stored in argtmps at the point of the defer
4967 stksize := fn.Type().ArgWidth()
4968 var callArgs []*ssa.Value
4970 if r.closure != nil {
4971 v := s.load(r.closure.Type.Elem(), r.closure)
4972 s.maybeNilCheckClosure(v, callDefer)
4973 codeptr := s.rawLoad(types.Types[types.TUINTPTR], v)
4974 aux := ssa.ClosureAuxCall(s.f.ABIDefault.ABIAnalyzeTypes(nil, nil, nil))
4975 call = s.newValue2A(ssa.OpClosureLECall, aux.LateExpansionResultType(), aux, codeptr, v)
4977 aux := ssa.StaticAuxCall(fn.(*ir.Name).Linksym(), s.f.ABIDefault.ABIAnalyzeTypes(nil, nil, nil))
4978 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
4980 callArgs = append(callArgs, s.mem())
4981 call.AddArgs(callArgs...)
4982 call.AuxInt = stksize
4983 s.vars[memVar] = s.newValue1I(ssa.OpSelectN, types.TypeMem, 0, call)
4984 // Make sure that the stack slots with pointers are kept live
4985 // through the call (which is a pre-emption point). Also, we will
4986 // use the first call of the last defer exit to compute liveness
4987 // for the deferreturn, so we want all stack slots to be live.
4988 if r.closureNode != nil {
4989 s.vars[memVar] = s.newValue1Apos(ssa.OpVarLive, types.TypeMem, r.closureNode, s.mem(), false)
4997 func (s *state) callResult(n *ir.CallExpr, k callKind) *ssa.Value {
4998 return s.call(n, k, false)
5001 func (s *state) callAddr(n *ir.CallExpr, k callKind) *ssa.Value {
5002 return s.call(n, k, true)
5005 // Calls the function n using the specified call type.
5006 // Returns the address of the return value (or nil if none).
5007 func (s *state) call(n *ir.CallExpr, k callKind, returnResultAddr bool) *ssa.Value {
5009 var callee *ir.Name // target function (if static)
5010 var closure *ssa.Value // ptr to closure to run (if dynamic)
5011 var codeptr *ssa.Value // ptr to target code (if dynamic)
5012 var rcvr *ssa.Value // receiver to set
5014 var ACArgs []*types.Type // AuxCall args
5015 var ACResults []*types.Type // AuxCall results
5016 var callArgs []*ssa.Value // For late-expansion, the args themselves (not stored, args to the call instead).
5018 callABI := s.f.ABIDefault
5020 if k != callNormal && k != callTail && (len(n.Args) != 0 || n.Op() == ir.OCALLINTER || n.X.Type().NumResults() != 0) {
5021 s.Fatalf("go/defer call with arguments: %v", n)
5026 if (k == callNormal || k == callTail) && fn.Op() == ir.ONAME && fn.(*ir.Name).Class == ir.PFUNC {
5029 if buildcfg.Experiment.RegabiArgs {
5030 // This is a static call, so it may be
5031 // a direct call to a non-ABIInternal
5032 // function. fn.Func may be nil for
5033 // some compiler-generated functions,
5034 // but those are all ABIInternal.
5036 callABI = abiForFunc(fn.Func, s.f.ABI0, s.f.ABI1)
5039 // TODO(register args) remove after register abi is working
5040 inRegistersImported := fn.Pragma()&ir.RegisterParams != 0
5041 inRegistersSamePackage := fn.Func != nil && fn.Func.Pragma&ir.RegisterParams != 0
5042 if inRegistersImported || inRegistersSamePackage {
5048 closure = s.expr(fn)
5049 if k != callDefer && k != callDeferStack {
5050 // Deferred nil function needs to panic when the function is invoked,
5051 // not the point of defer statement.
5052 s.maybeNilCheckClosure(closure, k)
5055 if fn.Op() != ir.ODOTINTER {
5056 s.Fatalf("OCALLINTER: n.Left not an ODOTINTER: %v", fn.Op())
5058 fn := fn.(*ir.SelectorExpr)
5059 var iclosure *ssa.Value
5060 iclosure, rcvr = s.getClosureAndRcvr(fn)
5061 if k == callNormal {
5062 codeptr = s.load(types.Types[types.TUINTPTR], iclosure)
5068 params := callABI.ABIAnalyze(n.X.Type(), false /* Do not set (register) nNames from caller side -- can cause races. */)
5069 types.CalcSize(fn.Type())
5070 stksize := params.ArgWidth() // includes receiver, args, and results
5072 res := n.X.Type().Results()
5073 if k == callNormal || k == callTail {
5074 for _, p := range params.OutParams() {
5075 ACResults = append(ACResults, p.Type)
5080 if k == callDeferStack {
5081 // Make a defer struct d on the stack.
5083 s.Fatalf("deferprocStack with non-zero stack size %d: %v", stksize, n)
5087 d := typecheck.TempAt(n.Pos(), s.curfn, t)
5089 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, d, s.mem())
5092 // Must match deferstruct() below and src/runtime/runtime2.go:_defer.
5093 // 0: started, set in deferprocStack
5094 // 1: heap, set in deferprocStack
5096 // 3: sp, set in deferprocStack
5097 // 4: pc, set in deferprocStack
5099 s.store(closure.Type,
5100 s.newValue1I(ssa.OpOffPtr, closure.Type.PtrTo(), t.FieldOff(5), addr),
5102 // 6: panic, set in deferprocStack
5103 // 7: link, set in deferprocStack
5108 // Call runtime.deferprocStack with pointer to _defer record.
5109 ACArgs = append(ACArgs, types.Types[types.TUINTPTR])
5110 aux := ssa.StaticAuxCall(ir.Syms.DeferprocStack, s.f.ABIDefault.ABIAnalyzeTypes(nil, ACArgs, ACResults))
5111 callArgs = append(callArgs, addr, s.mem())
5112 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5113 call.AddArgs(callArgs...)
5114 call.AuxInt = int64(types.PtrSize) // deferprocStack takes a *_defer arg
5116 // Store arguments to stack, including defer/go arguments and receiver for method calls.
5117 // These are written in SP-offset order.
5118 argStart := base.Ctxt.Arch.FixedFrameSize
5120 if k != callNormal && k != callTail {
5121 // Write closure (arg to newproc/deferproc).
5122 ACArgs = append(ACArgs, types.Types[types.TUINTPTR]) // not argExtra
5123 callArgs = append(callArgs, closure)
5124 stksize += int64(types.PtrSize)
5125 argStart += int64(types.PtrSize)
5128 // Set receiver (for interface calls).
5130 callArgs = append(callArgs, rcvr)
5137 for _, p := range params.InParams() { // includes receiver for interface calls
5138 ACArgs = append(ACArgs, p.Type)
5141 // Split the entry block if there are open defers, because later calls to
5142 // openDeferSave may cause a mismatch between the mem for an OpDereference
5143 // and the call site which uses it. See #49282.
5144 if s.curBlock.ID == s.f.Entry.ID && s.hasOpenDefers {
5146 b.Kind = ssa.BlockPlain
5147 curb := s.f.NewBlock(ssa.BlockPlain)
5152 for i, n := range args {
5153 callArgs = append(callArgs, s.putArg(n, t.Params().Field(i).Type))
5156 callArgs = append(callArgs, s.mem())
5160 case k == callDefer:
5161 aux := ssa.StaticAuxCall(ir.Syms.Deferproc, s.f.ABIDefault.ABIAnalyzeTypes(nil, ACArgs, ACResults)) // TODO paramResultInfo for DeferProc
5162 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5164 aux := ssa.StaticAuxCall(ir.Syms.Newproc, s.f.ABIDefault.ABIAnalyzeTypes(nil, ACArgs, ACResults))
5165 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux) // TODO paramResultInfo for NewProc
5166 case closure != nil:
5167 // rawLoad because loading the code pointer from a
5168 // closure is always safe, but IsSanitizerSafeAddr
5169 // can't always figure that out currently, and it's
5170 // critical that we not clobber any arguments already
5171 // stored onto the stack.
5172 codeptr = s.rawLoad(types.Types[types.TUINTPTR], closure)
5173 aux := ssa.ClosureAuxCall(callABI.ABIAnalyzeTypes(nil, ACArgs, ACResults))
5174 call = s.newValue2A(ssa.OpClosureLECall, aux.LateExpansionResultType(), aux, codeptr, closure)
5175 case codeptr != nil:
5176 // Note that the "receiver" parameter is nil because the actual receiver is the first input parameter.
5177 aux := ssa.InterfaceAuxCall(params)
5178 call = s.newValue1A(ssa.OpInterLECall, aux.LateExpansionResultType(), aux, codeptr)
5180 aux := ssa.StaticAuxCall(callTargetLSym(callee), params)
5181 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5183 call.Op = ssa.OpTailLECall
5184 stksize = 0 // Tail call does not use stack. We reuse caller's frame.
5187 s.Fatalf("bad call type %v %v", n.Op(), n)
5189 call.AddArgs(callArgs...)
5190 call.AuxInt = stksize // Call operations carry the argsize of the callee along with them
5193 s.vars[memVar] = s.newValue1I(ssa.OpSelectN, types.TypeMem, int64(len(ACResults)), call)
5194 // Insert OVARLIVE nodes
5195 for _, name := range n.KeepAlive {
5196 s.stmt(ir.NewUnaryExpr(n.Pos(), ir.OVARLIVE, name))
5199 // Finish block for defers
5200 if k == callDefer || k == callDeferStack {
5202 b.Kind = ssa.BlockDefer
5204 bNext := s.f.NewBlock(ssa.BlockPlain)
5206 // Add recover edge to exit code.
5207 r := s.f.NewBlock(ssa.BlockPlain)
5211 b.Likely = ssa.BranchLikely
5215 if res.NumFields() == 0 || k != callNormal {
5216 // call has no return value. Continue with the next statement.
5220 if returnResultAddr {
5221 return s.resultAddrOfCall(call, 0, fp.Type)
5223 return s.newValue1I(ssa.OpSelectN, fp.Type, 0, call)
5226 // maybeNilCheckClosure checks if a nil check of a closure is needed in some
5227 // architecture-dependent situations and, if so, emits the nil check.
5228 func (s *state) maybeNilCheckClosure(closure *ssa.Value, k callKind) {
5229 if Arch.LinkArch.Family == sys.Wasm || buildcfg.GOOS == "aix" && k != callGo {
5230 // On AIX, the closure needs to be verified as fn can be nil, except if it's a call go. This needs to be handled by the runtime to have the "go of nil func value" error.
5231 // TODO(neelance): On other architectures this should be eliminated by the optimization steps
5236 // getClosureAndRcvr returns values for the appropriate closure and receiver of an
5238 func (s *state) getClosureAndRcvr(fn *ir.SelectorExpr) (*ssa.Value, *ssa.Value) {
5240 itab := s.newValue1(ssa.OpITab, types.Types[types.TUINTPTR], i)
5242 itabidx := fn.Offset() + 2*int64(types.PtrSize) + 8 // offset of fun field in runtime.itab
5243 closure := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.UintptrPtr, itabidx, itab)
5244 rcvr := s.newValue1(ssa.OpIData, s.f.Config.Types.BytePtr, i)
5245 return closure, rcvr
5248 // etypesign returns the signed-ness of e, for integer/pointer etypes.
5249 // -1 means signed, +1 means unsigned, 0 means non-integer/non-pointer.
5250 func etypesign(e types.Kind) int8 {
5252 case types.TINT8, types.TINT16, types.TINT32, types.TINT64, types.TINT:
5254 case types.TUINT8, types.TUINT16, types.TUINT32, types.TUINT64, types.TUINT, types.TUINTPTR, types.TUNSAFEPTR:
5260 // addr converts the address of the expression n to SSA, adds it to s and returns the SSA result.
5261 // The value that the returned Value represents is guaranteed to be non-nil.
5262 func (s *state) addr(n ir.Node) *ssa.Value {
5263 if n.Op() != ir.ONAME {
5269 s.Fatalf("addr of canSSA expression: %+v", n)
5272 t := types.NewPtr(n.Type())
5273 linksymOffset := func(lsym *obj.LSym, offset int64) *ssa.Value {
5274 v := s.entryNewValue1A(ssa.OpAddr, t, lsym, s.sb)
5275 // TODO: Make OpAddr use AuxInt as well as Aux.
5277 v = s.entryNewValue1I(ssa.OpOffPtr, v.Type, offset, v)
5282 case ir.OLINKSYMOFFSET:
5283 no := n.(*ir.LinksymOffsetExpr)
5284 return linksymOffset(no.Linksym, no.Offset_)
5287 if n.Heapaddr != nil {
5288 return s.expr(n.Heapaddr)
5293 return linksymOffset(n.Linksym(), 0)
5300 s.Fatalf("addr of undeclared ONAME %v. declared: %v", n, s.decladdrs)
5303 return s.newValue2Apos(ssa.OpLocalAddr, t, n, s.sp, s.mem(), !ir.IsAutoTmp(n))
5305 case ir.PPARAMOUT: // Same as PAUTO -- cannot generate LEA early.
5306 // ensure that we reuse symbols for out parameters so
5307 // that cse works on their addresses
5308 return s.newValue2Apos(ssa.OpLocalAddr, t, n, s.sp, s.mem(), true)
5310 s.Fatalf("variable address class %v not implemented", n.Class)
5314 // load return from callee
5315 n := n.(*ir.ResultExpr)
5316 return s.resultAddrOfCall(s.prevCall, n.Index, n.Type())
5318 n := n.(*ir.IndexExpr)
5319 if n.X.Type().IsSlice() {
5321 i := s.expr(n.Index)
5322 len := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], a)
5323 i = s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded())
5324 p := s.newValue1(ssa.OpSlicePtr, t, a)
5325 return s.newValue2(ssa.OpPtrIndex, t, p, i)
5328 i := s.expr(n.Index)
5329 len := s.constInt(types.Types[types.TINT], n.X.Type().NumElem())
5330 i = s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded())
5331 return s.newValue2(ssa.OpPtrIndex, types.NewPtr(n.X.Type().Elem()), a, i)
5334 n := n.(*ir.StarExpr)
5335 return s.exprPtr(n.X, n.Bounded(), n.Pos())
5337 n := n.(*ir.SelectorExpr)
5339 return s.newValue1I(ssa.OpOffPtr, t, n.Offset(), p)
5341 n := n.(*ir.SelectorExpr)
5342 p := s.exprPtr(n.X, n.Bounded(), n.Pos())
5343 return s.newValue1I(ssa.OpOffPtr, t, n.Offset(), p)
5345 n := n.(*ir.ConvExpr)
5346 if n.Type() == n.X.Type() {
5350 return s.newValue1(ssa.OpCopy, t, addr) // ensure that addr has the right type
5351 case ir.OCALLFUNC, ir.OCALLINTER:
5352 n := n.(*ir.CallExpr)
5353 return s.callAddr(n, callNormal)
5354 case ir.ODOTTYPE, ir.ODYNAMICDOTTYPE:
5356 if n.Op() == ir.ODOTTYPE {
5357 v, _ = s.dottype(n.(*ir.TypeAssertExpr), false)
5359 v, _ = s.dynamicDottype(n.(*ir.DynamicTypeAssertExpr), false)
5361 if v.Op != ssa.OpLoad {
5362 s.Fatalf("dottype of non-load")
5364 if v.Args[1] != s.mem() {
5365 s.Fatalf("memory no longer live from dottype load")
5369 s.Fatalf("unhandled addr %v", n.Op())
5374 // canSSA reports whether n is SSA-able.
5375 // n must be an ONAME (or an ODOT sequence with an ONAME base).
5376 func (s *state) canSSA(n ir.Node) bool {
5377 if base.Flag.N != 0 {
5382 if nn.Op() == ir.ODOT {
5383 nn := nn.(*ir.SelectorExpr)
5387 if nn.Op() == ir.OINDEX {
5388 nn := nn.(*ir.IndexExpr)
5389 if nn.X.Type().IsArray() {
5396 if n.Op() != ir.ONAME {
5399 return s.canSSAName(n.(*ir.Name)) && TypeOK(n.Type())
5402 func (s *state) canSSAName(name *ir.Name) bool {
5403 if name.Addrtaken() || !name.OnStack() {
5409 // TODO: handle this case? Named return values must be
5410 // in memory so that the deferred function can see them.
5411 // Maybe do: if !strings.HasPrefix(n.String(), "~") { return false }
5412 // Or maybe not, see issue 18860. Even unnamed return values
5413 // must be written back so if a defer recovers, the caller can see them.
5416 if s.cgoUnsafeArgs {
5417 // Cgo effectively takes the address of all result args,
5418 // but the compiler can't see that.
5423 // TODO: try to make more variables SSAable?
5426 // TypeOK reports whether variables of type t are SSA-able.
5427 func TypeOK(t *types.Type) bool {
5429 if t.Size() > int64(4*types.PtrSize) {
5430 // 4*Widthptr is an arbitrary constant. We want it
5431 // to be at least 3*Widthptr so slices can be registerized.
5432 // Too big and we'll introduce too much register pressure.
5437 // We can't do larger arrays because dynamic indexing is
5438 // not supported on SSA variables.
5439 // TODO: allow if all indexes are constant.
5440 if t.NumElem() <= 1 {
5441 return TypeOK(t.Elem())
5445 if t.NumFields() > ssa.MaxStruct {
5448 for _, t1 := range t.Fields().Slice() {
5449 if !TypeOK(t1.Type) {
5459 // exprPtr evaluates n to a pointer and nil-checks it.
5460 func (s *state) exprPtr(n ir.Node, bounded bool, lineno src.XPos) *ssa.Value {
5462 if bounded || n.NonNil() {
5463 if s.f.Frontend().Debug_checknil() && lineno.Line() > 1 {
5464 s.f.Warnl(lineno, "removed nil check")
5472 // nilCheck generates nil pointer checking code.
5473 // Used only for automatically inserted nil checks,
5474 // not for user code like 'x != nil'.
5475 func (s *state) nilCheck(ptr *ssa.Value) {
5476 if base.Debug.DisableNil != 0 || s.curfn.NilCheckDisabled() {
5479 s.newValue2(ssa.OpNilCheck, types.TypeVoid, ptr, s.mem())
5482 // boundsCheck generates bounds checking code. Checks if 0 <= idx <[=] len, branches to exit if not.
5483 // Starts a new block on return.
5484 // On input, len must be converted to full int width and be nonnegative.
5485 // Returns idx converted to full int width.
5486 // If bounded is true then caller guarantees the index is not out of bounds
5487 // (but boundsCheck will still extend the index to full int width).
5488 func (s *state) boundsCheck(idx, len *ssa.Value, kind ssa.BoundsKind, bounded bool) *ssa.Value {
5489 idx = s.extendIndex(idx, len, kind, bounded)
5491 if bounded || base.Flag.B != 0 {
5492 // If bounded or bounds checking is flag-disabled, then no check necessary,
5493 // just return the extended index.
5495 // Here, bounded == true if the compiler generated the index itself,
5496 // such as in the expansion of a slice initializer. These indexes are
5497 // compiler-generated, not Go program variables, so they cannot be
5498 // attacker-controlled, so we can omit Spectre masking as well.
5500 // Note that we do not want to omit Spectre masking in code like:
5502 // if 0 <= i && i < len(x) {
5506 // Lucky for us, bounded==false for that code.
5507 // In that case (handled below), we emit a bound check (and Spectre mask)
5508 // and then the prove pass will remove the bounds check.
5509 // In theory the prove pass could potentially remove certain
5510 // Spectre masks, but it's very delicate and probably better
5511 // to be conservative and leave them all in.
5515 bNext := s.f.NewBlock(ssa.BlockPlain)
5516 bPanic := s.f.NewBlock(ssa.BlockExit)
5518 if !idx.Type.IsSigned() {
5520 case ssa.BoundsIndex:
5521 kind = ssa.BoundsIndexU
5522 case ssa.BoundsSliceAlen:
5523 kind = ssa.BoundsSliceAlenU
5524 case ssa.BoundsSliceAcap:
5525 kind = ssa.BoundsSliceAcapU
5526 case ssa.BoundsSliceB:
5527 kind = ssa.BoundsSliceBU
5528 case ssa.BoundsSlice3Alen:
5529 kind = ssa.BoundsSlice3AlenU
5530 case ssa.BoundsSlice3Acap:
5531 kind = ssa.BoundsSlice3AcapU
5532 case ssa.BoundsSlice3B:
5533 kind = ssa.BoundsSlice3BU
5534 case ssa.BoundsSlice3C:
5535 kind = ssa.BoundsSlice3CU
5540 if kind == ssa.BoundsIndex || kind == ssa.BoundsIndexU {
5541 cmp = s.newValue2(ssa.OpIsInBounds, types.Types[types.TBOOL], idx, len)
5543 cmp = s.newValue2(ssa.OpIsSliceInBounds, types.Types[types.TBOOL], idx, len)
5546 b.Kind = ssa.BlockIf
5548 b.Likely = ssa.BranchLikely
5552 s.startBlock(bPanic)
5553 if Arch.LinkArch.Family == sys.Wasm {
5554 // TODO(khr): figure out how to do "register" based calling convention for bounds checks.
5555 // Should be similar to gcWriteBarrier, but I can't make it work.
5556 s.rtcall(BoundsCheckFunc[kind], false, nil, idx, len)
5558 mem := s.newValue3I(ssa.OpPanicBounds, types.TypeMem, int64(kind), idx, len, s.mem())
5559 s.endBlock().SetControl(mem)
5563 // In Spectre index mode, apply an appropriate mask to avoid speculative out-of-bounds accesses.
5564 if base.Flag.Cfg.SpectreIndex {
5565 op := ssa.OpSpectreIndex
5566 if kind != ssa.BoundsIndex && kind != ssa.BoundsIndexU {
5567 op = ssa.OpSpectreSliceIndex
5569 idx = s.newValue2(op, types.Types[types.TINT], idx, len)
5575 // If cmp (a bool) is false, panic using the given function.
5576 func (s *state) check(cmp *ssa.Value, fn *obj.LSym) {
5578 b.Kind = ssa.BlockIf
5580 b.Likely = ssa.BranchLikely
5581 bNext := s.f.NewBlock(ssa.BlockPlain)
5583 pos := base.Ctxt.PosTable.Pos(line)
5584 fl := funcLine{f: fn, base: pos.Base(), line: pos.Line()}
5585 bPanic := s.panics[fl]
5587 bPanic = s.f.NewBlock(ssa.BlockPlain)
5588 s.panics[fl] = bPanic
5589 s.startBlock(bPanic)
5590 // The panic call takes/returns memory to ensure that the right
5591 // memory state is observed if the panic happens.
5592 s.rtcall(fn, false, nil)
5599 func (s *state) intDivide(n ir.Node, a, b *ssa.Value) *ssa.Value {
5602 case ssa.OpConst8, ssa.OpConst16, ssa.OpConst32, ssa.OpConst64:
5608 // do a size-appropriate check for zero
5609 cmp := s.newValue2(s.ssaOp(ir.ONE, n.Type()), types.Types[types.TBOOL], b, s.zeroVal(n.Type()))
5610 s.check(cmp, ir.Syms.Panicdivide)
5612 return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
5615 // rtcall issues a call to the given runtime function fn with the listed args.
5616 // Returns a slice of results of the given result types.
5617 // The call is added to the end of the current block.
5618 // If returns is false, the block is marked as an exit block.
5619 func (s *state) rtcall(fn *obj.LSym, returns bool, results []*types.Type, args ...*ssa.Value) []*ssa.Value {
5621 // Write args to the stack
5622 off := base.Ctxt.Arch.FixedFrameSize
5623 var callArgs []*ssa.Value
5624 var callArgTypes []*types.Type
5626 for _, arg := range args {
5628 off = types.Rnd(off, t.Alignment())
5630 callArgs = append(callArgs, arg)
5631 callArgTypes = append(callArgTypes, t)
5634 off = types.Rnd(off, int64(types.RegSize))
5638 aux := ssa.StaticAuxCall(fn, s.f.ABIDefault.ABIAnalyzeTypes(nil, callArgTypes, results))
5639 callArgs = append(callArgs, s.mem())
5640 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5641 call.AddArgs(callArgs...)
5642 s.vars[memVar] = s.newValue1I(ssa.OpSelectN, types.TypeMem, int64(len(results)), call)
5647 b.Kind = ssa.BlockExit
5649 call.AuxInt = off - base.Ctxt.Arch.FixedFrameSize
5650 if len(results) > 0 {
5651 s.Fatalf("panic call can't have results")
5657 res := make([]*ssa.Value, len(results))
5658 for i, t := range results {
5659 off = types.Rnd(off, t.Alignment())
5660 res[i] = s.resultOfCall(call, int64(i), t)
5663 off = types.Rnd(off, int64(types.PtrSize))
5665 // Remember how much callee stack space we needed.
5671 // do *left = right for type t.
5672 func (s *state) storeType(t *types.Type, left, right *ssa.Value, skip skipMask, leftIsStmt bool) {
5673 s.instrument(t, left, instrumentWrite)
5675 if skip == 0 && (!t.HasPointers() || ssa.IsStackAddr(left)) {
5676 // Known to not have write barrier. Store the whole type.
5677 s.vars[memVar] = s.newValue3Apos(ssa.OpStore, types.TypeMem, t, left, right, s.mem(), leftIsStmt)
5681 // store scalar fields first, so write barrier stores for
5682 // pointer fields can be grouped together, and scalar values
5683 // don't need to be live across the write barrier call.
5684 // TODO: if the writebarrier pass knows how to reorder stores,
5685 // we can do a single store here as long as skip==0.
5686 s.storeTypeScalars(t, left, right, skip)
5687 if skip&skipPtr == 0 && t.HasPointers() {
5688 s.storeTypePtrs(t, left, right)
5692 // do *left = right for all scalar (non-pointer) parts of t.
5693 func (s *state) storeTypeScalars(t *types.Type, left, right *ssa.Value, skip skipMask) {
5695 case t.IsBoolean() || t.IsInteger() || t.IsFloat() || t.IsComplex():
5696 s.store(t, left, right)
5697 case t.IsPtrShaped():
5698 if t.IsPtr() && t.Elem().NotInHeap() {
5699 s.store(t, left, right) // see issue 42032
5701 // otherwise, no scalar fields.
5703 if skip&skipLen != 0 {
5706 len := s.newValue1(ssa.OpStringLen, types.Types[types.TINT], right)
5707 lenAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, s.config.PtrSize, left)
5708 s.store(types.Types[types.TINT], lenAddr, len)
5710 if skip&skipLen == 0 {
5711 len := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], right)
5712 lenAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, s.config.PtrSize, left)
5713 s.store(types.Types[types.TINT], lenAddr, len)
5715 if skip&skipCap == 0 {
5716 cap := s.newValue1(ssa.OpSliceCap, types.Types[types.TINT], right)
5717 capAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, 2*s.config.PtrSize, left)
5718 s.store(types.Types[types.TINT], capAddr, cap)
5720 case t.IsInterface():
5721 // itab field doesn't need a write barrier (even though it is a pointer).
5722 itab := s.newValue1(ssa.OpITab, s.f.Config.Types.BytePtr, right)
5723 s.store(types.Types[types.TUINTPTR], left, itab)
5726 for i := 0; i < n; i++ {
5727 ft := t.FieldType(i)
5728 addr := s.newValue1I(ssa.OpOffPtr, ft.PtrTo(), t.FieldOff(i), left)
5729 val := s.newValue1I(ssa.OpStructSelect, ft, int64(i), right)
5730 s.storeTypeScalars(ft, addr, val, 0)
5732 case t.IsArray() && t.NumElem() == 0:
5734 case t.IsArray() && t.NumElem() == 1:
5735 s.storeTypeScalars(t.Elem(), left, s.newValue1I(ssa.OpArraySelect, t.Elem(), 0, right), 0)
5737 s.Fatalf("bad write barrier type %v", t)
5741 // do *left = right for all pointer parts of t.
5742 func (s *state) storeTypePtrs(t *types.Type, left, right *ssa.Value) {
5744 case t.IsPtrShaped():
5745 if t.IsPtr() && t.Elem().NotInHeap() {
5746 break // see issue 42032
5748 s.store(t, left, right)
5750 ptr := s.newValue1(ssa.OpStringPtr, s.f.Config.Types.BytePtr, right)
5751 s.store(s.f.Config.Types.BytePtr, left, ptr)
5753 elType := types.NewPtr(t.Elem())
5754 ptr := s.newValue1(ssa.OpSlicePtr, elType, right)
5755 s.store(elType, left, ptr)
5756 case t.IsInterface():
5757 // itab field is treated as a scalar.
5758 idata := s.newValue1(ssa.OpIData, s.f.Config.Types.BytePtr, right)
5759 idataAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.BytePtrPtr, s.config.PtrSize, left)
5760 s.store(s.f.Config.Types.BytePtr, idataAddr, idata)
5763 for i := 0; i < n; i++ {
5764 ft := t.FieldType(i)
5765 if !ft.HasPointers() {
5768 addr := s.newValue1I(ssa.OpOffPtr, ft.PtrTo(), t.FieldOff(i), left)
5769 val := s.newValue1I(ssa.OpStructSelect, ft, int64(i), right)
5770 s.storeTypePtrs(ft, addr, val)
5772 case t.IsArray() && t.NumElem() == 0:
5774 case t.IsArray() && t.NumElem() == 1:
5775 s.storeTypePtrs(t.Elem(), left, s.newValue1I(ssa.OpArraySelect, t.Elem(), 0, right))
5777 s.Fatalf("bad write barrier type %v", t)
5781 // putArg evaluates n for the purpose of passing it as an argument to a function and returns the value for the call.
5782 func (s *state) putArg(n ir.Node, t *types.Type) *ssa.Value {
5785 a = s.newValue2(ssa.OpDereference, t, s.addr(n), s.mem())
5792 func (s *state) storeArgWithBase(n ir.Node, t *types.Type, base *ssa.Value, off int64) {
5793 pt := types.NewPtr(t)
5796 // Use special routine that avoids allocation on duplicate offsets.
5797 addr = s.constOffPtrSP(pt, off)
5799 addr = s.newValue1I(ssa.OpOffPtr, pt, off, base)
5809 s.storeType(t, addr, a, 0, false)
5812 // slice computes the slice v[i:j:k] and returns ptr, len, and cap of result.
5813 // i,j,k may be nil, in which case they are set to their default value.
5814 // v may be a slice, string or pointer to an array.
5815 func (s *state) slice(v, i, j, k *ssa.Value, bounded bool) (p, l, c *ssa.Value) {
5817 var ptr, len, cap *ssa.Value
5820 ptr = s.newValue1(ssa.OpSlicePtr, types.NewPtr(t.Elem()), v)
5821 len = s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], v)
5822 cap = s.newValue1(ssa.OpSliceCap, types.Types[types.TINT], v)
5824 ptr = s.newValue1(ssa.OpStringPtr, types.NewPtr(types.Types[types.TUINT8]), v)
5825 len = s.newValue1(ssa.OpStringLen, types.Types[types.TINT], v)
5828 if !t.Elem().IsArray() {
5829 s.Fatalf("bad ptr to array in slice %v\n", t)
5832 ptr = s.newValue1(ssa.OpCopy, types.NewPtr(t.Elem().Elem()), v)
5833 len = s.constInt(types.Types[types.TINT], t.Elem().NumElem())
5836 s.Fatalf("bad type in slice %v\n", t)
5839 // Set default values
5841 i = s.constInt(types.Types[types.TINT], 0)
5852 // Panic if slice indices are not in bounds.
5853 // Make sure we check these in reverse order so that we're always
5854 // comparing against a value known to be nonnegative. See issue 28797.
5857 kind := ssa.BoundsSlice3Alen
5859 kind = ssa.BoundsSlice3Acap
5861 k = s.boundsCheck(k, cap, kind, bounded)
5864 j = s.boundsCheck(j, k, ssa.BoundsSlice3B, bounded)
5866 i = s.boundsCheck(i, j, ssa.BoundsSlice3C, bounded)
5869 kind := ssa.BoundsSliceAlen
5871 kind = ssa.BoundsSliceAcap
5873 j = s.boundsCheck(j, k, kind, bounded)
5875 i = s.boundsCheck(i, j, ssa.BoundsSliceB, bounded)
5878 // Word-sized integer operations.
5879 subOp := s.ssaOp(ir.OSUB, types.Types[types.TINT])
5880 mulOp := s.ssaOp(ir.OMUL, types.Types[types.TINT])
5881 andOp := s.ssaOp(ir.OAND, types.Types[types.TINT])
5883 // Calculate the length (rlen) and capacity (rcap) of the new slice.
5884 // For strings the capacity of the result is unimportant. However,
5885 // we use rcap to test if we've generated a zero-length slice.
5886 // Use length of strings for that.
5887 rlen := s.newValue2(subOp, types.Types[types.TINT], j, i)
5889 if j != k && !t.IsString() {
5890 rcap = s.newValue2(subOp, types.Types[types.TINT], k, i)
5893 if (i.Op == ssa.OpConst64 || i.Op == ssa.OpConst32) && i.AuxInt == 0 {
5894 // No pointer arithmetic necessary.
5895 return ptr, rlen, rcap
5898 // Calculate the base pointer (rptr) for the new slice.
5900 // Generate the following code assuming that indexes are in bounds.
5901 // The masking is to make sure that we don't generate a slice
5902 // that points to the next object in memory. We cannot just set
5903 // the pointer to nil because then we would create a nil slice or
5908 // rptr = ptr + (mask(rcap) & (i * stride))
5910 // Where mask(x) is 0 if x==0 and -1 if x>0 and stride is the width
5911 // of the element type.
5912 stride := s.constInt(types.Types[types.TINT], ptr.Type.Elem().Size())
5914 // The delta is the number of bytes to offset ptr by.
5915 delta := s.newValue2(mulOp, types.Types[types.TINT], i, stride)
5917 // If we're slicing to the point where the capacity is zero,
5918 // zero out the delta.
5919 mask := s.newValue1(ssa.OpSlicemask, types.Types[types.TINT], rcap)
5920 delta = s.newValue2(andOp, types.Types[types.TINT], delta, mask)
5922 // Compute rptr = ptr + delta.
5923 rptr := s.newValue2(ssa.OpAddPtr, ptr.Type, ptr, delta)
5925 return rptr, rlen, rcap
5928 type u642fcvtTab struct {
5929 leq, cvt2F, and, rsh, or, add ssa.Op
5930 one func(*state, *types.Type, int64) *ssa.Value
5933 var u64_f64 = u642fcvtTab{
5935 cvt2F: ssa.OpCvt64to64F,
5937 rsh: ssa.OpRsh64Ux64,
5940 one: (*state).constInt64,
5943 var u64_f32 = u642fcvtTab{
5945 cvt2F: ssa.OpCvt64to32F,
5947 rsh: ssa.OpRsh64Ux64,
5950 one: (*state).constInt64,
5953 func (s *state) uint64Tofloat64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
5954 return s.uint64Tofloat(&u64_f64, n, x, ft, tt)
5957 func (s *state) uint64Tofloat32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
5958 return s.uint64Tofloat(&u64_f32, n, x, ft, tt)
5961 func (s *state) uint64Tofloat(cvttab *u642fcvtTab, n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
5963 // result = (floatY) x
5965 // y = uintX(x) ; y = x & 1
5966 // z = uintX(x) ; z = z >> 1
5968 // result = floatY(z)
5969 // result = result + result
5972 // Code borrowed from old code generator.
5973 // What's going on: large 64-bit "unsigned" looks like
5974 // negative number to hardware's integer-to-float
5975 // conversion. However, because the mantissa is only
5976 // 63 bits, we don't need the LSB, so instead we do an
5977 // unsigned right shift (divide by two), convert, and
5978 // double. However, before we do that, we need to be
5979 // sure that we do not lose a "1" if that made the
5980 // difference in the resulting rounding. Therefore, we
5981 // preserve it, and OR (not ADD) it back in. The case
5982 // that matters is when the eleven discarded bits are
5983 // equal to 10000000001; that rounds up, and the 1 cannot
5984 // be lost else it would round down if the LSB of the
5985 // candidate mantissa is 0.
5986 cmp := s.newValue2(cvttab.leq, types.Types[types.TBOOL], s.zeroVal(ft), x)
5988 b.Kind = ssa.BlockIf
5990 b.Likely = ssa.BranchLikely
5992 bThen := s.f.NewBlock(ssa.BlockPlain)
5993 bElse := s.f.NewBlock(ssa.BlockPlain)
5994 bAfter := s.f.NewBlock(ssa.BlockPlain)
5998 a0 := s.newValue1(cvttab.cvt2F, tt, x)
6001 bThen.AddEdgeTo(bAfter)
6005 one := cvttab.one(s, ft, 1)
6006 y := s.newValue2(cvttab.and, ft, x, one)
6007 z := s.newValue2(cvttab.rsh, ft, x, one)
6008 z = s.newValue2(cvttab.or, ft, z, y)
6009 a := s.newValue1(cvttab.cvt2F, tt, z)
6010 a1 := s.newValue2(cvttab.add, tt, a, a)
6013 bElse.AddEdgeTo(bAfter)
6015 s.startBlock(bAfter)
6016 return s.variable(n, n.Type())
6019 type u322fcvtTab struct {
6020 cvtI2F, cvtF2F ssa.Op
6023 var u32_f64 = u322fcvtTab{
6024 cvtI2F: ssa.OpCvt32to64F,
6028 var u32_f32 = u322fcvtTab{
6029 cvtI2F: ssa.OpCvt32to32F,
6030 cvtF2F: ssa.OpCvt64Fto32F,
6033 func (s *state) uint32Tofloat64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6034 return s.uint32Tofloat(&u32_f64, n, x, ft, tt)
6037 func (s *state) uint32Tofloat32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6038 return s.uint32Tofloat(&u32_f32, n, x, ft, tt)
6041 func (s *state) uint32Tofloat(cvttab *u322fcvtTab, n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6043 // result = floatY(x)
6045 // result = floatY(float64(x) + (1<<32))
6047 cmp := s.newValue2(ssa.OpLeq32, types.Types[types.TBOOL], s.zeroVal(ft), x)
6049 b.Kind = ssa.BlockIf
6051 b.Likely = ssa.BranchLikely
6053 bThen := s.f.NewBlock(ssa.BlockPlain)
6054 bElse := s.f.NewBlock(ssa.BlockPlain)
6055 bAfter := s.f.NewBlock(ssa.BlockPlain)
6059 a0 := s.newValue1(cvttab.cvtI2F, tt, x)
6062 bThen.AddEdgeTo(bAfter)
6066 a1 := s.newValue1(ssa.OpCvt32to64F, types.Types[types.TFLOAT64], x)
6067 twoToThe32 := s.constFloat64(types.Types[types.TFLOAT64], float64(1<<32))
6068 a2 := s.newValue2(ssa.OpAdd64F, types.Types[types.TFLOAT64], a1, twoToThe32)
6069 a3 := s.newValue1(cvttab.cvtF2F, tt, a2)
6073 bElse.AddEdgeTo(bAfter)
6075 s.startBlock(bAfter)
6076 return s.variable(n, n.Type())
6079 // referenceTypeBuiltin generates code for the len/cap builtins for maps and channels.
6080 func (s *state) referenceTypeBuiltin(n *ir.UnaryExpr, x *ssa.Value) *ssa.Value {
6081 if !n.X.Type().IsMap() && !n.X.Type().IsChan() {
6082 s.Fatalf("node must be a map or a channel")
6088 // return *((*int)n)
6090 // return *(((*int)n)+1)
6093 nilValue := s.constNil(types.Types[types.TUINTPTR])
6094 cmp := s.newValue2(ssa.OpEqPtr, types.Types[types.TBOOL], x, nilValue)
6096 b.Kind = ssa.BlockIf
6098 b.Likely = ssa.BranchUnlikely
6100 bThen := s.f.NewBlock(ssa.BlockPlain)
6101 bElse := s.f.NewBlock(ssa.BlockPlain)
6102 bAfter := s.f.NewBlock(ssa.BlockPlain)
6104 // length/capacity of a nil map/chan is zero
6107 s.vars[n] = s.zeroVal(lenType)
6109 bThen.AddEdgeTo(bAfter)
6115 // length is stored in the first word for map/chan
6116 s.vars[n] = s.load(lenType, x)
6118 // capacity is stored in the second word for chan
6119 sw := s.newValue1I(ssa.OpOffPtr, lenType.PtrTo(), lenType.Size(), x)
6120 s.vars[n] = s.load(lenType, sw)
6122 s.Fatalf("op must be OLEN or OCAP")
6125 bElse.AddEdgeTo(bAfter)
6127 s.startBlock(bAfter)
6128 return s.variable(n, lenType)
6131 type f2uCvtTab struct {
6132 ltf, cvt2U, subf, or ssa.Op
6133 floatValue func(*state, *types.Type, float64) *ssa.Value
6134 intValue func(*state, *types.Type, int64) *ssa.Value
6138 var f32_u64 = f2uCvtTab{
6140 cvt2U: ssa.OpCvt32Fto64,
6143 floatValue: (*state).constFloat32,
6144 intValue: (*state).constInt64,
6148 var f64_u64 = f2uCvtTab{
6150 cvt2U: ssa.OpCvt64Fto64,
6153 floatValue: (*state).constFloat64,
6154 intValue: (*state).constInt64,
6158 var f32_u32 = f2uCvtTab{
6160 cvt2U: ssa.OpCvt32Fto32,
6163 floatValue: (*state).constFloat32,
6164 intValue: func(s *state, t *types.Type, v int64) *ssa.Value { return s.constInt32(t, int32(v)) },
6168 var f64_u32 = f2uCvtTab{
6170 cvt2U: ssa.OpCvt64Fto32,
6173 floatValue: (*state).constFloat64,
6174 intValue: func(s *state, t *types.Type, v int64) *ssa.Value { return s.constInt32(t, int32(v)) },
6178 func (s *state) float32ToUint64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6179 return s.floatToUint(&f32_u64, n, x, ft, tt)
6181 func (s *state) float64ToUint64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6182 return s.floatToUint(&f64_u64, n, x, ft, tt)
6185 func (s *state) float32ToUint32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6186 return s.floatToUint(&f32_u32, n, x, ft, tt)
6189 func (s *state) float64ToUint32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6190 return s.floatToUint(&f64_u32, n, x, ft, tt)
6193 func (s *state) floatToUint(cvttab *f2uCvtTab, n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6194 // cutoff:=1<<(intY_Size-1)
6195 // if x < floatX(cutoff) {
6196 // result = uintY(x)
6198 // y = x - floatX(cutoff)
6200 // result = z | -(cutoff)
6202 cutoff := cvttab.floatValue(s, ft, float64(cvttab.cutoff))
6203 cmp := s.newValue2(cvttab.ltf, types.Types[types.TBOOL], x, cutoff)
6205 b.Kind = ssa.BlockIf
6207 b.Likely = ssa.BranchLikely
6209 bThen := s.f.NewBlock(ssa.BlockPlain)
6210 bElse := s.f.NewBlock(ssa.BlockPlain)
6211 bAfter := s.f.NewBlock(ssa.BlockPlain)
6215 a0 := s.newValue1(cvttab.cvt2U, tt, x)
6218 bThen.AddEdgeTo(bAfter)
6222 y := s.newValue2(cvttab.subf, ft, x, cutoff)
6223 y = s.newValue1(cvttab.cvt2U, tt, y)
6224 z := cvttab.intValue(s, tt, int64(-cvttab.cutoff))
6225 a1 := s.newValue2(cvttab.or, tt, y, z)
6228 bElse.AddEdgeTo(bAfter)
6230 s.startBlock(bAfter)
6231 return s.variable(n, n.Type())
6234 // dottype generates SSA for a type assertion node.
6235 // commaok indicates whether to panic or return a bool.
6236 // If commaok is false, resok will be nil.
6237 func (s *state) dottype(n *ir.TypeAssertExpr, commaok bool) (res, resok *ssa.Value) {
6238 iface := s.expr(n.X) // input interface
6239 target := s.reflectType(n.Type()) // target type
6240 var targetItab *ssa.Value
6242 targetItab = s.expr(n.ITab)
6244 return s.dottype1(n.Pos(), n.X.Type(), n.Type(), iface, nil, target, targetItab, commaok)
6247 func (s *state) dynamicDottype(n *ir.DynamicTypeAssertExpr, commaok bool) (res, resok *ssa.Value) {
6248 iface := s.expr(n.X)
6249 var source, target, targetItab *ssa.Value
6250 if n.SrcRType != nil {
6251 source = s.expr(n.SrcRType)
6253 if !n.X.Type().IsEmptyInterface() && !n.Type().IsInterface() {
6254 byteptr := s.f.Config.Types.BytePtr
6255 targetItab = s.expr(n.ITab)
6256 // TODO(mdempsky): Investigate whether compiling n.RType could be
6257 // better than loading itab.typ.
6258 target = s.load(byteptr, s.newValue1I(ssa.OpOffPtr, byteptr, int64(types.PtrSize), targetItab)) // itab.typ
6260 target = s.expr(n.RType)
6262 return s.dottype1(n.Pos(), n.X.Type(), n.Type(), iface, source, target, targetItab, commaok)
6265 // dottype1 implements a x.(T) operation. iface is the argument (x), dst is the type we're asserting to (T)
6266 // and src is the type we're asserting from.
6267 // source is the *runtime._type of src
6268 // target is the *runtime._type of dst.
6269 // If src is a nonempty interface and dst is not an interface, targetItab is an itab representing (dst, src). Otherwise it is nil.
6270 // commaok is true if the caller wants a boolean success value. Otherwise, the generated code panics if the conversion fails.
6271 func (s *state) dottype1(pos src.XPos, src, dst *types.Type, iface, source, target, targetItab *ssa.Value, commaok bool) (res, resok *ssa.Value) {
6272 byteptr := s.f.Config.Types.BytePtr
6273 if dst.IsInterface() {
6274 if dst.IsEmptyInterface() {
6275 // Converting to an empty interface.
6276 // Input could be an empty or nonempty interface.
6277 if base.Debug.TypeAssert > 0 {
6278 base.WarnfAt(pos, "type assertion inlined")
6281 // Get itab/type field from input.
6282 itab := s.newValue1(ssa.OpITab, byteptr, iface)
6283 // Conversion succeeds iff that field is not nil.
6284 cond := s.newValue2(ssa.OpNeqPtr, types.Types[types.TBOOL], itab, s.constNil(byteptr))
6286 if src.IsEmptyInterface() && commaok {
6287 // Converting empty interface to empty interface with ,ok is just a nil check.
6291 // Branch on nilness.
6293 b.Kind = ssa.BlockIf
6295 b.Likely = ssa.BranchLikely
6296 bOk := s.f.NewBlock(ssa.BlockPlain)
6297 bFail := s.f.NewBlock(ssa.BlockPlain)
6302 // On failure, panic by calling panicnildottype.
6304 s.rtcall(ir.Syms.Panicnildottype, false, nil, target)
6306 // On success, return (perhaps modified) input interface.
6308 if src.IsEmptyInterface() {
6309 res = iface // Use input interface unchanged.
6312 // Load type out of itab, build interface with existing idata.
6313 off := s.newValue1I(ssa.OpOffPtr, byteptr, int64(types.PtrSize), itab)
6314 typ := s.load(byteptr, off)
6315 idata := s.newValue1(ssa.OpIData, byteptr, iface)
6316 res = s.newValue2(ssa.OpIMake, dst, typ, idata)
6321 // nonempty -> empty
6322 // Need to load type from itab
6323 off := s.newValue1I(ssa.OpOffPtr, byteptr, int64(types.PtrSize), itab)
6324 s.vars[typVar] = s.load(byteptr, off)
6327 // itab is nil, might as well use that as the nil result.
6329 s.vars[typVar] = itab
6333 bEnd := s.f.NewBlock(ssa.BlockPlain)
6335 bFail.AddEdgeTo(bEnd)
6337 idata := s.newValue1(ssa.OpIData, byteptr, iface)
6338 res = s.newValue2(ssa.OpIMake, dst, s.variable(typVar, byteptr), idata)
6340 delete(s.vars, typVar)
6343 // converting to a nonempty interface needs a runtime call.
6344 if base.Debug.TypeAssert > 0 {
6345 base.WarnfAt(pos, "type assertion not inlined")
6348 fn := ir.Syms.AssertI2I
6349 if src.IsEmptyInterface() {
6350 fn = ir.Syms.AssertE2I
6352 data := s.newValue1(ssa.OpIData, types.Types[types.TUNSAFEPTR], iface)
6353 tab := s.newValue1(ssa.OpITab, byteptr, iface)
6354 tab = s.rtcall(fn, true, []*types.Type{byteptr}, target, tab)[0]
6355 return s.newValue2(ssa.OpIMake, dst, tab, data), nil
6357 fn := ir.Syms.AssertI2I2
6358 if src.IsEmptyInterface() {
6359 fn = ir.Syms.AssertE2I2
6361 res = s.rtcall(fn, true, []*types.Type{dst}, target, iface)[0]
6362 resok = s.newValue2(ssa.OpNeqInter, types.Types[types.TBOOL], res, s.constInterface(dst))
6366 if base.Debug.TypeAssert > 0 {
6367 base.WarnfAt(pos, "type assertion inlined")
6370 // Converting to a concrete type.
6371 direct := types.IsDirectIface(dst)
6372 itab := s.newValue1(ssa.OpITab, byteptr, iface) // type word of interface
6373 if base.Debug.TypeAssert > 0 {
6374 base.WarnfAt(pos, "type assertion inlined")
6376 var wantedFirstWord *ssa.Value
6377 if src.IsEmptyInterface() {
6378 // Looking for pointer to target type.
6379 wantedFirstWord = target
6381 // Looking for pointer to itab for target type and source interface.
6382 wantedFirstWord = targetItab
6385 var tmp ir.Node // temporary for use with large types
6386 var addr *ssa.Value // address of tmp
6387 if commaok && !TypeOK(dst) {
6388 // unSSAable type, use temporary.
6389 // TODO: get rid of some of these temporaries.
6390 tmp, addr = s.temp(pos, dst)
6393 cond := s.newValue2(ssa.OpEqPtr, types.Types[types.TBOOL], itab, wantedFirstWord)
6395 b.Kind = ssa.BlockIf
6397 b.Likely = ssa.BranchLikely
6399 bOk := s.f.NewBlock(ssa.BlockPlain)
6400 bFail := s.f.NewBlock(ssa.BlockPlain)
6405 // on failure, panic by calling panicdottype
6409 taddr = s.reflectType(src)
6411 if src.IsEmptyInterface() {
6412 s.rtcall(ir.Syms.PanicdottypeE, false, nil, itab, target, taddr)
6414 s.rtcall(ir.Syms.PanicdottypeI, false, nil, itab, target, taddr)
6417 // on success, return data from interface
6420 return s.newValue1(ssa.OpIData, dst, iface), nil
6422 p := s.newValue1(ssa.OpIData, types.NewPtr(dst), iface)
6423 return s.load(dst, p), nil
6426 // commaok is the more complicated case because we have
6427 // a control flow merge point.
6428 bEnd := s.f.NewBlock(ssa.BlockPlain)
6429 // Note that we need a new valVar each time (unlike okVar where we can
6430 // reuse the variable) because it might have a different type every time.
6431 valVar := ssaMarker("val")
6433 // type assertion succeeded
6437 s.vars[valVar] = s.newValue1(ssa.OpIData, dst, iface)
6439 p := s.newValue1(ssa.OpIData, types.NewPtr(dst), iface)
6440 s.vars[valVar] = s.load(dst, p)
6443 p := s.newValue1(ssa.OpIData, types.NewPtr(dst), iface)
6444 s.move(dst, addr, p)
6446 s.vars[okVar] = s.constBool(true)
6450 // type assertion failed
6453 s.vars[valVar] = s.zeroVal(dst)
6457 s.vars[okVar] = s.constBool(false)
6459 bFail.AddEdgeTo(bEnd)
6464 res = s.variable(valVar, dst)
6465 delete(s.vars, valVar)
6467 res = s.load(dst, addr)
6468 s.vars[memVar] = s.newValue1A(ssa.OpVarKill, types.TypeMem, tmp.(*ir.Name), s.mem())
6470 resok = s.variable(okVar, types.Types[types.TBOOL])
6471 delete(s.vars, okVar)
6475 // temp allocates a temp of type t at position pos
6476 func (s *state) temp(pos src.XPos, t *types.Type) (*ir.Name, *ssa.Value) {
6477 tmp := typecheck.TempAt(pos, s.curfn, t)
6478 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, tmp, s.mem())
6483 // variable returns the value of a variable at the current location.
6484 func (s *state) variable(n ir.Node, t *types.Type) *ssa.Value {
6494 if s.curBlock == s.f.Entry {
6495 // No variable should be live at entry.
6496 s.Fatalf("Value live at entry. It shouldn't be. func %s, node %v, value %v", s.f.Name, n, v)
6498 // Make a FwdRef, which records a value that's live on block input.
6499 // We'll find the matching definition as part of insertPhis.
6500 v = s.newValue0A(ssa.OpFwdRef, t, fwdRefAux{N: n})
6502 if n.Op() == ir.ONAME {
6503 s.addNamedValue(n.(*ir.Name), v)
6508 func (s *state) mem() *ssa.Value {
6509 return s.variable(memVar, types.TypeMem)
6512 func (s *state) addNamedValue(n *ir.Name, v *ssa.Value) {
6513 if n.Class == ir.Pxxx {
6514 // Don't track our marker nodes (memVar etc.).
6517 if ir.IsAutoTmp(n) {
6518 // Don't track temporary variables.
6521 if n.Class == ir.PPARAMOUT {
6522 // Don't track named output values. This prevents return values
6523 // from being assigned too early. See #14591 and #14762. TODO: allow this.
6526 loc := ssa.LocalSlot{N: n, Type: n.Type(), Off: 0}
6527 values, ok := s.f.NamedValues[loc]
6529 s.f.Names = append(s.f.Names, &loc)
6530 s.f.CanonicalLocalSlots[loc] = &loc
6532 s.f.NamedValues[loc] = append(values, v)
6535 // Branch is an unresolved branch.
6536 type Branch struct {
6537 P *obj.Prog // branch instruction
6538 B *ssa.Block // target
6541 // State contains state needed during Prog generation.
6547 // Branches remembers all the branch instructions we've seen
6548 // and where they would like to go.
6551 // JumpTables remembers all the jump tables we've seen.
6552 JumpTables []*ssa.Block
6554 // bstart remembers where each block starts (indexed by block ID)
6557 maxarg int64 // largest frame size for arguments to calls made by the function
6559 // Map from GC safe points to liveness index, generated by
6560 // liveness analysis.
6561 livenessMap liveness.Map
6563 // partLiveArgs includes arguments that may be partially live, for which we
6564 // need to generate instructions that spill the argument registers.
6565 partLiveArgs map[*ir.Name]bool
6567 // lineRunStart records the beginning of the current run of instructions
6568 // within a single block sharing the same line number
6569 // Used to move statement marks to the beginning of such runs.
6570 lineRunStart *obj.Prog
6572 // wasm: The number of values on the WebAssembly stack. This is only used as a safeguard.
6573 OnWasmStackSkipped int
6576 func (s *State) FuncInfo() *obj.FuncInfo {
6577 return s.pp.CurFunc.LSym.Func()
6580 // Prog appends a new Prog.
6581 func (s *State) Prog(as obj.As) *obj.Prog {
6583 if objw.LosesStmtMark(as) {
6586 // Float a statement start to the beginning of any same-line run.
6587 // lineRunStart is reset at block boundaries, which appears to work well.
6588 if s.lineRunStart == nil || s.lineRunStart.Pos.Line() != p.Pos.Line() {
6590 } else if p.Pos.IsStmt() == src.PosIsStmt {
6591 s.lineRunStart.Pos = s.lineRunStart.Pos.WithIsStmt()
6592 p.Pos = p.Pos.WithNotStmt()
6597 // Pc returns the current Prog.
6598 func (s *State) Pc() *obj.Prog {
6602 // SetPos sets the current source position.
6603 func (s *State) SetPos(pos src.XPos) {
6607 // Br emits a single branch instruction and returns the instruction.
6608 // Not all architectures need the returned instruction, but otherwise
6609 // the boilerplate is common to all.
6610 func (s *State) Br(op obj.As, target *ssa.Block) *obj.Prog {
6612 p.To.Type = obj.TYPE_BRANCH
6613 s.Branches = append(s.Branches, Branch{P: p, B: target})
6617 // DebugFriendlySetPosFrom adjusts Pos.IsStmt subject to heuristics
6618 // that reduce "jumpy" line number churn when debugging.
6619 // Spill/fill/copy instructions from the register allocator,
6620 // phi functions, and instructions with a no-pos position
6621 // are examples of instructions that can cause churn.
6622 func (s *State) DebugFriendlySetPosFrom(v *ssa.Value) {
6624 case ssa.OpPhi, ssa.OpCopy, ssa.OpLoadReg, ssa.OpStoreReg:
6625 // These are not statements
6626 s.SetPos(v.Pos.WithNotStmt())
6629 if p != src.NoXPos {
6630 // If the position is defined, update the position.
6631 // Also convert default IsStmt to NotStmt; only
6632 // explicit statement boundaries should appear
6633 // in the generated code.
6634 if p.IsStmt() != src.PosIsStmt {
6635 if s.pp.Pos.IsStmt() == src.PosIsStmt && s.pp.Pos.SameFileAndLine(p) {
6636 // If s.pp.Pos already has a statement mark, then it was set here (below) for
6637 // the previous value. If an actual instruction had been emitted for that
6638 // value, then the statement mark would have been reset. Since the statement
6639 // mark of s.pp.Pos was not reset, this position (file/line) still needs a
6640 // statement mark on an instruction. If file and line for this value are
6641 // the same as the previous value, then the first instruction for this
6642 // value will work to take the statement mark. Return early to avoid
6643 // resetting the statement mark.
6645 // The reset of s.pp.Pos occurs in (*Progs).Prog() -- if it emits
6646 // an instruction, and the instruction's statement mark was set,
6647 // and it is not one of the LosesStmtMark instructions,
6648 // then Prog() resets the statement mark on the (*Progs).Pos.
6652 // Calls use the pos attached to v, but copy the statement mark from State
6656 s.SetPos(s.pp.Pos.WithNotStmt())
6661 // emit argument info (locations on stack) for traceback.
6662 func emitArgInfo(e *ssafn, f *ssa.Func, pp *objw.Progs) {
6663 ft := e.curfn.Type()
6664 if ft.NumRecvs() == 0 && ft.NumParams() == 0 {
6668 x := EmitArgInfo(e.curfn, f.OwnAux.ABIInfo())
6669 x.Set(obj.AttrContentAddressable, true)
6670 e.curfn.LSym.Func().ArgInfo = x
6672 // Emit a funcdata pointing at the arg info data.
6673 p := pp.Prog(obj.AFUNCDATA)
6674 p.From.SetConst(objabi.FUNCDATA_ArgInfo)
6675 p.To.Type = obj.TYPE_MEM
6676 p.To.Name = obj.NAME_EXTERN
6680 // emit argument info (locations on stack) of f for traceback.
6681 func EmitArgInfo(f *ir.Func, abiInfo *abi.ABIParamResultInfo) *obj.LSym {
6682 x := base.Ctxt.Lookup(fmt.Sprintf("%s.arginfo%d", f.LSym.Name, f.ABI))
6683 // NOTE: do not set ContentAddressable here. This may be referenced from
6684 // assembly code by name (in this case f is a declaration).
6685 // Instead, set it in emitArgInfo above.
6687 PtrSize := int64(types.PtrSize)
6688 uintptrTyp := types.Types[types.TUINTPTR]
6690 isAggregate := func(t *types.Type) bool {
6691 return t.IsStruct() || t.IsArray() || t.IsComplex() || t.IsInterface() || t.IsString() || t.IsSlice()
6694 // Populate the data.
6695 // The data is a stream of bytes, which contains the offsets and sizes of the
6696 // non-aggregate arguments or non-aggregate fields/elements of aggregate-typed
6697 // arguments, along with special "operators". Specifically,
6698 // - for each non-aggrgate arg/field/element, its offset from FP (1 byte) and
6700 // - special operators:
6701 // - 0xff - end of sequence
6702 // - 0xfe - print { (at the start of an aggregate-typed argument)
6703 // - 0xfd - print } (at the end of an aggregate-typed argument)
6704 // - 0xfc - print ... (more args/fields/elements)
6705 // - 0xfb - print _ (offset too large)
6706 // These constants need to be in sync with runtime.traceback.go:printArgs.
6712 _offsetTooLarge = 0xfb
6713 _special = 0xf0 // above this are operators, below this are ordinary offsets
6717 limit = 10 // print no more than 10 args/components
6718 maxDepth = 5 // no more than 5 layers of nesting
6720 // maxLen is a (conservative) upper bound of the byte stream length. For
6721 // each arg/component, it has no more than 2 bytes of data (size, offset),
6722 // and no more than one {, }, ... at each level (it cannot have both the
6723 // data and ... unless it is the last one, just be conservative). Plus 1
6725 maxLen = (maxDepth*3+2)*limit + 1
6730 writebyte := func(o uint8) { wOff = objw.Uint8(x, wOff, o) }
6732 // Write one non-aggrgate arg/field/element.
6733 write1 := func(sz, offset int64) {
6734 if offset >= _special {
6735 writebyte(_offsetTooLarge)
6737 writebyte(uint8(offset))
6738 writebyte(uint8(sz))
6743 // Visit t recursively and write it out.
6744 // Returns whether to continue visiting.
6745 var visitType func(baseOffset int64, t *types.Type, depth int) bool
6746 visitType = func(baseOffset int64, t *types.Type, depth int) bool {
6748 writebyte(_dotdotdot)
6751 if !isAggregate(t) {
6752 write1(t.Size(), baseOffset)
6755 writebyte(_startAgg)
6757 if depth >= maxDepth {
6758 writebyte(_dotdotdot)
6764 case t.IsInterface(), t.IsString():
6765 _ = visitType(baseOffset, uintptrTyp, depth) &&
6766 visitType(baseOffset+PtrSize, uintptrTyp, depth)
6768 _ = visitType(baseOffset, uintptrTyp, depth) &&
6769 visitType(baseOffset+PtrSize, uintptrTyp, depth) &&
6770 visitType(baseOffset+PtrSize*2, uintptrTyp, depth)
6772 _ = visitType(baseOffset, types.FloatForComplex(t), depth) &&
6773 visitType(baseOffset+t.Size()/2, types.FloatForComplex(t), depth)
6775 if t.NumElem() == 0 {
6776 n++ // {} counts as a component
6779 for i := int64(0); i < t.NumElem(); i++ {
6780 if !visitType(baseOffset, t.Elem(), depth) {
6783 baseOffset += t.Elem().Size()
6786 if t.NumFields() == 0 {
6787 n++ // {} counts as a component
6790 for _, field := range t.Fields().Slice() {
6791 if !visitType(baseOffset+field.Offset, field.Type, depth) {
6801 if strings.Contains(f.LSym.Name, "[") {
6802 // Skip the dictionary argument - it is implicit and the user doesn't need to see it.
6806 for _, a := range abiInfo.InParams()[start:] {
6807 if !visitType(a.FrameOffset(abiInfo), a.Type, 0) {
6813 base.Fatalf("ArgInfo too large")
6819 // for wrapper, emit info of wrapped function.
6820 func emitWrappedFuncInfo(e *ssafn, pp *objw.Progs) {
6821 if base.Ctxt.Flag_linkshared {
6822 // Relative reference (SymPtrOff) to another shared object doesn't work.
6827 wfn := e.curfn.WrappedFunc
6832 wsym := wfn.Linksym()
6833 x := base.Ctxt.LookupInit(fmt.Sprintf("%s.wrapinfo", wsym.Name), func(x *obj.LSym) {
6834 objw.SymPtrOff(x, 0, wsym)
6835 x.Set(obj.AttrContentAddressable, true)
6837 e.curfn.LSym.Func().WrapInfo = x
6839 // Emit a funcdata pointing at the wrap info data.
6840 p := pp.Prog(obj.AFUNCDATA)
6841 p.From.SetConst(objabi.FUNCDATA_WrapInfo)
6842 p.To.Type = obj.TYPE_MEM
6843 p.To.Name = obj.NAME_EXTERN
6847 // genssa appends entries to pp for each instruction in f.
6848 func genssa(f *ssa.Func, pp *objw.Progs) {
6850 s.ABI = f.OwnAux.Fn.ABI()
6852 e := f.Frontend().(*ssafn)
6854 s.livenessMap, s.partLiveArgs = liveness.Compute(e.curfn, f, e.stkptrsize, pp)
6855 emitArgInfo(e, f, pp)
6856 argLiveBlockMap, argLiveValueMap := liveness.ArgLiveness(e.curfn, f, pp)
6858 openDeferInfo := e.curfn.LSym.Func().OpenCodedDeferInfo
6859 if openDeferInfo != nil {
6860 // This function uses open-coded defers -- write out the funcdata
6861 // info that we computed at the end of genssa.
6862 p := pp.Prog(obj.AFUNCDATA)
6863 p.From.SetConst(objabi.FUNCDATA_OpenCodedDeferInfo)
6864 p.To.Type = obj.TYPE_MEM
6865 p.To.Name = obj.NAME_EXTERN
6866 p.To.Sym = openDeferInfo
6869 emitWrappedFuncInfo(e, pp)
6871 // Remember where each block starts.
6872 s.bstart = make([]*obj.Prog, f.NumBlocks())
6874 var progToValue map[*obj.Prog]*ssa.Value
6875 var progToBlock map[*obj.Prog]*ssa.Block
6876 var valueToProgAfter []*obj.Prog // The first Prog following computation of a value v; v is visible at this point.
6877 gatherPrintInfo := f.PrintOrHtmlSSA || ssa.GenssaDump[f.Name]
6878 if gatherPrintInfo {
6879 progToValue = make(map[*obj.Prog]*ssa.Value, f.NumValues())
6880 progToBlock = make(map[*obj.Prog]*ssa.Block, f.NumBlocks())
6881 f.Logf("genssa %s\n", f.Name)
6882 progToBlock[s.pp.Next] = f.Blocks[0]
6885 if base.Ctxt.Flag_locationlists {
6886 if cap(f.Cache.ValueToProgAfter) < f.NumValues() {
6887 f.Cache.ValueToProgAfter = make([]*obj.Prog, f.NumValues())
6889 valueToProgAfter = f.Cache.ValueToProgAfter[:f.NumValues()]
6890 for i := range valueToProgAfter {
6891 valueToProgAfter[i] = nil
6895 // If the very first instruction is not tagged as a statement,
6896 // debuggers may attribute it to previous function in program.
6897 firstPos := src.NoXPos
6898 for _, v := range f.Entry.Values {
6899 if v.Pos.IsStmt() == src.PosIsStmt {
6901 v.Pos = firstPos.WithDefaultStmt()
6906 // inlMarks has an entry for each Prog that implements an inline mark.
6907 // It maps from that Prog to the global inlining id of the inlined body
6908 // which should unwind to this Prog's location.
6909 var inlMarks map[*obj.Prog]int32
6910 var inlMarkList []*obj.Prog
6912 // inlMarksByPos maps from a (column 1) source position to the set of
6913 // Progs that are in the set above and have that source position.
6914 var inlMarksByPos map[src.XPos][]*obj.Prog
6916 var argLiveIdx int = -1 // argument liveness info index
6918 // Emit basic blocks
6919 for i, b := range f.Blocks {
6920 s.bstart[b.ID] = s.pp.Next
6921 s.lineRunStart = nil
6922 s.SetPos(s.pp.Pos.WithNotStmt()) // It needs a non-empty Pos, but cannot be a statement boundary (yet).
6924 // Attach a "default" liveness info. Normally this will be
6925 // overwritten in the Values loop below for each Value. But
6926 // for an empty block this will be used for its control
6927 // instruction. We won't use the actual liveness map on a
6928 // control instruction. Just mark it something that is
6929 // preemptible, unless this function is "all unsafe".
6930 s.pp.NextLive = objw.LivenessIndex{StackMapIndex: -1, IsUnsafePoint: liveness.IsUnsafe(f)}
6932 if idx, ok := argLiveBlockMap[b.ID]; ok && idx != argLiveIdx {
6934 p := s.pp.Prog(obj.APCDATA)
6935 p.From.SetConst(objabi.PCDATA_ArgLiveIndex)
6936 p.To.SetConst(int64(idx))
6939 // Emit values in block
6940 Arch.SSAMarkMoves(&s, b)
6941 for _, v := range b.Values {
6943 s.DebugFriendlySetPosFrom(v)
6945 if v.Op.ResultInArg0() && v.ResultReg() != v.Args[0].Reg() {
6946 v.Fatalf("input[0] and output not in same register %s", v.LongString())
6951 // memory arg needs no code
6953 // input args need no code
6954 case ssa.OpSP, ssa.OpSB:
6956 case ssa.OpSelect0, ssa.OpSelect1, ssa.OpSelectN, ssa.OpMakeResult:
6959 // nothing to do when there's a g register,
6960 // and checkLower complains if there's not
6961 case ssa.OpVarDef, ssa.OpVarLive, ssa.OpKeepAlive, ssa.OpVarKill:
6962 // nothing to do; already used by liveness
6966 // nothing to do; no-op conversion for liveness
6967 if v.Args[0].Reg() != v.Reg() {
6968 v.Fatalf("OpConvert should be a no-op: %s; %s", v.Args[0].LongString(), v.LongString())
6971 p := Arch.Ginsnop(s.pp)
6972 if inlMarks == nil {
6973 inlMarks = map[*obj.Prog]int32{}
6974 inlMarksByPos = map[src.XPos][]*obj.Prog{}
6976 inlMarks[p] = v.AuxInt32()
6977 inlMarkList = append(inlMarkList, p)
6978 pos := v.Pos.AtColumn1()
6979 inlMarksByPos[pos] = append(inlMarksByPos[pos], p)
6982 // Special case for first line in function; move it to the start (which cannot be a register-valued instruction)
6983 if firstPos != src.NoXPos && v.Op != ssa.OpArgIntReg && v.Op != ssa.OpArgFloatReg && v.Op != ssa.OpLoadReg && v.Op != ssa.OpStoreReg {
6985 firstPos = src.NoXPos
6987 // Attach this safe point to the next
6989 s.pp.NextLive = s.livenessMap.Get(v)
6991 // let the backend handle it
6992 Arch.SSAGenValue(&s, v)
6995 if idx, ok := argLiveValueMap[v.ID]; ok && idx != argLiveIdx {
6997 p := s.pp.Prog(obj.APCDATA)
6998 p.From.SetConst(objabi.PCDATA_ArgLiveIndex)
6999 p.To.SetConst(int64(idx))
7002 if base.Ctxt.Flag_locationlists {
7003 valueToProgAfter[v.ID] = s.pp.Next
7006 if gatherPrintInfo {
7007 for ; x != s.pp.Next; x = x.Link {
7012 // If this is an empty infinite loop, stick a hardware NOP in there so that debuggers are less confused.
7013 if s.bstart[b.ID] == s.pp.Next && len(b.Succs) == 1 && b.Succs[0].Block() == b {
7014 p := Arch.Ginsnop(s.pp)
7015 p.Pos = p.Pos.WithIsStmt()
7016 if b.Pos == src.NoXPos {
7017 b.Pos = p.Pos // It needs a file, otherwise a no-file non-zero line causes confusion. See #35652.
7018 if b.Pos == src.NoXPos {
7019 b.Pos = pp.Text.Pos // Sometimes p.Pos is empty. See #35695.
7022 b.Pos = b.Pos.WithBogusLine() // Debuggers are not good about infinite loops, force a change in line number
7024 // Emit control flow instructions for block
7026 if i < len(f.Blocks)-1 && base.Flag.N == 0 {
7027 // If -N, leave next==nil so every block with successors
7028 // ends in a JMP (except call blocks - plive doesn't like
7029 // select{send,recv} followed by a JMP call). Helps keep
7030 // line numbers for otherwise empty blocks.
7031 next = f.Blocks[i+1]
7035 Arch.SSAGenBlock(&s, b, next)
7036 if gatherPrintInfo {
7037 for ; x != s.pp.Next; x = x.Link {
7042 if f.Blocks[len(f.Blocks)-1].Kind == ssa.BlockExit {
7043 // We need the return address of a panic call to
7044 // still be inside the function in question. So if
7045 // it ends in a call which doesn't return, add a
7046 // nop (which will never execute) after the call.
7049 if openDeferInfo != nil {
7050 // When doing open-coded defers, generate a disconnected call to
7051 // deferreturn and a return. This will be used to during panic
7052 // recovery to unwind the stack and return back to the runtime.
7053 s.pp.NextLive = s.livenessMap.DeferReturn
7054 p := pp.Prog(obj.ACALL)
7055 p.To.Type = obj.TYPE_MEM
7056 p.To.Name = obj.NAME_EXTERN
7057 p.To.Sym = ir.Syms.Deferreturn
7059 // Load results into registers. So when a deferred function
7060 // recovers a panic, it will return to caller with right results.
7061 // The results are already in memory, because they are not SSA'd
7062 // when the function has defers (see canSSAName).
7063 for _, o := range f.OwnAux.ABIInfo().OutParams() {
7064 n := o.Name.(*ir.Name)
7065 rts, offs := o.RegisterTypesAndOffsets()
7066 for i := range o.Registers {
7067 Arch.LoadRegResult(&s, f, rts[i], ssa.ObjRegForAbiReg(o.Registers[i], f.Config), n, offs[i])
7074 if inlMarks != nil {
7075 // We have some inline marks. Try to find other instructions we're
7076 // going to emit anyway, and use those instructions instead of the
7078 for p := pp.Text; p != nil; p = p.Link {
7079 if p.As == obj.ANOP || p.As == obj.AFUNCDATA || p.As == obj.APCDATA || p.As == obj.ATEXT || p.As == obj.APCALIGN || Arch.LinkArch.Family == sys.Wasm {
7080 // Don't use 0-sized instructions as inline marks, because we need
7081 // to identify inline mark instructions by pc offset.
7082 // (Some of these instructions are sometimes zero-sized, sometimes not.
7083 // We must not use anything that even might be zero-sized.)
7084 // TODO: are there others?
7087 if _, ok := inlMarks[p]; ok {
7088 // Don't use inline marks themselves. We don't know
7089 // whether they will be zero-sized or not yet.
7092 pos := p.Pos.AtColumn1()
7093 s := inlMarksByPos[pos]
7097 for _, m := range s {
7098 // We found an instruction with the same source position as
7099 // some of the inline marks.
7100 // Use this instruction instead.
7101 p.Pos = p.Pos.WithIsStmt() // promote position to a statement
7102 pp.CurFunc.LSym.Func().AddInlMark(p, inlMarks[m])
7103 // Make the inline mark a real nop, so it doesn't generate any code.
7109 delete(inlMarksByPos, pos)
7111 // Any unmatched inline marks now need to be added to the inlining tree (and will generate a nop instruction).
7112 for _, p := range inlMarkList {
7113 if p.As != obj.ANOP {
7114 pp.CurFunc.LSym.Func().AddInlMark(p, inlMarks[p])
7119 if base.Ctxt.Flag_locationlists {
7120 var debugInfo *ssa.FuncDebug
7121 debugInfo = e.curfn.DebugInfo.(*ssa.FuncDebug)
7122 if e.curfn.ABI == obj.ABIInternal && base.Flag.N != 0 {
7123 ssa.BuildFuncDebugNoOptimized(base.Ctxt, f, base.Debug.LocationLists > 1, StackOffset, debugInfo)
7125 ssa.BuildFuncDebug(base.Ctxt, f, base.Debug.LocationLists, StackOffset, debugInfo)
7128 idToIdx := make([]int, f.NumBlocks())
7129 for i, b := range f.Blocks {
7132 // Note that at this moment, Prog.Pc is a sequence number; it's
7133 // not a real PC until after assembly, so this mapping has to
7135 debugInfo.GetPC = func(b, v ssa.ID) int64 {
7137 case ssa.BlockStart.ID:
7138 if b == f.Entry.ID {
7139 return 0 // Start at the very beginning, at the assembler-generated prologue.
7140 // this should only happen for function args (ssa.OpArg)
7143 case ssa.BlockEnd.ID:
7144 blk := f.Blocks[idToIdx[b]]
7145 nv := len(blk.Values)
7146 return valueToProgAfter[blk.Values[nv-1].ID].Pc
7147 case ssa.FuncEnd.ID:
7148 return e.curfn.LSym.Size
7150 return valueToProgAfter[v].Pc
7155 // Resolve branches, and relax DefaultStmt into NotStmt
7156 for _, br := range s.Branches {
7157 br.P.To.SetTarget(s.bstart[br.B.ID])
7158 if br.P.Pos.IsStmt() != src.PosIsStmt {
7159 br.P.Pos = br.P.Pos.WithNotStmt()
7160 } else if v0 := br.B.FirstPossibleStmtValue(); v0 != nil && v0.Pos.Line() == br.P.Pos.Line() && v0.Pos.IsStmt() == src.PosIsStmt {
7161 br.P.Pos = br.P.Pos.WithNotStmt()
7166 // Resolve jump table destinations.
7167 for _, jt := range s.JumpTables {
7168 // Convert from *Block targets to *Prog targets.
7169 targets := make([]*obj.Prog, len(jt.Succs))
7170 for i, e := range jt.Succs {
7171 targets[i] = s.bstart[e.Block().ID]
7173 // Add to list of jump tables to be resolved at assembly time.
7174 // The assembler converts from *Prog entries to absolute addresses
7175 // once it knows instruction byte offsets.
7176 fi := pp.CurFunc.LSym.Func()
7177 fi.JumpTables = append(fi.JumpTables, obj.JumpTable{Sym: jt.Aux.(*obj.LSym), Targets: targets})
7180 if e.log { // spew to stdout
7182 for p := pp.Text; p != nil; p = p.Link {
7183 if p.Pos.IsKnown() && p.InnermostFilename() != filename {
7184 filename = p.InnermostFilename()
7185 f.Logf("# %s\n", filename)
7189 if v, ok := progToValue[p]; ok {
7191 } else if b, ok := progToBlock[p]; ok {
7194 s = " " // most value and branch strings are 2-3 characters long
7196 f.Logf(" %-6s\t%.5d (%s)\t%s\n", s, p.Pc, p.InnermostLineNumber(), p.InstructionString())
7199 if f.HTMLWriter != nil { // spew to ssa.html
7200 var buf bytes.Buffer
7201 buf.WriteString("<code>")
7202 buf.WriteString("<dl class=\"ssa-gen\">")
7204 for p := pp.Text; p != nil; p = p.Link {
7205 // Don't spam every line with the file name, which is often huge.
7206 // Only print changes, and "unknown" is not a change.
7207 if p.Pos.IsKnown() && p.InnermostFilename() != filename {
7208 filename = p.InnermostFilename()
7209 buf.WriteString("<dt class=\"ssa-prog-src\"></dt><dd class=\"ssa-prog\">")
7210 buf.WriteString(html.EscapeString("# " + filename))
7211 buf.WriteString("</dd>")
7214 buf.WriteString("<dt class=\"ssa-prog-src\">")
7215 if v, ok := progToValue[p]; ok {
7216 buf.WriteString(v.HTML())
7217 } else if b, ok := progToBlock[p]; ok {
7218 buf.WriteString("<b>" + b.HTML() + "</b>")
7220 buf.WriteString("</dt>")
7221 buf.WriteString("<dd class=\"ssa-prog\">")
7222 buf.WriteString(fmt.Sprintf("%.5d <span class=\"l%v line-number\">(%s)</span> %s", p.Pc, p.InnermostLineNumber(), p.InnermostLineNumberHTML(), html.EscapeString(p.InstructionString())))
7223 buf.WriteString("</dd>")
7225 buf.WriteString("</dl>")
7226 buf.WriteString("</code>")
7227 f.HTMLWriter.WriteColumn("genssa", "genssa", "ssa-prog", buf.String())
7229 if ssa.GenssaDump[f.Name] {
7230 fi := f.DumpFileForPhase("genssa")
7233 // inliningDiffers if any filename changes or if any line number except the innermost (index 0) changes.
7234 inliningDiffers := func(a, b []src.Pos) bool {
7235 if len(a) != len(b) {
7239 if a[i].Filename() != b[i].Filename() {
7242 if i > 0 && a[i].Line() != b[i].Line() {
7249 var allPosOld []src.Pos
7250 var allPos []src.Pos
7252 for p := pp.Text; p != nil; p = p.Link {
7253 if p.Pos.IsKnown() {
7254 allPos = p.AllPos(allPos)
7255 if inliningDiffers(allPos, allPosOld) {
7256 for i := len(allPos) - 1; i >= 0; i-- {
7258 fmt.Fprintf(fi, "# %s:%d\n", pos.Filename(), pos.Line())
7260 allPos, allPosOld = allPosOld, allPos // swap, not copy, so that they do not share slice storage.
7265 if v, ok := progToValue[p]; ok {
7267 } else if b, ok := progToBlock[p]; ok {
7270 s = " " // most value and branch strings are 2-3 characters long
7272 fmt.Fprintf(fi, " %-6s\t%.5d %s\t%s\n", s, p.Pc, ssa.StmtString(p.Pos), p.InstructionString())
7280 f.HTMLWriter.Close()
7284 func defframe(s *State, e *ssafn, f *ssa.Func) {
7287 frame := types.Rnd(s.maxarg+e.stksize, int64(types.RegSize))
7288 if Arch.PadFrame != nil {
7289 frame = Arch.PadFrame(frame)
7292 // Fill in argument and frame size.
7293 pp.Text.To.Type = obj.TYPE_TEXTSIZE
7294 pp.Text.To.Val = int32(types.Rnd(f.OwnAux.ArgWidth(), int64(types.RegSize)))
7295 pp.Text.To.Offset = frame
7299 // Insert code to spill argument registers if the named slot may be partially
7300 // live. That is, the named slot is considered live by liveness analysis,
7301 // (because a part of it is live), but we may not spill all parts into the
7302 // slot. This can only happen with aggregate-typed arguments that are SSA-able
7303 // and not address-taken (for non-SSA-able or address-taken arguments we always
7305 // Note: spilling is unnecessary in the -N/no-optimize case, since all values
7306 // will be considered non-SSAable and spilled up front.
7307 // TODO(register args) Make liveness more fine-grained to that partial spilling is okay.
7308 if f.OwnAux.ABIInfo().InRegistersUsed() != 0 && base.Flag.N == 0 {
7309 // First, see if it is already spilled before it may be live. Look for a spill
7310 // in the entry block up to the first safepoint.
7311 type nameOff struct {
7315 partLiveArgsSpilled := make(map[nameOff]bool)
7316 for _, v := range f.Entry.Values {
7320 if v.Op != ssa.OpStoreReg || v.Args[0].Op != ssa.OpArgIntReg {
7323 n, off := ssa.AutoVar(v)
7324 if n.Class != ir.PPARAM || n.Addrtaken() || !TypeOK(n.Type()) || !s.partLiveArgs[n] {
7327 partLiveArgsSpilled[nameOff{n, off}] = true
7330 // Then, insert code to spill registers if not already.
7331 for _, a := range f.OwnAux.ABIInfo().InParams() {
7332 n, ok := a.Name.(*ir.Name)
7333 if !ok || n.Addrtaken() || !TypeOK(n.Type()) || !s.partLiveArgs[n] || len(a.Registers) <= 1 {
7336 rts, offs := a.RegisterTypesAndOffsets()
7337 for i := range a.Registers {
7338 if !rts[i].HasPointers() {
7341 if partLiveArgsSpilled[nameOff{n, offs[i]}] {
7342 continue // already spilled
7344 reg := ssa.ObjRegForAbiReg(a.Registers[i], f.Config)
7345 p = Arch.SpillArgReg(pp, p, f, rts[i], reg, n, offs[i])
7350 // Insert code to zero ambiguously live variables so that the
7351 // garbage collector only sees initialized values when it
7352 // looks for pointers.
7355 // Opaque state for backend to use. Current backends use it to
7356 // keep track of which helper registers have been zeroed.
7359 // Iterate through declarations. Autos are sorted in decreasing
7360 // frame offset order.
7361 for _, n := range e.curfn.Dcl {
7365 if n.Class != ir.PAUTO {
7366 e.Fatalf(n.Pos(), "needzero class %d", n.Class)
7368 if n.Type().Size()%int64(types.PtrSize) != 0 || n.FrameOffset()%int64(types.PtrSize) != 0 || n.Type().Size() == 0 {
7369 e.Fatalf(n.Pos(), "var %L has size %d offset %d", n, n.Type().Size(), n.Offset_)
7372 if lo != hi && n.FrameOffset()+n.Type().Size() >= lo-int64(2*types.RegSize) {
7373 // Merge with range we already have.
7374 lo = n.FrameOffset()
7379 p = Arch.ZeroRange(pp, p, frame+lo, hi-lo, &state)
7382 lo = n.FrameOffset()
7383 hi = lo + n.Type().Size()
7386 // Zero final range.
7387 Arch.ZeroRange(pp, p, frame+lo, hi-lo, &state)
7390 // For generating consecutive jump instructions to model a specific branching
7391 type IndexJump struct {
7396 func (s *State) oneJump(b *ssa.Block, jump *IndexJump) {
7397 p := s.Br(jump.Jump, b.Succs[jump.Index].Block())
7401 // CombJump generates combinational instructions (2 at present) for a block jump,
7402 // thereby the behaviour of non-standard condition codes could be simulated
7403 func (s *State) CombJump(b, next *ssa.Block, jumps *[2][2]IndexJump) {
7405 case b.Succs[0].Block():
7406 s.oneJump(b, &jumps[0][0])
7407 s.oneJump(b, &jumps[0][1])
7408 case b.Succs[1].Block():
7409 s.oneJump(b, &jumps[1][0])
7410 s.oneJump(b, &jumps[1][1])
7413 if b.Likely != ssa.BranchUnlikely {
7414 s.oneJump(b, &jumps[1][0])
7415 s.oneJump(b, &jumps[1][1])
7416 q = s.Br(obj.AJMP, b.Succs[1].Block())
7418 s.oneJump(b, &jumps[0][0])
7419 s.oneJump(b, &jumps[0][1])
7420 q = s.Br(obj.AJMP, b.Succs[0].Block())
7426 // AddAux adds the offset in the aux fields (AuxInt and Aux) of v to a.
7427 func AddAux(a *obj.Addr, v *ssa.Value) {
7428 AddAux2(a, v, v.AuxInt)
7430 func AddAux2(a *obj.Addr, v *ssa.Value, offset int64) {
7431 if a.Type != obj.TYPE_MEM && a.Type != obj.TYPE_ADDR {
7432 v.Fatalf("bad AddAux addr %v", a)
7434 // add integer offset
7437 // If no additional symbol offset, we're done.
7441 // Add symbol's offset from its base register.
7442 switch n := v.Aux.(type) {
7444 a.Name = obj.NAME_EXTERN
7447 a.Name = obj.NAME_EXTERN
7450 if n.Class == ir.PPARAM || (n.Class == ir.PPARAMOUT && !n.IsOutputParamInRegisters()) {
7451 a.Name = obj.NAME_PARAM
7452 a.Sym = ir.Orig(n).(*ir.Name).Linksym()
7453 a.Offset += n.FrameOffset()
7456 a.Name = obj.NAME_AUTO
7457 if n.Class == ir.PPARAMOUT {
7458 a.Sym = ir.Orig(n).(*ir.Name).Linksym()
7462 a.Offset += n.FrameOffset()
7464 v.Fatalf("aux in %s not implemented %#v", v, v.Aux)
7468 // extendIndex extends v to a full int width.
7469 // panic with the given kind if v does not fit in an int (only on 32-bit archs).
7470 func (s *state) extendIndex(idx, len *ssa.Value, kind ssa.BoundsKind, bounded bool) *ssa.Value {
7471 size := idx.Type.Size()
7472 if size == s.config.PtrSize {
7475 if size > s.config.PtrSize {
7476 // truncate 64-bit indexes on 32-bit pointer archs. Test the
7477 // high word and branch to out-of-bounds failure if it is not 0.
7479 if idx.Type.IsSigned() {
7480 lo = s.newValue1(ssa.OpInt64Lo, types.Types[types.TINT], idx)
7482 lo = s.newValue1(ssa.OpInt64Lo, types.Types[types.TUINT], idx)
7484 if bounded || base.Flag.B != 0 {
7487 bNext := s.f.NewBlock(ssa.BlockPlain)
7488 bPanic := s.f.NewBlock(ssa.BlockExit)
7489 hi := s.newValue1(ssa.OpInt64Hi, types.Types[types.TUINT32], idx)
7490 cmp := s.newValue2(ssa.OpEq32, types.Types[types.TBOOL], hi, s.constInt32(types.Types[types.TUINT32], 0))
7491 if !idx.Type.IsSigned() {
7493 case ssa.BoundsIndex:
7494 kind = ssa.BoundsIndexU
7495 case ssa.BoundsSliceAlen:
7496 kind = ssa.BoundsSliceAlenU
7497 case ssa.BoundsSliceAcap:
7498 kind = ssa.BoundsSliceAcapU
7499 case ssa.BoundsSliceB:
7500 kind = ssa.BoundsSliceBU
7501 case ssa.BoundsSlice3Alen:
7502 kind = ssa.BoundsSlice3AlenU
7503 case ssa.BoundsSlice3Acap:
7504 kind = ssa.BoundsSlice3AcapU
7505 case ssa.BoundsSlice3B:
7506 kind = ssa.BoundsSlice3BU
7507 case ssa.BoundsSlice3C:
7508 kind = ssa.BoundsSlice3CU
7512 b.Kind = ssa.BlockIf
7514 b.Likely = ssa.BranchLikely
7518 s.startBlock(bPanic)
7519 mem := s.newValue4I(ssa.OpPanicExtend, types.TypeMem, int64(kind), hi, lo, len, s.mem())
7520 s.endBlock().SetControl(mem)
7526 // Extend value to the required size
7528 if idx.Type.IsSigned() {
7529 switch 10*size + s.config.PtrSize {
7531 op = ssa.OpSignExt8to32
7533 op = ssa.OpSignExt8to64
7535 op = ssa.OpSignExt16to32
7537 op = ssa.OpSignExt16to64
7539 op = ssa.OpSignExt32to64
7541 s.Fatalf("bad signed index extension %s", idx.Type)
7544 switch 10*size + s.config.PtrSize {
7546 op = ssa.OpZeroExt8to32
7548 op = ssa.OpZeroExt8to64
7550 op = ssa.OpZeroExt16to32
7552 op = ssa.OpZeroExt16to64
7554 op = ssa.OpZeroExt32to64
7556 s.Fatalf("bad unsigned index extension %s", idx.Type)
7559 return s.newValue1(op, types.Types[types.TINT], idx)
7562 // CheckLoweredPhi checks that regalloc and stackalloc correctly handled phi values.
7563 // Called during ssaGenValue.
7564 func CheckLoweredPhi(v *ssa.Value) {
7565 if v.Op != ssa.OpPhi {
7566 v.Fatalf("CheckLoweredPhi called with non-phi value: %v", v.LongString())
7568 if v.Type.IsMemory() {
7572 loc := f.RegAlloc[v.ID]
7573 for _, a := range v.Args {
7574 if aloc := f.RegAlloc[a.ID]; aloc != loc { // TODO: .Equal() instead?
7575 v.Fatalf("phi arg at different location than phi: %v @ %s, but arg %v @ %s\n%s\n", v, loc, a, aloc, v.Block.Func)
7580 // CheckLoweredGetClosurePtr checks that v is the first instruction in the function's entry block,
7581 // except for incoming in-register arguments.
7582 // The output of LoweredGetClosurePtr is generally hardwired to the correct register.
7583 // That register contains the closure pointer on closure entry.
7584 func CheckLoweredGetClosurePtr(v *ssa.Value) {
7585 entry := v.Block.Func.Entry
7586 if entry != v.Block {
7587 base.Fatalf("in %s, badly placed LoweredGetClosurePtr: %v %v", v.Block.Func.Name, v.Block, v)
7589 for _, w := range entry.Values {
7594 case ssa.OpArgIntReg, ssa.OpArgFloatReg:
7597 base.Fatalf("in %s, badly placed LoweredGetClosurePtr: %v %v", v.Block.Func.Name, v.Block, v)
7602 // CheckArgReg ensures that v is in the function's entry block.
7603 func CheckArgReg(v *ssa.Value) {
7604 entry := v.Block.Func.Entry
7605 if entry != v.Block {
7606 base.Fatalf("in %s, badly placed ArgIReg or ArgFReg: %v %v", v.Block.Func.Name, v.Block, v)
7610 func AddrAuto(a *obj.Addr, v *ssa.Value) {
7611 n, off := ssa.AutoVar(v)
7612 a.Type = obj.TYPE_MEM
7614 a.Reg = int16(Arch.REGSP)
7615 a.Offset = n.FrameOffset() + off
7616 if n.Class == ir.PPARAM || (n.Class == ir.PPARAMOUT && !n.IsOutputParamInRegisters()) {
7617 a.Name = obj.NAME_PARAM
7619 a.Name = obj.NAME_AUTO
7623 // Call returns a new CALL instruction for the SSA value v.
7624 // It uses PrepareCall to prepare the call.
7625 func (s *State) Call(v *ssa.Value) *obj.Prog {
7626 pPosIsStmt := s.pp.Pos.IsStmt() // The statement-ness fo the call comes from ssaGenState
7629 p := s.Prog(obj.ACALL)
7630 if pPosIsStmt == src.PosIsStmt {
7631 p.Pos = v.Pos.WithIsStmt()
7633 p.Pos = v.Pos.WithNotStmt()
7635 if sym, ok := v.Aux.(*ssa.AuxCall); ok && sym.Fn != nil {
7636 p.To.Type = obj.TYPE_MEM
7637 p.To.Name = obj.NAME_EXTERN
7640 // TODO(mdempsky): Can these differences be eliminated?
7641 switch Arch.LinkArch.Family {
7642 case sys.AMD64, sys.I386, sys.PPC64, sys.RISCV64, sys.S390X, sys.Wasm:
7643 p.To.Type = obj.TYPE_REG
7644 case sys.ARM, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64:
7645 p.To.Type = obj.TYPE_MEM
7647 base.Fatalf("unknown indirect call family")
7649 p.To.Reg = v.Args[0].Reg()
7654 // TailCall returns a new tail call instruction for the SSA value v.
7655 // It is like Call, but for a tail call.
7656 func (s *State) TailCall(v *ssa.Value) *obj.Prog {
7662 // PrepareCall prepares to emit a CALL instruction for v and does call-related bookkeeping.
7663 // It must be called immediately before emitting the actual CALL instruction,
7664 // since it emits PCDATA for the stack map at the call (calls are safe points).
7665 func (s *State) PrepareCall(v *ssa.Value) {
7666 idx := s.livenessMap.Get(v)
7667 if !idx.StackMapValid() {
7668 // See Liveness.hasStackMap.
7669 if sym, ok := v.Aux.(*ssa.AuxCall); !ok || !(sym.Fn == ir.Syms.Typedmemclr || sym.Fn == ir.Syms.Typedmemmove) {
7670 base.Fatalf("missing stack map index for %v", v.LongString())
7674 call, ok := v.Aux.(*ssa.AuxCall)
7677 // Record call graph information for nowritebarrierrec
7679 if nowritebarrierrecCheck != nil {
7680 nowritebarrierrecCheck.recordCall(s.pp.CurFunc, call.Fn, v.Pos)
7684 if s.maxarg < v.AuxInt {
7689 // UseArgs records the fact that an instruction needs a certain amount of
7690 // callee args space for its use.
7691 func (s *State) UseArgs(n int64) {
7697 // fieldIdx finds the index of the field referred to by the ODOT node n.
7698 func fieldIdx(n *ir.SelectorExpr) int {
7701 panic("ODOT's LHS is not a struct")
7704 for i, f := range t.Fields().Slice() {
7706 if f.Offset != n.Offset() {
7707 panic("field offset doesn't match")
7712 panic(fmt.Sprintf("can't find field in expr %v\n", n))
7714 // TODO: keep the result of this function somewhere in the ODOT Node
7715 // so we don't have to recompute it each time we need it.
7718 // ssafn holds frontend information about a function that the backend is processing.
7719 // It also exports a bunch of compiler services for the ssa backend.
7722 strings map[string]*obj.LSym // map from constant string to data symbols
7723 stksize int64 // stack size for current frame
7724 stkptrsize int64 // prefix of stack containing pointers
7725 log bool // print ssa debug to the stdout
7728 // StringData returns a symbol which
7729 // is the data component of a global string constant containing s.
7730 func (e *ssafn) StringData(s string) *obj.LSym {
7731 if aux, ok := e.strings[s]; ok {
7734 if e.strings == nil {
7735 e.strings = make(map[string]*obj.LSym)
7737 data := staticdata.StringSym(e.curfn.Pos(), s)
7742 func (e *ssafn) Auto(pos src.XPos, t *types.Type) *ir.Name {
7743 return typecheck.TempAt(pos, e.curfn, t) // Note: adds new auto to e.curfn.Func.Dcl list
7746 // SplitSlot returns a slot representing the data of parent starting at offset.
7747 func (e *ssafn) SplitSlot(parent *ssa.LocalSlot, suffix string, offset int64, t *types.Type) ssa.LocalSlot {
7750 if node.Class != ir.PAUTO || node.Addrtaken() {
7751 // addressed things and non-autos retain their parents (i.e., cannot truly be split)
7752 return ssa.LocalSlot{N: node, Type: t, Off: parent.Off + offset}
7755 s := &types.Sym{Name: node.Sym().Name + suffix, Pkg: types.LocalPkg}
7756 n := ir.NewNameAt(parent.N.Pos(), s)
7758 ir.AsNode(s.Def).Name().SetUsed(true)
7761 n.SetEsc(ir.EscNever)
7763 e.curfn.Dcl = append(e.curfn.Dcl, n)
7765 return ssa.LocalSlot{N: n, Type: t, Off: 0, SplitOf: parent, SplitOffset: offset}
7768 func (e *ssafn) CanSSA(t *types.Type) bool {
7772 func (e *ssafn) Line(pos src.XPos) string {
7773 return base.FmtPos(pos)
7776 // Log logs a message from the compiler.
7777 func (e *ssafn) Logf(msg string, args ...interface{}) {
7779 fmt.Printf(msg, args...)
7783 func (e *ssafn) Log() bool {
7787 // Fatal reports a compiler error and exits.
7788 func (e *ssafn) Fatalf(pos src.XPos, msg string, args ...interface{}) {
7790 nargs := append([]interface{}{ir.FuncName(e.curfn)}, args...)
7791 base.Fatalf("'%s': "+msg, nargs...)
7794 // Warnl reports a "warning", which is usually flag-triggered
7795 // logging output for the benefit of tests.
7796 func (e *ssafn) Warnl(pos src.XPos, fmt_ string, args ...interface{}) {
7797 base.WarnfAt(pos, fmt_, args...)
7800 func (e *ssafn) Debug_checknil() bool {
7801 return base.Debug.Nil != 0
7804 func (e *ssafn) UseWriteBarrier() bool {
7808 func (e *ssafn) Syslook(name string) *obj.LSym {
7810 case "goschedguarded":
7811 return ir.Syms.Goschedguarded
7812 case "writeBarrier":
7813 return ir.Syms.WriteBarrier
7814 case "gcWriteBarrier":
7815 return ir.Syms.GCWriteBarrier
7816 case "typedmemmove":
7817 return ir.Syms.Typedmemmove
7819 return ir.Syms.Typedmemclr
7821 e.Fatalf(src.NoXPos, "unknown Syslook func %v", name)
7825 func (e *ssafn) SetWBPos(pos src.XPos) {
7826 e.curfn.SetWBPos(pos)
7829 func (e *ssafn) MyImportPath() string {
7830 return base.Ctxt.Pkgpath
7833 func (e *ssafn) LSym() string {
7834 return e.curfn.LSym.Name
7837 func clobberBase(n ir.Node) ir.Node {
7838 if n.Op() == ir.ODOT {
7839 n := n.(*ir.SelectorExpr)
7840 if n.X.Type().NumFields() == 1 {
7841 return clobberBase(n.X)
7844 if n.Op() == ir.OINDEX {
7845 n := n.(*ir.IndexExpr)
7846 if n.X.Type().IsArray() && n.X.Type().NumElem() == 1 {
7847 return clobberBase(n.X)
7853 // callTargetLSym returns the correct LSym to call 'callee' using its ABI.
7854 func callTargetLSym(callee *ir.Name) *obj.LSym {
7855 if callee.Func == nil {
7856 // TODO(austin): This happens in a few cases of
7857 // compiler-generated functions. These are all
7858 // ABIInternal. It would be better if callee.Func was
7859 // never nil and we didn't need this case.
7860 return callee.Linksym()
7863 return callee.LinksymABI(callee.Func.ABI)
7866 func min8(a, b int8) int8 {
7873 func max8(a, b int8) int8 {
7880 // deferstruct makes a runtime._defer structure.
7881 func deferstruct() *types.Type {
7882 makefield := func(name string, typ *types.Type) *types.Field {
7883 // Unlike the global makefield function, this one needs to set Pkg
7884 // because these types might be compared (in SSA CSE sorting).
7885 // TODO: unify this makefield and the global one above.
7886 sym := &types.Sym{Name: name, Pkg: types.LocalPkg}
7887 return types.NewField(src.NoXPos, sym, typ)
7889 // These fields must match the ones in runtime/runtime2.go:_defer and
7890 // (*state).call above.
7891 fields := []*types.Field{
7892 makefield("started", types.Types[types.TBOOL]),
7893 makefield("heap", types.Types[types.TBOOL]),
7894 makefield("openDefer", types.Types[types.TBOOL]),
7895 makefield("sp", types.Types[types.TUINTPTR]),
7896 makefield("pc", types.Types[types.TUINTPTR]),
7897 // Note: the types here don't really matter. Defer structures
7898 // are always scanned explicitly during stack copying and GC,
7899 // so we make them uintptr type even though they are real pointers.
7900 makefield("fn", types.Types[types.TUINTPTR]),
7901 makefield("_panic", types.Types[types.TUINTPTR]),
7902 makefield("link", types.Types[types.TUINTPTR]),
7903 makefield("fd", types.Types[types.TUINTPTR]),
7904 makefield("varp", types.Types[types.TUINTPTR]),
7905 makefield("framepc", types.Types[types.TUINTPTR]),
7908 // build struct holding the above fields
7909 s := types.NewStruct(types.NoPkg, fields)
7911 types.CalcStructSize(s)
7915 // SlotAddr uses LocalSlot information to initialize an obj.Addr
7916 // The resulting addr is used in a non-standard context -- in the prologue
7917 // of a function, before the frame has been constructed, so the standard
7918 // addressing for the parameters will be wrong.
7919 func SpillSlotAddr(spill ssa.Spill, baseReg int16, extraOffset int64) obj.Addr {
7921 Name: obj.NAME_NONE,
7924 Offset: spill.Offset + extraOffset,
7929 BoundsCheckFunc [ssa.BoundsKindCount]*obj.LSym
7930 ExtendCheckFunc [ssa.BoundsKindCount]*obj.LSym
7933 // GCWriteBarrierReg maps from registers to gcWriteBarrier implementation LSyms.
7934 var GCWriteBarrierReg map[int16]*obj.LSym