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
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
"""Exact estimator for what Yosys 0.70's memory_libmap does to ramgen.

The flows in /app/flows all end in memory_libmap.  Everything before it is
modelled analytically (see _build_mem), while memory_libmap itself (and the
memlib library parser) is ported statement by statement from
passes/memory/memory_libmap.cc and passes/memory/memlib.cc so that candidate
ordering, cost arithmetic (including the int truncations of the C++ code) and
the emulation logic match the original.
"""

import json, hashlib
import math
import os

# ---------------------------------------------------------------------------
# Library definitions (port of memlib.cc)
# ---------------------------------------------------------------------------

_HERE = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(_HERE, "memlibs.json")) as _f:
    _LIBTEXT = json.load(_f)
import premap

FLOWS = {
    "xc7": dict(libs=["xilinx/lutrams_xc5v.txt", "xilinx/brams_xc4v.txt"],
                defines={"HAS_SIZE_36", "HAS_CASCADE", "HAS_MIXWIDTH_SDP"},
                no_auto_huge=False, logic_cost_rom=0.015625, logic_cost_ram=1.0),
    "ice40": dict(libs=["ice40/brams.txt", "ice40/spram.txt"], defines=set(),
                  no_auto_huge=True, logic_cost_rom=1.0 / 16.0, logic_cost_ram=1.0),
    "ecp5": dict(libs=["lattice/lutrams_trellis.txt", "lattice/brams_16kd.txt"], defines=set(),
                 no_auto_huge=False, logic_cost_rom=1.0 / 16.0, logic_cost_ram=1.0),
    "gw1n": dict(libs=["gowin/lutrams.txt", "gowin/brams.txt"], defines=set(),
                 no_auto_huge=False, logic_cost_rom=1.0 / 16.0, logic_cost_ram=1.0),
}

# enums
K_AUTO, K_LOGIC, K_NOTLOGIC, K_DISTRIBUTED, K_BLOCK, K_HUGE = range(6)
WM_SINGLE, WM_GLOBAL, WM_PERPORT = range(3)
INIT_NONE, INIT_ZERO, INIT_ANY, INIT_NOUNDEF = range(4)
P_SR, P_AR, P_SW, P_SRSW, P_ARSW = range(5)
CLK_ANYEDGE, CLK_POSEDGE, CLK_NEGEDGE = range(3)
RDWR_UNDEF, RDWR_NOCHANGE, RDWR_NEW, RDWR_OLD, RDWR_NEWONLY = range(5)
RV_NONE, RV_ZERO, RV_ANY, RV_NOUNDEF, RV_INIT = range(5)
SRST_NONE, SRST_UNGATED, SRST_GATED_CLKEN, SRST_GATED_RDEN = range(4)
WT_ALL, WT_GROUP = range(2)
WTK_NEW, WTK_OLD = range(2)


class Cap:
    __slots__ = ("val", "opts", "portopts")

    def __init__(self, val, opts, portopts):
        self.val = val
        self.opts = opts
        self.portopts = portopts


class PortGroupDef:
    def __init__(self):
        self.kind = None
        self.portopts = {}   # name -> list of values (insertion ordered, unique)
        self.names = []
        self.forbid = []
        self.clock = []
        self.clken = []
        self.wrbe_separate = []
        self.width = []
        self.rden = []
        self.rdwr = []
        self.rdinit = []
        self.rdarst = []
        self.rdsrst = []
        self.wrprio = []
        self.wrtrans = []
        self.optional = []
        self.optional_rw = []


class RamDef:
    def __init__(self):
        self.id = None
        self.opts = {}
        self.kind = None
        self.forbid = []
        self.prune_rom = []
        self.ports = []
        self.abits = []
        self.widths = []
        self.resource = []
        self.cost = []
        self.widthscale = []
        self.byte = []
        self.init = []
        self.style = []


class PortVariant:
    def __init__(self):
        self.options = {}
        self.kind = None
        self.clk_shared = -1
        self.clk_pol = CLK_POSEDGE
        self.clk_en = False
        self.width_tied = True
        self.min_wr_wide_log2 = 0
        self.max_wr_wide_log2 = 0
        self.min_rd_wide_log2 = 0
        self.max_rd_wide_log2 = 0
        self.rd_en = False
        self.rdwr = RDWR_UNDEF
        self.rdinitval = RV_NONE
        self.rdarstval = RV_NONE
        self.rdsrstval = RV_NONE
        self.rdsrstmode = SRST_NONE
        self.rdsrst_block_wr = False
        self.wrbe_separate = False
        self.wrprio = []
        self.wrtrans = []   # (target_kind, target_group, kind)


class PortGroup:
    def __init__(self):
        self.names = []
        self.variants = []
        self.optional = False
        self.optional_rw = False


class Ram:
    def __init__(self):
        self.id = None
        self.kind = None
        self.options = {}
        self.prune_rom = False
        self.abits = 0
        self.dbits = []
        self.width_mode = WM_SINGLE
        self.resource_name = ""
        self.resource_count = 1
        self.cost = 0.0
        self.widthscale = 0.0
        self.byte = 0
        self.init = INIT_NONE
        self.style = []
        self.port_groups = []
        self.shared_clocks = []


class ParseError(Exception):
    pass


def _tokenize(text):
    """Replicates Parser::peek_token tokenisation."""
    toks = []
    for line in text.split("\n"):
        for tok in line.replace("\t", " ").replace("\r", " ").split(" "):
            if not tok:
                continue
            if tok[0] == "#":
                break
            if tok[-1] == ";":
                toks.append(tok[:-1])
                toks.append(";")
            else:
                toks.append(tok)
    return toks


class Parser:
    def __init__(self, text, lib, defines):
        self.tokens = _tokenize(text)
        self.idx = 0
        self.lib = lib
        self.defines = defines
        self.option_stack = []
        self.portoption_stack = []
        self.ram = None
        self.port = None
        self.active = True
        self.parse()

    # --- token helpers ---
    def peek_token(self):
        if self.idx < len(self.tokens):
            return self.tokens[self.idx]
        return ""

    def get_token(self):
        res = self.peek_token()
        if self.idx < len(self.tokens):
            self.idx += 1
        return res

    def eat_token(self, expected):
        t = self.get_token()
        if t != expected:
            raise ParseError("expected %s got %s" % (expected, t))

    def get_id(self):
        t = self.get_token()
        if not t or (t[0] != "$" and t[0] != "\\"):
            raise ParseError("expected id, got %s" % t)
        return t

    def get_name(self):
        return self.get_token()

    def get_string(self):
        t = self.get_token()
        if len(t) < 2 or t[0] != '"' or t[-1] != '"':
            raise ParseError("expected string, got %s" % t)
        return t[1:-1]

    def peek_string(self):
        t = self.peek_token()
        return bool(t) and t[0] == '"'

    def get_int(self):
        t = self.get_token()
        return int(t, 0)

    def get_double(self):
        t = self.get_token()
        return float(t)

    def peek_int(self):
        t = self.peek_token()
        return bool(t) and t[0].isdigit()

    def get_semi(self):
        t = self.get_token()
        if t != ";":
            raise ParseError("expected ; got %s" % t)

    def get_value(self):
        t = self.peek_token()
        if t and t[0] == '"':
            return self.get_string()
        return self.get_int()

    # --- option handling ---
    def enter_ifdef(self, polarity):
        res = self.active
        name = self.get_name()
        if self.active:
            if name in self.defines:
                self.active = polarity
            else:
                self.active = not polarity
        return res

    def enter_else(self, save):
        self.get_token()
        self.active = (not self.active) and save

    @staticmethod
    def _insert(d, name, val):
        lst = d.setdefault(name, [])
        if val not in lst:
            lst.append(val)

    def enter_option(self):
        name = self.get_string()
        val = self.get_value()
        if self.active:
            self._insert(self.ram.opts, name, val)
        self.option_stack.append((name, val))

    def exit_option(self):
        self.option_stack.pop()

    def get_options(self):
        res = {}
        for n, v in self.option_stack:
            res[n] = v
        return res

    def enter_portoption(self):
        name = self.get_string()
        val = self.get_value()
        if self.active:
            self._insert(self.port.portopts, name, val)
        self.portoption_stack.append((name, val))

    def exit_portoption(self):
        self.portoption_stack.pop()

    def get_portoptions(self):
        res = {}
        for n, v in self.portoption_stack:
            res[n] = v
        return res

    def add_cap(self, caps, val):
        if self.active:
            caps.append(Cap(val, self.get_options(), self.get_portoptions()))

    # --- blocks ---
    def parse_port_block(self):
        if self.peek_token() == "{":
            self.get_token()
            while self.peek_token() != "}":
                self.parse_port_item()
            self.get_token()
        else:
            self.parse_port_item()

    def parse_ram_block(self):
        if self.peek_token() == "{":
            self.get_token()
            while self.peek_token() != "}":
                self.parse_ram_item()
            self.get_token()
        else:
            self.parse_ram_item()

    def parse_top_block(self):
        if self.peek_token() == "{":
            self.get_token()
            while self.peek_token() != "}":
                self.parse_top_item()
            self.get_token()
        else:
            self.parse_top_item()

    def parse_port_item(self):
        token = self.get_token()
        port = self.port
        if token == "ifdef":
            save = self.enter_ifdef(True)
            self.parse_port_block()
            if self.peek_token() == "else":
                self.enter_else(save)
                self.parse_port_block()
            self.active = save
        elif token == "ifndef":
            save = self.enter_ifdef(False)
            self.parse_port_block()
            if self.peek_token() == "else":
                self.enter_else(save)
                self.parse_port_block()
            self.active = save
        elif token == "option":
            self.enter_option()
            self.parse_port_block()
            self.exit_option()
        elif token == "portoption":
            self.enter_portoption()
            self.parse_port_block()
            self.exit_portoption()
        elif token == "clock":
            token = self.get_token()
            kind = {"anyedge": CLK_ANYEDGE, "posedge": CLK_POSEDGE, "negedge": CLK_NEGEDGE}[token]
            name = ""
            if self.peek_string():
                name = self.get_string()
            self.get_semi()
            self.add_cap(port.clock, (kind, name))
        elif token == "clken":
            self.get_semi()
            self.add_cap(port.clken, None)
        elif token == "wrbe_separate":
            self.get_semi()
            self.add_cap(port.wrbe_separate, None)
        elif token == "width":
            token = self.peek_token()
            wr_widths = []
            rd_widths = []
            tied = True
            if token == "tied":
                self.get_token()
                while self.peek_int():
                    wr_widths.append(self.get_int())
                tied = True
            elif token == "mix":
                self.get_token()
                while self.peek_int():
                    wr_widths.append(self.get_int())
                rd_widths = list(wr_widths)
                tied = False
            elif token == "rd":
                self.get_token()
                while True:
                    rd_widths.append(self.get_int())
                    if not self.peek_int():
                        break
                self.eat_token("wr")
                while True:
                    wr_widths.append(self.get_int())
                    if not self.peek_int():
                        break
                tied = False
            elif token == "wr":
                self.get_token()
                while True:
                    wr_widths.append(self.get_int())
                    if not self.peek_int():
                        break
                self.eat_token("rd")
                while True:
                    rd_widths.append(self.get_int())
                    if not self.peek_int():
                        break
                tied = False
            else:
                while True:
                    wr_widths.append(self.get_int())
                    if not self.peek_int():
                        break
                tied = True
            self.get_semi()
            self.add_cap(port.width, (tied, wr_widths, rd_widths))
        elif token == "rden":
            self.get_semi()
            self.add_cap(port.rden, None)
        elif token == "rdwr":
            token = self.get_token()
            kind = {"undefined": RDWR_UNDEF, "no_change": RDWR_NOCHANGE, "new": RDWR_NEW,
                    "old": RDWR_OLD, "new_only": RDWR_NEWONLY}[token]
            self.get_semi()
            self.add_cap(port.rdwr, kind)
        elif token == "rdinit":
            token = self.get_token()
            kind = {"none": RV_NONE, "zero": RV_ZERO, "any": RV_ANY, "no_undef": RV_NOUNDEF}[token]
            self.get_semi()
            self.add_cap(port.rdinit, kind)
        elif token == "rdarst":
            token = self.get_token()
            kind = {"none": RV_NONE, "zero": RV_ZERO, "any": RV_ANY, "no_undef": RV_NOUNDEF,
                    "init": RV_INIT}[token]
            self.get_semi()
            self.add_cap(port.rdarst, kind)
        elif token == "rdsrst":
            token = self.get_token()
            val = {"none": RV_NONE, "zero": RV_ZERO, "any": RV_ANY, "no_undef": RV_NOUNDEF,
                   "init": RV_INIT}[token]
            if val == RV_NONE:
                kind = SRST_NONE
            else:
                token = self.get_token()
                kind = {"ungated": SRST_UNGATED, "gated_clken": SRST_GATED_CLKEN,
                        "gated_rden": SRST_GATED_RDEN}[token]
            block_wr = False
            if self.peek_token() == "block_wr":
                self.get_token()
                block_wr = True
            self.get_semi()
            self.add_cap(port.rdsrst, (val, kind, block_wr))
        elif token == "wrprio":
            while True:
                self.add_cap(port.wrprio, self.get_string())
                if not self.peek_string():
                    break
            self.get_semi()
        elif token == "wrtrans":
            token = self.peek_token()
            if token == "all":
                tk = WT_ALL
                tg = ""
                self.get_token()
            else:
                tk = WT_GROUP
                tg = self.get_string()
            token = self.get_token()
            kind = {"new": WTK_NEW, "old": WTK_OLD}[token]
            self.get_semi()
            self.add_cap(port.wrtrans, (tk, tg, kind))
        elif token == "forbid":
            self.get_semi()
            self.add_cap(port.forbid, None)
        elif token == "optional":
            self.get_semi()
            self.add_cap(port.optional, None)
        elif token == "optional_rw":
            self.get_semi()
            self.add_cap(port.optional_rw, None)
        else:
            raise ParseError("unknown port item %s" % token)

    def parse_ram_item(self):
        token = self.get_token()
        ram = self.ram
        if token == "ifdef":
            save = self.enter_ifdef(True)
            self.parse_ram_block()
            if self.peek_token() == "else":
                self.enter_else(save)
                self.parse_ram_block()
            self.active = save
        elif token == "ifndef":
            save = self.enter_ifdef(False)
            self.parse_ram_block()
            if self.peek_token() == "else":
                self.enter_else(save)
                self.parse_ram_block()
            self.active = save
        elif token == "option":
            self.enter_option()
            self.parse_ram_block()
            self.exit_option()
        elif token == "prune_rom":
            self.get_semi()
            self.add_cap(ram.prune_rom, None)
        elif token == "forbid":
            self.get_semi()
            self.add_cap(ram.forbid, None)
        elif token == "abits":
            val = self.get_int()
            self.get_semi()
            self.add_cap(ram.abits, val)
        elif token == "width":
            w = self.get_int()
            self.get_semi()
            self.add_cap(ram.widths, ([w], WM_SINGLE))
        elif token == "widths":
            widths = []
            while True:
                widths.append(self.get_int())
                if not self.peek_int():
                    break
            token = self.get_token()
            mode = {"global": WM_GLOBAL, "per_port": WM_PERPORT}[token]
            self.get_semi()
            self.add_cap(ram.widths, (widths, mode))
        elif token == "resource":
            name = self.get_string()
            if self.peek_int():
                count = self.get_int()
            else:
                count = 1
            self.get_semi()
            self.add_cap(ram.resource, (name, count))
        elif token == "cost":
            self.add_cap(ram.cost, self.get_double())
            self.get_semi()
        elif token == "widthscale":
            if self.peek_int():
                self.add_cap(ram.widthscale, self.get_double())
            else:
                self.add_cap(ram.widthscale, 0.0)
            self.get_semi()
        elif token == "byte":
            val = self.get_int()
            self.add_cap(ram.byte, val)
            self.get_semi()
        elif token == "init":
            token = self.get_token()
            kind = {"zero": INIT_ZERO, "any": INIT_ANY, "no_undef": INIT_NOUNDEF, "none": INIT_NONE}[token]
            self.get_semi()
            self.add_cap(ram.init, kind)
        elif token == "style":
            while True:
                self.add_cap(ram.style, self.get_string().lower())
                if not self.peek_string():
                    break
            self.get_semi()
        elif token == "port":
            self.port = PortGroupDef()
            token = self.get_token()
            self.port.kind = {"ar": P_AR, "sr": P_SR, "sw": P_SW, "arsw": P_ARSW, "srsw": P_SRSW}[token]
            while True:
                self.port.names.append(self.get_string())
                if not self.peek_string():
                    break
            self.parse_port_block()
            if self.active:
                self.add_cap(ram.ports, self.port)
        else:
            raise ParseError("unknown ram item %s" % token)

    def parse_top_item(self):
        token = self.get_token()
        if token == "ifdef":
            save = self.enter_ifdef(True)
            self.parse_top_block()
            if self.peek_token() == "else":
                self.enter_else(save)
                self.parse_top_block()
            self.active = save
        elif token == "ifndef":
            save = self.enter_ifdef(False)
            self.parse_top_block()
            if self.peek_token() == "else":
                self.enter_else(save)
                self.parse_top_block()
            self.active = save
        elif token == "ram":
            self.ram = RamDef()
            token = self.get_token()
            self.ram.kind = {"distributed": K_DISTRIBUTED, "block": K_BLOCK, "huge": K_HUGE}[token]
            self.ram.id = self.get_id()
            self.parse_ram_block()
            if self.active:
                self.compile_ram()
        else:
            raise ParseError("unknown top item %s" % token)

    # --- compilation ---
    @staticmethod
    def opts_ok(defo, var):
        for k, v in defo.items():
            if k not in var:
                raise ParseError("missing option %s" % k)
            if var[k] != v or type(var[k]) is not type(v):
                return False
        return True

    def find_single_cap(self, caps, opts, portopts):
        res = None
        found = False
        for cap in caps:
            if not self.opts_ok(cap.opts, opts):
                continue
            if not self.opts_ok(cap.portopts, portopts):
                continue
            if found:
                raise ParseError("duplicate cap")
            res = cap.val
            found = True
        return found, res

    @staticmethod
    def make_opt_combinations(opts):
        # Yosys hashlib dict/pool iterate in *reverse* insertion order.
        res = [{}]
        for name in reversed(list(opts.keys())):
            vals = opts[name]
            new_res = []
            for val in reversed(vals):
                for o in res:
                    o2 = dict(o)
                    o2[name] = val
                    new_res.append(o2)
            res = new_res
        return res

    def compile_portgroup(self, cram, pdef, clk_ids, port_ids):
        grp = PortGroup()
        grp.optional = self.find_single_cap(pdef.optional, cram.options, {})[0]
        grp.optional_rw = self.find_single_cap(pdef.optional_rw, cram.options, {})[0]
        grp.names = list(pdef.names)
        for portopts in self.make_opt_combinations(pdef.portopts):
            forbidden = False
            # NB: Yosys checks ram.forbid here (port-level forbid caps are
            # stored in port.forbid and never consulted) -- replicated.
            for fdef in self.ram.forbid:
                if self.opts_ok(fdef.opts, cram.options) and self.opts_ok(fdef.portopts, portopts):
                    forbidden = True
            if forbidden:
                continue
            var = PortVariant()
            var.options = dict(portopts)
            var.kind = pdef.kind
            if pdef.kind == P_AR:
                var.clk_en = False
            else:
                found, cdef = self.find_single_cap(pdef.clock, cram.options, portopts)
                if not found:
                    raise ParseError("missing clock capability")
                var.clk_pol = cdef[0]
                if cdef[1] == "":
                    var.clk_shared = -1
                else:
                    anyedge = cdef[0] == CLK_ANYEDGE
                    if cdef[1] not in clk_ids:
                        clk_ids[cdef[1]] = var.clk_shared = len(cram.shared_clocks)
                        cram.shared_clocks.append((cdef[1], anyedge))
                    else:
                        var.clk_shared = clk_ids[cdef[1]]
                var.clk_en = self.find_single_cap(pdef.clken, cram.options, portopts)[0]
            found, wdef = self.find_single_cap(pdef.width, cram.options, portopts)
            if found:
                if cram.width_mode != WM_PERPORT:
                    raise ParseError("per-port width doesn't make sense")
                self.compile_widths(var, cram.dbits, wdef)
            else:
                var.width_tied = True
                var.min_wr_wide_log2 = 0
                var.min_rd_wide_log2 = 0
                var.max_wr_wide_log2 = len(cram.dbits) - 1
                var.max_rd_wide_log2 = len(cram.dbits) - 1
            if pdef.kind in (P_SRSW, P_SR):
                found, rdwr = self.find_single_cap(pdef.rdwr, cram.options, portopts)
                var.rdwr = rdwr if found else RDWR_UNDEF
                var.rd_en = self.find_single_cap(pdef.rden, cram.options, portopts)[0]
                found, iv = self.find_single_cap(pdef.rdinit, cram.options, portopts)
                var.rdinitval = iv if found else RV_NONE
                found, arv = self.find_single_cap(pdef.rdarst, cram.options, portopts)
                var.rdarstval = arv if found else RV_NONE
                found, srv = self.find_single_cap(pdef.rdsrst, cram.options, portopts)
                if found:
                    var.rdsrstval = srv[0]
                    var.rdsrstmode = srv[1]
                    var.rdsrst_block_wr = srv[2]
                else:
                    var.rdsrstval = RV_NONE
                    var.rdsrstmode = SRST_NONE
                    var.rdsrst_block_wr = False
            var.wrbe_separate = self.find_single_cap(pdef.wrbe_separate, cram.options, portopts)[0]
            for d in pdef.wrprio:
                if not self.opts_ok(d.opts, cram.options):
                    continue
                if not self.opts_ok(d.portopts, portopts):
                    continue
                var.wrprio.append(port_ids[d.val])
            for d in pdef.wrtrans:
                if not self.opts_ok(d.opts, cram.options):
                    continue
                if not self.opts_ok(d.portopts, portopts):
                    continue
                tk, tg, kind = d.val
                tgi = port_ids[tg] if tk == WT_GROUP else 0
                var.wrtrans.append((tk, tgi, kind))
            grp.variants.append(var)
        if not grp.variants:
            raise ParseError("all port option combinations are forbidden")
        cram.port_groups.append(grp)

    def compile_ram(self):
        ram = self.ram
        for opts in self.make_opt_combinations(ram.opts):
            forbidden = False
            for fdef in ram.forbid:
                if self.opts_ok(fdef.opts, opts):
                    forbidden = True
            if forbidden:
                continue
            cram = Ram()
            cram.id = ram.id
            cram.kind = ram.kind
            cram.options = dict(opts)
            cram.prune_rom = self.find_single_cap(ram.prune_rom, opts, {})[0]
            found, abits = self.find_single_cap(ram.abits, opts, {})
            if not found:
                continue
            cram.abits = abits
            found, widths = self.find_single_cap(ram.widths, opts, {})
            if not found:
                continue
            cram.dbits = list(widths[0])
            cram.width_mode = widths[1]
            found, resource = self.find_single_cap(ram.resource, opts, {})
            if found:
                cram.resource_name = resource[0]
                cram.resource_count = resource[1]
            else:
                cram.resource_count = 1
            cram.cost = 0.0
            for cap in ram.cost:
                if self.opts_ok(cap.opts, opts):
                    cram.cost += cap.val
            found, widthscale = self.find_single_cap(ram.widthscale, opts, {})
            if found:
                cram.widthscale = widthscale if widthscale else cram.cost
            else:
                cram.widthscale = 0.0
            found, byte = self.find_single_cap(ram.byte, opts, {})
            cram.byte = byte if found else 0
            found, ik = self.find_single_cap(ram.init, opts, {})
            cram.init = ik if found else INIT_NONE
            for sdef in ram.style:
                if self.opts_ok(sdef.opts, opts):
                    cram.style.append(sdef.val)
            port_ids = {}
            ctr = 0
            for pdef in ram.ports:
                if not self.opts_ok(pdef.opts, opts):
                    continue
                for name in pdef.val.names:
                    port_ids[name] = ctr
                ctr += 1
            clk_ids = {}
            for pdef in ram.ports:
                if not self.opts_ok(pdef.opts, opts):
                    continue
                self.compile_portgroup(cram, pdef.val, clk_ids, port_ids)
            self.lib.append(cram)

    def compile_widths(self, var, dbits, wdef):
        tied, wr_widths, rd_widths = wdef
        var.width_tied = tied
        a, b = self.compile_widthdef(dbits, wr_widths)
        var.min_wr_wide_log2 = a
        var.max_wr_wide_log2 = b
        if tied:
            var.min_rd_wide_log2 = a
            var.max_rd_wide_log2 = b
        else:
            c, d = self.compile_widthdef(dbits, rd_widths)
            var.min_rd_wide_log2 = c
            var.max_rd_wide_log2 = d

    @staticmethod
    def compile_widthdef(dbits, widths):
        if not widths:
            return 0, len(dbits) - 1
        for i in range(len(dbits)):
            if dbits[i] == widths[0]:
                for j in range(len(widths)):
                    if i + j >= len(dbits) or dbits[i + j] != widths[j]:
                        raise ParseError("port width doesn't match dbits progression")
                return i, i + len(widths) - 1
        raise ParseError("port width invalid for dbits")

    def parse(self):
        while self.peek_token() != "":
            self.parse_top_item()


_LIB_CACHE = {}


def get_library(flow):
    if flow in _LIB_CACHE:
        return _LIB_CACHE[flow]
    fl = FLOWS[flow]
    lib = []
    for name in fl["libs"]:
        Parser(_LIBTEXT[name], lib, fl["defines"])
    _LIB_CACHE[flow] = lib
    return lib


# ---------------------------------------------------------------------------
# Abstract memory (state of the $mem_v2 cell when memory_libmap runs)
# ---------------------------------------------------------------------------

def ceil_log2(x):
    if x <= 1:
        return 0
    return (x - 1).bit_length()


def _bits(val, width):
    return [("1" if (val >> i) & 1 else "0") for i in range(width)]


def is_all_zero(bits):
    return "1" not in bits


def is_fully_undef(bits):
    return all(b == "x" for b in bits)


class WrPort:
    def __init__(self, abits, width, en):
        self.clk_enable = True
        self.wide_log2 = 0
        self.en = list(en)            # one token per bit ('1', or an enable wire bit)
        self.en_distinct = len(set(en))   # SigSpec::sort_and_unify size (handle_geom wren_size)
        self.en_runs = _en_runs(en)       # MemWr::compress_en size (emulate_read_first)
        self.addr_bits = abits
        self.width = width
        self.priority_mask = [False]


class RdPort:
    def __init__(self, width, abits):
        self.clk_enable = False
        self.wide_log2 = 0
        self.width = width
        self.addr_bits = abits        # all address bits are wires
        self.en_one = True            # EN == 1'b1
        self.en_excl_we = False       # EN can never be 1 while we is 1
        self.arst = False
        self.arst_value = ["x"] * width
        self.srst = False
        self.srst_value = ["x"] * width
        self.init_value = ["x"] * width
        self.ce_over_srst = False
        self.transparency_mask = [False]
        self.collision_x_mask = [False]
        self.addr_share = []          # per write port: sigmap_xmux(raddr) == sigmap_xmux(waddr)


class Mem:
    def __init__(self, width, size):
        self.width = width
        self.size = size
        self.start_offset = 0
        self.wr_ports = []
        self.rd_ports = []
        self.inits = []
        self.pre_ffbits = 0


def _build_mem(q):
    m = premap.derive(q)
    mem = Mem(m.width, m.size)
    mem.start_offset = m.offset
    mem.pre_ffbits = m.ff_prune
    mem.removed = m.removed
    if m.removed:
        return mem
    nw = len(m.wr)
    for p in m.wr:
        wp = WrPort(m.abits, m.width, p.en)
        wp.priority_mask = [(j in p.prio) for j in range(nw)]
        mem.wr_ports.append(wp)
    for p in m.rd:
        rp = RdPort(m.width, m.abits)
        rp.clk_enable = p.clk
        rp.en_one = True
        rp.transparency_mask = [False] * nw
        rp.collision_x_mask = [False] * nw
        rp.addr_share = [(w.addr == p.addr or j in p.xmux_share) for j, w in enumerate(m.wr)]
        mem.rd_ports.append(rp)
    mem.init_words = m.words
    mem.inits = []
    for wv in m.words:
        if wv is not None:
            mem.inits.append(wv)
    return mem


# ---------------------------------------------------------------------------
# memory_libmap port
# ---------------------------------------------------------------------------

FACTOR_MUX = 0.5
FACTOR_DEMUX = 0.5
FACTOR_EMU = 2


class WrPortConfig:
    def __init__(self):
        self.rd_port = -1
        self.port_group = 0
        self.port_variant = 0
        self.defn = None
        self.emu_prio = []
        self.force_uniform = False

    def clone(self):
        c = WrPortConfig()
        c.rd_port = self.rd_port
        c.port_group = self.port_group
        c.port_variant = self.port_variant
        c.defn = self.defn
        c.emu_prio = list(self.emu_prio)
        c.force_uniform = self.force_uniform
        return c


class RdPortConfig:
    def __init__(self):
        self.wr_port = -1
        self.port_group = 0
        self.port_variant = 0
        self.defn = None
        self.emu_sync = False
        self.emu_en = False
        self.emu_arst = False
        self.emu_srst = False
        self.emu_init = False
        self.emu_srst_en_prio = False
        self.rd_en_to_clk_en = False
        self.emu_trans = []

    def clone(self):
        c = RdPortConfig()
        c.__dict__.update(self.__dict__)
        c.emu_trans = list(self.emu_trans)
        return c


class MemConfig:
    def __init__(self):
        self.defn = None
        self.wr_ports = []
        self.rd_ports = []
        self.emu_read_first = False
        self.base_width_log2 = 0
        self.unit_width_log2 = 0
        self.swizzle_size = 0
        self.hard_wide_mask = 0
        self.emu_wide_mask = 0
        self.repl_d = 1
        self.repl_port = 1
        self.score_emu = 0
        self.score_mux = 0
        self.score_demux = 0
        self.cost = 0.0
        self.mult_a = 1

    def clone(self):
        c = MemConfig()
        c.__dict__.update(self.__dict__)
        c.wr_ports = [p.clone() for p in self.wr_ports]
        c.rd_ports = [p.clone() for p in self.rd_ports]
        return c


def _en_runs(en):
    runs = 1
    for i in range(1, len(en)):
        if en[i] != en[i - 1]:
            runs += 1
    return runs


def _trunc(x):
    """C++ double -> int conversion (truncation toward zero)."""
    return int(x)


class MemMapping:
    def __init__(self, mem, lib, opts):
        self.mem = mem
        self.lib = lib
        self.opts = opts
        self.cfgs = []
        self.kind = K_AUTO
        self.style = ""
        self.logic_ok = self.determine_logic_ok()
        if not mem.wr_ports:
            self.logic_cost = mem.width * mem.size * opts["logic_cost_rom"]
        else:
            self.logic_cost = mem.width * mem.size * opts["logic_cost_ram"]
        for rdef in lib:
            if not self.check_ram_kind(rdef):
                continue
            if not self.check_init(rdef):
                continue
            if rdef.prune_rom and not mem.wr_ports:
                continue
            cfg = MemConfig()
            cfg.defn = rdef
            self.cfgs.append(cfg)
        self.assign_wr_ports()
        self.assign_rd_ports()
        self.handle_trans()
        self.handle_priority()
        self.handle_rd_rst()
        self.score_emu_ports()
        self.handle_geom()
        self.prune_post_geom()

    # --- SAT query stand-ins (specialised to ramgen's enables) ---
    def addr_compatible(self, wpidx, rpidx):
        return self.mem.rd_ports[rpidx].addr_share[wpidx]

    def get_wr_implies_rd(self, wpidx, rpidx):
        # read enable is re (or !we & re): never implied by we
        rp = self.mem.rd_ports[rpidx]
        if rp.en_one:
            return True
        return False

    def get_wr_excludes_rd(self, wpidx, rpidx):
        rp = self.mem.rd_ports[rpidx]
        if rp.en_one:
            return False
        return rp.en_excl_we

    def get_wr_excludes_srst(self, wpidx, rpidx):
        rp = self.mem.rd_ports[rpidx]
        if rp.ce_over_srst and not rp.en_one and rp.en_excl_we:
            return True
        return False

    # --- checks ---
    def determine_logic_ok(self):
        if not self.mem.wr_ports:
            return True
        for p in self.mem.wr_ports:
            if not p.clk_enable:
                return False
        return True

    def check_ram_kind(self, ram):
        if self.style != "":
            return True
        if ram.kind == self.kind:
            return True
        if self.kind in (K_AUTO, K_NOTLOGIC):
            if ram.kind == K_DISTRIBUTED and self.opts.get("no_auto_distributed"):
                return False
            if ram.kind == K_BLOCK and self.opts.get("no_auto_block"):
                return False
            if ram.kind == K_HUGE and self.opts.get("no_auto_huge"):
                return False
            return True
        return False

    def check_init(self, ram):
        has_nonx = False
        has_one = False
        for wv in self.mem.inits:
            if all(b == "x" for b in wv):
                continue
            has_nonx = True
            if "1" in wv:
                has_one = True
        if ram.init == INIT_NONE:
            return not has_nonx
        if ram.init == INIT_ZERO:
            return not has_one
        return True

    # --- port assignment ---
    def assign_wr_ports(self):
        for port in self.mem.wr_ports:
            if not port.clk_enable:
                self.cfgs = []
                return
            new_cfgs = []
            for cfg in self.cfgs:
                for pgi, pg in enumerate(cfg.defn.port_groups):
                    used = sum(1 for op in cfg.wr_ports if op.port_group == pgi)
                    if used >= len(pg.names):
                        continue
                    for pvi, d in enumerate(pg.variants):
                        if d.kind in (P_AR, P_SR):
                            continue
                        new_cfg = cfg.clone()
                        pcfg = WrPortConfig()
                        pcfg.rd_port = -1
                        pcfg.port_group = pgi
                        pcfg.port_variant = pvi
                        pcfg.defn = d
                        # apply_clock: no shared clocks in these libraries
                        pass  # shared clocks: one clock and polarity for every port
                        new_cfg.wr_ports.append(pcfg)
                        new_cfgs.append(new_cfg)
            self.cfgs = new_cfgs

    def assign_rd_ports(self):
        mem = self.mem
        for pidx, port in enumerate(mem.rd_ports):
            new_cfgs = []
            for cfg in self.cfgs:
                # First pass: not shared
                for pgi, pg in enumerate(cfg.defn.port_groups):
                    used = sum(1 for op in cfg.wr_ports if op.port_group == pgi)
                    if used >= len(pg.names):
                        continue
                    for pvi, d in enumerate(pg.variants):
                        if d.kind == P_SW:
                            continue
                        if not port.clk_enable:
                            if d.kind in (P_SR, P_SRSW):
                                continue
                        new_cfg = cfg.clone()
                        pcfg = RdPortConfig()
                        pcfg.wr_port = -1
                        pcfg.port_group = pgi
                        pcfg.port_variant = pvi
                        pcfg.defn = d
                        if d.kind in (P_SR, P_SRSW):
                            pcfg.emu_sync = False
                            pass  # shared clocks: one clock and polarity for every port
                            if not port.en_one:
                                if d.clk_en:
                                    pcfg.rd_en_to_clk_en = True
                                else:
                                    pcfg.emu_en = not d.rd_en
                        else:
                            pcfg.emu_sync = port.clk_enable
                        new_cfg.rd_ports.append(pcfg)
                        new_cfgs.append(new_cfg)
                # Second pass: shared with a write port
                for wpidx, wport in enumerate(mem.wr_ports):
                    wpcfg = cfg.wr_ports[wpidx]
                    d = wpcfg.defn
                    if wpcfg.rd_port != -1:
                        continue
                    if d.kind == P_SW:
                        continue
                    if not self.addr_compatible(wpidx, pidx):
                        continue
                    if d.kind == P_SRSW:
                        if not port.clk_enable:
                            continue
                        # same clock / polarity always
                    new_cfg = cfg.clone()
                    new_cfg.wr_ports[wpidx].rd_port = pidx
                    pcfg = RdPortConfig()
                    pcfg.wr_port = wpidx
                    pcfg.port_group = wpcfg.port_group
                    pcfg.port_variant = wpcfg.port_variant
                    pcfg.defn = wpcfg.defn
                    pcfg.emu_sync = port.clk_enable and d.kind == P_ARSW
                    ok = True
                    if d.kind == P_SRSW:
                        trans = port.transparency_mask[wpidx]
                        col_x = port.collision_x_mask[wpidx]
                        if d.rdwr == RDWR_NOCHANGE:
                            if not self.get_wr_excludes_rd(wpidx, pidx):
                                if not trans and not col_x:
                                    ok = False
                                else:
                                    if trans:
                                        pcfg.emu_trans.append(wpidx)
                                    new_cfg.wr_ports[wpidx].force_uniform = True
                            if ok and not port.en_one:
                                if d.clk_en:
                                    pcfg.rd_en_to_clk_en = True
                                else:
                                    pcfg.emu_en = not d.rd_en
                        else:
                            if not col_x and not trans and d.rdwr != RDWR_OLD:
                                ok = False
                            else:
                                if trans:
                                    if d.rdwr != RDWR_NEW and d.rdwr != RDWR_NEWONLY:
                                        pcfg.emu_trans.append(wpidx)
                                if d.rdwr == RDWR_NEWONLY:
                                    if not self.get_wr_excludes_rd(wpidx, pidx):
                                        new_cfg.wr_ports[wpidx].force_uniform = True
                                if not port.en_one:
                                    if d.clk_en:
                                        if self.get_wr_implies_rd(wpidx, pidx):
                                            pcfg.rd_en_to_clk_en = True
                                        else:
                                            pcfg.emu_en = not d.rd_en
                                    else:
                                        pcfg.emu_en = not d.rd_en
                    if not ok:
                        continue
                    new_cfg.rd_ports.append(pcfg)
                    new_cfgs.append(new_cfg)
            self.cfgs = new_cfgs

    def emulate_read_first_ok(self):
        mem = self.mem
        if not mem.wr_ports:
            return False
        for p in mem.wr_ports:
            if not p.clk_enable:
                return False
        found = False
        for p in mem.rd_ports:
            if not p.clk_enable:
                return False
            for j in range(len(mem.wr_ports)):
                if not p.transparency_mask[j] and not p.collision_x_mask[j]:
                    found = True
        return found

    def handle_trans(self):
        mem = self.mem
        if self.emulate_read_first_ok():
            new_cfgs = []
            for cfg in self.cfgs:
                new_cfgs.append(cfg)
                ok = True
                for pcfg in cfg.rd_ports:
                    if pcfg.wr_port != -1:
                        ok = False
                if ok:
                    c2 = cfg.clone()
                    c2.emu_read_first = True
                    new_cfgs.append(c2)
            self.cfgs = new_cfgs
        for rpidx, rport in enumerate(mem.rd_ports):
            if not rport.clk_enable:
                continue
            for wpidx, wport in enumerate(mem.wr_ports):
                if not wport.clk_enable:
                    continue
                new_cfgs = []
                for cfg in self.cfgs:
                    rpcfg = cfg.rd_ports[rpidx]
                    wpcfg = cfg.wr_ports[wpidx]
                    if rpcfg.wr_port == wpidx:
                        new_cfgs.append(cfg)
                        continue
                    if rport.collision_x_mask[wpidx] and not cfg.emu_read_first:
                        new_cfgs.append(cfg)
                        continue
                    transparent = rport.transparency_mask[wpidx] or cfg.emu_read_first
                    if rpcfg.emu_sync:
                        if transparent:
                            rpcfg.emu_trans.append(wpidx)
                        new_cfgs.append(cfg)
                    else:
                        found = False
                        for (tk, tg, kind) in wpcfg.defn.wrtrans:
                            if tk == WT_GROUP and rpcfg.port_group != tg:
                                continue
                            if transparent:
                                if kind == WTK_OLD:
                                    continue
                            else:
                                if kind != WTK_OLD:
                                    continue
                            new_cfgs.append(cfg)
                            found = True
                            break
                        if not found and transparent:
                            rpcfg.emu_trans.append(wpidx)
                            new_cfgs.append(cfg)
                self.cfgs = new_cfgs

    def handle_priority(self):
        pass  # single write port: no priority relations

    def handle_rd_rst(self):
        mem = self.mem
        for cfg in self.cfgs:
            for pidx, port in enumerate(mem.rd_ports):
                pcfg = cfg.rd_ports[pidx]
                if not port.clk_enable or pcfg.emu_sync or pcfg.emu_en:
                    continue
                d = pcfg.defn
                if d.rdinitval == RV_NONE:
                    pcfg.emu_init = not is_fully_undef(port.init_value)
                elif d.rdinitval == RV_ZERO:
                    pcfg.emu_init = not is_all_zero(port.init_value)
                init_val = list(port.init_value)
                if port.arst:
                    if d.rdarstval == RV_NONE:
                        pcfg.emu_arst = True
                    elif d.rdarstval == RV_ZERO:
                        pcfg.emu_arst = not is_all_zero(port.arst_value)
                    elif d.rdarstval == RV_INIT:
                        if is_fully_undef(init_val):
                            init_val = list(port.arst_value)
                        pcfg.emu_arst = init_val != port.arst_value
                if port.srst:
                    if d.rdsrstval == RV_NONE:
                        pcfg.emu_srst = True
                    elif d.rdsrstval == RV_ZERO:
                        pcfg.emu_srst = not is_all_zero(port.srst_value)
                    elif d.rdsrstval == RV_INIT:
                        if is_fully_undef(init_val):
                            init_val = list(port.srst_value)
                        pcfg.emu_srst = init_val != port.srst_value
                    if not pcfg.emu_srst and d.rdsrst_block_wr and pcfg.wr_port != -1:
                        if not self.get_wr_excludes_srst(pcfg.wr_port, pidx):
                            pcfg.emu_srst = True
                    if not pcfg.emu_srst and not port.en_one:
                        if port.ce_over_srst:
                            if d.rdsrstmode == SRST_UNGATED:
                                pcfg.emu_srst_en_prio = True
                            elif d.rdsrstmode == SRST_GATED_CLKEN:
                                pcfg.emu_srst_en_prio = not pcfg.rd_en_to_clk_en
                            elif d.rdsrstmode == SRST_GATED_RDEN:
                                pass
                            else:
                                raise RuntimeError("bad srst mode")
                        else:
                            if d.rdsrstmode == SRST_UNGATED:
                                pass
                            elif d.rdsrstmode == SRST_GATED_CLKEN:
                                if pcfg.rd_en_to_clk_en:
                                    if d.rd_en:
                                        pcfg.rd_en_to_clk_en = False
                                    else:
                                        pcfg.emu_srst_en_prio = True
                            elif d.rdsrstmode == SRST_GATED_RDEN:
                                pcfg.emu_srst_en_prio = True
                            else:
                                raise RuntimeError("bad srst mode")
                else:
                    if d.rd_en and d.rdwr == RDWR_NOCHANGE and pcfg.wr_port != -1:
                        pcfg.rd_en_to_clk_en = False

    def score_emu_ports(self):
        for cfg in self.cfgs:
            ngroups = len(cfg.defn.port_groups)
            port_usage_wr = [0] * ngroups
            port_usage_rd = [0] * ngroups
            score = 0
            if cfg.emu_read_first:
                score += 3 * len(cfg.wr_ports)
            for pcfg in cfg.wr_ports:
                score += len(pcfg.emu_prio)
                port_usage_wr[pcfg.port_group] += 1
            for pcfg in cfg.rd_ports:
                score += 3 * len(pcfg.emu_trans)
                if pcfg.emu_en:
                    score += 3
                if pcfg.emu_init:
                    score += 2
                if pcfg.emu_arst:
                    score += 2
                if pcfg.emu_srst:
                    score += 2
                if pcfg.emu_srst_en_prio:
                    score += 1
                if pcfg.wr_port == -1:
                    score += 1
                    port_usage_rd[pcfg.port_group] += 1
            cfg.score_emu = score
            repl_port = 1
            for i in range(ngroups):
                space = len(cfg.defn.port_groups[i].names) - port_usage_wr[i]
                if port_usage_rd[i] > 0:
                    usage = port_usage_rd[i]
                    cur = (usage + space - 1) // space
                    if cur > repl_port:
                        repl_port = cur
            cfg.repl_port = repl_port

    def handle_geom(self):
        mem = self.mem
        wren_size = [p.en_distinct for p in mem.wr_ports]
        for cfg in self.cfgs:
            d = cfg.defn
            dbits = d.dbits
            byte_boundary = [False] * mem.width
            word_boundary = [False] * mem.width
            byte_boundary[0] = True
            for pidx, port in enumerate(mem.wr_ports):
                pcfg = cfg.wr_ports[pidx]
                if pcfg.force_uniform:
                    word_boundary[0] = True
                for i in range(1, mem.width):
                    if port.en[i] != port.en[i - 1]:
                        byte_boundary[i] = True
                        if pcfg.force_uniform:
                            word_boundary[i] = True
            got_config = False
            best_cost = 0
            byte_width_log2 = 0
            for i in range(len(dbits)):
                if d.byte >= dbits[i]:
                    byte_width_log2 = i
            if d.byte == 0:
                byte_width_log2 = len(dbits) - 1
            no_wide_bits = set()
            max_wr_wide_log2 = 0
            for port in mem.wr_ports:
                if port.wide_log2 > max_wr_wide_log2:
                    max_wr_wide_log2 = port.wide_log2
            max_wide_log2 = max_wr_wide_log2
            for port in mem.rd_ports:
                if port.wide_log2 > max_wide_log2:
                    max_wide_log2 = port.wide_log2
            wide_nu_start = max_wide_log2
            wide_nu_end = max_wr_wide_log2
            # (no wide ports in ramgen: uniformity loops are no-ops)
            for base_width_log2 in range(len(dbits)):
                unit_width_log2 = base_width_log2
                for pcfg in cfg.wr_ports:
                    if unit_width_log2 > pcfg.defn.max_wr_wide_log2:
                        unit_width_log2 = pcfg.defn.max_wr_wide_log2
                for pcfg in cfg.rd_ports:
                    if unit_width_log2 > pcfg.defn.max_rd_wide_log2:
                        unit_width_log2 = pcfg.defn.max_rd_wide_log2
                if unit_width_log2 != base_width_log2 and got_config:
                    break
                unit_width = dbits[unit_width_log2]
                effective_byte = d.byte
                if effective_byte == 0 or effective_byte > unit_width:
                    effective_byte = unit_width
                if not mem.wr_ports:
                    effective_byte = 1
                # swizzle
                swl = []
                for i in range(mem.width):
                    if word_boundary[i]:
                        while len(swl) % unit_width:
                            swl.append(-1)
                    elif byte_boundary[i]:
                        while len(swl) % effective_byte:
                            swl.append(-1)
                    swl.append(i)
                if word_boundary[0]:
                    while len(swl) % unit_width:
                        swl.append(-1)
                else:
                    while len(swl) % effective_byte:
                        swl.append(-1)
                swz = len(swl)
                hard_wide_mask = 0
                hard_wide_num = 0
                byte_failed = False
                while True:
                    min_width_ok = True
                    min_width_bit = wide_nu_start
                    for pidx, port in enumerate(mem.wr_ports):
                        w = base_width_log2
                        for i in range(port.wide_log2):
                            if hard_wide_mask & (1 << i):
                                w += 1
                        if w < cfg.wr_ports[pidx].defn.min_wr_wide_log2 and w < byte_width_log2:
                            min_width_ok = False
                            if min_width_bit > port.wide_log2:
                                min_width_bit = port.wide_log2
                    if min_width_ok:
                        emu_wide_bits = max_wide_log2 - hard_wide_num
                        mult_wide = 1 << emu_wide_bits
                        addrs = 1 << (d.abits - base_width_log2 + emu_wide_bits)
                        min_addr = mem.start_offset // addrs
                        max_addr = (mem.start_offset + mem.size - 1) // addrs
                        mult_a = max_addr - min_addr + 1
                        bits = mult_a * mult_wide * swz
                        repl = (bits + unit_width - 1) // unit_width
                        score_demux = 0
                        for i, port in enumerate(mem.wr_ports):
                            w = emu_wide_bits
                            for j in range(port.wide_log2):
                                if not (hard_wide_mask & (1 << j)):
                                    w -= 1
                            if w or mult_a != 1:
                                score_demux += (mult_a << w) * wren_size[i]
                        score_mux = 0
                        for port in mem.rd_ports:
                            w = emu_wide_bits
                            for j in range(port.wide_log2):
                                if not (hard_wide_mask & (1 << j)):
                                    w -= 1
                            score_mux += ((mult_a << w) - 1) * (port.width << port.wide_log2)
                        cost = (d.cost - d.widthscale) * repl * cfg.repl_port
                        cost += d.widthscale * mult_a * mult_wide * mem.width / unit_width * cfg.repl_port
                        cost += score_mux * FACTOR_MUX
                        cost += score_demux * FACTOR_DEMUX
                        cost += cfg.score_emu * FACTOR_EMU
                        if not got_config or cost < best_cost:
                            cfg.base_width_log2 = base_width_log2
                            cfg.unit_width_log2 = unit_width_log2
                            cfg.swizzle_size = swz
                            cfg.swizzle = list(swl)
                            cfg.hard_wide_mask = hard_wide_mask
                            cfg.emu_wide_mask = ((1 << max_wide_log2) - 1) & ~hard_wide_mask
                            cfg.repl_d = repl
                            cfg.score_demux = score_demux
                            cfg.score_mux = score_mux
                            cfg.cost = cost
                            cfg.mult_a = mult_a
                            best_cost = _trunc(cost)
                            got_config = True
                    if d.width_mode != WM_PERPORT:
                        break
                    # next_hw
                    done = False
                    while True:
                        retry = False
                        if not min_width_ok:
                            scan_from = min_width_bit
                            scan_to = 0
                        elif byte_failed:
                            scan_from = max_wide_log2
                            scan_to = wide_nu_end
                        elif base_width_log2 + hard_wide_num < byte_width_log2:
                            scan_from = wide_nu_start
                            scan_to = 0
                            retry = True
                        else:
                            scan_from = max_wide_log2
                            scan_to = 0
                        bit = scan_from - 1
                        failed = False
                        while True:
                            if bit < scan_to:
                                failed = True
                                break
                            if not (hard_wide_mask & (1 << bit)) and bit not in no_wide_bits:
                                break
                            bit -= 1
                        if not failed:
                            new_hw_mask = hard_wide_mask | (1 << bit)
                            for pidx, port in enumerate(mem.wr_ports):
                                w = base_width_log2
                                for i in range(port.wide_log2):
                                    if new_hw_mask & (1 << i):
                                        w += 1
                                if w > cfg.wr_ports[pidx].defn.max_wr_wide_log2:
                                    failed = True
                            if not failed:
                                for pidx, port in enumerate(mem.rd_ports):
                                    w = base_width_log2
                                    for i in range(port.wide_log2):
                                        if new_hw_mask & (1 << i):
                                            w += 1
                                    if w > cfg.rd_ports[pidx].defn.max_rd_wide_log2:
                                        failed = True
                        if failed:
                            if retry:
                                byte_failed = True
                                continue
                            done = True
                            break
                        hard_wide_mask = new_hw_mask
                        hard_wide_num += 1
                        break
                    if done:
                        break
            if not got_config:
                raise RuntimeError("no geometry found")

    def prune_post_geom(self):
        keep = []
        rsrc = {}
        for i, cfg in enumerate(self.cfgs):
            key = cfg.defn.resource_name
            if key == "":
                key = {K_DISTRIBUTED: "[distributed]", K_BLOCK: "[block]", K_HUGE: "[huge]"}.get(cfg.defn.kind, "")
            if key not in rsrc:
                rsrc[key] = i
                keep.append(True)
            else:
                ocfg = self.cfgs[rsrc[key]]
                if cfg.cost < ocfg.cost:
                    keep[rsrc[key]] = False
                    rsrc[key] = i
                    keep.append(True)
                else:
                    keep.append(False)
        self.cfgs = [c for c, k in zip(self.cfgs, keep) if k]

    # --- emission (counting only) ---
    def emit(self, cfg):
        mem = self.mem
        d = cfg.defn
        ffbits = 0
        # working copies of port state
        rd_state = []
        for port in mem.rd_ports:
            rd_state.append(dict(clk_enable=port.clk_enable, en_one=port.en_one, arst=port.arst,
                                 srst=port.srst, init=list(port.init_value), arst_value=list(port.arst_value),
                                 srst_value=list(port.srst_value), ce_over_srst=port.ce_over_srst,
                                 trans=list(port.transparency_mask), colx=list(port.collision_x_mask)))
        nwr = len(mem.wr_ports)
        if cfg.emu_read_first:
            for i, st in enumerate(rd_state):
                for j in range(nwr):
                    if st["trans"][j]:
                        ffbits += mem.width + _en_runs(mem.wr_ports[j].en)      # emulate_transparency
                        st["trans"][j] = False
                        st["colx"][j] = True
            for st in rd_state:
                for j in range(nwr):
                    st["colx"][j] = False
                    st["trans"][j] = True
            for port in mem.wr_ports:
                ffbits += port.width << port.wide_log2   # data
                ffbits += port.addr_bits                 # address
                ffbits += port.en_runs                   # compressed enable
        for pidx, port in enumerate(mem.rd_ports):
            pcfg = cfg.rd_ports[pidx]
            st = rd_state[pidx]
            if pcfg.emu_sync:
                # extract_rdff
                if not st["clk_enable"]:
                    continue
                trans_use_addr = all(st["trans"][i] for i in range(nwr))
                if nwr == 0:
                    trans_use_addr = False
                if (not st["en_one"]) or st["srst"] or st["arst"] or not is_fully_undef(st["init"]):
                    trans_use_addr = False
                if trans_use_addr:
                    ffbits += port.addr_bits
                else:
                    ffbits += port.width << port.wide_log2
                st["clk_enable"] = False
                st["en_one"] = True
                st["arst"] = False
                st["srst"] = False
                st["init"] = ["x"] * len(st["init"])
                for j in range(nwr):
                    st["trans"][j] = False
                    st["colx"][j] = False
            elif pcfg.emu_en:
                # emulate_rden: 1-bit select FF + W-bit data FF
                ffbits += 1 + (port.width << port.wide_log2)
                st["init"] = ["x"] * len(st["init"])
                st["arst"] = False
                st["srst"] = False
                st["en_one"] = True
                st["ce_over_srst"] = False
            else:
                if pcfg.emu_srst_en_prio:
                    if st["ce_over_srst"]:
                        st["ce_over_srst"] = False
                    else:
                        st["ce_over_srst"] = True
                # emulate_reset
                if pcfg.emu_init and not is_fully_undef(st["init"]):
                    ffbits += 1
                    if st["arst"] and pcfg.emu_arst and st["arst_value"] == st["init"]:
                        st["arst"] = False
                    if st["srst"] and pcfg.emu_srst and st["srst_value"] == st["init"]:
                        st["srst"] = False
                    st["init"] = ["x"] * len(st["init"])
                if pcfg.emu_arst and st["arst"]:
                    ffbits += 1
                    if st["srst"] and pcfg.emu_srst and st["srst_value"] == st["arst_value"]:
                        st["srst"] = False
                    st["arst"] = False
                if pcfg.emu_srst and st["srst"]:
                    ffbits += 1
                    st["srst"] = False
        for pidx, port in enumerate(mem.rd_ports):
            pcfg = cfg.rd_ports[pidx]
            st = rd_state[pidx]
            for opidx in pcfg.emu_trans:
                if st["trans"][opidx]:
                    ffbits += (mem.width << port.wide_log2) + _en_runs(mem.wr_ports[opidx].en)
                    st["trans"][opidx] = False
                    st["colx"][opidx] = True
        # port -> hardware port assignment
        ngroups = len(d.port_groups)
        ports = [[[] for _ in range(ngroups)] for _ in range(cfg.repl_port)]
        for i, pcfg in enumerate(cfg.wr_ports):
            for j in range(cfg.repl_port):
                if j == 0:
                    ports[j][pcfg.port_group].append((i, pcfg.rd_port))
                else:
                    ports[j][pcfg.port_group].append((i, -1))
        for i, pcfg in enumerate(cfg.rd_ports):
            if pcfg.wr_port != -1:
                continue
            pg = d.port_groups[pcfg.port_group]
            j = 0
            while len(ports[j][pcfg.port_group]) >= len(pg.names):
                j += 1
            ports[j][pcfg.port_group].append((-1, i))
        options = {}
        for name, val in d.options.items():
            options["OPTION_%s" % name] = val
        addr_shift = d.abits - cfg.base_width_log2 + bin(cfg.emu_wide_mask).count("1")
        for rp in range(cfg.repl_port):
            for pgi, pg in enumerate(d.port_groups):
                for pi, pname in enumerate(pg.names):
                    used = pi < len(ports[rp][pgi])
                    if used:
                        wpidx, rpidx = ports[rp][pgi][pi]
                        if wpidx != -1:
                            pdef = cfg.wr_ports[wpidx].defn
                        else:
                            pdef = cfg.rd_ports[rpidx].defn
                    else:
                        wpidx, rpidx = -1, -1
                        pdef = pg.variants[0]
                    if rp == 0:
                        self.emit_port_options(cfg, pdef, pname, wpidx, rpidx, options)
                    # generate_mux FF for sync read ports
                    if rpidx != -1 and rd_state[rpidx]["clk_enable"]:
                        rport = mem.rd_ports[rpidx]
                        rd_wide_log2 = rport.wide_log2
                        wide_log2 = rd_wide_log2
                        wr_wide_log2 = 0
                        if wpidx != -1:
                            wr_wide_log2 = mem.wr_ports[wpidx].wide_log2
                            wide_log2 = max(rd_wide_log2, wr_wide_log2)
                        if pdef.width_tied:
                            rd_wide_log2 = wide_log2
                        hw_rd = cfg.base_width_log2
                        for i in range(rd_wide_log2):
                            if cfg.hard_wide_mask & (1 << i):
                                hw_rd += 1
                        if hw_rd < pdef.min_rd_wide_log2:
                            hw_rd = pdef.min_rd_wide_log2
                        if hw_rd > pdef.max_rd_wide_log2:
                            hw_rd = pdef.max_rd_wide_log2
                        # gen_swizzle address mux bits
                        emu_wide_bits = []
                        hard_wide_bits = []
                        for i in range(ceil_log2(mem.size)):
                            if cfg.emu_wide_mask & (1 << i):
                                emu_wide_bits.append(i)
                            elif len(hard_wide_bits) < hw_rd - cfg.base_width_log2:
                                hard_wide_bits.append(i)
                        sw_wide_log2 = rport.wide_log2
                        nmux = sum(1 for x in hard_wide_bits if x >= sw_wide_log2)
                        nmux += sum(1 for x in emu_wide_bits if x >= sw_wide_log2)
                        ashift = d.abits - cfg.base_width_log2 + len(emu_wide_bits)
                        addr_start = mem.start_offset & ~((1 << ashift) - 1)
                        addr_end = ((mem.start_offset + mem.size - 1) | ((1 << ashift) - 1)) + 1
                        hi_bits = ceil_log2(addr_end - addr_start) - ashift
                        nsel = nmux + hi_bits
                        if nsel > 0:
                            ffbits += nsel
        cells = cfg.repl_port * cfg.repl_d
        return cells, ffbits, options

    def emit_port_options(self, cfg, pdef, name, wpidx, rpidx, options):
        mem = self.mem
        d = cfg.defn
        for k, v in pdef.options.items():
            options["PORT_%s_OPTION_%s" % (name, k)] = v
        wide_log2 = wr_wide_log2 = rd_wide_log2 = 0
        if wpidx != -1:
            wport = mem.wr_ports[wpidx]
            wide_log2 = wr_wide_log2 = wport.wide_log2
            if rpidx != -1:
                rport = mem.rd_ports[rpidx]
                rd_wide_log2 = rport.wide_log2
                if rd_wide_log2 > wr_wide_log2:
                    wide_log2 = rd_wide_log2
        elif rpidx != -1:
            rport = mem.rd_ports[rpidx]
            wide_log2 = rd_wide_log2 = rport.wide_log2
        if pdef.width_tied:
            rd_wide_log2 = wr_wide_log2 = wide_log2
        hw_wr = cfg.base_width_log2
        for i in range(wr_wide_log2):
            if cfg.hard_wide_mask & (1 << i):
                hw_wr += 1
        if hw_wr < pdef.min_wr_wide_log2:
            hw_wr = pdef.min_wr_wide_log2
        if hw_wr > pdef.max_wr_wide_log2:
            hw_wr = pdef.max_wr_wide_log2
        hw_rd = cfg.base_width_log2
        for i in range(rd_wide_log2):
            if cfg.hard_wide_mask & (1 << i):
                hw_rd += 1
        if hw_rd < pdef.min_rd_wide_log2:
            hw_rd = pdef.min_rd_wide_log2
        if hw_rd > pdef.max_rd_wide_log2:
            hw_rd = pdef.max_rd_wide_log2
        if pdef.width_tied:
            if wpidx == -1 and rpidx == -1:
                hw_wr = pdef.max_wr_wide_log2
                hw_rd = pdef.max_rd_wide_log2
        else:
            if wpidx == -1:
                hw_wr = pdef.max_wr_wide_log2
            if rpidx == -1:
                hw_rd = pdef.max_rd_wide_log2
        if pdef.kind not in (P_AR, P_SR) and pdef.wrbe_separate and d.width_mode != WM_SINGLE:
            width = d.dbits[hw_wr]
            eb = d.byte
            if eb == 0 or eb > width:
                eb = width
            options["PORT_%s_WR_BE_WIDTH" % name] = width // eb
        if d.width_mode == WM_PERPORT:
            if pdef.width_tied:
                options["PORT_%s_WIDTH" % name] = d.dbits[hw_wr]
            else:
                if pdef.kind not in (P_AR, P_SR):
                    options["PORT_%s_WR_WIDTH" % name] = d.dbits[hw_wr]
                if pdef.kind != P_SW:
                    options["PORT_%s_RD_WIDTH" % name] = d.dbits[hw_rd]


EMPTY_SHA = hashlib.sha256(b"").hexdigest()


def gen_swizzle_init(mem, cfg):
    """gen_swizzle(mem, cfg, 0, len(dbits) - 1) for memories without wide ports; returns bits[rd][hbit] = None or (addr, bit)"""
    d = cfg.defn
    dbits = d.dbits
    hw_wide_log2 = len(dbits) - 1
    emu_wide_bits = []
    hard_wide_bits = []
    nlim = ceil_log2(mem.size)
    for i in range(nlim):
        if cfg.emu_wide_mask & (1 << i):
            emu_wide_bits.append(i)
        elif len(hard_wide_bits) < hw_wide_log2 - cfg.base_width_log2:
            hard_wide_bits.append(i)
    addr_mux_bits = [x for x in hard_wide_bits if x >= 0] + [x for x in emu_wide_bits if x >= 0]
    addr_shift = d.abits - cfg.base_width_log2 + len(emu_wide_bits)
    addr_start = mem.start_offset & ~((1 << addr_shift) - 1)
    addr_end = ((mem.start_offset + mem.size - 1) | ((1 << addr_shift) - 1)) + 1
    hnum = (addr_end - addr_start) >> addr_shift
    unit_width = dbits[cfg.unit_width_log2]
    res = [[None] * dbits[hw_wide_log2] for _ in range(cfg.repl_d)]
    swl = cfg.swizzle
    for hi in range(hnum):
        for ewi in range(1 << len(emu_wide_bits)):
            for hwi in range(1 << len(hard_wide_bits)):
                mux_idx = 0; sub = 0; mib = 0; hbit_base = 0
                for i in range(len(hard_wide_bits)):
                    if hard_wide_bits[i] < 0:
                        if hwi & (1 << i): sub |= 1 << hard_wide_bits[i]
                    else:
                        if hwi & (1 << i): mux_idx |= 1 << mib
                        mib += 1
                    if hwi & (1 << i):
                        hbit_base += dbits[i + cfg.base_width_log2]
                for i in range(len(emu_wide_bits)):
                    if emu_wide_bits[i] < 0:
                        if ewi & (1 << i): sub |= 1 << emu_wide_bits[i]
                    else:
                        if ewi & (1 << i): mux_idx |= 1 << mib
                        mib += 1
                mux_idx |= hi << mib
                addr = addr_start + (hi << addr_shift)
                for i in range(len(addr_mux_bits)):
                    if mux_idx & (1 << i):
                        addr += 1 << addr_mux_bits[i]
                for bit in range(len(swl)):
                    if swl[bit] == -1:
                        continue
                    rbit = bit + len(swl) * (ewi + (hi << len(emu_wide_bits)))
                    rep = rbit // unit_width
                    hbit = hbit_base + rbit % unit_width
                    res[rep][hbit] = (addr, swl[bit] + sub * mem.width)
    return res, addr_shift


def init_params(mem, cfg):
    """INIT parameter of every cell (key "rp.rd") as a string MSB first, or None if the cell has none"""
    d = cfg.defn
    if d.init not in (INIT_ANY, INIT_NOUNDEF):
        return {"%d.%d" % (rp, rd): None for rp in range(cfg.repl_port) for rd in range(cfg.repl_d)}
    swz, addr_shift = gen_swizzle_init(mem, cfg)
    hw_addr_swizzle = [-1] * cfg.base_width_log2
    for i in range(addr_shift):
        if not (cfg.emu_wide_mask & (1 << i)):
            hw_addr_swizzle.append(i)
    assert len(hw_addr_swizzle) == d.abits
    W = mem.width
    words = mem.init_words
    step = 1 << (len(d.dbits) - 1)
    out = {}
    for rd in range(cfg.repl_d):
        val = []
        for hwa in range(0, 1 << d.abits, step):
            for b in swz[rd]:
                if b is None:
                    val.append("x"); continue
                addr, bit = b
                for i in range(len(d.dbits) - 1, d.abits):
                    if hwa & (1 << i):
                        addr += 1 << hw_addr_swizzle[i]
                if mem.start_offset <= addr < mem.start_offset + mem.size:
                    wv = words[addr - mem.start_offset]
                    val.append(wv[bit] if wv is not None else "x")
                else:
                    val.append("x")
        if d.init == INIT_NOUNDEF:
            val = ["0" if v == "x" else v for v in val]
        s = "".join(reversed(val))
        for rp in range(cfg.repl_port):
            out["%d.%d" % (rp, rd)] = s
    return out


def estimate(query):
    flow = query["flow"]
    fl = FLOWS[flow]
    lib = get_library(flow)
    mem = _build_mem(query)
    if mem.removed:
        return {"class": "NONE", "cells": 0, "ffbits": mem.pre_ffbits, "init": EMPTY_SHA}
    opts = dict(no_auto_distributed=False, no_auto_block=False, no_auto_huge=fl["no_auto_huge"],
                logic_cost_rom=fl["logic_cost_rom"], logic_cost_ram=fl["logic_cost_ram"])
    mp = MemMapping(mem, lib, opts)
    idx = -1
    best = _trunc(mp.logic_cost)
    if not mp.logic_ok:
        if not mp.cfgs:
            raise RuntimeError("no valid mapping")
        idx = 0
        best = _trunc(mp.cfgs[0].cost)
    for i, cfg in enumerate(mp.cfgs):
        if cfg.cost < best:
            idx = i
            best = _trunc(cfg.cost)
    if idx == -1:
        return {"class": "FF", "cells": 0, "ffbits": mem.pre_ffbits, "init": EMPTY_SHA}
    cfg = mp.cfgs[idx]
    cells, ffbits, options = mp.emit(cfg)
    inits = init_params(mem, cfg)
    lst = sorted((tuple(int(x) for x in k.split(".")), v) for k, v in inits.items())
    text = "".join("%d.%d:%s\n" % (k[0], k[1], v if v is not None else "-") for k, v in lst)
    return {"class": cfg.defn.id, "cells": cells, "ffbits": mem.pre_ffbits + ffbits, "init": hashlib.sha256(text.encode()).hexdigest()}


if __name__ == "__main__":
    import sys
    q = json.loads(sys.argv[1])
    print(json.dumps(estimate(q)))