-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegen.go
More file actions
1697 lines (1574 loc) · 44.4 KB
/
Copy pathcodegen.go
File metadata and controls
1697 lines (1574 loc) · 44.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"fmt"
"slices"
"strings"
)
// CPU execution model with highway markers for fast navigation.
// Tape layout, sentinel positions, and the bump-on-overflow scheme
// for phase temps are documented in docs/tape.md.
// Tape positions for registers. Interleaved with algo temps at 3, 6 so
// every register has at least one distance-1 neighbor.
var regPos = [5]int{1, 2, 4, 5, 7}
// Algo temp positions (skip markers and sentinels).
var algoTempPositions = []int{
3, 6, // group 0 (interleaved with registers)
9, 10, 11, 12, 13, 14, 15, // group 1
17, 18, 19, 20, 21, 22, 23, // group 2
}
// currentAlgoTemps returns the active algo-temp pool: the fixed set
// plus the position just below each highway marker that falls in
// [phaseTempBase, sentinelFwd). The interleaved positions give
// near-temps for far phase-temp operands (e.g. an operand at position
// 49 finds a temp at 47, distance 2, instead of 23 from the regular
// pool, distance 26). The lowerer's allocCell skips these positions
// so they stay available for codegen scratch.
func currentAlgoTemps() []int {
temps := append([]int{}, algoTempPositions...)
for m := highwayStride; m <= sentinelFwd; m += highwayStride {
if m-1 >= phaseTempBase {
temps = append(temps, m-1)
}
}
return temps
}
// isMarkerOrAlgoTemp reports whether tape position p is either
// a highway marker (a multiple of highwayStride below sentinelFwd,
// must stay at value 1 for navigation) or the codegen-managed
// interleaved algo-temp slot just below a marker (see
// currentAlgoTemps). The lowerer's phase-temp allocation paths skip
// such positions so navigation stays sound and the interleaved slots
// remain available as codegen scratch.
func isMarkerOrAlgoTemp(p int) bool {
return p > 0 && p < sentinelFwd &&
(p%highwayStride == 0 || (p+1)%highwayStride == 0)
}
const (
numRegs = 5
sentinelBack = 0 // backward sentinel
highwayStride = 8 // [>>>>>>>>] stride
phaseTempBase = 25 // first phase temp
maxSentinelBumps = 8 // max bumps to sentinelFwd before giving up
)
// sentinelFwd is the forward sentinel position (always 0 on the tape).
// Cells with IDs 0..sentinelFwd map directly to those tape positions
// and form the fixed CPU area (registers, algo temps, phase temps);
// the first stack slot has cell ID sentinelFwd+1 and lives further
// up the tape past two pad cells (see stackValuePos).
//
// It's a var rather than a const because the compile driver bumps it
// by highwayStride (8) when the default phase-temp pool overflows
// during recursive lowering -- the larger pool covers programs that
// would otherwise hit "too many local variables in recursive function".
var sentinelFwd = 24
// Generator converts IR to Brainfuck code using a register + stack model.
// 5 registers at positions 1,2,4,5,7 (interleaved with algo temps at 3,6 for
// neighbor optimization), highway markers at 8,16,24,32 for fast [>>>>>>>>] scanning.
type Generator struct {
buf strings.Builder
pos int
temps posAllocator
frameSize int
cache regCache
code bool
debug bool
stackUsed bool
}
// posAllocator manages a set of non-contiguous tape positions.
type posAllocator struct {
positions []int
inUse []bool
}
func newPosAllocator(positions []int) posAllocator {
return posAllocator{
positions: positions,
inUse: make([]bool, len(positions)),
}
}
func (pa *posAllocator) alloc() int {
for i, u := range pa.inUse {
if !u {
pa.inUse[i] = true
return pa.positions[i]
}
}
panic("out of temporary cells")
}
// allocNear allocates a temp near the given operand positions.
// When any operand is a phase temp (>= phaseTempBase), picks the closest
// free position. Otherwise uses default sequential allocation.
func (pa *posAllocator) allocNear(positions ...int) int {
target := -1
for _, p := range positions {
if p >= phaseTempBase {
target = p
break
}
}
if target < 0 {
return pa.alloc()
}
best := -1
bestDist := 1 << 30
for i, p := range pa.positions {
if !pa.inUse[i] {
d := abs(target - p)
if d < bestDist {
bestDist = d
best = i
}
}
}
if best < 0 {
panic("out of temporary cells")
}
pa.inUse[best] = true
return pa.positions[best]
}
func (pa *posAllocator) free(pos int) {
for i, p := range pa.positions {
if p == pos {
pa.inUse[i] = false
return
}
}
}
func (pa *posAllocator) allocConsecutive(n int) int {
var c, q int
for i, p := range pa.positions {
if pa.inUse[i] || i > 0 && p != q+1 {
c = 0
}
if !pa.inUse[i] {
if c++; c >= n {
s := i - n + 1
for j := s; j <= i; j++ {
pa.inUse[j] = true
}
return pa.positions[s]
}
}
q = p
}
panic("cannot allocate consecutive cells")
}
func (pa *posAllocator) freeConsecutive(base, n int) {
for i, p := range pa.positions {
if p == base {
for j := range n {
pa.inUse[i+j] = false
}
return
}
}
}
// regCache manages the registers.
type regCache struct {
regs [numRegs]regEntry
next int
gen *Generator
}
type regEntry struct {
slot int
dirty bool
}
func (rc *regCache) ensure(slot int, avoid []int) int {
for i := range rc.regs {
if rc.regs[i].slot == slot {
return regPos[i]
}
}
idx := rc.allocIdx(avoid)
rc.gen.loadFromStack(regPos[idx], slot)
rc.regs[idx] = regEntry{slot: slot}
return regPos[idx]
}
func (rc *regCache) assign(slot int, avoid []int) int {
for i := range rc.regs {
if rc.regs[i].slot == slot {
rc.regs[i].dirty = true
return regPos[i]
}
}
idx := rc.allocIdx(avoid)
rc.regs[idx] = regEntry{slot: slot, dirty: true}
return regPos[idx]
}
func (rc *regCache) allocIdx(avoid []int) int {
isAvoided := func(idx int) bool {
return slices.Contains(avoid, regPos[idx])
}
for i := range rc.regs {
if rc.regs[i].slot < 0 && !isAvoided(i) {
return i
}
}
for range rc.regs {
r := rc.next
rc.next = (rc.next + 1) % numRegs
if !isAvoided(r) {
rc.evict(r)
return r
}
}
panic("no available register")
}
// allocNeighbor returns the position of an empty register adjacent to pos,
// or -1 if none. The caller must call freeNeighbor when done.
func (rc *regCache) allocNeighbor(pos int) int {
for i := range rc.regs {
if rc.regs[i].slot < 0 && abs(regPos[i]-pos) == 1 {
rc.regs[i].slot = -2 // mark reserved
return regPos[i]
}
}
return -1
}
func (rc *regCache) freeNeighbor(pos int) {
for i := range rc.regs {
if regPos[i] == pos && rc.regs[i].slot == -2 {
rc.regs[i].slot = -1
return
}
}
}
func (rc *regCache) evict(idx int) {
if rc.regs[idx].slot >= 0 && rc.regs[idx].dirty {
rc.gen.storeToStack(rc.regs[idx].slot, regPos[idx])
}
rc.regs[idx] = regEntry{slot: -1}
}
func (rc *regCache) markDirty(pos int) {
for i, p := range regPos {
if p == pos {
rc.regs[i].dirty = true
return
}
}
}
func (rc *regCache) flush() {
for i := range rc.regs {
if rc.regs[i].slot >= 0 && rc.regs[i].dirty {
rc.gen.storeToStack(rc.regs[i].slot, regPos[i])
rc.regs[i].dirty = false
}
}
}
func (rc *regCache) invalidate() {
for i := range rc.regs {
rc.regs[i] = regEntry{slot: -1}
}
}
func (rc *regCache) flushAndInvalidate() {
rc.flush()
rc.invalidate()
}
// flushCell writes a specific cell back to stack if it's dirty in the cache.
func (rc *regCache) flushCell(cell int) {
slot := slotOf(cell)
for i := range rc.regs {
if rc.regs[i].slot == slot && rc.regs[i].dirty {
rc.gen.storeToStack(slot, regPos[i])
rc.regs[i].dirty = false
return
}
}
}
// dropCell removes a cell from the register cache without storing to stack.
// Used when a cell is freed (IRFree): the value is dead, so no writeback needed.
func (rc *regCache) dropCell(cell int) {
if isReg(cell) {
return
}
slot := slotOf(cell)
for i := range rc.regs {
if rc.regs[i].slot == slot {
rc.regs[i] = regEntry{slot: -1}
return
}
}
}
// Stack helpers.
func slotOf(cell int) int {
return cell - (sentinelFwd + 1)
}
func isReg(cell int) bool {
return cell <= sentinelFwd
}
func stackValuePos(slot int) int {
return sentinelFwd + 4 + 3*slot
}
// Generate produces Brainfuck code. If debug is true, comments are emitted.
func Generate(prog *Program, debug bool) string {
numSlots := prog.CellsUsed - (sentinelFwd + 1)
g := &Generator{
temps: newPosAllocator(currentAlgoTemps()),
frameSize: numSlots,
debug: debug,
}
g.cache.gen = g
for i := range g.cache.regs {
g.cache.regs[i].slot = -1
}
g.genHighwayMarkers()
if numSlots > 0 {
g.genFramePush(numSlots)
}
initEnd := g.buf.Len()
g.genNode(prog.Main)
if !g.stackUsed {
return strings.TrimSpace(g.buf.String()[initEnd:])
}
return g.buf.String()
}
// Brainfuck primitives.
func (g *Generator) emit(s string) {
g.buf.WriteString(s)
g.code = true
}
func (g *Generator) comment(format string, args ...any) {
if g.debug {
if g.code {
g.code = false
g.buf.WriteString("\n")
}
g.buf.WriteString("# ")
fmt.Fprintf(&g.buf, format, args...)
g.buf.WriteString("\n")
}
}
func (g *Generator) moveTo(cell int) {
diff := cell - g.pos
if diff > 0 {
// When moving forward from near position 0, check if going to the
// forward sentinel via highway then backward is shorter.
if g.pos < highwayStride {
marker := highwayStride
cost := (marker - g.pos) + len(scanFwd) + abs(sentinelFwd-cell)
if cost < diff {
g.moveToSentinel()
g.moveTo(cell)
return
}
}
g.emit(strings.Repeat(">", diff))
} else if diff < 0 {
// When moving backward from the sentinel area, check if using the
// highway backward to position 0 then forward is shorter.
if g.pos >= sentinelFwd {
marker := sentinelFwd - highwayStride
cost := (g.pos - marker) + len(scanBack) + cell
if cost < -diff {
g.backToHome()
g.moveTo(cell)
return
}
}
g.emit(strings.Repeat("<", -diff))
}
g.pos = cell
}
func (g *Generator) clear(cell int) {
g.moveTo(cell)
g.emit("[-]")
}
func (g *Generator) incr(cell int) {
g.moveTo(cell)
g.emit("+")
}
func (g *Generator) decr(cell int) {
g.moveTo(cell)
g.emit("-")
}
// set val to cell using multiplication when beneficial.
func (g *Generator) set(cell int, val byte) {
g.clear(cell)
g.emitAdd(cell, int(val))
}
// emitAdd adds v to cell using multiplication when beneficial.
func (g *Generator) emitAdd(cell, v int) {
g.emitDelta(cell, v, "+")
}
// emitSub subtracts v from cell using multiplication when beneficial.
func (g *Generator) emitSub(cell, v int) {
g.emitDelta(cell, v, "-")
}
// allocTemp allocates a temporary cell near the given position.
// Prefers an adjacent free register (distance 1), then the backward
// sentinel (position 0) for register 1, then falls back to algorithm temps.
// Only safe for local operations that don't navigate the highway
// (e.g., multiplication loops, copy). Not safe for storeToStack which
// uses [<<<<<<<<] scans that require position 0 to be 0.
func (g *Generator) allocTemp(pos int) (int, func()) {
if t := g.cache.allocNeighbor(pos); t >= 0 {
return t, func() { g.cache.freeNeighbor(t) }
}
if pos == 1 {
return sentinelBack, func() {}
}
t := g.temps.allocNear(pos)
return t, func() { g.temps.free(t) }
}
// mulFactors finds a, b, r such that a*b+r == n and a+b+r is minimized.
func mulFactors(n int) (int, int, int) {
ma, mb, mr := 0, 0, n
for a := 2; a*a <= n; a++ {
b := n / a
r := n - a*b
if a+b+r < ma+mb+mr {
ma, mb, mr = a, b, r
}
}
return ma, mb, mr
}
// emitDelta applies op ("+" or "-") v times to cell.
// For v > 12, uses a multiplication loop: t[cell op*b; t-] with a*b+r = v.
// Falls back to direct repeat if the loop would be larger.
func (g *Generator) emitDelta(cell, v int, op string) {
if v <= 0 {
return
}
if v <= 12 {
g.moveTo(cell)
g.emit(strings.Repeat(op, v))
return
}
ma, mb, mr := mulFactors(v)
t, freeT := g.allocTemp(cell)
dist := abs(cell - t)
// BF for the multiplication loop:
// moveTo(t) [-] a++ [ moveTo(cell) b++ moveTo(t) -] r++
cost := dist + 3 + ma + 1 + dist + mb + dist + 2 + mr
if mr > 0 {
cost += dist // moveTo(cell) for remainder
}
if cost >= v {
freeT()
g.moveTo(cell)
g.emit(strings.Repeat(op, v))
return
}
g.clear(t)
g.emit(strings.Repeat("+", ma))
g.while(t, func() {
g.moveTo(cell)
g.emit(strings.Repeat(op, mb))
g.decr(t)
})
freeT()
if mr > 0 {
g.moveTo(cell)
g.emit(strings.Repeat(op, mr))
}
}
// move src to dst: dst += src, src = 0.
func (g *Generator) move(dst, src int) {
g.while(src, func() {
g.incr(dst)
g.decr(src)
})
}
// subtract src from dst: dst -= src, src = 0.
func (g *Generator) subtract(dst, src int) {
g.while(src, func() {
g.decr(dst)
g.decr(src)
})
}
// copy src to dst non-destructively, using temp as a buffer.
// After: dst = src (preserved), temp = 0.
func (g *Generator) copy(dst, src, temp int) {
g.clear(dst)
g.clear(temp)
g.while(src, func() {
g.incr(dst)
g.incr(temp)
g.decr(src)
})
g.move(src, temp)
}
// Navigation.
var (
scanFwd = "[" + strings.Repeat(">", highwayStride) + "]"
scanBack = "[" + strings.Repeat("<", highwayStride) + "]"
)
// moveToSentinel navigates to the forward sentinel (position 40).
// Moves to the nearest highway marker, then scans forward with [>>>>>>>>].
// If already past the last marker, moves directly.
func (g *Generator) moveToSentinel() {
marker := max(((g.pos+highwayStride-1)/highwayStride)*highwayStride, highwayStride)
g.moveTo(marker)
if marker < sentinelFwd {
g.emit(scanFwd)
}
g.pos = sentinelFwd
}
// backToHome navigates to the backward sentinel (position 0).
// Moves to the nearest highway marker, then scans backward with [<<<<<<<<].
// If already before the first marker, moves directly.
func (g *Generator) backToHome() {
marker := min((g.pos/highwayStride)*highwayStride, sentinelFwd-highwayStride)
g.moveTo(marker)
if marker > sentinelBack {
g.emit(scanBack)
}
g.pos = sentinelBack
}
// backToSentinel scans backward through the guard column to the sentinel.
// The pointer must be on a guard column cell before calling.
func (g *Generator) backToSentinel() {
g.emit("[<<<]")
g.pos = sentinelFwd
}
// homeFromBreadcrumb navigates from the breadcrumb guard (=0) to position 0.
// Skips past the breadcrumb guard with <<< to reach the previous guard column,
// then navigates home.
func (g *Generator) homeFromBreadcrumb() {
g.emit("<<<")
g.backToSentinel()
g.backToHome()
}
// goToBreadcrumb navigates from position 0 to the first guard=0 cell.
// When a breadcrumb is set, this is the breadcrumb slot's guard.
// When no breadcrumb is set, this is the stack end (first unallocated slot).
func (g *Generator) goToBreadcrumb() {
g.moveToSentinel()
g.emit(">>>[>>>]")
}
// restoreBreadcrumb restores the guard and navigates home.
func (g *Generator) restoreBreadcrumb() {
g.goToBreadcrumb()
g.emit("+")
g.backToSentinel()
g.backToHome()
}
// Control flow.
// emitIfElse executes thenFn if cond != 0, elseFn otherwise. Preserves cond.
// Uses 2 temps: copies cond to t, sets u=1 as the else flag.
// Then-branch decrements u (exactly 1, so becomes 0);
// else-branch runs if u is still 1.
func (g *Generator) emitIfElse(cond int, thenFn, elseFn func()) {
t := g.temps.alloc()
u := g.temps.alloc()
g.copy(t, cond, u)
g.incr(u)
g.emitIf(t, func() {
thenFn()
g.decr(u)
})
g.temps.free(t)
g.while(u, func() {
elseFn()
g.decr(u)
})
g.temps.free(u)
}
// emitIf executes bodyFn if cond != 0, consuming cond (sets it to 0).
func (g *Generator) emitIf(cond int, bodyFn func()) {
g.while(cond, func() {
bodyFn()
g.clear(cond)
})
}
// while executes bodyFn repeatedly while cond != 0.
func (g *Generator) while(cond int, bodyFn func()) {
g.moveTo(cond)
g.emit("[")
bodyFn()
g.moveTo(cond)
g.emit("]")
}
// Register cache helpers.
func (g *Generator) ensureReg(cell int, avoid []int) int {
if isReg(cell) {
return cell
}
return g.cache.ensure(slotOf(cell), avoid)
}
func (g *Generator) assignReg(cell int, avoid []int) int {
if isReg(cell) {
return cell
}
return g.cache.assign(slotOf(cell), avoid)
}
func (g *Generator) markDirty(cell, rp int) {
if !isReg(cell) {
g.cache.markDirty(rp)
}
}
// evictConsumed removes a consumed source from the cache without writeback.
func (g *Generator) evictConsumed(cell int) {
if isReg(cell) {
return
}
for i := range g.cache.regs {
if g.cache.regs[i].slot == slotOf(cell) {
g.cache.regs[i] = regEntry{slot: -1}
return
}
}
}
// IR node dispatch.
func (g *Generator) genNode(node IRNode) {
switch n := node.(type) {
case *IRZero:
reg := g.assignReg(n.Dst, nil)
g.comment("zero r%d", reg)
g.clear(reg)
g.markDirty(n.Dst, reg)
case *IRConst:
reg := g.assignReg(n.Dst, nil)
g.comment("const r%d %d", reg, n.Value)
g.set(reg, n.Value)
g.markDirty(n.Dst, reg)
case *IRMove:
src := g.ensureReg(n.Src, nil)
dst := g.assignReg(n.Dst, []int{src})
if src != dst {
g.comment("move r%d r%d", dst, src)
g.clear(dst)
g.move(dst, src)
}
g.markDirty(n.Dst, dst)
if !isReg(n.Src) {
for i := range g.cache.regs {
if g.cache.regs[i].slot == slotOf(n.Src) {
g.cache.regs[i] = regEntry{slot: -1}
break
}
}
}
case *IRCopy:
src := g.ensureReg(n.Src, nil)
dst := g.assignReg(n.Dst, []int{src})
if src != dst {
g.comment("copy r%d r%d", dst, src)
ct, freeT := g.allocTemp(src)
g.copy(dst, src, ct)
freeT()
}
g.markDirty(n.Dst, dst)
case *IRAddI:
reg := g.ensureReg(n.Dst, nil)
g.comment("addi r%d %d", reg, n.Value)
g.emitAdd(reg, int(n.Value))
g.markDirty(n.Dst, reg)
case *IRSubI:
reg := g.ensureReg(n.Dst, nil)
g.comment("subi r%d %d", reg, n.Value)
g.emitSub(reg, int(n.Value))
g.markDirty(n.Dst, reg)
case *IRAdd:
r1 := g.ensureReg(n.Src1, nil)
r2 := g.ensureReg(n.Src2, []int{r1})
rd := g.assignReg(n.Dst, []int{r1, r2})
g.comment("add r%d r%d r%d", rd, r1, r2)
g.genAdd(rd, r1, r2)
g.markDirty(n.Dst, rd)
case *IRSub:
r1 := g.ensureReg(n.Src1, nil)
r2 := g.ensureReg(n.Src2, []int{r1})
rd := g.assignReg(n.Dst, []int{r1, r2})
g.comment("sub r%d r%d r%d", rd, r1, r2)
g.genSub(rd, r1, r2)
g.markDirty(n.Dst, rd)
case *IRMul:
r1 := g.ensureReg(n.Src1, nil)
r2 := g.ensureReg(n.Src2, []int{r1})
rd := g.assignReg(n.Dst, []int{r1, r2})
g.comment("mul r%d r%d r%d", rd, r1, r2)
g.genMul(rd, r1, r2)
g.markDirty(n.Dst, rd)
case *IRDiv:
r1 := g.ensureReg(n.Src1, nil)
r2 := g.ensureReg(n.Src2, []int{r1})
rd := g.assignReg(n.Dst, []int{r1, r2})
g.comment("div r%d r%d r%d", rd, r1, r2)
g.genDiv(rd, r1, r2)
g.markDirty(n.Dst, rd)
case *IRMod:
r1 := g.ensureReg(n.Src1, nil)
r2 := g.ensureReg(n.Src2, []int{r1})
rd := g.assignReg(n.Dst, []int{r1, r2})
g.comment("mod r%d r%d r%d", rd, r1, r2)
g.genMod(rd, r1, r2)
g.markDirty(n.Dst, rd)
case *IRDivMod:
r1 := g.ensureReg(n.Src1, nil)
r2 := g.ensureReg(n.Src2, []int{r1})
rq := g.assignReg(n.QuotDst, []int{r1, r2})
rr := g.assignReg(n.RemDst, []int{r1, r2, rq})
g.comment("divmod r%d r%d r%d r%d", rq, rr, r1, r2)
g.genDivMod(rq, rr, r1, r2)
g.markDirty(n.QuotDst, rq)
g.markDirty(n.RemDst, rr)
case *IRAnd:
r1 := g.ensureReg(n.Src1, nil)
r2 := g.ensureReg(n.Src2, []int{r1})
rd := g.assignReg(n.Dst, []int{r1, r2})
g.comment("and r%d r%d r%d", rd, r1, r2)
g.genBitwise(rd, r1, r2, bitwiseAND)
g.markDirty(n.Dst, rd)
case *IROr:
r1 := g.ensureReg(n.Src1, nil)
r2 := g.ensureReg(n.Src2, []int{r1})
rd := g.assignReg(n.Dst, []int{r1, r2})
g.comment("or r%d r%d r%d", rd, r1, r2)
g.genBitwise(rd, r1, r2, bitwiseOR)
g.markDirty(n.Dst, rd)
case *IRXor:
r1 := g.ensureReg(n.Src1, nil)
r2 := g.ensureReg(n.Src2, []int{r1})
rd := g.assignReg(n.Dst, []int{r1, r2})
g.comment("xor r%d r%d r%d", rd, r1, r2)
g.genBitwise(rd, r1, r2, bitwiseXOR)
g.markDirty(n.Dst, rd)
case *IRCmp:
r1 := g.ensureReg(n.Src1, nil)
r2 := g.ensureReg(n.Src2, []int{r1})
var consumedCell int
switch n.Op {
case CmpGt, CmpLeq:
consumedCell = n.Src1
default:
consumedCell = n.Src2
}
if !isReg(consumedCell) {
g.cache.flushCell(consumedCell)
} else {
src := r2
if n.Op == CmpGt || n.Op == CmpLeq {
src = r1
}
t := g.temps.allocNear(src)
ct := g.temps.allocNear(src, t)
switch n.Op {
case CmpGt, CmpLeq:
g.copy(t, r1, ct)
r1 = t
default:
g.copy(t, r2, ct)
r2 = t
}
g.temps.free(ct)
defer g.temps.free(t)
}
rd := g.assignReg(n.Dst, []int{r1, r2})
g.genCmp(n.Op, rd, r1, r2)
g.markDirty(n.Dst, rd)
g.evictConsumed(consumedCell)
case *IRNot:
rs := g.ensureReg(n.Src, nil)
rd := g.assignReg(n.Dst, []int{rs})
g.comment("not r%d r%d", rd, rs)
g.genNot(rd, rs)
g.markDirty(n.Dst, rd)
case *IRIf:
cond := g.ensureReg(n.Cond, nil)
// Flush-only (preserve cache mappings) when the if-body has no
// IRDynStore. After flush, all registers are clean and match their
// stack slots. If the body doesn't execute, the cache is still valid.
// If it does, flushAndInvalidate at the end clears it.
//
// When the body contains IRDynStore, we must invalidate. DynStore
// writes to a runtime-determined stack slot via counter-walk. The
// cache cannot track which slot was written. After the DynStore,
// ensureReg may load a cell into a register that previously held
// a different value for the same slot. On the next flush, this
// stale value overwrites the DynStore'd value.
if blockHasDynStore(n.Then) || blockHasDynStore(n.Else) {
g.cache.flushAndInvalidate()
} else {
g.cache.flush()
}
g.comment("if r%d {", cond)
if n.Else == nil {
g.emitIf(cond, func() {
g.genNode(n.Then)
g.cache.flushAndInvalidate()
})
} else {
g.emitIfElse(cond, func() {
g.genNode(n.Then)
g.cache.flushAndInvalidate()
}, func() {
g.comment("} else {")
g.genNode(n.Else)
g.cache.flushAndInvalidate()
})
}
g.comment("}")
case *IRLoop:
cond := g.ensureReg(n.Cond, nil)
condSlot := slotOf(n.Cond)
g.cache.flushAndInvalidate()
g.while(cond, func() {
g.genNode(n.Body)
g.cache.flushAndInvalidate()
if !isReg(n.Cond) {
g.loadFromStack(cond, condSlot)
}
})
case *IRPutc:
reg := g.ensureReg(n.Src, nil)
g.comment("putc r%d", reg)
g.moveTo(reg)
g.emit(".")
case *IRGetc:
reg := g.assignReg(n.Dst, nil)
g.comment("getc r%d", reg)
g.moveTo(reg)
g.emit(",")
g.markDirty(n.Dst, reg)
case *IRDynLoad:
idx := g.ensureReg(n.Index, nil)
g.cache.flushAndInvalidate()
result := regPos[0]
if result == idx {
result = regPos[1]
}
g.genDynLoad(result, n.BaseSlot, idx)
g.storeToStack(slotOf(n.Dst), result)
case *IRDynStore:
idx := g.ensureReg(n.Index, nil)
src := g.ensureReg(n.Src, []int{idx})
g.cache.flushAndInvalidate()
g.genDynStore(n.BaseSlot, idx, src)
case *IRBlock:
for _, node := range n.Nodes {
g.genNode(node)
}
case *IRFramePush:
g.cache.flushAndInvalidate()
g.genFramePush(n.Slots)
case *IRFramePop:
g.cache.flushAndInvalidate()
g.genFramePop(n.Slots)
case *IRFramePushDyn:
src := g.ensureReg(n.Size, nil)
g.cache.flushAndInvalidate()
g.genFramePushDyn(src)
case *IRFramePopDyn:
src := g.ensureReg(n.Size, nil)
g.cache.flushAndInvalidate()
g.genFramePopDyn(src)
case *IRLoadFrame:
dst := g.ensureReg(n.Dst, nil)
g.genLoadFrame(dst, n.Slot, n.FrameSize)
case *IRStoreFrame:
src := g.ensureReg(n.Src, nil)
g.genStoreFrame(n.Slot, src, n.FrameSize)
case *IRDispatch:
g.cache.flushAndInvalidate()
g.genDispatch(n)
case *IRFree:
g.cache.dropCell(n.Cell)
}
}
// blockHasDynStore checks if a block contains any IRDynStore node.
func blockHasDynStore(b *IRBlock) bool {
if b == nil {
return false
}
for _, node := range b.Nodes {
switch n := node.(type) {
case *IRDynStore:
return true
case *IRIf:
if blockHasDynStore(n.Then) || blockHasDynStore(n.Else) {
return true
}
case *IRLoop:
if blockHasDynStore(n.Body) {
return true
}
case *IRBlock:
if blockHasDynStore(n) {
return true
}
}
}
return false
}
// Arithmetic codegen.
// genAdd sets dst = src1 + src2. Skips one copy when dst == src1 or src2.
func (g *Generator) genAdd(dst, src1, src2 int) {
t1 := g.temps.allocNear(dst, src1, src2)
t2 := g.temps.allocNear(dst, src1, src2)
defer g.temps.free(t1)
defer g.temps.free(t2)
switch dst {
case src1:
g.copy(t2, src2, t1)
g.move(dst, t2)
case src2:
g.copy(t2, src1, t1)
g.move(dst, t2)
default:
g.copy(dst, src1, t1)
g.copy(t2, src2, t1)
g.move(dst, t2)
}
}
// genSub sets dst = src1 - src2. Skips one copy when dst == src1.
func (g *Generator) genSub(dst, src1, src2 int) {
t1 := g.temps.allocNear(dst, src1, src2)
t2 := g.temps.allocNear(dst, src1, src2)
defer g.temps.free(t1)
defer g.temps.free(t2)
if dst == src1 {
g.copy(t2, src2, t1)
g.subtract(dst, t2)
} else {
g.copy(dst, src1, t1)