1 // Copyright 2015 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
19 "cmd/compile/internal/abi"
20 "cmd/compile/internal/base"
21 "cmd/compile/internal/ir"
22 "cmd/compile/internal/liveness"
23 "cmd/compile/internal/objw"
24 "cmd/compile/internal/reflectdata"
25 "cmd/compile/internal/ssa"
26 "cmd/compile/internal/staticdata"
27 "cmd/compile/internal/typecheck"
28 "cmd/compile/internal/types"
37 var ssaConfig *ssa.Config
38 var ssaCaches []ssa.Cache
40 var ssaDump string // early copy of $GOSSAFUNC; the func name to dump output for
41 var ssaDir string // optional destination for ssa dump file
42 var ssaDumpStdout bool // whether to dump to stdout
43 var ssaDumpCFG string // generate CFGs for these phases
44 const ssaDumpFile = "ssa.html"
46 // ssaDumpInlined holds all inlined functions when ssaDump contains a function name.
47 var ssaDumpInlined []*ir.Func
49 func DumpInline(fn *ir.Func) {
50 if ssaDump != "" && ssaDump == ir.FuncName(fn) {
51 ssaDumpInlined = append(ssaDumpInlined, fn)
56 ssaDump = os.Getenv("GOSSAFUNC")
57 ssaDir = os.Getenv("GOSSADIR")
59 if strings.HasSuffix(ssaDump, "+") {
60 ssaDump = ssaDump[:len(ssaDump)-1]
63 spl := strings.Split(ssaDump, ":")
72 types_ := ssa.NewTypes()
78 // Generate a few pointer types that are uncommon in the frontend but common in the backend.
79 // Caching is disabled in the backend, so generating these here avoids allocations.
80 _ = types.NewPtr(types.Types[types.TINTER]) // *interface{}
81 _ = types.NewPtr(types.NewPtr(types.Types[types.TSTRING])) // **string
82 _ = types.NewPtr(types.NewSlice(types.Types[types.TINTER])) // *[]interface{}
83 _ = types.NewPtr(types.NewPtr(types.ByteType)) // **byte
84 _ = types.NewPtr(types.NewSlice(types.ByteType)) // *[]byte
85 _ = types.NewPtr(types.NewSlice(types.Types[types.TSTRING])) // *[]string
86 _ = types.NewPtr(types.NewPtr(types.NewPtr(types.Types[types.TUINT8]))) // ***uint8
87 _ = types.NewPtr(types.Types[types.TINT16]) // *int16
88 _ = types.NewPtr(types.Types[types.TINT64]) // *int64
89 _ = types.NewPtr(types.ErrorType) // *error
90 _ = types.NewPtr(reflectdata.MapType()) // *runtime.hmap
91 _ = types.NewPtr(deferstruct()) // *runtime._defer
92 types.NewPtrCacheEnabled = false
93 ssaConfig = ssa.NewConfig(base.Ctxt.Arch.Name, *types_, base.Ctxt, base.Flag.N == 0, Arch.SoftFloat)
94 ssaConfig.Race = base.Flag.Race
95 ssaCaches = make([]ssa.Cache, base.Flag.LowerC)
97 // Set up some runtime functions we'll need to call.
98 ir.Syms.AssertE2I = typecheck.LookupRuntimeFunc("assertE2I")
99 ir.Syms.AssertE2I2 = typecheck.LookupRuntimeFunc("assertE2I2")
100 ir.Syms.AssertI2I = typecheck.LookupRuntimeFunc("assertI2I")
101 ir.Syms.AssertI2I2 = typecheck.LookupRuntimeFunc("assertI2I2")
102 ir.Syms.CgoCheckMemmove = typecheck.LookupRuntimeFunc("cgoCheckMemmove")
103 ir.Syms.CgoCheckPtrWrite = typecheck.LookupRuntimeFunc("cgoCheckPtrWrite")
104 ir.Syms.CheckPtrAlignment = typecheck.LookupRuntimeFunc("checkptrAlignment")
105 ir.Syms.Deferproc = typecheck.LookupRuntimeFunc("deferproc")
106 ir.Syms.Deferprocat = typecheck.LookupRuntimeFunc("deferprocat")
107 ir.Syms.DeferprocStack = typecheck.LookupRuntimeFunc("deferprocStack")
108 ir.Syms.Deferreturn = typecheck.LookupRuntimeFunc("deferreturn")
109 ir.Syms.Duffcopy = typecheck.LookupRuntimeFunc("duffcopy")
110 ir.Syms.Duffzero = typecheck.LookupRuntimeFunc("duffzero")
111 ir.Syms.GCWriteBarrier[0] = typecheck.LookupRuntimeFunc("gcWriteBarrier1")
112 ir.Syms.GCWriteBarrier[1] = typecheck.LookupRuntimeFunc("gcWriteBarrier2")
113 ir.Syms.GCWriteBarrier[2] = typecheck.LookupRuntimeFunc("gcWriteBarrier3")
114 ir.Syms.GCWriteBarrier[3] = typecheck.LookupRuntimeFunc("gcWriteBarrier4")
115 ir.Syms.GCWriteBarrier[4] = typecheck.LookupRuntimeFunc("gcWriteBarrier5")
116 ir.Syms.GCWriteBarrier[5] = typecheck.LookupRuntimeFunc("gcWriteBarrier6")
117 ir.Syms.GCWriteBarrier[6] = typecheck.LookupRuntimeFunc("gcWriteBarrier7")
118 ir.Syms.GCWriteBarrier[7] = typecheck.LookupRuntimeFunc("gcWriteBarrier8")
119 ir.Syms.Goschedguarded = typecheck.LookupRuntimeFunc("goschedguarded")
120 ir.Syms.Growslice = typecheck.LookupRuntimeFunc("growslice")
121 ir.Syms.Memmove = typecheck.LookupRuntimeFunc("memmove")
122 ir.Syms.Msanread = typecheck.LookupRuntimeFunc("msanread")
123 ir.Syms.Msanwrite = typecheck.LookupRuntimeFunc("msanwrite")
124 ir.Syms.Msanmove = typecheck.LookupRuntimeFunc("msanmove")
125 ir.Syms.Asanread = typecheck.LookupRuntimeFunc("asanread")
126 ir.Syms.Asanwrite = typecheck.LookupRuntimeFunc("asanwrite")
127 ir.Syms.Newobject = typecheck.LookupRuntimeFunc("newobject")
128 ir.Syms.Newproc = typecheck.LookupRuntimeFunc("newproc")
129 ir.Syms.Panicdivide = typecheck.LookupRuntimeFunc("panicdivide")
130 ir.Syms.PanicdottypeE = typecheck.LookupRuntimeFunc("panicdottypeE")
131 ir.Syms.PanicdottypeI = typecheck.LookupRuntimeFunc("panicdottypeI")
132 ir.Syms.Panicnildottype = typecheck.LookupRuntimeFunc("panicnildottype")
133 ir.Syms.Panicoverflow = typecheck.LookupRuntimeFunc("panicoverflow")
134 ir.Syms.Panicshift = typecheck.LookupRuntimeFunc("panicshift")
135 ir.Syms.Racefuncenter = typecheck.LookupRuntimeFunc("racefuncenter")
136 ir.Syms.Racefuncexit = typecheck.LookupRuntimeFunc("racefuncexit")
137 ir.Syms.Raceread = typecheck.LookupRuntimeFunc("raceread")
138 ir.Syms.Racereadrange = typecheck.LookupRuntimeFunc("racereadrange")
139 ir.Syms.Racewrite = typecheck.LookupRuntimeFunc("racewrite")
140 ir.Syms.Racewriterange = typecheck.LookupRuntimeFunc("racewriterange")
141 ir.Syms.WBZero = typecheck.LookupRuntimeFunc("wbZero")
142 ir.Syms.WBMove = typecheck.LookupRuntimeFunc("wbMove")
143 ir.Syms.X86HasPOPCNT = typecheck.LookupRuntimeVar("x86HasPOPCNT") // bool
144 ir.Syms.X86HasSSE41 = typecheck.LookupRuntimeVar("x86HasSSE41") // bool
145 ir.Syms.X86HasFMA = typecheck.LookupRuntimeVar("x86HasFMA") // bool
146 ir.Syms.ARMHasVFPv4 = typecheck.LookupRuntimeVar("armHasVFPv4") // bool
147 ir.Syms.ARM64HasATOMICS = typecheck.LookupRuntimeVar("arm64HasATOMICS") // bool
148 ir.Syms.Staticuint64s = typecheck.LookupRuntimeVar("staticuint64s")
149 ir.Syms.Typedmemmove = typecheck.LookupRuntimeFunc("typedmemmove")
150 ir.Syms.Udiv = typecheck.LookupRuntimeVar("udiv") // asm func with special ABI
151 ir.Syms.WriteBarrier = typecheck.LookupRuntimeVar("writeBarrier") // struct { bool; ... }
152 ir.Syms.Zerobase = typecheck.LookupRuntimeVar("zerobase")
154 if Arch.LinkArch.Family == sys.Wasm {
155 BoundsCheckFunc[ssa.BoundsIndex] = typecheck.LookupRuntimeFunc("goPanicIndex")
156 BoundsCheckFunc[ssa.BoundsIndexU] = typecheck.LookupRuntimeFunc("goPanicIndexU")
157 BoundsCheckFunc[ssa.BoundsSliceAlen] = typecheck.LookupRuntimeFunc("goPanicSliceAlen")
158 BoundsCheckFunc[ssa.BoundsSliceAlenU] = typecheck.LookupRuntimeFunc("goPanicSliceAlenU")
159 BoundsCheckFunc[ssa.BoundsSliceAcap] = typecheck.LookupRuntimeFunc("goPanicSliceAcap")
160 BoundsCheckFunc[ssa.BoundsSliceAcapU] = typecheck.LookupRuntimeFunc("goPanicSliceAcapU")
161 BoundsCheckFunc[ssa.BoundsSliceB] = typecheck.LookupRuntimeFunc("goPanicSliceB")
162 BoundsCheckFunc[ssa.BoundsSliceBU] = typecheck.LookupRuntimeFunc("goPanicSliceBU")
163 BoundsCheckFunc[ssa.BoundsSlice3Alen] = typecheck.LookupRuntimeFunc("goPanicSlice3Alen")
164 BoundsCheckFunc[ssa.BoundsSlice3AlenU] = typecheck.LookupRuntimeFunc("goPanicSlice3AlenU")
165 BoundsCheckFunc[ssa.BoundsSlice3Acap] = typecheck.LookupRuntimeFunc("goPanicSlice3Acap")
166 BoundsCheckFunc[ssa.BoundsSlice3AcapU] = typecheck.LookupRuntimeFunc("goPanicSlice3AcapU")
167 BoundsCheckFunc[ssa.BoundsSlice3B] = typecheck.LookupRuntimeFunc("goPanicSlice3B")
168 BoundsCheckFunc[ssa.BoundsSlice3BU] = typecheck.LookupRuntimeFunc("goPanicSlice3BU")
169 BoundsCheckFunc[ssa.BoundsSlice3C] = typecheck.LookupRuntimeFunc("goPanicSlice3C")
170 BoundsCheckFunc[ssa.BoundsSlice3CU] = typecheck.LookupRuntimeFunc("goPanicSlice3CU")
171 BoundsCheckFunc[ssa.BoundsConvert] = typecheck.LookupRuntimeFunc("goPanicSliceConvert")
173 BoundsCheckFunc[ssa.BoundsIndex] = typecheck.LookupRuntimeFunc("panicIndex")
174 BoundsCheckFunc[ssa.BoundsIndexU] = typecheck.LookupRuntimeFunc("panicIndexU")
175 BoundsCheckFunc[ssa.BoundsSliceAlen] = typecheck.LookupRuntimeFunc("panicSliceAlen")
176 BoundsCheckFunc[ssa.BoundsSliceAlenU] = typecheck.LookupRuntimeFunc("panicSliceAlenU")
177 BoundsCheckFunc[ssa.BoundsSliceAcap] = typecheck.LookupRuntimeFunc("panicSliceAcap")
178 BoundsCheckFunc[ssa.BoundsSliceAcapU] = typecheck.LookupRuntimeFunc("panicSliceAcapU")
179 BoundsCheckFunc[ssa.BoundsSliceB] = typecheck.LookupRuntimeFunc("panicSliceB")
180 BoundsCheckFunc[ssa.BoundsSliceBU] = typecheck.LookupRuntimeFunc("panicSliceBU")
181 BoundsCheckFunc[ssa.BoundsSlice3Alen] = typecheck.LookupRuntimeFunc("panicSlice3Alen")
182 BoundsCheckFunc[ssa.BoundsSlice3AlenU] = typecheck.LookupRuntimeFunc("panicSlice3AlenU")
183 BoundsCheckFunc[ssa.BoundsSlice3Acap] = typecheck.LookupRuntimeFunc("panicSlice3Acap")
184 BoundsCheckFunc[ssa.BoundsSlice3AcapU] = typecheck.LookupRuntimeFunc("panicSlice3AcapU")
185 BoundsCheckFunc[ssa.BoundsSlice3B] = typecheck.LookupRuntimeFunc("panicSlice3B")
186 BoundsCheckFunc[ssa.BoundsSlice3BU] = typecheck.LookupRuntimeFunc("panicSlice3BU")
187 BoundsCheckFunc[ssa.BoundsSlice3C] = typecheck.LookupRuntimeFunc("panicSlice3C")
188 BoundsCheckFunc[ssa.BoundsSlice3CU] = typecheck.LookupRuntimeFunc("panicSlice3CU")
189 BoundsCheckFunc[ssa.BoundsConvert] = typecheck.LookupRuntimeFunc("panicSliceConvert")
191 if Arch.LinkArch.PtrSize == 4 {
192 ExtendCheckFunc[ssa.BoundsIndex] = typecheck.LookupRuntimeVar("panicExtendIndex")
193 ExtendCheckFunc[ssa.BoundsIndexU] = typecheck.LookupRuntimeVar("panicExtendIndexU")
194 ExtendCheckFunc[ssa.BoundsSliceAlen] = typecheck.LookupRuntimeVar("panicExtendSliceAlen")
195 ExtendCheckFunc[ssa.BoundsSliceAlenU] = typecheck.LookupRuntimeVar("panicExtendSliceAlenU")
196 ExtendCheckFunc[ssa.BoundsSliceAcap] = typecheck.LookupRuntimeVar("panicExtendSliceAcap")
197 ExtendCheckFunc[ssa.BoundsSliceAcapU] = typecheck.LookupRuntimeVar("panicExtendSliceAcapU")
198 ExtendCheckFunc[ssa.BoundsSliceB] = typecheck.LookupRuntimeVar("panicExtendSliceB")
199 ExtendCheckFunc[ssa.BoundsSliceBU] = typecheck.LookupRuntimeVar("panicExtendSliceBU")
200 ExtendCheckFunc[ssa.BoundsSlice3Alen] = typecheck.LookupRuntimeVar("panicExtendSlice3Alen")
201 ExtendCheckFunc[ssa.BoundsSlice3AlenU] = typecheck.LookupRuntimeVar("panicExtendSlice3AlenU")
202 ExtendCheckFunc[ssa.BoundsSlice3Acap] = typecheck.LookupRuntimeVar("panicExtendSlice3Acap")
203 ExtendCheckFunc[ssa.BoundsSlice3AcapU] = typecheck.LookupRuntimeVar("panicExtendSlice3AcapU")
204 ExtendCheckFunc[ssa.BoundsSlice3B] = typecheck.LookupRuntimeVar("panicExtendSlice3B")
205 ExtendCheckFunc[ssa.BoundsSlice3BU] = typecheck.LookupRuntimeVar("panicExtendSlice3BU")
206 ExtendCheckFunc[ssa.BoundsSlice3C] = typecheck.LookupRuntimeVar("panicExtendSlice3C")
207 ExtendCheckFunc[ssa.BoundsSlice3CU] = typecheck.LookupRuntimeVar("panicExtendSlice3CU")
210 // Wasm (all asm funcs with special ABIs)
211 ir.Syms.WasmDiv = typecheck.LookupRuntimeVar("wasmDiv")
212 ir.Syms.WasmTruncS = typecheck.LookupRuntimeVar("wasmTruncS")
213 ir.Syms.WasmTruncU = typecheck.LookupRuntimeVar("wasmTruncU")
214 ir.Syms.SigPanic = typecheck.LookupRuntimeFunc("sigpanic")
217 // AbiForBodylessFuncStackMap returns the ABI for a bodyless function's stack map.
218 // This is not necessarily the ABI used to call it.
219 // Currently (1.17 dev) such a stack map is always ABI0;
220 // any ABI wrapper that is present is nosplit, hence a precise
221 // stack map is not needed there (the parameters survive only long
222 // enough to call the wrapped assembly function).
223 // This always returns a freshly copied ABI.
224 func AbiForBodylessFuncStackMap(fn *ir.Func) *abi.ABIConfig {
225 return ssaConfig.ABI0.Copy() // No idea what races will result, be safe
228 // abiForFunc implements ABI policy for a function, but does not return a copy of the ABI.
229 // Passing a nil function returns the default ABI based on experiment configuration.
230 func abiForFunc(fn *ir.Func, abi0, abi1 *abi.ABIConfig) *abi.ABIConfig {
231 if buildcfg.Experiment.RegabiArgs {
232 // Select the ABI based on the function's defining ABI.
239 case obj.ABIInternal:
240 // TODO(austin): Clean up the nomenclature here.
241 // It's not clear that "abi1" is ABIInternal.
244 base.Fatalf("function %v has unknown ABI %v", fn, fn.ABI)
245 panic("not reachable")
250 if fn.Pragma&ir.RegisterParams != 0 { // TODO(register args) remove after register abi is working
257 // dvarint writes a varint v to the funcdata in symbol x and returns the new offset.
258 func dvarint(x *obj.LSym, off int, v int64) int {
259 if v < 0 || v > 1e9 {
260 panic(fmt.Sprintf("dvarint: bad offset for funcdata - %v", v))
263 return objw.Uint8(x, off, uint8(v))
265 off = objw.Uint8(x, off, uint8((v&127)|128))
267 return objw.Uint8(x, off, uint8(v>>7))
269 off = objw.Uint8(x, off, uint8(((v>>7)&127)|128))
271 return objw.Uint8(x, off, uint8(v>>14))
273 off = objw.Uint8(x, off, uint8(((v>>14)&127)|128))
275 return objw.Uint8(x, off, uint8(v>>21))
277 off = objw.Uint8(x, off, uint8(((v>>21)&127)|128))
278 return objw.Uint8(x, off, uint8(v>>28))
281 // emitOpenDeferInfo emits FUNCDATA information about the defers in a function
282 // that is using open-coded defers. This funcdata is used to determine the active
283 // defers in a function and execute those defers during panic processing.
285 // The funcdata is all encoded in varints (since values will almost always be less than
286 // 128, but stack offsets could potentially be up to 2Gbyte). All "locations" (offsets)
287 // for stack variables are specified as the number of bytes below varp (pointer to the
288 // top of the local variables) for their starting address. The format is:
290 // - Offset of the deferBits variable
291 // - Offset of the first closure slot (the rest are laid out consecutively).
292 func (s *state) emitOpenDeferInfo() {
293 firstOffset := s.openDefers[0].closureNode.FrameOffset()
295 // Verify that cmpstackvarlt laid out the slots in order.
296 for i, r := range s.openDefers {
297 have := r.closureNode.FrameOffset()
298 want := firstOffset + int64(i)*int64(types.PtrSize)
300 base.FatalfAt(s.curfn.Pos(), "unexpected frame offset for open-coded defer slot #%v: have %v, want %v", i, have, want)
304 x := base.Ctxt.Lookup(s.curfn.LSym.Name + ".opendefer")
305 x.Set(obj.AttrContentAddressable, true)
306 s.curfn.LSym.Func().OpenCodedDeferInfo = x
309 off = dvarint(x, off, -s.deferBitsTemp.FrameOffset())
310 off = dvarint(x, off, -firstOffset)
313 // buildssa builds an SSA function for fn.
314 // worker indicates which of the backend workers is doing the processing.
315 func buildssa(fn *ir.Func, worker int) *ssa.Func {
316 name := ir.FuncName(fn)
318 if ssaDump != "" { // match either a simple name e.g. "(*Reader).Reset", package.name e.g. "compress/gzip.(*Reader).Reset", or subpackage name "gzip.(*Reader).Reset"
319 pkgDotName := base.Ctxt.Pkgpath + "." + name
320 printssa = name == ssaDump ||
321 strings.HasSuffix(pkgDotName, ssaDump) && (pkgDotName == ssaDump || strings.HasSuffix(pkgDotName, "/"+ssaDump))
323 var astBuf *bytes.Buffer
325 astBuf = &bytes.Buffer{}
326 ir.FDumpList(astBuf, "buildssa-body", fn.Body)
328 fmt.Println("generating SSA for", name)
329 fmt.Print(astBuf.String())
337 s.hasdefer = fn.HasDefer()
338 if fn.Pragma&ir.CgoUnsafeArgs != 0 {
339 s.cgoUnsafeArgs = true
341 s.checkPtrEnabled = ir.ShouldCheckPtr(fn, 1)
343 if base.Flag.Cfg.Instrumenting && fn.Pragma&ir.Norace == 0 && !fn.Linksym().ABIWrapper() {
344 if !base.Flag.Race || !objabi.LookupPkgSpecial(fn.Sym().Pkg.Path).NoRaceFunc {
345 s.instrumentMemory = true
348 s.instrumentEnterExit = true
354 log: printssa && ssaDumpStdout,
358 cache := &ssaCaches[worker]
361 s.f = ssaConfig.NewFunc(&fe, cache)
365 s.f.PrintOrHtmlSSA = printssa
366 if fn.Pragma&ir.Nosplit != 0 {
369 s.f.ABI0 = ssaConfig.ABI0.Copy() // Make a copy to avoid racy map operations in type-register-width cache.
370 s.f.ABI1 = ssaConfig.ABI1.Copy()
371 s.f.ABIDefault = abiForFunc(nil, s.f.ABI0, s.f.ABI1)
372 s.f.ABISelf = abiForFunc(fn, s.f.ABI0, s.f.ABI1)
374 s.panics = map[funcLine]*ssa.Block{}
375 s.softFloat = s.config.SoftFloat
377 // Allocate starting block
378 s.f.Entry = s.f.NewBlock(ssa.BlockPlain)
379 s.f.Entry.Pos = fn.Pos()
384 ssaDF = filepath.Join(ssaDir, base.Ctxt.Pkgpath+"."+name+".html")
385 ssaD := filepath.Dir(ssaDF)
386 os.MkdirAll(ssaD, 0755)
388 s.f.HTMLWriter = ssa.NewHTMLWriter(ssaDF, s.f, ssaDumpCFG)
389 // TODO: generate and print a mapping from nodes to values and blocks
390 dumpSourcesColumn(s.f.HTMLWriter, fn)
391 s.f.HTMLWriter.WriteAST("AST", astBuf)
394 // Allocate starting values
395 s.labels = map[string]*ssaLabel{}
396 s.fwdVars = map[ir.Node]*ssa.Value{}
397 s.startmem = s.entryNewValue0(ssa.OpInitMem, types.TypeMem)
399 s.hasOpenDefers = base.Flag.N == 0 && s.hasdefer && !s.curfn.OpenCodedDeferDisallowed()
401 case base.Debug.NoOpenDefer != 0:
402 s.hasOpenDefers = false
403 case s.hasOpenDefers && (base.Ctxt.Flag_shared || base.Ctxt.Flag_dynlink) && base.Ctxt.Arch.Name == "386":
404 // Don't support open-coded defers for 386 ONLY when using shared
405 // libraries, because there is extra code (added by rewriteToUseGot())
406 // preceding the deferreturn/ret code that we don't track correctly.
407 s.hasOpenDefers = false
409 if s.hasOpenDefers && s.instrumentEnterExit {
410 // Skip doing open defers if we need to instrument function
411 // returns for the race detector, since we will not generate that
412 // code in the case of the extra deferreturn/ret segment.
413 s.hasOpenDefers = false
416 // Similarly, skip if there are any heap-allocated result
417 // parameters that need to be copied back to their stack slots.
418 for _, f := range s.curfn.Type().Results() {
419 if !f.Nname.(*ir.Name).OnStack() {
420 s.hasOpenDefers = false
425 if s.hasOpenDefers &&
426 s.curfn.NumReturns*s.curfn.NumDefers > 15 {
427 // Since we are generating defer calls at every exit for
428 // open-coded defers, skip doing open-coded defers if there are
429 // too many returns (especially if there are multiple defers).
430 // Open-coded defers are most important for improving performance
431 // for smaller functions (which don't have many returns).
432 s.hasOpenDefers = false
435 s.sp = s.entryNewValue0(ssa.OpSP, types.Types[types.TUINTPTR]) // TODO: use generic pointer type (unsafe.Pointer?) instead
436 s.sb = s.entryNewValue0(ssa.OpSB, types.Types[types.TUINTPTR])
438 s.startBlock(s.f.Entry)
439 s.vars[memVar] = s.startmem
441 // Create the deferBits variable and stack slot. deferBits is a
442 // bitmask showing which of the open-coded defers in this function
443 // have been activated.
444 deferBitsTemp := typecheck.TempAt(src.NoXPos, s.curfn, types.Types[types.TUINT8])
445 deferBitsTemp.SetAddrtaken(true)
446 s.deferBitsTemp = deferBitsTemp
447 // For this value, AuxInt is initialized to zero by default
448 startDeferBits := s.entryNewValue0(ssa.OpConst8, types.Types[types.TUINT8])
449 s.vars[deferBitsVar] = startDeferBits
450 s.deferBitsAddr = s.addr(deferBitsTemp)
451 s.store(types.Types[types.TUINT8], s.deferBitsAddr, startDeferBits)
452 // Make sure that the deferBits stack slot is kept alive (for use
453 // by panics) and stores to deferBits are not eliminated, even if
454 // all checking code on deferBits in the function exit can be
455 // eliminated, because the defer statements were all
457 s.vars[memVar] = s.newValue1Apos(ssa.OpVarLive, types.TypeMem, deferBitsTemp, s.mem(), false)
460 var params *abi.ABIParamResultInfo
461 params = s.f.ABISelf.ABIAnalyze(fn.Type(), true)
463 // The backend's stackframe pass prunes away entries from the fn's
464 // Dcl list, including PARAMOUT nodes that correspond to output
465 // params passed in registers. Walk the Dcl list and capture these
466 // nodes to a side list, so that we'll have them available during
467 // DWARF-gen later on. See issue 48573 for more details.
468 var debugInfo ssa.FuncDebug
469 for _, n := range fn.Dcl {
470 if n.Class == ir.PPARAMOUT && n.IsOutputParamInRegisters() {
471 debugInfo.RegOutputParams = append(debugInfo.RegOutputParams, n)
474 fn.DebugInfo = &debugInfo
476 // Generate addresses of local declarations
477 s.decladdrs = map[*ir.Name]*ssa.Value{}
478 for _, n := range fn.Dcl {
481 // Be aware that blank and unnamed input parameters will not appear here, but do appear in the type
482 s.decladdrs[n] = s.entryNewValue2A(ssa.OpLocalAddr, types.NewPtr(n.Type()), n, s.sp, s.startmem)
484 s.decladdrs[n] = s.entryNewValue2A(ssa.OpLocalAddr, types.NewPtr(n.Type()), n, s.sp, s.startmem)
486 // processed at each use, to prevent Addr coming
489 s.Fatalf("local variable with class %v unimplemented", n.Class)
493 s.f.OwnAux = ssa.OwnAuxCall(fn.LSym, params)
495 // Populate SSAable arguments.
496 for _, n := range fn.Dcl {
497 if n.Class == ir.PPARAM {
499 v := s.newValue0A(ssa.OpArg, n.Type(), n)
501 s.addNamedValue(n, v) // This helps with debugging information, not needed for compilation itself.
502 } else { // address was taken AND/OR too large for SSA
503 paramAssignment := ssa.ParamAssignmentForArgName(s.f, n)
504 if len(paramAssignment.Registers) > 0 {
505 if ssa.CanSSA(n.Type()) { // SSA-able type, so address was taken -- receive value in OpArg, DO NOT bind to var, store immediately to memory.
506 v := s.newValue0A(ssa.OpArg, n.Type(), n)
507 s.store(n.Type(), s.decladdrs[n], v)
508 } else { // Too big for SSA.
509 // Brute force, and early, do a bunch of stores from registers
510 // TODO fix the nasty storeArgOrLoad recursion in ssa/expand_calls.go so this Just Works with store of a big Arg.
511 s.storeParameterRegsToStack(s.f.ABISelf, paramAssignment, n, s.decladdrs[n], false)
518 // Populate closure variables.
520 clo := s.entryNewValue0(ssa.OpGetClosurePtr, s.f.Config.Types.BytePtr)
521 offset := int64(types.PtrSize) // PtrSize to skip past function entry PC field
522 for _, n := range fn.ClosureVars {
525 typ = types.NewPtr(typ)
528 offset = types.RoundUp(offset, typ.Alignment())
529 ptr := s.newValue1I(ssa.OpOffPtr, types.NewPtr(typ), offset, clo)
532 // If n is a small variable captured by value, promote
533 // it to PAUTO so it can be converted to SSA.
535 // Note: While we never capture a variable by value if
536 // the user took its address, we may have generated
537 // runtime calls that did (#43701). Since we don't
538 // convert Addrtaken variables to SSA anyway, no point
539 // in promoting them either.
540 if n.Byval() && !n.Addrtaken() && ssa.CanSSA(n.Type()) {
542 fn.Dcl = append(fn.Dcl, n)
543 s.assign(n, s.load(n.Type(), ptr), false, 0)
548 ptr = s.load(typ, ptr)
550 s.setHeapaddr(fn.Pos(), n, ptr)
554 // Convert the AST-based IR to the SSA-based IR
555 if s.instrumentEnterExit {
556 s.rtcall(ir.Syms.Racefuncenter, true, nil, s.newValue0(ssa.OpGetCallerPC, types.Types[types.TUINTPTR]))
562 // fallthrough to exit
563 if s.curBlock != nil {
564 s.pushLine(fn.Endlineno)
569 for _, b := range s.f.Blocks {
570 if b.Pos != src.NoXPos {
571 s.updateUnsetPredPos(b)
575 s.f.HTMLWriter.WritePhase("before insert phis", "before insert phis")
579 // Main call to ssa package to compile function
584 if len(s.openDefers) != 0 {
585 s.emitOpenDeferInfo()
588 // Record incoming parameter spill information for morestack calls emitted in the assembler.
589 // This is done here, using all the parameters (used, partially used, and unused) because
590 // it mimics the behavior of the former ABI (everything stored) and because it's not 100%
591 // clear if naming conventions are respected in autogenerated code.
592 // TODO figure out exactly what's unused, don't spill it. Make liveness fine-grained, also.
593 for _, p := range params.InParams() {
594 typs, offs := p.RegisterTypesAndOffsets()
595 for i, t := range typs {
596 o := offs[i] // offset within parameter
597 fo := p.FrameOffset(params) // offset of parameter in frame
598 reg := ssa.ObjRegForAbiReg(p.Registers[i], s.f.Config)
599 s.f.RegArgs = append(s.f.RegArgs, ssa.Spill{Reg: reg, Offset: fo + o, Type: t})
606 func (s *state) storeParameterRegsToStack(abi *abi.ABIConfig, paramAssignment *abi.ABIParamAssignment, n *ir.Name, addr *ssa.Value, pointersOnly bool) {
607 typs, offs := paramAssignment.RegisterTypesAndOffsets()
608 for i, t := range typs {
609 if pointersOnly && !t.IsPtrShaped() {
612 r := paramAssignment.Registers[i]
614 op, reg := ssa.ArgOpAndRegisterFor(r, abi)
615 aux := &ssa.AuxNameOffset{Name: n, Offset: o}
616 v := s.newValue0I(op, t, reg)
618 p := s.newValue1I(ssa.OpOffPtr, types.NewPtr(t), o, addr)
623 // zeroResults zeros the return values at the start of the function.
624 // We need to do this very early in the function. Defer might stop a
625 // panic and show the return values as they exist at the time of
626 // panic. For precise stacks, the garbage collector assumes results
627 // are always live, so we need to zero them before any allocations,
628 // even allocations to move params/results to the heap.
629 func (s *state) zeroResults() {
630 for _, f := range s.curfn.Type().Results() {
631 n := f.Nname.(*ir.Name)
633 // The local which points to the return value is the
634 // thing that needs zeroing. This is already handled
635 // by a Needzero annotation in plive.go:(*liveness).epilogue.
638 // Zero the stack location containing f.
639 if typ := n.Type(); ssa.CanSSA(typ) {
640 s.assign(n, s.zeroVal(typ), false, 0)
642 if typ.HasPointers() {
643 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, n, s.mem())
645 s.zero(n.Type(), s.decladdrs[n])
650 // paramsToHeap produces code to allocate memory for heap-escaped parameters
651 // and to copy non-result parameters' values from the stack.
652 func (s *state) paramsToHeap() {
653 do := func(params []*types.Field) {
654 for _, f := range params {
656 continue // anonymous or blank parameter
658 n := f.Nname.(*ir.Name)
659 if ir.IsBlank(n) || n.OnStack() {
663 if n.Class == ir.PPARAM {
664 s.move(n.Type(), s.expr(n.Heapaddr), s.decladdrs[n])
669 typ := s.curfn.Type()
675 // newHeapaddr allocates heap memory for n and sets its heap address.
676 func (s *state) newHeapaddr(n *ir.Name) {
677 s.setHeapaddr(n.Pos(), n, s.newObject(n.Type(), nil))
680 // setHeapaddr allocates a new PAUTO variable to store ptr (which must be non-nil)
681 // and then sets it as n's heap address.
682 func (s *state) setHeapaddr(pos src.XPos, n *ir.Name, ptr *ssa.Value) {
683 if !ptr.Type.IsPtr() || !types.Identical(n.Type(), ptr.Type.Elem()) {
684 base.FatalfAt(n.Pos(), "setHeapaddr %L with type %v", n, ptr.Type)
687 // Declare variable to hold address.
688 sym := &types.Sym{Name: "&" + n.Sym().Name, Pkg: types.LocalPkg}
689 addr := s.curfn.NewLocal(pos, sym, types.NewPtr(n.Type()))
691 types.CalcSize(addr.Type())
693 if n.Class == ir.PPARAMOUT {
694 addr.SetIsOutputParamHeapAddr(true)
698 s.assign(addr, ptr, false, 0)
701 // newObject returns an SSA value denoting new(typ).
702 func (s *state) newObject(typ *types.Type, rtype *ssa.Value) *ssa.Value {
704 return s.newValue1A(ssa.OpAddr, types.NewPtr(typ), ir.Syms.Zerobase, s.sb)
707 rtype = s.reflectType(typ)
709 return s.rtcall(ir.Syms.Newobject, true, []*types.Type{types.NewPtr(typ)}, rtype)[0]
712 func (s *state) checkPtrAlignment(n *ir.ConvExpr, v *ssa.Value, count *ssa.Value) {
713 if !n.Type().IsPtr() {
714 s.Fatalf("expected pointer type: %v", n.Type())
716 elem, rtypeExpr := n.Type().Elem(), n.ElemRType
719 s.Fatalf("expected array type: %v", elem)
721 elem, rtypeExpr = elem.Elem(), n.ElemElemRType
724 // Casting from larger type to smaller one is ok, so for smallest type, do nothing.
725 if elem.Alignment() == 1 && (size == 0 || size == 1 || count == nil) {
729 count = s.constInt(types.Types[types.TUINTPTR], 1)
731 if count.Type.Size() != s.config.PtrSize {
732 s.Fatalf("expected count fit to a uintptr size, have: %d, want: %d", count.Type.Size(), s.config.PtrSize)
735 if rtypeExpr != nil {
736 rtype = s.expr(rtypeExpr)
738 rtype = s.reflectType(elem)
740 s.rtcall(ir.Syms.CheckPtrAlignment, true, nil, v, rtype, count)
743 // reflectType returns an SSA value representing a pointer to typ's
744 // reflection type descriptor.
745 func (s *state) reflectType(typ *types.Type) *ssa.Value {
746 // TODO(mdempsky): Make this Fatalf under Unified IR; frontend needs
747 // to supply RType expressions.
748 lsym := reflectdata.TypeLinksym(typ)
749 return s.entryNewValue1A(ssa.OpAddr, types.NewPtr(types.Types[types.TUINT8]), lsym, s.sb)
752 func dumpSourcesColumn(writer *ssa.HTMLWriter, fn *ir.Func) {
753 // Read sources of target function fn.
754 fname := base.Ctxt.PosTable.Pos(fn.Pos()).Filename()
755 targetFn, err := readFuncLines(fname, fn.Pos().Line(), fn.Endlineno.Line())
757 writer.Logf("cannot read sources for function %v: %v", fn, err)
760 // Read sources of inlined functions.
761 var inlFns []*ssa.FuncLines
762 for _, fi := range ssaDumpInlined {
764 fname := base.Ctxt.PosTable.Pos(fi.Pos()).Filename()
765 fnLines, err := readFuncLines(fname, fi.Pos().Line(), elno.Line())
767 writer.Logf("cannot read sources for inlined function %v: %v", fi, err)
770 inlFns = append(inlFns, fnLines)
773 sort.Sort(ssa.ByTopo(inlFns))
775 inlFns = append([]*ssa.FuncLines{targetFn}, inlFns...)
778 writer.WriteSources("sources", inlFns)
781 func readFuncLines(file string, start, end uint) (*ssa.FuncLines, error) {
782 f, err := os.Open(os.ExpandEnv(file))
789 scanner := bufio.NewScanner(f)
790 for scanner.Scan() && ln <= end {
792 lines = append(lines, scanner.Text())
796 return &ssa.FuncLines{Filename: file, StartLineno: start, Lines: lines}, nil
799 // updateUnsetPredPos propagates the earliest-value position information for b
800 // towards all of b's predecessors that need a position, and recurs on that
801 // predecessor if its position is updated. B should have a non-empty position.
802 func (s *state) updateUnsetPredPos(b *ssa.Block) {
803 if b.Pos == src.NoXPos {
804 s.Fatalf("Block %s should have a position", b)
806 bestPos := src.NoXPos
807 for _, e := range b.Preds {
812 if bestPos == src.NoXPos {
814 for _, v := range b.Values {
818 if v.Pos != src.NoXPos {
819 // Assume values are still in roughly textual order;
820 // TODO: could also seek minimum position?
827 s.updateUnsetPredPos(p) // We do not expect long chains of these, thus recursion is okay.
831 // Information about each open-coded defer.
832 type openDeferInfo struct {
833 // The node representing the call of the defer
835 // If defer call is closure call, the address of the argtmp where the
836 // closure is stored.
838 // The node representing the argtmp where the closure is stored - used for
839 // function, method, or interface call, to store a closure that panic
840 // processing can use for this defer.
845 // configuration (arch) information
848 // function we're building
855 labels map[string]*ssaLabel
857 // unlabeled break and continue statement tracking
858 breakTo *ssa.Block // current target for plain break statement
859 continueTo *ssa.Block // current target for plain continue statement
861 // current location where we're interpreting the AST
864 // variable assignments in the current block (map from variable symbol to ssa value)
865 // *Node is the unique identifier (an ONAME Node) for the variable.
866 // TODO: keep a single varnum map, then make all of these maps slices instead?
867 vars map[ir.Node]*ssa.Value
869 // fwdVars are variables that are used before they are defined in the current block.
870 // This map exists just to coalesce multiple references into a single FwdRef op.
871 // *Node is the unique identifier (an ONAME Node) for the variable.
872 fwdVars map[ir.Node]*ssa.Value
874 // all defined variables at the end of each block. Indexed by block ID.
875 defvars []map[ir.Node]*ssa.Value
877 // addresses of PPARAM and PPARAMOUT variables on the stack.
878 decladdrs map[*ir.Name]*ssa.Value
880 // starting values. Memory, stack pointer, and globals pointer
884 // value representing address of where deferBits autotmp is stored
885 deferBitsAddr *ssa.Value
886 deferBitsTemp *ir.Name
888 // line number stack. The current line number is top of stack
890 // the last line number processed; it may have been popped
893 // list of panic calls by function name and line number.
894 // Used to deduplicate panic calls.
895 panics map[funcLine]*ssa.Block
898 hasdefer bool // whether the function contains a defer statement
900 hasOpenDefers bool // whether we are doing open-coded defers
901 checkPtrEnabled bool // whether to insert checkptr instrumentation
902 instrumentEnterExit bool // whether to instrument function enter/exit
903 instrumentMemory bool // whether to instrument memory operations
905 // If doing open-coded defers, list of info about the defer calls in
906 // scanning order. Hence, at exit we should run these defers in reverse
907 // order of this list
908 openDefers []*openDeferInfo
909 // For open-coded defers, this is the beginning and end blocks of the last
910 // defer exit code that we have generated so far. We use these to share
911 // code between exits if the shareDeferExits option (disabled by default)
913 lastDeferExit *ssa.Block // Entry block of last defer exit code we generated
914 lastDeferFinalBlock *ssa.Block // Final block of last defer exit code we generated
915 lastDeferCount int // Number of defers encountered at that point
917 prevCall *ssa.Value // the previous call; use this to tie results to the call op.
920 type funcLine struct {
926 type ssaLabel struct {
927 target *ssa.Block // block identified by this label
928 breakTarget *ssa.Block // block to break to in control flow node identified by this label
929 continueTarget *ssa.Block // block to continue to in control flow node identified by this label
932 // label returns the label associated with sym, creating it if necessary.
933 func (s *state) label(sym *types.Sym) *ssaLabel {
934 lab := s.labels[sym.Name]
937 s.labels[sym.Name] = lab
942 func (s *state) Logf(msg string, args ...interface{}) { s.f.Logf(msg, args...) }
943 func (s *state) Log() bool { return s.f.Log() }
944 func (s *state) Fatalf(msg string, args ...interface{}) {
945 s.f.Frontend().Fatalf(s.peekPos(), msg, args...)
947 func (s *state) Warnl(pos src.XPos, msg string, args ...interface{}) { s.f.Warnl(pos, msg, args...) }
948 func (s *state) Debug_checknil() bool { return s.f.Frontend().Debug_checknil() }
950 func ssaMarker(name string) *ir.Name {
951 return ir.NewNameAt(base.Pos, &types.Sym{Name: name}, nil)
955 // marker node for the memory variable
956 memVar = ssaMarker("mem")
958 // marker nodes for temporary variables
959 ptrVar = ssaMarker("ptr")
960 lenVar = ssaMarker("len")
961 capVar = ssaMarker("cap")
962 typVar = ssaMarker("typ")
963 okVar = ssaMarker("ok")
964 deferBitsVar = ssaMarker("deferBits")
967 // startBlock sets the current block we're generating code in to b.
968 func (s *state) startBlock(b *ssa.Block) {
969 if s.curBlock != nil {
970 s.Fatalf("starting block %v when block %v has not ended", b, s.curBlock)
973 s.vars = map[ir.Node]*ssa.Value{}
974 for n := range s.fwdVars {
979 // endBlock marks the end of generating code for the current block.
980 // Returns the (former) current block. Returns nil if there is no current
981 // block, i.e. if no code flows to the current execution point.
982 func (s *state) endBlock() *ssa.Block {
987 for len(s.defvars) <= int(b.ID) {
988 s.defvars = append(s.defvars, nil)
990 s.defvars[b.ID] = s.vars
994 // Empty plain blocks get the line of their successor (handled after all blocks created),
995 // except for increment blocks in For statements (handled in ssa conversion of OFOR),
996 // and for blocks ending in GOTO/BREAK/CONTINUE.
1004 // pushLine pushes a line number on the line number stack.
1005 func (s *state) pushLine(line src.XPos) {
1006 if !line.IsKnown() {
1007 // the frontend may emit node with line number missing,
1008 // use the parent line number in this case.
1010 if base.Flag.K != 0 {
1011 base.Warn("buildssa: unknown position (line 0)")
1017 s.line = append(s.line, line)
1020 // popLine pops the top of the line number stack.
1021 func (s *state) popLine() {
1022 s.line = s.line[:len(s.line)-1]
1025 // peekPos peeks the top of the line number stack.
1026 func (s *state) peekPos() src.XPos {
1027 return s.line[len(s.line)-1]
1030 // newValue0 adds a new value with no arguments to the current block.
1031 func (s *state) newValue0(op ssa.Op, t *types.Type) *ssa.Value {
1032 return s.curBlock.NewValue0(s.peekPos(), op, t)
1035 // newValue0A adds a new value with no arguments and an aux value to the current block.
1036 func (s *state) newValue0A(op ssa.Op, t *types.Type, aux ssa.Aux) *ssa.Value {
1037 return s.curBlock.NewValue0A(s.peekPos(), op, t, aux)
1040 // newValue0I adds a new value with no arguments and an auxint value to the current block.
1041 func (s *state) newValue0I(op ssa.Op, t *types.Type, auxint int64) *ssa.Value {
1042 return s.curBlock.NewValue0I(s.peekPos(), op, t, auxint)
1045 // newValue1 adds a new value with one argument to the current block.
1046 func (s *state) newValue1(op ssa.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
1047 return s.curBlock.NewValue1(s.peekPos(), op, t, arg)
1050 // newValue1A adds a new value with one argument and an aux value to the current block.
1051 func (s *state) newValue1A(op ssa.Op, t *types.Type, aux ssa.Aux, arg *ssa.Value) *ssa.Value {
1052 return s.curBlock.NewValue1A(s.peekPos(), op, t, aux, arg)
1055 // newValue1Apos adds a new value with one argument and an aux value to the current block.
1056 // isStmt determines whether the created values may be a statement or not
1057 // (i.e., false means never, yes means maybe).
1058 func (s *state) newValue1Apos(op ssa.Op, t *types.Type, aux ssa.Aux, arg *ssa.Value, isStmt bool) *ssa.Value {
1060 return s.curBlock.NewValue1A(s.peekPos(), op, t, aux, arg)
1062 return s.curBlock.NewValue1A(s.peekPos().WithNotStmt(), op, t, aux, arg)
1065 // newValue1I adds a new value with one argument and an auxint value to the current block.
1066 func (s *state) newValue1I(op ssa.Op, t *types.Type, aux int64, arg *ssa.Value) *ssa.Value {
1067 return s.curBlock.NewValue1I(s.peekPos(), op, t, aux, arg)
1070 // newValue2 adds a new value with two arguments to the current block.
1071 func (s *state) newValue2(op ssa.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
1072 return s.curBlock.NewValue2(s.peekPos(), op, t, arg0, arg1)
1075 // newValue2A adds a new value with two arguments and an aux value to the current block.
1076 func (s *state) newValue2A(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1 *ssa.Value) *ssa.Value {
1077 return s.curBlock.NewValue2A(s.peekPos(), op, t, aux, arg0, arg1)
1080 // newValue2Apos adds a new value with two arguments and an aux value to the current block.
1081 // isStmt determines whether the created values may be a statement or not
1082 // (i.e., false means never, yes means maybe).
1083 func (s *state) newValue2Apos(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1 *ssa.Value, isStmt bool) *ssa.Value {
1085 return s.curBlock.NewValue2A(s.peekPos(), op, t, aux, arg0, arg1)
1087 return s.curBlock.NewValue2A(s.peekPos().WithNotStmt(), op, t, aux, arg0, arg1)
1090 // newValue2I adds a new value with two arguments and an auxint value to the current block.
1091 func (s *state) newValue2I(op ssa.Op, t *types.Type, aux int64, arg0, arg1 *ssa.Value) *ssa.Value {
1092 return s.curBlock.NewValue2I(s.peekPos(), op, t, aux, arg0, arg1)
1095 // newValue3 adds a new value with three arguments to the current block.
1096 func (s *state) newValue3(op ssa.Op, t *types.Type, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
1097 return s.curBlock.NewValue3(s.peekPos(), op, t, arg0, arg1, arg2)
1100 // newValue3I adds a new value with three arguments and an auxint value to the current block.
1101 func (s *state) newValue3I(op ssa.Op, t *types.Type, aux int64, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
1102 return s.curBlock.NewValue3I(s.peekPos(), op, t, aux, arg0, arg1, arg2)
1105 // newValue3A adds a new value with three arguments and an aux value to the current block.
1106 func (s *state) newValue3A(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1, arg2 *ssa.Value) *ssa.Value {
1107 return s.curBlock.NewValue3A(s.peekPos(), op, t, aux, arg0, arg1, arg2)
1110 // newValue3Apos adds a new value with three arguments and an aux value to the current block.
1111 // isStmt determines whether the created values may be a statement or not
1112 // (i.e., false means never, yes means maybe).
1113 func (s *state) newValue3Apos(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1, arg2 *ssa.Value, isStmt bool) *ssa.Value {
1115 return s.curBlock.NewValue3A(s.peekPos(), op, t, aux, arg0, arg1, arg2)
1117 return s.curBlock.NewValue3A(s.peekPos().WithNotStmt(), op, t, aux, arg0, arg1, arg2)
1120 // newValue4 adds a new value with four arguments to the current block.
1121 func (s *state) newValue4(op ssa.Op, t *types.Type, arg0, arg1, arg2, arg3 *ssa.Value) *ssa.Value {
1122 return s.curBlock.NewValue4(s.peekPos(), op, t, arg0, arg1, arg2, arg3)
1125 // newValue4I adds a new value with four arguments and an auxint value to the current block.
1126 func (s *state) newValue4I(op ssa.Op, t *types.Type, aux int64, arg0, arg1, arg2, arg3 *ssa.Value) *ssa.Value {
1127 return s.curBlock.NewValue4I(s.peekPos(), op, t, aux, arg0, arg1, arg2, arg3)
1130 func (s *state) entryBlock() *ssa.Block {
1132 if base.Flag.N > 0 && s.curBlock != nil {
1133 // If optimizations are off, allocate in current block instead. Since with -N
1134 // we're not doing the CSE or tighten passes, putting lots of stuff in the
1135 // entry block leads to O(n^2) entries in the live value map during regalloc.
1142 // entryNewValue0 adds a new value with no arguments to the entry block.
1143 func (s *state) entryNewValue0(op ssa.Op, t *types.Type) *ssa.Value {
1144 return s.entryBlock().NewValue0(src.NoXPos, op, t)
1147 // entryNewValue0A adds a new value with no arguments and an aux value to the entry block.
1148 func (s *state) entryNewValue0A(op ssa.Op, t *types.Type, aux ssa.Aux) *ssa.Value {
1149 return s.entryBlock().NewValue0A(src.NoXPos, op, t, aux)
1152 // entryNewValue1 adds a new value with one argument to the entry block.
1153 func (s *state) entryNewValue1(op ssa.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
1154 return s.entryBlock().NewValue1(src.NoXPos, op, t, arg)
1157 // entryNewValue1I adds a new value with one argument and an auxint value to the entry block.
1158 func (s *state) entryNewValue1I(op ssa.Op, t *types.Type, auxint int64, arg *ssa.Value) *ssa.Value {
1159 return s.entryBlock().NewValue1I(src.NoXPos, op, t, auxint, arg)
1162 // entryNewValue1A adds a new value with one argument and an aux value to the entry block.
1163 func (s *state) entryNewValue1A(op ssa.Op, t *types.Type, aux ssa.Aux, arg *ssa.Value) *ssa.Value {
1164 return s.entryBlock().NewValue1A(src.NoXPos, op, t, aux, arg)
1167 // entryNewValue2 adds a new value with two arguments to the entry block.
1168 func (s *state) entryNewValue2(op ssa.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
1169 return s.entryBlock().NewValue2(src.NoXPos, op, t, arg0, arg1)
1172 // entryNewValue2A adds a new value with two arguments and an aux value to the entry block.
1173 func (s *state) entryNewValue2A(op ssa.Op, t *types.Type, aux ssa.Aux, arg0, arg1 *ssa.Value) *ssa.Value {
1174 return s.entryBlock().NewValue2A(src.NoXPos, op, t, aux, arg0, arg1)
1177 // const* routines add a new const value to the entry block.
1178 func (s *state) constSlice(t *types.Type) *ssa.Value {
1179 return s.f.ConstSlice(t)
1181 func (s *state) constInterface(t *types.Type) *ssa.Value {
1182 return s.f.ConstInterface(t)
1184 func (s *state) constNil(t *types.Type) *ssa.Value { return s.f.ConstNil(t) }
1185 func (s *state) constEmptyString(t *types.Type) *ssa.Value {
1186 return s.f.ConstEmptyString(t)
1188 func (s *state) constBool(c bool) *ssa.Value {
1189 return s.f.ConstBool(types.Types[types.TBOOL], c)
1191 func (s *state) constInt8(t *types.Type, c int8) *ssa.Value {
1192 return s.f.ConstInt8(t, c)
1194 func (s *state) constInt16(t *types.Type, c int16) *ssa.Value {
1195 return s.f.ConstInt16(t, c)
1197 func (s *state) constInt32(t *types.Type, c int32) *ssa.Value {
1198 return s.f.ConstInt32(t, c)
1200 func (s *state) constInt64(t *types.Type, c int64) *ssa.Value {
1201 return s.f.ConstInt64(t, c)
1203 func (s *state) constFloat32(t *types.Type, c float64) *ssa.Value {
1204 return s.f.ConstFloat32(t, c)
1206 func (s *state) constFloat64(t *types.Type, c float64) *ssa.Value {
1207 return s.f.ConstFloat64(t, c)
1209 func (s *state) constInt(t *types.Type, c int64) *ssa.Value {
1210 if s.config.PtrSize == 8 {
1211 return s.constInt64(t, c)
1213 if int64(int32(c)) != c {
1214 s.Fatalf("integer constant too big %d", c)
1216 return s.constInt32(t, int32(c))
1218 func (s *state) constOffPtrSP(t *types.Type, c int64) *ssa.Value {
1219 return s.f.ConstOffPtrSP(t, c, s.sp)
1222 // newValueOrSfCall* are wrappers around newValue*, which may create a call to a
1223 // soft-float runtime function instead (when emitting soft-float code).
1224 func (s *state) newValueOrSfCall1(op ssa.Op, t *types.Type, arg *ssa.Value) *ssa.Value {
1226 if c, ok := s.sfcall(op, arg); ok {
1230 return s.newValue1(op, t, arg)
1232 func (s *state) newValueOrSfCall2(op ssa.Op, t *types.Type, arg0, arg1 *ssa.Value) *ssa.Value {
1234 if c, ok := s.sfcall(op, arg0, arg1); ok {
1238 return s.newValue2(op, t, arg0, arg1)
1241 type instrumentKind uint8
1244 instrumentRead = iota
1249 func (s *state) instrument(t *types.Type, addr *ssa.Value, kind instrumentKind) {
1250 s.instrument2(t, addr, nil, kind)
1253 // instrumentFields instruments a read/write operation on addr.
1254 // If it is instrumenting for MSAN or ASAN and t is a struct type, it instruments
1255 // operation for each field, instead of for the whole struct.
1256 func (s *state) instrumentFields(t *types.Type, addr *ssa.Value, kind instrumentKind) {
1257 if !(base.Flag.MSan || base.Flag.ASan) || !t.IsStruct() {
1258 s.instrument(t, addr, kind)
1261 for _, f := range t.Fields() {
1262 if f.Sym.IsBlank() {
1265 offptr := s.newValue1I(ssa.OpOffPtr, types.NewPtr(f.Type), f.Offset, addr)
1266 s.instrumentFields(f.Type, offptr, kind)
1270 func (s *state) instrumentMove(t *types.Type, dst, src *ssa.Value) {
1272 s.instrument2(t, dst, src, instrumentMove)
1274 s.instrument(t, src, instrumentRead)
1275 s.instrument(t, dst, instrumentWrite)
1279 func (s *state) instrument2(t *types.Type, addr, addr2 *ssa.Value, kind instrumentKind) {
1280 if !s.instrumentMemory {
1286 return // can't race on zero-sized things
1289 if ssa.IsSanitizerSafeAddr(addr) {
1296 if addr2 != nil && kind != instrumentMove {
1297 panic("instrument2: non-nil addr2 for non-move instrumentation")
1302 case instrumentRead:
1303 fn = ir.Syms.Msanread
1304 case instrumentWrite:
1305 fn = ir.Syms.Msanwrite
1306 case instrumentMove:
1307 fn = ir.Syms.Msanmove
1309 panic("unreachable")
1312 } else if base.Flag.Race && t.NumComponents(types.CountBlankFields) > 1 {
1313 // for composite objects we have to write every address
1314 // because a write might happen to any subobject.
1315 // composites with only one element don't have subobjects, though.
1317 case instrumentRead:
1318 fn = ir.Syms.Racereadrange
1319 case instrumentWrite:
1320 fn = ir.Syms.Racewriterange
1322 panic("unreachable")
1325 } else if base.Flag.Race {
1326 // for non-composite objects we can write just the start
1327 // address, as any write must write the first byte.
1329 case instrumentRead:
1330 fn = ir.Syms.Raceread
1331 case instrumentWrite:
1332 fn = ir.Syms.Racewrite
1334 panic("unreachable")
1336 } else if base.Flag.ASan {
1338 case instrumentRead:
1339 fn = ir.Syms.Asanread
1340 case instrumentWrite:
1341 fn = ir.Syms.Asanwrite
1343 panic("unreachable")
1347 panic("unreachable")
1350 args := []*ssa.Value{addr}
1352 args = append(args, addr2)
1355 args = append(args, s.constInt(types.Types[types.TUINTPTR], w))
1357 s.rtcall(fn, true, nil, args...)
1360 func (s *state) load(t *types.Type, src *ssa.Value) *ssa.Value {
1361 s.instrumentFields(t, src, instrumentRead)
1362 return s.rawLoad(t, src)
1365 func (s *state) rawLoad(t *types.Type, src *ssa.Value) *ssa.Value {
1366 return s.newValue2(ssa.OpLoad, t, src, s.mem())
1369 func (s *state) store(t *types.Type, dst, val *ssa.Value) {
1370 s.vars[memVar] = s.newValue3A(ssa.OpStore, types.TypeMem, t, dst, val, s.mem())
1373 func (s *state) zero(t *types.Type, dst *ssa.Value) {
1374 s.instrument(t, dst, instrumentWrite)
1375 store := s.newValue2I(ssa.OpZero, types.TypeMem, t.Size(), dst, s.mem())
1377 s.vars[memVar] = store
1380 func (s *state) move(t *types.Type, dst, src *ssa.Value) {
1381 s.moveWhichMayOverlap(t, dst, src, false)
1383 func (s *state) moveWhichMayOverlap(t *types.Type, dst, src *ssa.Value, mayOverlap bool) {
1384 s.instrumentMove(t, dst, src)
1385 if mayOverlap && t.IsArray() && t.NumElem() > 1 && !ssa.IsInlinableMemmove(dst, src, t.Size(), s.f.Config) {
1386 // Normally, when moving Go values of type T from one location to another,
1387 // we don't need to worry about partial overlaps. The two Ts must either be
1388 // in disjoint (nonoverlapping) memory or in exactly the same location.
1389 // There are 2 cases where this isn't true:
1390 // 1) Using unsafe you can arrange partial overlaps.
1391 // 2) Since Go 1.17, you can use a cast from a slice to a ptr-to-array.
1392 // https://go.dev/ref/spec#Conversions_from_slice_to_array_pointer
1393 // This feature can be used to construct partial overlaps of array types.
1395 // p := (*[2]int)(a[:])
1396 // q := (*[2]int)(a[1:])
1398 // We don't care about solving 1. Or at least, we haven't historically
1399 // and no one has complained.
1400 // For 2, we need to ensure that if there might be partial overlap,
1401 // then we can't use OpMove; we must use memmove instead.
1402 // (memmove handles partial overlap by copying in the correct
1403 // direction. OpMove does not.)
1405 // Note that we have to be careful here not to introduce a call when
1406 // we're marshaling arguments to a call or unmarshaling results from a call.
1407 // Cases where this is happening must pass mayOverlap to false.
1408 // (Currently this only happens when unmarshaling results of a call.)
1409 if t.HasPointers() {
1410 s.rtcall(ir.Syms.Typedmemmove, true, nil, s.reflectType(t), dst, src)
1411 // We would have otherwise implemented this move with straightline code,
1412 // including a write barrier. Pretend we issue a write barrier here,
1413 // so that the write barrier tests work. (Otherwise they'd need to know
1414 // the details of IsInlineableMemmove.)
1415 s.curfn.SetWBPos(s.peekPos())
1417 s.rtcall(ir.Syms.Memmove, true, nil, dst, src, s.constInt(types.Types[types.TUINTPTR], t.Size()))
1419 ssa.LogLargeCopy(s.f.Name, s.peekPos(), t.Size())
1422 store := s.newValue3I(ssa.OpMove, types.TypeMem, t.Size(), dst, src, s.mem())
1424 s.vars[memVar] = store
1427 // stmtList converts the statement list n to SSA and adds it to s.
1428 func (s *state) stmtList(l ir.Nodes) {
1429 for _, n := range l {
1434 // stmt converts the statement n to SSA and adds it to s.
1435 func (s *state) stmt(n ir.Node) {
1439 // If s.curBlock is nil, and n isn't a label (which might have an associated goto somewhere),
1440 // then this code is dead. Stop here.
1441 if s.curBlock == nil && n.Op() != ir.OLABEL {
1445 s.stmtList(n.Init())
1449 n := n.(*ir.BlockStmt)
1452 case ir.OFALL: // no-op
1454 // Expression statements
1456 n := n.(*ir.CallExpr)
1457 if ir.IsIntrinsicCall(n) {
1464 n := n.(*ir.CallExpr)
1465 s.callResult(n, callNormal)
1466 if n.Op() == ir.OCALLFUNC && n.X.Op() == ir.ONAME && n.X.(*ir.Name).Class == ir.PFUNC {
1467 if fn := n.X.Sym().Name; base.Flag.CompilingRuntime && fn == "throw" ||
1468 n.X.Sym().Pkg == ir.Pkgs.Runtime && (fn == "throwinit" || fn == "gopanic" || fn == "panicwrap" || fn == "block" || fn == "panicmakeslicelen" || fn == "panicmakeslicecap" || fn == "panicunsafeslicelen" || fn == "panicunsafeslicenilptr" || fn == "panicunsafestringlen" || fn == "panicunsafestringnilptr") {
1471 b.Kind = ssa.BlockExit
1473 // TODO: never rewrite OPANIC to OCALLFUNC in the
1474 // first place. Need to wait until all backends
1479 n := n.(*ir.GoDeferStmt)
1480 if base.Debug.Defer > 0 {
1481 var defertype string
1482 if s.hasOpenDefers {
1483 defertype = "open-coded"
1484 } else if n.Esc() == ir.EscNever {
1485 defertype = "stack-allocated"
1487 defertype = "heap-allocated"
1489 base.WarnfAt(n.Pos(), "%s defer", defertype)
1491 if s.hasOpenDefers {
1492 s.openDeferRecord(n.Call.(*ir.CallExpr))
1495 if n.Esc() == ir.EscNever && n.DeferAt == nil {
1498 s.call(n.Call.(*ir.CallExpr), d, false, n.DeferAt)
1501 n := n.(*ir.GoDeferStmt)
1502 s.callResult(n.Call.(*ir.CallExpr), callGo)
1504 case ir.OAS2DOTTYPE:
1505 n := n.(*ir.AssignListStmt)
1506 var res, resok *ssa.Value
1507 if n.Rhs[0].Op() == ir.ODOTTYPE2 {
1508 res, resok = s.dottype(n.Rhs[0].(*ir.TypeAssertExpr), true)
1510 res, resok = s.dynamicDottype(n.Rhs[0].(*ir.DynamicTypeAssertExpr), true)
1513 if !ssa.CanSSA(n.Rhs[0].Type()) {
1514 if res.Op != ssa.OpLoad {
1515 s.Fatalf("dottype of non-load")
1518 if res.Args[1] != mem {
1519 s.Fatalf("memory no longer live from 2-result dottype load")
1524 s.assign(n.Lhs[0], res, deref, 0)
1525 s.assign(n.Lhs[1], resok, false, 0)
1529 // We come here only when it is an intrinsic call returning two values.
1530 n := n.(*ir.AssignListStmt)
1531 call := n.Rhs[0].(*ir.CallExpr)
1532 if !ir.IsIntrinsicCall(call) {
1533 s.Fatalf("non-intrinsic AS2FUNC not expanded %v", call)
1535 v := s.intrinsicCall(call)
1536 v1 := s.newValue1(ssa.OpSelect0, n.Lhs[0].Type(), v)
1537 v2 := s.newValue1(ssa.OpSelect1, n.Lhs[1].Type(), v)
1538 s.assign(n.Lhs[0], v1, false, 0)
1539 s.assign(n.Lhs[1], v2, false, 0)
1544 if v := n.X; v.Esc() == ir.EscHeap {
1549 n := n.(*ir.LabelStmt)
1552 // Nothing to do because the label isn't targetable. See issue 52278.
1557 // The label might already have a target block via a goto.
1558 if lab.target == nil {
1559 lab.target = s.f.NewBlock(ssa.BlockPlain)
1562 // Go to that label.
1563 // (We pretend "label:" is preceded by "goto label", unless the predecessor is unreachable.)
1564 if s.curBlock != nil {
1566 b.AddEdgeTo(lab.target)
1568 s.startBlock(lab.target)
1571 n := n.(*ir.BranchStmt)
1575 if lab.target == nil {
1576 lab.target = s.f.NewBlock(ssa.BlockPlain)
1580 b.Pos = s.lastPos.WithIsStmt() // Do this even if b is an empty block.
1581 b.AddEdgeTo(lab.target)
1584 n := n.(*ir.AssignStmt)
1585 if n.X == n.Y && n.X.Op() == ir.ONAME {
1586 // An x=x assignment. No point in doing anything
1587 // here. In addition, skipping this assignment
1588 // prevents generating:
1591 // which is bad because x is incorrectly considered
1592 // dead before the vardef. See issue #14904.
1596 // mayOverlap keeps track of whether the LHS and RHS might
1597 // refer to partially overlapping memory. Partial overlapping can
1598 // only happen for arrays, see the comment in moveWhichMayOverlap.
1600 // If both sides of the assignment are not dereferences, then partial
1601 // overlap can't happen. Partial overlap can only occur only when the
1602 // arrays referenced are strictly smaller parts of the same base array.
1603 // If one side of the assignment is a full array, then partial overlap
1604 // can't happen. (The arrays are either disjoint or identical.)
1605 mayOverlap := n.X.Op() == ir.ODEREF && (n.Y != nil && n.Y.Op() == ir.ODEREF)
1606 if n.Y != nil && n.Y.Op() == ir.ODEREF {
1607 p := n.Y.(*ir.StarExpr).X
1608 for p.Op() == ir.OCONVNOP {
1609 p = p.(*ir.ConvExpr).X
1611 if p.Op() == ir.OSPTR && p.(*ir.UnaryExpr).X.Type().IsString() {
1612 // Pointer fields of strings point to unmodifiable memory.
1613 // That memory can't overlap with the memory being written.
1622 case ir.OSTRUCTLIT, ir.OARRAYLIT, ir.OSLICELIT:
1623 // All literals with nonzero fields have already been
1624 // rewritten during walk. Any that remain are just T{}
1625 // or equivalents. Use the zero value.
1626 if !ir.IsZero(rhs) {
1627 s.Fatalf("literal with nonzero value in SSA: %v", rhs)
1631 rhs := rhs.(*ir.CallExpr)
1632 // Check whether we're writing the result of an append back to the same slice.
1633 // If so, we handle it specially to avoid write barriers on the fast
1634 // (non-growth) path.
1635 if !ir.SameSafeExpr(n.X, rhs.Args[0]) || base.Flag.N != 0 {
1638 // If the slice can be SSA'd, it'll be on the stack,
1639 // so there will be no write barriers,
1640 // so there's no need to attempt to prevent them.
1642 if base.Debug.Append > 0 { // replicating old diagnostic message
1643 base.WarnfAt(n.Pos(), "append: len-only update (in local slice)")
1647 if base.Debug.Append > 0 {
1648 base.WarnfAt(n.Pos(), "append: len-only update")
1655 if ir.IsBlank(n.X) {
1657 // Just evaluate rhs for side-effects.
1672 deref := !ssa.CanSSA(t)
1675 r = nil // Signal assign to use OpZero.
1688 if rhs != nil && (rhs.Op() == ir.OSLICE || rhs.Op() == ir.OSLICE3 || rhs.Op() == ir.OSLICESTR) && ir.SameSafeExpr(rhs.(*ir.SliceExpr).X, n.X) {
1689 // We're assigning a slicing operation back to its source.
1690 // Don't write back fields we aren't changing. See issue #14855.
1691 rhs := rhs.(*ir.SliceExpr)
1692 i, j, k := rhs.Low, rhs.High, rhs.Max
1693 if i != nil && (i.Op() == ir.OLITERAL && i.Val().Kind() == constant.Int && ir.Int64Val(i) == 0) {
1694 // [0:...] is the same as [:...]
1697 // TODO: detect defaults for len/cap also.
1698 // Currently doesn't really work because (*p)[:len(*p)] appears here as:
1701 // if j != nil && (j.Op == OLEN && SameSafeExpr(j.Left, n.Left)) {
1704 // if k != nil && (k.Op == OCAP && SameSafeExpr(k.Left, n.Left)) {
1718 s.assignWhichMayOverlap(n.X, r, deref, skip, mayOverlap)
1722 if ir.IsConst(n.Cond, constant.Bool) {
1723 s.stmtList(n.Cond.Init())
1724 if ir.BoolVal(n.Cond) {
1732 bEnd := s.f.NewBlock(ssa.BlockPlain)
1737 var bThen *ssa.Block
1738 if len(n.Body) != 0 {
1739 bThen = s.f.NewBlock(ssa.BlockPlain)
1743 var bElse *ssa.Block
1744 if len(n.Else) != 0 {
1745 bElse = s.f.NewBlock(ssa.BlockPlain)
1749 s.condBranch(n.Cond, bThen, bElse, likely)
1751 if len(n.Body) != 0 {
1754 if b := s.endBlock(); b != nil {
1758 if len(n.Else) != 0 {
1761 if b := s.endBlock(); b != nil {
1768 n := n.(*ir.ReturnStmt)
1769 s.stmtList(n.Results)
1771 b.Pos = s.lastPos.WithIsStmt()
1774 n := n.(*ir.TailCallStmt)
1775 s.callResult(n.Call, callTail)
1778 b.Kind = ssa.BlockRetJmp // could use BlockExit. BlockRetJmp is mostly for clarity.
1781 case ir.OCONTINUE, ir.OBREAK:
1782 n := n.(*ir.BranchStmt)
1785 // plain break/continue
1793 // labeled break/continue; look up the target
1798 to = lab.continueTarget
1800 to = lab.breakTarget
1805 b.Pos = s.lastPos.WithIsStmt() // Do this even if b is an empty block.
1809 // OFOR: for Ninit; Left; Right { Nbody }
1810 // cond (Left); body (Nbody); incr (Right)
1811 n := n.(*ir.ForStmt)
1812 base.Assert(!n.DistinctVars) // Should all be rewritten before escape analysis
1813 bCond := s.f.NewBlock(ssa.BlockPlain)
1814 bBody := s.f.NewBlock(ssa.BlockPlain)
1815 bIncr := s.f.NewBlock(ssa.BlockPlain)
1816 bEnd := s.f.NewBlock(ssa.BlockPlain)
1818 // ensure empty for loops have correct position; issue #30167
1821 // first, jump to condition test
1825 // generate code to test condition
1828 s.condBranch(n.Cond, bBody, bEnd, 1)
1831 b.Kind = ssa.BlockPlain
1835 // set up for continue/break in body
1836 prevContinue := s.continueTo
1837 prevBreak := s.breakTo
1838 s.continueTo = bIncr
1841 if sym := n.Label; sym != nil {
1844 lab.continueTarget = bIncr
1845 lab.breakTarget = bEnd
1852 // tear down continue/break
1853 s.continueTo = prevContinue
1854 s.breakTo = prevBreak
1856 lab.continueTarget = nil
1857 lab.breakTarget = nil
1860 // done with body, goto incr
1861 if b := s.endBlock(); b != nil {
1870 if b := s.endBlock(); b != nil {
1872 // It can happen that bIncr ends in a block containing only VARKILL,
1873 // and that muddles the debugging experience.
1874 if b.Pos == src.NoXPos {
1881 case ir.OSWITCH, ir.OSELECT:
1882 // These have been mostly rewritten by the front end into their Nbody fields.
1883 // Our main task is to correctly hook up any break statements.
1884 bEnd := s.f.NewBlock(ssa.BlockPlain)
1886 prevBreak := s.breakTo
1890 if n.Op() == ir.OSWITCH {
1891 n := n.(*ir.SwitchStmt)
1895 n := n.(*ir.SelectStmt)
1904 lab.breakTarget = bEnd
1907 // generate body code
1910 s.breakTo = prevBreak
1912 lab.breakTarget = nil
1915 // walk adds explicit OBREAK nodes to the end of all reachable code paths.
1916 // If we still have a current block here, then mark it unreachable.
1917 if s.curBlock != nil {
1920 b.Kind = ssa.BlockExit
1926 n := n.(*ir.JumpTableStmt)
1928 // Make blocks we'll need.
1929 jt := s.f.NewBlock(ssa.BlockJumpTable)
1930 bEnd := s.f.NewBlock(ssa.BlockPlain)
1932 // The only thing that needs evaluating is the index we're looking up.
1933 idx := s.expr(n.Idx)
1934 unsigned := idx.Type.IsUnsigned()
1936 // Extend so we can do everything in uintptr arithmetic.
1937 t := types.Types[types.TUINTPTR]
1938 idx = s.conv(nil, idx, idx.Type, t)
1940 // The ending condition for the current block decides whether we'll use
1941 // the jump table at all.
1942 // We check that min <= idx <= max and jump around the jump table
1943 // if that test fails.
1944 // We implement min <= idx <= max with 0 <= idx-min <= max-min, because
1945 // we'll need idx-min anyway as the control value for the jump table.
1948 min, _ = constant.Uint64Val(n.Cases[0])
1949 max, _ = constant.Uint64Val(n.Cases[len(n.Cases)-1])
1951 mn, _ := constant.Int64Val(n.Cases[0])
1952 mx, _ := constant.Int64Val(n.Cases[len(n.Cases)-1])
1956 // Compare idx-min with max-min, to see if we can use the jump table.
1957 idx = s.newValue2(s.ssaOp(ir.OSUB, t), t, idx, s.uintptrConstant(min))
1958 width := s.uintptrConstant(max - min)
1959 cmp := s.newValue2(s.ssaOp(ir.OLE, t), types.Types[types.TBOOL], idx, width)
1961 b.Kind = ssa.BlockIf
1963 b.AddEdgeTo(jt) // in range - use jump table
1964 b.AddEdgeTo(bEnd) // out of range - no case in the jump table will trigger
1965 b.Likely = ssa.BranchLikely // TODO: assumes missing the table entirely is unlikely. True?
1967 // Build jump table block.
1970 if base.Flag.Cfg.SpectreIndex {
1971 idx = s.newValue2(ssa.OpSpectreSliceIndex, t, idx, width)
1975 // Figure out where we should go for each index in the table.
1976 table := make([]*ssa.Block, max-min+1)
1977 for i := range table {
1978 table[i] = bEnd // default target
1980 for i := range n.Targets {
1982 lab := s.label(n.Targets[i])
1983 if lab.target == nil {
1984 lab.target = s.f.NewBlock(ssa.BlockPlain)
1988 val, _ = constant.Uint64Val(c)
1990 vl, _ := constant.Int64Val(c)
1993 // Overwrite the default target.
1994 table[val-min] = lab.target
1996 for _, t := range table {
2004 n := n.(*ir.UnaryExpr)
2009 n := n.(*ir.InlineMarkStmt)
2010 s.newValue1I(ssa.OpInlMark, types.TypeVoid, n.Index, s.mem())
2013 s.Fatalf("unhandled stmt %v", n.Op())
2017 // If true, share as many open-coded defer exits as possible (with the downside of
2018 // worse line-number information)
2019 const shareDeferExits = false
2021 // exit processes any code that needs to be generated just before returning.
2022 // It returns a BlockRet block that ends the control flow. Its control value
2023 // will be set to the final memory state.
2024 func (s *state) exit() *ssa.Block {
2026 if s.hasOpenDefers {
2027 if shareDeferExits && s.lastDeferExit != nil && len(s.openDefers) == s.lastDeferCount {
2028 if s.curBlock.Kind != ssa.BlockPlain {
2029 panic("Block for an exit should be BlockPlain")
2031 s.curBlock.AddEdgeTo(s.lastDeferExit)
2033 return s.lastDeferFinalBlock
2037 s.rtcall(ir.Syms.Deferreturn, true, nil)
2041 // Do actual return.
2042 // These currently turn into self-copies (in many cases).
2043 resultFields := s.curfn.Type().Results()
2044 results := make([]*ssa.Value, len(resultFields)+1, len(resultFields)+1)
2045 // Store SSAable and heap-escaped PPARAMOUT variables back to stack locations.
2046 for i, f := range resultFields {
2047 n := f.Nname.(*ir.Name)
2048 if s.canSSA(n) { // result is in some SSA variable
2049 if !n.IsOutputParamInRegisters() && n.Type().HasPointers() {
2050 // We are about to store to the result slot.
2051 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, n, s.mem())
2053 results[i] = s.variable(n, n.Type())
2054 } else if !n.OnStack() { // result is actually heap allocated
2055 // We are about to copy the in-heap result to the result slot.
2056 if n.Type().HasPointers() {
2057 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, n, s.mem())
2059 ha := s.expr(n.Heapaddr)
2060 s.instrumentFields(n.Type(), ha, instrumentRead)
2061 results[i] = s.newValue2(ssa.OpDereference, n.Type(), ha, s.mem())
2062 } else { // result is not SSA-able; not escaped, so not on heap, but too large for SSA.
2063 // Before register ABI this ought to be a self-move, home=dest,
2064 // With register ABI, it's still a self-move if parameter is on stack (i.e., too big or overflowed)
2065 // No VarDef, as the result slot is already holding live value.
2066 results[i] = s.newValue2(ssa.OpDereference, n.Type(), s.addr(n), s.mem())
2070 // In -race mode, we need to call racefuncexit.
2071 // Note: This has to happen after we load any heap-allocated results,
2072 // otherwise races will be attributed to the caller instead.
2073 if s.instrumentEnterExit {
2074 s.rtcall(ir.Syms.Racefuncexit, true, nil)
2077 results[len(results)-1] = s.mem()
2078 m := s.newValue0(ssa.OpMakeResult, s.f.OwnAux.LateExpansionResultType())
2079 m.AddArgs(results...)
2082 b.Kind = ssa.BlockRet
2084 if s.hasdefer && s.hasOpenDefers {
2085 s.lastDeferFinalBlock = b
2090 type opAndType struct {
2095 var opToSSA = map[opAndType]ssa.Op{
2096 {ir.OADD, types.TINT8}: ssa.OpAdd8,
2097 {ir.OADD, types.TUINT8}: ssa.OpAdd8,
2098 {ir.OADD, types.TINT16}: ssa.OpAdd16,
2099 {ir.OADD, types.TUINT16}: ssa.OpAdd16,
2100 {ir.OADD, types.TINT32}: ssa.OpAdd32,
2101 {ir.OADD, types.TUINT32}: ssa.OpAdd32,
2102 {ir.OADD, types.TINT64}: ssa.OpAdd64,
2103 {ir.OADD, types.TUINT64}: ssa.OpAdd64,
2104 {ir.OADD, types.TFLOAT32}: ssa.OpAdd32F,
2105 {ir.OADD, types.TFLOAT64}: ssa.OpAdd64F,
2107 {ir.OSUB, types.TINT8}: ssa.OpSub8,
2108 {ir.OSUB, types.TUINT8}: ssa.OpSub8,
2109 {ir.OSUB, types.TINT16}: ssa.OpSub16,
2110 {ir.OSUB, types.TUINT16}: ssa.OpSub16,
2111 {ir.OSUB, types.TINT32}: ssa.OpSub32,
2112 {ir.OSUB, types.TUINT32}: ssa.OpSub32,
2113 {ir.OSUB, types.TINT64}: ssa.OpSub64,
2114 {ir.OSUB, types.TUINT64}: ssa.OpSub64,
2115 {ir.OSUB, types.TFLOAT32}: ssa.OpSub32F,
2116 {ir.OSUB, types.TFLOAT64}: ssa.OpSub64F,
2118 {ir.ONOT, types.TBOOL}: ssa.OpNot,
2120 {ir.ONEG, types.TINT8}: ssa.OpNeg8,
2121 {ir.ONEG, types.TUINT8}: ssa.OpNeg8,
2122 {ir.ONEG, types.TINT16}: ssa.OpNeg16,
2123 {ir.ONEG, types.TUINT16}: ssa.OpNeg16,
2124 {ir.ONEG, types.TINT32}: ssa.OpNeg32,
2125 {ir.ONEG, types.TUINT32}: ssa.OpNeg32,
2126 {ir.ONEG, types.TINT64}: ssa.OpNeg64,
2127 {ir.ONEG, types.TUINT64}: ssa.OpNeg64,
2128 {ir.ONEG, types.TFLOAT32}: ssa.OpNeg32F,
2129 {ir.ONEG, types.TFLOAT64}: ssa.OpNeg64F,
2131 {ir.OBITNOT, types.TINT8}: ssa.OpCom8,
2132 {ir.OBITNOT, types.TUINT8}: ssa.OpCom8,
2133 {ir.OBITNOT, types.TINT16}: ssa.OpCom16,
2134 {ir.OBITNOT, types.TUINT16}: ssa.OpCom16,
2135 {ir.OBITNOT, types.TINT32}: ssa.OpCom32,
2136 {ir.OBITNOT, types.TUINT32}: ssa.OpCom32,
2137 {ir.OBITNOT, types.TINT64}: ssa.OpCom64,
2138 {ir.OBITNOT, types.TUINT64}: ssa.OpCom64,
2140 {ir.OIMAG, types.TCOMPLEX64}: ssa.OpComplexImag,
2141 {ir.OIMAG, types.TCOMPLEX128}: ssa.OpComplexImag,
2142 {ir.OREAL, types.TCOMPLEX64}: ssa.OpComplexReal,
2143 {ir.OREAL, types.TCOMPLEX128}: ssa.OpComplexReal,
2145 {ir.OMUL, types.TINT8}: ssa.OpMul8,
2146 {ir.OMUL, types.TUINT8}: ssa.OpMul8,
2147 {ir.OMUL, types.TINT16}: ssa.OpMul16,
2148 {ir.OMUL, types.TUINT16}: ssa.OpMul16,
2149 {ir.OMUL, types.TINT32}: ssa.OpMul32,
2150 {ir.OMUL, types.TUINT32}: ssa.OpMul32,
2151 {ir.OMUL, types.TINT64}: ssa.OpMul64,
2152 {ir.OMUL, types.TUINT64}: ssa.OpMul64,
2153 {ir.OMUL, types.TFLOAT32}: ssa.OpMul32F,
2154 {ir.OMUL, types.TFLOAT64}: ssa.OpMul64F,
2156 {ir.ODIV, types.TFLOAT32}: ssa.OpDiv32F,
2157 {ir.ODIV, types.TFLOAT64}: ssa.OpDiv64F,
2159 {ir.ODIV, types.TINT8}: ssa.OpDiv8,
2160 {ir.ODIV, types.TUINT8}: ssa.OpDiv8u,
2161 {ir.ODIV, types.TINT16}: ssa.OpDiv16,
2162 {ir.ODIV, types.TUINT16}: ssa.OpDiv16u,
2163 {ir.ODIV, types.TINT32}: ssa.OpDiv32,
2164 {ir.ODIV, types.TUINT32}: ssa.OpDiv32u,
2165 {ir.ODIV, types.TINT64}: ssa.OpDiv64,
2166 {ir.ODIV, types.TUINT64}: ssa.OpDiv64u,
2168 {ir.OMOD, types.TINT8}: ssa.OpMod8,
2169 {ir.OMOD, types.TUINT8}: ssa.OpMod8u,
2170 {ir.OMOD, types.TINT16}: ssa.OpMod16,
2171 {ir.OMOD, types.TUINT16}: ssa.OpMod16u,
2172 {ir.OMOD, types.TINT32}: ssa.OpMod32,
2173 {ir.OMOD, types.TUINT32}: ssa.OpMod32u,
2174 {ir.OMOD, types.TINT64}: ssa.OpMod64,
2175 {ir.OMOD, types.TUINT64}: ssa.OpMod64u,
2177 {ir.OAND, types.TINT8}: ssa.OpAnd8,
2178 {ir.OAND, types.TUINT8}: ssa.OpAnd8,
2179 {ir.OAND, types.TINT16}: ssa.OpAnd16,
2180 {ir.OAND, types.TUINT16}: ssa.OpAnd16,
2181 {ir.OAND, types.TINT32}: ssa.OpAnd32,
2182 {ir.OAND, types.TUINT32}: ssa.OpAnd32,
2183 {ir.OAND, types.TINT64}: ssa.OpAnd64,
2184 {ir.OAND, types.TUINT64}: ssa.OpAnd64,
2186 {ir.OOR, types.TINT8}: ssa.OpOr8,
2187 {ir.OOR, types.TUINT8}: ssa.OpOr8,
2188 {ir.OOR, types.TINT16}: ssa.OpOr16,
2189 {ir.OOR, types.TUINT16}: ssa.OpOr16,
2190 {ir.OOR, types.TINT32}: ssa.OpOr32,
2191 {ir.OOR, types.TUINT32}: ssa.OpOr32,
2192 {ir.OOR, types.TINT64}: ssa.OpOr64,
2193 {ir.OOR, types.TUINT64}: ssa.OpOr64,
2195 {ir.OXOR, types.TINT8}: ssa.OpXor8,
2196 {ir.OXOR, types.TUINT8}: ssa.OpXor8,
2197 {ir.OXOR, types.TINT16}: ssa.OpXor16,
2198 {ir.OXOR, types.TUINT16}: ssa.OpXor16,
2199 {ir.OXOR, types.TINT32}: ssa.OpXor32,
2200 {ir.OXOR, types.TUINT32}: ssa.OpXor32,
2201 {ir.OXOR, types.TINT64}: ssa.OpXor64,
2202 {ir.OXOR, types.TUINT64}: ssa.OpXor64,
2204 {ir.OEQ, types.TBOOL}: ssa.OpEqB,
2205 {ir.OEQ, types.TINT8}: ssa.OpEq8,
2206 {ir.OEQ, types.TUINT8}: ssa.OpEq8,
2207 {ir.OEQ, types.TINT16}: ssa.OpEq16,
2208 {ir.OEQ, types.TUINT16}: ssa.OpEq16,
2209 {ir.OEQ, types.TINT32}: ssa.OpEq32,
2210 {ir.OEQ, types.TUINT32}: ssa.OpEq32,
2211 {ir.OEQ, types.TINT64}: ssa.OpEq64,
2212 {ir.OEQ, types.TUINT64}: ssa.OpEq64,
2213 {ir.OEQ, types.TINTER}: ssa.OpEqInter,
2214 {ir.OEQ, types.TSLICE}: ssa.OpEqSlice,
2215 {ir.OEQ, types.TFUNC}: ssa.OpEqPtr,
2216 {ir.OEQ, types.TMAP}: ssa.OpEqPtr,
2217 {ir.OEQ, types.TCHAN}: ssa.OpEqPtr,
2218 {ir.OEQ, types.TPTR}: ssa.OpEqPtr,
2219 {ir.OEQ, types.TUINTPTR}: ssa.OpEqPtr,
2220 {ir.OEQ, types.TUNSAFEPTR}: ssa.OpEqPtr,
2221 {ir.OEQ, types.TFLOAT64}: ssa.OpEq64F,
2222 {ir.OEQ, types.TFLOAT32}: ssa.OpEq32F,
2224 {ir.ONE, types.TBOOL}: ssa.OpNeqB,
2225 {ir.ONE, types.TINT8}: ssa.OpNeq8,
2226 {ir.ONE, types.TUINT8}: ssa.OpNeq8,
2227 {ir.ONE, types.TINT16}: ssa.OpNeq16,
2228 {ir.ONE, types.TUINT16}: ssa.OpNeq16,
2229 {ir.ONE, types.TINT32}: ssa.OpNeq32,
2230 {ir.ONE, types.TUINT32}: ssa.OpNeq32,
2231 {ir.ONE, types.TINT64}: ssa.OpNeq64,
2232 {ir.ONE, types.TUINT64}: ssa.OpNeq64,
2233 {ir.ONE, types.TINTER}: ssa.OpNeqInter,
2234 {ir.ONE, types.TSLICE}: ssa.OpNeqSlice,
2235 {ir.ONE, types.TFUNC}: ssa.OpNeqPtr,
2236 {ir.ONE, types.TMAP}: ssa.OpNeqPtr,
2237 {ir.ONE, types.TCHAN}: ssa.OpNeqPtr,
2238 {ir.ONE, types.TPTR}: ssa.OpNeqPtr,
2239 {ir.ONE, types.TUINTPTR}: ssa.OpNeqPtr,
2240 {ir.ONE, types.TUNSAFEPTR}: ssa.OpNeqPtr,
2241 {ir.ONE, types.TFLOAT64}: ssa.OpNeq64F,
2242 {ir.ONE, types.TFLOAT32}: ssa.OpNeq32F,
2244 {ir.OLT, types.TINT8}: ssa.OpLess8,
2245 {ir.OLT, types.TUINT8}: ssa.OpLess8U,
2246 {ir.OLT, types.TINT16}: ssa.OpLess16,
2247 {ir.OLT, types.TUINT16}: ssa.OpLess16U,
2248 {ir.OLT, types.TINT32}: ssa.OpLess32,
2249 {ir.OLT, types.TUINT32}: ssa.OpLess32U,
2250 {ir.OLT, types.TINT64}: ssa.OpLess64,
2251 {ir.OLT, types.TUINT64}: ssa.OpLess64U,
2252 {ir.OLT, types.TFLOAT64}: ssa.OpLess64F,
2253 {ir.OLT, types.TFLOAT32}: ssa.OpLess32F,
2255 {ir.OLE, types.TINT8}: ssa.OpLeq8,
2256 {ir.OLE, types.TUINT8}: ssa.OpLeq8U,
2257 {ir.OLE, types.TINT16}: ssa.OpLeq16,
2258 {ir.OLE, types.TUINT16}: ssa.OpLeq16U,
2259 {ir.OLE, types.TINT32}: ssa.OpLeq32,
2260 {ir.OLE, types.TUINT32}: ssa.OpLeq32U,
2261 {ir.OLE, types.TINT64}: ssa.OpLeq64,
2262 {ir.OLE, types.TUINT64}: ssa.OpLeq64U,
2263 {ir.OLE, types.TFLOAT64}: ssa.OpLeq64F,
2264 {ir.OLE, types.TFLOAT32}: ssa.OpLeq32F,
2267 func (s *state) concreteEtype(t *types.Type) types.Kind {
2273 if s.config.PtrSize == 8 {
2278 if s.config.PtrSize == 8 {
2279 return types.TUINT64
2281 return types.TUINT32
2282 case types.TUINTPTR:
2283 if s.config.PtrSize == 8 {
2284 return types.TUINT64
2286 return types.TUINT32
2290 func (s *state) ssaOp(op ir.Op, t *types.Type) ssa.Op {
2291 etype := s.concreteEtype(t)
2292 x, ok := opToSSA[opAndType{op, etype}]
2294 s.Fatalf("unhandled binary op %v %s", op, etype)
2299 type opAndTwoTypes struct {
2305 type twoTypes struct {
2310 type twoOpsAndType struct {
2313 intermediateType types.Kind
2316 var fpConvOpToSSA = map[twoTypes]twoOpsAndType{
2318 {types.TINT8, types.TFLOAT32}: {ssa.OpSignExt8to32, ssa.OpCvt32to32F, types.TINT32},
2319 {types.TINT16, types.TFLOAT32}: {ssa.OpSignExt16to32, ssa.OpCvt32to32F, types.TINT32},
2320 {types.TINT32, types.TFLOAT32}: {ssa.OpCopy, ssa.OpCvt32to32F, types.TINT32},
2321 {types.TINT64, types.TFLOAT32}: {ssa.OpCopy, ssa.OpCvt64to32F, types.TINT64},
2323 {types.TINT8, types.TFLOAT64}: {ssa.OpSignExt8to32, ssa.OpCvt32to64F, types.TINT32},
2324 {types.TINT16, types.TFLOAT64}: {ssa.OpSignExt16to32, ssa.OpCvt32to64F, types.TINT32},
2325 {types.TINT32, types.TFLOAT64}: {ssa.OpCopy, ssa.OpCvt32to64F, types.TINT32},
2326 {types.TINT64, types.TFLOAT64}: {ssa.OpCopy, ssa.OpCvt64to64F, types.TINT64},
2328 {types.TFLOAT32, types.TINT8}: {ssa.OpCvt32Fto32, ssa.OpTrunc32to8, types.TINT32},
2329 {types.TFLOAT32, types.TINT16}: {ssa.OpCvt32Fto32, ssa.OpTrunc32to16, types.TINT32},
2330 {types.TFLOAT32, types.TINT32}: {ssa.OpCvt32Fto32, ssa.OpCopy, types.TINT32},
2331 {types.TFLOAT32, types.TINT64}: {ssa.OpCvt32Fto64, ssa.OpCopy, types.TINT64},
2333 {types.TFLOAT64, types.TINT8}: {ssa.OpCvt64Fto32, ssa.OpTrunc32to8, types.TINT32},
2334 {types.TFLOAT64, types.TINT16}: {ssa.OpCvt64Fto32, ssa.OpTrunc32to16, types.TINT32},
2335 {types.TFLOAT64, types.TINT32}: {ssa.OpCvt64Fto32, ssa.OpCopy, types.TINT32},
2336 {types.TFLOAT64, types.TINT64}: {ssa.OpCvt64Fto64, ssa.OpCopy, types.TINT64},
2338 {types.TUINT8, types.TFLOAT32}: {ssa.OpZeroExt8to32, ssa.OpCvt32to32F, types.TINT32},
2339 {types.TUINT16, types.TFLOAT32}: {ssa.OpZeroExt16to32, ssa.OpCvt32to32F, types.TINT32},
2340 {types.TUINT32, types.TFLOAT32}: {ssa.OpZeroExt32to64, ssa.OpCvt64to32F, types.TINT64}, // go wide to dodge unsigned
2341 {types.TUINT64, types.TFLOAT32}: {ssa.OpCopy, ssa.OpInvalid, types.TUINT64}, // Cvt64Uto32F, branchy code expansion instead
2343 {types.TUINT8, types.TFLOAT64}: {ssa.OpZeroExt8to32, ssa.OpCvt32to64F, types.TINT32},
2344 {types.TUINT16, types.TFLOAT64}: {ssa.OpZeroExt16to32, ssa.OpCvt32to64F, types.TINT32},
2345 {types.TUINT32, types.TFLOAT64}: {ssa.OpZeroExt32to64, ssa.OpCvt64to64F, types.TINT64}, // go wide to dodge unsigned
2346 {types.TUINT64, types.TFLOAT64}: {ssa.OpCopy, ssa.OpInvalid, types.TUINT64}, // Cvt64Uto64F, branchy code expansion instead
2348 {types.TFLOAT32, types.TUINT8}: {ssa.OpCvt32Fto32, ssa.OpTrunc32to8, types.TINT32},
2349 {types.TFLOAT32, types.TUINT16}: {ssa.OpCvt32Fto32, ssa.OpTrunc32to16, types.TINT32},
2350 {types.TFLOAT32, types.TUINT32}: {ssa.OpCvt32Fto64, ssa.OpTrunc64to32, types.TINT64}, // go wide to dodge unsigned
2351 {types.TFLOAT32, types.TUINT64}: {ssa.OpInvalid, ssa.OpCopy, types.TUINT64}, // Cvt32Fto64U, branchy code expansion instead
2353 {types.TFLOAT64, types.TUINT8}: {ssa.OpCvt64Fto32, ssa.OpTrunc32to8, types.TINT32},
2354 {types.TFLOAT64, types.TUINT16}: {ssa.OpCvt64Fto32, ssa.OpTrunc32to16, types.TINT32},
2355 {types.TFLOAT64, types.TUINT32}: {ssa.OpCvt64Fto64, ssa.OpTrunc64to32, types.TINT64}, // go wide to dodge unsigned
2356 {types.TFLOAT64, types.TUINT64}: {ssa.OpInvalid, ssa.OpCopy, types.TUINT64}, // Cvt64Fto64U, branchy code expansion instead
2359 {types.TFLOAT64, types.TFLOAT32}: {ssa.OpCvt64Fto32F, ssa.OpCopy, types.TFLOAT32},
2360 {types.TFLOAT64, types.TFLOAT64}: {ssa.OpRound64F, ssa.OpCopy, types.TFLOAT64},
2361 {types.TFLOAT32, types.TFLOAT32}: {ssa.OpRound32F, ssa.OpCopy, types.TFLOAT32},
2362 {types.TFLOAT32, types.TFLOAT64}: {ssa.OpCvt32Fto64F, ssa.OpCopy, types.TFLOAT64},
2365 // this map is used only for 32-bit arch, and only includes the difference
2366 // on 32-bit arch, don't use int64<->float conversion for uint32
2367 var fpConvOpToSSA32 = map[twoTypes]twoOpsAndType{
2368 {types.TUINT32, types.TFLOAT32}: {ssa.OpCopy, ssa.OpCvt32Uto32F, types.TUINT32},
2369 {types.TUINT32, types.TFLOAT64}: {ssa.OpCopy, ssa.OpCvt32Uto64F, types.TUINT32},
2370 {types.TFLOAT32, types.TUINT32}: {ssa.OpCvt32Fto32U, ssa.OpCopy, types.TUINT32},
2371 {types.TFLOAT64, types.TUINT32}: {ssa.OpCvt64Fto32U, ssa.OpCopy, types.TUINT32},
2374 // uint64<->float conversions, only on machines that have instructions for that
2375 var uint64fpConvOpToSSA = map[twoTypes]twoOpsAndType{
2376 {types.TUINT64, types.TFLOAT32}: {ssa.OpCopy, ssa.OpCvt64Uto32F, types.TUINT64},
2377 {types.TUINT64, types.TFLOAT64}: {ssa.OpCopy, ssa.OpCvt64Uto64F, types.TUINT64},
2378 {types.TFLOAT32, types.TUINT64}: {ssa.OpCvt32Fto64U, ssa.OpCopy, types.TUINT64},
2379 {types.TFLOAT64, types.TUINT64}: {ssa.OpCvt64Fto64U, ssa.OpCopy, types.TUINT64},
2382 var shiftOpToSSA = map[opAndTwoTypes]ssa.Op{
2383 {ir.OLSH, types.TINT8, types.TUINT8}: ssa.OpLsh8x8,
2384 {ir.OLSH, types.TUINT8, types.TUINT8}: ssa.OpLsh8x8,
2385 {ir.OLSH, types.TINT8, types.TUINT16}: ssa.OpLsh8x16,
2386 {ir.OLSH, types.TUINT8, types.TUINT16}: ssa.OpLsh8x16,
2387 {ir.OLSH, types.TINT8, types.TUINT32}: ssa.OpLsh8x32,
2388 {ir.OLSH, types.TUINT8, types.TUINT32}: ssa.OpLsh8x32,
2389 {ir.OLSH, types.TINT8, types.TUINT64}: ssa.OpLsh8x64,
2390 {ir.OLSH, types.TUINT8, types.TUINT64}: ssa.OpLsh8x64,
2392 {ir.OLSH, types.TINT16, types.TUINT8}: ssa.OpLsh16x8,
2393 {ir.OLSH, types.TUINT16, types.TUINT8}: ssa.OpLsh16x8,
2394 {ir.OLSH, types.TINT16, types.TUINT16}: ssa.OpLsh16x16,
2395 {ir.OLSH, types.TUINT16, types.TUINT16}: ssa.OpLsh16x16,
2396 {ir.OLSH, types.TINT16, types.TUINT32}: ssa.OpLsh16x32,
2397 {ir.OLSH, types.TUINT16, types.TUINT32}: ssa.OpLsh16x32,
2398 {ir.OLSH, types.TINT16, types.TUINT64}: ssa.OpLsh16x64,
2399 {ir.OLSH, types.TUINT16, types.TUINT64}: ssa.OpLsh16x64,
2401 {ir.OLSH, types.TINT32, types.TUINT8}: ssa.OpLsh32x8,
2402 {ir.OLSH, types.TUINT32, types.TUINT8}: ssa.OpLsh32x8,
2403 {ir.OLSH, types.TINT32, types.TUINT16}: ssa.OpLsh32x16,
2404 {ir.OLSH, types.TUINT32, types.TUINT16}: ssa.OpLsh32x16,
2405 {ir.OLSH, types.TINT32, types.TUINT32}: ssa.OpLsh32x32,
2406 {ir.OLSH, types.TUINT32, types.TUINT32}: ssa.OpLsh32x32,
2407 {ir.OLSH, types.TINT32, types.TUINT64}: ssa.OpLsh32x64,
2408 {ir.OLSH, types.TUINT32, types.TUINT64}: ssa.OpLsh32x64,
2410 {ir.OLSH, types.TINT64, types.TUINT8}: ssa.OpLsh64x8,
2411 {ir.OLSH, types.TUINT64, types.TUINT8}: ssa.OpLsh64x8,
2412 {ir.OLSH, types.TINT64, types.TUINT16}: ssa.OpLsh64x16,
2413 {ir.OLSH, types.TUINT64, types.TUINT16}: ssa.OpLsh64x16,
2414 {ir.OLSH, types.TINT64, types.TUINT32}: ssa.OpLsh64x32,
2415 {ir.OLSH, types.TUINT64, types.TUINT32}: ssa.OpLsh64x32,
2416 {ir.OLSH, types.TINT64, types.TUINT64}: ssa.OpLsh64x64,
2417 {ir.OLSH, types.TUINT64, types.TUINT64}: ssa.OpLsh64x64,
2419 {ir.ORSH, types.TINT8, types.TUINT8}: ssa.OpRsh8x8,
2420 {ir.ORSH, types.TUINT8, types.TUINT8}: ssa.OpRsh8Ux8,
2421 {ir.ORSH, types.TINT8, types.TUINT16}: ssa.OpRsh8x16,
2422 {ir.ORSH, types.TUINT8, types.TUINT16}: ssa.OpRsh8Ux16,
2423 {ir.ORSH, types.TINT8, types.TUINT32}: ssa.OpRsh8x32,
2424 {ir.ORSH, types.TUINT8, types.TUINT32}: ssa.OpRsh8Ux32,
2425 {ir.ORSH, types.TINT8, types.TUINT64}: ssa.OpRsh8x64,
2426 {ir.ORSH, types.TUINT8, types.TUINT64}: ssa.OpRsh8Ux64,
2428 {ir.ORSH, types.TINT16, types.TUINT8}: ssa.OpRsh16x8,
2429 {ir.ORSH, types.TUINT16, types.TUINT8}: ssa.OpRsh16Ux8,
2430 {ir.ORSH, types.TINT16, types.TUINT16}: ssa.OpRsh16x16,
2431 {ir.ORSH, types.TUINT16, types.TUINT16}: ssa.OpRsh16Ux16,
2432 {ir.ORSH, types.TINT16, types.TUINT32}: ssa.OpRsh16x32,
2433 {ir.ORSH, types.TUINT16, types.TUINT32}: ssa.OpRsh16Ux32,
2434 {ir.ORSH, types.TINT16, types.TUINT64}: ssa.OpRsh16x64,
2435 {ir.ORSH, types.TUINT16, types.TUINT64}: ssa.OpRsh16Ux64,
2437 {ir.ORSH, types.TINT32, types.TUINT8}: ssa.OpRsh32x8,
2438 {ir.ORSH, types.TUINT32, types.TUINT8}: ssa.OpRsh32Ux8,
2439 {ir.ORSH, types.TINT32, types.TUINT16}: ssa.OpRsh32x16,
2440 {ir.ORSH, types.TUINT32, types.TUINT16}: ssa.OpRsh32Ux16,
2441 {ir.ORSH, types.TINT32, types.TUINT32}: ssa.OpRsh32x32,
2442 {ir.ORSH, types.TUINT32, types.TUINT32}: ssa.OpRsh32Ux32,
2443 {ir.ORSH, types.TINT32, types.TUINT64}: ssa.OpRsh32x64,
2444 {ir.ORSH, types.TUINT32, types.TUINT64}: ssa.OpRsh32Ux64,
2446 {ir.ORSH, types.TINT64, types.TUINT8}: ssa.OpRsh64x8,
2447 {ir.ORSH, types.TUINT64, types.TUINT8}: ssa.OpRsh64Ux8,
2448 {ir.ORSH, types.TINT64, types.TUINT16}: ssa.OpRsh64x16,
2449 {ir.ORSH, types.TUINT64, types.TUINT16}: ssa.OpRsh64Ux16,
2450 {ir.ORSH, types.TINT64, types.TUINT32}: ssa.OpRsh64x32,
2451 {ir.ORSH, types.TUINT64, types.TUINT32}: ssa.OpRsh64Ux32,
2452 {ir.ORSH, types.TINT64, types.TUINT64}: ssa.OpRsh64x64,
2453 {ir.ORSH, types.TUINT64, types.TUINT64}: ssa.OpRsh64Ux64,
2456 func (s *state) ssaShiftOp(op ir.Op, t *types.Type, u *types.Type) ssa.Op {
2457 etype1 := s.concreteEtype(t)
2458 etype2 := s.concreteEtype(u)
2459 x, ok := shiftOpToSSA[opAndTwoTypes{op, etype1, etype2}]
2461 s.Fatalf("unhandled shift op %v etype=%s/%s", op, etype1, etype2)
2466 func (s *state) uintptrConstant(v uint64) *ssa.Value {
2467 if s.config.PtrSize == 4 {
2468 return s.newValue0I(ssa.OpConst32, types.Types[types.TUINTPTR], int64(v))
2470 return s.newValue0I(ssa.OpConst64, types.Types[types.TUINTPTR], int64(v))
2473 func (s *state) conv(n ir.Node, v *ssa.Value, ft, tt *types.Type) *ssa.Value {
2474 if ft.IsBoolean() && tt.IsKind(types.TUINT8) {
2475 // Bool -> uint8 is generated internally when indexing into runtime.staticbyte.
2476 return s.newValue1(ssa.OpCvtBoolToUint8, tt, v)
2478 if ft.IsInteger() && tt.IsInteger() {
2480 if tt.Size() == ft.Size() {
2482 } else if tt.Size() < ft.Size() {
2484 switch 10*ft.Size() + tt.Size() {
2486 op = ssa.OpTrunc16to8
2488 op = ssa.OpTrunc32to8
2490 op = ssa.OpTrunc32to16
2492 op = ssa.OpTrunc64to8
2494 op = ssa.OpTrunc64to16
2496 op = ssa.OpTrunc64to32
2498 s.Fatalf("weird integer truncation %v -> %v", ft, tt)
2500 } else if ft.IsSigned() {
2502 switch 10*ft.Size() + tt.Size() {
2504 op = ssa.OpSignExt8to16
2506 op = ssa.OpSignExt8to32
2508 op = ssa.OpSignExt8to64
2510 op = ssa.OpSignExt16to32
2512 op = ssa.OpSignExt16to64
2514 op = ssa.OpSignExt32to64
2516 s.Fatalf("bad integer sign extension %v -> %v", ft, tt)
2520 switch 10*ft.Size() + tt.Size() {
2522 op = ssa.OpZeroExt8to16
2524 op = ssa.OpZeroExt8to32
2526 op = ssa.OpZeroExt8to64
2528 op = ssa.OpZeroExt16to32
2530 op = ssa.OpZeroExt16to64
2532 op = ssa.OpZeroExt32to64
2534 s.Fatalf("weird integer sign extension %v -> %v", ft, tt)
2537 return s.newValue1(op, tt, v)
2540 if ft.IsComplex() && tt.IsComplex() {
2542 if ft.Size() == tt.Size() {
2549 s.Fatalf("weird complex conversion %v -> %v", ft, tt)
2551 } else if ft.Size() == 8 && tt.Size() == 16 {
2552 op = ssa.OpCvt32Fto64F
2553 } else if ft.Size() == 16 && tt.Size() == 8 {
2554 op = ssa.OpCvt64Fto32F
2556 s.Fatalf("weird complex conversion %v -> %v", ft, tt)
2558 ftp := types.FloatForComplex(ft)
2559 ttp := types.FloatForComplex(tt)
2560 return s.newValue2(ssa.OpComplexMake, tt,
2561 s.newValueOrSfCall1(op, ttp, s.newValue1(ssa.OpComplexReal, ftp, v)),
2562 s.newValueOrSfCall1(op, ttp, s.newValue1(ssa.OpComplexImag, ftp, v)))
2565 if tt.IsComplex() { // and ft is not complex
2566 // Needed for generics support - can't happen in normal Go code.
2567 et := types.FloatForComplex(tt)
2568 v = s.conv(n, v, ft, et)
2569 return s.newValue2(ssa.OpComplexMake, tt, v, s.zeroVal(et))
2572 if ft.IsFloat() || tt.IsFloat() {
2573 conv, ok := fpConvOpToSSA[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]
2574 if s.config.RegSize == 4 && Arch.LinkArch.Family != sys.MIPS && !s.softFloat {
2575 if conv1, ok1 := fpConvOpToSSA32[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]; ok1 {
2579 if Arch.LinkArch.Family == sys.ARM64 || Arch.LinkArch.Family == sys.Wasm || Arch.LinkArch.Family == sys.S390X || s.softFloat {
2580 if conv1, ok1 := uint64fpConvOpToSSA[twoTypes{s.concreteEtype(ft), s.concreteEtype(tt)}]; ok1 {
2585 if Arch.LinkArch.Family == sys.MIPS && !s.softFloat {
2586 if ft.Size() == 4 && ft.IsInteger() && !ft.IsSigned() {
2587 // tt is float32 or float64, and ft is also unsigned
2589 return s.uint32Tofloat32(n, v, ft, tt)
2592 return s.uint32Tofloat64(n, v, ft, tt)
2594 } else if tt.Size() == 4 && tt.IsInteger() && !tt.IsSigned() {
2595 // ft is float32 or float64, and tt is unsigned integer
2597 return s.float32ToUint32(n, v, ft, tt)
2600 return s.float64ToUint32(n, v, ft, tt)
2606 s.Fatalf("weird float conversion %v -> %v", ft, tt)
2608 op1, op2, it := conv.op1, conv.op2, conv.intermediateType
2610 if op1 != ssa.OpInvalid && op2 != ssa.OpInvalid {
2611 // normal case, not tripping over unsigned 64
2612 if op1 == ssa.OpCopy {
2613 if op2 == ssa.OpCopy {
2616 return s.newValueOrSfCall1(op2, tt, v)
2618 if op2 == ssa.OpCopy {
2619 return s.newValueOrSfCall1(op1, tt, v)
2621 return s.newValueOrSfCall1(op2, tt, s.newValueOrSfCall1(op1, types.Types[it], v))
2623 // Tricky 64-bit unsigned cases.
2625 // tt is float32 or float64, and ft is also unsigned
2627 return s.uint64Tofloat32(n, v, ft, tt)
2630 return s.uint64Tofloat64(n, v, ft, tt)
2632 s.Fatalf("weird unsigned integer to float conversion %v -> %v", ft, tt)
2634 // ft is float32 or float64, and tt is unsigned integer
2636 return s.float32ToUint64(n, v, ft, tt)
2639 return s.float64ToUint64(n, v, ft, tt)
2641 s.Fatalf("weird float to unsigned integer conversion %v -> %v", ft, tt)
2645 s.Fatalf("unhandled OCONV %s -> %s", ft.Kind(), tt.Kind())
2649 // expr converts the expression n to ssa, adds it to s and returns the ssa result.
2650 func (s *state) expr(n ir.Node) *ssa.Value {
2651 return s.exprCheckPtr(n, true)
2654 func (s *state) exprCheckPtr(n ir.Node, checkPtrOK bool) *ssa.Value {
2655 if ir.HasUniquePos(n) {
2656 // ONAMEs and named OLITERALs have the line number
2657 // of the decl, not the use. See issue 14742.
2662 s.stmtList(n.Init())
2664 case ir.OBYTES2STRTMP:
2665 n := n.(*ir.ConvExpr)
2666 slice := s.expr(n.X)
2667 ptr := s.newValue1(ssa.OpSlicePtr, s.f.Config.Types.BytePtr, slice)
2668 len := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], slice)
2669 return s.newValue2(ssa.OpStringMake, n.Type(), ptr, len)
2670 case ir.OSTR2BYTESTMP:
2671 n := n.(*ir.ConvExpr)
2673 ptr := s.newValue1(ssa.OpStringPtr, s.f.Config.Types.BytePtr, str)
2675 // We need to ensure []byte("") evaluates to []byte{}, and not []byte(nil).
2677 // TODO(mdempsky): Investigate using "len != 0" instead of "ptr != nil".
2678 cond := s.newValue2(ssa.OpNeqPtr, types.Types[types.TBOOL], ptr, s.constNil(ptr.Type))
2679 zerobase := s.newValue1A(ssa.OpAddr, ptr.Type, ir.Syms.Zerobase, s.sb)
2680 ptr = s.ternary(cond, ptr, zerobase)
2682 len := s.newValue1(ssa.OpStringLen, types.Types[types.TINT], str)
2683 return s.newValue3(ssa.OpSliceMake, n.Type(), ptr, len, len)
2685 n := n.(*ir.UnaryExpr)
2686 aux := n.X.(*ir.Name).Linksym()
2687 // OCFUNC is used to build function values, which must
2688 // always reference ABIInternal entry points.
2689 if aux.ABI() != obj.ABIInternal {
2690 s.Fatalf("expected ABIInternal: %v", aux.ABI())
2692 return s.entryNewValue1A(ssa.OpAddr, n.Type(), aux, s.sb)
2695 if n.Class == ir.PFUNC {
2696 // "value" of a function is the address of the function's closure
2697 sym := staticdata.FuncLinksym(n)
2698 return s.entryNewValue1A(ssa.OpAddr, types.NewPtr(n.Type()), sym, s.sb)
2701 return s.variable(n, n.Type())
2703 return s.load(n.Type(), s.addr(n))
2704 case ir.OLINKSYMOFFSET:
2705 n := n.(*ir.LinksymOffsetExpr)
2706 return s.load(n.Type(), s.addr(n))
2708 n := n.(*ir.NilExpr)
2712 return s.constSlice(t)
2713 case t.IsInterface():
2714 return s.constInterface(t)
2716 return s.constNil(t)
2719 switch u := n.Val(); u.Kind() {
2721 i := ir.IntVal(n.Type(), u)
2722 switch n.Type().Size() {
2724 return s.constInt8(n.Type(), int8(i))
2726 return s.constInt16(n.Type(), int16(i))
2728 return s.constInt32(n.Type(), int32(i))
2730 return s.constInt64(n.Type(), i)
2732 s.Fatalf("bad integer size %d", n.Type().Size())
2735 case constant.String:
2736 i := constant.StringVal(u)
2738 return s.constEmptyString(n.Type())
2740 return s.entryNewValue0A(ssa.OpConstString, n.Type(), ssa.StringToAux(i))
2742 return s.constBool(constant.BoolVal(u))
2743 case constant.Float:
2744 f, _ := constant.Float64Val(u)
2745 switch n.Type().Size() {
2747 return s.constFloat32(n.Type(), f)
2749 return s.constFloat64(n.Type(), f)
2751 s.Fatalf("bad float size %d", n.Type().Size())
2754 case constant.Complex:
2755 re, _ := constant.Float64Val(constant.Real(u))
2756 im, _ := constant.Float64Val(constant.Imag(u))
2757 switch n.Type().Size() {
2759 pt := types.Types[types.TFLOAT32]
2760 return s.newValue2(ssa.OpComplexMake, n.Type(),
2761 s.constFloat32(pt, re),
2762 s.constFloat32(pt, im))
2764 pt := types.Types[types.TFLOAT64]
2765 return s.newValue2(ssa.OpComplexMake, n.Type(),
2766 s.constFloat64(pt, re),
2767 s.constFloat64(pt, im))
2769 s.Fatalf("bad complex size %d", n.Type().Size())
2773 s.Fatalf("unhandled OLITERAL %v", u.Kind())
2777 n := n.(*ir.ConvExpr)
2781 // Assume everything will work out, so set up our return value.
2782 // Anything interesting that happens from here is a fatal.
2788 // Special case for not confusing GC and liveness.
2789 // We don't want pointers accidentally classified
2790 // as not-pointers or vice-versa because of copy
2792 if to.IsPtrShaped() != from.IsPtrShaped() {
2793 return s.newValue2(ssa.OpConvert, to, x, s.mem())
2796 v := s.newValue1(ssa.OpCopy, to, x) // ensure that v has the right type
2799 if to.Kind() == types.TFUNC && from.IsPtrShaped() {
2803 // named <--> unnamed type or typed <--> untyped const
2804 if from.Kind() == to.Kind() {
2808 // unsafe.Pointer <--> *T
2809 if to.IsUnsafePtr() && from.IsPtrShaped() || from.IsUnsafePtr() && to.IsPtrShaped() {
2810 if s.checkPtrEnabled && checkPtrOK && to.IsPtr() && from.IsUnsafePtr() {
2811 s.checkPtrAlignment(n, v, nil)
2817 if to.Kind() == types.TMAP && from == types.NewPtr(reflectdata.MapType()) {
2821 types.CalcSize(from)
2823 if from.Size() != to.Size() {
2824 s.Fatalf("CONVNOP width mismatch %v (%d) -> %v (%d)\n", from, from.Size(), to, to.Size())
2827 if etypesign(from.Kind()) != etypesign(to.Kind()) {
2828 s.Fatalf("CONVNOP sign mismatch %v (%s) -> %v (%s)\n", from, from.Kind(), to, to.Kind())
2832 if base.Flag.Cfg.Instrumenting {
2833 // These appear to be fine, but they fail the
2834 // integer constraint below, so okay them here.
2835 // Sample non-integer conversion: map[string]string -> *uint8
2839 if etypesign(from.Kind()) == 0 {
2840 s.Fatalf("CONVNOP unrecognized non-integer %v -> %v\n", from, to)
2844 // integer, same width, same sign
2848 n := n.(*ir.ConvExpr)
2850 return s.conv(n, x, n.X.Type(), n.Type())
2853 n := n.(*ir.TypeAssertExpr)
2854 res, _ := s.dottype(n, false)
2857 case ir.ODYNAMICDOTTYPE:
2858 n := n.(*ir.DynamicTypeAssertExpr)
2859 res, _ := s.dynamicDottype(n, false)
2863 case ir.OLT, ir.OEQ, ir.ONE, ir.OLE, ir.OGE, ir.OGT:
2864 n := n.(*ir.BinaryExpr)
2867 if n.X.Type().IsComplex() {
2868 pt := types.FloatForComplex(n.X.Type())
2869 op := s.ssaOp(ir.OEQ, pt)
2870 r := s.newValueOrSfCall2(op, types.Types[types.TBOOL], s.newValue1(ssa.OpComplexReal, pt, a), s.newValue1(ssa.OpComplexReal, pt, b))
2871 i := s.newValueOrSfCall2(op, types.Types[types.TBOOL], s.newValue1(ssa.OpComplexImag, pt, a), s.newValue1(ssa.OpComplexImag, pt, b))
2872 c := s.newValue2(ssa.OpAndB, types.Types[types.TBOOL], r, i)
2877 return s.newValue1(ssa.OpNot, types.Types[types.TBOOL], c)
2879 s.Fatalf("ordered complex compare %v", n.Op())
2883 // Convert OGE and OGT into OLE and OLT.
2887 op, a, b = ir.OLE, b, a
2889 op, a, b = ir.OLT, b, a
2891 if n.X.Type().IsFloat() {
2893 return s.newValueOrSfCall2(s.ssaOp(op, n.X.Type()), types.Types[types.TBOOL], a, b)
2895 // integer comparison
2896 return s.newValue2(s.ssaOp(op, n.X.Type()), types.Types[types.TBOOL], a, b)
2898 n := n.(*ir.BinaryExpr)
2901 if n.Type().IsComplex() {
2902 mulop := ssa.OpMul64F
2903 addop := ssa.OpAdd64F
2904 subop := ssa.OpSub64F
2905 pt := types.FloatForComplex(n.Type()) // Could be Float32 or Float64
2906 wt := types.Types[types.TFLOAT64] // Compute in Float64 to minimize cancellation error
2908 areal := s.newValue1(ssa.OpComplexReal, pt, a)
2909 breal := s.newValue1(ssa.OpComplexReal, pt, b)
2910 aimag := s.newValue1(ssa.OpComplexImag, pt, a)
2911 bimag := s.newValue1(ssa.OpComplexImag, pt, b)
2913 if pt != wt { // Widen for calculation
2914 areal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, areal)
2915 breal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, breal)
2916 aimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, aimag)
2917 bimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, bimag)
2920 xreal := s.newValueOrSfCall2(subop, wt, s.newValueOrSfCall2(mulop, wt, areal, breal), s.newValueOrSfCall2(mulop, wt, aimag, bimag))
2921 ximag := s.newValueOrSfCall2(addop, wt, s.newValueOrSfCall2(mulop, wt, areal, bimag), s.newValueOrSfCall2(mulop, wt, aimag, breal))
2923 if pt != wt { // Narrow to store back
2924 xreal = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, xreal)
2925 ximag = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, ximag)
2928 return s.newValue2(ssa.OpComplexMake, n.Type(), xreal, ximag)
2931 if n.Type().IsFloat() {
2932 return s.newValueOrSfCall2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
2935 return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
2938 n := n.(*ir.BinaryExpr)
2941 if n.Type().IsComplex() {
2942 // TODO this is not executed because the front-end substitutes a runtime call.
2943 // That probably ought to change; with modest optimization the widen/narrow
2944 // conversions could all be elided in larger expression trees.
2945 mulop := ssa.OpMul64F
2946 addop := ssa.OpAdd64F
2947 subop := ssa.OpSub64F
2948 divop := ssa.OpDiv64F
2949 pt := types.FloatForComplex(n.Type()) // Could be Float32 or Float64
2950 wt := types.Types[types.TFLOAT64] // Compute in Float64 to minimize cancellation error
2952 areal := s.newValue1(ssa.OpComplexReal, pt, a)
2953 breal := s.newValue1(ssa.OpComplexReal, pt, b)
2954 aimag := s.newValue1(ssa.OpComplexImag, pt, a)
2955 bimag := s.newValue1(ssa.OpComplexImag, pt, b)
2957 if pt != wt { // Widen for calculation
2958 areal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, areal)
2959 breal = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, breal)
2960 aimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, aimag)
2961 bimag = s.newValueOrSfCall1(ssa.OpCvt32Fto64F, wt, bimag)
2964 denom := s.newValueOrSfCall2(addop, wt, s.newValueOrSfCall2(mulop, wt, breal, breal), s.newValueOrSfCall2(mulop, wt, bimag, bimag))
2965 xreal := s.newValueOrSfCall2(addop, wt, s.newValueOrSfCall2(mulop, wt, areal, breal), s.newValueOrSfCall2(mulop, wt, aimag, bimag))
2966 ximag := s.newValueOrSfCall2(subop, wt, s.newValueOrSfCall2(mulop, wt, aimag, breal), s.newValueOrSfCall2(mulop, wt, areal, bimag))
2968 // TODO not sure if this is best done in wide precision or narrow
2969 // Double-rounding might be an issue.
2970 // Note that the pre-SSA implementation does the entire calculation
2971 // in wide format, so wide is compatible.
2972 xreal = s.newValueOrSfCall2(divop, wt, xreal, denom)
2973 ximag = s.newValueOrSfCall2(divop, wt, ximag, denom)
2975 if pt != wt { // Narrow to store back
2976 xreal = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, xreal)
2977 ximag = s.newValueOrSfCall1(ssa.OpCvt64Fto32F, pt, ximag)
2979 return s.newValue2(ssa.OpComplexMake, n.Type(), xreal, ximag)
2981 if n.Type().IsFloat() {
2982 return s.newValueOrSfCall2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
2984 return s.intDivide(n, a, b)
2986 n := n.(*ir.BinaryExpr)
2989 return s.intDivide(n, a, b)
2990 case ir.OADD, ir.OSUB:
2991 n := n.(*ir.BinaryExpr)
2994 if n.Type().IsComplex() {
2995 pt := types.FloatForComplex(n.Type())
2996 op := s.ssaOp(n.Op(), pt)
2997 return s.newValue2(ssa.OpComplexMake, n.Type(),
2998 s.newValueOrSfCall2(op, pt, s.newValue1(ssa.OpComplexReal, pt, a), s.newValue1(ssa.OpComplexReal, pt, b)),
2999 s.newValueOrSfCall2(op, pt, s.newValue1(ssa.OpComplexImag, pt, a), s.newValue1(ssa.OpComplexImag, pt, b)))
3001 if n.Type().IsFloat() {
3002 return s.newValueOrSfCall2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
3004 return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
3005 case ir.OAND, ir.OOR, ir.OXOR:
3006 n := n.(*ir.BinaryExpr)
3009 return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
3011 n := n.(*ir.BinaryExpr)
3014 b = s.newValue1(s.ssaOp(ir.OBITNOT, b.Type), b.Type, b)
3015 return s.newValue2(s.ssaOp(ir.OAND, n.Type()), a.Type, a, b)
3016 case ir.OLSH, ir.ORSH:
3017 n := n.(*ir.BinaryExpr)
3022 cmp := s.newValue2(s.ssaOp(ir.OLE, bt), types.Types[types.TBOOL], s.zeroVal(bt), b)
3023 s.check(cmp, ir.Syms.Panicshift)
3024 bt = bt.ToUnsigned()
3026 return s.newValue2(s.ssaShiftOp(n.Op(), n.Type(), bt), a.Type, a, b)
3027 case ir.OANDAND, ir.OOROR:
3028 // To implement OANDAND (and OOROR), we introduce a
3029 // new temporary variable to hold the result. The
3030 // variable is associated with the OANDAND node in the
3031 // s.vars table (normally variables are only
3032 // associated with ONAME nodes). We convert
3039 // Using var in the subsequent block introduces the
3040 // necessary phi variable.
3041 n := n.(*ir.LogicalExpr)
3046 b.Kind = ssa.BlockIf
3048 // In theory, we should set b.Likely here based on context.
3049 // However, gc only gives us likeliness hints
3050 // in a single place, for plain OIF statements,
3051 // and passing around context is finnicky, so don't bother for now.
3053 bRight := s.f.NewBlock(ssa.BlockPlain)
3054 bResult := s.f.NewBlock(ssa.BlockPlain)
3055 if n.Op() == ir.OANDAND {
3057 b.AddEdgeTo(bResult)
3058 } else if n.Op() == ir.OOROR {
3059 b.AddEdgeTo(bResult)
3063 s.startBlock(bRight)
3068 b.AddEdgeTo(bResult)
3070 s.startBlock(bResult)
3071 return s.variable(n, types.Types[types.TBOOL])
3073 n := n.(*ir.BinaryExpr)
3076 return s.newValue2(ssa.OpComplexMake, n.Type(), r, i)
3080 n := n.(*ir.UnaryExpr)
3082 if n.Type().IsComplex() {
3083 tp := types.FloatForComplex(n.Type())
3084 negop := s.ssaOp(n.Op(), tp)
3085 return s.newValue2(ssa.OpComplexMake, n.Type(),
3086 s.newValue1(negop, tp, s.newValue1(ssa.OpComplexReal, tp, a)),
3087 s.newValue1(negop, tp, s.newValue1(ssa.OpComplexImag, tp, a)))
3089 return s.newValue1(s.ssaOp(n.Op(), n.Type()), a.Type, a)
3090 case ir.ONOT, ir.OBITNOT:
3091 n := n.(*ir.UnaryExpr)
3093 return s.newValue1(s.ssaOp(n.Op(), n.Type()), a.Type, a)
3094 case ir.OIMAG, ir.OREAL:
3095 n := n.(*ir.UnaryExpr)
3097 return s.newValue1(s.ssaOp(n.Op(), n.X.Type()), n.Type(), a)
3099 n := n.(*ir.UnaryExpr)
3103 n := n.(*ir.AddrExpr)
3107 n := n.(*ir.ResultExpr)
3108 if s.prevCall == nil || s.prevCall.Op != ssa.OpStaticLECall && s.prevCall.Op != ssa.OpInterLECall && s.prevCall.Op != ssa.OpClosureLECall {
3109 panic("Expected to see a previous call")
3113 panic(fmt.Errorf("ORESULT %v does not match call %s", n, s.prevCall))
3115 return s.resultOfCall(s.prevCall, which, n.Type())
3118 n := n.(*ir.StarExpr)
3119 p := s.exprPtr(n.X, n.Bounded(), n.Pos())
3120 return s.load(n.Type(), p)
3123 n := n.(*ir.SelectorExpr)
3124 if n.X.Op() == ir.OSTRUCTLIT {
3125 // All literals with nonzero fields have already been
3126 // rewritten during walk. Any that remain are just T{}
3127 // or equivalents. Use the zero value.
3128 if !ir.IsZero(n.X) {
3129 s.Fatalf("literal with nonzero value in SSA: %v", n.X)
3131 return s.zeroVal(n.Type())
3133 // If n is addressable and can't be represented in
3134 // SSA, then load just the selected field. This
3135 // prevents false memory dependencies in race/msan/asan
3137 if ir.IsAddressable(n) && !s.canSSA(n) {
3139 return s.load(n.Type(), p)
3142 return s.newValue1I(ssa.OpStructSelect, n.Type(), int64(fieldIdx(n)), v)
3145 n := n.(*ir.SelectorExpr)
3146 p := s.exprPtr(n.X, n.Bounded(), n.Pos())
3147 p = s.newValue1I(ssa.OpOffPtr, types.NewPtr(n.Type()), n.Offset(), p)
3148 return s.load(n.Type(), p)
3151 n := n.(*ir.IndexExpr)
3153 case n.X.Type().IsString():
3154 if n.Bounded() && ir.IsConst(n.X, constant.String) && ir.IsConst(n.Index, constant.Int) {
3155 // Replace "abc"[1] with 'b'.
3156 // Delayed until now because "abc"[1] is not an ideal constant.
3157 // See test/fixedbugs/issue11370.go.
3158 return s.newValue0I(ssa.OpConst8, types.Types[types.TUINT8], int64(int8(ir.StringVal(n.X)[ir.Int64Val(n.Index)])))
3161 i := s.expr(n.Index)
3162 len := s.newValue1(ssa.OpStringLen, types.Types[types.TINT], a)
3163 i = s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded())
3164 ptrtyp := s.f.Config.Types.BytePtr
3165 ptr := s.newValue1(ssa.OpStringPtr, ptrtyp, a)
3166 if ir.IsConst(n.Index, constant.Int) {
3167 ptr = s.newValue1I(ssa.OpOffPtr, ptrtyp, ir.Int64Val(n.Index), ptr)
3169 ptr = s.newValue2(ssa.OpAddPtr, ptrtyp, ptr, i)
3171 return s.load(types.Types[types.TUINT8], ptr)
3172 case n.X.Type().IsSlice():
3174 return s.load(n.X.Type().Elem(), p)
3175 case n.X.Type().IsArray():
3176 if ssa.CanSSA(n.X.Type()) {
3177 // SSA can handle arrays of length at most 1.
3178 bound := n.X.Type().NumElem()
3180 i := s.expr(n.Index)
3182 // Bounds check will never succeed. Might as well
3183 // use constants for the bounds check.
3184 z := s.constInt(types.Types[types.TINT], 0)
3185 s.boundsCheck(z, z, ssa.BoundsIndex, false)
3186 // The return value won't be live, return junk.
3187 // But not quite junk, in case bounds checks are turned off. See issue 48092.
3188 return s.zeroVal(n.Type())
3190 len := s.constInt(types.Types[types.TINT], bound)
3191 s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded()) // checks i == 0
3192 return s.newValue1I(ssa.OpArraySelect, n.Type(), 0, a)
3195 return s.load(n.X.Type().Elem(), p)
3197 s.Fatalf("bad type for index %v", n.X.Type())
3201 case ir.OLEN, ir.OCAP:
3202 n := n.(*ir.UnaryExpr)
3204 case n.X.Type().IsSlice():
3205 op := ssa.OpSliceLen
3206 if n.Op() == ir.OCAP {
3209 return s.newValue1(op, types.Types[types.TINT], s.expr(n.X))
3210 case n.X.Type().IsString(): // string; not reachable for OCAP
3211 return s.newValue1(ssa.OpStringLen, types.Types[types.TINT], s.expr(n.X))
3212 case n.X.Type().IsMap(), n.X.Type().IsChan():
3213 return s.referenceTypeBuiltin(n, s.expr(n.X))
3215 return s.constInt(types.Types[types.TINT], n.X.Type().NumElem())
3219 n := n.(*ir.UnaryExpr)
3221 if n.X.Type().IsSlice() {
3223 return s.newValue1(ssa.OpSlicePtr, n.Type(), a)
3225 return s.newValue1(ssa.OpSlicePtrUnchecked, n.Type(), a)
3227 return s.newValue1(ssa.OpStringPtr, n.Type(), a)
3231 n := n.(*ir.UnaryExpr)
3233 return s.newValue1(ssa.OpITab, n.Type(), a)
3236 n := n.(*ir.UnaryExpr)
3238 return s.newValue1(ssa.OpIData, n.Type(), a)
3241 n := n.(*ir.BinaryExpr)
3244 return s.newValue2(ssa.OpIMake, n.Type(), tab, data)
3246 case ir.OSLICEHEADER:
3247 n := n.(*ir.SliceHeaderExpr)
3251 return s.newValue3(ssa.OpSliceMake, n.Type(), p, l, c)
3253 case ir.OSTRINGHEADER:
3254 n := n.(*ir.StringHeaderExpr)
3257 return s.newValue2(ssa.OpStringMake, n.Type(), p, l)
3259 case ir.OSLICE, ir.OSLICEARR, ir.OSLICE3, ir.OSLICE3ARR:
3260 n := n.(*ir.SliceExpr)
3261 check := s.checkPtrEnabled && n.Op() == ir.OSLICE3ARR && n.X.Op() == ir.OCONVNOP && n.X.(*ir.ConvExpr).X.Type().IsUnsafePtr()
3262 v := s.exprCheckPtr(n.X, !check)
3263 var i, j, k *ssa.Value
3273 p, l, c := s.slice(v, i, j, k, n.Bounded())
3275 // Emit checkptr instrumentation after bound check to prevent false positive, see #46938.
3276 s.checkPtrAlignment(n.X.(*ir.ConvExpr), v, s.conv(n.Max, k, k.Type, types.Types[types.TUINTPTR]))
3278 return s.newValue3(ssa.OpSliceMake, n.Type(), p, l, c)
3281 n := n.(*ir.SliceExpr)
3290 p, l, _ := s.slice(v, i, j, nil, n.Bounded())
3291 return s.newValue2(ssa.OpStringMake, n.Type(), p, l)
3293 case ir.OSLICE2ARRPTR:
3294 // if arrlen > slice.len {
3298 n := n.(*ir.ConvExpr)
3300 nelem := n.Type().Elem().NumElem()
3301 arrlen := s.constInt(types.Types[types.TINT], nelem)
3302 cap := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], v)
3303 s.boundsCheck(arrlen, cap, ssa.BoundsConvert, false)
3304 op := ssa.OpSlicePtr
3306 op = ssa.OpSlicePtrUnchecked
3308 return s.newValue1(op, n.Type(), v)
3311 n := n.(*ir.CallExpr)
3312 if ir.IsIntrinsicCall(n) {
3313 return s.intrinsicCall(n)
3318 n := n.(*ir.CallExpr)
3319 return s.callResult(n, callNormal)
3322 n := n.(*ir.CallExpr)
3323 return s.newValue1(ssa.OpGetG, n.Type(), s.mem())
3325 case ir.OGETCALLERPC:
3326 n := n.(*ir.CallExpr)
3327 return s.newValue0(ssa.OpGetCallerPC, n.Type())
3329 case ir.OGETCALLERSP:
3330 n := n.(*ir.CallExpr)
3331 return s.newValue1(ssa.OpGetCallerSP, n.Type(), s.mem())
3334 return s.append(n.(*ir.CallExpr), false)
3336 case ir.OMIN, ir.OMAX:
3337 return s.minMax(n.(*ir.CallExpr))
3339 case ir.OSTRUCTLIT, ir.OARRAYLIT:
3340 // All literals with nonzero fields have already been
3341 // rewritten during walk. Any that remain are just T{}
3342 // or equivalents. Use the zero value.
3343 n := n.(*ir.CompLitExpr)
3345 s.Fatalf("literal with nonzero value in SSA: %v", n)
3347 return s.zeroVal(n.Type())
3350 n := n.(*ir.UnaryExpr)
3351 var rtype *ssa.Value
3352 if x, ok := n.X.(*ir.DynamicType); ok && x.Op() == ir.ODYNAMICTYPE {
3353 rtype = s.expr(x.RType)
3355 return s.newObject(n.Type().Elem(), rtype)
3358 n := n.(*ir.BinaryExpr)
3362 // Force len to uintptr to prevent misuse of garbage bits in the
3363 // upper part of the register (#48536).
3364 len = s.conv(n, len, len.Type, types.Types[types.TUINTPTR])
3366 return s.newValue2(ssa.OpAddPtr, n.Type(), ptr, len)
3369 s.Fatalf("unhandled expr %v", n.Op())
3374 func (s *state) resultOfCall(c *ssa.Value, which int64, t *types.Type) *ssa.Value {
3375 aux := c.Aux.(*ssa.AuxCall)
3376 pa := aux.ParamAssignmentForResult(which)
3377 // TODO(register args) determine if in-memory TypeOK is better loaded early from SelectNAddr or later when SelectN is expanded.
3378 // SelectN is better for pattern-matching and possible call-aware analysis we might want to do in the future.
3379 if len(pa.Registers) == 0 && !ssa.CanSSA(t) {
3380 addr := s.newValue1I(ssa.OpSelectNAddr, types.NewPtr(t), which, c)
3381 return s.rawLoad(t, addr)
3383 return s.newValue1I(ssa.OpSelectN, t, which, c)
3386 func (s *state) resultAddrOfCall(c *ssa.Value, which int64, t *types.Type) *ssa.Value {
3387 aux := c.Aux.(*ssa.AuxCall)
3388 pa := aux.ParamAssignmentForResult(which)
3389 if len(pa.Registers) == 0 {
3390 return s.newValue1I(ssa.OpSelectNAddr, types.NewPtr(t), which, c)
3392 _, addr := s.temp(c.Pos, t)
3393 rval := s.newValue1I(ssa.OpSelectN, t, which, c)
3394 s.vars[memVar] = s.newValue3Apos(ssa.OpStore, types.TypeMem, t, addr, rval, s.mem(), false)
3398 // append converts an OAPPEND node to SSA.
3399 // If inplace is false, it converts the OAPPEND expression n to an ssa.Value,
3400 // adds it to s, and returns the Value.
3401 // If inplace is true, it writes the result of the OAPPEND expression n
3402 // back to the slice being appended to, and returns nil.
3403 // inplace MUST be set to false if the slice can be SSA'd.
3404 // Note: this code only handles fixed-count appends. Dotdotdot appends
3405 // have already been rewritten at this point (by walk).
3406 func (s *state) append(n *ir.CallExpr, inplace bool) *ssa.Value {
3407 // If inplace is false, process as expression "append(s, e1, e2, e3)":
3409 // ptr, len, cap := s
3411 // if uint(len) > uint(cap) {
3412 // ptr, len, cap = growslice(ptr, len, cap, 3, typ)
3413 // Note that len is unmodified by growslice.
3415 // // with write barriers, if needed:
3416 // *(ptr+(len-3)) = e1
3417 // *(ptr+(len-2)) = e2
3418 // *(ptr+(len-1)) = e3
3419 // return makeslice(ptr, len, cap)
3422 // If inplace is true, process as statement "s = append(s, e1, e2, e3)":
3425 // ptr, len, cap := s
3427 // if uint(len) > uint(cap) {
3428 // ptr, len, cap = growslice(ptr, len, cap, 3, typ)
3429 // vardef(a) // if necessary, advise liveness we are writing a new a
3430 // *a.cap = cap // write before ptr to avoid a spill
3431 // *a.ptr = ptr // with write barrier
3434 // // with write barriers, if needed:
3435 // *(ptr+(len-3)) = e1
3436 // *(ptr+(len-2)) = e2
3437 // *(ptr+(len-1)) = e3
3439 et := n.Type().Elem()
3440 pt := types.NewPtr(et)
3443 sn := n.Args[0] // the slice node is the first in the list
3444 var slice, addr *ssa.Value
3447 slice = s.load(n.Type(), addr)
3452 // Allocate new blocks
3453 grow := s.f.NewBlock(ssa.BlockPlain)
3454 assign := s.f.NewBlock(ssa.BlockPlain)
3456 // Decomposse input slice.
3457 p := s.newValue1(ssa.OpSlicePtr, pt, slice)
3458 l := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], slice)
3459 c := s.newValue1(ssa.OpSliceCap, types.Types[types.TINT], slice)
3461 // Add number of new elements to length.
3462 nargs := s.constInt(types.Types[types.TINT], int64(len(n.Args)-1))
3463 l = s.newValue2(s.ssaOp(ir.OADD, types.Types[types.TINT]), types.Types[types.TINT], l, nargs)
3465 // Decide if we need to grow
3466 cmp := s.newValue2(s.ssaOp(ir.OLT, types.Types[types.TUINT]), types.Types[types.TBOOL], c, l)
3468 // Record values of ptr/len/cap before branch.
3476 b.Kind = ssa.BlockIf
3477 b.Likely = ssa.BranchUnlikely
3484 taddr := s.expr(n.X)
3485 r := s.rtcall(ir.Syms.Growslice, true, []*types.Type{n.Type()}, p, l, c, nargs, taddr)
3487 // Decompose output slice
3488 p = s.newValue1(ssa.OpSlicePtr, pt, r[0])
3489 l = s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], r[0])
3490 c = s.newValue1(ssa.OpSliceCap, types.Types[types.TINT], r[0])
3496 if sn.Op() == ir.ONAME {
3498 if sn.Class != ir.PEXTERN {
3499 // Tell liveness we're about to build a new slice
3500 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, sn, s.mem())
3503 capaddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, types.SliceCapOffset, addr)
3504 s.store(types.Types[types.TINT], capaddr, c)
3505 s.store(pt, addr, p)
3511 // assign new elements to slots
3512 s.startBlock(assign)
3513 p = s.variable(ptrVar, pt) // generates phi for ptr
3514 l = s.variable(lenVar, types.Types[types.TINT]) // generates phi for len
3516 c = s.variable(capVar, types.Types[types.TINT]) // generates phi for cap
3520 // Update length in place.
3521 // We have to wait until here to make sure growslice succeeded.
3522 lenaddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, types.SliceLenOffset, addr)
3523 s.store(types.Types[types.TINT], lenaddr, l)
3527 type argRec struct {
3528 // if store is true, we're appending the value v. If false, we're appending the
3533 args := make([]argRec, 0, len(n.Args[1:]))
3534 for _, n := range n.Args[1:] {
3535 if ssa.CanSSA(n.Type()) {
3536 args = append(args, argRec{v: s.expr(n), store: true})
3539 args = append(args, argRec{v: v})
3543 // Write args into slice.
3544 oldLen := s.newValue2(s.ssaOp(ir.OSUB, types.Types[types.TINT]), types.Types[types.TINT], l, nargs)
3545 p2 := s.newValue2(ssa.OpPtrIndex, pt, p, oldLen)
3546 for i, arg := range args {
3547 addr := s.newValue2(ssa.OpPtrIndex, pt, p2, s.constInt(types.Types[types.TINT], int64(i)))
3549 s.storeType(et, addr, arg.v, 0, true)
3551 s.move(et, addr, arg.v)
3555 // The following deletions have no practical effect at this time
3556 // because state.vars has been reset by the preceding state.startBlock.
3557 // They only enforce the fact that these variables are no longer need in
3558 // the current scope.
3559 delete(s.vars, ptrVar)
3560 delete(s.vars, lenVar)
3562 delete(s.vars, capVar)
3569 return s.newValue3(ssa.OpSliceMake, n.Type(), p, l, c)
3572 // minMax converts an OMIN/OMAX builtin call into SSA.
3573 func (s *state) minMax(n *ir.CallExpr) *ssa.Value {
3574 // The OMIN/OMAX builtin is variadic, but its semantics are
3575 // equivalent to left-folding a binary min/max operation across the
3577 fold := func(op func(x, a *ssa.Value) *ssa.Value) *ssa.Value {
3578 x := s.expr(n.Args[0])
3579 for _, arg := range n.Args[1:] {
3580 x = op(x, s.expr(arg))
3587 if typ.IsFloat() || typ.IsString() {
3588 // min/max semantics for floats are tricky because of NaNs and
3589 // negative zero. Some architectures have instructions which
3590 // we can use to generate the right result. For others we must
3591 // call into the runtime instead.
3593 // Strings are conceptually simpler, but we currently desugar
3594 // string comparisons during walk, not ssagen.
3597 switch Arch.LinkArch.Family {
3598 case sys.AMD64, sys.ARM64:
3601 case typ.Kind() == types.TFLOAT64 && n.Op() == ir.OMIN:
3603 case typ.Kind() == types.TFLOAT64 && n.Op() == ir.OMAX:
3605 case typ.Kind() == types.TFLOAT32 && n.Op() == ir.OMIN:
3607 case typ.Kind() == types.TFLOAT32 && n.Op() == ir.OMAX:
3610 return fold(func(x, a *ssa.Value) *ssa.Value {
3611 return s.newValue2(op, typ, x, a)
3617 case types.TFLOAT32:
3624 case types.TFLOAT64:
3639 fn := typecheck.LookupRuntimeFunc(name)
3641 return fold(func(x, a *ssa.Value) *ssa.Value {
3642 return s.rtcall(fn, true, []*types.Type{typ}, x, a)[0]
3646 lt := s.ssaOp(ir.OLT, typ)
3648 return fold(func(x, a *ssa.Value) *ssa.Value {
3652 return s.ternary(s.newValue2(lt, types.Types[types.TBOOL], a, x), a, x)
3655 return s.ternary(s.newValue2(lt, types.Types[types.TBOOL], x, a), a, x)
3657 panic("unreachable")
3661 // ternary emits code to evaluate cond ? x : y.
3662 func (s *state) ternary(cond, x, y *ssa.Value) *ssa.Value {
3663 // Note that we need a new ternaryVar each time (unlike okVar where we can
3664 // reuse the variable) because it might have a different type every time.
3665 ternaryVar := ssaMarker("ternary")
3667 bThen := s.f.NewBlock(ssa.BlockPlain)
3668 bElse := s.f.NewBlock(ssa.BlockPlain)
3669 bEnd := s.f.NewBlock(ssa.BlockPlain)
3672 b.Kind = ssa.BlockIf
3678 s.vars[ternaryVar] = x
3679 s.endBlock().AddEdgeTo(bEnd)
3682 s.vars[ternaryVar] = y
3683 s.endBlock().AddEdgeTo(bEnd)
3686 r := s.variable(ternaryVar, x.Type)
3687 delete(s.vars, ternaryVar)
3691 // condBranch evaluates the boolean expression cond and branches to yes
3692 // if cond is true and no if cond is false.
3693 // This function is intended to handle && and || better than just calling
3694 // s.expr(cond) and branching on the result.
3695 func (s *state) condBranch(cond ir.Node, yes, no *ssa.Block, likely int8) {
3698 cond := cond.(*ir.LogicalExpr)
3699 mid := s.f.NewBlock(ssa.BlockPlain)
3700 s.stmtList(cond.Init())
3701 s.condBranch(cond.X, mid, no, max8(likely, 0))
3703 s.condBranch(cond.Y, yes, no, likely)
3705 // Note: if likely==1, then both recursive calls pass 1.
3706 // If likely==-1, then we don't have enough information to decide
3707 // whether the first branch is likely or not. So we pass 0 for
3708 // the likeliness of the first branch.
3709 // TODO: have the frontend give us branch prediction hints for
3710 // OANDAND and OOROR nodes (if it ever has such info).
3712 cond := cond.(*ir.LogicalExpr)
3713 mid := s.f.NewBlock(ssa.BlockPlain)
3714 s.stmtList(cond.Init())
3715 s.condBranch(cond.X, yes, mid, min8(likely, 0))
3717 s.condBranch(cond.Y, yes, no, likely)
3719 // Note: if likely==-1, then both recursive calls pass -1.
3720 // If likely==1, then we don't have enough info to decide
3721 // the likelihood of the first branch.
3723 cond := cond.(*ir.UnaryExpr)
3724 s.stmtList(cond.Init())
3725 s.condBranch(cond.X, no, yes, -likely)
3728 cond := cond.(*ir.ConvExpr)
3729 s.stmtList(cond.Init())
3730 s.condBranch(cond.X, yes, no, likely)
3735 b.Kind = ssa.BlockIf
3737 b.Likely = ssa.BranchPrediction(likely) // gc and ssa both use -1/0/+1 for likeliness
3745 skipPtr skipMask = 1 << iota
3750 // assign does left = right.
3751 // Right has already been evaluated to ssa, left has not.
3752 // If deref is true, then we do left = *right instead (and right has already been nil-checked).
3753 // If deref is true and right == nil, just do left = 0.
3754 // skip indicates assignments (at the top level) that can be avoided.
3755 // mayOverlap indicates whether left&right might partially overlap in memory. Default is false.
3756 func (s *state) assign(left ir.Node, right *ssa.Value, deref bool, skip skipMask) {
3757 s.assignWhichMayOverlap(left, right, deref, skip, false)
3759 func (s *state) assignWhichMayOverlap(left ir.Node, right *ssa.Value, deref bool, skip skipMask, mayOverlap bool) {
3760 if left.Op() == ir.ONAME && ir.IsBlank(left) {
3767 s.Fatalf("can SSA LHS %v but not RHS %s", left, right)
3769 if left.Op() == ir.ODOT {
3770 // We're assigning to a field of an ssa-able value.
3771 // We need to build a new structure with the new value for the
3772 // field we're assigning and the old values for the other fields.
3774 // type T struct {a, b, c int}
3777 // For the x.b = 5 assignment we want to generate x = T{x.a, 5, x.c}
3779 // Grab information about the structure type.
3780 left := left.(*ir.SelectorExpr)
3783 idx := fieldIdx(left)
3785 // Grab old value of structure.
3786 old := s.expr(left.X)
3788 // Make new structure.
3789 new := s.newValue0(ssa.StructMakeOp(t.NumFields()), t)
3791 // Add fields as args.
3792 for i := 0; i < nf; i++ {
3796 new.AddArg(s.newValue1I(ssa.OpStructSelect, t.FieldType(i), int64(i), old))
3800 // Recursively assign the new value we've made to the base of the dot op.
3801 s.assign(left.X, new, false, 0)
3802 // TODO: do we need to update named values here?
3805 if left.Op() == ir.OINDEX && left.(*ir.IndexExpr).X.Type().IsArray() {
3806 left := left.(*ir.IndexExpr)
3807 s.pushLine(left.Pos())
3809 // We're assigning to an element of an ssa-able array.
3814 i := s.expr(left.Index) // index
3816 // The bounds check must fail. Might as well
3817 // ignore the actual index and just use zeros.
3818 z := s.constInt(types.Types[types.TINT], 0)
3819 s.boundsCheck(z, z, ssa.BoundsIndex, false)
3823 s.Fatalf("assigning to non-1-length array")
3825 // Rewrite to a = [1]{v}
3826 len := s.constInt(types.Types[types.TINT], 1)
3827 s.boundsCheck(i, len, ssa.BoundsIndex, false) // checks i == 0
3828 v := s.newValue1(ssa.OpArrayMake1, t, right)
3829 s.assign(left.X, v, false, 0)
3832 left := left.(*ir.Name)
3833 // Update variable assignment.
3834 s.vars[left] = right
3835 s.addNamedValue(left, right)
3839 // If this assignment clobbers an entire local variable, then emit
3840 // OpVarDef so liveness analysis knows the variable is redefined.
3841 if base, ok := clobberBase(left).(*ir.Name); ok && base.OnStack() && skip == 0 && t.HasPointers() {
3842 s.vars[memVar] = s.newValue1Apos(ssa.OpVarDef, types.TypeMem, base, s.mem(), !ir.IsAutoTmp(base))
3845 // Left is not ssa-able. Compute its address.
3846 addr := s.addr(left)
3847 if ir.IsReflectHeaderDataField(left) {
3848 // Package unsafe's documentation says storing pointers into
3849 // reflect.SliceHeader and reflect.StringHeader's Data fields
3850 // is valid, even though they have type uintptr (#19168).
3851 // Mark it pointer type to signal the writebarrier pass to
3852 // insert a write barrier.
3853 t = types.Types[types.TUNSAFEPTR]
3856 // Treat as a mem->mem move.
3860 s.moveWhichMayOverlap(t, addr, right, mayOverlap)
3864 // Treat as a store.
3865 s.storeType(t, addr, right, skip, !ir.IsAutoTmp(left))
3868 // zeroVal returns the zero value for type t.
3869 func (s *state) zeroVal(t *types.Type) *ssa.Value {
3874 return s.constInt8(t, 0)
3876 return s.constInt16(t, 0)
3878 return s.constInt32(t, 0)
3880 return s.constInt64(t, 0)
3882 s.Fatalf("bad sized integer type %v", t)
3887 return s.constFloat32(t, 0)
3889 return s.constFloat64(t, 0)
3891 s.Fatalf("bad sized float type %v", t)
3896 z := s.constFloat32(types.Types[types.TFLOAT32], 0)
3897 return s.entryNewValue2(ssa.OpComplexMake, t, z, z)
3899 z := s.constFloat64(types.Types[types.TFLOAT64], 0)
3900 return s.entryNewValue2(ssa.OpComplexMake, t, z, z)
3902 s.Fatalf("bad sized complex type %v", t)
3906 return s.constEmptyString(t)
3907 case t.IsPtrShaped():
3908 return s.constNil(t)
3910 return s.constBool(false)
3911 case t.IsInterface():
3912 return s.constInterface(t)
3914 return s.constSlice(t)
3917 v := s.entryNewValue0(ssa.StructMakeOp(t.NumFields()), t)
3918 for i := 0; i < n; i++ {
3919 v.AddArg(s.zeroVal(t.FieldType(i)))
3923 switch t.NumElem() {
3925 return s.entryNewValue0(ssa.OpArrayMake0, t)
3927 return s.entryNewValue1(ssa.OpArrayMake1, t, s.zeroVal(t.Elem()))
3930 s.Fatalf("zero for type %v not implemented", t)
3937 callNormal callKind = iota
3944 type sfRtCallDef struct {
3949 var softFloatOps map[ssa.Op]sfRtCallDef
3951 func softfloatInit() {
3952 // Some of these operations get transformed by sfcall.
3953 softFloatOps = map[ssa.Op]sfRtCallDef{
3954 ssa.OpAdd32F: {typecheck.LookupRuntimeFunc("fadd32"), types.TFLOAT32},
3955 ssa.OpAdd64F: {typecheck.LookupRuntimeFunc("fadd64"), types.TFLOAT64},
3956 ssa.OpSub32F: {typecheck.LookupRuntimeFunc("fadd32"), types.TFLOAT32},
3957 ssa.OpSub64F: {typecheck.LookupRuntimeFunc("fadd64"), types.TFLOAT64},
3958 ssa.OpMul32F: {typecheck.LookupRuntimeFunc("fmul32"), types.TFLOAT32},
3959 ssa.OpMul64F: {typecheck.LookupRuntimeFunc("fmul64"), types.TFLOAT64},
3960 ssa.OpDiv32F: {typecheck.LookupRuntimeFunc("fdiv32"), types.TFLOAT32},
3961 ssa.OpDiv64F: {typecheck.LookupRuntimeFunc("fdiv64"), types.TFLOAT64},
3963 ssa.OpEq64F: {typecheck.LookupRuntimeFunc("feq64"), types.TBOOL},
3964 ssa.OpEq32F: {typecheck.LookupRuntimeFunc("feq32"), types.TBOOL},
3965 ssa.OpNeq64F: {typecheck.LookupRuntimeFunc("feq64"), types.TBOOL},
3966 ssa.OpNeq32F: {typecheck.LookupRuntimeFunc("feq32"), types.TBOOL},
3967 ssa.OpLess64F: {typecheck.LookupRuntimeFunc("fgt64"), types.TBOOL},
3968 ssa.OpLess32F: {typecheck.LookupRuntimeFunc("fgt32"), types.TBOOL},
3969 ssa.OpLeq64F: {typecheck.LookupRuntimeFunc("fge64"), types.TBOOL},
3970 ssa.OpLeq32F: {typecheck.LookupRuntimeFunc("fge32"), types.TBOOL},
3972 ssa.OpCvt32to32F: {typecheck.LookupRuntimeFunc("fint32to32"), types.TFLOAT32},
3973 ssa.OpCvt32Fto32: {typecheck.LookupRuntimeFunc("f32toint32"), types.TINT32},
3974 ssa.OpCvt64to32F: {typecheck.LookupRuntimeFunc("fint64to32"), types.TFLOAT32},
3975 ssa.OpCvt32Fto64: {typecheck.LookupRuntimeFunc("f32toint64"), types.TINT64},
3976 ssa.OpCvt64Uto32F: {typecheck.LookupRuntimeFunc("fuint64to32"), types.TFLOAT32},
3977 ssa.OpCvt32Fto64U: {typecheck.LookupRuntimeFunc("f32touint64"), types.TUINT64},
3978 ssa.OpCvt32to64F: {typecheck.LookupRuntimeFunc("fint32to64"), types.TFLOAT64},
3979 ssa.OpCvt64Fto32: {typecheck.LookupRuntimeFunc("f64toint32"), types.TINT32},
3980 ssa.OpCvt64to64F: {typecheck.LookupRuntimeFunc("fint64to64"), types.TFLOAT64},
3981 ssa.OpCvt64Fto64: {typecheck.LookupRuntimeFunc("f64toint64"), types.TINT64},
3982 ssa.OpCvt64Uto64F: {typecheck.LookupRuntimeFunc("fuint64to64"), types.TFLOAT64},
3983 ssa.OpCvt64Fto64U: {typecheck.LookupRuntimeFunc("f64touint64"), types.TUINT64},
3984 ssa.OpCvt32Fto64F: {typecheck.LookupRuntimeFunc("f32to64"), types.TFLOAT64},
3985 ssa.OpCvt64Fto32F: {typecheck.LookupRuntimeFunc("f64to32"), types.TFLOAT32},
3989 // TODO: do not emit sfcall if operation can be optimized to constant in later
3991 func (s *state) sfcall(op ssa.Op, args ...*ssa.Value) (*ssa.Value, bool) {
3992 f2i := func(t *types.Type) *types.Type {
3994 case types.TFLOAT32:
3995 return types.Types[types.TUINT32]
3996 case types.TFLOAT64:
3997 return types.Types[types.TUINT64]
4002 if callDef, ok := softFloatOps[op]; ok {
4008 args[0], args[1] = args[1], args[0]
4011 args[1] = s.newValue1(s.ssaOp(ir.ONEG, types.Types[callDef.rtype]), args[1].Type, args[1])
4014 // runtime functions take uints for floats and returns uints.
4015 // Convert to uints so we use the right calling convention.
4016 for i, a := range args {
4017 if a.Type.IsFloat() {
4018 args[i] = s.newValue1(ssa.OpCopy, f2i(a.Type), a)
4022 rt := types.Types[callDef.rtype]
4023 result := s.rtcall(callDef.rtfn, true, []*types.Type{f2i(rt)}, args...)[0]
4025 result = s.newValue1(ssa.OpCopy, rt, result)
4027 if op == ssa.OpNeq32F || op == ssa.OpNeq64F {
4028 result = s.newValue1(ssa.OpNot, result.Type, result)
4035 var intrinsics map[intrinsicKey]intrinsicBuilder
4037 // An intrinsicBuilder converts a call node n into an ssa value that
4038 // implements that call as an intrinsic. args is a list of arguments to the func.
4039 type intrinsicBuilder func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value
4041 type intrinsicKey struct {
4048 intrinsics = map[intrinsicKey]intrinsicBuilder{}
4053 var lwatomics []*sys.Arch
4054 for _, a := range &sys.Archs {
4055 all = append(all, a)
4061 if a.Family != sys.PPC64 {
4062 lwatomics = append(lwatomics, a)
4066 // add adds the intrinsic b for pkg.fn for the given list of architectures.
4067 add := func(pkg, fn string, b intrinsicBuilder, archs ...*sys.Arch) {
4068 for _, a := range archs {
4069 intrinsics[intrinsicKey{a, pkg, fn}] = b
4072 // addF does the same as add but operates on architecture families.
4073 addF := func(pkg, fn string, b intrinsicBuilder, archFamilies ...sys.ArchFamily) {
4075 for _, f := range archFamilies {
4077 panic("too many architecture families")
4081 for _, a := range all {
4082 if m>>uint(a.Family)&1 != 0 {
4083 intrinsics[intrinsicKey{a, pkg, fn}] = b
4087 // alias defines pkg.fn = pkg2.fn2 for all architectures in archs for which pkg2.fn2 exists.
4088 alias := func(pkg, fn, pkg2, fn2 string, archs ...*sys.Arch) {
4090 for _, a := range archs {
4091 if b, ok := intrinsics[intrinsicKey{a, pkg2, fn2}]; ok {
4092 intrinsics[intrinsicKey{a, pkg, fn}] = b
4097 panic(fmt.Sprintf("attempted to alias undefined intrinsic: %s.%s", pkg, fn))
4101 /******** runtime ********/
4102 if !base.Flag.Cfg.Instrumenting {
4103 add("runtime", "slicebytetostringtmp",
4104 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4105 // Compiler frontend optimizations emit OBYTES2STRTMP nodes
4106 // for the backend instead of slicebytetostringtmp calls
4107 // when not instrumenting.
4108 return s.newValue2(ssa.OpStringMake, n.Type(), args[0], args[1])
4112 addF("runtime/internal/math", "MulUintptr",
4113 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4114 if s.config.PtrSize == 4 {
4115 return s.newValue2(ssa.OpMul32uover, types.NewTuple(types.Types[types.TUINT], types.Types[types.TUINT]), args[0], args[1])
4117 return s.newValue2(ssa.OpMul64uover, types.NewTuple(types.Types[types.TUINT], types.Types[types.TUINT]), args[0], args[1])
4119 sys.AMD64, sys.I386, sys.Loong64, sys.MIPS64, sys.RISCV64, sys.ARM64)
4120 alias("runtime", "mulUintptr", "runtime/internal/math", "MulUintptr", all...)
4121 add("runtime", "KeepAlive",
4122 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4123 data := s.newValue1(ssa.OpIData, s.f.Config.Types.BytePtr, args[0])
4124 s.vars[memVar] = s.newValue2(ssa.OpKeepAlive, types.TypeMem, data, s.mem())
4128 add("runtime", "getclosureptr",
4129 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4130 return s.newValue0(ssa.OpGetClosurePtr, s.f.Config.Types.Uintptr)
4134 add("runtime", "getcallerpc",
4135 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4136 return s.newValue0(ssa.OpGetCallerPC, s.f.Config.Types.Uintptr)
4140 add("runtime", "getcallersp",
4141 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4142 return s.newValue1(ssa.OpGetCallerSP, s.f.Config.Types.Uintptr, s.mem())
4146 addF("runtime", "publicationBarrier",
4147 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4148 s.vars[memVar] = s.newValue1(ssa.OpPubBarrier, types.TypeMem, s.mem())
4151 sys.ARM64, sys.PPC64)
4153 brev_arch := []sys.ArchFamily{sys.AMD64, sys.I386, sys.ARM64, sys.ARM, sys.S390X}
4154 if buildcfg.GOPPC64 >= 10 {
4155 // Use only on Power10 as the new byte reverse instructions that Power10 provide
4156 // make it worthwhile as an intrinsic
4157 brev_arch = append(brev_arch, sys.PPC64)
4159 /******** runtime/internal/sys ********/
4160 addF("runtime/internal/sys", "Bswap32",
4161 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4162 return s.newValue1(ssa.OpBswap32, types.Types[types.TUINT32], args[0])
4165 addF("runtime/internal/sys", "Bswap64",
4166 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4167 return s.newValue1(ssa.OpBswap64, types.Types[types.TUINT64], args[0])
4171 /****** Prefetch ******/
4172 makePrefetchFunc := func(op ssa.Op) func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4173 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4174 s.vars[memVar] = s.newValue2(op, types.TypeMem, args[0], s.mem())
4179 // Make Prefetch intrinsics for supported platforms
4180 // On the unsupported platforms stub function will be eliminated
4181 addF("runtime/internal/sys", "Prefetch", makePrefetchFunc(ssa.OpPrefetchCache),
4182 sys.AMD64, sys.ARM64, sys.PPC64)
4183 addF("runtime/internal/sys", "PrefetchStreamed", makePrefetchFunc(ssa.OpPrefetchCacheStreamed),
4184 sys.AMD64, sys.ARM64, sys.PPC64)
4186 /******** runtime/internal/atomic ********/
4187 addF("runtime/internal/atomic", "Load",
4188 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4189 v := s.newValue2(ssa.OpAtomicLoad32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], s.mem())
4190 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4191 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4193 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4194 addF("runtime/internal/atomic", "Load8",
4195 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4196 v := s.newValue2(ssa.OpAtomicLoad8, types.NewTuple(types.Types[types.TUINT8], types.TypeMem), args[0], s.mem())
4197 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4198 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT8], v)
4200 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4201 addF("runtime/internal/atomic", "Load64",
4202 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4203 v := s.newValue2(ssa.OpAtomicLoad64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], s.mem())
4204 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4205 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4207 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4208 addF("runtime/internal/atomic", "LoadAcq",
4209 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4210 v := s.newValue2(ssa.OpAtomicLoadAcq32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], s.mem())
4211 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4212 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4214 sys.PPC64, sys.S390X)
4215 addF("runtime/internal/atomic", "LoadAcq64",
4216 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4217 v := s.newValue2(ssa.OpAtomicLoadAcq64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], s.mem())
4218 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4219 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4222 addF("runtime/internal/atomic", "Loadp",
4223 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4224 v := s.newValue2(ssa.OpAtomicLoadPtr, types.NewTuple(s.f.Config.Types.BytePtr, types.TypeMem), args[0], s.mem())
4225 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4226 return s.newValue1(ssa.OpSelect0, s.f.Config.Types.BytePtr, v)
4228 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4230 addF("runtime/internal/atomic", "Store",
4231 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4232 s.vars[memVar] = s.newValue3(ssa.OpAtomicStore32, types.TypeMem, args[0], args[1], s.mem())
4235 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4236 addF("runtime/internal/atomic", "Store8",
4237 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4238 s.vars[memVar] = s.newValue3(ssa.OpAtomicStore8, types.TypeMem, args[0], args[1], s.mem())
4241 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4242 addF("runtime/internal/atomic", "Store64",
4243 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4244 s.vars[memVar] = s.newValue3(ssa.OpAtomicStore64, types.TypeMem, args[0], args[1], s.mem())
4247 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4248 addF("runtime/internal/atomic", "StorepNoWB",
4249 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4250 s.vars[memVar] = s.newValue3(ssa.OpAtomicStorePtrNoWB, types.TypeMem, args[0], args[1], s.mem())
4253 sys.AMD64, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.RISCV64, sys.S390X)
4254 addF("runtime/internal/atomic", "StoreRel",
4255 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4256 s.vars[memVar] = s.newValue3(ssa.OpAtomicStoreRel32, types.TypeMem, args[0], args[1], s.mem())
4259 sys.PPC64, sys.S390X)
4260 addF("runtime/internal/atomic", "StoreRel64",
4261 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4262 s.vars[memVar] = s.newValue3(ssa.OpAtomicStoreRel64, types.TypeMem, args[0], args[1], s.mem())
4267 addF("runtime/internal/atomic", "Xchg",
4268 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4269 v := s.newValue3(ssa.OpAtomicExchange32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], args[1], s.mem())
4270 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4271 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4273 sys.AMD64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4274 addF("runtime/internal/atomic", "Xchg64",
4275 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4276 v := s.newValue3(ssa.OpAtomicExchange64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], args[1], s.mem())
4277 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4278 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4280 sys.AMD64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4282 type atomicOpEmitter func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind)
4284 makeAtomicGuardedIntrinsicARM64 := func(op0, op1 ssa.Op, typ, rtyp types.Kind, emit atomicOpEmitter) intrinsicBuilder {
4286 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4287 // Target Atomic feature is identified by dynamic detection
4288 addr := s.entryNewValue1A(ssa.OpAddr, types.Types[types.TBOOL].PtrTo(), ir.Syms.ARM64HasATOMICS, s.sb)
4289 v := s.load(types.Types[types.TBOOL], addr)
4291 b.Kind = ssa.BlockIf
4293 bTrue := s.f.NewBlock(ssa.BlockPlain)
4294 bFalse := s.f.NewBlock(ssa.BlockPlain)
4295 bEnd := s.f.NewBlock(ssa.BlockPlain)
4298 b.Likely = ssa.BranchLikely
4300 // We have atomic instructions - use it directly.
4302 emit(s, n, args, op1, typ)
4303 s.endBlock().AddEdgeTo(bEnd)
4305 // Use original instruction sequence.
4306 s.startBlock(bFalse)
4307 emit(s, n, args, op0, typ)
4308 s.endBlock().AddEdgeTo(bEnd)
4312 if rtyp == types.TNIL {
4315 return s.variable(n, types.Types[rtyp])
4320 atomicXchgXaddEmitterARM64 := func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind) {
4321 v := s.newValue3(op, types.NewTuple(types.Types[typ], types.TypeMem), args[0], args[1], s.mem())
4322 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4323 s.vars[n] = s.newValue1(ssa.OpSelect0, types.Types[typ], v)
4325 addF("runtime/internal/atomic", "Xchg",
4326 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicExchange32, ssa.OpAtomicExchange32Variant, types.TUINT32, types.TUINT32, atomicXchgXaddEmitterARM64),
4328 addF("runtime/internal/atomic", "Xchg64",
4329 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicExchange64, ssa.OpAtomicExchange64Variant, types.TUINT64, types.TUINT64, atomicXchgXaddEmitterARM64),
4332 addF("runtime/internal/atomic", "Xadd",
4333 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4334 v := s.newValue3(ssa.OpAtomicAdd32, types.NewTuple(types.Types[types.TUINT32], types.TypeMem), args[0], args[1], s.mem())
4335 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4336 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT32], v)
4338 sys.AMD64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4339 addF("runtime/internal/atomic", "Xadd64",
4340 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4341 v := s.newValue3(ssa.OpAtomicAdd64, types.NewTuple(types.Types[types.TUINT64], types.TypeMem), args[0], args[1], s.mem())
4342 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4343 return s.newValue1(ssa.OpSelect0, types.Types[types.TUINT64], v)
4345 sys.AMD64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4347 addF("runtime/internal/atomic", "Xadd",
4348 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAdd32, ssa.OpAtomicAdd32Variant, types.TUINT32, types.TUINT32, atomicXchgXaddEmitterARM64),
4350 addF("runtime/internal/atomic", "Xadd64",
4351 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAdd64, ssa.OpAtomicAdd64Variant, types.TUINT64, types.TUINT64, atomicXchgXaddEmitterARM64),
4354 addF("runtime/internal/atomic", "Cas",
4355 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4356 v := s.newValue4(ssa.OpAtomicCompareAndSwap32, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4357 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4358 return s.newValue1(ssa.OpSelect0, types.Types[types.TBOOL], v)
4360 sys.AMD64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4361 addF("runtime/internal/atomic", "Cas64",
4362 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4363 v := s.newValue4(ssa.OpAtomicCompareAndSwap64, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4364 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4365 return s.newValue1(ssa.OpSelect0, types.Types[types.TBOOL], v)
4367 sys.AMD64, sys.Loong64, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4368 addF("runtime/internal/atomic", "CasRel",
4369 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4370 v := s.newValue4(ssa.OpAtomicCompareAndSwap32, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4371 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4372 return s.newValue1(ssa.OpSelect0, types.Types[types.TBOOL], v)
4376 atomicCasEmitterARM64 := func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind) {
4377 v := s.newValue4(op, types.NewTuple(types.Types[types.TBOOL], types.TypeMem), args[0], args[1], args[2], s.mem())
4378 s.vars[memVar] = s.newValue1(ssa.OpSelect1, types.TypeMem, v)
4379 s.vars[n] = s.newValue1(ssa.OpSelect0, types.Types[typ], v)
4382 addF("runtime/internal/atomic", "Cas",
4383 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicCompareAndSwap32, ssa.OpAtomicCompareAndSwap32Variant, types.TUINT32, types.TBOOL, atomicCasEmitterARM64),
4385 addF("runtime/internal/atomic", "Cas64",
4386 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicCompareAndSwap64, ssa.OpAtomicCompareAndSwap64Variant, types.TUINT64, types.TBOOL, atomicCasEmitterARM64),
4389 addF("runtime/internal/atomic", "And8",
4390 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4391 s.vars[memVar] = s.newValue3(ssa.OpAtomicAnd8, types.TypeMem, args[0], args[1], s.mem())
4394 sys.AMD64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4395 addF("runtime/internal/atomic", "And",
4396 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4397 s.vars[memVar] = s.newValue3(ssa.OpAtomicAnd32, types.TypeMem, args[0], args[1], s.mem())
4400 sys.AMD64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4401 addF("runtime/internal/atomic", "Or8",
4402 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4403 s.vars[memVar] = s.newValue3(ssa.OpAtomicOr8, types.TypeMem, args[0], args[1], s.mem())
4406 sys.AMD64, sys.ARM64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4407 addF("runtime/internal/atomic", "Or",
4408 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4409 s.vars[memVar] = s.newValue3(ssa.OpAtomicOr32, types.TypeMem, args[0], args[1], s.mem())
4412 sys.AMD64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X)
4414 atomicAndOrEmitterARM64 := func(s *state, n *ir.CallExpr, args []*ssa.Value, op ssa.Op, typ types.Kind) {
4415 s.vars[memVar] = s.newValue3(op, types.TypeMem, args[0], args[1], s.mem())
4418 addF("runtime/internal/atomic", "And8",
4419 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAnd8, ssa.OpAtomicAnd8Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4421 addF("runtime/internal/atomic", "And",
4422 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicAnd32, ssa.OpAtomicAnd32Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4424 addF("runtime/internal/atomic", "Or8",
4425 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicOr8, ssa.OpAtomicOr8Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4427 addF("runtime/internal/atomic", "Or",
4428 makeAtomicGuardedIntrinsicARM64(ssa.OpAtomicOr32, ssa.OpAtomicOr32Variant, types.TNIL, types.TNIL, atomicAndOrEmitterARM64),
4431 // Aliases for atomic load operations
4432 alias("runtime/internal/atomic", "Loadint32", "runtime/internal/atomic", "Load", all...)
4433 alias("runtime/internal/atomic", "Loadint64", "runtime/internal/atomic", "Load64", all...)
4434 alias("runtime/internal/atomic", "Loaduintptr", "runtime/internal/atomic", "Load", p4...)
4435 alias("runtime/internal/atomic", "Loaduintptr", "runtime/internal/atomic", "Load64", p8...)
4436 alias("runtime/internal/atomic", "Loaduint", "runtime/internal/atomic", "Load", p4...)
4437 alias("runtime/internal/atomic", "Loaduint", "runtime/internal/atomic", "Load64", p8...)
4438 alias("runtime/internal/atomic", "LoadAcq", "runtime/internal/atomic", "Load", lwatomics...)
4439 alias("runtime/internal/atomic", "LoadAcq64", "runtime/internal/atomic", "Load64", lwatomics...)
4440 alias("runtime/internal/atomic", "LoadAcquintptr", "runtime/internal/atomic", "LoadAcq", p4...)
4441 alias("sync", "runtime_LoadAcquintptr", "runtime/internal/atomic", "LoadAcq", p4...) // linknamed
4442 alias("runtime/internal/atomic", "LoadAcquintptr", "runtime/internal/atomic", "LoadAcq64", p8...)
4443 alias("sync", "runtime_LoadAcquintptr", "runtime/internal/atomic", "LoadAcq64", p8...) // linknamed
4445 // Aliases for atomic store operations
4446 alias("runtime/internal/atomic", "Storeint32", "runtime/internal/atomic", "Store", all...)
4447 alias("runtime/internal/atomic", "Storeint64", "runtime/internal/atomic", "Store64", all...)
4448 alias("runtime/internal/atomic", "Storeuintptr", "runtime/internal/atomic", "Store", p4...)
4449 alias("runtime/internal/atomic", "Storeuintptr", "runtime/internal/atomic", "Store64", p8...)
4450 alias("runtime/internal/atomic", "StoreRel", "runtime/internal/atomic", "Store", lwatomics...)
4451 alias("runtime/internal/atomic", "StoreRel64", "runtime/internal/atomic", "Store64", lwatomics...)
4452 alias("runtime/internal/atomic", "StoreReluintptr", "runtime/internal/atomic", "StoreRel", p4...)
4453 alias("sync", "runtime_StoreReluintptr", "runtime/internal/atomic", "StoreRel", p4...) // linknamed
4454 alias("runtime/internal/atomic", "StoreReluintptr", "runtime/internal/atomic", "StoreRel64", p8...)
4455 alias("sync", "runtime_StoreReluintptr", "runtime/internal/atomic", "StoreRel64", p8...) // linknamed
4457 // Aliases for atomic swap operations
4458 alias("runtime/internal/atomic", "Xchgint32", "runtime/internal/atomic", "Xchg", all...)
4459 alias("runtime/internal/atomic", "Xchgint64", "runtime/internal/atomic", "Xchg64", all...)
4460 alias("runtime/internal/atomic", "Xchguintptr", "runtime/internal/atomic", "Xchg", p4...)
4461 alias("runtime/internal/atomic", "Xchguintptr", "runtime/internal/atomic", "Xchg64", p8...)
4463 // Aliases for atomic add operations
4464 alias("runtime/internal/atomic", "Xaddint32", "runtime/internal/atomic", "Xadd", all...)
4465 alias("runtime/internal/atomic", "Xaddint64", "runtime/internal/atomic", "Xadd64", all...)
4466 alias("runtime/internal/atomic", "Xadduintptr", "runtime/internal/atomic", "Xadd", p4...)
4467 alias("runtime/internal/atomic", "Xadduintptr", "runtime/internal/atomic", "Xadd64", p8...)
4469 // Aliases for atomic CAS operations
4470 alias("runtime/internal/atomic", "Casint32", "runtime/internal/atomic", "Cas", all...)
4471 alias("runtime/internal/atomic", "Casint64", "runtime/internal/atomic", "Cas64", all...)
4472 alias("runtime/internal/atomic", "Casuintptr", "runtime/internal/atomic", "Cas", p4...)
4473 alias("runtime/internal/atomic", "Casuintptr", "runtime/internal/atomic", "Cas64", p8...)
4474 alias("runtime/internal/atomic", "Casp1", "runtime/internal/atomic", "Cas", p4...)
4475 alias("runtime/internal/atomic", "Casp1", "runtime/internal/atomic", "Cas64", p8...)
4476 alias("runtime/internal/atomic", "CasRel", "runtime/internal/atomic", "Cas", lwatomics...)
4478 /******** math ********/
4479 addF("math", "sqrt",
4480 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4481 return s.newValue1(ssa.OpSqrt, types.Types[types.TFLOAT64], args[0])
4483 sys.I386, sys.AMD64, sys.ARM, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64, sys.PPC64, sys.RISCV64, sys.S390X, sys.Wasm)
4484 addF("math", "Trunc",
4485 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4486 return s.newValue1(ssa.OpTrunc, types.Types[types.TFLOAT64], args[0])
4488 sys.ARM64, sys.PPC64, sys.S390X, sys.Wasm)
4489 addF("math", "Ceil",
4490 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4491 return s.newValue1(ssa.OpCeil, types.Types[types.TFLOAT64], args[0])
4493 sys.ARM64, sys.PPC64, sys.S390X, sys.Wasm)
4494 addF("math", "Floor",
4495 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4496 return s.newValue1(ssa.OpFloor, types.Types[types.TFLOAT64], args[0])
4498 sys.ARM64, sys.PPC64, sys.S390X, sys.Wasm)
4499 addF("math", "Round",
4500 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4501 return s.newValue1(ssa.OpRound, types.Types[types.TFLOAT64], args[0])
4503 sys.ARM64, sys.PPC64, sys.S390X)
4504 addF("math", "RoundToEven",
4505 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4506 return s.newValue1(ssa.OpRoundToEven, types.Types[types.TFLOAT64], args[0])
4508 sys.ARM64, sys.S390X, sys.Wasm)
4510 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4511 return s.newValue1(ssa.OpAbs, types.Types[types.TFLOAT64], args[0])
4513 sys.ARM64, sys.ARM, sys.PPC64, sys.RISCV64, sys.Wasm, sys.MIPS, sys.MIPS64)
4514 addF("math", "Copysign",
4515 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4516 return s.newValue2(ssa.OpCopysign, types.Types[types.TFLOAT64], args[0], args[1])
4518 sys.PPC64, sys.RISCV64, sys.Wasm)
4520 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4521 return s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4523 sys.ARM64, sys.PPC64, sys.RISCV64, sys.S390X)
4525 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4526 if !s.config.UseFMA {
4527 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4528 return s.variable(n, types.Types[types.TFLOAT64])
4531 if buildcfg.GOAMD64 >= 3 {
4532 return s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4535 v := s.entryNewValue0A(ssa.OpHasCPUFeature, types.Types[types.TBOOL], ir.Syms.X86HasFMA)
4537 b.Kind = ssa.BlockIf
4539 bTrue := s.f.NewBlock(ssa.BlockPlain)
4540 bFalse := s.f.NewBlock(ssa.BlockPlain)
4541 bEnd := s.f.NewBlock(ssa.BlockPlain)
4544 b.Likely = ssa.BranchLikely // >= haswell cpus are common
4546 // We have the intrinsic - use it directly.
4548 s.vars[n] = s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4549 s.endBlock().AddEdgeTo(bEnd)
4551 // Call the pure Go version.
4552 s.startBlock(bFalse)
4553 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4554 s.endBlock().AddEdgeTo(bEnd)
4558 return s.variable(n, types.Types[types.TFLOAT64])
4562 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4563 if !s.config.UseFMA {
4564 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4565 return s.variable(n, types.Types[types.TFLOAT64])
4567 addr := s.entryNewValue1A(ssa.OpAddr, types.Types[types.TBOOL].PtrTo(), ir.Syms.ARMHasVFPv4, s.sb)
4568 v := s.load(types.Types[types.TBOOL], addr)
4570 b.Kind = ssa.BlockIf
4572 bTrue := s.f.NewBlock(ssa.BlockPlain)
4573 bFalse := s.f.NewBlock(ssa.BlockPlain)
4574 bEnd := s.f.NewBlock(ssa.BlockPlain)
4577 b.Likely = ssa.BranchLikely
4579 // We have the intrinsic - use it directly.
4581 s.vars[n] = s.newValue3(ssa.OpFMA, types.Types[types.TFLOAT64], args[0], args[1], args[2])
4582 s.endBlock().AddEdgeTo(bEnd)
4584 // Call the pure Go version.
4585 s.startBlock(bFalse)
4586 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4587 s.endBlock().AddEdgeTo(bEnd)
4591 return s.variable(n, types.Types[types.TFLOAT64])
4595 makeRoundAMD64 := func(op ssa.Op) func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4596 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4597 if buildcfg.GOAMD64 >= 2 {
4598 return s.newValue1(op, types.Types[types.TFLOAT64], args[0])
4601 v := s.entryNewValue0A(ssa.OpHasCPUFeature, types.Types[types.TBOOL], ir.Syms.X86HasSSE41)
4603 b.Kind = ssa.BlockIf
4605 bTrue := s.f.NewBlock(ssa.BlockPlain)
4606 bFalse := s.f.NewBlock(ssa.BlockPlain)
4607 bEnd := s.f.NewBlock(ssa.BlockPlain)
4610 b.Likely = ssa.BranchLikely // most machines have sse4.1 nowadays
4612 // We have the intrinsic - use it directly.
4614 s.vars[n] = s.newValue1(op, types.Types[types.TFLOAT64], args[0])
4615 s.endBlock().AddEdgeTo(bEnd)
4617 // Call the pure Go version.
4618 s.startBlock(bFalse)
4619 s.vars[n] = s.callResult(n, callNormal) // types.Types[TFLOAT64]
4620 s.endBlock().AddEdgeTo(bEnd)
4624 return s.variable(n, types.Types[types.TFLOAT64])
4627 addF("math", "RoundToEven",
4628 makeRoundAMD64(ssa.OpRoundToEven),
4630 addF("math", "Floor",
4631 makeRoundAMD64(ssa.OpFloor),
4633 addF("math", "Ceil",
4634 makeRoundAMD64(ssa.OpCeil),
4636 addF("math", "Trunc",
4637 makeRoundAMD64(ssa.OpTrunc),
4640 /******** math/bits ********/
4641 addF("math/bits", "TrailingZeros64",
4642 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4643 return s.newValue1(ssa.OpCtz64, types.Types[types.TINT], args[0])
4645 sys.AMD64, sys.I386, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4646 addF("math/bits", "TrailingZeros32",
4647 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4648 return s.newValue1(ssa.OpCtz32, types.Types[types.TINT], args[0])
4650 sys.AMD64, sys.I386, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4651 addF("math/bits", "TrailingZeros16",
4652 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4653 x := s.newValue1(ssa.OpZeroExt16to32, types.Types[types.TUINT32], args[0])
4654 c := s.constInt32(types.Types[types.TUINT32], 1<<16)
4655 y := s.newValue2(ssa.OpOr32, types.Types[types.TUINT32], x, c)
4656 return s.newValue1(ssa.OpCtz32, types.Types[types.TINT], y)
4659 addF("math/bits", "TrailingZeros16",
4660 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4661 return s.newValue1(ssa.OpCtz16, types.Types[types.TINT], args[0])
4663 sys.AMD64, sys.I386, sys.ARM, sys.ARM64, sys.Wasm)
4664 addF("math/bits", "TrailingZeros16",
4665 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4666 x := s.newValue1(ssa.OpZeroExt16to64, types.Types[types.TUINT64], args[0])
4667 c := s.constInt64(types.Types[types.TUINT64], 1<<16)
4668 y := s.newValue2(ssa.OpOr64, types.Types[types.TUINT64], x, c)
4669 return s.newValue1(ssa.OpCtz64, types.Types[types.TINT], y)
4671 sys.S390X, sys.PPC64)
4672 addF("math/bits", "TrailingZeros8",
4673 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4674 x := s.newValue1(ssa.OpZeroExt8to32, types.Types[types.TUINT32], args[0])
4675 c := s.constInt32(types.Types[types.TUINT32], 1<<8)
4676 y := s.newValue2(ssa.OpOr32, types.Types[types.TUINT32], x, c)
4677 return s.newValue1(ssa.OpCtz32, types.Types[types.TINT], y)
4680 addF("math/bits", "TrailingZeros8",
4681 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4682 return s.newValue1(ssa.OpCtz8, types.Types[types.TINT], args[0])
4684 sys.AMD64, sys.I386, sys.ARM, sys.ARM64, sys.Wasm)
4685 addF("math/bits", "TrailingZeros8",
4686 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4687 x := s.newValue1(ssa.OpZeroExt8to64, types.Types[types.TUINT64], args[0])
4688 c := s.constInt64(types.Types[types.TUINT64], 1<<8)
4689 y := s.newValue2(ssa.OpOr64, types.Types[types.TUINT64], x, c)
4690 return s.newValue1(ssa.OpCtz64, types.Types[types.TINT], y)
4693 alias("math/bits", "ReverseBytes64", "runtime/internal/sys", "Bswap64", all...)
4694 alias("math/bits", "ReverseBytes32", "runtime/internal/sys", "Bswap32", all...)
4695 // ReverseBytes inlines correctly, no need to intrinsify it.
4696 // Nothing special is needed for targets where ReverseBytes16 lowers to a rotate
4697 // On Power10, 16-bit rotate is not available so use BRH instruction
4698 if buildcfg.GOPPC64 >= 10 {
4699 addF("math/bits", "ReverseBytes16",
4700 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4701 return s.newValue1(ssa.OpBswap16, types.Types[types.TUINT], args[0])
4706 addF("math/bits", "Len64",
4707 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4708 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], args[0])
4710 sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4711 addF("math/bits", "Len32",
4712 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4713 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], args[0])
4715 sys.AMD64, sys.ARM64, sys.PPC64)
4716 addF("math/bits", "Len32",
4717 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4718 if s.config.PtrSize == 4 {
4719 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], args[0])
4721 x := s.newValue1(ssa.OpZeroExt32to64, types.Types[types.TUINT64], args[0])
4722 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], x)
4724 sys.ARM, sys.S390X, sys.MIPS, sys.Wasm)
4725 addF("math/bits", "Len16",
4726 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4727 if s.config.PtrSize == 4 {
4728 x := s.newValue1(ssa.OpZeroExt16to32, types.Types[types.TUINT32], args[0])
4729 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], x)
4731 x := s.newValue1(ssa.OpZeroExt16to64, types.Types[types.TUINT64], args[0])
4732 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], x)
4734 sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4735 addF("math/bits", "Len16",
4736 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4737 return s.newValue1(ssa.OpBitLen16, types.Types[types.TINT], args[0])
4740 addF("math/bits", "Len8",
4741 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4742 if s.config.PtrSize == 4 {
4743 x := s.newValue1(ssa.OpZeroExt8to32, types.Types[types.TUINT32], args[0])
4744 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], x)
4746 x := s.newValue1(ssa.OpZeroExt8to64, types.Types[types.TUINT64], args[0])
4747 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], x)
4749 sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4750 addF("math/bits", "Len8",
4751 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4752 return s.newValue1(ssa.OpBitLen8, types.Types[types.TINT], args[0])
4755 addF("math/bits", "Len",
4756 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4757 if s.config.PtrSize == 4 {
4758 return s.newValue1(ssa.OpBitLen32, types.Types[types.TINT], args[0])
4760 return s.newValue1(ssa.OpBitLen64, types.Types[types.TINT], args[0])
4762 sys.AMD64, sys.ARM64, sys.ARM, sys.S390X, sys.MIPS, sys.PPC64, sys.Wasm)
4763 // LeadingZeros is handled because it trivially calls Len.
4764 addF("math/bits", "Reverse64",
4765 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4766 return s.newValue1(ssa.OpBitRev64, types.Types[types.TINT], args[0])
4769 addF("math/bits", "Reverse32",
4770 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4771 return s.newValue1(ssa.OpBitRev32, types.Types[types.TINT], args[0])
4774 addF("math/bits", "Reverse16",
4775 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4776 return s.newValue1(ssa.OpBitRev16, types.Types[types.TINT], args[0])
4779 addF("math/bits", "Reverse8",
4780 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4781 return s.newValue1(ssa.OpBitRev8, types.Types[types.TINT], args[0])
4784 addF("math/bits", "Reverse",
4785 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4786 return s.newValue1(ssa.OpBitRev64, types.Types[types.TINT], args[0])
4789 addF("math/bits", "RotateLeft8",
4790 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4791 return s.newValue2(ssa.OpRotateLeft8, types.Types[types.TUINT8], args[0], args[1])
4794 addF("math/bits", "RotateLeft16",
4795 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4796 return s.newValue2(ssa.OpRotateLeft16, types.Types[types.TUINT16], args[0], args[1])
4799 addF("math/bits", "RotateLeft32",
4800 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4801 return s.newValue2(ssa.OpRotateLeft32, types.Types[types.TUINT32], args[0], args[1])
4803 sys.AMD64, sys.ARM, sys.ARM64, sys.S390X, sys.PPC64, sys.Wasm, sys.Loong64)
4804 addF("math/bits", "RotateLeft64",
4805 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4806 return s.newValue2(ssa.OpRotateLeft64, types.Types[types.TUINT64], args[0], args[1])
4808 sys.AMD64, sys.ARM64, sys.S390X, sys.PPC64, sys.Wasm, sys.Loong64)
4809 alias("math/bits", "RotateLeft", "math/bits", "RotateLeft64", p8...)
4811 makeOnesCountAMD64 := func(op ssa.Op) func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4812 return func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4813 if buildcfg.GOAMD64 >= 2 {
4814 return s.newValue1(op, types.Types[types.TINT], args[0])
4817 v := s.entryNewValue0A(ssa.OpHasCPUFeature, types.Types[types.TBOOL], ir.Syms.X86HasPOPCNT)
4819 b.Kind = ssa.BlockIf
4821 bTrue := s.f.NewBlock(ssa.BlockPlain)
4822 bFalse := s.f.NewBlock(ssa.BlockPlain)
4823 bEnd := s.f.NewBlock(ssa.BlockPlain)
4826 b.Likely = ssa.BranchLikely // most machines have popcnt nowadays
4828 // We have the intrinsic - use it directly.
4830 s.vars[n] = s.newValue1(op, types.Types[types.TINT], args[0])
4831 s.endBlock().AddEdgeTo(bEnd)
4833 // Call the pure Go version.
4834 s.startBlock(bFalse)
4835 s.vars[n] = s.callResult(n, callNormal) // types.Types[TINT]
4836 s.endBlock().AddEdgeTo(bEnd)
4840 return s.variable(n, types.Types[types.TINT])
4843 addF("math/bits", "OnesCount64",
4844 makeOnesCountAMD64(ssa.OpPopCount64),
4846 addF("math/bits", "OnesCount64",
4847 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4848 return s.newValue1(ssa.OpPopCount64, types.Types[types.TINT], args[0])
4850 sys.PPC64, sys.ARM64, sys.S390X, sys.Wasm)
4851 addF("math/bits", "OnesCount32",
4852 makeOnesCountAMD64(ssa.OpPopCount32),
4854 addF("math/bits", "OnesCount32",
4855 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4856 return s.newValue1(ssa.OpPopCount32, types.Types[types.TINT], args[0])
4858 sys.PPC64, sys.ARM64, sys.S390X, sys.Wasm)
4859 addF("math/bits", "OnesCount16",
4860 makeOnesCountAMD64(ssa.OpPopCount16),
4862 addF("math/bits", "OnesCount16",
4863 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4864 return s.newValue1(ssa.OpPopCount16, types.Types[types.TINT], args[0])
4866 sys.ARM64, sys.S390X, sys.PPC64, sys.Wasm)
4867 addF("math/bits", "OnesCount8",
4868 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4869 return s.newValue1(ssa.OpPopCount8, types.Types[types.TINT], args[0])
4871 sys.S390X, sys.PPC64, sys.Wasm)
4872 addF("math/bits", "OnesCount",
4873 makeOnesCountAMD64(ssa.OpPopCount64),
4875 addF("math/bits", "Mul64",
4876 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4877 return s.newValue2(ssa.OpMul64uhilo, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1])
4879 sys.AMD64, sys.ARM64, sys.PPC64, sys.S390X, sys.MIPS64, sys.RISCV64, sys.Loong64)
4880 alias("math/bits", "Mul", "math/bits", "Mul64", p8...)
4881 alias("runtime/internal/math", "Mul64", "math/bits", "Mul64", p8...)
4882 addF("math/bits", "Add64",
4883 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4884 return s.newValue3(ssa.OpAdd64carry, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1], args[2])
4886 sys.AMD64, sys.ARM64, sys.PPC64, sys.S390X, sys.RISCV64, sys.Loong64, sys.MIPS64)
4887 alias("math/bits", "Add", "math/bits", "Add64", p8...)
4888 alias("runtime/internal/math", "Add64", "math/bits", "Add64", all...)
4889 addF("math/bits", "Sub64",
4890 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4891 return s.newValue3(ssa.OpSub64borrow, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1], args[2])
4893 sys.AMD64, sys.ARM64, sys.PPC64, sys.S390X, sys.RISCV64, sys.Loong64, sys.MIPS64)
4894 alias("math/bits", "Sub", "math/bits", "Sub64", p8...)
4895 addF("math/bits", "Div64",
4896 func(s *state, n *ir.CallExpr, args []*ssa.Value) *ssa.Value {
4897 // check for divide-by-zero/overflow and panic with appropriate message
4898 cmpZero := s.newValue2(s.ssaOp(ir.ONE, types.Types[types.TUINT64]), types.Types[types.TBOOL], args[2], s.zeroVal(types.Types[types.TUINT64]))
4899 s.check(cmpZero, ir.Syms.Panicdivide)
4900 cmpOverflow := s.newValue2(s.ssaOp(ir.OLT, types.Types[types.TUINT64]), types.Types[types.TBOOL], args[0], args[2])
4901 s.check(cmpOverflow, ir.Syms.Panicoverflow)
4902 return s.newValue3(ssa.OpDiv128u, types.NewTuple(types.Types[types.TUINT64], types.Types[types.TUINT64]), args[0], args[1], args[2])
4905 alias("math/bits", "Div", "math/bits", "Div64", sys.ArchAMD64)
4907 alias("runtime/internal/sys", "TrailingZeros8", "math/bits", "TrailingZeros8", all...)
4908 alias("runtime/internal/sys", "TrailingZeros32", "math/bits", "TrailingZeros32", all...)
4909 alias("runtime/internal/sys", "TrailingZeros64", "math/bits", "TrailingZeros64", all...)
4910 alias("runtime/internal/sys", "Len8", "math/bits", "Len8", all...)
4911 alias("runtime/internal/sys", "Len64", "math/bits", "Len64", all...)
4912 alias("runtime/internal/sys", "OnesCount64", "math/bits", "OnesCount64", all...)
4914 /******** sync/atomic ********/
4916 // Note: these are disabled by flag_race in findIntrinsic below.
4917 alias("sync/atomic", "LoadInt32", "runtime/internal/atomic", "Load", all...)
4918 alias("sync/atomic", "LoadInt64", "runtime/internal/atomic", "Load64", all...)
4919 alias("sync/atomic", "LoadPointer", "runtime/internal/atomic", "Loadp", all...)
4920 alias("sync/atomic", "LoadUint32", "runtime/internal/atomic", "Load", all...)
4921 alias("sync/atomic", "LoadUint64", "runtime/internal/atomic", "Load64", all...)
4922 alias("sync/atomic", "LoadUintptr", "runtime/internal/atomic", "Load", p4...)
4923 alias("sync/atomic", "LoadUintptr", "runtime/internal/atomic", "Load64", p8...)
4925 alias("sync/atomic", "StoreInt32", "runtime/internal/atomic", "Store", all...)
4926 alias("sync/atomic", "StoreInt64", "runtime/internal/atomic", "Store64", all...)
4927 // Note: not StorePointer, that needs a write barrier. Same below for {CompareAnd}Swap.
4928 alias("sync/atomic", "StoreUint32", "runtime/internal/atomic", "Store", all...)
4929 alias("sync/atomic", "StoreUint64", "runtime/internal/atomic", "Store64", all...)
4930 alias("sync/atomic", "StoreUintptr", "runtime/internal/atomic", "Store", p4...)
4931 alias("sync/atomic", "StoreUintptr", "runtime/internal/atomic", "Store64", p8...)
4933 alias("sync/atomic", "SwapInt32", "runtime/internal/atomic", "Xchg", all...)
4934 alias("sync/atomic", "SwapInt64", "runtime/internal/atomic", "Xchg64", all...)
4935 alias("sync/atomic", "SwapUint32", "runtime/internal/atomic", "Xchg", all...)
4936 alias("sync/atomic", "SwapUint64", "runtime/internal/atomic", "Xchg64", all...)
4937 alias("sync/atomic", "SwapUintptr", "runtime/internal/atomic", "Xchg", p4...)
4938 alias("sync/atomic", "SwapUintptr", "runtime/internal/atomic", "Xchg64", p8...)
4940 alias("sync/atomic", "CompareAndSwapInt32", "runtime/internal/atomic", "Cas", all...)
4941 alias("sync/atomic", "CompareAndSwapInt64", "runtime/internal/atomic", "Cas64", all...)
4942 alias("sync/atomic", "CompareAndSwapUint32", "runtime/internal/atomic", "Cas", all...)
4943 alias("sync/atomic", "CompareAndSwapUint64", "runtime/internal/atomic", "Cas64", all...)
4944 alias("sync/atomic", "CompareAndSwapUintptr", "runtime/internal/atomic", "Cas", p4...)
4945 alias("sync/atomic", "CompareAndSwapUintptr", "runtime/internal/atomic", "Cas64", p8...)
4947 alias("sync/atomic", "AddInt32", "runtime/internal/atomic", "Xadd", all...)
4948 alias("sync/atomic", "AddInt64", "runtime/internal/atomic", "Xadd64", all...)
4949 alias("sync/atomic", "AddUint32", "runtime/internal/atomic", "Xadd", all...)
4950 alias("sync/atomic", "AddUint64", "runtime/internal/atomic", "Xadd64", all...)
4951 alias("sync/atomic", "AddUintptr", "runtime/internal/atomic", "Xadd", p4...)
4952 alias("sync/atomic", "AddUintptr", "runtime/internal/atomic", "Xadd64", p8...)
4954 /******** math/big ********/
4955 alias("math/big", "mulWW", "math/bits", "Mul64", p8...)
4958 // findIntrinsic returns a function which builds the SSA equivalent of the
4959 // function identified by the symbol sym. If sym is not an intrinsic call, returns nil.
4960 func findIntrinsic(sym *types.Sym) intrinsicBuilder {
4961 if sym == nil || sym.Pkg == nil {
4965 if sym.Pkg == ir.Pkgs.Runtime {
4968 if base.Flag.Race && pkg == "sync/atomic" {
4969 // The race detector needs to be able to intercept these calls.
4970 // We can't intrinsify them.
4973 // Skip intrinsifying math functions (which may contain hard-float
4974 // instructions) when soft-float
4975 if Arch.SoftFloat && pkg == "math" {
4980 if ssa.IntrinsicsDisable {
4981 if pkg == "runtime" && (fn == "getcallerpc" || fn == "getcallersp" || fn == "getclosureptr") {
4982 // These runtime functions don't have definitions, must be intrinsics.
4987 return intrinsics[intrinsicKey{Arch.LinkArch.Arch, pkg, fn}]
4990 func IsIntrinsicCall(n *ir.CallExpr) bool {
4994 name, ok := n.X.(*ir.Name)
4998 return findIntrinsic(name.Sym()) != nil
5001 // intrinsicCall converts a call to a recognized intrinsic function into the intrinsic SSA operation.
5002 func (s *state) intrinsicCall(n *ir.CallExpr) *ssa.Value {
5003 v := findIntrinsic(n.X.Sym())(s, n, s.intrinsicArgs(n))
5004 if ssa.IntrinsicsDebug > 0 {
5009 if x.Op == ssa.OpSelect0 || x.Op == ssa.OpSelect1 {
5012 base.WarnfAt(n.Pos(), "intrinsic substitution for %v with %s", n.X.Sym().Name, x.LongString())
5017 // intrinsicArgs extracts args from n, evaluates them to SSA values, and returns them.
5018 func (s *state) intrinsicArgs(n *ir.CallExpr) []*ssa.Value {
5019 args := make([]*ssa.Value, len(n.Args))
5020 for i, n := range n.Args {
5026 // openDeferRecord adds code to evaluate and store the function for an open-code defer
5027 // call, and records info about the defer, so we can generate proper code on the
5028 // exit paths. n is the sub-node of the defer node that is the actual function
5029 // call. We will also record funcdata information on where the function is stored
5030 // (as well as the deferBits variable), and this will enable us to run the proper
5031 // defer calls during panics.
5032 func (s *state) openDeferRecord(n *ir.CallExpr) {
5033 if len(n.Args) != 0 || n.Op() != ir.OCALLFUNC || n.X.Type().NumResults() != 0 {
5034 s.Fatalf("defer call with arguments or results: %v", n)
5037 opendefer := &openDeferInfo{
5041 // We must always store the function value in a stack slot for the
5042 // runtime panic code to use. But in the defer exit code, we will
5043 // call the function directly if it is a static function.
5044 closureVal := s.expr(fn)
5045 closure := s.openDeferSave(fn.Type(), closureVal)
5046 opendefer.closureNode = closure.Aux.(*ir.Name)
5047 if !(fn.Op() == ir.ONAME && fn.(*ir.Name).Class == ir.PFUNC) {
5048 opendefer.closure = closure
5050 index := len(s.openDefers)
5051 s.openDefers = append(s.openDefers, opendefer)
5053 // Update deferBits only after evaluation and storage to stack of
5054 // the function is successful.
5055 bitvalue := s.constInt8(types.Types[types.TUINT8], 1<<uint(index))
5056 newDeferBits := s.newValue2(ssa.OpOr8, types.Types[types.TUINT8], s.variable(deferBitsVar, types.Types[types.TUINT8]), bitvalue)
5057 s.vars[deferBitsVar] = newDeferBits
5058 s.store(types.Types[types.TUINT8], s.deferBitsAddr, newDeferBits)
5061 // openDeferSave generates SSA nodes to store a value (with type t) for an
5062 // open-coded defer at an explicit autotmp location on the stack, so it can be
5063 // reloaded and used for the appropriate call on exit. Type t must be a function type
5064 // (therefore SSAable). val is the value to be stored. The function returns an SSA
5065 // value representing a pointer to the autotmp location.
5066 func (s *state) openDeferSave(t *types.Type, val *ssa.Value) *ssa.Value {
5068 s.Fatalf("openDeferSave of non-SSA-able type %v val=%v", t, val)
5070 if !t.HasPointers() {
5071 s.Fatalf("openDeferSave of pointerless type %v val=%v", t, val)
5074 temp := typecheck.TempAt(pos.WithNotStmt(), s.curfn, t)
5075 temp.SetOpenDeferSlot(true)
5076 temp.SetFrameOffset(int64(len(s.openDefers))) // so cmpstackvarlt can order them
5077 var addrTemp *ssa.Value
5078 // Use OpVarLive to make sure stack slot for the closure is not removed by
5079 // dead-store elimination
5080 if s.curBlock.ID != s.f.Entry.ID {
5081 // Force the tmp storing this defer function to be declared in the entry
5082 // block, so that it will be live for the defer exit code (which will
5083 // actually access it only if the associated defer call has been activated).
5084 if t.HasPointers() {
5085 s.defvars[s.f.Entry.ID][memVar] = s.f.Entry.NewValue1A(src.NoXPos, ssa.OpVarDef, types.TypeMem, temp, s.defvars[s.f.Entry.ID][memVar])
5087 s.defvars[s.f.Entry.ID][memVar] = s.f.Entry.NewValue1A(src.NoXPos, ssa.OpVarLive, types.TypeMem, temp, s.defvars[s.f.Entry.ID][memVar])
5088 addrTemp = s.f.Entry.NewValue2A(src.NoXPos, ssa.OpLocalAddr, types.NewPtr(temp.Type()), temp, s.sp, s.defvars[s.f.Entry.ID][memVar])
5090 // Special case if we're still in the entry block. We can't use
5091 // the above code, since s.defvars[s.f.Entry.ID] isn't defined
5092 // until we end the entry block with s.endBlock().
5093 if t.HasPointers() {
5094 s.vars[memVar] = s.newValue1Apos(ssa.OpVarDef, types.TypeMem, temp, s.mem(), false)
5096 s.vars[memVar] = s.newValue1Apos(ssa.OpVarLive, types.TypeMem, temp, s.mem(), false)
5097 addrTemp = s.newValue2Apos(ssa.OpLocalAddr, types.NewPtr(temp.Type()), temp, s.sp, s.mem(), false)
5099 // Since we may use this temp during exit depending on the
5100 // deferBits, we must define it unconditionally on entry.
5101 // Therefore, we must make sure it is zeroed out in the entry
5102 // block if it contains pointers, else GC may wrongly follow an
5103 // uninitialized pointer value.
5104 temp.SetNeedzero(true)
5105 // We are storing to the stack, hence we can avoid the full checks in
5106 // storeType() (no write barrier) and do a simple store().
5107 s.store(t, addrTemp, val)
5111 // openDeferExit generates SSA for processing all the open coded defers at exit.
5112 // The code involves loading deferBits, and checking each of the bits to see if
5113 // the corresponding defer statement was executed. For each bit that is turned
5114 // on, the associated defer call is made.
5115 func (s *state) openDeferExit() {
5116 deferExit := s.f.NewBlock(ssa.BlockPlain)
5117 s.endBlock().AddEdgeTo(deferExit)
5118 s.startBlock(deferExit)
5119 s.lastDeferExit = deferExit
5120 s.lastDeferCount = len(s.openDefers)
5121 zeroval := s.constInt8(types.Types[types.TUINT8], 0)
5122 // Test for and run defers in reverse order
5123 for i := len(s.openDefers) - 1; i >= 0; i-- {
5124 r := s.openDefers[i]
5125 bCond := s.f.NewBlock(ssa.BlockPlain)
5126 bEnd := s.f.NewBlock(ssa.BlockPlain)
5128 deferBits := s.variable(deferBitsVar, types.Types[types.TUINT8])
5129 // Generate code to check if the bit associated with the current
5131 bitval := s.constInt8(types.Types[types.TUINT8], 1<<uint(i))
5132 andval := s.newValue2(ssa.OpAnd8, types.Types[types.TUINT8], deferBits, bitval)
5133 eqVal := s.newValue2(ssa.OpEq8, types.Types[types.TBOOL], andval, zeroval)
5135 b.Kind = ssa.BlockIf
5139 bCond.AddEdgeTo(bEnd)
5142 // Clear this bit in deferBits and force store back to stack, so
5143 // we will not try to re-run this defer call if this defer call panics.
5144 nbitval := s.newValue1(ssa.OpCom8, types.Types[types.TUINT8], bitval)
5145 maskedval := s.newValue2(ssa.OpAnd8, types.Types[types.TUINT8], deferBits, nbitval)
5146 s.store(types.Types[types.TUINT8], s.deferBitsAddr, maskedval)
5147 // Use this value for following tests, so we keep previous
5149 s.vars[deferBitsVar] = maskedval
5151 // Generate code to call the function call of the defer, using the
5152 // closure that were stored in argtmps at the point of the defer
5155 stksize := fn.Type().ArgWidth()
5156 var callArgs []*ssa.Value
5158 if r.closure != nil {
5159 v := s.load(r.closure.Type.Elem(), r.closure)
5160 s.maybeNilCheckClosure(v, callDefer)
5161 codeptr := s.rawLoad(types.Types[types.TUINTPTR], v)
5162 aux := ssa.ClosureAuxCall(s.f.ABIDefault.ABIAnalyzeTypes(nil, nil))
5163 call = s.newValue2A(ssa.OpClosureLECall, aux.LateExpansionResultType(), aux, codeptr, v)
5165 aux := ssa.StaticAuxCall(fn.(*ir.Name).Linksym(), s.f.ABIDefault.ABIAnalyzeTypes(nil, nil))
5166 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5168 callArgs = append(callArgs, s.mem())
5169 call.AddArgs(callArgs...)
5170 call.AuxInt = stksize
5171 s.vars[memVar] = s.newValue1I(ssa.OpSelectN, types.TypeMem, 0, call)
5172 // Make sure that the stack slots with pointers are kept live
5173 // through the call (which is a pre-emption point). Also, we will
5174 // use the first call of the last defer exit to compute liveness
5175 // for the deferreturn, so we want all stack slots to be live.
5176 if r.closureNode != nil {
5177 s.vars[memVar] = s.newValue1Apos(ssa.OpVarLive, types.TypeMem, r.closureNode, s.mem(), false)
5185 func (s *state) callResult(n *ir.CallExpr, k callKind) *ssa.Value {
5186 return s.call(n, k, false, nil)
5189 func (s *state) callAddr(n *ir.CallExpr, k callKind) *ssa.Value {
5190 return s.call(n, k, true, nil)
5193 // Calls the function n using the specified call type.
5194 // Returns the address of the return value (or nil if none).
5195 func (s *state) call(n *ir.CallExpr, k callKind, returnResultAddr bool, deferExtra ir.Expr) *ssa.Value {
5197 var callee *ir.Name // target function (if static)
5198 var closure *ssa.Value // ptr to closure to run (if dynamic)
5199 var codeptr *ssa.Value // ptr to target code (if dynamic)
5200 var dextra *ssa.Value // defer extra arg
5201 var rcvr *ssa.Value // receiver to set
5203 var ACArgs []*types.Type // AuxCall args
5204 var ACResults []*types.Type // AuxCall results
5205 var callArgs []*ssa.Value // For late-expansion, the args themselves (not stored, args to the call instead).
5207 callABI := s.f.ABIDefault
5209 if k != callNormal && k != callTail && (len(n.Args) != 0 || n.Op() == ir.OCALLINTER || n.X.Type().NumResults() != 0) {
5210 s.Fatalf("go/defer call with arguments: %v", n)
5215 if (k == callNormal || k == callTail) && fn.Op() == ir.ONAME && fn.(*ir.Name).Class == ir.PFUNC {
5218 if buildcfg.Experiment.RegabiArgs {
5219 // This is a static call, so it may be
5220 // a direct call to a non-ABIInternal
5221 // function. fn.Func may be nil for
5222 // some compiler-generated functions,
5223 // but those are all ABIInternal.
5225 callABI = abiForFunc(fn.Func, s.f.ABI0, s.f.ABI1)
5228 // TODO(register args) remove after register abi is working
5229 inRegistersImported := fn.Pragma()&ir.RegisterParams != 0
5230 inRegistersSamePackage := fn.Func != nil && fn.Func.Pragma&ir.RegisterParams != 0
5231 if inRegistersImported || inRegistersSamePackage {
5237 closure = s.expr(fn)
5238 if k != callDefer && k != callDeferStack {
5239 // Deferred nil function needs to panic when the function is invoked,
5240 // not the point of defer statement.
5241 s.maybeNilCheckClosure(closure, k)
5244 if fn.Op() != ir.ODOTINTER {
5245 s.Fatalf("OCALLINTER: n.Left not an ODOTINTER: %v", fn.Op())
5247 fn := fn.(*ir.SelectorExpr)
5248 var iclosure *ssa.Value
5249 iclosure, rcvr = s.getClosureAndRcvr(fn)
5250 if k == callNormal {
5251 codeptr = s.load(types.Types[types.TUINTPTR], iclosure)
5256 if deferExtra != nil {
5257 dextra = s.expr(deferExtra)
5260 params := callABI.ABIAnalyze(n.X.Type(), false /* Do not set (register) nNames from caller side -- can cause races. */)
5261 types.CalcSize(fn.Type())
5262 stksize := params.ArgWidth() // includes receiver, args, and results
5264 res := n.X.Type().Results()
5265 if k == callNormal || k == callTail {
5266 for _, p := range params.OutParams() {
5267 ACResults = append(ACResults, p.Type)
5272 if k == callDeferStack {
5274 s.Fatalf("deferprocStack with non-zero stack size %d: %v", stksize, n)
5276 // Make a defer struct on the stack.
5278 _, addr := s.temp(n.Pos(), t)
5279 s.store(closure.Type,
5280 s.newValue1I(ssa.OpOffPtr, closure.Type.PtrTo(), t.FieldOff(deferStructFnField), addr),
5283 // Call runtime.deferprocStack with pointer to _defer record.
5284 ACArgs = append(ACArgs, types.Types[types.TUINTPTR])
5285 aux := ssa.StaticAuxCall(ir.Syms.DeferprocStack, s.f.ABIDefault.ABIAnalyzeTypes(ACArgs, ACResults))
5286 callArgs = append(callArgs, addr, s.mem())
5287 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5288 call.AddArgs(callArgs...)
5289 call.AuxInt = int64(types.PtrSize) // deferprocStack takes a *_defer arg
5291 // Store arguments to stack, including defer/go arguments and receiver for method calls.
5292 // These are written in SP-offset order.
5293 argStart := base.Ctxt.Arch.FixedFrameSize
5295 if k != callNormal && k != callTail {
5296 // Write closure (arg to newproc/deferproc).
5297 ACArgs = append(ACArgs, types.Types[types.TUINTPTR]) // not argExtra
5298 callArgs = append(callArgs, closure)
5299 stksize += int64(types.PtrSize)
5300 argStart += int64(types.PtrSize)
5302 // Extra token of type any for deferproc
5303 ACArgs = append(ACArgs, types.Types[types.TINTER])
5304 callArgs = append(callArgs, dextra)
5305 stksize += 2 * int64(types.PtrSize)
5306 argStart += 2 * int64(types.PtrSize)
5310 // Set receiver (for interface calls).
5312 callArgs = append(callArgs, rcvr)
5319 for _, p := range params.InParams() { // includes receiver for interface calls
5320 ACArgs = append(ACArgs, p.Type)
5323 // Split the entry block if there are open defers, because later calls to
5324 // openDeferSave may cause a mismatch between the mem for an OpDereference
5325 // and the call site which uses it. See #49282.
5326 if s.curBlock.ID == s.f.Entry.ID && s.hasOpenDefers {
5328 b.Kind = ssa.BlockPlain
5329 curb := s.f.NewBlock(ssa.BlockPlain)
5334 for i, n := range args {
5335 callArgs = append(callArgs, s.putArg(n, t.Param(i).Type))
5338 callArgs = append(callArgs, s.mem())
5342 case k == callDefer:
5343 sym := ir.Syms.Deferproc
5345 sym = ir.Syms.Deferprocat
5347 aux := ssa.StaticAuxCall(sym, s.f.ABIDefault.ABIAnalyzeTypes(ACArgs, ACResults)) // TODO paramResultInfo for Deferproc(at)
5348 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5350 aux := ssa.StaticAuxCall(ir.Syms.Newproc, s.f.ABIDefault.ABIAnalyzeTypes(ACArgs, ACResults))
5351 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux) // TODO paramResultInfo for Newproc
5352 case closure != nil:
5353 // rawLoad because loading the code pointer from a
5354 // closure is always safe, but IsSanitizerSafeAddr
5355 // can't always figure that out currently, and it's
5356 // critical that we not clobber any arguments already
5357 // stored onto the stack.
5358 codeptr = s.rawLoad(types.Types[types.TUINTPTR], closure)
5359 aux := ssa.ClosureAuxCall(callABI.ABIAnalyzeTypes(ACArgs, ACResults))
5360 call = s.newValue2A(ssa.OpClosureLECall, aux.LateExpansionResultType(), aux, codeptr, closure)
5361 case codeptr != nil:
5362 // Note that the "receiver" parameter is nil because the actual receiver is the first input parameter.
5363 aux := ssa.InterfaceAuxCall(params)
5364 call = s.newValue1A(ssa.OpInterLECall, aux.LateExpansionResultType(), aux, codeptr)
5366 aux := ssa.StaticAuxCall(callTargetLSym(callee), params)
5367 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5369 call.Op = ssa.OpTailLECall
5370 stksize = 0 // Tail call does not use stack. We reuse caller's frame.
5373 s.Fatalf("bad call type %v %v", n.Op(), n)
5375 call.AddArgs(callArgs...)
5376 call.AuxInt = stksize // Call operations carry the argsize of the callee along with them
5379 s.vars[memVar] = s.newValue1I(ssa.OpSelectN, types.TypeMem, int64(len(ACResults)), call)
5380 // Insert VarLive opcodes.
5381 for _, v := range n.KeepAlive {
5383 s.Fatalf("KeepAlive variable %v must have Addrtaken set", v)
5386 case ir.PAUTO, ir.PPARAM, ir.PPARAMOUT:
5388 s.Fatalf("KeepAlive variable %v must be Auto or Arg", v)
5390 s.vars[memVar] = s.newValue1A(ssa.OpVarLive, types.TypeMem, v, s.mem())
5393 // Finish block for defers
5394 if k == callDefer || k == callDeferStack {
5396 b.Kind = ssa.BlockDefer
5398 bNext := s.f.NewBlock(ssa.BlockPlain)
5400 // Add recover edge to exit code.
5401 r := s.f.NewBlock(ssa.BlockPlain)
5405 b.Likely = ssa.BranchLikely
5409 if len(res) == 0 || k != callNormal {
5410 // call has no return value. Continue with the next statement.
5414 if returnResultAddr {
5415 return s.resultAddrOfCall(call, 0, fp.Type)
5417 return s.newValue1I(ssa.OpSelectN, fp.Type, 0, call)
5420 // maybeNilCheckClosure checks if a nil check of a closure is needed in some
5421 // architecture-dependent situations and, if so, emits the nil check.
5422 func (s *state) maybeNilCheckClosure(closure *ssa.Value, k callKind) {
5423 if Arch.LinkArch.Family == sys.Wasm || buildcfg.GOOS == "aix" && k != callGo {
5424 // On AIX, the closure needs to be verified as fn can be nil, except if it's a call go. This needs to be handled by the runtime to have the "go of nil func value" error.
5425 // TODO(neelance): On other architectures this should be eliminated by the optimization steps
5430 // getClosureAndRcvr returns values for the appropriate closure and receiver of an
5432 func (s *state) getClosureAndRcvr(fn *ir.SelectorExpr) (*ssa.Value, *ssa.Value) {
5434 itab := s.newValue1(ssa.OpITab, types.Types[types.TUINTPTR], i)
5436 itabidx := fn.Offset() + 2*int64(types.PtrSize) + 8 // offset of fun field in runtime.itab
5437 closure := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.UintptrPtr, itabidx, itab)
5438 rcvr := s.newValue1(ssa.OpIData, s.f.Config.Types.BytePtr, i)
5439 return closure, rcvr
5442 // etypesign returns the signed-ness of e, for integer/pointer etypes.
5443 // -1 means signed, +1 means unsigned, 0 means non-integer/non-pointer.
5444 func etypesign(e types.Kind) int8 {
5446 case types.TINT8, types.TINT16, types.TINT32, types.TINT64, types.TINT:
5448 case types.TUINT8, types.TUINT16, types.TUINT32, types.TUINT64, types.TUINT, types.TUINTPTR, types.TUNSAFEPTR:
5454 // addr converts the address of the expression n to SSA, adds it to s and returns the SSA result.
5455 // The value that the returned Value represents is guaranteed to be non-nil.
5456 func (s *state) addr(n ir.Node) *ssa.Value {
5457 if n.Op() != ir.ONAME {
5463 s.Fatalf("addr of canSSA expression: %+v", n)
5466 t := types.NewPtr(n.Type())
5467 linksymOffset := func(lsym *obj.LSym, offset int64) *ssa.Value {
5468 v := s.entryNewValue1A(ssa.OpAddr, t, lsym, s.sb)
5469 // TODO: Make OpAddr use AuxInt as well as Aux.
5471 v = s.entryNewValue1I(ssa.OpOffPtr, v.Type, offset, v)
5476 case ir.OLINKSYMOFFSET:
5477 no := n.(*ir.LinksymOffsetExpr)
5478 return linksymOffset(no.Linksym, no.Offset_)
5481 if n.Heapaddr != nil {
5482 return s.expr(n.Heapaddr)
5487 return linksymOffset(n.Linksym(), 0)
5494 s.Fatalf("addr of undeclared ONAME %v. declared: %v", n, s.decladdrs)
5497 return s.newValue2Apos(ssa.OpLocalAddr, t, n, s.sp, s.mem(), !ir.IsAutoTmp(n))
5499 case ir.PPARAMOUT: // Same as PAUTO -- cannot generate LEA early.
5500 // ensure that we reuse symbols for out parameters so
5501 // that cse works on their addresses
5502 return s.newValue2Apos(ssa.OpLocalAddr, t, n, s.sp, s.mem(), true)
5504 s.Fatalf("variable address class %v not implemented", n.Class)
5508 // load return from callee
5509 n := n.(*ir.ResultExpr)
5510 return s.resultAddrOfCall(s.prevCall, n.Index, n.Type())
5512 n := n.(*ir.IndexExpr)
5513 if n.X.Type().IsSlice() {
5515 i := s.expr(n.Index)
5516 len := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], a)
5517 i = s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded())
5518 p := s.newValue1(ssa.OpSlicePtr, t, a)
5519 return s.newValue2(ssa.OpPtrIndex, t, p, i)
5522 i := s.expr(n.Index)
5523 len := s.constInt(types.Types[types.TINT], n.X.Type().NumElem())
5524 i = s.boundsCheck(i, len, ssa.BoundsIndex, n.Bounded())
5525 return s.newValue2(ssa.OpPtrIndex, types.NewPtr(n.X.Type().Elem()), a, i)
5528 n := n.(*ir.StarExpr)
5529 return s.exprPtr(n.X, n.Bounded(), n.Pos())
5531 n := n.(*ir.SelectorExpr)
5533 return s.newValue1I(ssa.OpOffPtr, t, n.Offset(), p)
5535 n := n.(*ir.SelectorExpr)
5536 p := s.exprPtr(n.X, n.Bounded(), n.Pos())
5537 return s.newValue1I(ssa.OpOffPtr, t, n.Offset(), p)
5539 n := n.(*ir.ConvExpr)
5540 if n.Type() == n.X.Type() {
5544 return s.newValue1(ssa.OpCopy, t, addr) // ensure that addr has the right type
5545 case ir.OCALLFUNC, ir.OCALLINTER:
5546 n := n.(*ir.CallExpr)
5547 return s.callAddr(n, callNormal)
5548 case ir.ODOTTYPE, ir.ODYNAMICDOTTYPE:
5550 if n.Op() == ir.ODOTTYPE {
5551 v, _ = s.dottype(n.(*ir.TypeAssertExpr), false)
5553 v, _ = s.dynamicDottype(n.(*ir.DynamicTypeAssertExpr), false)
5555 if v.Op != ssa.OpLoad {
5556 s.Fatalf("dottype of non-load")
5558 if v.Args[1] != s.mem() {
5559 s.Fatalf("memory no longer live from dottype load")
5563 s.Fatalf("unhandled addr %v", n.Op())
5568 // canSSA reports whether n is SSA-able.
5569 // n must be an ONAME (or an ODOT sequence with an ONAME base).
5570 func (s *state) canSSA(n ir.Node) bool {
5571 if base.Flag.N != 0 {
5576 if nn.Op() == ir.ODOT {
5577 nn := nn.(*ir.SelectorExpr)
5581 if nn.Op() == ir.OINDEX {
5582 nn := nn.(*ir.IndexExpr)
5583 if nn.X.Type().IsArray() {
5590 if n.Op() != ir.ONAME {
5593 return s.canSSAName(n.(*ir.Name)) && ssa.CanSSA(n.Type())
5596 func (s *state) canSSAName(name *ir.Name) bool {
5597 if name.Addrtaken() || !name.OnStack() {
5603 // TODO: handle this case? Named return values must be
5604 // in memory so that the deferred function can see them.
5605 // Maybe do: if !strings.HasPrefix(n.String(), "~") { return false }
5606 // Or maybe not, see issue 18860. Even unnamed return values
5607 // must be written back so if a defer recovers, the caller can see them.
5610 if s.cgoUnsafeArgs {
5611 // Cgo effectively takes the address of all result args,
5612 // but the compiler can't see that.
5617 // TODO: try to make more variables SSAable?
5620 // exprPtr evaluates n to a pointer and nil-checks it.
5621 func (s *state) exprPtr(n ir.Node, bounded bool, lineno src.XPos) *ssa.Value {
5623 if bounded || n.NonNil() {
5624 if s.f.Frontend().Debug_checknil() && lineno.Line() > 1 {
5625 s.f.Warnl(lineno, "removed nil check")
5633 // nilCheck generates nil pointer checking code.
5634 // Used only for automatically inserted nil checks,
5635 // not for user code like 'x != nil'.
5636 func (s *state) nilCheck(ptr *ssa.Value) {
5637 if base.Debug.DisableNil != 0 || s.curfn.NilCheckDisabled() {
5640 s.newValue2(ssa.OpNilCheck, types.TypeVoid, ptr, s.mem())
5643 // boundsCheck generates bounds checking code. Checks if 0 <= idx <[=] len, branches to exit if not.
5644 // Starts a new block on return.
5645 // On input, len must be converted to full int width and be nonnegative.
5646 // Returns idx converted to full int width.
5647 // If bounded is true then caller guarantees the index is not out of bounds
5648 // (but boundsCheck will still extend the index to full int width).
5649 func (s *state) boundsCheck(idx, len *ssa.Value, kind ssa.BoundsKind, bounded bool) *ssa.Value {
5650 idx = s.extendIndex(idx, len, kind, bounded)
5652 if bounded || base.Flag.B != 0 {
5653 // If bounded or bounds checking is flag-disabled, then no check necessary,
5654 // just return the extended index.
5656 // Here, bounded == true if the compiler generated the index itself,
5657 // such as in the expansion of a slice initializer. These indexes are
5658 // compiler-generated, not Go program variables, so they cannot be
5659 // attacker-controlled, so we can omit Spectre masking as well.
5661 // Note that we do not want to omit Spectre masking in code like:
5663 // if 0 <= i && i < len(x) {
5667 // Lucky for us, bounded==false for that code.
5668 // In that case (handled below), we emit a bound check (and Spectre mask)
5669 // and then the prove pass will remove the bounds check.
5670 // In theory the prove pass could potentially remove certain
5671 // Spectre masks, but it's very delicate and probably better
5672 // to be conservative and leave them all in.
5676 bNext := s.f.NewBlock(ssa.BlockPlain)
5677 bPanic := s.f.NewBlock(ssa.BlockExit)
5679 if !idx.Type.IsSigned() {
5681 case ssa.BoundsIndex:
5682 kind = ssa.BoundsIndexU
5683 case ssa.BoundsSliceAlen:
5684 kind = ssa.BoundsSliceAlenU
5685 case ssa.BoundsSliceAcap:
5686 kind = ssa.BoundsSliceAcapU
5687 case ssa.BoundsSliceB:
5688 kind = ssa.BoundsSliceBU
5689 case ssa.BoundsSlice3Alen:
5690 kind = ssa.BoundsSlice3AlenU
5691 case ssa.BoundsSlice3Acap:
5692 kind = ssa.BoundsSlice3AcapU
5693 case ssa.BoundsSlice3B:
5694 kind = ssa.BoundsSlice3BU
5695 case ssa.BoundsSlice3C:
5696 kind = ssa.BoundsSlice3CU
5701 if kind == ssa.BoundsIndex || kind == ssa.BoundsIndexU {
5702 cmp = s.newValue2(ssa.OpIsInBounds, types.Types[types.TBOOL], idx, len)
5704 cmp = s.newValue2(ssa.OpIsSliceInBounds, types.Types[types.TBOOL], idx, len)
5707 b.Kind = ssa.BlockIf
5709 b.Likely = ssa.BranchLikely
5713 s.startBlock(bPanic)
5714 if Arch.LinkArch.Family == sys.Wasm {
5715 // TODO(khr): figure out how to do "register" based calling convention for bounds checks.
5716 // Should be similar to gcWriteBarrier, but I can't make it work.
5717 s.rtcall(BoundsCheckFunc[kind], false, nil, idx, len)
5719 mem := s.newValue3I(ssa.OpPanicBounds, types.TypeMem, int64(kind), idx, len, s.mem())
5720 s.endBlock().SetControl(mem)
5724 // In Spectre index mode, apply an appropriate mask to avoid speculative out-of-bounds accesses.
5725 if base.Flag.Cfg.SpectreIndex {
5726 op := ssa.OpSpectreIndex
5727 if kind != ssa.BoundsIndex && kind != ssa.BoundsIndexU {
5728 op = ssa.OpSpectreSliceIndex
5730 idx = s.newValue2(op, types.Types[types.TINT], idx, len)
5736 // If cmp (a bool) is false, panic using the given function.
5737 func (s *state) check(cmp *ssa.Value, fn *obj.LSym) {
5739 b.Kind = ssa.BlockIf
5741 b.Likely = ssa.BranchLikely
5742 bNext := s.f.NewBlock(ssa.BlockPlain)
5744 pos := base.Ctxt.PosTable.Pos(line)
5745 fl := funcLine{f: fn, base: pos.Base(), line: pos.Line()}
5746 bPanic := s.panics[fl]
5748 bPanic = s.f.NewBlock(ssa.BlockPlain)
5749 s.panics[fl] = bPanic
5750 s.startBlock(bPanic)
5751 // The panic call takes/returns memory to ensure that the right
5752 // memory state is observed if the panic happens.
5753 s.rtcall(fn, false, nil)
5760 func (s *state) intDivide(n ir.Node, a, b *ssa.Value) *ssa.Value {
5763 case ssa.OpConst8, ssa.OpConst16, ssa.OpConst32, ssa.OpConst64:
5769 // do a size-appropriate check for zero
5770 cmp := s.newValue2(s.ssaOp(ir.ONE, n.Type()), types.Types[types.TBOOL], b, s.zeroVal(n.Type()))
5771 s.check(cmp, ir.Syms.Panicdivide)
5773 return s.newValue2(s.ssaOp(n.Op(), n.Type()), a.Type, a, b)
5776 // rtcall issues a call to the given runtime function fn with the listed args.
5777 // Returns a slice of results of the given result types.
5778 // The call is added to the end of the current block.
5779 // If returns is false, the block is marked as an exit block.
5780 func (s *state) rtcall(fn *obj.LSym, returns bool, results []*types.Type, args ...*ssa.Value) []*ssa.Value {
5782 // Write args to the stack
5783 off := base.Ctxt.Arch.FixedFrameSize
5784 var callArgs []*ssa.Value
5785 var callArgTypes []*types.Type
5787 for _, arg := range args {
5789 off = types.RoundUp(off, t.Alignment())
5791 callArgs = append(callArgs, arg)
5792 callArgTypes = append(callArgTypes, t)
5795 off = types.RoundUp(off, int64(types.RegSize))
5799 aux := ssa.StaticAuxCall(fn, s.f.ABIDefault.ABIAnalyzeTypes(callArgTypes, results))
5800 callArgs = append(callArgs, s.mem())
5801 call = s.newValue0A(ssa.OpStaticLECall, aux.LateExpansionResultType(), aux)
5802 call.AddArgs(callArgs...)
5803 s.vars[memVar] = s.newValue1I(ssa.OpSelectN, types.TypeMem, int64(len(results)), call)
5808 b.Kind = ssa.BlockExit
5810 call.AuxInt = off - base.Ctxt.Arch.FixedFrameSize
5811 if len(results) > 0 {
5812 s.Fatalf("panic call can't have results")
5818 res := make([]*ssa.Value, len(results))
5819 for i, t := range results {
5820 off = types.RoundUp(off, t.Alignment())
5821 res[i] = s.resultOfCall(call, int64(i), t)
5824 off = types.RoundUp(off, int64(types.PtrSize))
5826 // Remember how much callee stack space we needed.
5832 // do *left = right for type t.
5833 func (s *state) storeType(t *types.Type, left, right *ssa.Value, skip skipMask, leftIsStmt bool) {
5834 s.instrument(t, left, instrumentWrite)
5836 if skip == 0 && (!t.HasPointers() || ssa.IsStackAddr(left)) {
5837 // Known to not have write barrier. Store the whole type.
5838 s.vars[memVar] = s.newValue3Apos(ssa.OpStore, types.TypeMem, t, left, right, s.mem(), leftIsStmt)
5842 // store scalar fields first, so write barrier stores for
5843 // pointer fields can be grouped together, and scalar values
5844 // don't need to be live across the write barrier call.
5845 // TODO: if the writebarrier pass knows how to reorder stores,
5846 // we can do a single store here as long as skip==0.
5847 s.storeTypeScalars(t, left, right, skip)
5848 if skip&skipPtr == 0 && t.HasPointers() {
5849 s.storeTypePtrs(t, left, right)
5853 // do *left = right for all scalar (non-pointer) parts of t.
5854 func (s *state) storeTypeScalars(t *types.Type, left, right *ssa.Value, skip skipMask) {
5856 case t.IsBoolean() || t.IsInteger() || t.IsFloat() || t.IsComplex():
5857 s.store(t, left, right)
5858 case t.IsPtrShaped():
5859 if t.IsPtr() && t.Elem().NotInHeap() {
5860 s.store(t, left, right) // see issue 42032
5862 // otherwise, no scalar fields.
5864 if skip&skipLen != 0 {
5867 len := s.newValue1(ssa.OpStringLen, types.Types[types.TINT], right)
5868 lenAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, s.config.PtrSize, left)
5869 s.store(types.Types[types.TINT], lenAddr, len)
5871 if skip&skipLen == 0 {
5872 len := s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], right)
5873 lenAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, s.config.PtrSize, left)
5874 s.store(types.Types[types.TINT], lenAddr, len)
5876 if skip&skipCap == 0 {
5877 cap := s.newValue1(ssa.OpSliceCap, types.Types[types.TINT], right)
5878 capAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.IntPtr, 2*s.config.PtrSize, left)
5879 s.store(types.Types[types.TINT], capAddr, cap)
5881 case t.IsInterface():
5882 // itab field doesn't need a write barrier (even though it is a pointer).
5883 itab := s.newValue1(ssa.OpITab, s.f.Config.Types.BytePtr, right)
5884 s.store(types.Types[types.TUINTPTR], left, itab)
5887 for i := 0; i < n; i++ {
5888 ft := t.FieldType(i)
5889 addr := s.newValue1I(ssa.OpOffPtr, ft.PtrTo(), t.FieldOff(i), left)
5890 val := s.newValue1I(ssa.OpStructSelect, ft, int64(i), right)
5891 s.storeTypeScalars(ft, addr, val, 0)
5893 case t.IsArray() && t.NumElem() == 0:
5895 case t.IsArray() && t.NumElem() == 1:
5896 s.storeTypeScalars(t.Elem(), left, s.newValue1I(ssa.OpArraySelect, t.Elem(), 0, right), 0)
5898 s.Fatalf("bad write barrier type %v", t)
5902 // do *left = right for all pointer parts of t.
5903 func (s *state) storeTypePtrs(t *types.Type, left, right *ssa.Value) {
5905 case t.IsPtrShaped():
5906 if t.IsPtr() && t.Elem().NotInHeap() {
5907 break // see issue 42032
5909 s.store(t, left, right)
5911 ptr := s.newValue1(ssa.OpStringPtr, s.f.Config.Types.BytePtr, right)
5912 s.store(s.f.Config.Types.BytePtr, left, ptr)
5914 elType := types.NewPtr(t.Elem())
5915 ptr := s.newValue1(ssa.OpSlicePtr, elType, right)
5916 s.store(elType, left, ptr)
5917 case t.IsInterface():
5918 // itab field is treated as a scalar.
5919 idata := s.newValue1(ssa.OpIData, s.f.Config.Types.BytePtr, right)
5920 idataAddr := s.newValue1I(ssa.OpOffPtr, s.f.Config.Types.BytePtrPtr, s.config.PtrSize, left)
5921 s.store(s.f.Config.Types.BytePtr, idataAddr, idata)
5924 for i := 0; i < n; i++ {
5925 ft := t.FieldType(i)
5926 if !ft.HasPointers() {
5929 addr := s.newValue1I(ssa.OpOffPtr, ft.PtrTo(), t.FieldOff(i), left)
5930 val := s.newValue1I(ssa.OpStructSelect, ft, int64(i), right)
5931 s.storeTypePtrs(ft, addr, val)
5933 case t.IsArray() && t.NumElem() == 0:
5935 case t.IsArray() && t.NumElem() == 1:
5936 s.storeTypePtrs(t.Elem(), left, s.newValue1I(ssa.OpArraySelect, t.Elem(), 0, right))
5938 s.Fatalf("bad write barrier type %v", t)
5942 // putArg evaluates n for the purpose of passing it as an argument to a function and returns the value for the call.
5943 func (s *state) putArg(n ir.Node, t *types.Type) *ssa.Value {
5946 a = s.newValue2(ssa.OpDereference, t, s.addr(n), s.mem())
5953 func (s *state) storeArgWithBase(n ir.Node, t *types.Type, base *ssa.Value, off int64) {
5954 pt := types.NewPtr(t)
5957 // Use special routine that avoids allocation on duplicate offsets.
5958 addr = s.constOffPtrSP(pt, off)
5960 addr = s.newValue1I(ssa.OpOffPtr, pt, off, base)
5970 s.storeType(t, addr, a, 0, false)
5973 // slice computes the slice v[i:j:k] and returns ptr, len, and cap of result.
5974 // i,j,k may be nil, in which case they are set to their default value.
5975 // v may be a slice, string or pointer to an array.
5976 func (s *state) slice(v, i, j, k *ssa.Value, bounded bool) (p, l, c *ssa.Value) {
5978 var ptr, len, cap *ssa.Value
5981 ptr = s.newValue1(ssa.OpSlicePtr, types.NewPtr(t.Elem()), v)
5982 len = s.newValue1(ssa.OpSliceLen, types.Types[types.TINT], v)
5983 cap = s.newValue1(ssa.OpSliceCap, types.Types[types.TINT], v)
5985 ptr = s.newValue1(ssa.OpStringPtr, types.NewPtr(types.Types[types.TUINT8]), v)
5986 len = s.newValue1(ssa.OpStringLen, types.Types[types.TINT], v)
5989 if !t.Elem().IsArray() {
5990 s.Fatalf("bad ptr to array in slice %v\n", t)
5993 ptr = s.newValue1(ssa.OpCopy, types.NewPtr(t.Elem().Elem()), v)
5994 len = s.constInt(types.Types[types.TINT], t.Elem().NumElem())
5997 s.Fatalf("bad type in slice %v\n", t)
6000 // Set default values
6002 i = s.constInt(types.Types[types.TINT], 0)
6013 // Panic if slice indices are not in bounds.
6014 // Make sure we check these in reverse order so that we're always
6015 // comparing against a value known to be nonnegative. See issue 28797.
6018 kind := ssa.BoundsSlice3Alen
6020 kind = ssa.BoundsSlice3Acap
6022 k = s.boundsCheck(k, cap, kind, bounded)
6025 j = s.boundsCheck(j, k, ssa.BoundsSlice3B, bounded)
6027 i = s.boundsCheck(i, j, ssa.BoundsSlice3C, bounded)
6030 kind := ssa.BoundsSliceAlen
6032 kind = ssa.BoundsSliceAcap
6034 j = s.boundsCheck(j, k, kind, bounded)
6036 i = s.boundsCheck(i, j, ssa.BoundsSliceB, bounded)
6039 // Word-sized integer operations.
6040 subOp := s.ssaOp(ir.OSUB, types.Types[types.TINT])
6041 mulOp := s.ssaOp(ir.OMUL, types.Types[types.TINT])
6042 andOp := s.ssaOp(ir.OAND, types.Types[types.TINT])
6044 // Calculate the length (rlen) and capacity (rcap) of the new slice.
6045 // For strings the capacity of the result is unimportant. However,
6046 // we use rcap to test if we've generated a zero-length slice.
6047 // Use length of strings for that.
6048 rlen := s.newValue2(subOp, types.Types[types.TINT], j, i)
6050 if j != k && !t.IsString() {
6051 rcap = s.newValue2(subOp, types.Types[types.TINT], k, i)
6054 if (i.Op == ssa.OpConst64 || i.Op == ssa.OpConst32) && i.AuxInt == 0 {
6055 // No pointer arithmetic necessary.
6056 return ptr, rlen, rcap
6059 // Calculate the base pointer (rptr) for the new slice.
6061 // Generate the following code assuming that indexes are in bounds.
6062 // The masking is to make sure that we don't generate a slice
6063 // that points to the next object in memory. We cannot just set
6064 // the pointer to nil because then we would create a nil slice or
6069 // rptr = ptr + (mask(rcap) & (i * stride))
6071 // Where mask(x) is 0 if x==0 and -1 if x>0 and stride is the width
6072 // of the element type.
6073 stride := s.constInt(types.Types[types.TINT], ptr.Type.Elem().Size())
6075 // The delta is the number of bytes to offset ptr by.
6076 delta := s.newValue2(mulOp, types.Types[types.TINT], i, stride)
6078 // If we're slicing to the point where the capacity is zero,
6079 // zero out the delta.
6080 mask := s.newValue1(ssa.OpSlicemask, types.Types[types.TINT], rcap)
6081 delta = s.newValue2(andOp, types.Types[types.TINT], delta, mask)
6083 // Compute rptr = ptr + delta.
6084 rptr := s.newValue2(ssa.OpAddPtr, ptr.Type, ptr, delta)
6086 return rptr, rlen, rcap
6089 type u642fcvtTab struct {
6090 leq, cvt2F, and, rsh, or, add ssa.Op
6091 one func(*state, *types.Type, int64) *ssa.Value
6094 var u64_f64 = u642fcvtTab{
6096 cvt2F: ssa.OpCvt64to64F,
6098 rsh: ssa.OpRsh64Ux64,
6101 one: (*state).constInt64,
6104 var u64_f32 = u642fcvtTab{
6106 cvt2F: ssa.OpCvt64to32F,
6108 rsh: ssa.OpRsh64Ux64,
6111 one: (*state).constInt64,
6114 func (s *state) uint64Tofloat64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6115 return s.uint64Tofloat(&u64_f64, n, x, ft, tt)
6118 func (s *state) uint64Tofloat32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6119 return s.uint64Tofloat(&u64_f32, n, x, ft, tt)
6122 func (s *state) uint64Tofloat(cvttab *u642fcvtTab, n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6124 // result = (floatY) x
6126 // y = uintX(x) ; y = x & 1
6127 // z = uintX(x) ; z = z >> 1
6129 // result = floatY(z)
6130 // result = result + result
6133 // Code borrowed from old code generator.
6134 // What's going on: large 64-bit "unsigned" looks like
6135 // negative number to hardware's integer-to-float
6136 // conversion. However, because the mantissa is only
6137 // 63 bits, we don't need the LSB, so instead we do an
6138 // unsigned right shift (divide by two), convert, and
6139 // double. However, before we do that, we need to be
6140 // sure that we do not lose a "1" if that made the
6141 // difference in the resulting rounding. Therefore, we
6142 // preserve it, and OR (not ADD) it back in. The case
6143 // that matters is when the eleven discarded bits are
6144 // equal to 10000000001; that rounds up, and the 1 cannot
6145 // be lost else it would round down if the LSB of the
6146 // candidate mantissa is 0.
6147 cmp := s.newValue2(cvttab.leq, types.Types[types.TBOOL], s.zeroVal(ft), x)
6149 b.Kind = ssa.BlockIf
6151 b.Likely = ssa.BranchLikely
6153 bThen := s.f.NewBlock(ssa.BlockPlain)
6154 bElse := s.f.NewBlock(ssa.BlockPlain)
6155 bAfter := s.f.NewBlock(ssa.BlockPlain)
6159 a0 := s.newValue1(cvttab.cvt2F, tt, x)
6162 bThen.AddEdgeTo(bAfter)
6166 one := cvttab.one(s, ft, 1)
6167 y := s.newValue2(cvttab.and, ft, x, one)
6168 z := s.newValue2(cvttab.rsh, ft, x, one)
6169 z = s.newValue2(cvttab.or, ft, z, y)
6170 a := s.newValue1(cvttab.cvt2F, tt, z)
6171 a1 := s.newValue2(cvttab.add, tt, a, a)
6174 bElse.AddEdgeTo(bAfter)
6176 s.startBlock(bAfter)
6177 return s.variable(n, n.Type())
6180 type u322fcvtTab struct {
6181 cvtI2F, cvtF2F ssa.Op
6184 var u32_f64 = u322fcvtTab{
6185 cvtI2F: ssa.OpCvt32to64F,
6189 var u32_f32 = u322fcvtTab{
6190 cvtI2F: ssa.OpCvt32to32F,
6191 cvtF2F: ssa.OpCvt64Fto32F,
6194 func (s *state) uint32Tofloat64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6195 return s.uint32Tofloat(&u32_f64, n, x, ft, tt)
6198 func (s *state) uint32Tofloat32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6199 return s.uint32Tofloat(&u32_f32, n, x, ft, tt)
6202 func (s *state) uint32Tofloat(cvttab *u322fcvtTab, n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6204 // result = floatY(x)
6206 // result = floatY(float64(x) + (1<<32))
6208 cmp := s.newValue2(ssa.OpLeq32, types.Types[types.TBOOL], s.zeroVal(ft), x)
6210 b.Kind = ssa.BlockIf
6212 b.Likely = ssa.BranchLikely
6214 bThen := s.f.NewBlock(ssa.BlockPlain)
6215 bElse := s.f.NewBlock(ssa.BlockPlain)
6216 bAfter := s.f.NewBlock(ssa.BlockPlain)
6220 a0 := s.newValue1(cvttab.cvtI2F, tt, x)
6223 bThen.AddEdgeTo(bAfter)
6227 a1 := s.newValue1(ssa.OpCvt32to64F, types.Types[types.TFLOAT64], x)
6228 twoToThe32 := s.constFloat64(types.Types[types.TFLOAT64], float64(1<<32))
6229 a2 := s.newValue2(ssa.OpAdd64F, types.Types[types.TFLOAT64], a1, twoToThe32)
6230 a3 := s.newValue1(cvttab.cvtF2F, tt, a2)
6234 bElse.AddEdgeTo(bAfter)
6236 s.startBlock(bAfter)
6237 return s.variable(n, n.Type())
6240 // referenceTypeBuiltin generates code for the len/cap builtins for maps and channels.
6241 func (s *state) referenceTypeBuiltin(n *ir.UnaryExpr, x *ssa.Value) *ssa.Value {
6242 if !n.X.Type().IsMap() && !n.X.Type().IsChan() {
6243 s.Fatalf("node must be a map or a channel")
6249 // return *((*int)n)
6251 // return *(((*int)n)+1)
6254 nilValue := s.constNil(types.Types[types.TUINTPTR])
6255 cmp := s.newValue2(ssa.OpEqPtr, types.Types[types.TBOOL], x, nilValue)
6257 b.Kind = ssa.BlockIf
6259 b.Likely = ssa.BranchUnlikely
6261 bThen := s.f.NewBlock(ssa.BlockPlain)
6262 bElse := s.f.NewBlock(ssa.BlockPlain)
6263 bAfter := s.f.NewBlock(ssa.BlockPlain)
6265 // length/capacity of a nil map/chan is zero
6268 s.vars[n] = s.zeroVal(lenType)
6270 bThen.AddEdgeTo(bAfter)
6276 // length is stored in the first word for map/chan
6277 s.vars[n] = s.load(lenType, x)
6279 // capacity is stored in the second word for chan
6280 sw := s.newValue1I(ssa.OpOffPtr, lenType.PtrTo(), lenType.Size(), x)
6281 s.vars[n] = s.load(lenType, sw)
6283 s.Fatalf("op must be OLEN or OCAP")
6286 bElse.AddEdgeTo(bAfter)
6288 s.startBlock(bAfter)
6289 return s.variable(n, lenType)
6292 type f2uCvtTab struct {
6293 ltf, cvt2U, subf, or ssa.Op
6294 floatValue func(*state, *types.Type, float64) *ssa.Value
6295 intValue func(*state, *types.Type, int64) *ssa.Value
6299 var f32_u64 = f2uCvtTab{
6301 cvt2U: ssa.OpCvt32Fto64,
6304 floatValue: (*state).constFloat32,
6305 intValue: (*state).constInt64,
6309 var f64_u64 = f2uCvtTab{
6311 cvt2U: ssa.OpCvt64Fto64,
6314 floatValue: (*state).constFloat64,
6315 intValue: (*state).constInt64,
6319 var f32_u32 = f2uCvtTab{
6321 cvt2U: ssa.OpCvt32Fto32,
6324 floatValue: (*state).constFloat32,
6325 intValue: func(s *state, t *types.Type, v int64) *ssa.Value { return s.constInt32(t, int32(v)) },
6329 var f64_u32 = f2uCvtTab{
6331 cvt2U: ssa.OpCvt64Fto32,
6334 floatValue: (*state).constFloat64,
6335 intValue: func(s *state, t *types.Type, v int64) *ssa.Value { return s.constInt32(t, int32(v)) },
6339 func (s *state) float32ToUint64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6340 return s.floatToUint(&f32_u64, n, x, ft, tt)
6342 func (s *state) float64ToUint64(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6343 return s.floatToUint(&f64_u64, n, x, ft, tt)
6346 func (s *state) float32ToUint32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6347 return s.floatToUint(&f32_u32, n, x, ft, tt)
6350 func (s *state) float64ToUint32(n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6351 return s.floatToUint(&f64_u32, n, x, ft, tt)
6354 func (s *state) floatToUint(cvttab *f2uCvtTab, n ir.Node, x *ssa.Value, ft, tt *types.Type) *ssa.Value {
6355 // cutoff:=1<<(intY_Size-1)
6356 // if x < floatX(cutoff) {
6357 // result = uintY(x)
6359 // y = x - floatX(cutoff)
6361 // result = z | -(cutoff)
6363 cutoff := cvttab.floatValue(s, ft, float64(cvttab.cutoff))
6364 cmp := s.newValue2(cvttab.ltf, types.Types[types.TBOOL], x, cutoff)
6366 b.Kind = ssa.BlockIf
6368 b.Likely = ssa.BranchLikely
6370 bThen := s.f.NewBlock(ssa.BlockPlain)
6371 bElse := s.f.NewBlock(ssa.BlockPlain)
6372 bAfter := s.f.NewBlock(ssa.BlockPlain)
6376 a0 := s.newValue1(cvttab.cvt2U, tt, x)
6379 bThen.AddEdgeTo(bAfter)
6383 y := s.newValue2(cvttab.subf, ft, x, cutoff)
6384 y = s.newValue1(cvttab.cvt2U, tt, y)
6385 z := cvttab.intValue(s, tt, int64(-cvttab.cutoff))
6386 a1 := s.newValue2(cvttab.or, tt, y, z)
6389 bElse.AddEdgeTo(bAfter)
6391 s.startBlock(bAfter)
6392 return s.variable(n, n.Type())
6395 // dottype generates SSA for a type assertion node.
6396 // commaok indicates whether to panic or return a bool.
6397 // If commaok is false, resok will be nil.
6398 func (s *state) dottype(n *ir.TypeAssertExpr, commaok bool) (res, resok *ssa.Value) {
6399 iface := s.expr(n.X) // input interface
6400 target := s.reflectType(n.Type()) // target type
6401 var targetItab *ssa.Value
6403 targetItab = s.expr(n.ITab)
6405 return s.dottype1(n.Pos(), n.X.Type(), n.Type(), iface, nil, target, targetItab, commaok)
6408 func (s *state) dynamicDottype(n *ir.DynamicTypeAssertExpr, commaok bool) (res, resok *ssa.Value) {
6409 iface := s.expr(n.X)
6410 var source, target, targetItab *ssa.Value
6411 if n.SrcRType != nil {
6412 source = s.expr(n.SrcRType)
6414 if !n.X.Type().IsEmptyInterface() && !n.Type().IsInterface() {
6415 byteptr := s.f.Config.Types.BytePtr
6416 targetItab = s.expr(n.ITab)
6417 // TODO(mdempsky): Investigate whether compiling n.RType could be
6418 // better than loading itab.typ.
6419 target = s.load(byteptr, s.newValue1I(ssa.OpOffPtr, byteptr, int64(types.PtrSize), targetItab)) // itab.typ
6421 target = s.expr(n.RType)
6423 return s.dottype1(n.Pos(), n.X.Type(), n.Type(), iface, source, target, targetItab, commaok)
6426 // dottype1 implements a x.(T) operation. iface is the argument (x), dst is the type we're asserting to (T)
6427 // and src is the type we're asserting from.
6428 // source is the *runtime._type of src
6429 // target is the *runtime._type of dst.
6430 // If src is a nonempty interface and dst is not an interface, targetItab is an itab representing (dst, src). Otherwise it is nil.
6431 // commaok is true if the caller wants a boolean success value. Otherwise, the generated code panics if the conversion fails.
6432 func (s *state) dottype1(pos src.XPos, src, dst *types.Type, iface, source, target, targetItab *ssa.Value, commaok bool) (res, resok *ssa.Value) {
6433 byteptr := s.f.Config.Types.BytePtr
6434 if dst.IsInterface() {
6435 if dst.IsEmptyInterface() {
6436 // Converting to an empty interface.
6437 // Input could be an empty or nonempty interface.
6438 if base.Debug.TypeAssert > 0 {
6439 base.WarnfAt(pos, "type assertion inlined")
6442 // Get itab/type field from input.
6443 itab := s.newValue1(ssa.OpITab, byteptr, iface)
6444 // Conversion succeeds iff that field is not nil.
6445 cond := s.newValue2(ssa.OpNeqPtr, types.Types[types.TBOOL], itab, s.constNil(byteptr))
6447 if src.IsEmptyInterface() && commaok {
6448 // Converting empty interface to empty interface with ,ok is just a nil check.
6452 // Branch on nilness.
6454 b.Kind = ssa.BlockIf
6456 b.Likely = ssa.BranchLikely
6457 bOk := s.f.NewBlock(ssa.BlockPlain)
6458 bFail := s.f.NewBlock(ssa.BlockPlain)
6463 // On failure, panic by calling panicnildottype.
6465 s.rtcall(ir.Syms.Panicnildottype, false, nil, target)
6467 // On success, return (perhaps modified) input interface.
6469 if src.IsEmptyInterface() {
6470 res = iface // Use input interface unchanged.
6473 // Load type out of itab, build interface with existing idata.
6474 off := s.newValue1I(ssa.OpOffPtr, byteptr, int64(types.PtrSize), itab)
6475 typ := s.load(byteptr, off)
6476 idata := s.newValue1(ssa.OpIData, byteptr, iface)
6477 res = s.newValue2(ssa.OpIMake, dst, typ, idata)
6482 // nonempty -> empty
6483 // Need to load type from itab
6484 off := s.newValue1I(ssa.OpOffPtr, byteptr, int64(types.PtrSize), itab)
6485 s.vars[typVar] = s.load(byteptr, off)
6488 // itab is nil, might as well use that as the nil result.
6490 s.vars[typVar] = itab
6494 bEnd := s.f.NewBlock(ssa.BlockPlain)
6496 bFail.AddEdgeTo(bEnd)
6498 idata := s.newValue1(ssa.OpIData, byteptr, iface)
6499 res = s.newValue2(ssa.OpIMake, dst, s.variable(typVar, byteptr), idata)
6501 delete(s.vars, typVar) // no practical effect, just to indicate typVar is no longer live.
6504 // converting to a nonempty interface needs a runtime call.
6505 if base.Debug.TypeAssert > 0 {
6506 base.WarnfAt(pos, "type assertion not inlined")
6509 fn := ir.Syms.AssertI2I
6510 if src.IsEmptyInterface() {
6511 fn = ir.Syms.AssertE2I
6513 data := s.newValue1(ssa.OpIData, types.Types[types.TUNSAFEPTR], iface)
6514 tab := s.newValue1(ssa.OpITab, byteptr, iface)
6515 tab = s.rtcall(fn, true, []*types.Type{byteptr}, target, tab)[0]
6516 return s.newValue2(ssa.OpIMake, dst, tab, data), nil
6518 fn := ir.Syms.AssertI2I2
6519 if src.IsEmptyInterface() {
6520 fn = ir.Syms.AssertE2I2
6522 res = s.rtcall(fn, true, []*types.Type{dst}, target, iface)[0]
6523 resok = s.newValue2(ssa.OpNeqInter, types.Types[types.TBOOL], res, s.constInterface(dst))
6527 if base.Debug.TypeAssert > 0 {
6528 base.WarnfAt(pos, "type assertion inlined")
6531 // Converting to a concrete type.
6532 direct := types.IsDirectIface(dst)
6533 itab := s.newValue1(ssa.OpITab, byteptr, iface) // type word of interface
6534 if base.Debug.TypeAssert > 0 {
6535 base.WarnfAt(pos, "type assertion inlined")
6537 var wantedFirstWord *ssa.Value
6538 if src.IsEmptyInterface() {
6539 // Looking for pointer to target type.
6540 wantedFirstWord = target
6542 // Looking for pointer to itab for target type and source interface.
6543 wantedFirstWord = targetItab
6546 var tmp ir.Node // temporary for use with large types
6547 var addr *ssa.Value // address of tmp
6548 if commaok && !ssa.CanSSA(dst) {
6549 // unSSAable type, use temporary.
6550 // TODO: get rid of some of these temporaries.
6551 tmp, addr = s.temp(pos, dst)
6554 cond := s.newValue2(ssa.OpEqPtr, types.Types[types.TBOOL], itab, wantedFirstWord)
6556 b.Kind = ssa.BlockIf
6558 b.Likely = ssa.BranchLikely
6560 bOk := s.f.NewBlock(ssa.BlockPlain)
6561 bFail := s.f.NewBlock(ssa.BlockPlain)
6566 // on failure, panic by calling panicdottype
6570 taddr = s.reflectType(src)
6572 if src.IsEmptyInterface() {
6573 s.rtcall(ir.Syms.PanicdottypeE, false, nil, itab, target, taddr)
6575 s.rtcall(ir.Syms.PanicdottypeI, false, nil, itab, target, taddr)
6578 // on success, return data from interface
6581 return s.newValue1(ssa.OpIData, dst, iface), nil
6583 p := s.newValue1(ssa.OpIData, types.NewPtr(dst), iface)
6584 return s.load(dst, p), nil
6587 // commaok is the more complicated case because we have
6588 // a control flow merge point.
6589 bEnd := s.f.NewBlock(ssa.BlockPlain)
6590 // Note that we need a new valVar each time (unlike okVar where we can
6591 // reuse the variable) because it might have a different type every time.
6592 valVar := ssaMarker("val")
6594 // type assertion succeeded
6598 s.vars[valVar] = s.newValue1(ssa.OpIData, dst, iface)
6600 p := s.newValue1(ssa.OpIData, types.NewPtr(dst), iface)
6601 s.vars[valVar] = s.load(dst, p)
6604 p := s.newValue1(ssa.OpIData, types.NewPtr(dst), iface)
6605 s.move(dst, addr, p)
6607 s.vars[okVar] = s.constBool(true)
6611 // type assertion failed
6614 s.vars[valVar] = s.zeroVal(dst)
6618 s.vars[okVar] = s.constBool(false)
6620 bFail.AddEdgeTo(bEnd)
6625 res = s.variable(valVar, dst)
6626 delete(s.vars, valVar) // no practical effect, just to indicate typVar is no longer live.
6628 res = s.load(dst, addr)
6630 resok = s.variable(okVar, types.Types[types.TBOOL])
6631 delete(s.vars, okVar) // ditto
6635 // temp allocates a temp of type t at position pos
6636 func (s *state) temp(pos src.XPos, t *types.Type) (*ir.Name, *ssa.Value) {
6637 tmp := typecheck.TempAt(pos, s.curfn, t)
6638 if t.HasPointers() {
6639 s.vars[memVar] = s.newValue1A(ssa.OpVarDef, types.TypeMem, tmp, s.mem())
6645 // variable returns the value of a variable at the current location.
6646 func (s *state) variable(n ir.Node, t *types.Type) *ssa.Value {
6656 if s.curBlock == s.f.Entry {
6657 // No variable should be live at entry.
6658 s.f.Fatalf("value %v (%v) incorrectly live at entry", n, v)
6660 // Make a FwdRef, which records a value that's live on block input.
6661 // We'll find the matching definition as part of insertPhis.
6662 v = s.newValue0A(ssa.OpFwdRef, t, fwdRefAux{N: n})
6664 if n.Op() == ir.ONAME {
6665 s.addNamedValue(n.(*ir.Name), v)
6670 func (s *state) mem() *ssa.Value {
6671 return s.variable(memVar, types.TypeMem)
6674 func (s *state) addNamedValue(n *ir.Name, v *ssa.Value) {
6675 if n.Class == ir.Pxxx {
6676 // Don't track our marker nodes (memVar etc.).
6679 if ir.IsAutoTmp(n) {
6680 // Don't track temporary variables.
6683 if n.Class == ir.PPARAMOUT {
6684 // Don't track named output values. This prevents return values
6685 // from being assigned too early. See #14591 and #14762. TODO: allow this.
6688 loc := ssa.LocalSlot{N: n, Type: n.Type(), Off: 0}
6689 values, ok := s.f.NamedValues[loc]
6691 s.f.Names = append(s.f.Names, &loc)
6692 s.f.CanonicalLocalSlots[loc] = &loc
6694 s.f.NamedValues[loc] = append(values, v)
6697 // Branch is an unresolved branch.
6698 type Branch struct {
6699 P *obj.Prog // branch instruction
6700 B *ssa.Block // target
6703 // State contains state needed during Prog generation.
6709 // Branches remembers all the branch instructions we've seen
6710 // and where they would like to go.
6713 // JumpTables remembers all the jump tables we've seen.
6714 JumpTables []*ssa.Block
6716 // bstart remembers where each block starts (indexed by block ID)
6719 maxarg int64 // largest frame size for arguments to calls made by the function
6721 // Map from GC safe points to liveness index, generated by
6722 // liveness analysis.
6723 livenessMap liveness.Map
6725 // partLiveArgs includes arguments that may be partially live, for which we
6726 // need to generate instructions that spill the argument registers.
6727 partLiveArgs map[*ir.Name]bool
6729 // lineRunStart records the beginning of the current run of instructions
6730 // within a single block sharing the same line number
6731 // Used to move statement marks to the beginning of such runs.
6732 lineRunStart *obj.Prog
6734 // wasm: The number of values on the WebAssembly stack. This is only used as a safeguard.
6735 OnWasmStackSkipped int
6738 func (s *State) FuncInfo() *obj.FuncInfo {
6739 return s.pp.CurFunc.LSym.Func()
6742 // Prog appends a new Prog.
6743 func (s *State) Prog(as obj.As) *obj.Prog {
6745 if objw.LosesStmtMark(as) {
6748 // Float a statement start to the beginning of any same-line run.
6749 // lineRunStart is reset at block boundaries, which appears to work well.
6750 if s.lineRunStart == nil || s.lineRunStart.Pos.Line() != p.Pos.Line() {
6752 } else if p.Pos.IsStmt() == src.PosIsStmt {
6753 s.lineRunStart.Pos = s.lineRunStart.Pos.WithIsStmt()
6754 p.Pos = p.Pos.WithNotStmt()
6759 // Pc returns the current Prog.
6760 func (s *State) Pc() *obj.Prog {
6764 // SetPos sets the current source position.
6765 func (s *State) SetPos(pos src.XPos) {
6769 // Br emits a single branch instruction and returns the instruction.
6770 // Not all architectures need the returned instruction, but otherwise
6771 // the boilerplate is common to all.
6772 func (s *State) Br(op obj.As, target *ssa.Block) *obj.Prog {
6774 p.To.Type = obj.TYPE_BRANCH
6775 s.Branches = append(s.Branches, Branch{P: p, B: target})
6779 // DebugFriendlySetPosFrom adjusts Pos.IsStmt subject to heuristics
6780 // that reduce "jumpy" line number churn when debugging.
6781 // Spill/fill/copy instructions from the register allocator,
6782 // phi functions, and instructions with a no-pos position
6783 // are examples of instructions that can cause churn.
6784 func (s *State) DebugFriendlySetPosFrom(v *ssa.Value) {
6786 case ssa.OpPhi, ssa.OpCopy, ssa.OpLoadReg, ssa.OpStoreReg:
6787 // These are not statements
6788 s.SetPos(v.Pos.WithNotStmt())
6791 if p != src.NoXPos {
6792 // If the position is defined, update the position.
6793 // Also convert default IsStmt to NotStmt; only
6794 // explicit statement boundaries should appear
6795 // in the generated code.
6796 if p.IsStmt() != src.PosIsStmt {
6797 if s.pp.Pos.IsStmt() == src.PosIsStmt && s.pp.Pos.SameFileAndLine(p) {
6798 // If s.pp.Pos already has a statement mark, then it was set here (below) for
6799 // the previous value. If an actual instruction had been emitted for that
6800 // value, then the statement mark would have been reset. Since the statement
6801 // mark of s.pp.Pos was not reset, this position (file/line) still needs a
6802 // statement mark on an instruction. If file and line for this value are
6803 // the same as the previous value, then the first instruction for this
6804 // value will work to take the statement mark. Return early to avoid
6805 // resetting the statement mark.
6807 // The reset of s.pp.Pos occurs in (*Progs).Prog() -- if it emits
6808 // an instruction, and the instruction's statement mark was set,
6809 // and it is not one of the LosesStmtMark instructions,
6810 // then Prog() resets the statement mark on the (*Progs).Pos.
6814 // Calls use the pos attached to v, but copy the statement mark from State
6818 s.SetPos(s.pp.Pos.WithNotStmt())
6823 // emit argument info (locations on stack) for traceback.
6824 func emitArgInfo(e *ssafn, f *ssa.Func, pp *objw.Progs) {
6825 ft := e.curfn.Type()
6826 if ft.NumRecvs() == 0 && ft.NumParams() == 0 {
6830 x := EmitArgInfo(e.curfn, f.OwnAux.ABIInfo())
6831 x.Set(obj.AttrContentAddressable, true)
6832 e.curfn.LSym.Func().ArgInfo = x
6834 // Emit a funcdata pointing at the arg info data.
6835 p := pp.Prog(obj.AFUNCDATA)
6836 p.From.SetConst(rtabi.FUNCDATA_ArgInfo)
6837 p.To.Type = obj.TYPE_MEM
6838 p.To.Name = obj.NAME_EXTERN
6842 // emit argument info (locations on stack) of f for traceback.
6843 func EmitArgInfo(f *ir.Func, abiInfo *abi.ABIParamResultInfo) *obj.LSym {
6844 x := base.Ctxt.Lookup(fmt.Sprintf("%s.arginfo%d", f.LSym.Name, f.ABI))
6845 // NOTE: do not set ContentAddressable here. This may be referenced from
6846 // assembly code by name (in this case f is a declaration).
6847 // Instead, set it in emitArgInfo above.
6849 PtrSize := int64(types.PtrSize)
6850 uintptrTyp := types.Types[types.TUINTPTR]
6852 isAggregate := func(t *types.Type) bool {
6853 return t.IsStruct() || t.IsArray() || t.IsComplex() || t.IsInterface() || t.IsString() || t.IsSlice()
6856 // Populate the data.
6857 // The data is a stream of bytes, which contains the offsets and sizes of the
6858 // non-aggregate arguments or non-aggregate fields/elements of aggregate-typed
6859 // arguments, along with special "operators". Specifically,
6860 // - for each non-aggrgate arg/field/element, its offset from FP (1 byte) and
6862 // - special operators:
6863 // - 0xff - end of sequence
6864 // - 0xfe - print { (at the start of an aggregate-typed argument)
6865 // - 0xfd - print } (at the end of an aggregate-typed argument)
6866 // - 0xfc - print ... (more args/fields/elements)
6867 // - 0xfb - print _ (offset too large)
6868 // These constants need to be in sync with runtime.traceback.go:printArgs.
6874 _offsetTooLarge = 0xfb
6875 _special = 0xf0 // above this are operators, below this are ordinary offsets
6879 limit = 10 // print no more than 10 args/components
6880 maxDepth = 5 // no more than 5 layers of nesting
6882 // maxLen is a (conservative) upper bound of the byte stream length. For
6883 // each arg/component, it has no more than 2 bytes of data (size, offset),
6884 // and no more than one {, }, ... at each level (it cannot have both the
6885 // data and ... unless it is the last one, just be conservative). Plus 1
6887 maxLen = (maxDepth*3+2)*limit + 1
6892 writebyte := func(o uint8) { wOff = objw.Uint8(x, wOff, o) }
6894 // Write one non-aggrgate arg/field/element.
6895 write1 := func(sz, offset int64) {
6896 if offset >= _special {
6897 writebyte(_offsetTooLarge)
6899 writebyte(uint8(offset))
6900 writebyte(uint8(sz))
6905 // Visit t recursively and write it out.
6906 // Returns whether to continue visiting.
6907 var visitType func(baseOffset int64, t *types.Type, depth int) bool
6908 visitType = func(baseOffset int64, t *types.Type, depth int) bool {
6910 writebyte(_dotdotdot)
6913 if !isAggregate(t) {
6914 write1(t.Size(), baseOffset)
6917 writebyte(_startAgg)
6919 if depth >= maxDepth {
6920 writebyte(_dotdotdot)
6926 case t.IsInterface(), t.IsString():
6927 _ = visitType(baseOffset, uintptrTyp, depth) &&
6928 visitType(baseOffset+PtrSize, uintptrTyp, depth)
6930 _ = visitType(baseOffset, uintptrTyp, depth) &&
6931 visitType(baseOffset+PtrSize, uintptrTyp, depth) &&
6932 visitType(baseOffset+PtrSize*2, uintptrTyp, depth)
6934 _ = visitType(baseOffset, types.FloatForComplex(t), depth) &&
6935 visitType(baseOffset+t.Size()/2, types.FloatForComplex(t), depth)
6937 if t.NumElem() == 0 {
6938 n++ // {} counts as a component
6941 for i := int64(0); i < t.NumElem(); i++ {
6942 if !visitType(baseOffset, t.Elem(), depth) {
6945 baseOffset += t.Elem().Size()
6948 if t.NumFields() == 0 {
6949 n++ // {} counts as a component
6952 for _, field := range t.Fields() {
6953 if !visitType(baseOffset+field.Offset, field.Type, depth) {
6963 if strings.Contains(f.LSym.Name, "[") {
6964 // Skip the dictionary argument - it is implicit and the user doesn't need to see it.
6968 for _, a := range abiInfo.InParams()[start:] {
6969 if !visitType(a.FrameOffset(abiInfo), a.Type, 0) {
6975 base.Fatalf("ArgInfo too large")
6981 // for wrapper, emit info of wrapped function.
6982 func emitWrappedFuncInfo(e *ssafn, pp *objw.Progs) {
6983 if base.Ctxt.Flag_linkshared {
6984 // Relative reference (SymPtrOff) to another shared object doesn't work.
6989 wfn := e.curfn.WrappedFunc
6994 wsym := wfn.Linksym()
6995 x := base.Ctxt.LookupInit(fmt.Sprintf("%s.wrapinfo", wsym.Name), func(x *obj.LSym) {
6996 objw.SymPtrOff(x, 0, wsym)
6997 x.Set(obj.AttrContentAddressable, true)
6999 e.curfn.LSym.Func().WrapInfo = x
7001 // Emit a funcdata pointing at the wrap info data.
7002 p := pp.Prog(obj.AFUNCDATA)
7003 p.From.SetConst(rtabi.FUNCDATA_WrapInfo)
7004 p.To.Type = obj.TYPE_MEM
7005 p.To.Name = obj.NAME_EXTERN
7009 // genssa appends entries to pp for each instruction in f.
7010 func genssa(f *ssa.Func, pp *objw.Progs) {
7012 s.ABI = f.OwnAux.Fn.ABI()
7014 e := f.Frontend().(*ssafn)
7016 s.livenessMap, s.partLiveArgs = liveness.Compute(e.curfn, f, e.stkptrsize, pp)
7017 emitArgInfo(e, f, pp)
7018 argLiveBlockMap, argLiveValueMap := liveness.ArgLiveness(e.curfn, f, pp)
7020 openDeferInfo := e.curfn.LSym.Func().OpenCodedDeferInfo
7021 if openDeferInfo != nil {
7022 // This function uses open-coded defers -- write out the funcdata
7023 // info that we computed at the end of genssa.
7024 p := pp.Prog(obj.AFUNCDATA)
7025 p.From.SetConst(rtabi.FUNCDATA_OpenCodedDeferInfo)
7026 p.To.Type = obj.TYPE_MEM
7027 p.To.Name = obj.NAME_EXTERN
7028 p.To.Sym = openDeferInfo
7031 emitWrappedFuncInfo(e, pp)
7033 // Remember where each block starts.
7034 s.bstart = make([]*obj.Prog, f.NumBlocks())
7036 var progToValue map[*obj.Prog]*ssa.Value
7037 var progToBlock map[*obj.Prog]*ssa.Block
7038 var valueToProgAfter []*obj.Prog // The first Prog following computation of a value v; v is visible at this point.
7039 gatherPrintInfo := f.PrintOrHtmlSSA || ssa.GenssaDump[f.Name]
7040 if gatherPrintInfo {
7041 progToValue = make(map[*obj.Prog]*ssa.Value, f.NumValues())
7042 progToBlock = make(map[*obj.Prog]*ssa.Block, f.NumBlocks())
7043 f.Logf("genssa %s\n", f.Name)
7044 progToBlock[s.pp.Next] = f.Blocks[0]
7047 if base.Ctxt.Flag_locationlists {
7048 if cap(f.Cache.ValueToProgAfter) < f.NumValues() {
7049 f.Cache.ValueToProgAfter = make([]*obj.Prog, f.NumValues())
7051 valueToProgAfter = f.Cache.ValueToProgAfter[:f.NumValues()]
7052 for i := range valueToProgAfter {
7053 valueToProgAfter[i] = nil
7057 // If the very first instruction is not tagged as a statement,
7058 // debuggers may attribute it to previous function in program.
7059 firstPos := src.NoXPos
7060 for _, v := range f.Entry.Values {
7061 if v.Pos.IsStmt() == src.PosIsStmt && v.Op != ssa.OpArg && v.Op != ssa.OpArgIntReg && v.Op != ssa.OpArgFloatReg && v.Op != ssa.OpLoadReg && v.Op != ssa.OpStoreReg {
7063 v.Pos = firstPos.WithDefaultStmt()
7068 // inlMarks has an entry for each Prog that implements an inline mark.
7069 // It maps from that Prog to the global inlining id of the inlined body
7070 // which should unwind to this Prog's location.
7071 var inlMarks map[*obj.Prog]int32
7072 var inlMarkList []*obj.Prog
7074 // inlMarksByPos maps from a (column 1) source position to the set of
7075 // Progs that are in the set above and have that source position.
7076 var inlMarksByPos map[src.XPos][]*obj.Prog
7078 var argLiveIdx int = -1 // argument liveness info index
7080 // Emit basic blocks
7081 for i, b := range f.Blocks {
7082 s.bstart[b.ID] = s.pp.Next
7083 s.lineRunStart = nil
7084 s.SetPos(s.pp.Pos.WithNotStmt()) // It needs a non-empty Pos, but cannot be a statement boundary (yet).
7086 if idx, ok := argLiveBlockMap[b.ID]; ok && idx != argLiveIdx {
7088 p := s.pp.Prog(obj.APCDATA)
7089 p.From.SetConst(rtabi.PCDATA_ArgLiveIndex)
7090 p.To.SetConst(int64(idx))
7093 // Emit values in block
7094 Arch.SSAMarkMoves(&s, b)
7095 for _, v := range b.Values {
7097 s.DebugFriendlySetPosFrom(v)
7099 if v.Op.ResultInArg0() && v.ResultReg() != v.Args[0].Reg() {
7100 v.Fatalf("input[0] and output not in same register %s", v.LongString())
7105 // memory arg needs no code
7107 // input args need no code
7108 case ssa.OpSP, ssa.OpSB:
7110 case ssa.OpSelect0, ssa.OpSelect1, ssa.OpSelectN, ssa.OpMakeResult:
7113 // nothing to do when there's a g register,
7114 // and checkLower complains if there's not
7115 case ssa.OpVarDef, ssa.OpVarLive, ssa.OpKeepAlive, ssa.OpWBend:
7116 // nothing to do; already used by liveness
7120 // nothing to do; no-op conversion for liveness
7121 if v.Args[0].Reg() != v.Reg() {
7122 v.Fatalf("OpConvert should be a no-op: %s; %s", v.Args[0].LongString(), v.LongString())
7125 p := Arch.Ginsnop(s.pp)
7126 if inlMarks == nil {
7127 inlMarks = map[*obj.Prog]int32{}
7128 inlMarksByPos = map[src.XPos][]*obj.Prog{}
7130 inlMarks[p] = v.AuxInt32()
7131 inlMarkList = append(inlMarkList, p)
7132 pos := v.Pos.AtColumn1()
7133 inlMarksByPos[pos] = append(inlMarksByPos[pos], p)
7134 firstPos = src.NoXPos
7137 // Special case for first line in function; move it to the start (which cannot be a register-valued instruction)
7138 if firstPos != src.NoXPos && v.Op != ssa.OpArgIntReg && v.Op != ssa.OpArgFloatReg && v.Op != ssa.OpLoadReg && v.Op != ssa.OpStoreReg {
7140 firstPos = src.NoXPos
7142 // Attach this safe point to the next
7144 s.pp.NextLive = s.livenessMap.Get(v)
7145 s.pp.NextUnsafe = s.livenessMap.GetUnsafe(v)
7147 // let the backend handle it
7148 Arch.SSAGenValue(&s, v)
7151 if idx, ok := argLiveValueMap[v.ID]; ok && idx != argLiveIdx {
7153 p := s.pp.Prog(obj.APCDATA)
7154 p.From.SetConst(rtabi.PCDATA_ArgLiveIndex)
7155 p.To.SetConst(int64(idx))
7158 if base.Ctxt.Flag_locationlists {
7159 valueToProgAfter[v.ID] = s.pp.Next
7162 if gatherPrintInfo {
7163 for ; x != s.pp.Next; x = x.Link {
7168 // If this is an empty infinite loop, stick a hardware NOP in there so that debuggers are less confused.
7169 if s.bstart[b.ID] == s.pp.Next && len(b.Succs) == 1 && b.Succs[0].Block() == b {
7170 p := Arch.Ginsnop(s.pp)
7171 p.Pos = p.Pos.WithIsStmt()
7172 if b.Pos == src.NoXPos {
7173 b.Pos = p.Pos // It needs a file, otherwise a no-file non-zero line causes confusion. See #35652.
7174 if b.Pos == src.NoXPos {
7175 b.Pos = pp.Text.Pos // Sometimes p.Pos is empty. See #35695.
7178 b.Pos = b.Pos.WithBogusLine() // Debuggers are not good about infinite loops, force a change in line number
7181 // Set unsafe mark for any end-of-block generated instructions
7182 // (normally, conditional or unconditional branches).
7183 // This is particularly important for empty blocks, as there
7184 // are no values to inherit the unsafe mark from.
7185 s.pp.NextUnsafe = s.livenessMap.GetUnsafeBlock(b)
7187 // Emit control flow instructions for block
7189 if i < len(f.Blocks)-1 && base.Flag.N == 0 {
7190 // If -N, leave next==nil so every block with successors
7191 // ends in a JMP (except call blocks - plive doesn't like
7192 // select{send,recv} followed by a JMP call). Helps keep
7193 // line numbers for otherwise empty blocks.
7194 next = f.Blocks[i+1]
7198 Arch.SSAGenBlock(&s, b, next)
7199 if gatherPrintInfo {
7200 for ; x != s.pp.Next; x = x.Link {
7205 if f.Blocks[len(f.Blocks)-1].Kind == ssa.BlockExit {
7206 // We need the return address of a panic call to
7207 // still be inside the function in question. So if
7208 // it ends in a call which doesn't return, add a
7209 // nop (which will never execute) after the call.
7212 if openDeferInfo != nil {
7213 // When doing open-coded defers, generate a disconnected call to
7214 // deferreturn and a return. This will be used to during panic
7215 // recovery to unwind the stack and return back to the runtime.
7216 s.pp.NextLive = s.livenessMap.DeferReturn
7217 p := pp.Prog(obj.ACALL)
7218 p.To.Type = obj.TYPE_MEM
7219 p.To.Name = obj.NAME_EXTERN
7220 p.To.Sym = ir.Syms.Deferreturn
7222 // Load results into registers. So when a deferred function
7223 // recovers a panic, it will return to caller with right results.
7224 // The results are already in memory, because they are not SSA'd
7225 // when the function has defers (see canSSAName).
7226 for _, o := range f.OwnAux.ABIInfo().OutParams() {
7228 rts, offs := o.RegisterTypesAndOffsets()
7229 for i := range o.Registers {
7230 Arch.LoadRegResult(&s, f, rts[i], ssa.ObjRegForAbiReg(o.Registers[i], f.Config), n, offs[i])
7237 if inlMarks != nil {
7240 // We have some inline marks. Try to find other instructions we're
7241 // going to emit anyway, and use those instructions instead of the
7243 for p := pp.Text; p != nil; p = p.Link {
7244 if p.As == obj.ANOP || p.As == obj.AFUNCDATA || p.As == obj.APCDATA || p.As == obj.ATEXT || p.As == obj.APCALIGN || Arch.LinkArch.Family == sys.Wasm {
7245 // Don't use 0-sized instructions as inline marks, because we need
7246 // to identify inline mark instructions by pc offset.
7247 // (Some of these instructions are sometimes zero-sized, sometimes not.
7248 // We must not use anything that even might be zero-sized.)
7249 // TODO: are there others?
7252 if _, ok := inlMarks[p]; ok {
7253 // Don't use inline marks themselves. We don't know
7254 // whether they will be zero-sized or not yet.
7257 if p.As == obj.ACALL || p.As == obj.ADUFFCOPY || p.As == obj.ADUFFZERO {
7260 pos := p.Pos.AtColumn1()
7261 s := inlMarksByPos[pos]
7265 for _, m := range s {
7266 // We found an instruction with the same source position as
7267 // some of the inline marks.
7268 // Use this instruction instead.
7269 p.Pos = p.Pos.WithIsStmt() // promote position to a statement
7270 pp.CurFunc.LSym.Func().AddInlMark(p, inlMarks[m])
7271 // Make the inline mark a real nop, so it doesn't generate any code.
7277 delete(inlMarksByPos, pos)
7279 // Any unmatched inline marks now need to be added to the inlining tree (and will generate a nop instruction).
7280 for _, p := range inlMarkList {
7281 if p.As != obj.ANOP {
7282 pp.CurFunc.LSym.Func().AddInlMark(p, inlMarks[p])
7286 if e.stksize == 0 && !hasCall {
7287 // Frameless leaf function. It doesn't need any preamble,
7288 // so make sure its first instruction isn't from an inlined callee.
7289 // If it is, add a nop at the start of the function with a position
7290 // equal to the start of the function.
7291 // This ensures that runtime.FuncForPC(uintptr(reflect.ValueOf(fn).Pointer())).Name()
7292 // returns the right answer. See issue 58300.
7293 for p := pp.Text; p != nil; p = p.Link {
7294 if p.As == obj.AFUNCDATA || p.As == obj.APCDATA || p.As == obj.ATEXT || p.As == obj.ANOP {
7297 if base.Ctxt.PosTable.Pos(p.Pos).Base().InliningIndex() >= 0 {
7298 // Make a real (not 0-sized) nop.
7299 nop := Arch.Ginsnop(pp)
7300 nop.Pos = e.curfn.Pos().WithIsStmt()
7302 // Unfortunately, Ginsnop puts the instruction at the
7303 // end of the list. Move it up to just before p.
7305 // Unlink from the current list.
7306 for x := pp.Text; x != nil; x = x.Link {
7312 // Splice in right before p.
7313 for x := pp.Text; x != nil; x = x.Link {
7326 if base.Ctxt.Flag_locationlists {
7327 var debugInfo *ssa.FuncDebug
7328 debugInfo = e.curfn.DebugInfo.(*ssa.FuncDebug)
7329 if e.curfn.ABI == obj.ABIInternal && base.Flag.N != 0 {
7330 ssa.BuildFuncDebugNoOptimized(base.Ctxt, f, base.Debug.LocationLists > 1, StackOffset, debugInfo)
7332 ssa.BuildFuncDebug(base.Ctxt, f, base.Debug.LocationLists, StackOffset, debugInfo)
7335 idToIdx := make([]int, f.NumBlocks())
7336 for i, b := range f.Blocks {
7339 // Note that at this moment, Prog.Pc is a sequence number; it's
7340 // not a real PC until after assembly, so this mapping has to
7342 debugInfo.GetPC = func(b, v ssa.ID) int64 {
7344 case ssa.BlockStart.ID:
7345 if b == f.Entry.ID {
7346 return 0 // Start at the very beginning, at the assembler-generated prologue.
7347 // this should only happen for function args (ssa.OpArg)
7350 case ssa.BlockEnd.ID:
7351 blk := f.Blocks[idToIdx[b]]
7352 nv := len(blk.Values)
7353 return valueToProgAfter[blk.Values[nv-1].ID].Pc
7354 case ssa.FuncEnd.ID:
7355 return e.curfn.LSym.Size
7357 return valueToProgAfter[v].Pc
7362 // Resolve branches, and relax DefaultStmt into NotStmt
7363 for _, br := range s.Branches {
7364 br.P.To.SetTarget(s.bstart[br.B.ID])
7365 if br.P.Pos.IsStmt() != src.PosIsStmt {
7366 br.P.Pos = br.P.Pos.WithNotStmt()
7367 } else if v0 := br.B.FirstPossibleStmtValue(); v0 != nil && v0.Pos.Line() == br.P.Pos.Line() && v0.Pos.IsStmt() == src.PosIsStmt {
7368 br.P.Pos = br.P.Pos.WithNotStmt()
7373 // Resolve jump table destinations.
7374 for _, jt := range s.JumpTables {
7375 // Convert from *Block targets to *Prog targets.
7376 targets := make([]*obj.Prog, len(jt.Succs))
7377 for i, e := range jt.Succs {
7378 targets[i] = s.bstart[e.Block().ID]
7380 // Add to list of jump tables to be resolved at assembly time.
7381 // The assembler converts from *Prog entries to absolute addresses
7382 // once it knows instruction byte offsets.
7383 fi := pp.CurFunc.LSym.Func()
7384 fi.JumpTables = append(fi.JumpTables, obj.JumpTable{Sym: jt.Aux.(*obj.LSym), Targets: targets})
7387 if e.log { // spew to stdout
7389 for p := pp.Text; p != nil; p = p.Link {
7390 if p.Pos.IsKnown() && p.InnermostFilename() != filename {
7391 filename = p.InnermostFilename()
7392 f.Logf("# %s\n", filename)
7396 if v, ok := progToValue[p]; ok {
7398 } else if b, ok := progToBlock[p]; ok {
7401 s = " " // most value and branch strings are 2-3 characters long
7403 f.Logf(" %-6s\t%.5d (%s)\t%s\n", s, p.Pc, p.InnermostLineNumber(), p.InstructionString())
7406 if f.HTMLWriter != nil { // spew to ssa.html
7407 var buf strings.Builder
7408 buf.WriteString("<code>")
7409 buf.WriteString("<dl class=\"ssa-gen\">")
7411 for p := pp.Text; p != nil; p = p.Link {
7412 // Don't spam every line with the file name, which is often huge.
7413 // Only print changes, and "unknown" is not a change.
7414 if p.Pos.IsKnown() && p.InnermostFilename() != filename {
7415 filename = p.InnermostFilename()
7416 buf.WriteString("<dt class=\"ssa-prog-src\"></dt><dd class=\"ssa-prog\">")
7417 buf.WriteString(html.EscapeString("# " + filename))
7418 buf.WriteString("</dd>")
7421 buf.WriteString("<dt class=\"ssa-prog-src\">")
7422 if v, ok := progToValue[p]; ok {
7423 buf.WriteString(v.HTML())
7424 } else if b, ok := progToBlock[p]; ok {
7425 buf.WriteString("<b>" + b.HTML() + "</b>")
7427 buf.WriteString("</dt>")
7428 buf.WriteString("<dd class=\"ssa-prog\">")
7429 fmt.Fprintf(&buf, "%.5d <span class=\"l%v line-number\">(%s)</span> %s", p.Pc, p.InnermostLineNumber(), p.InnermostLineNumberHTML(), html.EscapeString(p.InstructionString()))
7430 buf.WriteString("</dd>")
7432 buf.WriteString("</dl>")
7433 buf.WriteString("</code>")
7434 f.HTMLWriter.WriteColumn("genssa", "genssa", "ssa-prog", buf.String())
7436 if ssa.GenssaDump[f.Name] {
7437 fi := f.DumpFileForPhase("genssa")
7440 // inliningDiffers if any filename changes or if any line number except the innermost (last index) changes.
7441 inliningDiffers := func(a, b []src.Pos) bool {
7442 if len(a) != len(b) {
7446 if a[i].Filename() != b[i].Filename() {
7449 if i != len(a)-1 && a[i].Line() != b[i].Line() {
7456 var allPosOld []src.Pos
7457 var allPos []src.Pos
7459 for p := pp.Text; p != nil; p = p.Link {
7460 if p.Pos.IsKnown() {
7462 p.Ctxt.AllPos(p.Pos, func(pos src.Pos) { allPos = append(allPos, pos) })
7463 if inliningDiffers(allPos, allPosOld) {
7464 for _, pos := range allPos {
7465 fmt.Fprintf(fi, "# %s:%d\n", pos.Filename(), pos.Line())
7467 allPos, allPosOld = allPosOld, allPos // swap, not copy, so that they do not share slice storage.
7472 if v, ok := progToValue[p]; ok {
7474 } else if b, ok := progToBlock[p]; ok {
7477 s = " " // most value and branch strings are 2-3 characters long
7479 fmt.Fprintf(fi, " %-6s\t%.5d %s\t%s\n", s, p.Pc, ssa.StmtString(p.Pos), p.InstructionString())
7487 f.HTMLWriter.Close()
7491 func defframe(s *State, e *ssafn, f *ssa.Func) {
7494 s.maxarg = types.RoundUp(s.maxarg, e.stkalign)
7495 frame := s.maxarg + e.stksize
7496 if Arch.PadFrame != nil {
7497 frame = Arch.PadFrame(frame)
7500 // Fill in argument and frame size.
7501 pp.Text.To.Type = obj.TYPE_TEXTSIZE
7502 pp.Text.To.Val = int32(types.RoundUp(f.OwnAux.ArgWidth(), int64(types.RegSize)))
7503 pp.Text.To.Offset = frame
7507 // Insert code to spill argument registers if the named slot may be partially
7508 // live. That is, the named slot is considered live by liveness analysis,
7509 // (because a part of it is live), but we may not spill all parts into the
7510 // slot. This can only happen with aggregate-typed arguments that are SSA-able
7511 // and not address-taken (for non-SSA-able or address-taken arguments we always
7513 // Note: spilling is unnecessary in the -N/no-optimize case, since all values
7514 // will be considered non-SSAable and spilled up front.
7515 // TODO(register args) Make liveness more fine-grained to that partial spilling is okay.
7516 if f.OwnAux.ABIInfo().InRegistersUsed() != 0 && base.Flag.N == 0 {
7517 // First, see if it is already spilled before it may be live. Look for a spill
7518 // in the entry block up to the first safepoint.
7519 type nameOff struct {
7523 partLiveArgsSpilled := make(map[nameOff]bool)
7524 for _, v := range f.Entry.Values {
7528 if v.Op != ssa.OpStoreReg || v.Args[0].Op != ssa.OpArgIntReg {
7531 n, off := ssa.AutoVar(v)
7532 if n.Class != ir.PPARAM || n.Addrtaken() || !ssa.CanSSA(n.Type()) || !s.partLiveArgs[n] {
7535 partLiveArgsSpilled[nameOff{n, off}] = true
7538 // Then, insert code to spill registers if not already.
7539 for _, a := range f.OwnAux.ABIInfo().InParams() {
7541 if n == nil || n.Addrtaken() || !ssa.CanSSA(n.Type()) || !s.partLiveArgs[n] || len(a.Registers) <= 1 {
7544 rts, offs := a.RegisterTypesAndOffsets()
7545 for i := range a.Registers {
7546 if !rts[i].HasPointers() {
7549 if partLiveArgsSpilled[nameOff{n, offs[i]}] {
7550 continue // already spilled
7552 reg := ssa.ObjRegForAbiReg(a.Registers[i], f.Config)
7553 p = Arch.SpillArgReg(pp, p, f, rts[i], reg, n, offs[i])
7558 // Insert code to zero ambiguously live variables so that the
7559 // garbage collector only sees initialized values when it
7560 // looks for pointers.
7563 // Opaque state for backend to use. Current backends use it to
7564 // keep track of which helper registers have been zeroed.
7567 // Iterate through declarations. Autos are sorted in decreasing
7568 // frame offset order.
7569 for _, n := range e.curfn.Dcl {
7573 if n.Class != ir.PAUTO {
7574 e.Fatalf(n.Pos(), "needzero class %d", n.Class)
7576 if n.Type().Size()%int64(types.PtrSize) != 0 || n.FrameOffset()%int64(types.PtrSize) != 0 || n.Type().Size() == 0 {
7577 e.Fatalf(n.Pos(), "var %L has size %d offset %d", n, n.Type().Size(), n.Offset_)
7580 if lo != hi && n.FrameOffset()+n.Type().Size() >= lo-int64(2*types.RegSize) {
7581 // Merge with range we already have.
7582 lo = n.FrameOffset()
7587 p = Arch.ZeroRange(pp, p, frame+lo, hi-lo, &state)
7590 lo = n.FrameOffset()
7591 hi = lo + n.Type().Size()
7594 // Zero final range.
7595 Arch.ZeroRange(pp, p, frame+lo, hi-lo, &state)
7598 // For generating consecutive jump instructions to model a specific branching
7599 type IndexJump struct {
7604 func (s *State) oneJump(b *ssa.Block, jump *IndexJump) {
7605 p := s.Br(jump.Jump, b.Succs[jump.Index].Block())
7609 // CombJump generates combinational instructions (2 at present) for a block jump,
7610 // thereby the behaviour of non-standard condition codes could be simulated
7611 func (s *State) CombJump(b, next *ssa.Block, jumps *[2][2]IndexJump) {
7613 case b.Succs[0].Block():
7614 s.oneJump(b, &jumps[0][0])
7615 s.oneJump(b, &jumps[0][1])
7616 case b.Succs[1].Block():
7617 s.oneJump(b, &jumps[1][0])
7618 s.oneJump(b, &jumps[1][1])
7621 if b.Likely != ssa.BranchUnlikely {
7622 s.oneJump(b, &jumps[1][0])
7623 s.oneJump(b, &jumps[1][1])
7624 q = s.Br(obj.AJMP, b.Succs[1].Block())
7626 s.oneJump(b, &jumps[0][0])
7627 s.oneJump(b, &jumps[0][1])
7628 q = s.Br(obj.AJMP, b.Succs[0].Block())
7634 // AddAux adds the offset in the aux fields (AuxInt and Aux) of v to a.
7635 func AddAux(a *obj.Addr, v *ssa.Value) {
7636 AddAux2(a, v, v.AuxInt)
7638 func AddAux2(a *obj.Addr, v *ssa.Value, offset int64) {
7639 if a.Type != obj.TYPE_MEM && a.Type != obj.TYPE_ADDR {
7640 v.Fatalf("bad AddAux addr %v", a)
7642 // add integer offset
7645 // If no additional symbol offset, we're done.
7649 // Add symbol's offset from its base register.
7650 switch n := v.Aux.(type) {
7652 a.Name = obj.NAME_EXTERN
7655 a.Name = obj.NAME_EXTERN
7658 if n.Class == ir.PPARAM || (n.Class == ir.PPARAMOUT && !n.IsOutputParamInRegisters()) {
7659 a.Name = obj.NAME_PARAM
7661 a.Name = obj.NAME_AUTO
7664 a.Offset += n.FrameOffset()
7666 v.Fatalf("aux in %s not implemented %#v", v, v.Aux)
7670 // extendIndex extends v to a full int width.
7671 // panic with the given kind if v does not fit in an int (only on 32-bit archs).
7672 func (s *state) extendIndex(idx, len *ssa.Value, kind ssa.BoundsKind, bounded bool) *ssa.Value {
7673 size := idx.Type.Size()
7674 if size == s.config.PtrSize {
7677 if size > s.config.PtrSize {
7678 // truncate 64-bit indexes on 32-bit pointer archs. Test the
7679 // high word and branch to out-of-bounds failure if it is not 0.
7681 if idx.Type.IsSigned() {
7682 lo = s.newValue1(ssa.OpInt64Lo, types.Types[types.TINT], idx)
7684 lo = s.newValue1(ssa.OpInt64Lo, types.Types[types.TUINT], idx)
7686 if bounded || base.Flag.B != 0 {
7689 bNext := s.f.NewBlock(ssa.BlockPlain)
7690 bPanic := s.f.NewBlock(ssa.BlockExit)
7691 hi := s.newValue1(ssa.OpInt64Hi, types.Types[types.TUINT32], idx)
7692 cmp := s.newValue2(ssa.OpEq32, types.Types[types.TBOOL], hi, s.constInt32(types.Types[types.TUINT32], 0))
7693 if !idx.Type.IsSigned() {
7695 case ssa.BoundsIndex:
7696 kind = ssa.BoundsIndexU
7697 case ssa.BoundsSliceAlen:
7698 kind = ssa.BoundsSliceAlenU
7699 case ssa.BoundsSliceAcap:
7700 kind = ssa.BoundsSliceAcapU
7701 case ssa.BoundsSliceB:
7702 kind = ssa.BoundsSliceBU
7703 case ssa.BoundsSlice3Alen:
7704 kind = ssa.BoundsSlice3AlenU
7705 case ssa.BoundsSlice3Acap:
7706 kind = ssa.BoundsSlice3AcapU
7707 case ssa.BoundsSlice3B:
7708 kind = ssa.BoundsSlice3BU
7709 case ssa.BoundsSlice3C:
7710 kind = ssa.BoundsSlice3CU
7714 b.Kind = ssa.BlockIf
7716 b.Likely = ssa.BranchLikely
7720 s.startBlock(bPanic)
7721 mem := s.newValue4I(ssa.OpPanicExtend, types.TypeMem, int64(kind), hi, lo, len, s.mem())
7722 s.endBlock().SetControl(mem)
7728 // Extend value to the required size
7730 if idx.Type.IsSigned() {
7731 switch 10*size + s.config.PtrSize {
7733 op = ssa.OpSignExt8to32
7735 op = ssa.OpSignExt8to64
7737 op = ssa.OpSignExt16to32
7739 op = ssa.OpSignExt16to64
7741 op = ssa.OpSignExt32to64
7743 s.Fatalf("bad signed index extension %s", idx.Type)
7746 switch 10*size + s.config.PtrSize {
7748 op = ssa.OpZeroExt8to32
7750 op = ssa.OpZeroExt8to64
7752 op = ssa.OpZeroExt16to32
7754 op = ssa.OpZeroExt16to64
7756 op = ssa.OpZeroExt32to64
7758 s.Fatalf("bad unsigned index extension %s", idx.Type)
7761 return s.newValue1(op, types.Types[types.TINT], idx)
7764 // CheckLoweredPhi checks that regalloc and stackalloc correctly handled phi values.
7765 // Called during ssaGenValue.
7766 func CheckLoweredPhi(v *ssa.Value) {
7767 if v.Op != ssa.OpPhi {
7768 v.Fatalf("CheckLoweredPhi called with non-phi value: %v", v.LongString())
7770 if v.Type.IsMemory() {
7774 loc := f.RegAlloc[v.ID]
7775 for _, a := range v.Args {
7776 if aloc := f.RegAlloc[a.ID]; aloc != loc { // TODO: .Equal() instead?
7777 v.Fatalf("phi arg at different location than phi: %v @ %s, but arg %v @ %s\n%s\n", v, loc, a, aloc, v.Block.Func)
7782 // CheckLoweredGetClosurePtr checks that v is the first instruction in the function's entry block,
7783 // except for incoming in-register arguments.
7784 // The output of LoweredGetClosurePtr is generally hardwired to the correct register.
7785 // That register contains the closure pointer on closure entry.
7786 func CheckLoweredGetClosurePtr(v *ssa.Value) {
7787 entry := v.Block.Func.Entry
7788 if entry != v.Block {
7789 base.Fatalf("in %s, badly placed LoweredGetClosurePtr: %v %v", v.Block.Func.Name, v.Block, v)
7791 for _, w := range entry.Values {
7796 case ssa.OpArgIntReg, ssa.OpArgFloatReg:
7799 base.Fatalf("in %s, badly placed LoweredGetClosurePtr: %v %v", v.Block.Func.Name, v.Block, v)
7804 // CheckArgReg ensures that v is in the function's entry block.
7805 func CheckArgReg(v *ssa.Value) {
7806 entry := v.Block.Func.Entry
7807 if entry != v.Block {
7808 base.Fatalf("in %s, badly placed ArgIReg or ArgFReg: %v %v", v.Block.Func.Name, v.Block, v)
7812 func AddrAuto(a *obj.Addr, v *ssa.Value) {
7813 n, off := ssa.AutoVar(v)
7814 a.Type = obj.TYPE_MEM
7816 a.Reg = int16(Arch.REGSP)
7817 a.Offset = n.FrameOffset() + off
7818 if n.Class == ir.PPARAM || (n.Class == ir.PPARAMOUT && !n.IsOutputParamInRegisters()) {
7819 a.Name = obj.NAME_PARAM
7821 a.Name = obj.NAME_AUTO
7825 // Call returns a new CALL instruction for the SSA value v.
7826 // It uses PrepareCall to prepare the call.
7827 func (s *State) Call(v *ssa.Value) *obj.Prog {
7828 pPosIsStmt := s.pp.Pos.IsStmt() // The statement-ness fo the call comes from ssaGenState
7831 p := s.Prog(obj.ACALL)
7832 if pPosIsStmt == src.PosIsStmt {
7833 p.Pos = v.Pos.WithIsStmt()
7835 p.Pos = v.Pos.WithNotStmt()
7837 if sym, ok := v.Aux.(*ssa.AuxCall); ok && sym.Fn != nil {
7838 p.To.Type = obj.TYPE_MEM
7839 p.To.Name = obj.NAME_EXTERN
7842 // TODO(mdempsky): Can these differences be eliminated?
7843 switch Arch.LinkArch.Family {
7844 case sys.AMD64, sys.I386, sys.PPC64, sys.RISCV64, sys.S390X, sys.Wasm:
7845 p.To.Type = obj.TYPE_REG
7846 case sys.ARM, sys.ARM64, sys.Loong64, sys.MIPS, sys.MIPS64:
7847 p.To.Type = obj.TYPE_MEM
7849 base.Fatalf("unknown indirect call family")
7851 p.To.Reg = v.Args[0].Reg()
7856 // TailCall returns a new tail call instruction for the SSA value v.
7857 // It is like Call, but for a tail call.
7858 func (s *State) TailCall(v *ssa.Value) *obj.Prog {
7864 // PrepareCall prepares to emit a CALL instruction for v and does call-related bookkeeping.
7865 // It must be called immediately before emitting the actual CALL instruction,
7866 // since it emits PCDATA for the stack map at the call (calls are safe points).
7867 func (s *State) PrepareCall(v *ssa.Value) {
7868 idx := s.livenessMap.Get(v)
7869 if !idx.StackMapValid() {
7870 // See Liveness.hasStackMap.
7871 if sym, ok := v.Aux.(*ssa.AuxCall); !ok || !(sym.Fn == ir.Syms.WBZero || sym.Fn == ir.Syms.WBMove) {
7872 base.Fatalf("missing stack map index for %v", v.LongString())
7876 call, ok := v.Aux.(*ssa.AuxCall)
7879 // Record call graph information for nowritebarrierrec
7881 if nowritebarrierrecCheck != nil {
7882 nowritebarrierrecCheck.recordCall(s.pp.CurFunc, call.Fn, v.Pos)
7886 if s.maxarg < v.AuxInt {
7891 // UseArgs records the fact that an instruction needs a certain amount of
7892 // callee args space for its use.
7893 func (s *State) UseArgs(n int64) {
7899 // fieldIdx finds the index of the field referred to by the ODOT node n.
7900 func fieldIdx(n *ir.SelectorExpr) int {
7903 panic("ODOT's LHS is not a struct")
7906 for i, f := range t.Fields() {
7908 if f.Offset != n.Offset() {
7909 panic("field offset doesn't match")
7914 panic(fmt.Sprintf("can't find field in expr %v\n", n))
7916 // TODO: keep the result of this function somewhere in the ODOT Node
7917 // so we don't have to recompute it each time we need it.
7920 // ssafn holds frontend information about a function that the backend is processing.
7921 // It also exports a bunch of compiler services for the ssa backend.
7924 strings map[string]*obj.LSym // map from constant string to data symbols
7925 stksize int64 // stack size for current frame
7926 stkptrsize int64 // prefix of stack containing pointers
7928 // alignment for current frame.
7929 // NOTE: when stkalign > PtrSize, currently this only ensures the offsets of
7930 // objects in the stack frame are aligned. The stack pointer is still aligned
7934 log bool // print ssa debug to the stdout
7937 // StringData returns a symbol which
7938 // is the data component of a global string constant containing s.
7939 func (e *ssafn) StringData(s string) *obj.LSym {
7940 if aux, ok := e.strings[s]; ok {
7943 if e.strings == nil {
7944 e.strings = make(map[string]*obj.LSym)
7946 data := staticdata.StringSym(e.curfn.Pos(), s)
7951 // SplitSlot returns a slot representing the data of parent starting at offset.
7952 func (e *ssafn) SplitSlot(parent *ssa.LocalSlot, suffix string, offset int64, t *types.Type) ssa.LocalSlot {
7955 if node.Class != ir.PAUTO || node.Addrtaken() {
7956 // addressed things and non-autos retain their parents (i.e., cannot truly be split)
7957 return ssa.LocalSlot{N: node, Type: t, Off: parent.Off + offset}
7960 sym := &types.Sym{Name: node.Sym().Name + suffix, Pkg: types.LocalPkg}
7961 n := e.curfn.NewLocal(parent.N.Pos(), sym, t)
7963 n.SetEsc(ir.EscNever)
7965 return ssa.LocalSlot{N: n, Type: t, Off: 0, SplitOf: parent, SplitOffset: offset}
7968 // Logf logs a message from the compiler.
7969 func (e *ssafn) Logf(msg string, args ...interface{}) {
7971 fmt.Printf(msg, args...)
7975 func (e *ssafn) Log() bool {
7979 // Fatalf reports a compiler error and exits.
7980 func (e *ssafn) Fatalf(pos src.XPos, msg string, args ...interface{}) {
7982 nargs := append([]interface{}{ir.FuncName(e.curfn)}, args...)
7983 base.Fatalf("'%s': "+msg, nargs...)
7986 // Warnl reports a "warning", which is usually flag-triggered
7987 // logging output for the benefit of tests.
7988 func (e *ssafn) Warnl(pos src.XPos, fmt_ string, args ...interface{}) {
7989 base.WarnfAt(pos, fmt_, args...)
7992 func (e *ssafn) Debug_checknil() bool {
7993 return base.Debug.Nil != 0
7996 func (e *ssafn) UseWriteBarrier() bool {
8000 func (e *ssafn) Syslook(name string) *obj.LSym {
8002 case "goschedguarded":
8003 return ir.Syms.Goschedguarded
8004 case "writeBarrier":
8005 return ir.Syms.WriteBarrier
8007 return ir.Syms.WBZero
8009 return ir.Syms.WBMove
8010 case "cgoCheckMemmove":
8011 return ir.Syms.CgoCheckMemmove
8012 case "cgoCheckPtrWrite":
8013 return ir.Syms.CgoCheckPtrWrite
8015 e.Fatalf(src.NoXPos, "unknown Syslook func %v", name)
8019 func (e *ssafn) Func() *ir.Func {
8023 func clobberBase(n ir.Node) ir.Node {
8024 if n.Op() == ir.ODOT {
8025 n := n.(*ir.SelectorExpr)
8026 if n.X.Type().NumFields() == 1 {
8027 return clobberBase(n.X)
8030 if n.Op() == ir.OINDEX {
8031 n := n.(*ir.IndexExpr)
8032 if n.X.Type().IsArray() && n.X.Type().NumElem() == 1 {
8033 return clobberBase(n.X)
8039 // callTargetLSym returns the correct LSym to call 'callee' using its ABI.
8040 func callTargetLSym(callee *ir.Name) *obj.LSym {
8041 if callee.Func == nil {
8042 // TODO(austin): This happens in case of interface method I.M from imported package.
8043 // It's ABIInternal, and would be better if callee.Func was never nil and we didn't
8045 return callee.Linksym()
8048 return callee.LinksymABI(callee.Func.ABI)
8051 func min8(a, b int8) int8 {
8058 func max8(a, b int8) int8 {
8065 // deferStructFnField is the field index of _defer.fn.
8066 const deferStructFnField = 4
8068 var deferType *types.Type
8070 // deferstruct returns a type interchangeable with runtime._defer.
8071 // Make sure this stays in sync with runtime/runtime2.go:_defer.
8072 func deferstruct() *types.Type {
8073 if deferType != nil {
8077 makefield := func(name string, t *types.Type) *types.Field {
8078 sym := (*types.Pkg)(nil).Lookup(name)
8079 return types.NewField(src.NoXPos, sym, t)
8082 fields := []*types.Field{
8083 makefield("heap", types.Types[types.TBOOL]),
8084 makefield("rangefunc", types.Types[types.TBOOL]),
8085 makefield("sp", types.Types[types.TUINTPTR]),
8086 makefield("pc", types.Types[types.TUINTPTR]),
8087 // Note: the types here don't really matter. Defer structures
8088 // are always scanned explicitly during stack copying and GC,
8089 // so we make them uintptr type even though they are real pointers.
8090 makefield("fn", types.Types[types.TUINTPTR]),
8091 makefield("link", types.Types[types.TUINTPTR]),
8092 makefield("head", types.Types[types.TUINTPTR]),
8094 if name := fields[deferStructFnField].Sym.Name; name != "fn" {
8095 base.Fatalf("deferStructFnField is %q, not fn", name)
8098 n := ir.NewDeclNameAt(src.NoXPos, ir.OTYPE, ir.Pkgs.Runtime.Lookup("_defer"))
8099 typ := types.NewNamed(n)
8103 // build struct holding the above fields
8104 typ.SetUnderlying(types.NewStruct(fields))
8105 types.CalcStructSize(typ)
8111 // SpillSlotAddr uses LocalSlot information to initialize an obj.Addr
8112 // The resulting addr is used in a non-standard context -- in the prologue
8113 // of a function, before the frame has been constructed, so the standard
8114 // addressing for the parameters will be wrong.
8115 func SpillSlotAddr(spill ssa.Spill, baseReg int16, extraOffset int64) obj.Addr {
8117 Name: obj.NAME_NONE,
8120 Offset: spill.Offset + extraOffset,
8125 BoundsCheckFunc [ssa.BoundsKindCount]*obj.LSym
8126 ExtendCheckFunc [ssa.BoundsKindCount]*obj.LSym