Debian Codegraph @

go/ir/lift.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 // This file defines the lifting pass which tries to "lift" Alloc
8 // cells (new/local variables) into SSA registers, replacing loads
9 // with the dominating stored value, eliminating loads and stores, and
10 // inserting φ-nodes as needed.
11
12 // Cited papers and resources:
13 //
14 // Ron Cytron et al. 1991. Efficiently computing SSA form...
15 // https://doi.acm.org/10.1145/115372.115320
16 //
17 // Cooper, Harvey, Kennedy. 2001. A Simple, Fast Dominance Algorithm.
18 // Software Practice and Experience 2001, 4:1-10.
19 // https://www.hipersoft.rice.edu/grads/publications/dom14.pdf
20 //
21 // Daniel Berlin, llvmdev mailing list, 2012.
22 // https://lists.cs.uiuc.edu/pipermail/llvmdev/2012-January/046638.html
23 // (Be sure to expand the whole thread.)
24 //
25 // C. Scott Ananian. 1997. The static single information form.
26 //
27 // Jeremy Singer. 2006. Static program analysis based on virtual register renaming.
28
29 // TODO(adonovan): opt: there are many optimizations worth evaluating, and
30 // the conventional wisdom for SSA construction is that a simple
31 // algorithm well engineered often beats those of better asymptotic
32 // complexity on all but the most egregious inputs.
33 //
34 // Danny Berlin suggests that the Cooper et al. algorithm for
35 // computing the dominance frontier is superior to Cytron et al.
36 // Furthermore he recommends that rather than computing the DF for the
37 // whole function then renaming all alloc cells, it may be cheaper to
38 // compute the DF for each alloc cell separately and throw it away.
39 //
40 // Consider exploiting liveness information to avoid creating dead
41 // φ-nodes which we then immediately remove.
42 //
43 // Also see many other "TODO: opt" suggestions in the code.
44
45 import (
46 "fmt"
47 "os"
48 "slices"
49 )
50
51 // If true, show diagnostic information at each step of lifting.
52 // Very verbose.
53 const debugLifting = false
54
55 // domFrontier maps each block to the set of blocks in its dominance
56 // frontier. The outer slice is conceptually a map keyed by
57 // Block.Index. The inner slice is conceptually a set, possibly
58 // containing duplicates.
59 //
60 // TODO(adonovan): opt: measure impact of dups; consider a packed bit
61 // representation, e.g. big.Int, and bitwise parallel operations for
62 // the union step in the Children loop.
63 //
64 // domFrontier's methods mutate the slice's elements but not its
65 // length, so their receivers needn't be pointers.
66 type domFrontier BlockMap[[]*BasicBlock]
67
68 func (df domFrontier) add(u, v *BasicBlock) {
69 df[u.Index] = append(df[u.Index], v)
70 }
71
72 // build builds the dominance frontier df for the dominator tree of
73 // fn, using the algorithm found in A Simple, Fast Dominance
74 // Algorithm, Figure 5.
75 //
76 // TODO(adonovan): opt: consider Berlin approach, computing pruned SSA
77 // by pruning the entire IDF computation, rather than merely pruning
78 // the DF -> IDF step.
79 func (df domFrontier) build(fn *Function) {
80 for _, b := range fn.Blocks {
81 if len(b.Preds) >= 2 {
82 for _, p := range b.Preds {
83 runner := p
84 for runner != b.dom.idom {
85 df.add(runner, b)
86 runner = runner.dom.idom
87 }
88 }
89 }
90 }
91 }
92
93 func buildDomFrontier(fn *Function) domFrontier {
94 df := make(domFrontier, len(fn.Blocks))
95 df.build(fn)
96 return df
97 }
98
99 func removeInstr(refs []Instruction, instr Instruction) []Instruction {
100 s := refs
101 i := -1
102 for j := range s {
103 if instr == s[j] {
104 i = j
105 break
106 }
107 }
108 if i == -1 {
109 return s
110 }
111 // Don't start copying elements until we find one to delete.
112 for j := i + 1; j < len(s); j++ {
113 if v := s[j]; v != instr {
114 s[i] = v
115 i++
116 }
117 }
118 clear(s[i:]) // zero/nil out the obsolete elements, for GC
119 return s[:i]
120 }
121
122 func clearInstrs(instrs []Instruction) {
123 for i := range instrs {
124 instrs[i] = nil
125 }
126 }
127
128 func numberNodesPerBlock(f *Function) {
129 for _, b := range f.Blocks {
130 var base ID
131 for _, instr := range b.Instrs {
132 if instr == nil {
133 continue
134 }
135 instr.setID(base)
136 base++
137 }
138 }
139 }
140
141 // lift replaces local and new Allocs accessed only with
142 // load/store by IR registers, inserting φ-nodes where necessary.
143 // The result is a program in pruned SSA form.
144 //
145 // Preconditions:
146 // - fn has no dead blocks (blockopt has run).
147 // - Def/use info (Operands and Referrers) is up-to-date.
148 // - The dominator tree is up-to-date.
149 func lift(fn *Function) bool {
150 // TODO(adonovan): opt: lots of little optimizations may be
151 // worthwhile here, especially if they cause us to avoid
152 // buildDomFrontier. For example:
153 //
154 // - Alloc never loaded? Eliminate.
155 // - Alloc never stored? Replace all loads with a zero constant.
156 // - Alloc stored once? Replace loads with dominating store;
157 // don't forget that an Alloc is itself an effective store
158 // of zero.
159 // - Alloc used only within a single block?
160 // Use degenerate algorithm avoiding φ-nodes.
161 // - Consider synergy with scalar replacement of aggregates (SRA).
162 // e.g. *(&x.f) where x is an Alloc.
163 // Perhaps we'd get better results if we generated this as x.f
164 // i.e. Field(x, .f) instead of Load(FieldIndex(x, .f)).
165 // Unclear.
166 //
167 // But we will start with the simplest correct code.
168 var df domFrontier
169 var newPhis BlockMap[[]newPhi]
170
171 // During this pass we will replace some BasicBlock.Instrs
172 // (allocs, loads and stores) with nil, keeping a count in
173 // BasicBlock.gaps. At the end we will reset Instrs to the
174 // concatenation of all non-dead newPhis and non-nil Instrs
175 // for the block, reusing the original array if space permits.
176
177 // While we're here, we also eliminate 'rundefers'
178 // instructions and ssa:deferstack() in functions that contain no
179 // 'defer' instructions. Eliminate ssa:deferstack() if it does not
180 // escape.
181 usesDefer := false
182 deferstackAlloc, deferstackCall := deferstackPreamble(fn)
183 eliminateDeferStack := deferstackAlloc != nil && !deferstackAlloc.Heap
184
185 // Determine which allocs we can lift and number them densely.
186 // The renaming phase uses this numbering for compact maps.
187 numAllocs := 0
188
189 instructions := make(BlockMap[liftInstructions], len(fn.Blocks))
190 for i := range instructions {
191 instructions[i].insertInstructions = map[Instruction][]Instruction{}
192 }
193
194 // Number nodes, for liftable
195 numberNodesPerBlock(fn)
196
197 heads := make(BlockMap[int], len(fn.Blocks))
198 for i := range heads {
199 heads[i] = -1
200 }
201 for _, b := range fn.Blocks {
202 for i, instr := range b.Instrs {
203 if _, ok := instr.(*Phi); !ok {
204 heads[b.Index] = i
205 break
206 }
207 }
208 }
209
210 for _, b := range fn.Blocks {
211 b.gaps = 0
212 b.rundefers = 0
213
214 for _, instr := range b.Instrs {
215 switch instr := instr.(type) {
216 case *Alloc:
217 if !liftable(instr, instructions, heads) {
218 instr.index = -1
219 continue
220 }
221
222 if numAllocs == 0 {
223 df = buildDomFrontier(fn)
224 newPhis = make(BlockMap[[]newPhi], len(fn.Blocks))
225
226 if debugLifting {
227 title := false
228 for i, blocks := range df {
229 if blocks != nil {
230 if !title {
231 fmt.Fprintf(os.Stderr, "Dominance frontier of %s:\n", fn)
232 title = true
233 }
234 fmt.Fprintf(os.Stderr, "\t%s: %s\n", fn.Blocks[i], blocks)
235 }
236 }
237 }
238 }
239 instr.index = numAllocs
240 numAllocs++
241 case *Defer:
242 usesDefer = true
243 if eliminateDeferStack {
244 // Clear _DeferStack and remove references to loads
245 if instr.DeferStack != nil {
246 if refs := instr.DeferStack.Referrers(); refs != nil {
247 *refs = removeInstr(*refs, instr)
248 }
249 instr.DeferStack = nil
250 }
251 }
252 case *RunDefers:
253 b.rundefers++
254 }
255 }
256 }
257
258 if numAllocs > 0 {
259 for _, b := range fn.Blocks {
260 work := instructions[b.Index]
261 for _, rename := range work.renameAllocs {
262 for _, instr_ := range b.Instrs[rename.startingAt:] {
263 replace(instr_, rename.from, rename.to)
264 }
265 }
266 }
267
268 for _, b := range fn.Blocks {
269 work := instructions[b.Index]
270 if len(work.insertInstructions) != 0 {
271 newInstrs := make([]Instruction, 0, len(fn.Blocks)+len(work.insertInstructions)*3)
272 for _, instr := range b.Instrs {
273 if add, ok := work.insertInstructions[instr]; ok {
274 newInstrs = append(newInstrs, add...)
275 }
276 newInstrs = append(newInstrs, instr)
277 }
278 b.Instrs = newInstrs
279 }
280 }
281
282 // TODO(dh): remove inserted allocs that end up unused after lifting.
283
284 for _, b := range fn.Blocks {
285 for _, instr := range b.Instrs {
286 if instr, ok := instr.(*Alloc); ok && instr.index >= 0 {
287 liftAlloc(df, instr, newPhis)
288 }
289 }
290 }
291
292 // renaming maps an alloc (keyed by index) to its replacement
293 // value. Initially the renaming contains nil, signifying the
294 // zero constant of the appropriate type; we construct the
295 // Const lazily at most once on each path through the domtree.
296 // TODO(adonovan): opt: cache per-function not per subtree.
297 renaming := make([]Value, numAllocs)
298
299 // Renaming.
300 rename(fn.Blocks[0], renaming, newPhis)
301
302 simplifyPhis(newPhis)
303
304 // Eliminate dead φ-nodes.
305 markLiveNodes(fn.Blocks, newPhis)
306
307 // Eliminate ssa:deferstack() call.
308 if eliminateDeferStack {
309 b := deferstackCall.block
310 for i, instr := range b.Instrs {
311 if instr == deferstackCall {
312 b.Instrs[i] = nil
313 b.gaps++
314 break
315 }
316 }
317 }
318 }
319
320 // Prepend remaining live φ-nodes to each block and possibly kill rundefers.
321 for _, b := range fn.Blocks {
322 var head []Instruction
323 if numAllocs > 0 {
324 nps := newPhis[b.Index]
325 head = make([]Instruction, 0, len(nps))
326 for _, np := range nps {
327 if np.phi.live {
328 head = append(head, np.phi)
329 } else {
330 for _, edge := range np.phi.Edges {
331 if refs := edge.Referrers(); refs != nil {
332 *refs = removeInstr(*refs, np.phi)
333 }
334 }
335 np.phi.block = nil
336 }
337 }
338 }
339
340 rundefersToKill := b.rundefers
341 if usesDefer {
342 rundefersToKill = 0
343 }
344
345 j := len(head)
346 if j+b.gaps+rundefersToKill == 0 {
347 continue // fast path: no new phis or gaps
348 }
349
350 // We could do straight copies instead of element-wise copies
351 // when both b.gaps and rundefersToKill are zero. However,
352 // that seems to only be the case ~1% of the time, which
353 // doesn't seem worth the extra branch.
354
355 // Remove dead instructions, add phis
356 ns := len(b.Instrs) + j - b.gaps - rundefersToKill
357 if ns <= cap(b.Instrs) {
358 // b.Instrs has enough capacity to store all instructions
359
360 // OPT(dh): check cap vs the actually required space; if
361 // there is a big enough difference, it may be worth
362 // allocating a new slice, to avoid pinning memory.
363 dst := b.Instrs[:cap(b.Instrs)]
364 i := len(dst) - 1
365 for n := len(b.Instrs) - 1; n >= 0; n-- {
366 instr := dst[n]
367 if instr == nil {
368 continue
369 }
370 if !usesDefer {
371 if _, ok := instr.(*RunDefers); ok {
372 continue
373 }
374 }
375 dst[i] = instr
376 i--
377 }
378 off := i + 1 - len(head)
379 // aid GC
380 clearInstrs(dst[:off])
381 dst = dst[off:]
382 copy(dst, head)
383 b.Instrs = dst
384 } else {
385 // not enough space, so allocate a new slice and copy
386 // over.
387 dst := make([]Instruction, ns)
388 copy(dst, head)
389
390 for _, instr := range b.Instrs {
391 if instr == nil {
392 continue
393 }
394 if !usesDefer {
395 if _, ok := instr.(*RunDefers); ok {
396 continue
397 }
398 }
399 dst[j] = instr
400 j++
401 }
402 b.Instrs = dst
403 }
404 }
405
406 // Remove any fn.Locals that were lifted.
407 j := 0
408 for _, l := range fn.Locals {
409 if l.index < 0 {
410 fn.Locals[j] = l
411 j++
412 }
413 }
414 // Nil out fn.Locals[j:] to aid GC.
415 for i := j; i < len(fn.Locals); i++ {
416 fn.Locals[i] = nil
417 }
418 fn.Locals = fn.Locals[:j]
419
420 return numAllocs > 0
421 }
422
423 func hasDirectReferrer(instr Instruction) bool {
424 for _, instr := range *instr.Referrers() {
425 if _, ok := instr.(*Phi); !ok {
426 return true
427 }
428 }
429 return false
430 }
431
432 func markLiveNodes(blocks []*BasicBlock, newPhis BlockMap[[]newPhi]) {
433 // Phis may become dead due to optimization passes.
434
435 // Phi nodes are considered live if a non-phi
436 // node uses them. Once we find a node that is live, we mark all
437 // of its operands as used, too.
438 for _, npList := range newPhis {
439 for _, np := range npList {
440 phi := np.phi
441 if !phi.live && hasDirectReferrer(phi) {
442 markLivePhi(phi)
443 }
444 }
445 }
446 // Existing φ-nodes due to && and || operators
447 // are all considered live (see Go issue 19622).
448 for _, b := range blocks {
449 for _, phi := range b.phis() {
450 markLivePhi(phi.(*Phi))
451 }
452 }
453 }
454
455 func markLivePhi(phi *Phi) {
456 phi.live = true
457 for _, rand := range phi.Edges {
458 if rand, ok := rand.(*Phi); ok {
459 if !rand.live {
460 markLivePhi(rand)
461 }
462 }
463 }
464 }
465
466 // simplifyPhis replaces trivial phis with non-phi alternatives. Phi
467 // nodes where all edges are identical, or consist of only the phi
468 // itself and one other value, may be replaced with the value.
469 func simplifyPhis(newPhis BlockMap[[]newPhi]) {
470 // find all phis that are trivial and can be replaced with a
471 // non-phi value. run until we reach a fixpoint, because replacing
472 // a phi may make other phis trivial.
473 for changed := true; changed; {
474 changed = false
475 for _, npList := range newPhis {
476 for _, np := range npList {
477 if np.phi.live {
478 // we're reusing 'live' to mean 'dead' in the context of simplifyPhis
479 continue
480 }
481 if r, ok := isUselessPhi(np.phi); ok {
482 // useless phi, replace its uses with the
483 // replacement value. the dead phi pass will clean
484 // up the phi afterwards.
485 replaceAll(np.phi, r)
486 np.phi.live = true
487 changed = true
488 }
489 }
490 }
491 }
492 }
493
494 type BlockSet struct {
495 idx int
496 values []bool
497 count int
498 }
499
500 func NewBlockSet(size int) *BlockSet {
501 return &BlockSet{values: make([]bool, size)}
502 }
503
504 func (s *BlockSet) Set(s2 *BlockSet) {
505 copy(s.values, s2.values)
506 s.count = 0
507 for _, v := range s.values {
508 if v {
509 s.count++
510 }
511 }
512 }
513
514 func (s *BlockSet) Num() int {
515 return s.count
516 }
517
518 func (s *BlockSet) Has(b *BasicBlock) bool {
519 if b.Index >= len(s.values) {
520 return false
521 }
522 return s.values[b.Index]
523 }
524
525 // add adds b to the set and returns true if the set changed.
526 func (s *BlockSet) Add(b *BasicBlock) bool {
527 if s.values[b.Index] {
528 return false
529 }
530 s.count++
531 s.values[b.Index] = true
532 s.idx = b.Index
533
534 return true
535 }
536
537 func (s *BlockSet) Clear() {
538 for j := range s.values {
539 s.values[j] = false
540 }
541 s.count = 0
542 }
543
544 // take removes an arbitrary element from a set s and
545 // returns its index, or returns -1 if empty.
546 func (s *BlockSet) Take() int {
547 // [i, end]
548 for i := s.idx; i < len(s.values); i++ {
549 if s.values[i] {
550 s.values[i] = false
551 s.idx = i
552 s.count--
553 return i
554 }
555 }
556
557 // [start, i)
558 for i := 0; i < s.idx; i++ {
559 if s.values[i] {
560 s.values[i] = false
561 s.idx = i
562 s.count--
563 return i
564 }
565 }
566
567 return -1
568 }
569
570 // newPhi is a pair of a newly introduced φ-node and the lifted Alloc
571 // it replaces.
572 type newPhi struct {
573 phi *Phi
574 alloc *Alloc
575 }
576
577 type liftInstructions struct {
578 insertInstructions map[Instruction][]Instruction
579 renameAllocs []struct {
580 from *Alloc
581 to *Alloc
582 startingAt int
583 }
584 }
585
586 type liftableBlockDesc struct {
587 // is the block (partially) unliftable, because it contains unliftable
588 // instructions or is reachable by an unliftable block
589 isUnliftable bool
590 hasLiftableLoad bool
591 hasLiftableOther bool
592 // we need to emit stores in predecessors because the unliftable use is in
593 // a phi
594 storeInPreds bool
595
596 lastLiftable int
597 firstUnliftable int
598 }
599
600 // liftable determines if alloc can be lifted, and records instructions to split partially liftable allocs.
601 //
602 // In the trivial case, all uses of the alloc can be lifted. This is the case when it is only used for storing into and
603 // loading from. In that case, no instructions are recorded.
604 //
605 // In the more complex case, the alloc is used for storing into and loading from, but it is also used as a value, for
606 // example because it gets passed to a function, e.g. fn(&x). In this case, uses of the alloc fall into one of two
607 // categories: those that can be lifted and those that can't. A boundary forms between these two categories in the
608 // function's control flow: Once an unliftable use is encountered, the alloc is no longer liftable for the remainder of
609 // the basic block the use is in, nor in any blocks reachable from it.
610 //
611 // We record instructions that split the alloc into two allocs: one that is used in liftable uses, and one that is used
612 // in unliftable uses. Whenever we encounter a boundary between liftable and unliftable uses or blocks, we emit a pair
613 // of Load and Store that copy the value from the liftable alloc into the unliftable alloc. Taking these instructions
614 // into account, the normal lifting machinery will completely lift the liftable alloc, store the correct lifted values
615 // into the unliftable alloc, and will not at all lift the unliftable alloc.
616 //
617 // In Go syntax, the transformation looks somewhat like this:
618 //
619 // func foo() {
620 // x := 32
621 // if cond {
622 // println(x)
623 // escape(&x)
624 // println(x)
625 // } else {
626 // println(x)
627 // }
628 // println(x)
629 // }
630 //
631 // transforms into
632 //
633 // func fooSplitAlloc() {
634 // x := 32
635 // var x_ int
636 // if cond {
637 // println(x)
638 // x_ = x
639 // escape(&x_)
640 // println(x_)
641 // } else {
642 // println(x)
643 // x_ = x
644 // }
645 // println(x_)
646 // }
647 func liftable(alloc *Alloc, instructions BlockMap[liftInstructions], heads BlockMap[int]) bool {
648 fn := alloc.block.parent
649
650 // Don't lift result values in functions that defer
651 // calls that may recover from panic.
652 if fn.Recover != nil {
653 if slices.Contains(fn.results, alloc) {
654 return false
655 }
656 }
657
658 blocks := fn.liftableBlockMap
659 if len(blocks) != len(fn.Blocks) {
660 blocks = make(BlockMap[liftableBlockDesc], len(fn.Blocks))
661 fn.liftableBlockMap = blocks
662 } else {
663 clear(blocks)
664 }
665 for _, b := range fn.Blocks {
666 blocks[b.Index].lastLiftable = -1
667 blocks[b.Index].firstUnliftable = len(b.Instrs) + 1
668 }
669
670 // Look at all uses of the alloc and deduce which blocks have liftable or unliftable instructions.
671 for _, instr := range alloc.referrers {
672 // Find the first unliftable use
673
674 desc := &blocks[instr.Block().Index]
675 hasUnliftable := false
676 inHead := false
677 switch instr := instr.(type) {
678 case *Store:
679 if instr.Val == alloc {
680 hasUnliftable = true
681 }
682 case *Load:
683 case *debugRef:
684 case *Phi:
685 inHead = true
686 hasUnliftable = true
687 default:
688 hasUnliftable = true
689 }
690
691 if hasUnliftable {
692 desc.isUnliftable = true
693 if int(instr.ID()) < desc.firstUnliftable {
694 desc.firstUnliftable = int(instr.ID())
695 }
696 if inHead {
697 desc.storeInPreds = true
698 desc.firstUnliftable = 0
699 }
700 }
701 }
702
703 for _, instr := range alloc.referrers {
704 // Find the last liftable use, taking the previously calculated firstUnliftable into consideration
705
706 desc := &blocks[instr.Block().Index]
707 if int(instr.ID()) >= desc.firstUnliftable {
708 continue
709 }
710 hasLiftable := false
711 switch instr := instr.(type) {
712 case *Store:
713 if instr.Val != alloc {
714 desc.hasLiftableOther = true
715 hasLiftable = true
716 }
717 case *Load:
718 desc.hasLiftableLoad = true
719 hasLiftable = true
720 case *debugRef:
721 desc.hasLiftableOther = true
722 }
723 if hasLiftable {
724 if int(instr.ID()) > desc.lastLiftable {
725 desc.lastLiftable = int(instr.ID())
726 }
727 }
728 }
729
730 for i := range blocks {
731 // Update firstUnliftable to be one after lastLiftable. We do this to include the unliftable's preceding
732 // DebugRefs in the renaming.
733 if blocks[i].lastLiftable == -1 && !blocks[i].storeInPreds {
734 // There are no liftable instructions (for this alloc) in this block. Set firstUnliftable to the
735 // first non-head instruction to avoid inserting the store before phi instructions, which would
736 // fail validation.
737 first := heads[i]
738 blocks[i].firstUnliftable = first
739 } else {
740 blocks[i].firstUnliftable = blocks[i].lastLiftable + 1
741 }
742 }
743
744 // If a block is reachable by a (partially) unliftable block, then the entirety of the block is unliftable. In that
745 // case, stores have to be inserted in the predecessors.
746 //
747 // TODO(dh): this isn't always necessary. If the block is reachable by itself, i.e. part of a loop, then if the
748 // Alloc instruction is itself part of that loop, then there is a subset of instructions in the loop that can be
749 // lifted. For example:
750 //
751 // for {
752 // x := 42
753 // println(x)
754 // escape(&x)
755 // }
756 //
757 // The x that escapes in one iteration of the loop isn't the same x that we read from on the next iteration.
758 seen := make(BlockMap[bool], len(fn.Blocks))
759 var dfs func(b *BasicBlock)
760 dfs = func(b *BasicBlock) {
761 if seen[b.Index] {
762 return
763 }
764 seen[b.Index] = true
765 desc := &blocks[b.Index]
766 desc.hasLiftableLoad = false
767 desc.hasLiftableOther = false
768 desc.isUnliftable = true
769 desc.firstUnliftable = 0
770 desc.storeInPreds = true
771 for _, succ := range b.Succs {
772 dfs(succ)
773 }
774 }
775 for _, b := range fn.Blocks {
776 if blocks[b.Index].isUnliftable {
777 for _, succ := range b.Succs {
778 dfs(succ)
779 }
780 }
781 }
782
783 hasLiftableLoad := false
784 hasLiftableOther := false
785 hasUnliftable := false
786 for _, b := range fn.Blocks {
787 desc := &blocks[b.Index]
788 hasLiftableLoad = hasLiftableLoad || desc.hasLiftableLoad
789 hasLiftableOther = hasLiftableOther || desc.hasLiftableOther
790 if desc.isUnliftable {
791 hasUnliftable = true
792 }
793 }
794 if !hasLiftableLoad && !hasLiftableOther {
795 // There are no liftable uses
796 return false
797 } else if !hasUnliftable {
798 // The alloc is entirely liftable without splitting
799 return true
800 } else if !hasLiftableLoad {
801 // The alloc is not entirely liftable, and the only liftable uses are stores. While some of those stores could
802 // get lifted away, it would also lead to an infinite loop when lifting to a fixpoint, because the newly created
803 // allocs also get stored into repeatable and that's their only liftable uses.
804 return false
805 }
806
807 // We need to insert stores for the new alloc. If a (partially) unliftable block has no unliftable
808 // predecessors and the use isn't in a phi node, then the store can be inserted right before the unliftable use.
809 // Otherwise, stores have to be inserted at the end of all liftable predecessors.
810
811 newAlloc := &Alloc{Heap: true}
812 newAlloc.setBlock(alloc.block)
813 newAlloc.setType(alloc.typ)
814 newAlloc.setSource(alloc.source)
815 newAlloc.index = -1
816 newAlloc.comment = "split alloc"
817
818 {
819 work := instructions[alloc.block.Index]
820 work.insertInstructions[alloc] = append(work.insertInstructions[alloc], newAlloc)
821 }
822
823 predHasStore := make(BlockMap[bool], len(fn.Blocks))
824 for _, b := range fn.Blocks {
825 desc := &blocks[b.Index]
826 bWork := &instructions[b.Index]
827
828 if desc.isUnliftable {
829 bWork.renameAllocs = append(bWork.renameAllocs, struct {
830 from *Alloc
831 to *Alloc
832 startingAt int
833 }{
834 alloc, newAlloc, int(desc.firstUnliftable),
835 })
836 }
837
838 if !desc.isUnliftable {
839 continue
840 }
841
842 propagate := func(in *BasicBlock, before Instruction) {
843 load := &Load{
844 X: alloc,
845 }
846 store := &Store{
847 Addr: newAlloc,
848 Val: load,
849 }
850 load.setType(deref(alloc.typ))
851 load.setBlock(in)
852 load.comment = "split alloc"
853 store.setBlock(in)
854 updateOperandReferrers(load)
855 updateOperandReferrers(store)
856 store.comment = "split alloc"
857
858 entry := &instructions[in.Index]
859 entry.insertInstructions[before] = append(entry.insertInstructions[before], load, store)
860 }
861
862 if desc.storeInPreds {
863 // emit stores at the end of liftable preds
864 for _, pred := range b.Preds {
865 if blocks[pred.Index].isUnliftable {
866 continue
867 }
868
869 if !alloc.block.Dominates(pred) {
870 // Consider this cfg:
871 //
872 // 1
873 // /|
874 // / |
875 // ↙ ↓
876 // 2--→3
877 //
878 // with an Alloc in block 2. It doesn't make sense to insert a store in block 1 for the jump to
879 // block 3, because 1 can never see the Alloc in the first place.
880 //
881 // Ignoring phi nodes, an Alloc always dominates all of its uses, and phi nodes don't matter here,
882 // because for the incoming edges that do matter, we do emit the stores.
883
884 continue
885 }
886
887 if predHasStore[pred.Index] {
888 // Don't generate redundant propagations. Not only is it unnecessary, it can lead to infinite loops
889 // when trying to lift to a fix point, because redundant stores are liftable.
890 continue
891 }
892
893 predHasStore[pred.Index] = true
894
895 before := pred.Instrs[len(pred.Instrs)-1]
896 propagate(pred, before)
897 }
898 } else {
899 // emit store before the first unliftable use
900 before := b.Instrs[desc.firstUnliftable]
901 propagate(b, before)
902 }
903 }
904
905 return true
906 }
907
908 // liftAlloc lifts alloc into registers and populates newPhis with all the φ-nodes it may require.
909 func liftAlloc(df domFrontier, alloc *Alloc, newPhis BlockMap[[]newPhi]) {
910 fn := alloc.Parent()
911
912 defblocks := fn.blockset(0)
913 Aphi := fn.blockset(2)
914 W := fn.blockset(3)
915
916 // Compute defblocks, the set of blocks containing a
917 // definition of the alloc cell.
918 for _, instr := range *alloc.Referrers() {
919 switch instr := instr.(type) {
920 case *Store:
921 defblocks.Add(instr.Block())
922 }
923 }
924 // The Alloc itself counts as a (zero) definition of the cell.
925 defblocks.Add(alloc.Block())
926
927 if debugLifting {
928 fmt.Fprintln(os.Stderr, "\tlifting ", alloc, alloc.Name())
929 }
930
931 // Φ-insertion.
932 //
933 // What follows is the body of the main loop of the insert-φ
934 // function described by Cytron et al, but instead of using
935 // counter tricks, we just reset the 'hasAlready' and 'work'
936 // sets each iteration. These are bitmaps so it's pretty cheap.
937
938 // Initialize W and work to defblocks.
939
940 for change := true; change; {
941 change = false
942 {
943 // Traverse iterated dominance frontier, inserting φ-nodes.
944 W.Set(defblocks)
945
946 for i := W.Take(); i != -1; i = W.Take() {
947 n := fn.Blocks[i]
948 for _, y := range df[n.Index] {
949 if Aphi.Add(y) {
950 if len(*alloc.Referrers()) == 0 {
951 continue
952 }
953 live := false
954 for _, ref := range *alloc.Referrers() {
955 if _, ok := ref.(*Load); ok {
956 if y.Reaches(ref.Block()) {
957 live = true
958 break
959 }
960 }
961 }
962 if !live {
963 continue
964 }
965
966 // Create φ-node.
967 // It will be prepended to v.Instrs later, if needed.
968 phi := &Phi{
969 Edges: make([]Value, len(y.Preds)),
970 }
971 phi.comment = alloc.comment
972 phi.source = alloc.source
973 phi.setType(deref(alloc.Type()))
974 phi.block = y
975 if debugLifting {
976 fmt.Fprintf(os.Stderr, "\tplace %s = %s at block %s\n", phi.Name(), phi, y)
977 }
978 newPhis[y.Index] = append(newPhis[y.Index], newPhi{phi, alloc})
979
980 change = true
981 if defblocks.Add(y) {
982 W.Add(y)
983 }
984 }
985 }
986 }
987 }
988 }
989 }
990
991 // replaceAll replaces all intraprocedural uses of x with y,
992 // updating x.Referrers and y.Referrers.
993 // Precondition: x.Referrers() != nil, i.e. x must be local to some function.
994 func replaceAll(x, y Value) {
995 var rands []*Value
996 pxrefs := x.Referrers()
997 pyrefs := y.Referrers()
998 for _, instr := range *pxrefs {
999 switch instr := instr.(type) {
1000 case *CompositeValue:
1001 // Special case CompositeValue because it might have very large lists of operands
1002 //
1003 // OPT(dh): this loop is still expensive for large composite values
1004 for i, rand := range instr.Values {
1005 if rand == x {
1006 instr.Values[i] = y
1007 }
1008 }
1009 default:
1010 rands = instr.Operands(rands[:0]) // recycle storage
1011 for _, rand := range rands {
1012 if *rand != nil {
1013 if *rand == x {
1014 *rand = y
1015 }
1016 }
1017 }
1018 }
1019 if pyrefs != nil {
1020 *pyrefs = append(*pyrefs, instr) // dups ok
1021 }
1022 }
1023 *pxrefs = nil // x is now unreferenced
1024 }
1025
1026 func replace(instr Instruction, x, y Value) {
1027 args := instr.Operands(nil)
1028 matched := false
1029 for _, arg := range args {
1030 if *arg == x {
1031 *arg = y
1032 matched = true
1033 }
1034 }
1035 if matched {
1036 yrefs := y.Referrers()
1037 if yrefs != nil {
1038 *yrefs = append(*yrefs, instr)
1039 }
1040
1041 xrefs := x.Referrers()
1042 if xrefs != nil {
1043 *xrefs = removeInstr(*xrefs, instr)
1044 }
1045 }
1046 }
1047
1048 // renamed returns the value to which alloc is being renamed,
1049 // constructing it lazily if it's the implicit zero initialization.
1050 func renamed(fn *Function, renaming []Value, alloc *Alloc) Value {
1051 v := renaming[alloc.index]
1052 if v == nil {
1053 v = zeroConst(deref(alloc.Type()), alloc.source)
1054 renaming[alloc.index] = v
1055 }
1056 return v
1057 }
1058
1059 // rename implements the Cytron et al-based SSA renaming algorithm, a
1060 // preorder traversal of the dominator tree replacing all loads of
1061 // Alloc cells with the value stored to that cell by the dominating
1062 // store instruction.
1063 //
1064 // renaming is a map from *Alloc (keyed by index number) to its
1065 // dominating stored value; newPhis[x] is the set of new φ-nodes to be
1066 // prepended to block x.
1067 func rename(u_ *BasicBlock, renaming_ []Value, newPhis BlockMap[[]newPhi]) {
1068 type worklistEntry struct {
1069 u *BasicBlock
1070 renaming []Value
1071 }
1072
1073 worklist := []worklistEntry{{u_, renaming_}}
1074 var freelist [][]Value
1075
1076 for len(worklist) > 0 {
1077 entry := worklist[len(worklist)-1]
1078 worklist = worklist[:len(worklist)-1]
1079 u, renaming := entry.u, entry.renaming
1080
1081 // Each φ-node becomes the new name for its associated Alloc.
1082 for _, np := range newPhis[u.Index] {
1083 phi := np.phi
1084 alloc := np.alloc
1085 renaming[alloc.index] = phi
1086 }
1087
1088 // Rename loads and stores of allocs.
1089 for i, instr := range u.Instrs {
1090 switch instr := instr.(type) {
1091 case *Alloc:
1092 if instr.index >= 0 { // store of zero to Alloc cell
1093 // Replace dominated loads by the zero value.
1094 renaming[instr.index] = nil
1095 if debugLifting {
1096 fmt.Fprintf(os.Stderr, "\tkill alloc %s\n", instr)
1097 }
1098 // Delete the Alloc.
1099 u.Instrs[i] = nil
1100 u.gaps++
1101 }
1102
1103 case *Store:
1104 if alloc, ok := instr.Addr.(*Alloc); ok && alloc.index >= 0 { // store to Alloc cell
1105 // Replace dominated loads by the stored value.
1106 renaming[alloc.index] = instr.Val
1107 if debugLifting {
1108 fmt.Fprintf(os.Stderr, "\tkill store %s; new value: %s\n",
1109 instr, instr.Val.Name())
1110 }
1111 if refs := instr.Addr.Referrers(); refs != nil {
1112 *refs = removeInstr(*refs, instr)
1113 }
1114 if refs := instr.Val.Referrers(); refs != nil {
1115 *refs = removeInstr(*refs, instr)
1116 }
1117 // Delete the Store.
1118 u.Instrs[i] = nil
1119 u.gaps++
1120 }
1121
1122 case *Load:
1123 if alloc, ok := instr.X.(*Alloc); ok && alloc.index >= 0 { // load of Alloc cell
1124 newval := renamed(u.Parent(), renaming, alloc)
1125 if debugLifting {
1126 fmt.Fprintf(os.Stderr, "\tupdate load %s = %s with %s\n",
1127 instr.Name(), instr, newval)
1128 }
1129 // Replace all references to the loaded value by the dominating
1130 // stored value.
1131 replaceAll(instr, newval)
1132 u.Instrs[i] = nil
1133 u.gaps++
1134 }
1135
1136 case *debugRef:
1137 if x, ok := instr.X.(*Alloc); ok && x.index >= 0 {
1138 if instr.IsAddr {
1139 instr.X = renamed(u.Parent(), renaming, x)
1140 instr.IsAddr = false
1141
1142 // Add DebugRef to instr.X's referrers.
1143 if refs := instr.X.Referrers(); refs != nil {
1144 *refs = append(*refs, instr)
1145 }
1146 } else {
1147 // A source expression denotes the address
1148 // of an Alloc that was optimized away.
1149 instr.X = nil
1150
1151 // Delete the DebugRef.
1152 u.Instrs[i] = nil
1153 u.gaps++
1154 }
1155 }
1156 }
1157 }
1158
1159 // For each φ-node in a CFG successor, rename the edge.
1160 for _, v := range u.Succs {
1161 phis := newPhis[v.Index]
1162 if len(phis) == 0 {
1163 continue
1164 }
1165 i := v.predIndex(u)
1166 for _, np := range phis {
1167 phi := np.phi
1168 alloc := np.alloc
1169 newval := renamed(u.Parent(), renaming, alloc)
1170 if debugLifting {
1171 fmt.Fprintf(os.Stderr, "\tsetphi %s edge %s -> %s (#%d) (alloc=%s) := %s\n",
1172 phi.Name(), u, v, i, alloc.Name(), newval.Name())
1173 }
1174 phi.Edges[i] = newval
1175 if prefs := newval.Referrers(); prefs != nil {
1176 *prefs = append(*prefs, phi)
1177 }
1178 }
1179 }
1180
1181 // Continue depth-first recursion over domtree, pushing a
1182 // fresh copy of the renaming map for each subtree.
1183 for _, v := range slices.Backward(u.dom.children) {
1184 var r []Value
1185 if len(freelist) == 0 {
1186 r = make([]Value, len(renaming))
1187 } else {
1188 r = freelist[len(freelist)-1]
1189 freelist = freelist[:len(freelist)-1]
1190 }
1191 copy(r, renaming)
1192 worklist = append(worklist, worklistEntry{v, r})
1193 }
1194 freelist = append(freelist, renaming)
1195 }
1196 }
1197
1198 func simplifyConstantCompositeValues(fn *Function) bool {
1199 changed := false
1200
1201 for _, b := range fn.Blocks {
1202 n := 0
1203 for _, instr := range b.Instrs {
1204 replaced := false
1205
1206 if cv, ok := instr.(*CompositeValue); ok {
1207 ac := &AggregateConst{}
1208 ac.typ = cv.typ
1209 replaced = true
1210 for _, v := range cv.Values {
1211 if c, ok := v.(Constant); ok {
1212 ac.Values = append(ac.Values, c)
1213 } else {
1214 replaced = false
1215 break
1216 }
1217 }
1218 if replaced {
1219 replaceAll(cv, ac)
1220 killInstruction(cv)
1221 }
1222
1223 }
1224
1225 if replaced {
1226 changed = true
1227 } else {
1228 b.Instrs[n] = instr
1229 n++
1230 }
1231 }
1232
1233 clearInstrs(b.Instrs[n:])
1234 b.Instrs = b.Instrs[:n]
1235 }
1236
1237 return changed
1238 }
1239
1240 func updateOperandReferrers(instr Instruction) {
1241 for _, op := range instr.Operands(nil) {
1242 refs := (*op).Referrers()
1243 if refs != nil {
1244 *refs = append(*refs, instr)
1245 }
1246 }
1247 }
1248
1249 // deferstackPreamble returns the *Alloc and ssa:deferstack() call for fn.deferstack.
1250 func deferstackPreamble(fn *Function) (*Alloc, *Call) {
1251 if alloc, _ := fn.vars[fn.deferstack].(*Alloc); alloc != nil {
1252 for _, ref := range *alloc.Referrers() {
1253 if ref, _ := ref.(*Store); ref != nil && ref.Addr == alloc {
1254 if call, _ := ref.Val.(*Call); call != nil {
1255 return alloc, call
1256 }
1257 }
1258 }
1259 }
1260 return nil, nil
1261 }