Debian Codegraph @

go/ssa/builder.go

raw symbols SCIP
1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package ssa
6
7 // This file defines the builder, which builds SSA-form IR for function bodies.
8 //
9 // SSA construction has two phases, "create" and "build". First, one
10 // or more packages are created in any order by a sequence of calls to
11 // CreatePackage, either from syntax or from mere type information.
12 // Each created package has a complete set of Members (const, var,
13 // type, func) that can be accessed through methods like
14 // Program.FuncValue.
15 //
16 // It is not necessary to call CreatePackage for all dependencies of
17 // each syntax package, only for its direct imports. (In future
18 // perhaps even this restriction may be lifted.)
19 //
20 // Second, packages created from syntax are built, by one or more
21 // calls to Package.Build, which may be concurrent; or by a call to
22 // Program.Build, which builds all packages in parallel. Building
23 // traverses the type-annotated syntax tree of each function body and
24 // creates SSA-form IR, a control-flow graph of instructions,
25 // populating fields such as Function.Body, .Params, and others.
26 //
27 // Building may create additional methods, including:
28 // - wrapper methods (e.g. for embedding, or implicit &recv)
29 // - bound method closures (e.g. for use(recv.f))
30 // - thunks (e.g. for use(I.f) or use(T.f))
31 // - generic instances (e.g. to produce f[int] from f[any]).
32 // As these methods are created, they are added to the build queue,
33 // and then processed in turn, until a fixed point is reached,
34 // Since these methods might belong to packages that were not
35 // created (by a call to CreatePackage), their Pkg field is unset.
36 //
37 // Instances of generic functions may be either instantiated (f[int]
38 // is a copy of f[T] with substitutions) or wrapped (f[int] delegates
39 // to f[T]), depending on the availability of generic syntax and the
40 // InstantiateGenerics mode flag.
41 //
42 // Each package has an initializer function named "init" that calls
43 // the initializer functions of each direct import, computes and
44 // assigns the initial value of each global variable, and calls each
45 // source-level function named "init". (These generate SSA functions
46 // named "init#1", "init#2", etc.)
47 //
48 // Runtime types
49 //
50 // Each MakeInterface operation is a conversion from a non-interface
51 // type to an interface type. The semantics of this operation requires
52 // a runtime type descriptor, which is the type portion of an
53 // interface, and the value abstracted by reflect.Type.
54 //
55 // The program accumulates all non-parameterized types that are
56 // encountered as MakeInterface operands, along with all types that
57 // may be derived from them using reflection. This set is available as
58 // Program.RuntimeTypes, and the methods of these types may be
59 // reachable via interface calls or reflection even if they are never
60 // referenced from the SSA IR. (In practice, algorithms such as RTA
61 // that compute reachability from package main perform their own
62 // tracking of runtime types at a finer grain, so this feature is not
63 // very useful.)
64 //
65 // Function literals
66 //
67 // Anonymous functions must be built as soon as they are encountered,
68 // as it may affect locals of the enclosing function, but they are not
69 // marked 'built' until the end of the outermost enclosing function.
70 // (Among other things, this causes them to be logged in top-down order.)
71 //
72 // The Function.build fields determines the algorithm for building the
73 // function body. It is cleared to mark that building is complete.
74
75 import (
76 "fmt"
77 "go/ast"
78 "go/constant"
79 "go/token"
80 "go/types"
81 "os"
82 "runtime"
83 "sync"
84
85 "slices"
86
87 "golang.org/x/tools/internal/typeparams"
88 "golang.org/x/tools/internal/versions"
89 )
90
91 type opaqueType struct{ name string }
92
93 func (t *opaqueType) String() string { return t.name }
94 func (t *opaqueType) Underlying() types.Type { return t }
95
96 var (
97 varOk = newVar("ok", tBool)
98 varIndex = newVar("index", tInt)
99
100 // Type constants.
101 tBool = types.Typ[types.Bool]
102 tByte = types.Typ[types.Byte]
103 tRune = types.Universe.Lookup("rune").Type() // prints as "rune" (Typ[Rune] is same as Int32)
104 tInt = types.Typ[types.Int]
105 tInvalid = types.Typ[types.Invalid]
106 tString = types.Typ[types.String]
107 tUntypedNil = types.Typ[types.UntypedNil]
108
109 tRangeIter = &opaqueType{"iter"} // the type of all "range" iterators
110 tDeferStack = types.NewPointer(&opaqueType{"deferStack"}) // the type of a "deferStack" from ssa:deferstack()
111 tEface = types.NewInterfaceType(nil, nil).Complete()
112
113 // SSA Value constants.
114 vZero = intConst(0)
115 vOne = intConst(1)
116 vTrue = NewConst(constant.MakeBool(true), tBool)
117 vFalse = NewConst(constant.MakeBool(false), tBool)
118 vNoReturn = NewConst(constant.MakeString("noreturn"), tString)
119
120 jReady = intConst(0) // range-over-func jump is READY
121 jBusy = intConst(-1) // range-over-func jump is BUSY
122 jDone = intConst(-2) // range-over-func jump is DONE
123
124 // The ssa:deferstack intrinsic returns the current function's defer stack.
125 vDeferStack = &Builtin{
126 name: "ssa:deferstack",
127 sig: types.NewSignatureType(nil, nil, nil, nil, types.NewTuple(anonVar(tDeferStack)), false),
128 }
129 )
130
131 // builder holds state associated with the package currently being built.
132 // Its methods contain all the logic for AST-to-SSA conversion.
133 //
134 // All Functions belong to the same Program.
135 //
136 // builders are not thread-safe.
137 type builder struct {
138 fns []*Function // Functions that have finished their CREATE phases.
139
140 finished int // finished is the length of the prefix of fns containing built functions.
141
142 // The task of building shared functions within the builder.
143 // Shared functions are ones the builder may either create or lookup.
144 // These may be built by other builders in parallel.
145 // The task is done when the builder has finished iterating, and it
146 // waits for all shared functions to finish building.
147 // nil implies there are no hared functions to wait on.
148 buildshared *task
149 }
150
151 // shared is done when the builder has built all of the
152 // enqueued functions to a fixed-point.
153 func (b *builder) shared() *task {
154 if b.buildshared == nil { // lazily-initialize
155 b.buildshared = &task{done: make(chan unit)}
156 }
157 return b.buildshared
158 }
159
160 // enqueue fn to be built by the builder.
161 func (b *builder) enqueue(fn *Function) {
162 b.fns = append(b.fns, fn)
163 }
164
165 // waitForSharedFunction indicates that the builder should wait until
166 // the potentially shared function fn has finished building.
167 //
168 // This should include any functions that may be built by other
169 // builders.
170 func (b *builder) waitForSharedFunction(fn *Function) {
171 if fn.buildshared != nil { // maybe need to wait?
172 s := b.shared()
173 s.addEdge(fn.buildshared)
174 }
175 }
176
177 // cond emits to fn code to evaluate boolean condition e and jump
178 // to t or f depending on its value, performing various simplifications.
179 //
180 // Postcondition: fn.currentBlock is nil.
181 func (b *builder) cond(fn *Function, e ast.Expr, t, f *BasicBlock) {
182 switch e := e.(type) {
183 case *ast.ParenExpr:
184 b.cond(fn, e.X, t, f)
185 return
186
187 case *ast.BinaryExpr:
188 switch e.Op {
189 case token.LAND:
190 ltrue := fn.newBasicBlock("cond.true")
191 b.cond(fn, e.X, ltrue, f)
192 fn.currentBlock = ltrue
193 b.cond(fn, e.Y, t, f)
194 return
195
196 case token.LOR:
197 lfalse := fn.newBasicBlock("cond.false")
198 b.cond(fn, e.X, t, lfalse)
199 fn.currentBlock = lfalse
200 b.cond(fn, e.Y, t, f)
201 return
202 }
203
204 case *ast.UnaryExpr:
205 if e.Op == token.NOT {
206 b.cond(fn, e.X, f, t)
207 return
208 }
209 }
210
211 // A traditional compiler would simplify "if false" (etc) here
212 // but we do not, for better fidelity to the source code.
213 //
214 // The value of a constant condition may be platform-specific,
215 // and may cause blocks that are reachable in some configuration
216 // to be hidden from subsequent analyses such as bug-finding tools.
217 emitIf(fn, b.expr(fn, e), t, f)
218 }
219
220 // logicalBinop emits code to fn to evaluate e, a &&- or
221 // ||-expression whose reified boolean value is wanted.
222 // The value is returned.
223 func (b *builder) logicalBinop(fn *Function, e *ast.BinaryExpr) Value {
224 rhs := fn.newBasicBlock("binop.rhs")
225 done := fn.newBasicBlock("binop.done")
226
227 // T(e) = T(e.X) = T(e.Y) after untyped constants have been
228 // eliminated.
229 // TODO(adonovan): not true; MyBool==MyBool yields UntypedBool.
230 t := fn.typeOf(e)
231
232 var short Value // value of the short-circuit path
233 switch e.Op {
234 case token.LAND:
235 b.cond(fn, e.X, rhs, done)
236 short = NewConst(constant.MakeBool(false), t)
237
238 case token.LOR:
239 b.cond(fn, e.X, done, rhs)
240 short = NewConst(constant.MakeBool(true), t)
241 }
242
243 // Is rhs unreachable?
244 if rhs.Preds == nil {
245 // Simplify false&&y to false, true||y to true.
246 fn.currentBlock = done
247 return short
248 }
249
250 // Is done unreachable?
251 if done.Preds == nil {
252 // Simplify true&&y (or false||y) to y.
253 fn.currentBlock = rhs
254 return b.expr(fn, e.Y)
255 }
256
257 // All edges from e.X to done carry the short-circuit value.
258 var edges []Value
259 for range done.Preds {
260 edges = append(edges, short)
261 }
262
263 // The edge from e.Y to done carries the value of e.Y.
264 fn.currentBlock = rhs
265 edges = append(edges, b.expr(fn, e.Y))
266 emitJump(fn, done)
267 fn.currentBlock = done
268
269 phi := &Phi{Edges: edges, Comment: e.Op.String()}
270 phi.pos = e.OpPos
271 phi.typ = t
272 return done.emit(phi)
273 }
274
275 // exprN lowers a multi-result expression e to SSA form, emitting code
276 // to fn and returning a single Value whose type is a *types.Tuple.
277 // The caller must access the components via Extract.
278 //
279 // Multi-result expressions include CallExprs in a multi-value
280 // assignment or return statement, and "value,ok" uses of
281 // TypeAssertExpr, IndexExpr (when X is a map), and UnaryExpr (when Op
282 // is token.ARROW).
283 func (b *builder) exprN(fn *Function, e ast.Expr) Value {
284 typ := fn.typeOf(e).(*types.Tuple)
285 switch e := e.(type) {
286 case *ast.ParenExpr:
287 return b.exprN(fn, e.X)
288
289 case *ast.CallExpr:
290 // Currently, no built-in function nor type conversion
291 // has multiple results, so we can avoid some of the
292 // cases for single-valued CallExpr.
293 var c Call
294 b.setCall(fn, e, &c.Call)
295 c.typ = typ
296 return emitCall(fn, &c)
297
298 case *ast.IndexExpr:
299 mapt := typeparams.CoreType(fn.typeOf(e.X)).(*types.Map) // ,ok must be a map.
300 lookup := &Lookup{
301 X: b.expr(fn, e.X),
302 Index: emitConv(fn, b.expr(fn, e.Index), mapt.Key()),
303 CommaOk: true,
304 }
305 lookup.setType(typ)
306 lookup.setPos(e.Lbrack)
307 return fn.emit(lookup)
308
309 case *ast.TypeAssertExpr:
310 return emitTypeTest(fn, b.expr(fn, e.X), typ.At(0).Type(), e.Lparen)
311
312 case *ast.UnaryExpr: // must be receive <-
313 unop := &UnOp{
314 Op: token.ARROW,
315 X: b.expr(fn, e.X),
316 CommaOk: true,
317 }
318 unop.setType(typ)
319 unop.setPos(e.OpPos)
320 return fn.emit(unop)
321 }
322 panic(fmt.Sprintf("exprN(%T) in %s", e, fn))
323 }
324
325 // builtin emits to fn SSA instructions to implement a call to the
326 // built-in function obj with the specified arguments
327 // and return type. It returns the value defined by the result.
328 //
329 // The result is nil if no special handling was required; in this case
330 // the caller should treat this like an ordinary library function
331 // call.
332 func (b *builder) builtin(fn *Function, obj *types.Builtin, args []ast.Expr, typ types.Type, pos token.Pos) Value {
333 typ = fn.typ(typ)
334 switch obj.Name() {
335 case "make":
336 switch ct := typeparams.CoreType(typ).(type) {
337 case *types.Slice:
338 n := b.expr(fn, args[1])
339 m := n
340 if len(args) == 3 {
341 m = b.expr(fn, args[2])
342 }
343 if m, ok := m.(*Const); ok {
344 // treat make([]T, n, m) as new([m]T)[:n]
345 cap := m.Int64()
346 at := types.NewArray(ct.Elem(), cap)
347 v := &Slice{
348 X: emitNew(fn, at, pos, "makeslice"),
349 High: n,
350 }
351 v.setPos(pos)
352 v.setType(typ)
353 return fn.emit(v)
354 }
355 v := &MakeSlice{
356 Len: n,
357 Cap: m,
358 }
359 v.setPos(pos)
360 v.setType(typ)
361 return fn.emit(v)
362
363 case *types.Map:
364 var res Value
365 if len(args) == 2 {
366 res = b.expr(fn, args[1])
367 }
368 v := &MakeMap{Reserve: res}
369 v.setPos(pos)
370 v.setType(typ)
371 return fn.emit(v)
372
373 case *types.Chan:
374 var sz Value = vZero
375 if len(args) == 2 {
376 sz = b.expr(fn, args[1])
377 }
378 v := &MakeChan{Size: sz}
379 v.setPos(pos)
380 v.setType(typ)
381 return fn.emit(v)
382 }
383
384 case "new":
385 alloc := emitNew(fn, typeparams.MustDeref(typ), pos, "new")
386 if !fn.info.Types[args[0]].IsType() {
387 // new(expr), requires go1.26
388 v := b.expr(fn, args[0])
389 emitStore(fn, alloc, v, pos)
390 }
391 return alloc
392
393 case "len", "cap":
394 // Special case: len or cap of an array or *array is
395 // based on the type, not the value which may be nil.
396 // We must still evaluate the value, though. (If it
397 // was side-effect free, the whole call would have
398 // been constant-folded.)
399 t := typeparams.Deref(fn.typeOf(args[0]))
400 if at, ok := typeparams.CoreType(t).(*types.Array); ok {
401 b.expr(fn, args[0]) // for effects only
402 return intConst(at.Len())
403 }
404 // Otherwise treat as normal.
405
406 case "panic":
407 fn.emit(&Panic{
408 X: emitConv(fn, b.expr(fn, args[0]), tEface),
409 pos: pos,
410 })
411 fn.currentBlock = fn.newBasicBlock("unreachable")
412 return vTrue // any non-nil Value will do
413 }
414 return nil // treat all others as a regular function call
415 }
416
417 // addr lowers a single-result addressable expression e to SSA form,
418 // emitting code to fn and returning the location (an lvalue) defined
419 // by the expression.
420 //
421 // If escaping is true, addr marks the base variable of the
422 // addressable expression e as being a potentially escaping pointer
423 // value. For example, in this code:
424 //
425 // a := A{
426 // b: [1]B{B{c: 1}}
427 // }
428 // return &a.b[0].c
429 //
430 // the application of & causes a.b[0].c to have its address taken,
431 // which means that ultimately the local variable a must be
432 // heap-allocated. This is a simple but very conservative escape
433 // analysis.
434 //
435 // Operations forming potentially escaping pointers include:
436 // - &x, including when implicit in method call or composite literals.
437 // - a[:] iff a is an array (not *array)
438 // - references to variables in lexically enclosing functions.
439 func (b *builder) addr(fn *Function, e ast.Expr, escaping bool) lvalue {
440 switch e := e.(type) {
441 case *ast.Ident:
442 if isBlankIdent(e) {
443 return blank{}
444 }
445 obj := fn.objectOf(e).(*types.Var)
446 var v Value
447 if g := fn.Prog.packageLevelMember(obj); g != nil {
448 v = g.(*Global) // var (address)
449 } else {
450 v = fn.lookup(obj, escaping)
451 }
452 return &address{addr: v, pos: e.Pos(), expr: e}
453
454 case *ast.CompositeLit:
455 typ := typeparams.Deref(fn.typeOf(e))
456 var v *Alloc
457 if escaping {
458 v = emitNew(fn, typ, e.Lbrace, "complit")
459 } else {
460 v = emitLocal(fn, typ, e.Lbrace, "complit")
461 }
462 var sb storebuf
463 b.compLit(fn, v, e, true, &sb)
464 sb.emit(fn)
465 return &address{addr: v, pos: e.Lbrace, expr: e}
466
467 case *ast.ParenExpr:
468 return b.addr(fn, e.X, escaping)
469
470 case *ast.SelectorExpr:
471 sel := fn.selection(e)
472 if sel == nil {
473 // qualified identifier
474 return b.addr(fn, e.Sel, escaping)
475 }
476 if sel.kind != types.FieldVal {
477 panic(sel)
478 }
479 wantAddr := true
480 v := b.receiver(fn, e.X, wantAddr, escaping, sel)
481 index := sel.index[len(sel.index)-1]
482 fld := fieldOf(typeparams.MustDeref(v.Type()), index) // v is an addr.
483
484 // Due to the two phases of resolving AssignStmt, a panic from x.f = p()
485 // when x is nil is required to come after the side-effects of
486 // evaluating x and p().
487 emit := func(fn *Function) Value {
488 return emitFieldSelection(fn, v, index, true, e.Sel)
489 }
490 return &lazyAddress{addr: emit, t: fld.Type(), pos: e.Sel.Pos(), expr: e.Sel}
491
492 case *ast.IndexExpr:
493 xt := fn.typeOf(e.X)
494 elem, mode := indexType(xt)
495 var x Value
496 var et types.Type
497 switch mode {
498 case ixArrVar: // array, array|slice, array|*array, or array|*array|slice.
499 x = b.addr(fn, e.X, escaping).address(fn)
500 et = types.NewPointer(elem)
501 case ixVar: // *array, slice, *array|slice
502 x = b.expr(fn, e.X)
503 et = types.NewPointer(elem)
504 case ixMap:
505 mt := typeparams.CoreType(xt).(*types.Map)
506 return &element{
507 m: b.expr(fn, e.X),
508 k: emitConv(fn, b.expr(fn, e.Index), mt.Key()),
509 t: mt.Elem(),
510 pos: e.Lbrack,
511 }
512 default:
513 panic("unexpected container type in IndexExpr: " + xt.String())
514 }
515 index := b.expr(fn, e.Index)
516 if isUntyped(index.Type()) {
517 index = emitConv(fn, index, tInt)
518 }
519 // Due to the two phases of resolving AssignStmt, a panic from x[i] = p()
520 // when x is nil or i is out-of-bounds is required to come after the
521 // side-effects of evaluating x, i and p().
522 emit := func(fn *Function) Value {
523 v := &IndexAddr{
524 X: x,
525 Index: index,
526 }
527 v.setPos(e.Lbrack)
528 v.setType(et)
529 return fn.emit(v)
530 }
531 return &lazyAddress{addr: emit, t: typeparams.MustDeref(et), pos: e.Lbrack, expr: e}
532
533 case *ast.StarExpr:
534 return &address{addr: b.expr(fn, e.X), pos: e.Star, expr: e}
535 }
536
537 panic(fmt.Sprintf("unexpected address expression: %T", e))
538 }
539
540 type store struct {
541 lhs lvalue
542 rhs Value
543 }
544
545 type storebuf struct{ stores []store }
546
547 func (sb *storebuf) store(lhs lvalue, rhs Value) {
548 sb.stores = append(sb.stores, store{lhs, rhs})
549 }
550
551 func (sb *storebuf) emit(fn *Function) {
552 for _, s := range sb.stores {
553 s.lhs.store(fn, s.rhs)
554 }
555 }
556
557 // assign emits to fn code to initialize the lvalue loc with the value
558 // of expression e. If isZero is true, assign assumes that loc holds
559 // the zero value for its type.
560 //
561 // This is equivalent to loc.store(fn, b.expr(fn, e)), but may generate
562 // better code in some cases, e.g., for composite literals in an
563 // addressable location.
564 //
565 // If sb is not nil, assign generates code to evaluate expression e, but
566 // not to update loc. Instead, the necessary stores are appended to the
567 // storebuf sb so that they can be executed later. This allows correct
568 // in-place update of existing variables when the RHS is a composite
569 // literal that may reference parts of the LHS.
570 func (b *builder) assign(fn *Function, loc lvalue, e ast.Expr, isZero bool, sb *storebuf) {
571 // Can we initialize it in place?
572 if e, ok := ast.Unparen(e).(*ast.CompositeLit); ok {
573 // A CompositeLit never evaluates to a pointer,
574 // so if the type of the location is a pointer,
575 // an &-operation is implied.
576 if !is[blank](loc) && isPointerCore(loc.typ()) { // avoid calling blank.typ()
577 ptr := b.addr(fn, e, true).address(fn)
578 // copy address
579 if sb != nil {
580 sb.store(loc, ptr)
581 } else {
582 loc.store(fn, ptr)
583 }
584 return
585 }
586
587 if _, ok := loc.(*address); ok {
588 if isNonTypeParamInterface(loc.typ()) {
589 // e.g. var x interface{} = T{...}
590 // Can't in-place initialize an interface value.
591 // Fall back to copying.
592 } else {
593 // x = T{...} or x := T{...}
594 addr := loc.address(fn)
595 if sb != nil {
596 b.compLit(fn, addr, e, isZero, sb)
597 } else {
598 var sb storebuf
599 b.compLit(fn, addr, e, isZero, &sb)
600 sb.emit(fn)
601 }
602
603 // Subtle: emit debug ref for aggregate types only;
604 // slice and map are handled by store ops in compLit.
605 switch typeparams.CoreType(loc.typ()).(type) {
606 case *types.Struct, *types.Array:
607 emitDebugRef(fn, e, addr, true)
608 }
609
610 return
611 }
612 }
613 }
614
615 // simple case: just copy
616 rhs := b.expr(fn, e)
617 if sb != nil {
618 sb.store(loc, rhs)
619 } else {
620 loc.store(fn, rhs)
621 }
622 }
623
624 // expr lowers a single-result expression e to SSA form, emitting code
625 // to fn and returning the Value defined by the expression.
626 func (b *builder) expr(fn *Function, e ast.Expr) Value {
627 e = ast.Unparen(e)
628
629 tv := fn.info.Types[e]
630
631 // Is expression a constant?
632 if tv.Value != nil {
633 return NewConst(tv.Value, fn.typ(tv.Type))
634 }
635
636 var v Value
637 if tv.Addressable() {
638 // Prefer pointer arithmetic ({Index,Field}Addr) followed
639 // by Load over subelement extraction (e.g. Index, Field),
640 // to avoid large copies.
641 v = b.addr(fn, e, false).load(fn)
642 } else {
643 v = b.expr0(fn, e, tv)
644 }
645 if fn.debugInfo() {
646 emitDebugRef(fn, e, v, false)
647 }
648 return v
649 }
650
651 func (b *builder) expr0(fn *Function, e ast.Expr, tv types.TypeAndValue) Value {
652 switch e := e.(type) {
653 case *ast.BasicLit:
654 panic("non-constant BasicLit") // unreachable
655
656 case *ast.FuncLit:
657 /* function literal */
658 anon := &Function{
659 name: fmt.Sprintf("%s$%d", fn.Name(), 1+len(fn.AnonFuncs)),
660 Signature: fn.typeOf(e.Type).(*types.Signature),
661 pos: e.Type.Func,
662 parent: fn,
663 anonIdx: int32(len(fn.AnonFuncs)),
664 Pkg: fn.Pkg,
665 Prog: fn.Prog,
666 syntax: e,
667 info: fn.info,
668 goversion: fn.goversion,
669 build: (*builder).buildFromSyntax,
670 topLevelOrigin: nil, // use anonIdx to lookup an anon instance's origin.
671 typeparams: fn.typeparams, // share the parent's type parameters.
672 typeargs: fn.typeargs, // share the parent's type arguments.
673 subst: fn.subst, // share the parent's type substitutions.
674 uniq: fn.uniq, // start from parent's unique values
675 }
676 fn.AnonFuncs = append(fn.AnonFuncs, anon)
677 // Build anon immediately, as it may cause fn's locals to escape.
678 // (It is not marked 'built' until the end of the enclosing FuncDecl.)
679 anon.build(b, anon)
680 fn.uniq = anon.uniq // resume after anon's unique values
681 if anon.FreeVars == nil {
682 return anon
683 }
684 v := &MakeClosure{Fn: anon}
685 v.setType(fn.typ(tv.Type))
686 for _, fv := range anon.FreeVars {
687 v.Bindings = append(v.Bindings, fv.outer)
688 fv.outer = nil
689 }
690 return fn.emit(v)
691
692 case *ast.TypeAssertExpr: // single-result form only
693 return emitTypeAssert(fn, b.expr(fn, e.X), fn.typ(tv.Type), e.Lparen)
694
695 case *ast.CallExpr:
696 if fn.info.Types[e.Fun].IsType() {
697 // Explicit type conversion, e.g. string(x) or big.Int(x)
698 x := b.expr(fn, e.Args[0])
699 y := emitConv(fn, x, fn.typ(tv.Type))
700 if y != x {
701 switch y := y.(type) {
702 case *Convert:
703 y.pos = e.Lparen
704 case *ChangeType:
705 y.pos = e.Lparen
706 case *MakeInterface:
707 y.pos = e.Lparen
708 case *SliceToArrayPointer:
709 y.pos = e.Lparen
710 case *UnOp: // conversion from slice to array.
711 y.pos = e.Lparen
712 }
713 }
714 return y
715 }
716 // Call to "intrinsic" built-ins, e.g. new, make, panic.
717 if id, ok := ast.Unparen(e.Fun).(*ast.Ident); ok {
718 if obj, ok := fn.info.Uses[id].(*types.Builtin); ok {
719 if v := b.builtin(fn, obj, e.Args, fn.typ(tv.Type), e.Lparen); v != nil {
720 return v
721 }
722 }
723 }
724 // Regular function call.
725 var v Call
726 b.setCall(fn, e, &v.Call)
727 v.setType(fn.typ(tv.Type))
728 return emitCall(fn, &v)
729
730 case *ast.UnaryExpr:
731 switch e.Op {
732 case token.AND: // &X --- potentially escaping.
733 addr := b.addr(fn, e.X, true)
734 if _, ok := ast.Unparen(e.X).(*ast.StarExpr); ok {
735 // &*p must panic if p is nil (http://golang.org/s/go12nil).
736 // For simplicity, we'll just (suboptimally) rely
737 // on the side effects of a load.
738 // TODO(adonovan): emit dedicated nilcheck.
739 addr.load(fn)
740 }
741 return addr.address(fn)
742 case token.ADD:
743 return b.expr(fn, e.X)
744 case token.NOT, token.ARROW, token.SUB, token.XOR: // ! <- - ^
745 v := &UnOp{
746 Op: e.Op,
747 X: b.expr(fn, e.X),
748 }
749 v.setPos(e.OpPos)
750 v.setType(fn.typ(tv.Type))
751 return fn.emit(v)
752 default:
753 panic(e.Op)
754 }
755
756 case *ast.BinaryExpr:
757 switch e.Op {
758 case token.LAND, token.LOR:
759 return b.logicalBinop(fn, e)
760 case token.SHL, token.SHR:
761 fallthrough
762 case token.ADD, token.SUB, token.MUL, token.QUO, token.REM, token.AND, token.OR, token.XOR, token.AND_NOT:
763 return emitArith(fn, e.Op, b.expr(fn, e.X), b.expr(fn, e.Y), fn.typ(tv.Type), e.OpPos)
764
765 case token.EQL, token.NEQ, token.GTR, token.LSS, token.LEQ, token.GEQ:
766 cmp := emitCompare(fn, e.Op, b.expr(fn, e.X), b.expr(fn, e.Y), e.OpPos)
767 // The type of x==y may be UntypedBool.
768 return emitConv(fn, cmp, types.Default(fn.typ(tv.Type)))
769 default:
770 panic("illegal op in BinaryExpr: " + e.Op.String())
771 }
772
773 case *ast.SliceExpr:
774 var low, high, max Value
775 var x Value
776 xtyp := fn.typeOf(e.X)
777 switch typeparams.CoreType(xtyp).(type) {
778 case *types.Array:
779 // Potentially escaping.
780 x = b.addr(fn, e.X, true).address(fn)
781 case *types.Basic, *types.Slice, *types.Pointer: // *array
782 x = b.expr(fn, e.X)
783 default:
784 // core type exception?
785 if isBytestring(xtyp) {
786 x = b.expr(fn, e.X) // bytestring is handled as string and []byte.
787 } else {
788 panic("unexpected sequence type in SliceExpr")
789 }
790 }
791 if e.Low != nil {
792 low = b.expr(fn, e.Low)
793 }
794 if e.High != nil {
795 high = b.expr(fn, e.High)
796 }
797 if e.Slice3 {
798 max = b.expr(fn, e.Max)
799 }
800 v := &Slice{
801 X: x,
802 Low: low,
803 High: high,
804 Max: max,
805 }
806 v.setPos(e.Lbrack)
807 v.setType(fn.typ(tv.Type))
808 return fn.emit(v)
809
810 case *ast.Ident:
811 obj := fn.info.Uses[e]
812 // Universal built-in or nil?
813 switch obj := obj.(type) {
814 case *types.Builtin:
815 return &Builtin{name: obj.Name(), sig: fn.instanceType(e).(*types.Signature)}
816 case *types.Nil:
817 return zeroConst(fn.instanceType(e))
818 }
819
820 // Package-level func or var?
821 // (obj must belong to same package or a direct import.)
822 if v := fn.Prog.packageLevelMember(obj); v != nil {
823 if g, ok := v.(*Global); ok {
824 return emitLoad(fn, g) // var (address)
825 }
826 callee := v.(*Function) // (func)
827 if callee.typeparams.Len() > 0 {
828 targs := fn.subtargs(e)
829 callee = callee.instance(nil, targs, b)
830 }
831 return callee
832 }
833 // Local var.
834 return emitLoad(fn, fn.lookup(obj.(*types.Var), false)) // var (address)
835
836 case *ast.SelectorExpr:
837 sel := fn.selection(e)
838 if sel == nil {
839 // builtin unsafe.{Add,Slice}
840 if obj, ok := fn.info.Uses[e.Sel].(*types.Builtin); ok {
841 return &Builtin{name: obj.Name(), sig: fn.typ(tv.Type).(*types.Signature)}
842 }
843 // qualified identifier
844 return b.expr(fn, e.Sel)
845 }
846 switch sel.kind {
847 case types.MethodExpr:
848 // (*T).f or T.f, the method f from the method-set of type T.
849 // The result is a "thunk".
850 targs := fn.subtargs(e.Sel)
851 thunk := createThunk(fn.Prog, sel, targs)
852 b.enqueue(thunk)
853 return thunk
854
855 case types.MethodVal:
856 // e.f where e is an expression and f is a method.
857 // The result is a "bound".
858 m := sel.obj.(*types.Func)
859 rt := fn.typ(recvType(m))
860 wantAddr := isPointer(rt)
861 escaping := true
862 v := b.receiver(fn, e.X, wantAddr, escaping, sel)
863
864 if types.IsInterface(rt) {
865 // If v may be an interface type I (after instantiating),
866 // we must emit a check that v is non-nil.
867 if recv, ok := types.Unalias(sel.recv).(*types.TypeParam); ok {
868 // Emit a nil check if any possible instantiation of the
869 // type parameter is an interface type.
870 if !typeSetIsEmpty(recv) {
871 // recv has a concrete term its typeset.
872 // So it cannot be instantiated as an interface.
873 //
874 // Example:
875 // func _[T interface{~int; Foo()}] () {
876 // var v T
877 // _ = v.Foo // <-- MethodVal
878 // }
879 } else {
880 // rt may be instantiated as an interface.
881 // Emit nil check: typeassert (any(v)).(any).
882 emitTypeAssert(fn, emitConv(fn, v, tEface), tEface, token.NoPos)
883 }
884 } else {
885 // non-type param interface
886 // Emit nil check: typeassert v.(I).
887 emitTypeAssert(fn, v, rt, e.Sel.Pos())
888 }
889 }
890
891 if rtargs := fn.subrtargs(m); len(rtargs) > 0 {
892 m = fn.Prog.canon.instantiateMethod(m, rtargs, fn.Prog.ctxt)
893 }
894
895 targs := fn.subtargs(e.Sel)
896 bound := createBound(fn.Prog, m, targs)
897 b.enqueue(bound)
898
899 // The assignment may widen a type parameter to its
900 // interface bound (case #3 of go.dev/issue.78110).
901 v = emitConv(fn, v, bound.FreeVars[0].Type())
902
903 c := &MakeClosure{
904 Fn: bound,
905 Bindings: []Value{v},
906 }
907 c.setPos(e.Sel.Pos())
908 c.setType(bound.Signature)
909 return fn.emit(c)
910
911 case types.FieldVal:
912 indices := sel.index
913 last := len(indices) - 1
914 v := b.expr(fn, e.X)
915 v = emitImplicitSelections(fn, v, indices[:last], e.Pos())
916 v = emitFieldSelection(fn, v, indices[last], false, e.Sel)
917 return v
918 }
919
920 panic("unexpected expression-relative selector")
921
922 case *ast.IndexListExpr:
923 // f[X, Y] must be a generic function
924 if !instance(fn.info, e.X) {
925 panic("unexpected expression-could not match index list to instantiation")
926 }
927 return b.expr(fn, e.X) // Handle instantiation within the *Ident or *SelectorExpr cases.
928
929 case *ast.IndexExpr:
930 if instance(fn.info, e.X) {
931 return b.expr(fn, e.X) // Handle instantiation within the *Ident or *SelectorExpr cases.
932 }
933 // not a generic instantiation.
934 xt := fn.typeOf(e.X)
935 switch et, mode := indexType(xt); mode {
936 case ixVar:
937 // Addressable slice/array; use IndexAddr and Load.
938 return b.addr(fn, e, false).load(fn)
939
940 case ixArrVar, ixValue:
941 // An array in a register, a string or a combined type that contains
942 // either an [_]array (ixArrVar) or string (ixValue).
943
944 // Note: for ixArrVar and CoreType(xt)==nil can be IndexAddr and Load.
945 index := b.expr(fn, e.Index)
946 if isUntyped(index.Type()) {
947 index = emitConv(fn, index, tInt)
948 }
949 v := &Index{
950 X: b.expr(fn, e.X),
951 Index: index,
952 }
953 v.setPos(e.Lbrack)
954 v.setType(et)
955 return fn.emit(v)
956
957 case ixMap:
958 ct := typeparams.CoreType(xt).(*types.Map)
959 v := &Lookup{
960 X: b.expr(fn, e.X),
961 Index: emitConv(fn, b.expr(fn, e.Index), ct.Key()),
962 }
963 v.setPos(e.Lbrack)
964 v.setType(ct.Elem())
965 return fn.emit(v)
966 default:
967 panic("unexpected container type in IndexExpr: " + xt.String())
968 }
969
970 case *ast.CompositeLit, *ast.StarExpr:
971 // Addressable types (lvalues)
972 return b.addr(fn, e, false).load(fn)
973 }
974
975 panic(fmt.Sprintf("unexpected expr: %T", e))
976 }
977
978 // stmtList emits to fn code for all statements in list.
979 func (b *builder) stmtList(fn *Function, list []ast.Stmt) {
980 for _, s := range list {
981 b.stmt(fn, s)
982 }
983 }
984
985 // receiver emits to fn code for expression e in the "receiver"
986 // position of selection e.f (where f may be a field or a method) and
987 // returns the effective receiver after applying the implicit field
988 // selections of sel.
989 //
990 // wantAddr requests that the result is an address. If
991 // !sel.indirect, this may require that e be built in addr() mode; it
992 // must thus be addressable.
993 //
994 // escaping is defined as per builder.addr().
995 func (b *builder) receiver(fn *Function, e ast.Expr, wantAddr, escaping bool, sel *selection) Value {
996 var v Value
997 if wantAddr && !sel.indirect && !isPointerCore(fn.typeOf(e)) {
998 v = b.addr(fn, e, escaping).address(fn)
999 } else {
1000 v = b.expr(fn, e)
1001 }
1002
1003 last := len(sel.index) - 1
1004 // The position of implicit selection is the position of the inducing receiver expression.
1005 v = emitImplicitSelections(fn, v, sel.index[:last], e.Pos())
1006 if types.IsInterface(v.Type()) {
1007 // When v is an interface, sel.Kind()==MethodValue and v.f is invoked.
1008 // So v is not loaded, even if v has a pointer core type.
1009 } else if !wantAddr && isPointerCore(v.Type()) {
1010 v = emitLoad(fn, v)
1011 }
1012 return v
1013 }
1014
1015 // setCallFunc populates the function parts of a CallCommon structure
1016 // (Func, Method, Recv, Args[0]) based on the kind of invocation
1017 // occurring in e.
1018 func (b *builder) setCallFunc(fn *Function, e *ast.CallExpr, c *CallCommon) {
1019 c.pos = e.Lparen
1020
1021 // Is this a (possibly generic) method call?
1022 m := ast.Unparen(e.Fun)
1023 switch e := m.(type) {
1024 case *ast.IndexExpr:
1025 m = e.X
1026 case *ast.IndexListExpr:
1027 m = e.X
1028 }
1029 if selector, ok := m.(*ast.SelectorExpr); ok {
1030 sel := fn.selection(selector)
1031 if sel != nil && sel.kind == types.MethodVal {
1032 obj := sel.obj.(*types.Func)
1033 recv := recvType(obj)
1034
1035 wantAddr := isPointer(recv)
1036 escaping := true
1037 v := b.receiver(fn, selector.X, wantAddr, escaping, sel)
1038 if types.IsInterface(recv) {
1039 // Invoke-mode call.
1040 c.Value = v // possibly type param
1041 c.Method = obj
1042 } else {
1043 // "Call"-mode call.
1044 targs := fn.subtargs(selector.Sel)
1045 c.Value = fn.Prog.objectMethod(obj, targs, b)
1046 c.Args = append(c.Args, v)
1047 }
1048 return
1049 }
1050
1051 // sel.kind==MethodExpr indicates T.f() or (*T).f():
1052 // a statically dispatched call to the method f in the
1053 // method-set of T or *T. T may be an interface.
1054 //
1055 // e.Fun would evaluate to a concrete method, interface
1056 // wrapper function, or promotion wrapper.
1057 //
1058 // For now, we evaluate it in the usual way.
1059 //
1060 // TODO(adonovan): opt: inline expr() here, to make the
1061 // call static and to avoid generation of wrappers.
1062 // It's somewhat tricky as it may consume the first
1063 // actual parameter if the call is "invoke" mode.
1064 //
1065 // Examples:
1066 // type T struct{}; func (T) f() {} // "call" mode
1067 // type T interface { f() } // "invoke" mode
1068 //
1069 // type S struct{ T }
1070 //
1071 // var s S
1072 // S.f(s)
1073 // (*S).f(&s)
1074 //
1075 // Suggested approach:
1076 // - consume the first actual parameter expression
1077 // and build it with b.expr().
1078 // - apply implicit field selections.
1079 // - use MethodVal logic to populate fields of c.
1080 }
1081
1082 // Evaluate the function operand in the usual way.
1083 c.Value = b.expr(fn, e.Fun)
1084 }
1085
1086 // emitCallArgs emits to f code for the actual parameters of call e to
1087 // a (possibly built-in) function of effective type sig.
1088 // The argument values are appended to args, which is then returned.
1089 func (b *builder) emitCallArgs(fn *Function, sig *types.Signature, e *ast.CallExpr, args []Value) []Value {
1090 // f(x, y, z...): pass slice z straight through.
1091 if e.Ellipsis != 0 {
1092 for i, arg := range e.Args {
1093 v := emitConv(fn, b.expr(fn, arg), sig.Params().At(i).Type())
1094 args = append(args, v)
1095 }
1096 return args
1097 }
1098
1099 offset := len(args) // 1 if call has receiver, 0 otherwise
1100
1101 // Evaluate actual parameter expressions.
1102 //
1103 // If this is a chained call of the form f(g()) where g has
1104 // multiple return values (MRV), they are flattened out into
1105 // args; a suffix of them may end up in a varargs slice.
1106 for _, arg := range e.Args {
1107 v := b.expr(fn, arg)
1108 if ttuple, ok := v.Type().(*types.Tuple); ok { // MRV chain
1109 for i, n := 0, ttuple.Len(); i < n; i++ {
1110 args = append(args, emitExtract(fn, v, i))
1111 }
1112 } else {
1113 args = append(args, v)
1114 }
1115 }
1116
1117 // Actual->formal assignability conversions for normal parameters.
1118 np := sig.Params().Len() // number of normal parameters
1119 if sig.Variadic() {
1120 np--
1121 }
1122 for i := 0; i < np; i++ {
1123 args[offset+i] = emitConv(fn, args[offset+i], sig.Params().At(i).Type())
1124 }
1125
1126 // Actual->formal assignability conversions for variadic parameter,
1127 // and construction of slice.
1128 if sig.Variadic() {
1129 varargs := args[offset+np:]
1130 st := sig.Params().At(np).Type().(*types.Slice)
1131 vt := st.Elem()
1132 if len(varargs) == 0 {
1133 args = append(args, zeroConst(st))
1134 } else {
1135 // Replace a suffix of args with a slice containing it.
1136 at := types.NewArray(vt, int64(len(varargs)))
1137 a := emitNew(fn, at, token.NoPos, "varargs")
1138 a.setPos(e.Rparen)
1139 for i, arg := range varargs {
1140 iaddr := &IndexAddr{
1141 X: a,
1142 Index: intConst(int64(i)),
1143 }
1144 iaddr.setType(types.NewPointer(vt))
1145 fn.emit(iaddr)
1146 emitStore(fn, iaddr, arg, arg.Pos())
1147 }
1148 s := &Slice{X: a}
1149 s.setType(st)
1150 args[offset+np] = fn.emit(s)
1151 args = args[:offset+np+1]
1152 }
1153 }
1154 return args
1155 }
1156
1157 // setCall emits to fn code to evaluate all the parameters of a function
1158 // call e, and populates *c with those values.
1159 func (b *builder) setCall(fn *Function, e *ast.CallExpr, c *CallCommon) {
1160 // First deal with the f(...) part and optional receiver.
1161 b.setCallFunc(fn, e, c)
1162
1163 // Then append the other actual parameters.
1164 sig, _ := typeparams.CoreType(fn.typeOf(e.Fun)).(*types.Signature)
1165 if sig == nil {
1166 panic(fmt.Sprintf("no signature for call of %s", e.Fun))
1167 }
1168 c.Args = b.emitCallArgs(fn, sig, e, c.Args)
1169 }
1170
1171 // assignOp emits to fn code to perform loc <op>= val.
1172 func (b *builder) assignOp(fn *Function, loc lvalue, val Value, op token.Token, pos token.Pos) {
1173 loc.store(fn, emitArith(fn, op, loc.load(fn), val, loc.typ(), pos))
1174 }
1175
1176 // localValueSpec emits to fn code to define all of the vars in the
1177 // function-local ValueSpec, spec.
1178 func (b *builder) localValueSpec(fn *Function, spec *ast.ValueSpec) {
1179 switch {
1180 case len(spec.Values) == len(spec.Names):
1181 // e.g. var x, y = 0, 1
1182 // 1:1 assignment
1183 for i, id := range spec.Names {
1184 if !isBlankIdent(id) {
1185 emitLocalVar(fn, identVar(fn, id))
1186 }
1187 lval := b.addr(fn, id, false) // non-escaping
1188 b.assign(fn, lval, spec.Values[i], true, nil)
1189 }
1190
1191 case len(spec.Values) == 0:
1192 // e.g. var x, y int
1193 // Locals are implicitly zero-initialized.
1194 for _, id := range spec.Names {
1195 if !isBlankIdent(id) {
1196 lhs := emitLocalVar(fn, identVar(fn, id))
1197 if fn.debugInfo() {
1198 emitDebugRef(fn, id, lhs, true)
1199 }
1200 }
1201 }
1202
1203 default:
1204 // e.g. var x, y = pos()
1205 tuple := b.exprN(fn, spec.Values[0])
1206 for i, id := range spec.Names {
1207 if !isBlankIdent(id) {
1208 emitLocalVar(fn, identVar(fn, id))
1209 lhs := b.addr(fn, id, false) // non-escaping
1210 lhs.store(fn, emitExtract(fn, tuple, i))
1211 }
1212 }
1213 }
1214 }
1215
1216 // assignStmt emits code to fn for a parallel assignment of rhss to lhss.
1217 // isDef is true if this is a short variable declaration (:=).
1218 //
1219 // Note the similarity with localValueSpec.
1220 func (b *builder) assignStmt(fn *Function, lhss, rhss []ast.Expr, isDef bool) {
1221 // Side effects of all LHSs and RHSs must occur in left-to-right order.
1222 lvals := make([]lvalue, len(lhss))
1223 isZero := make([]bool, len(lhss))
1224 for i, lhs := range lhss {
1225 var lval lvalue = blank{}
1226 if !isBlankIdent(lhs) {
1227 if isDef {
1228 if obj, ok := fn.info.Defs[lhs.(*ast.Ident)].(*types.Var); ok {
1229 emitLocalVar(fn, obj)
1230 isZero[i] = true
1231 }
1232 }
1233 lval = b.addr(fn, lhs, false) // non-escaping
1234 }
1235 lvals[i] = lval
1236 }
1237 if len(lhss) == len(rhss) {
1238 // Simple assignment: x = f() (!isDef)
1239 // Parallel assignment: x, y = f(), g() (!isDef)
1240 // or short var decl: x, y := f(), g() (isDef)
1241 //
1242 // In all cases, the RHSs may refer to the LHSs,
1243 // so we need a storebuf.
1244 var sb storebuf
1245 for i := range rhss {
1246 b.assign(fn, lvals[i], rhss[i], isZero[i], &sb)
1247 }
1248 sb.emit(fn)
1249 } else {
1250 // e.g. x, y = pos()
1251 tuple := b.exprN(fn, rhss[0])
1252 emitDebugRef(fn, rhss[0], tuple, false)
1253 for i, lval := range lvals {
1254 lval.store(fn, emitExtract(fn, tuple, i))
1255 }
1256 }
1257 }
1258
1259 // arrayLen returns the length of the array whose composite literal elements are elts.
1260 func (b *builder) arrayLen(fn *Function, elts []ast.Expr) int64 {
1261 var max int64 = -1
1262 var i int64 = -1
1263 for _, e := range elts {
1264 if kv, ok := e.(*ast.KeyValueExpr); ok {
1265 i = b.expr(fn, kv.Key).(*Const).Int64()
1266 } else {
1267 i++
1268 }
1269 if i > max {
1270 max = i
1271 }
1272 }
1273 return max + 1
1274 }
1275
1276 // compLit emits to fn code to initialize a composite literal e at
1277 // address addr with type typ.
1278 //
1279 // Nested composite literals are recursively initialized in place
1280 // where possible. If isZero is true, compLit assumes that addr
1281 // holds the zero value for typ.
1282 //
1283 // Because the elements of a composite literal may refer to the
1284 // variables being updated, as in the second line below,
1285 //
1286 // x := T{a: 1}
1287 // x = T{a: x.a}
1288 //
1289 // all the reads must occur before all the writes. Thus all stores to
1290 // loc are emitted to the storebuf sb for later execution.
1291 //
1292 // A CompositeLit may have pointer type only in the recursive (nested)
1293 // case when the type name is implicit. e.g. in []*T{{}}, the inner
1294 // literal has type *T behaves like &T{}.
1295 // In that case, addr must hold a T, not a *T.
1296 func (b *builder) compLit(fn *Function, addr Value, e *ast.CompositeLit, isZero bool, sb *storebuf) {
1297 typ := typeparams.Deref(fn.typeOf(e)) // retain the named/alias/param type, if any
1298 switch t := typeparams.CoreType(typ).(type) {
1299 case *types.Struct:
1300 if !isZero && len(e.Elts) != t.NumFields() {
1301 // memclear
1302 zt := typeparams.MustDeref(addr.Type())
1303 sb.store(&address{addr, e.Lbrace, nil}, zeroConst(zt))
1304 isZero = true
1305 }
1306 var fIndices []int
1307 for i, e := range e.Elts {
1308 var (
1309 pos token.Pos
1310 fType types.Type
1311 )
1312
1313 if kv, ok := e.(*ast.KeyValueExpr); ok { // tagged field
1314 fname := kv.Key.(*ast.Ident).Name
1315 obj, index, _ := types.LookupFieldOrMethod(t, true, fn.declaredPackage().Pkg, fname)
1316 fIndices = append(fIndices[:0], index...)
1317 pos = kv.Colon
1318 e = kv.Value
1319 fType = obj.Type()
1320 } else { // untagged field
1321 fIndices = append(fIndices[:0], i)
1322 pos = e.Pos()
1323 fType = t.Field(i).Type()
1324 }
1325
1326 last := len(fIndices) - 1
1327 v := emitImplicitSelections(fn, addr, fIndices[:last], pos)
1328
1329 faddr := &FieldAddr{
1330 X: v,
1331 Field: fIndices[last],
1332 }
1333 faddr.setPos(pos)
1334 faddr.setType(types.NewPointer(fType))
1335 fn.emit(faddr)
1336 b.assign(fn, &address{addr: faddr, pos: pos, expr: e}, e, isZero, sb)
1337 }
1338
1339 case *types.Array, *types.Slice:
1340 var at *types.Array
1341 var array Value
1342 switch t := t.(type) {
1343 case *types.Slice:
1344 at = types.NewArray(t.Elem(), b.arrayLen(fn, e.Elts))
1345 array = emitNew(fn, at, e.Lbrace, "slicelit")
1346 case *types.Array:
1347 at = t
1348 array = addr
1349
1350 if !isZero && int64(len(e.Elts)) != at.Len() {
1351 // memclear
1352 zt := typeparams.MustDeref(array.Type())
1353 sb.store(&address{array, e.Lbrace, nil}, zeroConst(zt))
1354 }
1355 }
1356
1357 var idx *Const
1358 for _, e := range e.Elts {
1359 pos := e.Pos()
1360 if kv, ok := e.(*ast.KeyValueExpr); ok {
1361 idx = b.expr(fn, kv.Key).(*Const)
1362 pos = kv.Colon
1363 e = kv.Value
1364 } else {
1365 var idxval int64
1366 if idx != nil {
1367 idxval = idx.Int64() + 1
1368 }
1369 idx = intConst(idxval)
1370 }
1371 iaddr := &IndexAddr{
1372 X: array,
1373 Index: idx,
1374 }
1375 iaddr.setType(types.NewPointer(at.Elem()))
1376 fn.emit(iaddr)
1377 if t != at { // slice
1378 // backing array is unaliased => storebuf not needed.
1379 b.assign(fn, &address{addr: iaddr, pos: pos, expr: e}, e, true, nil)
1380 } else {
1381 b.assign(fn, &address{addr: iaddr, pos: pos, expr: e}, e, true, sb)
1382 }
1383 }
1384
1385 if t != at { // slice
1386 s := &Slice{X: array}
1387 s.setPos(e.Lbrace)
1388 s.setType(typ)
1389 sb.store(&address{addr: addr, pos: e.Lbrace, expr: e}, fn.emit(s))
1390 }
1391
1392 case *types.Map:
1393 m := &MakeMap{Reserve: intConst(int64(len(e.Elts)))}
1394 m.setPos(e.Lbrace)
1395 m.setType(typ)
1396 fn.emit(m)
1397 for _, e := range e.Elts {
1398 e := e.(*ast.KeyValueExpr)
1399
1400 // If a key expression in a map literal is itself a
1401 // composite literal, the type may be omitted.
1402 // For example:
1403 // map[*struct{}]bool{{}: true}
1404 // An &-operation may be implied:
1405 // map[*struct{}]bool{&struct{}{}: true}
1406 wantAddr := false
1407 if _, ok := ast.Unparen(e.Key).(*ast.CompositeLit); ok {
1408 wantAddr = isPointerCore(t.Key())
1409 }
1410
1411 var key Value
1412 if wantAddr {
1413 // A CompositeLit never evaluates to a pointer,
1414 // so if the type of the location is a pointer,
1415 // an &-operation is implied.
1416 key = b.addr(fn, e.Key, true).address(fn)
1417 } else {
1418 key = b.expr(fn, e.Key)
1419 }
1420
1421 loc := element{
1422 m: m,
1423 k: emitConv(fn, key, t.Key()),
1424 t: t.Elem(),
1425 pos: e.Colon,
1426 }
1427
1428 // We call assign() only because it takes care
1429 // of any &-operation required in the recursive
1430 // case, e.g.,
1431 // map[int]*struct{}{0: {}} implies &struct{}{}.
1432 // In-place update is of course impossible,
1433 // and no storebuf is needed.
1434 b.assign(fn, &loc, e.Value, true, nil)
1435 }
1436 sb.store(&address{addr: addr, pos: e.Lbrace, expr: e}, m)
1437
1438 default:
1439 panic("unexpected CompositeLit type: " + typ.String())
1440 }
1441 }
1442
1443 // switchStmt emits to fn code for the switch statement s, optionally
1444 // labelled by label.
1445 func (b *builder) switchStmt(fn *Function, s *ast.SwitchStmt, label *lblock) {
1446 // We treat SwitchStmt like a sequential if-else chain.
1447 // Multiway dispatch can be recovered later by ssautil.Switches()
1448 // to those cases that are free of side effects.
1449 if s.Init != nil {
1450 b.stmt(fn, s.Init)
1451 }
1452 var tag Value = vTrue
1453 if s.Tag != nil {
1454 tag = b.expr(fn, s.Tag)
1455 }
1456 done := fn.newBasicBlock("switch.done")
1457 if label != nil {
1458 label._break = done
1459 }
1460 // We pull the default case (if present) down to the end.
1461 // But each fallthrough label must point to the next
1462 // body block in source order, so we preallocate a
1463 // body block (fallthru) for the next case.
1464 // Unfortunately this makes for a confusing block order.
1465 var dfltBody *[]ast.Stmt
1466 var dfltFallthrough *BasicBlock
1467 var fallthru, dfltBlock *BasicBlock
1468 ncases := len(s.Body.List)
1469 for i, clause := range s.Body.List {
1470 body := fallthru
1471 if body == nil {
1472 body = fn.newBasicBlock("switch.body") // first case only
1473 }
1474
1475 // Preallocate body block for the next case.
1476 fallthru = done
1477 if i+1 < ncases {
1478 fallthru = fn.newBasicBlock("switch.body")
1479 }
1480
1481 cc := clause.(*ast.CaseClause)
1482 if cc.List == nil {
1483 // Default case.
1484 dfltBody = &cc.Body
1485 dfltFallthrough = fallthru
1486 dfltBlock = body
1487 continue
1488 }
1489
1490 var nextCond *BasicBlock
1491 for _, cond := range cc.List {
1492 nextCond = fn.newBasicBlock("switch.next")
1493 // For boolean switches, emit short-circuit control flow,
1494 // just like an if/else-chain.
1495 if tag == vTrue && !isNonTypeParamInterface(fn.info.Types[cond].Type) {
1496 b.cond(fn, cond, body, nextCond)
1497 } else {
1498 c := emitCompare(fn, token.EQL, tag, b.expr(fn, cond), cond.Pos())
1499 emitIf(fn, c, body, nextCond)
1500 }
1501 fn.currentBlock = nextCond
1502 }
1503 fn.currentBlock = body
1504 fn.targets = &targets{
1505 tail: fn.targets,
1506 _break: done,
1507 _fallthrough: fallthru,
1508 }
1509 b.stmtList(fn, cc.Body)
1510 fn.targets = fn.targets.tail
1511 emitJump(fn, done)
1512 fn.currentBlock = nextCond
1513 }
1514 if dfltBlock != nil {
1515 emitJump(fn, dfltBlock)
1516 fn.currentBlock = dfltBlock
1517 fn.targets = &targets{
1518 tail: fn.targets,
1519 _break: done,
1520 _fallthrough: dfltFallthrough,
1521 }
1522 b.stmtList(fn, *dfltBody)
1523 fn.targets = fn.targets.tail
1524 }
1525 emitJump(fn, done)
1526 fn.currentBlock = done
1527 }
1528
1529 // typeSwitchStmt emits to fn code for the type switch statement s, optionally
1530 // labelled by label.
1531 func (b *builder) typeSwitchStmt(fn *Function, s *ast.TypeSwitchStmt, label *lblock) {
1532 // We treat TypeSwitchStmt like a sequential if-else chain.
1533 // Multiway dispatch can be recovered later by ssautil.Switches().
1534
1535 // Typeswitch lowering:
1536 //
1537 // var x X
1538 // switch y := x.(type) {
1539 // case T1, T2: S1 // >1 (y := x)
1540 // case nil: SN // nil (y := x)
1541 // default: SD // 0 types (y := x)
1542 // case T3: S3 // 1 type (y := x.(T3))
1543 // }
1544 //
1545 // ...s.Init...
1546 // x := eval x
1547 // .caseT1:
1548 // t1, ok1 := typeswitch,ok x <T1>
1549 // if ok1 then goto S1 else goto .caseT2
1550 // .caseT2:
1551 // t2, ok2 := typeswitch,ok x <T2>
1552 // if ok2 then goto S1 else goto .caseNil
1553 // .S1:
1554 // y := x
1555 // ...S1...
1556 // goto done
1557 // .caseNil:
1558 // if t2, ok2 := typeswitch,ok x <T2>
1559 // if x == nil then goto SN else goto .caseT3
1560 // .SN:
1561 // y := x
1562 // ...SN...
1563 // goto done
1564 // .caseT3:
1565 // t3, ok3 := typeswitch,ok x <T3>
1566 // if ok3 then goto S3 else goto default
1567 // .S3:
1568 // y := t3
1569 // ...S3...
1570 // goto done
1571 // .default:
1572 // y := x
1573 // ...SD...
1574 // goto done
1575 // .done:
1576 if s.Init != nil {
1577 b.stmt(fn, s.Init)
1578 }
1579
1580 var x Value
1581 switch ass := s.Assign.(type) {
1582 case *ast.ExprStmt: // x.(type)
1583 x = b.expr(fn, ast.Unparen(ass.X).(*ast.TypeAssertExpr).X)
1584 case *ast.AssignStmt: // y := x.(type)
1585 x = b.expr(fn, ast.Unparen(ass.Rhs[0]).(*ast.TypeAssertExpr).X)
1586 }
1587
1588 done := fn.newBasicBlock("typeswitch.done")
1589 if label != nil {
1590 label._break = done
1591 }
1592 var default_ *ast.CaseClause
1593 for _, clause := range s.Body.List {
1594 cc := clause.(*ast.CaseClause)
1595 if cc.List == nil {
1596 default_ = cc
1597 continue
1598 }
1599 body := fn.newBasicBlock("typeswitch.body")
1600 var next *BasicBlock
1601 var casetype types.Type
1602 var ti Value // ti, ok := typeassert,ok x <Ti>
1603 for _, cond := range cc.List {
1604 next = fn.newBasicBlock("typeswitch.next")
1605 casetype = fn.typeOf(cond)
1606 var condv Value
1607 if casetype == tUntypedNil {
1608 condv = emitCompare(fn, token.EQL, x, zeroConst(x.Type()), cond.Pos())
1609 ti = x
1610 } else {
1611 yok := emitTypeTest(fn, x, casetype, cc.Case)
1612 ti = emitExtract(fn, yok, 0)
1613 condv = emitExtract(fn, yok, 1)
1614 }
1615 emitIf(fn, condv, body, next)
1616 fn.currentBlock = next
1617 }
1618 if len(cc.List) != 1 {
1619 ti = x
1620 }
1621 fn.currentBlock = body
1622 b.typeCaseBody(fn, cc, ti, done)
1623 fn.currentBlock = next
1624 }
1625 if default_ != nil {
1626 b.typeCaseBody(fn, default_, x, done)
1627 } else {
1628 emitJump(fn, done)
1629 }
1630 fn.currentBlock = done
1631 }
1632
1633 func (b *builder) typeCaseBody(fn *Function, cc *ast.CaseClause, x Value, done *BasicBlock) {
1634 if obj, ok := fn.info.Implicits[cc].(*types.Var); ok {
1635 // In a switch y := x.(type), each case clause
1636 // implicitly declares a distinct object y.
1637 // In a single-type case, y has that type.
1638 // In multi-type cases, 'case nil' and default,
1639 // y has the same type as the interface operand.
1640 emitStore(fn, emitLocalVar(fn, obj), x, obj.Pos())
1641 }
1642 fn.targets = &targets{
1643 tail: fn.targets,
1644 _break: done,
1645 }
1646 b.stmtList(fn, cc.Body)
1647 fn.targets = fn.targets.tail
1648 emitJump(fn, done)
1649 }
1650
1651 // selectStmt emits to fn code for the select statement s, optionally
1652 // labelled by label.
1653 func (b *builder) selectStmt(fn *Function, s *ast.SelectStmt, label *lblock) {
1654 // A blocking select of a single case degenerates to a
1655 // simple send or receive.
1656 // TODO(adonovan): opt: is this optimization worth its weight?
1657 if len(s.Body.List) == 1 {
1658 clause := s.Body.List[0].(*ast.CommClause)
1659 if clause.Comm != nil {
1660 b.stmt(fn, clause.Comm)
1661 done := fn.newBasicBlock("select.done")
1662 if label != nil {
1663 label._break = done
1664 }
1665 fn.targets = &targets{
1666 tail: fn.targets,
1667 _break: done,
1668 }
1669 b.stmtList(fn, clause.Body)
1670 fn.targets = fn.targets.tail
1671 emitJump(fn, done)
1672 fn.currentBlock = done
1673 return
1674 }
1675 }
1676
1677 // First evaluate all channels in all cases, and find
1678 // the directions of each state.
1679 var states []*SelectState
1680 blocking := true
1681 debugInfo := fn.debugInfo()
1682 for _, clause := range s.Body.List {
1683 var st *SelectState
1684 switch comm := clause.(*ast.CommClause).Comm.(type) {
1685 case nil: // default case
1686 blocking = false
1687 continue
1688
1689 case *ast.SendStmt: // ch<- i
1690 ch := b.expr(fn, comm.Chan)
1691 chtyp := typeparams.CoreType(fn.typ(ch.Type())).(*types.Chan)
1692 st = &SelectState{
1693 Dir: types.SendOnly,
1694 Chan: ch,
1695 Send: emitConv(fn, b.expr(fn, comm.Value), chtyp.Elem()),
1696 Pos: comm.Arrow,
1697 }
1698 if debugInfo {
1699 st.DebugNode = comm
1700 }
1701
1702 case *ast.AssignStmt: // x := <-ch
1703 recv := ast.Unparen(comm.Rhs[0]).(*ast.UnaryExpr)
1704 st = &SelectState{
1705 Dir: types.RecvOnly,
1706 Chan: b.expr(fn, recv.X),
1707 Pos: recv.OpPos,
1708 }
1709 if debugInfo {
1710 st.DebugNode = recv
1711 }
1712
1713 case *ast.ExprStmt: // <-ch
1714 recv := ast.Unparen(comm.X).(*ast.UnaryExpr)
1715 st = &SelectState{
1716 Dir: types.RecvOnly,
1717 Chan: b.expr(fn, recv.X),
1718 Pos: recv.OpPos,
1719 }
1720 if debugInfo {
1721 st.DebugNode = recv
1722 }
1723 }
1724 states = append(states, st)
1725 }
1726
1727 // We dispatch on the (fair) result of Select using a
1728 // sequential if-else chain, in effect:
1729 //
1730 // idx, recvOk, r0...r_n-1 := select(...)
1731 // if idx == 0 { // receive on channel 0 (first receive => r0)
1732 // x, ok := r0, recvOk
1733 // ...state0...
1734 // } else if v == 1 { // send on channel 1
1735 // ...state1...
1736 // } else {
1737 // ...default...
1738 // }
1739 sel := &Select{
1740 States: states,
1741 Blocking: blocking,
1742 }
1743 sel.setPos(s.Select)
1744 var vars []*types.Var
1745 vars = append(vars, varIndex, varOk)
1746 for _, st := range states {
1747 if st.Dir == types.RecvOnly {
1748 chtyp := typeparams.CoreType(fn.typ(st.Chan.Type())).(*types.Chan)
1749 vars = append(vars, anonVar(chtyp.Elem()))
1750 }
1751 }
1752 sel.setType(types.NewTuple(vars...))
1753
1754 fn.emit(sel)
1755 idx := emitExtract(fn, sel, 0)
1756
1757 done := fn.newBasicBlock("select.done")
1758 if label != nil {
1759 label._break = done
1760 }
1761
1762 var defaultBody *[]ast.Stmt
1763 state := 0
1764 r := 2 // index in 'sel' tuple of value; increments if st.Dir==RECV
1765 for _, cc := range s.Body.List {
1766 clause := cc.(*ast.CommClause)
1767 if clause.Comm == nil {
1768 defaultBody = &clause.Body
1769 continue
1770 }
1771 body := fn.newBasicBlock("select.body")
1772 next := fn.newBasicBlock("select.next")
1773 emitIf(fn, emitCompare(fn, token.EQL, idx, intConst(int64(state)), token.NoPos), body, next)
1774 fn.currentBlock = body
1775 fn.targets = &targets{
1776 tail: fn.targets,
1777 _break: done,
1778 }
1779 switch comm := clause.Comm.(type) {
1780 case *ast.ExprStmt: // <-ch
1781 if debugInfo {
1782 v := emitExtract(fn, sel, r)
1783 emitDebugRef(fn, states[state].DebugNode.(ast.Expr), v, false)
1784 }
1785 r++
1786
1787 case *ast.AssignStmt: // x := <-states[state].Chan
1788 if comm.Tok == token.DEFINE {
1789 emitLocalVar(fn, identVar(fn, comm.Lhs[0].(*ast.Ident)))
1790 }
1791 x := b.addr(fn, comm.Lhs[0], false) // non-escaping
1792 v := emitExtract(fn, sel, r)
1793 if debugInfo {
1794 emitDebugRef(fn, states[state].DebugNode.(ast.Expr), v, false)
1795 }
1796 x.store(fn, v)
1797
1798 if len(comm.Lhs) == 2 { // x, ok := ...
1799 if comm.Tok == token.DEFINE {
1800 emitLocalVar(fn, identVar(fn, comm.Lhs[1].(*ast.Ident)))
1801 }
1802 ok := b.addr(fn, comm.Lhs[1], false) // non-escaping
1803 ok.store(fn, emitExtract(fn, sel, 1))
1804 }
1805 r++
1806 }
1807 b.stmtList(fn, clause.Body)
1808 fn.targets = fn.targets.tail
1809 emitJump(fn, done)
1810 fn.currentBlock = next
1811 state++
1812 }
1813 if defaultBody != nil {
1814 fn.targets = &targets{
1815 tail: fn.targets,
1816 _break: done,
1817 }
1818 b.stmtList(fn, *defaultBody)
1819 fn.targets = fn.targets.tail
1820 } else {
1821 // A blocking select must match some case.
1822 // (This should really be a runtime.errorString, not a string.)
1823 fn.emit(&Panic{
1824 X: emitConv(fn, stringConst("blocking select matched no case"), tEface),
1825 })
1826 fn.currentBlock = fn.newBasicBlock("unreachable")
1827 }
1828 emitJump(fn, done)
1829 fn.currentBlock = done
1830 }
1831
1832 // forStmt emits to fn code for the for statement s, optionally
1833 // labelled by label.
1834 func (b *builder) forStmt(fn *Function, s *ast.ForStmt, label *lblock) {
1835 // Use forStmtGo122 instead if it applies.
1836 if s.Init != nil {
1837 if assign, ok := s.Init.(*ast.AssignStmt); ok && assign.Tok == token.DEFINE {
1838 if versions.AtLeast(fn.goversion, versions.Go1_22) {
1839 b.forStmtGo122(fn, s, label)
1840 return
1841 }
1842 }
1843 }
1844
1845 // ...init...
1846 // jump loop
1847 // loop:
1848 // if cond goto body else done
1849 // body:
1850 // ...body...
1851 // jump post
1852 // post: (target of continue)
1853 // ...post...
1854 // jump loop
1855 // done: (target of break)
1856 if s.Init != nil {
1857 b.stmt(fn, s.Init)
1858 }
1859
1860 body := fn.newBasicBlock("for.body")
1861 done := fn.newBasicBlock("for.done") // target of 'break'
1862 loop := body // target of back-edge
1863 if s.Cond != nil {
1864 loop = fn.newBasicBlock("for.loop")
1865 }
1866 cont := loop // target of 'continue'
1867 if s.Post != nil {
1868 cont = fn.newBasicBlock("for.post")
1869 }
1870 if label != nil {
1871 label._break = done
1872 label._continue = cont
1873 }
1874 emitJump(fn, loop)
1875 fn.currentBlock = loop
1876 if loop != body {
1877 b.cond(fn, s.Cond, body, done)
1878 fn.currentBlock = body
1879 }
1880 fn.targets = &targets{
1881 tail: fn.targets,
1882 _break: done,
1883 _continue: cont,
1884 }
1885 b.stmt(fn, s.Body)
1886 fn.targets = fn.targets.tail
1887 emitJump(fn, cont)
1888
1889 if s.Post != nil {
1890 fn.currentBlock = cont
1891 b.stmt(fn, s.Post)
1892 emitJump(fn, loop) // back-edge
1893 }
1894 fn.currentBlock = done
1895 }
1896
1897 // forStmtGo122 emits to fn code for the for statement s, optionally
1898 // labelled by label. s must define its variables.
1899 //
1900 // This allocates once per loop iteration. This is only correct in
1901 // GoVersions >= go1.22.
1902 func (b *builder) forStmtGo122(fn *Function, s *ast.ForStmt, label *lblock) {
1903 // i_outer = alloc[T]
1904 // *i_outer = ...init... // under objects[i] = i_outer
1905 // jump loop
1906 // loop:
1907 // i = phi [head: i_outer, loop: i_next]
1908 // ...cond... // under objects[i] = i
1909 // if cond goto body else done
1910 // body:
1911 // ...body... // under objects[i] = i (same as loop)
1912 // jump post
1913 // post:
1914 // tmp = *i
1915 // i_next = alloc[T]
1916 // *i_next = tmp
1917 // ...post... // under objects[i] = i_next
1918 // goto loop
1919 // done:
1920
1921 init := s.Init.(*ast.AssignStmt)
1922 startingBlocks := len(fn.Blocks)
1923
1924 pre := fn.currentBlock // current block before starting
1925 loop := fn.newBasicBlock("for.loop") // target of back-edge
1926 body := fn.newBasicBlock("for.body")
1927 post := fn.newBasicBlock("for.post") // target of 'continue'
1928 done := fn.newBasicBlock("for.done") // target of 'break'
1929
1930 // For each of the n loop variables, we create five SSA values,
1931 // outer, phi, next, load, and store in pre, loop, and post.
1932 // There is no limit on n.
1933 type loopVar struct {
1934 obj *types.Var
1935 outer *Alloc
1936 phi *Phi
1937 load *UnOp
1938 next *Alloc
1939 store *Store
1940 }
1941 vars := make([]loopVar, len(init.Lhs))
1942 for i, lhs := range init.Lhs {
1943 v := identVar(fn, lhs.(*ast.Ident))
1944 typ := fn.typ(v.Type())
1945
1946 fn.currentBlock = pre
1947 outer := emitLocal(fn, typ, v.Pos(), v.Name())
1948
1949 fn.currentBlock = loop
1950 phi := &Phi{Comment: v.Name()}
1951 phi.pos = v.Pos()
1952 phi.typ = outer.Type()
1953 fn.emit(phi)
1954
1955 fn.currentBlock = post
1956 // If next is local, it reuses the address and zeroes the old value so
1957 // load before allocating next.
1958 load := emitLoad(fn, phi)
1959 next := emitLocal(fn, typ, v.Pos(), v.Name())
1960 store := emitStore(fn, next, load, token.NoPos)
1961
1962 phi.Edges = []Value{outer, next} // pre edge is emitted before post edge.
1963
1964 vars[i] = loopVar{v, outer, phi, load, next, store}
1965 }
1966
1967 // ...init... under fn.objects[v] = i_outer
1968 fn.currentBlock = pre
1969 for _, v := range vars {
1970 fn.vars[v.obj] = v.outer
1971 }
1972 const isDef = false // assign to already-allocated outers
1973 b.assignStmt(fn, init.Lhs, init.Rhs, isDef)
1974 if label != nil {
1975 label._break = done
1976 label._continue = post
1977 }
1978 emitJump(fn, loop)
1979
1980 // ...cond... under fn.objects[v] = i
1981 fn.currentBlock = loop
1982 for _, v := range vars {
1983 fn.vars[v.obj] = v.phi
1984 }
1985 if s.Cond != nil {
1986 b.cond(fn, s.Cond, body, done)
1987 } else {
1988 emitJump(fn, body)
1989 }
1990
1991 // ...body... under fn.objects[v] = i
1992 fn.currentBlock = body
1993 fn.targets = &targets{
1994 tail: fn.targets,
1995 _break: done,
1996 _continue: post,
1997 }
1998 b.stmt(fn, s.Body)
1999 fn.targets = fn.targets.tail
2000 emitJump(fn, post)
2001
2002 // ...post... under fn.objects[v] = i_next
2003 for _, v := range vars {
2004 fn.vars[v.obj] = v.next
2005 }
2006 fn.currentBlock = post
2007 if s.Post != nil {
2008 b.stmt(fn, s.Post)
2009 }
2010 emitJump(fn, loop) // back-edge
2011 fn.currentBlock = done
2012
2013 // For each loop variable that does not escape,
2014 // (the common case), fuse its next cells into its
2015 // (local) outer cell as they have disjoint live ranges.
2016 //
2017 // It is sufficient to test whether i_next escapes,
2018 // because its Heap flag will be marked true if either
2019 // the cond or post expression causes i to escape
2020 // (because escape distributes over phi).
2021 var nlocals int
2022 for _, v := range vars {
2023 if !v.next.Heap {
2024 nlocals++
2025 }
2026 }
2027 if nlocals > 0 {
2028 replace := make(map[Value]Value, 2*nlocals)
2029 dead := make(map[Instruction]bool, 4*nlocals)
2030 for _, v := range vars {
2031 if !v.next.Heap {
2032 replace[v.next] = v.outer
2033 replace[v.phi] = v.outer
2034 dead[v.phi], dead[v.next], dead[v.load], dead[v.store] = true, true, true, true
2035 }
2036 }
2037
2038 // Replace all uses of i_next and phi with i_outer.
2039 // Referrers have not been built for fn yet so only update Instruction operands.
2040 // We need only look within the blocks added by the loop.
2041 var operands []*Value // recycle storage
2042 for _, b := range fn.Blocks[startingBlocks:] {
2043 for _, instr := range b.Instrs {
2044 operands = instr.Operands(operands[:0])
2045 for _, ptr := range operands {
2046 k := *ptr
2047 if v := replace[k]; v != nil {
2048 *ptr = v
2049 }
2050 }
2051 }
2052 }
2053
2054 // Remove instructions for phi, load, and store.
2055 // lift() will remove the unused i_next *Alloc.
2056 isDead := func(i Instruction) bool { return dead[i] }
2057 loop.Instrs = slices.DeleteFunc(loop.Instrs, isDead)
2058 post.Instrs = slices.DeleteFunc(post.Instrs, isDead)
2059 }
2060 }
2061
2062 // rangeIndexed emits to fn the header for an integer-indexed loop
2063 // over array, *array or slice value x.
2064 // The v result is defined only if tv is non-nil.
2065 // forPos is the position of the "for" token.
2066 func (b *builder) rangeIndexed(fn *Function, x Value, tv types.Type, pos token.Pos) (k, v Value, loop, done *BasicBlock) {
2067 //
2068 // length = len(x)
2069 // index = -1
2070 // loop: (target of continue)
2071 // index++
2072 // if index < length goto body else done
2073 // body:
2074 // k = index
2075 // v = x[index]
2076 // ...body...
2077 // jump loop
2078 // done: (target of break)
2079
2080 // Determine number of iterations.
2081 var length Value
2082 dt := typeparams.Deref(x.Type())
2083 if arr, ok := typeparams.CoreType(dt).(*types.Array); ok {
2084 // For array or *array, the number of iterations is
2085 // known statically thanks to the type. We avoid a
2086 // data dependence upon x, permitting later dead-code
2087 // elimination if x is pure, static unrolling, etc.
2088 // Ranging over a nil *array may have >0 iterations.
2089 // We still generate code for x, in case it has effects.
2090 length = intConst(arr.Len())
2091 } else {
2092 // length = len(x).
2093 var c Call
2094 c.Call.Value = makeLen(x.Type())
2095 c.Call.Args = []Value{x}
2096 c.setType(tInt)
2097 length = fn.emit(&c)
2098 }
2099
2100 index := emitLocal(fn, tInt, token.NoPos, "rangeindex")
2101 emitStore(fn, index, intConst(-1), pos)
2102
2103 loop = fn.newBasicBlock("rangeindex.loop")
2104 emitJump(fn, loop)
2105 fn.currentBlock = loop
2106
2107 incr := &BinOp{
2108 Op: token.ADD,
2109 X: emitLoad(fn, index),
2110 Y: vOne,
2111 }
2112 incr.setType(tInt)
2113 emitStore(fn, index, fn.emit(incr), pos)
2114
2115 body := fn.newBasicBlock("rangeindex.body")
2116 done = fn.newBasicBlock("rangeindex.done")
2117 emitIf(fn, emitCompare(fn, token.LSS, incr, length, token.NoPos), body, done)
2118 fn.currentBlock = body
2119
2120 k = emitLoad(fn, index)
2121 if tv != nil {
2122 switch t := typeparams.CoreType(x.Type()).(type) {
2123 case *types.Array:
2124 instr := &Index{
2125 X: x,
2126 Index: k,
2127 }
2128 instr.setType(t.Elem())
2129 instr.setPos(x.Pos())
2130 v = fn.emit(instr)
2131
2132 case *types.Pointer: // *array
2133 instr := &IndexAddr{
2134 X: x,
2135 Index: k,
2136 }
2137 instr.setType(types.NewPointer(t.Elem().Underlying().(*types.Array).Elem()))
2138 instr.setPos(x.Pos())
2139 v = emitLoad(fn, fn.emit(instr))
2140
2141 case *types.Slice:
2142 instr := &IndexAddr{
2143 X: x,
2144 Index: k,
2145 }
2146 instr.setType(types.NewPointer(t.Elem()))
2147 instr.setPos(x.Pos())
2148 v = emitLoad(fn, fn.emit(instr))
2149
2150 default:
2151 panic("rangeIndexed x:" + t.String())
2152 }
2153 }
2154 return
2155 }
2156
2157 // rangeIter emits to fn the header for a loop using
2158 // Range/Next/Extract to iterate over map or string value x.
2159 // tk and tv are the types of the key/value results k and v, or nil
2160 // if the respective component is not wanted.
2161 func (b *builder) rangeIter(fn *Function, x Value, tk, tv types.Type, pos token.Pos) (k, v Value, loop, done *BasicBlock) {
2162 //
2163 // it = range x
2164 // loop: (target of continue)
2165 // okv = next it (ok, key, value)
2166 // ok = extract okv #0
2167 // if ok goto body else done
2168 // body:
2169 // k = extract okv #1
2170 // v = extract okv #2
2171 // ...body...
2172 // jump loop
2173 // done: (target of break)
2174 //
2175
2176 rng := &Range{X: x}
2177 rng.setPos(pos)
2178 rng.setType(tRangeIter)
2179 it := fn.emit(rng)
2180
2181 loop = fn.newBasicBlock("rangeiter.loop")
2182 emitJump(fn, loop)
2183 fn.currentBlock = loop
2184
2185 var ak, av types.Type
2186 isString := false
2187 if m, ok := typeparams.CoreType(x.Type()).(*types.Map); ok {
2188 ak, av = m.Key(), m.Elem()
2189 } else {
2190 isString = true
2191 ak, av = tInt, tRune
2192 }
2193 if tk == nil {
2194 ak = tInvalid
2195 }
2196 if tv == nil {
2197 av = tInvalid
2198 }
2199
2200 okv := &Next{
2201 Iter: it,
2202 IsString: isString,
2203 }
2204 okv.setType(types.NewTuple(
2205 varOk,
2206 newVar("k", ak),
2207 newVar("v", av),
2208 ))
2209 fn.emit(okv)
2210
2211 body := fn.newBasicBlock("rangeiter.body")
2212 done = fn.newBasicBlock("rangeiter.done")
2213 emitIf(fn, emitExtract(fn, okv, 0), body, done)
2214 fn.currentBlock = body
2215
2216 // The assignment may widen a map or string
2217 // key/value to a variable's interface type
2218 // (cases #1 and #2 of go.dev/issue/78110).
2219 if tk != nil {
2220 k = emitConv(fn, emitExtract(fn, okv, 1), tk)
2221 }
2222 if tv != nil {
2223 v = emitConv(fn, emitExtract(fn, okv, 2), tv)
2224 }
2225 return
2226 }
2227
2228 // rangeChan emits to fn the header for a loop that receives from
2229 // channel x until it fails.
2230 // tk is the channel's element type, or nil if the k result is
2231 // not wanted
2232 // pos is the position of the '=' or ':=' token.
2233 func (b *builder) rangeChan(fn *Function, x Value, tk types.Type, pos token.Pos) (k Value, loop, done *BasicBlock) {
2234 //
2235 // loop: (target of continue)
2236 // ko = <-x (key, ok)
2237 // ok = extract ko #1
2238 // if ok goto body else done
2239 // body:
2240 // k = extract ko #0
2241 // ...body...
2242 // goto loop
2243 // done: (target of break)
2244
2245 loop = fn.newBasicBlock("rangechan.loop")
2246 emitJump(fn, loop)
2247 fn.currentBlock = loop
2248 recv := &UnOp{
2249 Op: token.ARROW,
2250 X: x,
2251 CommaOk: true,
2252 }
2253 recv.setPos(pos)
2254 recv.setType(types.NewTuple(
2255 newVar("k", typeparams.CoreType(x.Type()).(*types.Chan).Elem()),
2256 varOk,
2257 ))
2258 ko := fn.emit(recv)
2259 body := fn.newBasicBlock("rangechan.body")
2260 done = fn.newBasicBlock("rangechan.done")
2261 emitIf(fn, emitExtract(fn, ko, 1), body, done)
2262 fn.currentBlock = body
2263 if tk != nil {
2264 k = emitExtract(fn, ko, 0)
2265 }
2266 return
2267 }
2268
2269 // rangeInt emits to fn the header for a range loop with an integer operand.
2270 // tk is the key value's type, or nil if the k result is not wanted.
2271 // pos is the position of the "for" token.
2272 func (b *builder) rangeInt(fn *Function, x Value, tk types.Type, pos token.Pos) (k Value, loop, done *BasicBlock) {
2273 //
2274 // iter = 0
2275 // if 0 < x goto body else done
2276 // loop: (target of continue)
2277 // iter++
2278 // if iter < x goto body else done
2279 // body:
2280 // k = x
2281 // ...body...
2282 // jump loop
2283 // done: (target of break)
2284
2285 if isUntyped(x.Type()) {
2286 x = emitConv(fn, x, tInt)
2287 }
2288
2289 T := x.Type()
2290 iter := emitLocal(fn, T, token.NoPos, "rangeint.iter")
2291 // x may be unsigned. Avoid initializing x to -1.
2292
2293 body := fn.newBasicBlock("rangeint.body")
2294 done = fn.newBasicBlock("rangeint.done")
2295 emitIf(fn, emitCompare(fn, token.LSS, zeroConst(T), x, token.NoPos), body, done)
2296
2297 loop = fn.newBasicBlock("rangeint.loop")
2298 fn.currentBlock = loop
2299
2300 incr := &BinOp{
2301 Op: token.ADD,
2302 X: emitLoad(fn, iter),
2303 Y: emitConv(fn, vOne, T),
2304 }
2305 incr.setType(T)
2306 emitStore(fn, iter, fn.emit(incr), pos)
2307 emitIf(fn, emitCompare(fn, token.LSS, incr, x, token.NoPos), body, done)
2308 fn.currentBlock = body
2309
2310 if tk != nil {
2311 // Integer types (int, uint8, etc.) are named and
2312 // we know that k is assignable to x when tk != nil.
2313 // This implies tk and T are identical so no conversion is needed.
2314 k = emitLoad(fn, iter)
2315 }
2316
2317 return
2318 }
2319
2320 // rangeStmt emits to fn code for the range statement s, optionally
2321 // labelled by label.
2322 func (b *builder) rangeStmt(fn *Function, s *ast.RangeStmt, label *lblock) {
2323 var tk, tv types.Type
2324 if s.Key != nil && !isBlankIdent(s.Key) {
2325 tk = fn.typeOf(s.Key)
2326 }
2327 if s.Value != nil && !isBlankIdent(s.Value) {
2328 tv = fn.typeOf(s.Value)
2329 }
2330
2331 // create locals for s.Key and s.Value.
2332 createVars := func() {
2333 // Unlike a short variable declaration, a RangeStmt
2334 // using := never redeclares an existing variable; it
2335 // always creates a new one.
2336 if tk != nil {
2337 emitLocalVar(fn, identVar(fn, s.Key.(*ast.Ident)))
2338 }
2339 if tv != nil {
2340 emitLocalVar(fn, identVar(fn, s.Value.(*ast.Ident)))
2341 }
2342 }
2343
2344 afterGo122 := versions.AtLeast(fn.goversion, versions.Go1_22)
2345 if s.Tok == token.DEFINE && !afterGo122 {
2346 // pre-go1.22: If iteration variables are defined (:=), this
2347 // occurs once outside the loop.
2348 createVars()
2349 }
2350
2351 x := b.expr(fn, s.X)
2352
2353 var k, v Value
2354 var loop, done *BasicBlock
2355 switch rt := typeparams.CoreType(x.Type()).(type) {
2356 case *types.Slice, *types.Array, *types.Pointer: // *array
2357 k, v, loop, done = b.rangeIndexed(fn, x, tv, s.For)
2358
2359 case *types.Chan:
2360 k, loop, done = b.rangeChan(fn, x, tk, s.For)
2361
2362 case *types.Map:
2363 k, v, loop, done = b.rangeIter(fn, x, tk, tv, s.For)
2364
2365 case *types.Basic:
2366 switch {
2367 case rt.Info()&types.IsString != 0:
2368 k, v, loop, done = b.rangeIter(fn, x, tk, tv, s.For)
2369
2370 case rt.Info()&types.IsInteger != 0:
2371 k, loop, done = b.rangeInt(fn, x, tk, s.For)
2372
2373 default:
2374 panic("Cannot range over basic type: " + rt.String())
2375 }
2376
2377 case *types.Signature:
2378 // Special case rewrite (fn.goversion >= go1.23):
2379 // for x := range f { ... }
2380 // into
2381 // f(func(x T) bool { ... })
2382 b.rangeFunc(fn, x, s, label)
2383 return
2384
2385 default:
2386 panic("Cannot range over: " + rt.String())
2387 }
2388
2389 if s.Tok == token.DEFINE && afterGo122 {
2390 // go1.22: If iteration variables are defined (:=), this occurs inside the loop.
2391 createVars()
2392 }
2393
2394 // Evaluate both LHS expressions before we update either.
2395 var kl, vl lvalue
2396 if tk != nil {
2397 kl = b.addr(fn, s.Key, false) // non-escaping
2398 }
2399 if tv != nil {
2400 vl = b.addr(fn, s.Value, false) // non-escaping
2401 }
2402 if tk != nil {
2403 kl.store(fn, k)
2404 }
2405 if tv != nil {
2406 vl.store(fn, v)
2407 }
2408
2409 if label != nil {
2410 label._break = done
2411 label._continue = loop
2412 }
2413
2414 fn.targets = &targets{
2415 tail: fn.targets,
2416 _break: done,
2417 _continue: loop,
2418 }
2419 b.stmt(fn, s.Body)
2420 fn.targets = fn.targets.tail
2421 emitJump(fn, loop) // back-edge
2422 fn.currentBlock = done
2423 }
2424
2425 // rangeFunc emits to fn code for the range-over-func rng.Body of the iterator
2426 // function x, optionally labelled by label. It creates a new anonymous function
2427 // yield for rng and builds the function.
2428 func (b *builder) rangeFunc(fn *Function, x Value, rng *ast.RangeStmt, label *lblock) {
2429 // Consider the SSA code for the outermost range-over-func in fn:
2430 //
2431 // func fn(...) (ret R) {
2432 // ...
2433 // for k, v = range x {
2434 // ...
2435 // }
2436 // ...
2437 // }
2438 //
2439 // The code emitted into fn will look something like this.
2440 //
2441 // loop:
2442 // jump := READY
2443 // y := make closure yield [ret, deferstack, jump, k, v]
2444 // x(y)
2445 // switch jump {
2446 // [see resuming execution]
2447 // }
2448 // goto done
2449 // done:
2450 // ...
2451 //
2452 // where yield is a new synthetic yield function:
2453 //
2454 // func yield(_k tk, _v tv) bool
2455 // free variables: [ret, stack, jump, k, v]
2456 // {
2457 // entry:
2458 // if jump != READY then goto invalid else valid
2459 // invalid:
2460 // panic("iterator called when it is not in a ready state")
2461 // valid:
2462 // jump = BUSY
2463 // k = _k
2464 // v = _v
2465 // ...
2466 // cont:
2467 // jump = READY
2468 // return true
2469 // }
2470 //
2471 // Yield state:
2472 //
2473 // Each range loop has an associated jump variable that records
2474 // the state of the iterator. A yield function is initially
2475 // in a READY (0) and callable state. If the yield function is called
2476 // and is not in READY state, it panics. When it is called in a callable
2477 // state, it becomes BUSY. When execution reaches the end of the body
2478 // of the loop (or a continue statement targeting the loop is executed),
2479 // the yield function returns true and resumes being in a READY state.
2480 // After the iterator function x(y) returns, then if the yield function
2481 // is in a READY state, the yield enters the DONE state.
2482 //
2483 // Each lowered control statement (break X, continue X, goto Z, or return)
2484 // that exits the loop sets the variable to a unique positive EXIT value,
2485 // before returning false from the yield function.
2486 //
2487 // If the yield function returns abruptly due to a panic or GoExit,
2488 // it remains in a BUSY state. The generated code asserts that, after
2489 // the iterator call x(y) returns normally, the jump variable state
2490 // is DONE.
2491 //
2492 // Resuming execution:
2493 //
2494 // The code generated for the range statement checks the jump
2495 // variable to determine how to resume execution.
2496 //
2497 // switch jump {
2498 // case BUSY: panic("...")
2499 // case DONE: goto done
2500 // case READY: state = DONE; goto done
2501 // case 123: ... // action for exit 123.
2502 // case 456: ... // action for exit 456.
2503 // ...
2504 // }
2505 //
2506 // Forward goto statements within a yield are jumps to labels that
2507 // have not yet been traversed in fn. They may be in the Body of the
2508 // function. What we emit for these is:
2509 //
2510 // goto target
2511 // target:
2512 // ...
2513 //
2514 // We leave an unresolved exit in yield.exits to check at the end
2515 // of building yield if it encountered target in the body. If it
2516 // encountered target, no additional work is required. Otherwise,
2517 // the yield emits a new early exit in the basic block for target.
2518 // We expect that blockopt will fuse the early exit into the case
2519 // block later. The unresolved exit is then added to yield.parent.exits.
2520
2521 loop := fn.newBasicBlock("rangefunc.loop")
2522 done := fn.newBasicBlock("rangefunc.done")
2523
2524 // These are targets within y.
2525 fn.targets = &targets{
2526 tail: fn.targets,
2527 _break: done,
2528 // _continue is within y.
2529 }
2530 if label != nil {
2531 label._break = done
2532 // _continue is within y
2533 }
2534
2535 emitJump(fn, loop)
2536 fn.currentBlock = loop
2537
2538 // loop:
2539 // jump := READY
2540
2541 anonIdx := len(fn.AnonFuncs)
2542
2543 jump := newVar(fmt.Sprintf("jump$%d", anonIdx+1), tInt)
2544 emitLocalVar(fn, jump) // zero value is READY
2545
2546 xsig := typeparams.CoreType(x.Type()).(*types.Signature)
2547 ysig := typeparams.CoreType(xsig.Params().At(0).Type()).(*types.Signature)
2548
2549 /* synthetic yield function for body of range-over-func loop */
2550 y := &Function{
2551 name: fmt.Sprintf("%s$%d", fn.Name(), anonIdx+1),
2552 Signature: ysig,
2553 Synthetic: "range-over-func yield",
2554 pos: rng.Range,
2555 parent: fn,
2556 anonIdx: int32(len(fn.AnonFuncs)),
2557 Pkg: fn.Pkg,
2558 Prog: fn.Prog,
2559 syntax: rng,
2560 info: fn.info,
2561 goversion: fn.goversion,
2562 build: (*builder).buildYieldFunc,
2563 topLevelOrigin: nil,
2564 typeparams: fn.typeparams,
2565 typeargs: fn.typeargs,
2566 subst: fn.subst,
2567 jump: jump,
2568 deferstack: fn.deferstack,
2569 returnVars: fn.returnVars, // use the parent's return variables
2570 uniq: fn.uniq, // start from parent's unique values
2571 }
2572
2573 // If the RangeStmt has a label, this is how it is passed to buildYieldFunc.
2574 if label != nil {
2575 y.lblocks = map[*types.Label]*lblock{label.label: nil}
2576 }
2577 fn.AnonFuncs = append(fn.AnonFuncs, y)
2578
2579 // Build y immediately. It may:
2580 // * cause fn's locals to escape, and
2581 // * create new exit nodes in exits.
2582 // (y is not marked 'built' until the end of the enclosing FuncDecl.)
2583 unresolved := len(fn.exits)
2584 y.build(b, y)
2585 fn.uniq = y.uniq // resume after y's unique values
2586
2587 // Emit the call of y.
2588 // c := MakeClosure y
2589 // x(c)
2590 c := &MakeClosure{Fn: y}
2591 c.setType(ysig)
2592 for _, fv := range y.FreeVars {
2593 c.Bindings = append(c.Bindings, fv.outer)
2594 fv.outer = nil
2595 }
2596 fn.emit(c)
2597 call := Call{
2598 Call: CallCommon{
2599 Value: x,
2600 Args: []Value{c},
2601 pos: token.NoPos,
2602 },
2603 }
2604 call.setType(xsig.Results())
2605 fn.emit(&call)
2606
2607 exits := fn.exits[unresolved:]
2608 b.buildYieldResume(fn, jump, exits, done)
2609
2610 emitJump(fn, done)
2611 fn.currentBlock = done
2612 // pop the stack for the range-over-func
2613 fn.targets = fn.targets.tail
2614 }
2615
2616 // buildYieldResume emits to fn code for how to resume execution once a call to
2617 // the iterator function over the yield function returns x(y). It does this by building
2618 // a switch over the value of jump for when it is READY, BUSY, or EXIT(id).
2619 func (b *builder) buildYieldResume(fn *Function, jump *types.Var, exits []*exit, done *BasicBlock) {
2620 // v := *jump
2621 // switch v {
2622 // case BUSY: panic("...")
2623 // case READY: jump = DONE; goto done
2624 // case EXIT(a): ...
2625 // case EXIT(b): ...
2626 // ...
2627 // }
2628 v := emitLoad(fn, fn.lookup(jump, false))
2629
2630 // case BUSY: panic("...")
2631 isbusy := fn.newBasicBlock("rangefunc.resume.busy")
2632 ifready := fn.newBasicBlock("rangefunc.resume.ready.check")
2633 emitIf(fn, emitCompare(fn, token.EQL, v, jBusy, token.NoPos), isbusy, ifready)
2634 fn.currentBlock = isbusy
2635 fn.emit(&Panic{
2636 X: emitConv(fn, stringConst("iterator call did not preserve panic"), tEface),
2637 })
2638 fn.currentBlock = ifready
2639
2640 // case READY: jump = DONE; goto done
2641 isready := fn.newBasicBlock("rangefunc.resume.ready")
2642 ifexit := fn.newBasicBlock("rangefunc.resume.exits")
2643 emitIf(fn, emitCompare(fn, token.EQL, v, jReady, token.NoPos), isready, ifexit)
2644 fn.currentBlock = isready
2645 storeVar(fn, jump, jDone, token.NoPos)
2646 emitJump(fn, done)
2647 fn.currentBlock = ifexit
2648
2649 for _, e := range exits {
2650 id := intConst(e.id)
2651
2652 // case EXIT(id): { /* do e */ }
2653 cond := emitCompare(fn, token.EQL, v, id, e.pos)
2654 matchb := fn.newBasicBlock("rangefunc.resume.match")
2655 cndb := fn.newBasicBlock("rangefunc.resume.cnd")
2656 emitIf(fn, cond, matchb, cndb)
2657 fn.currentBlock = matchb
2658
2659 // Cases to fill in the { /* do e */ } bit.
2660 switch {
2661 case e.label != nil: // forward goto?
2662 // case EXIT(id): goto lb // label
2663 lb := fn.lblockOf(e.label)
2664 // Do not mark lb as resolved.
2665 // If fn does not contain label, lb remains unresolved and
2666 // fn must itself be a range-over-func function. lb will be:
2667 // lb:
2668 // fn.jump = id
2669 // return false
2670 emitJump(fn, lb._goto)
2671
2672 case e.to != fn: // e jumps to an ancestor of fn?
2673 // case EXIT(id): { fn.jump = id; return false }
2674 // fn is a range-over-func function.
2675 storeVar(fn, fn.jump, id, token.NoPos)
2676 fn.emit(&Return{Results: []Value{vFalse}, pos: e.pos})
2677
2678 case e.block == nil && e.label == nil: // return from fn?
2679 // case EXIT(id): { return ... }
2680 fn.emit(new(RunDefers))
2681 results := make([]Value, len(fn.results))
2682 for i, r := range fn.results {
2683 results[i] = emitLoad(fn, r)
2684 }
2685 fn.emit(&Return{Results: results, pos: e.pos})
2686
2687 case e.block != nil:
2688 // case EXIT(id): goto block
2689 emitJump(fn, e.block)
2690
2691 default:
2692 panic("unreachable")
2693 }
2694 fn.currentBlock = cndb
2695 }
2696 }
2697
2698 // stmt lowers statement s to SSA form, emitting code to fn.
2699 func (b *builder) stmt(fn *Function, _s ast.Stmt) {
2700 // The label of the current statement. If non-nil, its _goto
2701 // target is always set; its _break and _continue are set only
2702 // within the body of switch/typeswitch/select/for/range.
2703 // It is effectively an additional default-nil parameter of stmt().
2704 var label *lblock
2705 start:
2706 switch s := _s.(type) {
2707 case *ast.EmptyStmt:
2708 // ignore. (Usually removed by gofmt.)
2709
2710 case *ast.DeclStmt: // Con, Var or Typ
2711 d := s.Decl.(*ast.GenDecl)
2712 if d.Tok == token.VAR {
2713 for _, spec := range d.Specs {
2714 if vs, ok := spec.(*ast.ValueSpec); ok {
2715 b.localValueSpec(fn, vs)
2716 }
2717 }
2718 }
2719
2720 case *ast.LabeledStmt:
2721 if s.Label.Name == "_" {
2722 // Blank labels can't be the target of a goto, break,
2723 // or continue statement, so we don't need a new block.
2724 _s = s.Stmt
2725 goto start
2726 }
2727 label = fn.lblockOf(fn.label(s.Label))
2728 label.resolved = true
2729 emitJump(fn, label._goto)
2730 fn.currentBlock = label._goto
2731 _s = s.Stmt
2732 goto start // effectively: tailcall stmt(fn, s.Stmt, label)
2733
2734 case *ast.ExprStmt:
2735 b.expr(fn, s.X)
2736
2737 case *ast.SendStmt:
2738 chtyp := typeparams.CoreType(fn.typeOf(s.Chan)).(*types.Chan)
2739 fn.emit(&Send{
2740 Chan: b.expr(fn, s.Chan),
2741 X: emitConv(fn, b.expr(fn, s.Value), chtyp.Elem()),
2742 pos: s.Arrow,
2743 })
2744
2745 case *ast.IncDecStmt:
2746 op := token.ADD
2747 if s.Tok == token.DEC {
2748 op = token.SUB
2749 }
2750 loc := b.addr(fn, s.X, false)
2751 b.assignOp(fn, loc, NewConst(constant.MakeInt64(1), loc.typ()), op, s.Pos())
2752
2753 case *ast.AssignStmt:
2754 switch s.Tok {
2755 case token.ASSIGN, token.DEFINE:
2756 b.assignStmt(fn, s.Lhs, s.Rhs, s.Tok == token.DEFINE)
2757
2758 default: // +=, etc.
2759 op := s.Tok + token.ADD - token.ADD_ASSIGN
2760 b.assignOp(fn, b.addr(fn, s.Lhs[0], false), b.expr(fn, s.Rhs[0]), op, s.Pos())
2761 }
2762
2763 case *ast.GoStmt:
2764 // The "intrinsics" new/make/len/cap are forbidden here.
2765 // panic is treated like an ordinary function call.
2766 v := Go{pos: s.Go}
2767 b.setCall(fn, s.Call, &v.Call)
2768 fn.emit(&v)
2769
2770 case *ast.DeferStmt:
2771 // The "intrinsics" new/make/len/cap are forbidden here.
2772 // panic is treated like an ordinary function call.
2773 deferstack := emitLoad(fn, fn.lookup(fn.deferstack, false))
2774 v := Defer{pos: s.Defer, DeferStack: deferstack}
2775 b.setCall(fn, s.Call, &v.Call)
2776 fn.emit(&v)
2777
2778 // A deferred call can cause recovery from panic,
2779 // and control resumes at the Recover block.
2780 createRecoverBlock(fn.source)
2781
2782 case *ast.ReturnStmt:
2783 b.returnStmt(fn, s)
2784
2785 case *ast.BranchStmt:
2786 b.branchStmt(fn, s)
2787
2788 case *ast.BlockStmt:
2789 b.stmtList(fn, s.List)
2790
2791 case *ast.IfStmt:
2792 if s.Init != nil {
2793 b.stmt(fn, s.Init)
2794 }
2795 then := fn.newBasicBlock("if.then")
2796 done := fn.newBasicBlock("if.done")
2797 els := done
2798 if s.Else != nil {
2799 els = fn.newBasicBlock("if.else")
2800 }
2801 b.cond(fn, s.Cond, then, els)
2802 fn.currentBlock = then
2803 b.stmt(fn, s.Body)
2804 emitJump(fn, done)
2805
2806 if s.Else != nil {
2807 fn.currentBlock = els
2808 b.stmt(fn, s.Else)
2809 emitJump(fn, done)
2810 }
2811
2812 fn.currentBlock = done
2813
2814 case *ast.SwitchStmt:
2815 b.switchStmt(fn, s, label)
2816
2817 case *ast.TypeSwitchStmt:
2818 b.typeSwitchStmt(fn, s, label)
2819
2820 case *ast.SelectStmt:
2821 b.selectStmt(fn, s, label)
2822
2823 case *ast.ForStmt:
2824 b.forStmt(fn, s, label)
2825
2826 case *ast.RangeStmt:
2827 b.rangeStmt(fn, s, label)
2828
2829 default:
2830 panic(fmt.Sprintf("unexpected statement kind: %T", s))
2831 }
2832 }
2833
2834 func (b *builder) branchStmt(fn *Function, s *ast.BranchStmt) {
2835 var block *BasicBlock
2836 if s.Label == nil {
2837 block = targetedBlock(fn, s.Tok)
2838 } else {
2839 target := fn.label(s.Label)
2840 block = labelledBlock(fn, target, s.Tok)
2841 if block == nil { // forward goto
2842 lb := fn.lblockOf(target)
2843 block = lb._goto // jump to lb._goto
2844 if fn.jump != nil {
2845 // fn is a range-over-func and the goto may exit fn.
2846 // Create an exit and resolve it at the end of
2847 // builder.buildYieldFunc.
2848 labelExit(fn, target, s.Pos())
2849 }
2850 }
2851 }
2852 to := block.parent
2853
2854 if to == fn {
2855 emitJump(fn, block)
2856 } else { // break outside of fn.
2857 // fn must be a range-over-func
2858 e := blockExit(fn, block, s.Pos())
2859 storeVar(fn, fn.jump, intConst(e.id), e.pos)
2860 fn.emit(&Return{Results: []Value{vFalse}, pos: e.pos})
2861 }
2862 fn.currentBlock = fn.newBasicBlock("unreachable")
2863 }
2864
2865 func (b *builder) returnStmt(fn *Function, s *ast.ReturnStmt) {
2866 var results []Value
2867
2868 sig := fn.source.Signature // signature of the enclosing source function
2869
2870 // Convert return operands to result type.
2871 if len(s.Results) == 1 && sig.Results().Len() > 1 {
2872 // Return of one expression in a multi-valued function.
2873 tuple := b.exprN(fn, s.Results[0])
2874 ttuple := tuple.Type().(*types.Tuple)
2875 for i, n := 0, ttuple.Len(); i < n; i++ {
2876 results = append(results,
2877 emitConv(fn, emitExtract(fn, tuple, i),
2878 sig.Results().At(i).Type()))
2879 }
2880 } else {
2881 // 1:1 return, or no-arg return in non-void function.
2882 for i, r := range s.Results {
2883 v := emitConv(fn, b.expr(fn, r), sig.Results().At(i).Type())
2884 results = append(results, v)
2885 }
2886 }
2887
2888 // Store the results.
2889 for i, r := range results {
2890 var result Value // fn.source.result[i] conceptually
2891 if fn == fn.source {
2892 result = fn.results[i]
2893 } else { // lookup needed?
2894 result = fn.lookup(fn.returnVars[i], false)
2895 }
2896 emitStore(fn, result, r, s.Return)
2897 }
2898
2899 if fn.jump != nil {
2900 // Return from body of a range-over-func.
2901 // The return statement is syntactically within the loop,
2902 // but the generated code is in the 'switch jump {...}' after it.
2903 e := returnExit(fn, s.Pos())
2904 storeVar(fn, fn.jump, intConst(e.id), e.pos)
2905 fn.emit(&Return{Results: []Value{vFalse}, pos: e.pos})
2906 fn.currentBlock = fn.newBasicBlock("unreachable")
2907 return
2908 }
2909
2910 // Run function calls deferred in this
2911 // function when explicitly returning from it.
2912 fn.emit(new(RunDefers))
2913 // Reload (potentially) named result variables to form the result tuple.
2914 results = results[:0]
2915 for _, nr := range fn.results {
2916 results = append(results, emitLoad(fn, nr))
2917 }
2918 fn.emit(&Return{Results: results, pos: s.Return})
2919 fn.currentBlock = fn.newBasicBlock("unreachable")
2920 }
2921
2922 // A buildFunc is a strategy for building the SSA body for a function.
2923 type buildFunc = func(*builder, *Function)
2924
2925 // iterate causes all created but unbuilt functions to be built. As
2926 // this may create new methods, the process is iterated until it
2927 // converges.
2928 //
2929 // Waits for any dependencies to finish building.
2930 func (b *builder) iterate() {
2931 for ; b.finished < len(b.fns); b.finished++ {
2932 fn := b.fns[b.finished]
2933 b.buildFunction(fn)
2934 }
2935
2936 b.buildshared.markDone()
2937 b.buildshared.wait()
2938 }
2939
2940 // buildFunction builds SSA code for the body of function fn. Idempotent.
2941 func (b *builder) buildFunction(fn *Function) {
2942 if fn.build != nil {
2943 assert(fn.parent == nil, "anonymous functions should not be built by buildFunction()")
2944
2945 if fn.Prog.mode&LogSource != 0 {
2946 defer logStack("build %s @ %s", fn, fn.Prog.Fset.Position(fn.pos))()
2947 }
2948 fn.build(b, fn)
2949 fn.done()
2950 }
2951 }
2952
2953 // buildParamsOnly builds fn.Params from fn.Signature, but does not build fn.Body.
2954 func (b *builder) buildParamsOnly(fn *Function) {
2955 // For external (C, asm) functions or functions loaded from
2956 // export data, we must set fn.Params even though there is no
2957 // body code to reference them.
2958 if recv := fn.Signature.Recv(); recv != nil {
2959 fn.addParamVar(recv)
2960 }
2961 params := fn.Signature.Params()
2962 for i, n := 0, params.Len(); i < n; i++ {
2963 fn.addParamVar(params.At(i))
2964 }
2965
2966 // clear out other function state (keep consistent with finishBody)
2967 fn.subst = nil
2968 }
2969
2970 // buildFromSyntax builds fn.Body from fn.syntax, which must be non-nil.
2971 func (b *builder) buildFromSyntax(fn *Function) {
2972 var (
2973 recvField *ast.FieldList
2974 body *ast.BlockStmt
2975 functype *ast.FuncType
2976 )
2977 switch syntax := fn.syntax.(type) {
2978 case *ast.FuncDecl:
2979 functype = syntax.Type
2980 recvField = syntax.Recv
2981 body = syntax.Body
2982 if body == nil {
2983 b.buildParamsOnly(fn) // no body (non-Go function)
2984 return
2985 }
2986 case *ast.FuncLit:
2987 functype = syntax.Type
2988 body = syntax.Body
2989 case nil:
2990 panic("no syntax")
2991 default:
2992 panic(syntax) // unexpected syntax
2993 }
2994 fn.source = fn
2995 fn.startBody()
2996 fn.createSyntacticParams(recvField, functype)
2997 fn.createDeferStack()
2998 b.stmt(fn, body)
2999 if cb := fn.currentBlock; cb != nil && (cb == fn.Blocks[0] || cb == fn.Recover || cb.Preds != nil) {
3000 // Control fell off the end of the function's body block.
3001 //
3002 // Block optimizations eliminate the current block, if
3003 // unreachable. It is a builder invariant that
3004 // if this no-arg return is ill-typed for
3005 // fn.Signature.Results, this block must be
3006 // unreachable. The sanity checker checks this.
3007 fn.emit(new(RunDefers))
3008 fn.emit(new(Return))
3009 }
3010 fn.finishBody()
3011 }
3012
3013 // buildYieldFunc builds the body of the yield function created
3014 // from a range-over-func *ast.RangeStmt.
3015 func (b *builder) buildYieldFunc(fn *Function) {
3016 // See builder.rangeFunc for detailed documentation on how fn is set up.
3017 //
3018 // In pseudo-Go this roughly builds:
3019 // func yield(_k tk, _v tv) bool {
3020 // if jump != READY { panic("yield function called after range loop exit") }
3021 // jump = BUSY
3022 // k, v = _k, _v // assign the iterator variable (if needed)
3023 // ... // rng.Body
3024 // continue:
3025 // jump = READY
3026 // return true
3027 // }
3028 s := fn.syntax.(*ast.RangeStmt)
3029 fn.source = fn.parent.source
3030 fn.startBody()
3031 params := fn.Signature.Params()
3032 for v := range params.Variables() {
3033 fn.addParamVar(v)
3034 }
3035
3036 // Initial targets
3037 ycont := fn.newBasicBlock("yield-continue")
3038 // lblocks is either {} or is {label: nil} where label is the label of syntax.
3039 for label := range fn.lblocks {
3040 fn.lblocks[label] = &lblock{
3041 label: label,
3042 resolved: true,
3043 _goto: ycont,
3044 _continue: ycont,
3045 // `break label` statement targets fn.parent.targets._break
3046 }
3047 }
3048 fn.targets = &targets{
3049 tail: fn.targets,
3050 _continue: ycont,
3051 // `break` statement targets fn.parent.targets._break.
3052 }
3053
3054 // continue:
3055 // jump = READY
3056 // return true
3057 saved := fn.currentBlock
3058 fn.currentBlock = ycont
3059 storeVar(fn, fn.jump, jReady, s.Body.Rbrace)
3060 // A yield function's own deferstack is always empty, so rundefers is not needed.
3061 fn.emit(&Return{Results: []Value{vTrue}, pos: token.NoPos})
3062
3063 // Emit header:
3064 //
3065 // if jump != READY { panic("yield iterator accessed after exit") }
3066 // jump = BUSY
3067 // k, v = _k, _v
3068 fn.currentBlock = saved
3069 yloop := fn.newBasicBlock("yield-loop")
3070 invalid := fn.newBasicBlock("yield-invalid")
3071
3072 jumpVal := emitLoad(fn, fn.lookup(fn.jump, true))
3073 emitIf(fn, emitCompare(fn, token.EQL, jumpVal, jReady, token.NoPos), yloop, invalid)
3074 fn.currentBlock = invalid
3075 fn.emit(&Panic{
3076 X: emitConv(fn, stringConst("yield function called after range loop exit"), tEface),
3077 })
3078
3079 fn.currentBlock = yloop
3080 storeVar(fn, fn.jump, jBusy, s.Body.Rbrace)
3081
3082 // Initialize k and v from params.
3083 var tk, tv types.Type
3084 if s.Key != nil && !isBlankIdent(s.Key) {
3085 tk = fn.typeOf(s.Key) // fn.parent.typeOf is identical
3086 }
3087 if s.Value != nil && !isBlankIdent(s.Value) {
3088 tv = fn.typeOf(s.Value)
3089 }
3090 if s.Tok == token.DEFINE {
3091 if tk != nil {
3092 emitLocalVar(fn, identVar(fn, s.Key.(*ast.Ident)))
3093 }
3094 if tv != nil {
3095 emitLocalVar(fn, identVar(fn, s.Value.(*ast.Ident)))
3096 }
3097 }
3098 var k, v Value
3099 if len(fn.Params) > 0 {
3100 k = fn.Params[0]
3101 }
3102 if len(fn.Params) > 1 {
3103 v = fn.Params[1]
3104 }
3105 var kl, vl lvalue
3106 if tk != nil {
3107 kl = b.addr(fn, s.Key, false) // non-escaping
3108 }
3109 if tv != nil {
3110 vl = b.addr(fn, s.Value, false) // non-escaping
3111 }
3112 if tk != nil {
3113 kl.store(fn, k)
3114 }
3115 if tv != nil {
3116 vl.store(fn, v)
3117 }
3118
3119 // Build the body of the range loop.
3120 b.stmt(fn, s.Body)
3121 if cb := fn.currentBlock; cb != nil && (cb == fn.Blocks[0] || cb == fn.Recover || cb.Preds != nil) {
3122 // Control fell off the end of the function's body block.
3123 // Block optimizations eliminate the current block, if
3124 // unreachable.
3125 emitJump(fn, ycont)
3126 }
3127 // pop the stack for the yield function
3128 fn.targets = fn.targets.tail
3129
3130 // Clean up exits and promote any unresolved exits to fn.parent.
3131 for _, e := range fn.exits {
3132 if e.label != nil {
3133 lb := fn.lblocks[e.label]
3134 if lb.resolved {
3135 // label was resolved. Do not turn lb into an exit.
3136 // e does not need to be handled by the parent.
3137 continue
3138 }
3139
3140 // _goto becomes an exit.
3141 // _goto:
3142 // jump = id
3143 // return false
3144 fn.currentBlock = lb._goto
3145 id := intConst(e.id)
3146 storeVar(fn, fn.jump, id, e.pos)
3147 fn.emit(&Return{Results: []Value{vFalse}, pos: e.pos})
3148 }
3149
3150 if e.to != fn { // e needs to be handled by the parent too.
3151 fn.parent.exits = append(fn.parent.exits, e)
3152 }
3153 }
3154
3155 fn.finishBody()
3156 }
3157
3158 // addMakeInterfaceType records non-interface type t as the type of
3159 // the operand a MakeInterface operation, for [Program.RuntimeTypes].
3160 //
3161 // Acquires prog.makeInterfaceTypesMu.
3162 func addMakeInterfaceType(prog *Program, t types.Type) {
3163 prog.makeInterfaceTypesMu.Lock()
3164 defer prog.makeInterfaceTypesMu.Unlock()
3165 if prog.makeInterfaceTypes == nil {
3166 prog.makeInterfaceTypes = make(map[types.Type]unit)
3167 }
3168 prog.makeInterfaceTypes[t] = unit{}
3169 }
3170
3171 // Build calls Package.Build for each package in prog.
3172 // Building occurs in parallel unless the BuildSerially mode flag was set.
3173 //
3174 // Build is intended for whole-program analysis; a typical compiler
3175 // need only build a single package.
3176 //
3177 // Build is idempotent and thread-safe.
3178 func (prog *Program) Build() {
3179 var wg sync.WaitGroup
3180 for _, p := range prog.packages {
3181 if prog.mode&BuildSerially != 0 {
3182 p.Build()
3183 } else {
3184 wg.Add(1)
3185 cpuLimit <- unit{} // acquire a token
3186 go func(p *Package) {
3187 p.Build()
3188 wg.Done()
3189 <-cpuLimit // release a token
3190 }(p)
3191 }
3192 }
3193 wg.Wait()
3194 }
3195
3196 // cpuLimit is a counting semaphore to limit CPU parallelism.
3197 var cpuLimit = make(chan unit, runtime.GOMAXPROCS(0))
3198
3199 // Build builds SSA code for all functions and vars in package p.
3200 //
3201 // CreatePackage must have been called for all of p's direct imports
3202 // (and hence its direct imports must have been error-free). It is not
3203 // necessary to call CreatePackage for indirect dependencies.
3204 // Functions will be created for all necessary methods in those
3205 // packages on demand.
3206 //
3207 // Build is idempotent and thread-safe.
3208 func (p *Package) Build() { p.buildOnce.Do(p.build) }
3209
3210 func (p *Package) build() {
3211 if p.info == nil {
3212 return // synthetic package, e.g. "testmain"
3213 }
3214 if p.Prog.mode&LogSource != 0 {
3215 defer logStack("build %s", p)()
3216 }
3217
3218 b := builder{fns: p.created}
3219 b.iterate()
3220
3221 // We no longer need transient information: ASTs or go/types deductions.
3222 p.info = nil
3223 p.created = nil
3224 p.files = nil
3225 p.initVersion = nil
3226
3227 if p.Prog.mode&SanityCheckFunctions != 0 {
3228 sanityCheckPackage(p)
3229 }
3230 }
3231
3232 // buildPackageInit builds fn.Body for the synthetic package initializer.
3233 func (b *builder) buildPackageInit(fn *Function) {
3234 p := fn.Pkg
3235 fn.startBody()
3236
3237 var done *BasicBlock
3238
3239 if p.Prog.mode&BareInits == 0 {
3240 // Make init() skip if package is already initialized.
3241 initguard := p.Var("init$guard")
3242 doinit := fn.newBasicBlock("init.start")
3243 done = fn.newBasicBlock("init.done")
3244 emitIf(fn, emitLoad(fn, initguard), done, doinit)
3245 fn.currentBlock = doinit
3246 emitStore(fn, initguard, vTrue, token.NoPos)
3247
3248 // Call the init() function of each package we import.
3249 for _, pkg := range p.Pkg.Imports() {
3250 prereq := p.Prog.packages[pkg]
3251 if prereq == nil {
3252 panic(fmt.Sprintf("Package(%q).Build(): unsatisfied import: Program.CreatePackage(%q) was not called", p.Pkg.Path(), pkg.Path()))
3253 }
3254 var v Call
3255 v.Call.Value = prereq.init
3256 v.Call.pos = fn.pos
3257 v.setType(types.NewTuple())
3258 fn.emit(&v)
3259 }
3260 }
3261
3262 // Initialize package-level vars in correct order.
3263 if len(p.info.InitOrder) > 0 && len(p.files) == 0 {
3264 panic("no source files provided for package. cannot initialize globals")
3265 }
3266
3267 for _, varinit := range p.info.InitOrder {
3268 if fn.Prog.mode&LogSource != 0 {
3269 fmt.Fprintf(os.Stderr, "build global initializer %v @ %s\n",
3270 varinit.Lhs, p.Prog.Fset.Position(varinit.Rhs.Pos()))
3271 }
3272 // Initializers for global vars are evaluated in dependency
3273 // order, but may come from arbitrary files of the package
3274 // with different versions, so we transiently update
3275 // fn.goversion for each one. (Since init is a synthetic
3276 // function it has no syntax of its own that needs a version.)
3277 fn.goversion = p.initVersion[varinit.Rhs]
3278 if len(varinit.Lhs) == 1 {
3279 // 1:1 initialization: var x, y = a(), b()
3280 var lval lvalue
3281 if v := varinit.Lhs[0]; v.Name() != "_" {
3282 lval = &address{addr: p.objects[v].(*Global), pos: v.Pos()}
3283 } else {
3284 lval = blank{}
3285 }
3286 b.assign(fn, lval, varinit.Rhs, true, nil)
3287 } else {
3288 // n:1 initialization: var x, y := f()
3289 tuple := b.exprN(fn, varinit.Rhs)
3290 for i, v := range varinit.Lhs {
3291 if v.Name() == "_" {
3292 continue
3293 }
3294 emitStore(fn, p.objects[v].(*Global), emitExtract(fn, tuple, i), v.Pos())
3295 }
3296 }
3297 }
3298
3299 // The rest of the init function is synthetic:
3300 // no syntax, info, goversion.
3301 fn.info = nil
3302 fn.goversion = ""
3303
3304 // Call all of the declared init() functions in source order.
3305 for _, file := range p.files {
3306 for _, decl := range file.Decls {
3307 if decl, ok := decl.(*ast.FuncDecl); ok {
3308 id := decl.Name
3309 if !isBlankIdent(id) && id.Name == "init" && decl.Recv == nil {
3310 declaredInit := p.objects[p.info.Defs[id]].(*Function)
3311 var v Call
3312 v.Call.Value = declaredInit
3313 v.setType(types.NewTuple())
3314 p.init.emit(&v)
3315 }
3316 }
3317 }
3318 }
3319
3320 // Finish up init().
3321 if p.Prog.mode&BareInits == 0 {
3322 emitJump(fn, done)
3323 fn.currentBlock = done
3324 }
3325 fn.emit(new(Return))
3326 fn.finishBody()
3327 }