summaryrefslogtreecommitdiff
path: root/emit.fun
blob: 90cbaa2e66792a3070ce7e88eefb0145167cb453 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
functor Emit(I: IL) = struct
  structure I = I

  structure P = I.P
  structure D = P.D
  structure PP = P.P

  val ip = I

  val file = ref NONE

  datatype reg =
    Rax | Rbx | Rcx | Rdx | Rsi | Rdi | Rbp | Rsp | R8 |
    R9 | R10 | R11 | R12 | R13 | R14 | R15

  datatype vConst = VConst of word | VAddrConst of int * word
  datatype vrType =
    VtConst of vConst | VtReg of reg | VtStack of int | VtUnk

  datatype affinity = AfHard of reg | AfSoft of int list | AfUnk

  val regs = [
    (R8, 0),
    (R9, 1),
    (R10, 2),
    (R11, 3),

    (Rbx, 4),
    (R12, 5),
    (R13, 6),
    (R14, 7),
    (R15, 8),

    (Rdi, 9),
    (Rsi, 10),
    (Rdx, 11),
    (Rcx, 12),

    (Rax, 13),
    (Rsp, 14),
    (Rbp, 15)
  ]

  val callerSavedRegs = 4
  val usedRegNum = 9

  val usedOverallRegNum = 13

  fun reg2idx reg =
    case List.find (fn (r, _) => r = reg) regs of
      NONE => raise Unreachable
    | SOME (_, idx) => idx

  fun idx2reg idx =
    case List.find (fn (_, i) => i = idx) regs of
      NONE => raise Unreachable
    | SOME (r, _) => r

  val debugFile = ref NONE

  local
    fun output s =
    let
      val outstream = !debugFile
    in
      case outstream of
        NONE => ()
      | SOME outstream => TextIO.output (outstream, s)
    end

    val ctx = ((false, makePrintfBase output),
      fn (_: bool * ((string -> unit) * (unit -> unit))) => ())
  in
    fun dprintf g = Fold.fold ctx g
  end

  local
    fun output s =
    let
      val outstream = valOf $ !file
    in
      TextIO.output (outstream, s)
    end

    val ctx = ((false, makePrintfBase output),
      fn (_: bool * ((string -> unit) * (unit -> unit))) => ())
  in
    fun fprint g = Fold.fold ctx g
  end

  fun fprintt g = fprint `"\t" g

  fun fprinttn g =
    fprintt (fn (a, _) => g (a, fn (_, out) => (Printf out `"\n" %)))

  fun handleBSS objsZI =
  let
    val () = fprint `"section .bss\n" %

    fun handleObj (id, _, t, _, _) =
    let
      val align = P.alignOfType t
      val size = P.sizeOfType t
    in
      fprinttn `"align\t" W align %;
      fprint PP.? id `":\tresb " W size `"\n" %
    end
  in
    List.app handleObj objsZI
  end

  fun dd size w =
  let
    val cmd =
      case size of
        0w1 => "db"
      | 0w2 => "dw"
      | 0w4 => "dd"
      | 0w8 => "dq"
      | _ => raise Unreachable
  in
    fprint `cmd `" " W w %
  end

  fun emitAggrLayout id =
  let
    val (_, size, layout) = D.get P.iniLayouts id
    val size = I.wrapTo8 size

    val () = fprint `"\n" %

    fun getPadding offset t [] = size - (offset + P.sizeOfType t)
      | getPadding offset t ({ offset = offset', ... } :: _) =
        offset' - (offset + P.sizeOfType t)

    fun emitScalars ({ offset, t, value } :: tail) =
    let
      val () = fprint `"\t" %
      val () = dd (P.sizeOfType t) value
      val padding = getPadding offset t tail
    in
      if padding > 0w0 then
        fprint `"\n\tresb " W padding `"\n" %
      else
        fprint `"\n" %;
      emitScalars tail
    end
      | emitScalars [] = ()
  in
    emitScalars layout
  end

  fun handleData objs =
  let
    val () = fprint `"section .data\n" %

    fun emitLayout (id, _, t, ini, _) =
    let
      val align = P.alignOfType t
      val () = fprinttn `"align\t" W align %
      val () = fprint PP.? id `":" %
    in
      case ini of
        P.CiniLayout id => emitAggrLayout id
      | P.CiniExpr _ => raise Unreachable
    end
  in
    List.app emitLayout objs
  end

  fun handleStrlits strlits =
  let
    fun unique l =
    let
      val l = sort (op <=) l
      fun u [] acc = rev acc
        | u (x :: xs) [] = u xs [x]
        | u (x :: xs) (y :: ys) =
          if x = y then
            u xs (y :: ys)
          else
            u xs (x :: y :: ys)
    in
      u l []
    end

    fun emitStrlit id =
    let
      val symbols = PP.T.strlit2charList (PP.?? id)

      datatype strPart = SpStr of string | SpOrd of int

      open Char

      fun collectStr (c :: cs) acc =
        if isPrint c andalso (c = #" " orelse not (isSpace c)) then
          collectStr cs (c :: acc)
        else
          let
            val p = SpOrd (ord c)
            val l = collectStr cs []
          in
            if null acc then p :: l else SpStr (implode $ rev acc) :: p :: l
          end
        | collectStr [] acc =
            if null acc then [] else [SpStr (implode $ rev acc)]

     fun printPart (SpStr s) out = Printf out `"\"" `s `"\"" %
       | printPart (SpOrd v) out = Printf out I v %

     fun printStr [] = ()
       | printStr (p :: ps) = (fprint A1 printPart p `", " %; printStr ps)

      val parts = collectStr symbols []
    in
      fprint `"S." I id `":\t" %;
      fprint `"db " %;
      List.app (fn p => fprint A1 printPart p `", " %) parts;
      fprint `"0\n" %
    end
  in
    fprint `"\n" %;
    List.app emitStrlit (unique strlits)
  end

  fun handleLocalIniLayouts () =
  let
    fun f (_, (true, _, _)) = ()
      | f (n, (false, _, _)) = (
        fprint `"\talign 16\n" %;
        fprint `"I." I n `":" %;
        emitAggrLayout n
      )
  in
    D.appi f P.iniLayouts
  end

  fun extendEnd (iStart, iEnd) ops labels =
  let
    fun loop idx iEnd =
      if idx = D.length ops then
        iEnd
      else
        let
          val (ins, _) = D.get ops idx
        in
          case ins of
            SOME (I.IrJmp lid) | SOME (I.IrJz (_, lid)) |
            SOME (I.IrJnz (_, lid)) =>
            let
              val ldest = valOf $ D.get labels lid

              val iEnd =
                if ldest > iStart andalso ldest < iEnd then
                  idx
                else
                  iEnd
            in
              loop (idx + 1) iEnd
            end
          | _ => loop (idx + 1) iEnd
        end
  in
    loop iEnd iEnd
  end

  fun computeIntLocal (s, e) firstDef ops labels =
  let
    val e = extendEnd (s, e) ops labels

    val (_, li) = D.get ops firstDef
  in
    case li of
      SOME (startL, endL) =>
      let
        val (startLoop, endLoop) =
          (valOf $ D.get labels startL, valOf $ D.get labels endL)

        val s = if s < startLoop then s else startLoop
        val e = if e > endLoop then e else endLoop
      in
        (s, e)
      end
    | _ => (s, e)
  end

  fun getBasicInt [] _ = raise Unreachable
    | getBasicInt defs [] = (List.last defs, hd defs + 1)
    | getBasicInt defs use =
    let
      val (firstDef, lastDef) = (List.last defs, hd defs)
      val (firstUse, lastUse) = (List.last use, hd use)

      val first = if firstDef < firstUse then firstDef else firstUse - 1
      val last = if lastDef < lastUse then lastUse else lastDef + 1
    in
      (first, last)
    end

  fun computeInt (I.Fi { vregs, ops, localBound, labels, ... }) var =
  let
    val { defs, use, ... } = D.get vregs var
    val (iStart, iEnd) = getBasicInt defs use

    val (iStart, iEnd) =
      if var < localBound then
        computeIntLocal (iStart, iEnd) (List.last defs) ops labels
      else
        (iStart, iEnd)
  in
    (var, iStart, iEnd)
  end

  fun computeInts F vars = List.map (computeInt F) vars

  fun printInts ints =
  let
    val () = dprintf `"\nsorted intervals:\n" %
    fun p (id, s, e) = dprintf `"id: %" I id `" {" I s `", " I e `"}\n" %
  in
    List.app p ints;
    dprintf `"\n" %
  end

  fun updAff arr idx aff =
  let
    val (_, vt) = Array.sub (arr, idx)
  in
    Array.update (arr, idx, (aff, vt))
  end

  datatype insAff = IaNone | IaHard of (int * reg) list
                  | IaSoft of int * int list

  fun parNum2reg pr =
    case pr of
      0 => Rdi
    | 1 => Rsi
    | 2 => Rdx
    | 3 => Rcx
    | 5 => R8
    | 6 => R9
    | _ => raise Unreachable

  fun getInsAff (SOME ins) =
  let
    fun tr (rd, rs1, rs2) = IaSoft (rd, [rs1, rs2])

    fun setAff (rd, I.SaVReg rs) = IaSoft (rd, [rs])
      | setAff _ = IaNone

    fun fcallAff args =
    let
      fun collect idx (arg :: args) acc =
        collect (idx + 1) args ((arg, parNum2reg idx) :: acc)
        | collect _ [] acc = rev acc
    in
      IaHard $ collect 0 args []
    end
  in
    case ins of
      I.IrSet p => setAff p
    | I.IrAdd t => tr t
    | I.IrSub t => tr t
    | I.IrMul t => tr t
    | I.IrIMul t => tr t
    | I.IrDiv t => tr t
    | I.IrIDiv t => tr t
    | I.IrMod t => tr t
    | I.IrIMod t => tr t
    | I.IrShl t => tr t
    | I.IrShr t => tr t
    | I.IrSar t => tr t
    | I.IrAnd t => tr t
    | I.IrOr t => tr t
    | I.IrXor t => tr t

    | I.IrCmp (_, _, _, _) => IaNone

    | I.IrExtZero _ | I.IrExtSign _
    | I.IrLoad _ | I.IrStore _ | I.IrJmp _
    | I.IrJz _ | I.IrJnz _ | I.IrJmpc _ | I.IrNopLabel _
    | I.IrNop _ | I.IrRet _ | I.IrAlloc _
    | I.IrCopy _ => IaNone
    | I.IrFcall (_, _, args) => fcallAff args
  end
   | getInsAff NONE = IaNone

  fun updateSoftAff rinfo rd rss =
  let
    fun sort [r] = [r]
      | sort [rs1, rs2] = if rs1 < rs2 then [rs1, rs2] else [rs2, rs1]
      | sort _ = raise Unreachable

    fun isNotConst rv =
    let
      val (_, vt) = Array.sub (rinfo, rv)
    in
      case vt of
        VtConst _ => false
      | _ => true
    end

    val (aff, vt) = Array.sub (rinfo, rd)
    val rss = List.filter isNotConst $ sort rss

    fun insertSorted ins [] = ins
      | insertSorted [] acc = acc
      | insertSorted (x :: xs) (y :: ys) =
        if x < y then
          x :: insertSorted xs (y :: ys)
        else
          y :: insertSorted (x :: xs) ys

    val aff =
      case aff of
        AfUnk => AfSoft rss
      | AfSoft affs => AfSoft $ insertSorted rss affs
      | AfHard _ => aff
  in
    Array.update (rinfo, rd, (aff, vt))
  end

  fun updateHardAff rinfo hards =
  let
    fun f (rd, reg) =
    let
      val (aff, vt) = Array.sub (rinfo, rd)

      val aff =
        case aff of
          AfUnk | AfSoft _ => AfHard reg
        | AfHard _ => raise Unreachable
    in
      Array.update (rinfo, rd, (aff, vt))
    end
  in
    List.app f hards
  end

  fun compAffinity rinfo ops paramNum =
  let
    fun compParams idx =
      if idx = paramNum then
        ()
      else
        let
          val reg = parNum2reg idx
        in
          updAff rinfo idx (AfHard reg);
          compParams (idx + 1)
        end
    val () = compParams 0

    fun loop idx =
      if idx = D.length ops then
        ()
      else
        let
          val (ins, _) = D.get ops idx
        in
          case getInsAff ins of
            IaNone => ()
          | IaSoft (rd, rss) => updateSoftAff rinfo rd rss
          | IaHard hards => updateHardAff rinfo hards;
          loop (idx + 1)
        end
  in
    loop 0
  end

  fun prepareRegInfo paramNum ops vregs =
  let
    val rinfo = Array.array (D.length vregs, (AfUnk, VtUnk))

    val () = compAffinity rinfo ops paramNum;

    fun transfer idx acc =
      if idx = D.length vregs then
        rev acc
      else
      let
        val (aff, _) = Array.sub (rinfo, idx)

        val (vt, cand) =
          case #t $ D.get vregs idx of
            I.RtRem => (VtUnk, NONE)
          | I.RtConst w => (VtConst (VConst w), NONE)
          | I.RtAddrConst (id, w) =>
              (VtConst (VAddrConst (id, w)), NONE)
          | I.RtReg => (
            case aff of
              AfHard reg => (VtReg reg, NONE)
            | _ => (VtUnk, SOME idx)
          )
      in
        Array.update (rinfo, idx, (aff, vt));
        transfer (idx + 1) (if isSome cand then valOf cand :: acc else acc)
      end

    val toAlloc = transfer 0 []
  in
    (toAlloc, rinfo)
  end

  fun preg reg out =
  let
    val s =
      case reg of
        Rax => "rax"
      | Rbx => "rbx"
      | Rcx => "rcx"
      | Rdx => "rdx"
      | Rsi => "rsi"
      | Rdi => "rdi"
      | Rbp => "rbp"
      | Rsp => "rsp"
      | R8 => "r8"
      | R9 => "r9"
      | R10 => "r10"
      | R11 => "r11"
      | R12 => "r12"
      | R13 => "r13"
      | R14 => "r14"
      | R15 => "r15"
  in
    Printf out `s %
  end

  val Preg = fn z => bind A1 preg z

  fun affPrint rinfo =
  let
    fun pv idx out = Printf out `"%" I idx %

    fun p (idx, (aff, _)) =
    let
      val () = dprintf `"%" I idx %
    in
      case aff of
       AfUnk => dprintf `" = unk\n" %
     | AfHard reg => dprintf `" <- " Preg reg `"\n" %
     | AfSoft rss => dprintf `" <- " Plist pv rss (", ", true, 1) `"\n" %
    end
  in
    Array.appi p rinfo
  end

  fun updateI i = fn z =>
  let
    fun from rinfo active pool intervals stackOff  =
      { rinfo, active, pool, intervals, stackOff }
    fun to f { rinfo, active, pool, intervals, stackOff } =
      f rinfo active pool intervals stackOff
  in
    FRU.makeUpdate5 (from, from, to) i
  end z

  fun returnToPool pool reg =
  let
    val idx = reg2idx reg
  in
    Array.update (pool, idx, NONE)
  end

  fun expireOne { rinfo, active, pool, ... } (_, start, _) =
    case !active of
      [] => false
    | (j, startp, endp) :: acts =>
      if endp > start then
        false
      else
        let
          val (_, vt) = Array.sub (rinfo, j)
          val reg = case vt of VtReg reg => reg | _ => raise Unreachable

          val () = dprintf `"III!!! interval %"
              ip j `"(" ip startp `", " ip endp `") "
              `"with " Preg reg `" has expired\n" %
        in
          returnToPool pool reg;
          active := acts;
          true
        end

  fun expireOld (I as { active, ... }) int =
    let
      fun loop I =
        case expireOne I int of
          false => dprintf `"\n" %
        | true => loop I
    in
      case !active of
        [] => ()
      | _ => (dprintf `"\n" %; loop I)
    end

  fun addToActive int [] = [int]
    | addToActive (I as (_, _, e1)) (act :: acts) =
    if e1 < #3 act then
      (I :: act :: acts)
    else
      act :: addToActive I acts

  fun updReg arr idx reg =
  let
    val (aff, _) = Array.sub (arr, idx)
  in
    Array.update (arr, idx, (aff, reg))
  end

  fun getUser pool r = Array.sub (pool, reg2idx r)
  fun setUser pool u r = Array.update(pool, reg2idx r, SOME u)

  fun assignFirstReg poff { rinfo, pool, ... } vr =
  let
    fun loop idx =
      if idx = Array.length pool then
        raise Unreachable
      else
        let
          val user = Array.sub (pool, idx)
        in
          case user of
            SOME _ => loop (idx + 1)
          | NONE =>
            let
              val reg = idx2reg idx
              val () = setUser pool vr reg

              val () = dprintf R poff
                `"assigned (first) reg " Preg reg `" to %" ip vr `"\n" %
            in
              updReg rinfo vr (VtReg reg)
            end
        end
  in
    loop 0
  end

  fun freeRegList pool =
  let
    fun loop idx acc =
      if idx = Array.length pool then
        rev acc
      else
        case Array.sub (pool, idx) of
          NONE => loop (idx + 1) (idx2reg idx :: acc)
        | SOME _ => loop (idx + 1) acc
  in
    loop 0 []
  end

  fun getAffRegList rinfo affs =
  let
    fun loop [] acc = rev acc
      | loop (vr :: vrs) acc =
      let
        val (_, vt) = Array.sub (rinfo, vr)
      in
        case vt of
          VtReg r => loop vrs (r :: acc)
        | _ => loop vrs acc
      end
  in
    loop affs []
  end

  fun findCommonRegs l1 l2 =
  let
    val l1 = sort (fn (r1, r2) => reg2idx r1 <= reg2idx r2) l1
    val l2 = sort (fn (r1, r2) => reg2idx r1 <= reg2idx r2) l2

    fun intersection [] _ = []
      | intersection _ [] = []
      | intersection (x :: xs) (y :: ys) =
        case Int.compare (reg2idx x, reg2idx y) of
          LESS => intersection xs (y :: ys)
        | EQUAL => x :: intersection xs ys
        | GREATER => intersection (x :: xs) ys
  in
    intersection l1 l2
  end

  fun assignSoftReg poff affs (I as { rinfo, pool, ... }) vr =
  let
    val () = dprintf R poff
      `"trying to assign register (by affinity) to %" ip vr `"\n" %

    val regs = freeRegList pool
    val affRegs = getAffRegList rinfo affs
    val common = findCommonRegs regs affRegs

    val () = dprintf R (poff + 1)
      `"free registers: " Plist preg regs (", ", true, 0) `"\n" %
    val () = dprintf R (poff + 1)
      `"affinity registers: " Plist preg affRegs (", ", true, 0) `"\n" %
  in
    case common of
      [] =>
      let
        val () = dprintf R (poff + 1) `"affinity was not satisfied\n" %
      in
        assignFirstReg (poff + 2) I vr
      end
    | (reg :: _) =>
      let
      in
        updReg rinfo vr (VtReg reg);
        setUser pool vr reg;

        dprintf R (poff + 1)
          `"assigned (by affinity) reg " Preg reg `" to %" ip vr `"\n" %;
        dprintf R (poff + 1)
          `"free registers: " Plist preg (freeRegList pool) (", ", true, 0)
          `"\n" %
      end
  end

  fun putToStack poff { rinfo, stackOff, ... } vr =
  let
    val newStackOff = !stackOff - 8
    val () = dprintf R poff
      `"puting %" ip vr `" to stack: " ip newStackOff `"\n" %
  in
    updReg rinfo vr (VtStack newStackOff);
    stackOff := newStackOff
  end

  fun assignReg (I as { rinfo, ... }) (vr, _, _) =
  let
    val (aff, _) = Array.sub (rinfo, vr)
  in
    case aff of
      AfUnk => assignFirstReg 0 I vr
    | AfSoft affs => assignSoftReg 0 affs I vr
    | AfHard _ => raise Unreachable
  end

  fun getPool () = Array.array (usedRegNum, NONE)

  fun changeInActive active newInt oldVr =
  let
    val a = !active
    val a = List.filter (fn (v, _, _) => v <> oldVr) a
  in
    active := addToActive newInt a
  end

  fun userIdx pool vr =
  let
    fun loop idx =
      if idx = Array.length pool then
        raise Unreachable
      else
        case Array.sub (pool, idx) of
          SOME u =>
            if u = vr then
              idx
            else
              loop (idx + 1)
        | NONE => loop (idx + 1)
  in
    loop 0
  end

  fun spillAtInterval (I as { rinfo, active, pool, ... }) int =
  let
    val spill = List.last (!active)

    val vr = #1 int

    val () = dprintf `"SpillAtInt\n" %
    val () = dprintf R 0
      `"free registers: " Plist preg (freeRegList pool) (", ", true, 0) `"\n" %
  in
    if #3 spill > #3 int then
      let
        val () = dprintf `"spilling!!!\n" %
        val idx = userIdx pool (#1 spill)
        val reg = idx2reg idx
      in
        setUser pool vr reg;
        updReg rinfo vr (VtReg reg);
        putToStack 1 I (#1 spill);
        changeInActive active int (#1 spill)
      end
    else
      putToStack 0 I vr
  end

  fun linearscan rinfo ints stackOff =
  let
    fun incStart ((_, start1, _), (_, start2, _)) = start1 <= start2
    val ints = sort incStart ints

    val () = printInts ints

    fun loop { stackOff, ... } [] = stackOff
      | loop (I as { active, ... }) (int :: ints) =
      let
        val () = expireOld I int

        val () = dprintf `"inspecting interval %"
            ip (#1 int) `": (" ip (#2 int) `", " ip (#3 int) `")\n" %

        val () =
          if length (!active) < usedRegNum then
            let
              val () = assignReg I int
            in
              active := addToActive int (!active)
            end
          else
            spillAtInterval I int
      in
        loop I ints
      end
  in
    loop { active = ref [], pool = getPool (), rinfo,
      stackOff = ref stackOff } ints
  end

  fun pr is8 reg out =
  let
    fun old s =
    let
      val s = if is8 then s else "e" ^ String.extract (s, 1, NONE)
    in
      Printf out `s %
    end

    fun new s = Printf out `(if is8 then s else s ^ "d") %
  in
    case reg of
      Rcx => old "rcx"
    | Rsi => old "rsi"
    | Rdi => old "rdi"
    | R8 => new "r8"
    | R9 => new "r9"
    | R10 => new "r10"
    | R11 => new "r11"

    | Rbx => old "rbx"
    | R12 => new "r12"
    | R13 => new "r13"
    | R14 => new "r14"
    | R15 => new "r15"

    | Rax => old "rax"
    | Rdx => old "rdx"
    | Rsp => old "rsp"
    | Rbp => old "rbp"
  end

  fun printAllocVar rinfo v =
  let
    val () = dprintf `"%" I v `": " %
    val (_, vt) = Array.sub (rinfo, v)
  in
    case vt of
      VtStack off => dprintf `"stack " I off `"\n" %
    | VtReg reg => dprintf `"reg " A1 preg reg `"\n" %
    | VtConst _ | VtUnk => raise Unreachable
  end

  fun printAlloced rinfo toAlloc =
  let
    val () = dprintf `"\nallocated:\n\n" %
  in
    List.app (printAllocVar rinfo) toAlloc
  end

  fun getUsedRegs rinfo =
  let
    val regs = Array.array (usedOverallRegNum, false)

    fun loop idx =
      if idx = Array.length rinfo then
        ()
      else
        let
          val (_, vt) = Array.sub (rinfo, idx)
        in
          case vt of
            VtReg reg => Array.update (regs, reg2idx reg, true)
          | _ => ();
          loop (idx + 1)
        end
    val () = loop 0

    fun collect idx acc =
      if idx = usedRegNum then
        acc
      else
        if Array.sub (regs, idx) then
          collect (idx + 1) (idx2reg idx :: acc)
        else
          collect (idx + 1) acc
  in
    collect 0 []
  end

  fun getRegsToSave rinfo =
  let
    val regs = getUsedRegs rinfo
  in
    List.filter (fn r => reg2idx r >= callerSavedRegs) regs
  end

  fun initMap len =
  let
    open Array
    val map = array (len, array (callerSavedRegs, NONE))
    val i = ref 1
  in
    while !i < len do (
        update (map, !i, array (callerSavedRegs, NONE));
        i := !i + 1
    );
    map
  end

  fun computeMap len intervals rinfo =
  let
    val map = initMap len

    fun addInt (vr, startp, endp) =
      case #2 $ Array.sub (rinfo, vr) of
        VtReg reg =>
          let
            fun f idx =
              if reg2idx reg >= callerSavedRegs orelse idx = endp then
                ()
              else
                let
                  val row = Array.sub (map, idx)
                in
                  Array.update (row, reg2idx reg, SOME vr);
                  f (idx + 1)
                end
          in
            f (startp + 1)
          end
      | _ => ()
  in
    List.app addInt intervals;
    map
  end

  fun printMap map =
  let
    val () = dprintf `"Register map\n\n" %

    fun printHeader idx =
      if idx = callerSavedRegs then
        dprintf `"\n" %
      else
        let
          val reg = sprintf Preg (idx2reg idx) %
          val reg = if size reg = 3 then reg else " " ^ reg
        in
          dprintf `" " `reg `" " %;
          printHeader (idx + 1)
        end
    val () = dprintf `"      " %
    val () = printHeader 0

    fun printRow (idx, row) =
    let
      val () = dprintf Ip 4 idx `": " %

      fun loop idx =
        if idx = callerSavedRegs then
          dprintf `"\n" %
        else (
          case Array.sub (row, idx) of
            NONE => dprintf `"     " %
          | SOME vr =>
            let
              val n: string = sprintf I vr %
              val n =
                if size n < 3 then
                  implode (List.tabulate (3 - size n, fn _ => #" ")) ^ n
                else
                  n
            in
              dprintf `" " `n `" " %
            end;
          loop (idx + 1)
        )
    in
      loop 0
    end
  in
    Array.appi printRow map
  end

  fun resolveAlloc ops =
  let
    fun loop idx stackOffset =
      if idx = D.length ops then
        stackOffset
      else
        case D.get ops idx of
          (SOME (I.IrAlloc (v, size, _)), li) =>
          let
            val () =
              if Word.mod (size, 0w8) <> 0w0 then
                raise Unreachable
              else
                ()

            val stackOffset = stackOffset - Word.toInt size
            val negOffset = ~stackOffset
            val ins = (SOME $ I.IrAlloc (v, size, SOME negOffset), li)
          in
            D.set ops idx ins;
            loop (idx + 1) stackOffset
          end
        | (NONE, _) | (SOME _, _) => loop (idx + 1) stackOffset
  in
    loop 0 0
  end

  fun regAlloc (F as I.Fi { vregs, ops, paramNum, ... }) =
  let
    val stackOffset = resolveAlloc ops
    val (toAlloc, regInfo) = prepareRegInfo paramNum ops vregs
    val () = dprintf `"for alloc: " Plist i toAlloc (", ", true, 0) `"\n" %

    val () = affPrint regInfo

    val intervals = computeInts F toAlloc

    val stackOffset = linearscan regInfo intervals stackOffset
    val () = printAlloced regInfo toAlloc

    val regsToSave = getRegsToSave regInfo
    val () = dprintf
      `"registers to save: " Plist preg regsToSave (", ", true, 0) `"\n" %

    val regMap = computeMap (D.length ops) intervals regInfo
    val () = printMap regMap
  in
    { regsToSave, stackOffset = !stackOffset, regMap, ops,
      rinfo = regInfo, vregs }
  end

  fun emitPushPopReg op' reg = fprinttn `op' `" " Preg reg %

  fun emitPrologue ({ stackOffset, regsToSave, ... }) name =
  let
    val () = fprint PP.? name `":\n" %
  in
    List.app (emitPushPopReg "push") regsToSave;
    if stackOffset <> 0 then (
      fprinttn `"push rbp" %;
      fprinttn `"mov rbp, rsp" %;
      fprinttn `"sub rsp, " I (~ stackOffset) %
    ) else
      ()
  end

  fun emitEpilogue { regsToSave, stackOffset, ... } = (
    if stackOffset <> 0 then (
      fprinttn `"mov rsp, rbp" %;
      fprinttn `"pop rbp" %
    ) else
      ();
    List.app (emitPushPopReg "pop") (rev regsToSave);
    fprinttn `"ret" %
  )


  fun pm is8 off out =
    Printf out `(if is8 then "qword" else "dword") `" [rbp-" I off `"]"%

  fun getType { rinfo, vregs, ... } vr =
  let
    val (_, vt) = Array.sub (rinfo, vr)
    val { class, ... } = D.get vregs vr
  in
    (if class = I.VR8 then true else false, vt)
  end

  datatype template =
    RRR of reg * reg * reg |
    RRM of reg * reg * int |
    RRV of reg * reg * vConst |
    RMR of reg * int * reg |
    RMM of reg * int * int |
    RMV of reg * int * vConst |
    RVR of reg * vConst * reg |
    RVM of reg * vConst * int |

    MRR of int * reg * reg |
    MRM of int * reg * int |
    MRV of int * reg * vConst |
    MMR of int * int * reg |
    MMM of int * int * int |
    MMV of int * int * vConst |
    MVR of int * vConst * reg |
    MVM of int * vConst * int |

    RR of reg * reg |
    RM of reg * int |
    RV of reg * vConst |
    MR of int * reg |
    MM of int * int |
    MV of int * vConst

  fun pc is8 c out =
    case c of
      VConst w =>
        if is8 then
          Printf out W w %
        else
          Printf out W (P.extz w 0w4) %
    | VAddrConst (id, w) =>
      let
        val repr = PP.?? id
        val repr =
          if String.sub (repr, 0) = #"\"" then
            "S." ^ Int.toString id
          else
            repr
      in
        if w = 0w0 then
          Printf out `repr %
        else
          Printf out `repr I.Pwc I.VR8 w %
      end

  fun wordFitsInNsx N w =
  let
    open Word
    val nm1 = fromInt N - 0w1
  in
    if w < << (0w1, nm1) then (* sign bit is zero *)
      true
    else
      let
        val mask = << (~ 0w1, nm1)
      in
        andb (mask, w) = mask (* sign bit and all bits after == 1 *)
      end
  end

  fun fitsInNsx N c =
    case c of
      VConst w => wordFitsInNsx N w
    | VAddrConst _ => false

  fun opRR is8 op' r1 r2 = sprintf `op' `" " A2 pr is8 r1 `", " A2 pr is8 r2 %
  fun opRM is8 op' r off = sprintf `op' `" " A2 pr is8 r `", " A2 pm is8 off %
  fun opMR is8 op' off r = sprintf `op' `" " A2 pm is8 off `", " A2 pr is8 r %

  fun opRV is8 op' r c =
    sprintf `op' `" " A2 pr is8 r `", " A2 pc is8 c %

  fun opMV is8 op' off c =
    sprintf `op' `" " A2 pm is8 off `", " A2 pc is8 c %

  fun movRR is8 r1 r2 = sprintf `"mov " A2 pr is8 r1 `", " A2 pr is8 r2 %
  fun movRM is8 r off = sprintf `"mov " A2 pr is8 r `", " A2 pm is8 off %
  fun movMR is8 off r = sprintf `"mov " A2 pm is8 off `", " A2 pr is8 r %

  fun isZeroConst (VConst 0w0) = true
    | isZeroConst _ = false

  fun xorIdiom r = sprintf `"xor " A2 pr false r `", " A2 pr false r %

  fun movRV is8 r c =
    if isZeroConst c then
      xorIdiom r
    else
      sprintf `"mov " A2 pr is8 r `", " A2 pc is8 c %

  fun movMV is8 off c =
  let
    val () = if not $ fitsInNsx 32 c then raise Unreachable else ()
  in
    opMV is8 "mov" off c
  end

  fun getTripleTemplate I (rd, rs1, rs2) comm fold =
  let
    val (is81, t1) = getType I rd
    val (is82, t2) = getType I rs1
    val (is83, t3) = getType I rs2

    val () =
      if is81 <> is82 orelse is82 <> is83 then raise Unreachable else ()

    val tmp =
      case (t1, t2, t3) of
        (VtReg r1, VtReg r2, VtReg r3) =>
            if r1 = r2 andalso fold then
              RR (r1, r3)
            else if r1 = r3 andalso comm andalso fold then
              RR (r1, r2)
            else
              RRR (r1, r2, r3)

      | (VtReg r1, VtReg r2, VtStack off) =>
          if r1 = r2 andalso fold then
            RM (r1, off)
          else
            RRM (r1, r2, off)
      | (VtReg r1, VtStack off, VtReg r2) =>
          if r1 = r2 andalso comm andalso fold then
            RM (r1, off)
          else
            RMR (r1, off, r2)

      | (VtReg r1, VtReg r2, VtConst c) =>
          if r1 = r2 andalso fold then
            RV (r1, c)
          else
            RRV (r1, r2, c)
      | (VtReg r1, VtConst c, VtReg r2) =>
          if r1 = r2 andalso comm andalso fold then
            RV (r1, c)
          else
            RVR (r1, c, r2)

      | (VtReg r, VtStack off1, VtStack off2) => RMM (r, off1, off2)

      | (VtReg r, VtStack off, VtConst c) => RMV (r, off, c)
      | (VtReg r, VtConst c, VtStack off) => RVM (r, c, off)

      | (VtStack off, VtReg r1, VtReg r2) => MRR (off, r1, r2)

      | (VtStack off1, VtReg r, VtStack off2) =>
          if off1 = off2 andalso comm andalso fold then
            MR (off1, r)
          else
            MRM (off1, r, off2)
      | (VtStack off1, VtStack off2, VtReg r) =>
          if off1 = off2 andalso fold then
            MR (off1, r)
          else
            MMR (off1, off2, r)

      | (VtStack off, VtReg r, VtConst c) => MRV (off, r, c)
      | (VtStack off, VtConst c, VtReg r) => MVR (off, c, r)

      | (VtStack off1, VtStack off2, VtStack off3) =>
          if off1 = off2 andalso fold then
            MM (off1, off3)
          else if off1 = off3 andalso comm andalso fold then
            MM (off1, off2)
          else
            MMM (off1, off2, off3)

      | (VtStack off1, VtStack off2, VtConst c) =>
          if off1 = off2 andalso fold then
            MV (off1, c)
          else
            MMV (off1, off2, c)
      | (VtStack off1, VtConst c, VtStack off2) =>
          if off1 = off2 andalso comm andalso fold then
            MV (off1, c)
          else
            MVM (off1, c, off2)
      | (VtConst _, _, _) | (VtUnk, _, _) | (_, VtUnk, _) |
        (_, _, VtUnk) | (_, VtConst _, VtConst _) => raise Unreachable
  in
    (is81, tmp)
  end

  fun getUtilMovs is8 =
  let
    val movRR = movRR is8
    val movRM = movRM is8
    val movMR = movMR is8
    val movRV = movRV is8
  in
    { movRR, movRM, movRV, movMR }
  end

  fun getUtilOps is8 op' =
  let
    val opRR = opRR is8 op'
    val opRM = opRM is8 op'
    val opRV = opRV is8 op'
    val opMR = opMR is8 op'
    val opMV = opMV is8 op'
  in
    { opRR, opRM, opRV, opMR, opMV }
  end

  fun emitGenComm I op' triple =
  let
    val (is8, tmp) = getTripleTemplate I triple true true
    val Pr = fn z => bind A1 (pr is8) z
    val { movRR, movRM, movMR, movRV } = getUtilMovs is8
    val { opRR, opRM, opMR, opRV, opMV } = getUtilOps is8 op'
  in
    case tmp of
      RRR (r1, r2, r3) =>
        if op' = "add" then
          [sprintf `"lea " Pr r1 `", [" Pr r2 `"+" Pr r3 `"]" % ]
        else
          [movRR r1 r2, opRR r1 r3]
    | RRM (r1, r2, off) | RMR (r1, off, r2) => [ movRR r1 r2, opRM r1 off ]
    | MMM (off1, off2, off3) =>
        [ movRM Rax off2, opRM Rax off3, movMR off1 Rax ]
    | MRM (off1, r, off2) | MMR (off1, off2, r) =>
        [ movMR off1 r, movRM Rax off2, opMR off1 Rax ]
    | MRR (off, r1, r2) => [ movMR off r1, opMR off r2 ]
    | RMM (r, off1, off2) => [ movRM r off1, opRM r off2 ]
    | RRV (r1, r2, c) | RVR (r1, c, r2) =>
      if fitsInNsx 32 c then
        [ movRR r1 r2, opRV r1 c ]
      else
        [ movRV r1 c, opRR r1 r2 ]
    | MMV (off1, off2, c) | MVM (off1, c, off2) =>
        [ movRV Rax c, opRM Rax off2, movMR off1 Rax ]
    | MRV (off, r, c) | MVR (off, c, r) =>
        [ movRV Rax c, opRR Rax r, movMR off Rax ]
    | RMV (r, off, c) | RVM (r, c, off) => [ movRV r c, opRM r off ]
    | MM (off1, off2) => [ movRM Rax off2, opMR off1 Rax ]
    | MR (off, r) => [ opMR off r ]
    | MV (off, c) =>
        if fitsInNsx 32 c then
          [ opMV off c ]
        else
          [ movRV Rax c, opMR off Rax ]
    | RR (r1, r2) => [ opRR r1 r2 ]
    | RM (r, off) => [ opRM r off ]
    | RV (r, c) =>
      if fitsInNsx 32 c then
        [ opRV r c ]
      else
        [ movRV Rax c, opRR r Rax ]
  end

  fun truncConst (VConst w) N = VConst $ P.extz w N
    | truncConst (C as (VAddrConst _)) _ = C

  fun emitShift I op' triple =
  let
    val (is8, tmp) = getTripleTemplate I triple false true
    val Pr = fn z => bind A1 (pr is8) z
    val { movRR, movRM, movMR, movRV } = getUtilMovs is8
    val opRV = opRV is8 op'
    val opRR = opRR is8 op'
    val opMV = opMV is8 op'

    fun shift3 r1 r2 r3 =
      sprintf `op' `"x " Pr r1 `", " Pr r2 `", " Pr r3 %

    fun shift3m r1 off r2 =
      sprintf `op' `"x " Pr r1 `", " A2 pm is8 off `", " Pr r2 %

    fun t v = truncConst v 0w1
  in
    case tmp of
      RRR (r1, r2, r3) => [shift3 r1 r2 r3]
    | RRM (r1, r2, off) => [movRM Rax off, shift3 r1 r2 Rax]
    | RRV (r1, r2, v) => [movRR r1 r2, opRV r1 (t v)]
    | RMR (r1, off, r2) => [shift3m r1 off r2]
    | RMM (r1, off1, off2) =>
        [movRM Rax off1, movRM Rdx off2, shift3 r1 Rax Rdx]
    | RMV (r, off, v) => [movRM r off, opRV r (t v)]
    | RVR (r1, v, r2) => [movRV Rax v, shift3 r1 Rax r2]
    | RVM (r, v, off) => [movRV Rax v, movRM Rdx off, shift3 r Rax Rdx]
    | MRR (off, r1, r2) => [shift3 Rax r1 r2, movMR off Rax]
    | MRM (off1, r1, off2) =>
        [movRM Rax off2, shift3 Rax r1 Rax, movMR off1 Rax]
    | MRV (off, r, v) => [movRV Rax (t v), shift3 Rax r Rax, movMR off Rax]
    | MMR (off1, off2, v) => [shift3m Rax off2 v, movMR off1 Rax]
    | MMM (off1, off2, off3) =>
        [movRM Rdx off3, shift3m Rax off2 Rdx, movMR off1 Rax]
    | MMV (off1, off2, v) =>
        [movRM Rax off2, opRV Rax (t v), movMR off1 Rax]
    | MVR (off1, v, r) => [movRV Rax v, opRR Rax r, movMR off1 Rax]
    | MVM (off1, v, off2) =>
        [movRV Rax v, movRM Rdx off2, opRR Rax Rdx, movMR off1 Rax]

    | RR (r1, r2) => [opRR r1 r2]
    | RM (r1, off) => [movRM Rax off, shift3 r1 r1 Rax]
    | RV (r1, v) => [opRV r1 (t v)]
    | MR (off, r) => [movRM Rax off, opRR Rax r, movMR off Rax]
    | MM (off1, off2) =>
        [movRM Rax off1, movRM Rdx off2, opRR Rax Rdx, movMR off1 Rax]
    | MV (off, v) => [opMV off (t v)]
  end

  fun wordIsZero w =
    case Word.compare (w, 0w0) of
       EQUAL => true
     | _ => false

  datatype cbv = CbvTrue | CbvFalse | CbvUnsure of int * word

  fun constBoolVal (VConst w) = if wordIsZero w then CbvFalse else CbvTrue
   | constBoolVal (VAddrConst (id, off)) =
    if wordIsZero off then
     CbvTrue
    else
     CbvUnsure (id, off)

  fun emitSub I triple =
  let
    val (is8, tmp) = getTripleTemplate I triple false true
    val { movRR, movRM, movRV, movMR } = getUtilMovs is8
    val { opRR, opRM, opRV, opMR, opMV } = getUtilOps is8 "sub"
  in
    case tmp of
      RRR (r1, r2, r3) => [movRR r1 r2, opRR r1 r3]
    | RRM (r1, r2, off) => [movRR r1 r2, opRM r1 off]
    | RRV (r1, r2, c) =>
      if fitsInNsx 32 c then
        [movRR r1 r2, opRV r1 c]
      else
        [movRR r1 r2, movRV Rax c, opRR r1 Rax]
    | RMR (r1, off, r2) => [movRM r1 off, opRR r1 r2]
    | RMM (r1, off1, off2) =>
        [movRM r1 off1, movRM Rax off2, opRR r1 Rax]
    | RMV (r1, off, v) =>
      if fitsInNsx 32 v then
        [movRM r1 off, opRV r1 v]
      else
        [movRM r1 off, movRV Rax v, opRR r1 Rax]
    | RVR (r1, v, r2) =>
      if r1 = r2 andalso isZeroConst v then
        [sprintf `"neg " A2 pr is8 r1 %]
      else
        [movRV r1 v, opRR r1 r2]
    | RVM (r, v, off) => [movRV r v, opRM r off]
    | MRR (off, r1, r2) => [movRR Rax r1, opRR Rax r2, movMR off Rax]
    | MRM (off1, r, off2) => [opRM r off2, movMR off1 r]
    | MRV (off, r, v) =>
        if fitsInNsx 32 v then
          [movRR Rax r, opRV Rax v, movMR off Rax]
        else
          [movRR Rax r, movRV Rdx v, opRR Rax Rdx, movMR off Rax]
    | MMR (off1, off2, r) => [movRM Rax off2, opRR Rax r, movMR off1 Rax]
    | MMM (off1, off2, off3) =>
        [movRM Rax off2, opRM Rax off3, movMR off1 Rax]
    | MMV (off1, off2, v) =>
        if fitsInNsx 32 v then
          [movRM Rax off2, opRV Rax v, movMR off1 Rax]
        else
          [movRM Rax off2, movRV Rdx v, opRR Rax Rdx, movMR off1 Rax]
    | MVM (off1, v, off2) =>
      if off1 = off2 andalso isZeroConst v then
        [sprintf `"neg " A2 pm is8 off1 %]
      else
        [movRV Rax v, opRM Rax off2, movMR off1 Rax]
    | MVR (off1, v, r) => [movRV Rax v, opRR Rax r, movMR off1 Rax]
    | RR (r1, r2) => [opRR r1 r2]
    | RM (r, off) => [opRM r off]
    | RV (r, v) =>
        if fitsInNsx 32 v then
          [opRV r v]
        else
          [movRV Rax v, opRR r Rax]
    | MR (off, r) => [opMR off r]
    | MM (off1, off2) => [movRM Rax off2, opMR off1 Rax]
    | MV (off, v) =>
        if fitsInNsx 32 v then
          [opMV off v]
        else
          [movRV Rax v, opMR off Rax]
  end

  fun mov is8 r1 r2 =
    case (r1, r2) of
      (VtReg r1, VtReg r2) => movRR is8 r1 r2
    | (VtReg r, VtStack off) => movRM is8 r off
    | (VtReg r, VtConst c) => movRV is8 r c
    | (VtStack off, VtReg r) => movMR is8 off r
    | _ => raise Unreachable

  fun prm is8 vr out =
    case vr of
      VtReg r => Printf out A2 pr is8 r %
    | VtStack off => Printf out A2 pm is8 off %
    | _ => raise Unreachable

  fun assertSize is81 is82 is83 =
    if is81 <> is82 orelse is82 <> is83 then
      raise Unreachable
    else
      ()

  fun emitDivMod I (rd, rs1, rs2) op' resInReg signExtend =
  let
    val (is81, t1) = getType I rd
    val (is82, t2) = getType I rs1
    val (is83, t3) = getType I rs2

    val () = assertSize is81 is82 is83

    val (pre, right) =
      case t3 of
        VtReg _ | VtStack _ => ([], t3)
      | VtConst c => ([movRV is81 Rcx c], VtReg Rcx)
      | VtUnk => raise Unreachable
  in
    pre @ [
      mov is81 (VtReg Rax) t2,
      if signExtend then
        if is81 then "cqo" else "cdq"
      else
        "xor edx, edx",
      sprintf `op' `" " A2 prm is81 right %,
      mov is81 t1 (VtReg resInReg)
    ]
  end

  fun moveBackIfNeeded is8 dest vt =
    if dest = Rax then
      [mov is8 vt (VtReg Rax)]
    else
      []

  fun emitIMul I (vd, vs1, vs2) =
  let
    val (is81, t1) = getType I vd
    val (is82, t2) = getType I vs1
    val (is83, t3) = getType I vs2

    val () = assertSize is81 is82 is83

    datatype form = Reduced of vrType | Normal of vrType * vrType

    fun getReg vt =
      case vt of
        VtReg r => r
      | _ => Rax

    fun op2 () =
    let
      val form =
        if t3 = t1 then
          Reduced t2
        else if t2 = t1 then
          Reduced t3
       else
         Normal (t2, t3)

      val dest = getReg t1
      val main =
        case form of
          Reduced rs =>
            [ sprintf `"imul " A2 pr is81 dest `", " A2 prm is81 rs % ]
        | Normal (rs1, rs2) => [
            mov is81 (VtReg dest) rs1,
            sprintf `"imul " A2 pr is81 dest `", " A2 prm is81 rs2 %
          ]
    in
      main @ moveBackIfNeeded is81 dest t1
    end

    fun op3 rs1 c =
      if fitsInNsx 32 c then
        let
          val dest = getReg t1

          val main =
            [sprintf `"imul " A2 pr is81 dest `", "
              A2 prm is81 rs1 `", " A2 pc is81 c %]
        in
          main @ moveBackIfNeeded is81 dest t1
        end
      else
        op2 ()
  in
    case (t2, t3) of
      (VtConst c, _) => op3 t3 c
    | (_, VtConst c) => op3 t2 c
    | _ => op2 ()
  end

  fun regByAc ac r =
  let
    fun get16bitName r =
    let
      val repr = sprintf A2 pr false r %
    in
      if String.sub (repr, 0) = #"r" then
        repr ^ "w"
      else
        String.extract (repr, 1, NONE)
    end

    fun get8bitName r =
    let
      val repr = sprintf A2 pr false r %
    in
      if String.sub (repr, 0) = #"r" then
        let
          val len = size repr
        in
          String.substring (repr, 0, len - 1) ^ "b"
        end
      else
        case r of
          Rbx => "bl"
        | Rcx => "cl"
        | Rsi => "sil"
        | Rdi => "dil"
        | R8 | R9 | R10 | R11 | R12 | R13 | R14 | R15
        | Rbp | Rsp | Rax | Rdx => raise Unreachable
    end
  in
    case ac of
      I.AC8 => sprintf A2 pr true r %
    | I.AC4 => sprintf A2 pr false r %
    | I.AC2 => get16bitName r
    | I.AC1 => get8bitName r
  end

  fun pByAc ac vt out =
    case vt of
      VtReg r => Printf out `(regByAc ac r) %
    | VtStack off => Printf out I.Pac ac `" [rbp-" I off `"]" %
    | _ => raise Unreachable

  fun emitLoad I (vd, vs, ac) =
  let
    val (_, tl) = getType I vd
    val (_, tr) = getType I vs

    val (pre, src) =
      case tr of
        VtReg r => ([], r)
      | _ => ([mov true (VtReg Rdx) tr], Rdx)

    val dest =
      case tl of
        VtReg r => r
      | _ => Rax

    val main =
      [
        sprintf `"mov " `(regByAc ac dest) `", "
          I.Pac ac `" [" A2 pr true src `"]" %
      ]
  in
    pre @ main @ moveBackIfNeeded true dest tl
  end

  fun emitStore I (vd, vs, ac) =
  let
    val (_, tl) = getType I vd
    val (_, tr) = getType I vs
    val (pre, src) =
      case tr of
        VtReg r => ([], VtReg r)
      | VtConst c =>
          if fitsInNsx 32 c then
            ([], VtConst c)
          else
            ([mov true (VtReg Rdx) tr], VtReg Rdx)
      | _ => ([mov true (VtReg Rdx) tr], VtReg Rdx)


    val (mid, dest) =
      case tl of
        VtReg r => ([], r)
      | _ => ([mov true (VtReg Rax) tl], Rax)

    fun p vt out =
      case vt of
        VtReg reg => Printf out `(regByAc ac reg) %
      | VtConst c => Printf out A2 pc true c %
      | _ => raise Unreachable

    val main =
      [ sprintf `"mov " I.Pac ac `" [" A2 pr true dest `"], " A1 p src % ]
  in
    pre @ mid @ main
  end

  fun cmpOp2cc op' =
    case op' of
      I.Cmpeq => "e"
    | I.Cmpneq => "ne"
    | I.Cmpul => "b"
    | I.Cmpug => "a"
    | I.Cmpule => "be"
    | I.Cmpuge => "ae"
    | I.Cmpsl => "l"
    | I.Cmpsg => "g"
    | I.Cmpsle => "le"
    | I.Cmpsge => "ge"

  fun getCmpSeq E rs1 rs2 =
  let
    val (is82, ts1) = getType E rs1
    val (is83, ts2) = getType E rs2

    val () = if is82 <> is83 then raise Unreachable else ()

    fun RMwithImm vt c =
      sprintf `"cmp " A2 prm is82 vt `", " A2 pc is82 c %

    fun RMwithR vt r =
      sprintf `"cmp " A2 prm is82 vt `", " A2 pr is82 r %

    fun RwithRM r vt = sprintf `"cmp " A2 pr is82 r `", " A2 prm is82 vt %

    val (pre, main) =
      case (ts1, ts2) of
        (VtReg _ | VtStack _, VtConst c) =>
          if fitsInNsx 32 c then
            ([], RMwithImm ts1 c)
          else
            ([movRV is82 Rax c], RMwithR ts1 Rax)
      | (VtReg _ | VtStack _, VtReg r) => ([], RMwithR ts1 r)
      | (VtReg r, VtStack _) => ([], RwithRM r ts2)

      | (VtConst c, _) => ([movRV is82 Rax c], RwithRM Rax ts2)
      | (VtStack off, VtStack _) => ([movRM is82 Rax off], RwithRM Rax ts2)
      | (VtUnk, _) | (_, VtUnk) => raise Unreachable

  in
    pre @ [main]
  end

  fun emitCmp E (op', rd, rs1, rs2) =
  let
    val (_, td) = getType E rd
    val cmpPart = getCmpSeq E rs1 rs2
    val setPart = sprintf `"set" `(cmpOp2cc op') `" dl" %
  in
    [xorIdiom Rdx] @ cmpPart @ [setPart] @ [mov true td (VtReg Rdx)]
  end

  fun emitJmpc E (op', rs1, rs2, lid) =
  let
    val cmpPart = getCmpSeq E rs1 rs2
    val jmp = sprintf `"j" `(cmpOp2cc op') `" " I.Pl lid %
  in
    cmpPart @ [jmp]
  end

  fun emitExt E (vd, vs, from) op' =
  let
    val (is81, td) = getType E vd
    val (_, ts) = getType E vs

    val to = if is81 then I.AC8 else I.AC4
    val dest =
      case td of
        VtReg r => r
      | _ => Rax

    fun ext () =
      sprintf `op' `" " A2 pr is81 dest `", " A2 pByAc from ts %
    val main =
      case (to, from) of
        (I.AC4, I.AC1) | (I.AC4, I.AC2) => ext ()
      | (I.AC8, I.AC1) | (I.AC8, I.AC2) => ext ()
      | (I.AC8, I.AC4) =>
          if op' = "movzx" then
            mov false (VtReg dest) ts
          else
            ext ()

      | (I.AC4, I.AC4) | (I.AC4, I.AC8) => raise Unreachable
      | (I.AC8, I.AC8) => raise Unreachable

      | (I.AC1, _) | (I.AC2, _) => raise Unreachable
  in
    [main] @ moveBackIfNeeded is81 dest td
  end

  fun emitSet I (vrd, I.SaVReg vrs) =
  let
    val (is81, t1) = getType I vrd
    val (is82, t2) = getType I vrs
  in
    case (is81, t1, is82, t2) of
      (false, VtReg r1, false, VtReg r2)
    | (false, VtReg r1, true, VtReg r2)
    | (true, VtReg r1, true, VtReg r2) =>
        if r1 = r2 then
          []
        else
          [movRR true r1 r2]
    | (true, VtReg r1, false, VtReg r2) => [movRR false r1 r2]

    | (_, VtReg r, _, VtConst c) => [movRV true r c]
    | (_, VtReg r, _, VtStack off) => [movRM true r off]
    | (_, VtStack off, _, VtReg r) => [movMR true off r]
    | (_, VtStack off1, _, VtStack off2) =>
        [movRM true Rax off2, movMR true off1 Rax]

    | (_, VtStack off, _, VtConst c) =>
        if fitsInNsx 32 c then
          [movMV true off c]
        else
          [movRV true Rax c, movMR true off Rax]

    | (_, VtConst _, _, _) | (_, VtUnk, _, _) | (_, _, _, VtUnk) =>
        raise Unreachable
  end
   | emitSet I (vrd, I.SaConst w) =
   let
      val (_, t1) = getType I vrd
     val c = VConst w
   in
     case t1 of
       VtReg r => [movRV true r c]
     | VtStack off =>
         if fitsInNsx 32 c then
           [movMV true off c]
         else
           [movRV true Rax c, movMR true off Rax]
     | VtConst _ | VtUnk => raise Unreachable
   end
   | emitSet I (vrd, I.SaAddr p) =
   let
     val (_, t1) = getType I vrd
     val c = VAddrConst p
   in
     case t1 of
       VtReg r => [movRV true r c]
     | VtStack off => [movRV true Rax c, movMR true off Rax]
     | VtUnk | VtConst _ => raise Unreachable
   end

  fun emitAlloc E (vrd, _, SOME stackOffset) =
  let
    val (is8, t1) = getType E vrd
    val () = if not is8 then raise Unreachable else ()
  in
    case t1 of
      VtReg r =>
      [ sprintf `"lea " A2 pr true r `", [rbp-" I stackOffset `"]" % ]
    | _ => raise Unreachable
  end
    | emitAlloc _ (_, _, NONE) = raise Unreachable

  fun jmp lid = sprintf `"jmp .L" I lid %

  fun emitRet (E as { ops, ... }) vr idx =
  let
    val begin =
      case vr of
        NONE => []
      | SOME vr =>
        let
          val (is8, t) = getType E vr
        in
          case t of
            VtReg r => [movRR is8 Rax r]
          | VtStack off => [movRM is8 Rax off]
          | VtConst c => [movRV is8 Rax c]
          | VtUnk => raise Unreachable
        end
  in
    if idx < D.length ops - 2 then
      begin @ [ jmp 0 ]
    else
      begin
  end

  fun emitCopy E (vr, lid, size) =
  let
    val (is8, t) = getType E vr
    val () = if not is8 then raise Unreachable else ()
    val (prolog, destReg) =
      case t of
        VtReg r => ([], r)
      | VtStack off => ([movRM true Rdx off], Rdx)
      | VtConst _ | VtUnk => raise Unreachable

    fun loop off acc =
      if off = size then
        rev acc
      else
        let
          val from = sprintf `"mov rax, qword [I." I lid `"+" W off `"]" %
          val to =
            sprintf `"mov [" A2 pr true destReg `"+" W off `"], rax" %
        in
          loop (off + 0w8) (to :: from :: acc)
        end
  in
    loop 0w0 prolog
  end

  fun emitJz E (vr, lid) isJz =
  let
    val (is8, vt) = getType E vr
    val jmp' = sprintf `"j" `(if isJz then "z" else "nz") `" .L" I lid %
  in
    case vt of
      VtReg reg =>
        [sprintf `"test " A2 pr is8 reg `", " A2 pr is8 reg %, jmp']
    | VtStack off => [sprintf `"cmp " A2 pm is8 off `", 0" %, jmp']
    | VtConst c => (
      case constBoolVal c of
        CbvTrue => [ jmp lid ]
      | CbvFalse => []
      | CbvUnsure (id, off) => [
          sprintf `"lea rax, [" PP.? id I.Pwc I.VR8 off `"]" %,
          sprintf `"test rax, 0" %,
          jmp'
      ]
    )
    | VtUnk => raise Unreachable
  end

  fun getRegsWeSave map idx =
  let
    val row = Array.sub (map, idx)

    fun loop j acc =
      if j = callerSavedRegs then
        rev acc
      else
        case Array.sub (row, j) of
          NONE => loop (j + 1) acc
        | SOME _ => loop (j + 1) (idx2reg j :: acc)
  in
    loop 0 []
  end

  fun prepFuncPrologue ({ stackOffset, regsToSave, regMap, ... }) idx =
  let
    val offFromCall = 8 + 8 * length regsToSave
    val offFromCall =
      if (stackOffset <> 0) then
        offFromCall + 8 (* push rbp *)
      else
        offFromCall
    val offFromCall = offFromCall + ~ stackOffset

    fun pushRegs regs = map (fn r => sprintf `"push " A2 pr true r %) regs
    val regsWeSave = getRegsWeSave regMap idx

    val registerPush: string list = pushRegs regsWeSave
    val offFromCall = offFromCall + 8 * length regsWeSave

    val tail =
      if offFromCall mod 16 <> 0 then
        [sprintf `"sub rsp, 8" %]
      else
        []
  in
    (not $ null tail, regsWeSave, registerPush @ tail)
  end

  fun emitFcall E (rd, rf, _) idx =
  let
    val (shouldAdd, regsToRestore, prologueSeq) = prepFuncPrologue E idx
    val (_, tf) = getType E rf

    val fcall =
      case tf of
        VtConst (C as VAddrConst _) => [sprintf `"call " A2 pc true C %]
      | VtConst (VConst _) => [mov true (VtReg Rax) tf, sprintf `"call rax" %]
      | VtReg _ | VtStack _ => [sprintf `"call " A2 prm true tf %]
      | VtUnk => raise Unreachable

    val regRestoration =
      let
        val pre =
          if shouldAdd then
            [sprintf `"add rsp, 8" %]
          else
            []
        val restoration =
          map (fn r => sprintf `"pop " A2 pr true r %) (rev regsToRestore)

      in
        pre @ restoration
      end
    val assignRes =
      if rd = ~1 then
        []
      else
        let
          val (is8, t) = getType E rd
        in
          [mov is8 t (VtReg Rax)]
        end
  in
    prologueSeq @ fcall @ regRestoration @ assignRes
  end

  fun emitOpStrList ins E idx =
    case ins of
      I.IrSet p => emitSet E p
    | I.IrAdd t => emitGenComm E "add" t
    | I.IrAnd t => emitGenComm E "and" t
    | I.IrOr t => emitGenComm E "or" t
    | I.IrXor t => emitGenComm E "xor" t

    | I.IrSub t => emitSub E t

    | I.IrShl t => emitShift E "shl" t
    | I.IrShr t => emitShift E "shr" t
    | I.IrSar t => emitShift E "sar" t

    | I.IrMul t => emitIMul E t
    | I.IrIMul t => emitIMul E t
    | I.IrDiv t => emitDivMod E t "div" Rax false
    | I.IrIDiv t => emitDivMod E t "idiv" Rax true
    | I.IrMod t => emitDivMod E t "div" Rdx false
    | I.IrIMod t => emitDivMod E t "idiv" Rdx true

    | I.IrCmp q => emitCmp E q
    | I.IrJmpc q => emitJmpc E q

    | I.IrLoad t => emitLoad E t
    | I.IrStore t => emitStore E t

    | I.IrExtZero t => emitExt E t "movzx"
    | I.IrExtSign t => emitExt E t "movsx"

    | I.IrFcall t => emitFcall E t idx

    | I.IrAlloc t => emitAlloc E t
    | I.IrRet vr => emitRet E vr idx
    | I.IrCopy t => emitCopy E t
    | I.IrNopLabel lid => [ sprintf `".L" I lid `":" % ]
    | I.IrJmp lid => [ jmp lid ]
    | I.IrJz p => emitJz E p true
    | I.IrJnz p => emitJz E p false
    | I.IrNop comment => [sprintf  `"; " `comment %]

  fun emitIns (I as { ops, ... }) =
  let
    val outputBuf = Array.array (D.length ops, [])

    fun printFromBuf () =
    let
      fun printLine line = (
        if String.sub (line, 0) <> #"." then
          fprint `"\t" %
        else
          ();
        fprint `line `"\n" %
      )

    in
      Array.app
        (fn lines => List.app printLine lines)
        outputBuf
    end

    fun loop idx =
      if idx < 0 then
        printFromBuf ()
      else
        let
          val (ins, _) = D.get ops idx
        in
          case ins of
            SOME ins =>
            let
              val slist = emitOpStrList ins I idx
            in
              Array.update (outputBuf, idx, slist);
              loop (idx - 1)
            end
          | NONE => loop (idx - 1)
        end
  in
    loop (D.length ops - 1)
  end

  fun emitFunction info name = (
    fprint `"\nsection .text\n" %;
    emitPrologue info name;
    emitIns info;
    emitEpilogue info
  )

  fun emitFunc (F as I.Fi { name, ... }) =
  let
    val info = regAlloc F
  in
    emitFunction info name
  end

  fun openFile fname = file := SOME (TextIO.openOut fname)

  fun emit fname
    (I.Ctx { globSyms, extSyms, objsZI, objs, strlits, funcInfos, ... })
    debugFileName
  =
  let

    val () =
      case debugFileName of
        NONE => ()
      | SOME fname => debugFile := SOME (TextIO.openOut fname)
    val () = openFile fname

    val () = List.app (fn gs => fprint `"global " PP.? gs `"\n" %) globSyms
    val () = List.app (fn es => fprint `"extern " PP.? es `"\n" %) extSyms

    val () = handleBSS objsZI
    val () = handleData objs
    val () = handleStrlits strlits
    val () = handleLocalIniLayouts ()

    val () = List.app emitFunc funcInfos
  in
    ()
  end
end