Debian Codegraph @

go/ir/emit.go

raw
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 ir
6
7 // Helpers for emitting IR instructions.
8
9 import (
10 "fmt"
11 "go/ast"
12 "go/constant"
13 "go/token"
14 "go/types"
15
16 "golang.org/x/exp/typeparams"
17 )
18
19 // emitAlloc emits to f a new Alloc instruction allocating a variable
20 // of type typ.
21 //
22 // The caller must set Alloc.Heap=true (for a heap-allocated variable)
23 // or add the Alloc to f.Locals (for a frame-allocated variable).
24 //
25 // During building, a variable in f.Locals may have its Heap flag
26 // set when it is discovered that its address is taken.
27 // These Allocs are removed from f.Locals at the end.
28 //
29 // The builder should generally call one of the emit{New,Local,LocalVar} wrappers instead.
30 func emitAlloc(f *Function, typ types.Type, source ast.Node, comment string) *Alloc {
31 v := &Alloc{}
32 v.comment = comment
33 v.setType(types.NewPointer(typ))
34 f.emit(v, source)
35 return v
36 }
37
38 // emitNew emits to f a new Alloc instruction heap-allocating a
39 // variable of type typ.
40 func emitNew(f *Function, typ types.Type, source ast.Node, comment string) *Alloc {
41 alloc := emitAlloc(f, typ, source, comment)
42 alloc.Heap = true
43 return alloc
44 }
45
46 // emitLocal creates a local var for (t, source, comment) and
47 // emits an Alloc instruction for it.
48 //
49 // (Use this function or emitNew for synthetic variables;
50 // for source-level variables in the same function, use emitLocalVar.)
51 func emitLocal(f *Function, t types.Type, source ast.Node, comment string) *Alloc {
52 local := emitAlloc(f, t, source, comment)
53 f.Locals = append(f.Locals, local)
54 return local
55 }
56
57 // emitLocalVar creates a local var for v and emits an Alloc instruction for it.
58 // Subsequent calls to f.lookup(v) return it.
59 // It applies the appropriate generic instantiation to the type.
60 func emitLocalVar(f *Function, v *types.Var, source ast.Node) *Alloc {
61 alloc := emitLocal(f, f.typ(v.Type()), source, v.Name())
62 f.vars[v] = alloc
63 return alloc
64 }
65
66 // emitLoad emits to f an instruction to load the address addr into a
67 // new temporary, and returns the value so defined.
68 func emitLoad(f *Function, addr Value, source ast.Node) *Load {
69 v := &Load{X: addr}
70 v.setType(deref(addr.Type()))
71 f.emit(v, source)
72 return v
73 }
74
75 func emitRecv(f *Function, ch Value, commaOk bool, typ types.Type, source ast.Node) Value {
76 recv := &Recv{
77 Chan: ch,
78 CommaOk: commaOk,
79 }
80 recv.setType(typ)
81 return f.emit(recv, source)
82 }
83
84 // emitDebugRef emits to f a DebugRef pseudo-instruction associating
85 // expression e with value v.
86 func emitDebugRef(f *Function, e ast.Expr, v Value, isAddr bool) {
87 ref := makeDebugRef(f, e, v, isAddr)
88 if ref == nil {
89 return
90 }
91 f.emit(ref, nil)
92 }
93
94 func makeDebugRef(f *Function, e ast.Expr, v Value, isAddr bool) *debugRef {
95 if !f.debugInfo() {
96 return nil // debugging not enabled
97 }
98 if v == nil || e == nil {
99 panic("nil")
100 }
101 var obj types.Object
102 e = ast.Unparen(e)
103 if id, ok := e.(*ast.Ident); ok {
104 if isBlankIdent(id) {
105 return nil
106 }
107 obj = f.objectOf(id)
108 switch obj.(type) {
109 case *types.Nil, *types.Const, *types.Builtin:
110 return nil
111 }
112 }
113 return &debugRef{
114 X: v,
115 Expr: e,
116 IsAddr: isAddr,
117 object: obj,
118 }
119 }
120
121 // emitArith emits to f code to compute the binary operation op(x, y)
122 // where op is an eager shift, logical or arithmetic operation.
123 // (Use emitCompare() for comparisons and Builder.logicalBinop() for
124 // non-eager operations.)
125 func emitArith(f *Function, op token.Token, x, y Value, t types.Type, source ast.Node) Value {
126 switch op {
127 case token.SHL, token.SHR:
128 x = emitConv(f, x, t, source)
129 // y may be signed or an 'untyped' constant.
130 // There is a runtime panic if y is signed and <0. Instead of inserting a check for y<0
131 // and converting to an unsigned value (like the compiler) leave y as is.
132 if b, ok := y.Type().Underlying().(*types.Basic); ok && b.Info()&types.IsUntyped != 0 {
133 // Untyped conversion:
134 // Spec https://go.dev/ref/spec#Operators:
135 // The right operand in a shift expression must have integer type or be an untyped constant
136 // representable by a value of type uint.
137 y = emitConv(f, y, types.Typ[types.Uint], source)
138 }
139
140 case token.ADD, token.SUB, token.MUL, token.QUO, token.REM, token.AND, token.OR, token.XOR, token.AND_NOT:
141 x = emitConv(f, x, t, source)
142 y = emitConv(f, y, t, source)
143
144 default:
145 panic("illegal op in emitArith: " + op.String())
146
147 }
148 v := &BinOp{
149 Op: op,
150 X: x,
151 Y: y,
152 }
153 v.setType(t)
154 return f.emit(v, source)
155 }
156
157 // emitCompare emits to f code compute the boolean result of
158 // comparison 'x op y'.
159 func emitCompare(f *Function, op token.Token, x, y Value, source ast.Node) Value {
160 xt := x.Type().Underlying()
161 yt := y.Type().Underlying()
162
163 // Special case to optimise a tagless SwitchStmt so that
164 // these are equivalent
165 // switch { case e: ...}
166 // switch true { case e: ... }
167 // if e==true { ... }
168 // even in the case when e's type is an interface.
169 // TODO(adonovan): opt: generalise to x==true, false!=y, etc.
170 if x, ok := x.(*Const); ok && op == token.EQL && x.Value != nil && x.Value.Kind() == constant.Bool && constant.BoolVal(x.Value) {
171 if yt, ok := yt.(*types.Basic); ok && yt.Info()&types.IsBoolean != 0 {
172 return y
173 }
174 }
175
176 if types.Identical(xt, yt) {
177 // no conversion necessary
178 } else if _, ok := xt.(*types.Interface); ok && !typeparams.IsTypeParam(x.Type()) {
179 y = emitConv(f, y, x.Type(), source)
180 } else if _, ok := yt.(*types.Interface); ok && !typeparams.IsTypeParam(y.Type()) {
181 x = emitConv(f, x, y.Type(), source)
182 } else if _, ok := x.(*Const); ok {
183 x = emitConv(f, x, y.Type(), source)
184 } else if _, ok := y.(*Const); ok {
185 y = emitConv(f, y, x.Type(), source)
186 //lint:ignore SA9003 no-op
187 } else {
188 // other cases, e.g. channels. No-op.
189 }
190
191 v := &BinOp{
192 Op: op,
193 X: x,
194 Y: y,
195 }
196 v.setType(tBool)
197 return f.emit(v, source)
198 }
199
200 // isValuePreserving returns true if a conversion from ut_src to
201 // ut_dst is value-preserving, i.e. just a change of type.
202 // Precondition: neither argument is a named or alias type.
203 func isValuePreserving(ut_src, ut_dst types.Type) bool {
204 // Identical underlying types?
205 if types.IdenticalIgnoreTags(ut_dst, ut_src) {
206 return true
207 }
208
209 switch ut_dst.(type) {
210 case *types.Chan:
211 // Conversion between channel types?
212 _, ok := ut_src.(*types.Chan)
213 return ok
214
215 case *types.Pointer:
216 // Conversion between pointers with identical base types?
217 _, ok := ut_src.(*types.Pointer)
218 return ok
219 }
220 return false
221 }
222
223 // emitConv emits to f code to convert Value val to exactly type typ,
224 // and returns the converted value. Implicit conversions are required
225 // by language assignability rules in assignments, parameter passing,
226 // etc.
227 func emitConv(f *Function, val Value, t_dst types.Type, source ast.Node) Value {
228 t_src := val.Type()
229
230 // Identical types? Conversion is a no-op.
231 if types.Identical(t_src, t_dst) {
232 return val
233 }
234
235 ut_dst := t_dst.Underlying()
236 ut_src := t_src.Underlying()
237
238 // Conversion to, or construction of a value of, an interface type?
239 if isNonTypeParamInterface(t_dst) {
240 // Interface name change?
241 if isValuePreserving(ut_src, ut_dst) {
242 c := &ChangeType{X: val}
243 c.setType(t_dst)
244 return f.emit(c, source)
245 }
246
247 // Assignment from one interface type to another?
248 if isNonTypeParamInterface(t_src) {
249 c := &ChangeInterface{X: val}
250 c.setType(t_dst)
251 return f.emit(c, source)
252 }
253
254 // Untyped nil constant? Return interface-typed nil constant.
255 if ut_src == tUntypedNil {
256 return zeroConst(t_dst, source)
257 }
258
259 // Convert (non-nil) "untyped" literals to their default type.
260 if t, ok := ut_src.(*types.Basic); ok && t.Info()&types.IsUntyped != 0 {
261 val = emitConv(f, val, types.Default(ut_src), source)
262 }
263
264 // Record the types of operands to MakeInterface, if
265 // non-parameterized, as they are the set of runtime types.
266 t := val.Type()
267 if !f.Prog.isParameterized(t) {
268 addMakeInterfaceType(f.Prog, t)
269 }
270
271 mi := &MakeInterface{X: val}
272 mi.setType(t_dst)
273 return f.emit(mi, source)
274 }
275
276 // conversionCase describes an instruction pattern that maybe emitted to
277 // model d <- s for d in dst_terms and s in src_terms.
278 // Multiple conversions can match the same pattern.
279 type conversionCase uint8
280 const (
281 changeType conversionCase = 1 << iota
282 sliceToArray
283 sliceToArrayPtr
284 sliceTo0Array
285 sliceTo0ArrayPtr
286 convert
287 )
288 // classify the conversion case of a source type us to a destination type ud.
289 // us and ud are underlying types (not *Named or *Alias)
290 classify := func(s, d types.Type) conversionCase {
291 // Just a change of type, but not value or representation?
292 if isValuePreserving(s, d) {
293 return changeType
294 }
295
296 // Conversion from slice to array or slice to array pointer?
297 if slice, ok := s.(*types.Slice); ok {
298 var arr *types.Array
299 var ptr bool
300 // Conversion from slice to array pointer?
301 switch d := d.(type) {
302 case *types.Array:
303 arr = d
304 case *types.Pointer:
305 arr, _ = d.Elem().Underlying().(*types.Array)
306 ptr = true
307 }
308 if arr != nil && types.Identical(slice.Elem(), arr.Elem()) {
309 if arr.Len() == 0 {
310 if ptr {
311 return sliceTo0ArrayPtr
312 } else {
313 return sliceTo0Array
314 }
315 }
316 if ptr {
317 return sliceToArrayPtr
318 } else {
319 return sliceToArray
320 }
321 }
322 }
323
324 // The only remaining case in well-typed code is a representation-
325 // changing conversion of basic types (possibly with []byte/[]rune).
326 if !isBasic(s) && !isBasic(d) {
327 panic(fmt.Sprintf("in %s: cannot convert term %s (%s [within %s]) to type %s [within %s]", f, val, val.Type(), s, t_dst, d))
328 }
329 return convert
330 }
331
332 var classifications conversionCase
333 underIs(ut_src, func(us types.Type) bool {
334 return underIs(ut_dst, func(ud types.Type) bool {
335 if us != nil && ud != nil {
336 classifications |= classify(us, ud)
337 }
338 return classifications != 0
339 })
340 })
341 if classifications == 0 {
342 panic(fmt.Sprintf("in %s: cannot convert %s (%s) to %s", f, val, val.Type(), t_dst))
343 }
344
345 // Conversion of a compile-time constant value?
346 if c, ok := val.(*Const); ok {
347 // Conversion to a basic type?
348 if isBasic(ut_dst) {
349 // Conversion of a compile-time constant to
350 // another constant type results in a new
351 // constant of the destination type and
352 // (initially) the same abstract value.
353 // We don't truncate the value yet.
354 return NewConst(c.Value, t_dst, source)
355 }
356 // Can we always convert from zero value without panicking?
357 const mayPanic = sliceToArray | sliceToArrayPtr
358 if c.Value == nil && classifications&mayPanic == 0 {
359 return NewConst(nil, t_dst, source)
360 }
361
362 // We're converting from constant to non-constant type,
363 // e.g. string -> []byte/[]rune.
364 }
365
366 switch classifications {
367 case changeType: // representation-preserving change
368 c := &ChangeType{X: val}
369 c.setType(t_dst)
370 return f.emit(c, source)
371
372 case sliceToArrayPtr, sliceTo0ArrayPtr: // slice to array pointer
373 c := &SliceToArrayPointer{X: val}
374 c.setType(t_dst)
375 return f.emit(c, source)
376
377 case sliceToArray: // slice to arrays (not zero-length)
378 p := &SliceToArray{X: val}
379 p.setType(t_dst)
380 return f.emit(p, source)
381
382 case sliceTo0Array: // slice to zero-length arrays (constant)
383 return zeroConst(t_dst, source)
384
385 case convert: // representation-changing conversion
386 c := &Convert{X: val}
387 c.setType(t_dst)
388 return f.emit(c, source)
389
390 default: // The conversion represents a cross product.
391 c := &MultiConvert{X: val, from: t_src, to: t_dst}
392 c.setType(t_dst)
393 return f.emit(c, source)
394 }
395 }
396
397 // emitTypeCoercion emits to f code to coerce the type of a
398 // Value v to exactly type typ, and returns the coerced value.
399 //
400 // Requires that coercing v.Typ() to typ is a value preserving change.
401 //
402 // Currently used only when v.Type() is a type instance of typ or vice versa.
403 // A type v is a type instance of a type t if there exists a
404 // type parameter substitution σ s.t. σ(v) == t. Example:
405 //
406 // σ(func(T) T) == func(int) int for σ == [T ↦ int]
407 //
408 // This happens in instantiation wrappers for conversion
409 // from an instantiation to a parameterized type (and vice versa)
410 // with σ substituting f.typeparams by f.typeargs.
411 func emitTypeCoercion(f *Function, v Value, typ types.Type, source ast.Node) Value {
412 if types.Identical(v.Type(), typ) {
413 return v // no coercion needed
414 }
415 // TODO(taking): for instances should we record which side is the instance?
416 c := &ChangeType{
417 X: v,
418 }
419 c.setType(typ)
420 f.emit(c, source)
421 return c
422 }
423
424 // emitStore emits to f an instruction to store value val at location
425 // addr, applying implicit conversions as required by assignability rules.
426 func emitStore(f *Function, addr, val Value, source ast.Node) *Store {
427 typ := deref(addr.Type())
428 s := &Store{
429 Addr: addr,
430 Val: emitConv(f, val, typ, source),
431 }
432 f.emit(s, source)
433 return s
434 }
435
436 // emitJump emits to f a jump to target, and updates the control-flow graph.
437 // Postcondition: f.currentBlock is nil.
438 func emitJump(f *Function, target *BasicBlock, source ast.Node) *Jump {
439 b := f.currentBlock
440 j := new(Jump)
441 b.emit(j, source)
442 addEdge(b, target)
443 f.currentBlock = nil
444 return j
445 }
446
447 // emitIf emits to f a conditional jump to tblock or fblock based on
448 // cond, and updates the control-flow graph.
449 // Postcondition: f.currentBlock is nil.
450 func emitIf(f *Function, cond Value, tblock, fblock *BasicBlock, source ast.Node) *If {
451 b := f.currentBlock
452 stmt := &If{Cond: cond}
453 b.emit(stmt, source)
454 addEdge(b, tblock)
455 addEdge(b, fblock)
456 f.currentBlock = nil
457 return stmt
458 }
459
460 // emitExtract emits to f an instruction to extract the index'th
461 // component of tuple. It returns the extracted value.
462 func emitExtract(f *Function, tuple Value, index int, source ast.Node) Value {
463 e := &Extract{Tuple: tuple, Index: index}
464 e.setType(tuple.Type().(*types.Tuple).At(index).Type())
465 return f.emit(e, source)
466 }
467
468 // emitTypeAssert emits to f a type assertion value := x.(t) and
469 // returns the value. x.Type() must be an interface.
470 func emitTypeAssert(f *Function, x Value, t types.Type, source ast.Node) Value {
471 a := &TypeAssert{X: x, AssertedType: t}
472 a.setType(t)
473 return f.emit(a, source)
474 }
475
476 // emitTypeTest emits to f a type test value,ok := x.(t) and returns
477 // a (value, ok) tuple. x.Type() must be an interface.
478 func emitTypeTest(f *Function, x Value, t types.Type, source ast.Node) Value {
479 a := &TypeAssert{
480 X: x,
481 AssertedType: t,
482 CommaOk: true,
483 }
484 a.setType(types.NewTuple(
485 newVar("value", t),
486 varOk,
487 ))
488 return f.emit(a, source)
489 }
490
491 // emitTailCall emits to f a function call in tail position. The
492 // caller is responsible for all fields of 'call' except its type.
493 // Intended for wrapper methods.
494 // Precondition: f does/will not use deferred procedure calls.
495 // Postcondition: f.currentBlock is nil.
496 func emitTailCall(f *Function, call *Call, source ast.Node) {
497 tresults := f.Signature.Results()
498 nr := tresults.Len()
499 if nr == 1 {
500 call.typ = tresults.At(0).Type()
501 } else {
502 call.typ = tresults
503 }
504 tuple := emitCall(f, call, source)
505 var ret Return
506 switch nr {
507 case 0:
508 // no-op
509 case 1:
510 ret.Results = []Value{tuple}
511 default:
512 for i := range nr {
513 v := emitExtract(f, tuple, i, source)
514 // TODO(adonovan): in principle, this is required:
515 // v = emitConv(f, o.Type, f.Signature.Results[i].Type)
516 // but in practice emitTailCall is only used when
517 // the types exactly match.
518 ret.Results = append(ret.Results, v)
519 }
520 }
521
522 f.emit(&ret, source)
523 f.currentBlock = nil
524 }
525
526 // emitCall emits a call instruction. If the callee is "no return",
527 // it also emits a panic to eliminate infeasible CFG edges.
528 func emitCall(fn *Function, call *Call, source ast.Node) Value {
529 res := fn.emit(call, source)
530
531 callee := call.Call.StaticCallee()
532 if callee != nil &&
533 callee.object != nil &&
534 fn.Prog.noReturn != nil &&
535 fn.Prog.noReturn(callee.object) {
536 // Call doesn't return normally. Either it doesn't return at all
537 // (infinitely blocked or exitting the process), or it unwinds the stack
538 // (panic, runtime.Goexit). Model this as a panic.
539 fn.emit(&Panic{
540 X: emitConv(fn, vNoReturn, tEface, source),
541 }, source)
542 fn.currentBlock = fn.newBasicBlock("unreachable")
543 }
544
545 return res
546 }
547
548 // emitImplicitSelections emits to f code to apply the sequence of
549 // implicit field selections specified by indices to base value v, and
550 // returns the selected value.
551 //
552 // If v is the address of a struct, the result will be the address of
553 // a field; if it is the value of a struct, the result will be the
554 // value of a field.
555 func emitImplicitSelections(f *Function, v Value, indices []int, source ast.Node) Value {
556 for _, index := range indices {
557 // We may have a generic type containing a pointer, or a pointer to a generic type containing a struct. A
558 // pointer to a generic containing a pointer to a struct shouldn't be possible because the outer pointer gets
559 // dereferenced implicitly before we get here.
560 if isPointerCore(v.Type()) {
561 fld := fieldOf(deref(v.Type()), index)
562 instr := &FieldAddr{
563 X: v,
564 Field: index,
565 }
566 instr.setType(types.NewPointer(fld.Type()))
567 v = f.emit(instr, source)
568 // Load the field's value iff indirectly embedded.
569 if isPointerCore(fld.Type()) {
570 v = emitLoad(f, v, source)
571 }
572 } else {
573 fld := fieldOf(v.Type(), index)
574 instr := &Field{
575 X: v,
576 Field: index,
577 }
578 instr.setType(fld.Type())
579 v = f.emit(instr, source)
580 }
581 }
582 return v
583 }
584
585 // emitFieldSelection emits to f code to select the index'th field of v.
586 //
587 // If wantAddr, the input must be a pointer-to-struct and the result
588 // will be the field's address; otherwise the result will be the
589 // field's value.
590 // Ident id is used for position and debug info.
591 func emitFieldSelection(f *Function, v Value, index int, wantAddr bool, id *ast.Ident) Value {
592 if isPointerCore(v.Type()) {
593 fld := fieldOf(deref(v.Type()), index)
594 instr := &FieldAddr{
595 X: v,
596 Field: index,
597 }
598 instr.setSource(id)
599 instr.setType(types.NewPointer(fld.Type()))
600 v = f.emit(instr, id)
601 // Load the field's value iff we don't want its address.
602 if !wantAddr {
603 v = emitLoad(f, v, id)
604 }
605 } else {
606 fld := fieldOf(v.Type(), index)
607 instr := &Field{
608 X: v,
609 Field: index,
610 }
611 instr.setSource(id)
612 instr.setType(fld.Type())
613 v = f.emit(instr, id)
614 }
615 emitDebugRef(f, id, v, wantAddr)
616 return v
617 }
618
619 // createRecoverBlock emits to f a block of code to return after a
620 // recovered panic, and sets f.Recover to it.
621 //
622 // If f's result parameters are named, the code loads and returns
623 // their current values, otherwise it returns the zero values of their
624 // type.
625 //
626 // Idempotent.
627 func createRecoverBlock(f *Function) {
628 if f.Recover != nil {
629 return // already created
630 }
631 saved := f.currentBlock
632
633 f.Recover = f.newBasicBlock("recover")
634 f.currentBlock = f.Recover
635
636 var results []Value
637 // Reload NRPs to form value tuple.
638 for _, nr := range f.results {
639 results = append(results, emitLoad(f, nr, nr.source))
640 }
641
642 f.emit(&Return{Results: results}, nil)
643
644 f.currentBlock = saved
645 }