veryl-simulator 0.20.0

A modern hardware description language
Documentation
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
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
use crate::HashMap;
use crate::HashSet;
#[cfg(not(target_family = "wasm"))]
use crate::cranelift;
use crate::ir::context::{Context, Conv, ScopeContext};
use crate::ir::declaration::stable_topo_sort;
use crate::ir::schedule::IrSchedule;
use crate::ir::variable::{
    ModuleVariableMeta, ModuleVariables, VarOffset, Variable, create_variable_meta, value_size,
    write_native_value,
};
use crate::ir::{
    Event, ProtoDeclaration, ProtoStatement, ProtoStatementBlock, ProtoStatements, Statement,
    VarId, VarPath,
};
use crate::simulator_error::SimulatorError;
use daggy::Dag;
use daggy::petgraph::Direction::Outgoing;
use daggy::petgraph::algo;
use std::collections::VecDeque;
use veryl_analyzer::ir as air;
use veryl_parser::resource_table::StrId;

pub struct Module {
    pub name: StrId,
    pub ports: HashMap<VarPath, VarId>,
    pub ff_values: Box<[u8]>,
    pub comb_values: Box<[u8]>,
    pub module_variables: ModuleVariables,

    pub event_statements: HashMap<Event, Vec<Statement>>,
    /// Unified comb statements: all port connections, child comb, and internal
    /// comb combined into a single dependency-sorted list.
    pub comb_statements: Vec<Statement>,
    /// Number of eval_comb passes needed for full convergence.
    /// Pre-computed from backward edges in the sorted comb statement list.
    pub required_comb_passes: usize,
    /// FF commit entries: (current_offset, value_size) pairs.
    pub ff_commit_entries: Vec<(usize, usize)>,
    /// Sensitivity-fanout + topological-rank index for the seeded-worklist
    /// scheduler. Populated from the topologically-sorted comb list;
    /// `eval_comb_worklist` uses it when `Config::use_seeded_worklist` is on.
    pub comb_schedule: IrSchedule,
    /// Diagnostic: number of non-trivial strongly-connected components in
    /// the pre-JIT `unified_sorted` dataflow graph.  Real RTL combinational
    /// loops are rejected up-front by `analyze_dependency`, so any non-zero
    /// value here is a duplication artifact in the simulator IR assembly.
    /// Exposed for regression tests.
    pub nontrivial_comb_scc: usize,
}

pub struct ProtoModule {
    pub name: StrId,
    pub ports: HashMap<VarPath, VarId>,
    pub ff_bytes: usize,
    pub comb_bytes: usize,
    pub use_4state: bool,
    pub module_variable_meta: ModuleVariableMeta,

    pub event_statements: HashMap<Event, ProtoStatements>,
    /// Unified comb statements: all port connections, child comb, and internal
    /// comb combined into a single dependency-sorted list.
    pub comb_statements: ProtoStatements,
    /// Number of eval_comb passes needed for full convergence.
    pub required_comb_passes: usize,
    /// See `Module::comb_schedule`.
    pub comb_schedule: IrSchedule,
    /// See `Module::nontrivial_comb_scc`.
    pub nontrivial_comb_scc: usize,
}

fn create_buffers(
    module_variable_meta: &ModuleVariableMeta,
    ff_bytes: usize,
    comb_bytes: usize,
    use_4state: bool,
) -> (Box<[u8]>, Box<[u8]>) {
    let mut ff_values = vec![0u8; ff_bytes];
    let mut comb_values = vec![0u8; comb_bytes];

    fill_buffers_recursive(
        module_variable_meta,
        &mut ff_values,
        &mut comb_values,
        use_4state,
    );

    (ff_values.into_boxed_slice(), comb_values.into_boxed_slice())
}

/// Fill byte buffers with initial values, writing at the offsets stored in VariableElement.
fn fill_buffers_recursive(
    module_meta: &ModuleVariableMeta,
    ff_values: &mut [u8],
    comb_values: &mut [u8],
    use_4state: bool,
) {
    let mut sorted: Vec<_> = module_meta.variable_meta.iter().collect();
    sorted.sort_by_key(|(k, _)| **k);

    for (_, meta) in &sorted {
        // Single-entry initial_values on a multi-element variable is the
        // compact template form used for large arrays.
        let template_mode = meta.initial_values.len() == 1 && meta.elements.len() > 1;
        for (i, element) in meta.elements.iter().enumerate() {
            let initial = if template_mode {
                &meta.initial_values[0]
            } else {
                match meta.initial_values.get(i) {
                    Some(v) => v,
                    None => continue,
                }
            };
            let nb = element.native_bytes;
            let _vs = value_size(nb, use_4state);
            if element.is_ff() {
                #[cfg(debug_assertions)]
                {
                    let off = element.current_offset() as usize;
                    debug_assert!(
                        off + _vs <= ff_values.len(),
                        "FF current_offset out of bounds"
                    );
                    debug_assert!(
                        element.next_offset as usize + _vs <= ff_values.len(),
                        "FF next_offset out of bounds"
                    );
                }
                let cur =
                    &mut ff_values[element.current_offset() as usize..] as *mut [u8] as *mut u8;
                let nxt = &mut ff_values[element.next_offset as usize..] as *mut [u8] as *mut u8;
                unsafe {
                    write_native_value(cur, nb, use_4state, initial);
                    write_native_value(nxt, nb, use_4state, initial);
                }
            } else {
                #[cfg(debug_assertions)]
                debug_assert!(
                    element.current_offset() as usize + _vs <= comb_values.len(),
                    "Comb current_offset out of bounds"
                );
                let cur =
                    &mut comb_values[element.current_offset() as usize..] as *mut [u8] as *mut u8;
                unsafe {
                    write_native_value(cur, nb, use_4state, initial);
                }
            }
        }
    }

    for child in &module_meta.children {
        fill_buffers_recursive(child, ff_values, comb_values, use_4state);
    }
}

fn create_variables_recursive(
    module_meta: &ModuleVariableMeta,
    ff_base: *mut u8,
    comb_base: *mut u8,
) -> ModuleVariables {
    let mut variables = HashMap::default();

    for (id, meta) in &module_meta.variable_meta {
        let mut current_values: Vec<*mut u8> = vec![];
        let mut next_values: Vec<*mut u8> = vec![];

        for element in &meta.elements {
            let current = unsafe {
                let base = if element.is_ff() { ff_base } else { comb_base };
                base.add(element.current_offset() as usize)
            };
            current_values.push(current);

            if element.is_ff() {
                let next = unsafe { ff_base.add(element.next_offset as usize) };
                next_values.push(next);
            }
        }

        variables.insert(
            *id,
            Variable {
                path: meta.path.clone(),
                r#type: meta.r#type.clone(),
                width: meta.width,
                native_bytes: meta.native_bytes,
                current_values,
                next_values,
            },
        );
    }

    let children = module_meta
        .children
        .iter()
        .map(|child| create_variables_recursive(child, ff_base, comb_base))
        .collect();

    ModuleVariables {
        name: module_meta.name,
        variables,
        children,
    }
}

/// Collect all FF commit entries (current_offset, value_size) from module metadata.
fn collect_ff_commit_entries(
    module_meta: &ModuleVariableMeta,
    use_4state: bool,
) -> Vec<(usize, usize)> {
    let mut entries = vec![];
    for meta in module_meta.variable_meta.values() {
        for element in &meta.elements {
            if element.is_ff() {
                let vs = value_size(element.native_bytes, use_4state);
                entries.push((element.current_offset() as usize, vs));
            }
        }
    }
    for child in &module_meta.children {
        entries.extend(collect_ff_commit_entries(child, use_4state));
    }
    entries.sort_unstable();
    entries
}

impl ProtoModule {
    pub fn instantiate(&self) -> Module {
        log::trace!(
            "instantiate: module={}, ff_bytes={}, comb_bytes={}",
            self.name,
            self.ff_bytes,
            self.comb_bytes,
        );
        let (mut ff_values, mut comb_values) = create_buffers(
            &self.module_variable_meta,
            self.ff_bytes,
            self.comb_bytes,
            self.use_4state,
        );

        let ff_base = ff_values.as_mut_ptr();
        let comb_base = comb_values.as_mut_ptr();

        let module_variables =
            create_variables_recursive(&self.module_variable_meta, ff_base, comb_base);

        let ff_ptr = ff_values.as_mut_ptr();
        let comb_ptr = comb_values.as_mut_ptr();

        let ff_len = self.ff_bytes;
        let comb_len = self.comb_bytes;

        let event_statements = self
            .event_statements
            .iter()
            .map(|(event, stmts)| {
                let s = stmts.to_statements(ff_ptr, ff_len, comb_ptr, comb_len, self.use_4state);
                (event.clone(), batch_binary_statements(s))
            })
            .collect();

        let comb_statements = batch_binary_statements(self.comb_statements.to_statements(
            ff_ptr,
            ff_len,
            comb_ptr,
            comb_len,
            self.use_4state,
        ));

        let ff_commit_entries =
            collect_ff_commit_entries(&self.module_variable_meta, self.use_4state);

        #[cfg(debug_assertions)]
        self.validate_offsets();

        Module {
            name: self.name,
            ports: self.ports.clone(),
            ff_values,
            comb_values,
            module_variables,

            event_statements,
            comb_statements,
            required_comb_passes: self.required_comb_passes,
            ff_commit_entries,
            comb_schedule: self.comb_schedule.clone(),
            nontrivial_comb_scc: self.nontrivial_comb_scc,
        }
    }

    /// Validate that all variable offsets in statements are within buffer bounds.
    #[cfg(debug_assertions)]
    fn validate_offsets(&self) {
        let ff_bytes = self.ff_bytes;
        let comb_bytes = self.comb_bytes;
        let use_4state = self.use_4state;

        let check = |off: &VarOffset, context: &str| {
            let raw = off.raw() as usize;
            if off.is_ff() {
                assert!(
                    raw < ff_bytes || ff_bytes == 0,
                    "validate_offsets [{}]: ff offset {} >= ff_bytes {} (module={})",
                    context,
                    raw,
                    ff_bytes,
                    self.name,
                );
            } else {
                assert!(
                    raw < comb_bytes || comb_bytes == 0,
                    "validate_offsets [{}]: comb offset {} >= comb_bytes {} (module={})",
                    context,
                    raw,
                    comb_bytes,
                    self.name,
                );
            }
        };

        let validate_stmts = |stmts: &ProtoStatements, label: &str| {
            for block in &stmts.0 {
                if let ProtoStatementBlock::Interpreted(proto) = block {
                    for s in proto {
                        let mut ins = vec![];
                        let mut outs = vec![];
                        s.gather_variable_offsets(&mut ins, &mut outs);
                        for off in ins.iter().chain(outs.iter()) {
                            check(off, label);
                        }
                    }
                }
            }
        };

        for (event, stmts) in &self.event_statements {
            validate_stmts(stmts, &format!("event {event:?}"));
        }
        validate_stmts(&self.comb_statements, "comb");

        // Validate variable metadata offsets
        validate_meta_offsets(&self.module_variable_meta, ff_bytes, comb_bytes, use_4state);
    }
}

#[cfg(debug_assertions)]
fn validate_meta_offsets(
    meta: &ModuleVariableMeta,
    ff_bytes: usize,
    comb_bytes: usize,
    use_4state: bool,
) {
    for (id, var_meta) in &meta.variable_meta {
        let vs = crate::ir::variable::value_size(var_meta.native_bytes, use_4state);
        for (i, elem) in var_meta.elements.iter().enumerate() {
            let off = elem.current_offset() as usize;
            if elem.is_ff() {
                assert!(
                    off + vs * 2 <= ff_bytes,
                    "validate_meta: ff var {:?}[{}] offset {} + vs*2 {} > ff_bytes {}",
                    id,
                    i,
                    off,
                    vs * 2,
                    ff_bytes,
                );
            } else {
                assert!(
                    off + vs <= comb_bytes,
                    "validate_meta: comb var {:?}[{}] offset {} + vs {} > comb_bytes {}",
                    id,
                    i,
                    off,
                    vs,
                    comb_bytes,
                );
            }
        }
    }
    for child in &meta.children {
        validate_meta_offsets(child, ff_bytes, comb_bytes, use_4state);
    }
}

/// Maximum number of statements per JIT function.
/// Keeps regalloc2 cost manageable (O(N^2) in SSA variable count).
/// Sized large enough to fuse a typical design's comb body into a single
/// JIT function — shrinking num_chunks reduces per-step enum-match
/// dispatch overhead in `eval_comb_full` proportionally.
/// Overridable via `VERYL_JIT_CHUNK_SIZE` env var for sweeps.
const JIT_CHUNK_SIZE_DEFAULT: usize = 8192;

fn jit_chunk_size() -> usize {
    std::env::var("VERYL_JIT_CHUNK_SIZE")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(JIT_CHUNK_SIZE_DEFAULT)
}

/// Build an IrSchedule whose stmt ids align 1:1 with the post-JIT
/// `comb_statements` slice. Mirrors the chunking logic of
/// `try_jit_no_cache` so each post-JIT Statement index maps to a
/// contiguous [start..end) range of pre-JIT ProtoStatements, and
/// aggregates gather_variable_offsets across that range.
#[cfg(not(target_family = "wasm"))]
fn build_aligned_schedule(
    pre_jit_stmts: &[ProtoStatement],
    use_jit: bool,
    meta: &ModuleVariableMeta,
    use_4state: bool,
) -> IrSchedule {
    use smallvec::SmallVec;
    let mut per_stmt_inputs: Vec<SmallVec<[VarOffset; 4]>> = Vec::new();
    let mut per_stmt_outputs: Vec<SmallVec<[VarOffset; 4]>> = Vec::new();

    let emit_chunk = |chunk: &[ProtoStatement],
                      per_in: &mut Vec<SmallVec<[VarOffset; 4]>>,
                      per_out: &mut Vec<SmallVec<[VarOffset; 4]>>| {
        let mut ins_all: Vec<VarOffset> = Vec::new();
        let mut outs_all: Vec<VarOffset> = Vec::new();
        for s in chunk {
            s.gather_variable_offsets_expanded(&mut ins_all, &mut outs_all);
        }
        let mut ins: SmallVec<[VarOffset; 4]> = SmallVec::new();
        for off in ins_all {
            if !ins.contains(&off) {
                ins.push(off);
            }
        }
        let mut outs: SmallVec<[VarOffset; 4]> = SmallVec::new();
        for off in outs_all {
            if !outs.contains(&off) {
                outs.push(off);
            }
        }
        per_in.push(ins);
        per_out.push(outs);
    };

    if !use_jit {
        // JIT-off: try_jit_no_cache returns a single Interpreted block
        // holding all pre-JIT stmts — one aligned slot covers everything.
        emit_chunk(pre_jit_stmts, &mut per_stmt_inputs, &mut per_stmt_outputs);
    } else {
        // Mirror try_jit_no_cache: contiguous groups of same can_build_binary,
        // jittable groups further split by JIT_CHUNK_SIZE.
        let mut current_jittable: Option<bool> = None;
        let mut group_start: usize = 0;

        let flush = |group_start: usize,
                     group_end: usize,
                     was_jittable: bool,
                     per_in: &mut Vec<SmallVec<[VarOffset; 4]>>,
                     per_out: &mut Vec<SmallVec<[VarOffset; 4]>>| {
            let group = &pre_jit_stmts[group_start..group_end];
            let chunk_size = jit_chunk_size();
            if was_jittable && group.len() > chunk_size {
                for chunk in group.chunks(chunk_size) {
                    emit_chunk(chunk, per_in, per_out);
                }
            } else {
                emit_chunk(group, per_in, per_out);
            }
        };

        for (i, stmt) in pre_jit_stmts.iter().enumerate() {
            let jittable = stmt.can_build_binary();
            match current_jittable {
                None => {
                    current_jittable = Some(jittable);
                    group_start = i;
                }
                Some(prev) if prev == jittable => {}
                Some(prev) => {
                    flush(
                        group_start,
                        i,
                        prev,
                        &mut per_stmt_inputs,
                        &mut per_stmt_outputs,
                    );
                    current_jittable = Some(jittable);
                    group_start = i;
                }
            }
        }
        if let Some(prev) = current_jittable
            && group_start < pre_jit_stmts.len()
        {
            flush(
                group_start,
                pre_jit_stmts.len(),
                prev,
                &mut per_stmt_inputs,
                &mut per_stmt_outputs,
            );
        }
    }

    let n = per_stmt_inputs.len();
    let mut sched = IrSchedule {
        n_stmts: n as u32,
        stmt_inputs: per_stmt_inputs,
        stmt_outputs: per_stmt_outputs,
        output_to_readers: crate::HashMap::default(),
        topo_rank: (0..n as crate::ir::schedule::StmtId).collect(),
        offset_sizes: crate::HashMap::default(),
    };
    sched.rebuild_fanout();
    sched.attach_offset_sizes(meta, use_4state);
    sched
}

#[cfg(not(target_family = "wasm"))]
fn try_jit_group(
    context: &mut Context,
    blocks: &mut Vec<ProtoStatementBlock>,
    group: Vec<ProtoStatement>,
) {
    // Split large groups into chunks to avoid regalloc2 O(N^2) scaling
    if group.len() <= jit_chunk_size() {
        match cranelift::build_binary(context, group.clone()) {
            Some(func) => blocks.push(ProtoStatementBlock::Compiled(func)),
            None => blocks.push(ProtoStatementBlock::Interpreted(group)),
        }
    } else {
        for chunk in group.chunks(jit_chunk_size()) {
            let chunk = chunk.to_vec();
            match cranelift::build_binary(context, chunk.clone()) {
                Some(func) => blocks.push(ProtoStatementBlock::Compiled(func)),
                None => blocks.push(ProtoStatementBlock::Interpreted(chunk)),
            }
        }
    }
}

#[cfg(target_family = "wasm")]
fn try_jit(_context: &mut Context, proto: Vec<ProtoStatement>) -> ProtoStatements {
    ProtoStatements(vec![ProtoStatementBlock::Interpreted(proto)])
}

#[cfg(not(target_family = "wasm"))]
fn try_jit(context: &mut Context, proto: Vec<ProtoStatement>) -> ProtoStatements {
    if !context.config.use_jit {
        return ProtoStatements(vec![ProtoStatementBlock::Interpreted(proto)]);
    }

    // Group consecutive statements by can_build_binary() result
    let mut blocks: Vec<ProtoStatementBlock> = Vec::new();
    let mut current_jittable: Option<bool> = None;
    let mut current_group: Vec<ProtoStatement> = Vec::new();

    for stmt in proto {
        let jittable = stmt.can_build_binary();

        if current_jittable == Some(jittable) {
            current_group.push(stmt);
        } else {
            if let Some(was_jittable) = current_jittable {
                let group = std::mem::take(&mut current_group);
                if was_jittable {
                    try_jit_group(context, &mut blocks, group);
                } else {
                    blocks.push(ProtoStatementBlock::Interpreted(group));
                }
            }
            current_jittable = Some(jittable);
            current_group.push(stmt);
        }
    }

    // Flush the last group
    if let Some(was_jittable) = current_jittable {
        if was_jittable {
            try_jit_group(context, &mut blocks, current_group);
        } else {
            blocks.push(ProtoStatementBlock::Interpreted(current_group));
        }
    }

    ProtoStatements(blocks)
}

/// JIT with load_cache disabled for unified comb.
/// CompiledBlocks (child comb functions) may modify comb values between
/// cached loads, so load_cache must be disabled for correctness.
#[cfg(target_family = "wasm")]
fn try_jit_no_cache(_context: &mut Context, proto: Vec<ProtoStatement>) -> ProtoStatements {
    ProtoStatements(vec![ProtoStatementBlock::Interpreted(proto)])
}

#[cfg(not(target_family = "wasm"))]
fn try_jit_no_cache(context: &mut Context, proto: Vec<ProtoStatement>) -> ProtoStatements {
    if !context.config.use_jit {
        return ProtoStatements(vec![ProtoStatementBlock::Interpreted(proto)]);
    }

    let mut blocks: Vec<ProtoStatementBlock> = Vec::new();
    let mut current_jittable: Option<bool> = None;
    let mut current_group: Vec<ProtoStatement> = Vec::new();

    for stmt in proto {
        let jittable = stmt.can_build_binary();
        if current_jittable == Some(jittable) {
            current_group.push(stmt);
        } else {
            if let Some(was_jittable) = current_jittable {
                let group = std::mem::take(&mut current_group);
                if was_jittable {
                    // Use no_cache build for unified comb safety
                    if group.len() <= jit_chunk_size() {
                        match cranelift::build_binary_no_cache(context, group.clone()) {
                            Some(func) => blocks.push(ProtoStatementBlock::Compiled(func)),
                            None => blocks.push(ProtoStatementBlock::Interpreted(group)),
                        }
                    } else {
                        for chunk in group.chunks(jit_chunk_size()) {
                            let chunk = chunk.to_vec();
                            match cranelift::build_binary_no_cache(context, chunk.clone()) {
                                Some(func) => blocks.push(ProtoStatementBlock::Compiled(func)),
                                None => blocks.push(ProtoStatementBlock::Interpreted(chunk)),
                            }
                        }
                    }
                } else {
                    blocks.push(ProtoStatementBlock::Interpreted(group));
                }
            }
            current_jittable = Some(jittable);
            current_group.push(stmt);
        }
    }

    if let Some(was_jittable) = current_jittable {
        if was_jittable {
            if current_group.len() <= jit_chunk_size() {
                match cranelift::build_binary_no_cache(context, current_group.clone()) {
                    Some(func) => blocks.push(ProtoStatementBlock::Compiled(func)),
                    None => blocks.push(ProtoStatementBlock::Interpreted(current_group)),
                }
            } else {
                for chunk in current_group.chunks(jit_chunk_size()) {
                    let chunk = chunk.to_vec();
                    match cranelift::build_binary_no_cache(context, chunk.clone()) {
                        Some(func) => blocks.push(ProtoStatementBlock::Compiled(func)),
                        None => blocks.push(ProtoStatementBlock::Interpreted(chunk)),
                    }
                }
            }
        } else {
            blocks.push(ProtoStatementBlock::Interpreted(current_group));
        }
    }

    ProtoStatements(blocks)
}

pub(crate) fn analyze_dependency(
    statements: Vec<ProtoStatement>,
) -> Result<Vec<ProtoStatement>, SimulatorError> {
    #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
    enum Node {
        Var(VarOffset),
        Statement(usize),
    }

    let mut table = HashMap::default();
    for (i, x) in statements.into_iter().enumerate() {
        table.insert(i, x);
    }

    // Helper: build DAG and attempt stable topological sort (Kahn's algorithm).
    // Returns Ok(sorted) on success, Err(failed_id) on cycle.
    // Uses FIFO queue initialized in source order to preserve source ordering
    // for statements that have no explicit dependency between them.
    let try_topo_sort =
        |table: &HashMap<usize, ProtoStatement>| -> Result<Vec<ProtoStatement>, usize> {
            let mut dag = Dag::<Node, ()>::new();
            let mut dag_nodes: HashMap<Node, _> = HashMap::default();

            let mut sorted_keys: Vec<usize> = table.keys().cloned().collect();
            sorted_keys.sort();

            let mut node_to_stmt: HashMap<daggy::NodeIndex, usize> = HashMap::default();

            for id in &sorted_keys {
                let x = &table[id];
                let mut inputs = vec![];
                let mut outputs = vec![];
                x.gather_variable_offsets(&mut inputs, &mut outputs);
                let stmt_node = Node::Statement(*id);
                let stmt = dag.add_node(stmt_node);
                dag_nodes.insert(stmt_node, stmt);
                node_to_stmt.insert(stmt, *id);

                let output_set: HashSet<VarOffset> = outputs.iter().cloned().collect();
                let mut ok = true;
                for var_key in inputs {
                    if output_set.contains(&var_key) {
                        continue;
                    }
                    let var_node = Node::Var(var_key);
                    let var = *dag_nodes
                        .entry(var_node)
                        .or_insert_with(|| dag.add_node(var_node));
                    if dag.add_edge(var, stmt, ()).is_err() {
                        ok = false;
                        break;
                    }
                }
                if !ok {
                    return Err(*id);
                }
                for var_key in outputs {
                    let var_node = Node::Var(var_key);
                    let var = *dag_nodes
                        .entry(var_node)
                        .or_insert_with(|| dag.add_node(var_node));
                    if dag.add_edge(stmt, var, ()).is_err() {
                        ok = false;
                        break;
                    }
                }
                if !ok {
                    return Err(*id);
                }
            }

            let graph = dag.graph();
            let node_count = graph.node_count();
            let mut in_degree: HashMap<daggy::NodeIndex, usize> = HashMap::default();
            for idx in graph.node_indices() {
                in_degree.insert(idx, 0);
            }
            for edge in graph.edge_indices() {
                if let Some((_src, tgt)) = graph.edge_endpoints(edge) {
                    *in_degree.entry(tgt).or_insert(0) += 1;
                }
            }

            let mut queue: VecDeque<daggy::NodeIndex> = VecDeque::new();
            let mut zero_nodes: Vec<daggy::NodeIndex> = in_degree
                .iter()
                .filter(|&(_, &deg)| deg == 0)
                .map(|(&idx, _)| idx)
                .collect();
            zero_nodes.sort_by_key(|&idx| node_to_stmt.get(&idx).copied().unwrap_or(usize::MAX));
            for idx in zero_nodes {
                queue.push_back(idx);
            }

            let mut ret = vec![];
            let mut t = table.clone();
            let mut visited = 0;
            while let Some(idx) = queue.pop_front() {
                visited += 1;
                if let Node::Statement(x) = graph[idx]
                    && let Some(s) = t.remove(&x)
                {
                    ret.push(s);
                }
                let mut successors: Vec<daggy::NodeIndex> =
                    graph.neighbors_directed(idx, Outgoing).collect();
                successors.sort_by_key(|&s| node_to_stmt.get(&s).copied().unwrap_or(usize::MAX));
                for succ in successors {
                    let deg = in_degree.get_mut(&succ).unwrap();
                    *deg -= 1;
                    if *deg == 0 {
                        queue.push_back(succ);
                    }
                }
            }

            if visited != node_count {
                return Err(sorted_keys[0]);
            }

            Ok(ret)
        };

    // Phase 1: Try with CompiledBlocks as atomic nodes.
    if let Ok(sorted) = try_topo_sort(&table) {
        return Ok(sorted);
    }

    // Phase 2: Expand CompiledBlocks and SequentialBlocks and retry.
    // Rebuild the table with fresh sequential IDs so expanded sub-statements
    // keep their parent's position; Phase 3's fallback sorts by ID and relies
    // on that ordering for `let x = expr` vs `always_comb { x = expr; }` to
    // produce equivalent schedules when the block participates in a cycle.
    let has_expandable = table.values().any(|x| {
        matches!(x, ProtoStatement::CompiledBlock(cb) if !cb.original_stmts.is_empty())
            || matches!(x, ProtoStatement::SequentialBlock(_))
    });

    if has_expandable {
        let mut sorted_keys: Vec<usize> = table.keys().cloned().collect();
        sorted_keys.sort();

        let mut new_table: HashMap<usize, ProtoStatement> = HashMap::default();
        let mut new_id = 0usize;
        for key in sorted_keys {
            let stmt = table.remove(&key).unwrap();
            match stmt {
                ProtoStatement::CompiledBlock(cb) if !cb.original_stmts.is_empty() => {
                    for sub in cb.original_stmts {
                        new_table.insert(new_id, sub);
                        new_id += 1;
                    }
                }
                ProtoStatement::SequentialBlock(body) => {
                    for sub in body {
                        new_table.insert(new_id, sub);
                        new_id += 1;
                    }
                }
                other => {
                    new_table.insert(new_id, other);
                    new_id += 1;
                }
            }
        }
        table = new_table;

        if let Ok(sorted) = try_topo_sort(&table) {
            return Ok(sorted);
        }
    }

    // Phase 3: Check for genuine combinational loop vs false positive
    // from non-expandable CompiledBlocks (shared JIT cache).
    let has_non_expandable_cb = table
        .values()
        .any(|x| matches!(x, ProtoStatement::CompiledBlock(cb) if cb.original_stmts.is_empty()));
    let has_any_cb = table
        .values()
        .any(|x| matches!(x, ProtoStatement::CompiledBlock(_)));

    if !has_any_cb || !has_non_expandable_cb {
        // DAG-based sort failed (false cycle from inlined function bodies).
        // Fall back to direct statement-level sort.
        let mut sorted_keys: Vec<usize> = table.keys().cloned().collect();
        sorted_keys.sort();
        let stmts: Vec<ProtoStatement> = sorted_keys.iter().map(|k| table[k].clone()).collect();
        let sorted = stable_topo_sort(stmts);
        // Verify no genuine combinational loop remains.
        let n = sorted.len();
        let mut s_inputs: Vec<Vec<VarOffset>> = Vec::with_capacity(n);
        let mut s_outputs: Vec<Vec<VarOffset>> = Vec::with_capacity(n);
        for s in &sorted {
            let mut ins = vec![];
            let mut outs = vec![];
            s.gather_variable_offsets(&mut ins, &mut outs);
            s_inputs.push(ins);
            s_outputs.push(outs);
        }
        let mut w: HashMap<VarOffset, Vec<usize>> = HashMap::default();
        for (i, outs) in s_outputs.iter().enumerate() {
            for &key in outs {
                w.entry(key).or_default().push(i);
            }
        }
        let mut a: Vec<HashSet<usize>> = vec![HashSet::default(); n];
        let mut deg: Vec<usize> = vec![0; n];
        for (ri, ins) in s_inputs.iter().enumerate() {
            for key in ins {
                if let Some(wis) = w.get(key) {
                    if wis.len() == 1 {
                        let wi = wis[0];
                        if wi != ri && a[wi].insert(ri) {
                            deg[ri] += 1;
                        }
                    } else if let Some(&wi) = wis.iter().rev().find(|&&w| w < ri)
                        && a[wi].insert(ri)
                    {
                        deg[ri] += 1;
                    }
                }
            }
        }
        let mut q: VecDeque<usize> = VecDeque::new();
        for (i, &d) in deg.iter().enumerate() {
            if d == 0 {
                q.push_back(i);
            }
        }
        let mut cnt = 0;
        while let Some(idx) = q.pop_front() {
            cnt += 1;
            for &succ in &a[idx] {
                deg[succ] -= 1;
                if deg[succ] == 0 {
                    q.push_back(succ);
                }
            }
        }
        if cnt == n {
            return Ok(sorted);
        }
        // Collect tokens from statements involved in the cycle (deg > 0).
        let mut tokens: Vec<_> = deg
            .iter()
            .enumerate()
            .filter(|(_, d)| **d > 0)
            .filter_map(|(i, _)| sorted[i].token())
            .filter(|t| *t != Default::default())
            .collect();
        let trigger = tokens.pop().unwrap_or_default();
        return Err(SimulatorError::combinational_loop(&trigger, &tokens));
    }

    // Relaxed ordering: skip edges that would create cycles when at least
    // one endpoint is a non-expandable CompiledBlock.
    // NOTE: With original_stmts now stored in shared JIT cache, all CBs
    // should be expandable. This path should be unreachable in practice.
    log::warn!(
        "analyze_dependency: falling back to relaxed ordering for {} stmts with non-expandable CompiledBlocks",
        table.len()
    );
    let mut dag_relaxed = Dag::<Node, ()>::new();
    let mut dag_nodes_relaxed: HashMap<Node, _> = HashMap::default();
    let cb_ids: HashSet<usize> = table
        .iter()
        .filter_map(|(id, x)| {
            if matches!(x, ProtoStatement::CompiledBlock(_)) {
                Some(*id)
            } else {
                None
            }
        })
        .collect();

    let mut sorted_keys: Vec<usize> = table.keys().cloned().collect();
    sorted_keys.sort();
    for id in &sorted_keys {
        let x = &table[id];
        let mut inputs = vec![];
        let mut outputs = vec![];
        x.gather_variable_offsets(&mut inputs, &mut outputs);
        let stmt_node = Node::Statement(*id);
        let stmt = dag_relaxed.add_node(stmt_node);
        dag_nodes_relaxed.insert(stmt_node, stmt);

        let output_set: HashSet<VarOffset> = outputs.iter().cloned().collect();
        for var_key in &inputs {
            if output_set.contains(var_key) {
                continue;
            }
            let var_node = Node::Var(*var_key);
            let var = *dag_nodes_relaxed
                .entry(var_node)
                .or_insert_with(|| dag_relaxed.add_node(var_node));
            if dag_relaxed.add_edge(var, stmt, ()).is_err() {
                if cb_ids.contains(id) {
                    continue;
                }
                let written_by_cb = table.iter().any(|(oid, ox)| {
                    cb_ids.contains(oid) && {
                        let mut o_outs = vec![];
                        let mut o_ins = vec![];
                        ox.gather_variable_offsets(&mut o_ins, &mut o_outs);
                        o_outs.contains(var_key)
                    }
                });
                if written_by_cb {
                    continue;
                }
            }
        }
        for var_key in &outputs {
            let var_node = Node::Var(*var_key);
            let var = *dag_nodes_relaxed
                .entry(var_node)
                .or_insert_with(|| dag_relaxed.add_node(var_node));
            if dag_relaxed.add_edge(stmt, var, ()).is_err() {
                if cb_ids.contains(id) {
                    continue;
                }
                let read_by_cb = table.iter().any(|(oid, ox)| {
                    cb_ids.contains(oid) && {
                        let mut o_outs = vec![];
                        let mut o_ins = vec![];
                        ox.gather_variable_offsets(&mut o_ins, &mut o_outs);
                        o_ins.contains(var_key)
                    }
                });
                if read_by_cb {
                    continue;
                }
            }
        }
    }

    let nodes = algo::toposort(dag_relaxed.graph(), None).unwrap();
    let mut ret = vec![];
    for i in nodes {
        if let Node::Statement(x) = dag_relaxed[i]
            && let Some(stmt) = table.remove(&x)
        {
            ret.push(stmt);
        }
    }
    Ok(ret)
}

/// Compute the number of eval_comb passes required for convergence.
///
/// After topological sorting, some dependency edges may be "backward"
/// (a statement reads a variable written by a later statement in the
/// sorted order). Each backward edge requires an additional eval pass
/// to propagate the correct value. The required number of passes is
/// the longest chain of backward edges + 1.
///
/// Since backward edges always point from higher positions to lower
/// positions, they form a DAG. A single reverse scan computes the
/// longest chain in O(N) time.
/// Bit range for a partial comb assignment. `None` = full-width write/read.
/// Pair is (high_bit_inclusive, low_bit_inclusive) matching Veryl's
/// `Assign.select` convention. Overlap: two ranges overlap if their
/// bit intervals intersect.
type BitRange = Option<(usize, usize)>;

fn ranges_overlap(a: BitRange, b: BitRange) -> bool {
    match (a, b) {
        (None, _) | (_, None) => true,
        (Some((a_hi, a_lo)), Some((b_hi, b_lo))) => a_lo <= b_hi && b_lo <= a_hi,
    }
}

/// Collect (offset, bit_range) outputs for bit-aware SCC analysis.
/// Only captures writes that are precisely bit-ranged (via Assign.select);
/// everything else falls back to full-width (None).
fn gather_bit_aware_outputs(stmt: &ProtoStatement, out: &mut Vec<(VarOffset, BitRange)>) {
    match stmt {
        ProtoStatement::Assign(x) => out.push((x.dst, x.select)),
        ProtoStatement::AssignDynamic(x) => {
            out.push((x.dst_base, None));
            if x.dst_num_elements > 1 {
                let last = VarOffset::new(
                    x.dst_base.is_ff(),
                    x.dst_base.raw() + x.dst_stride * (x.dst_num_elements as isize - 1),
                );
                out.push((last, None));
            }
        }
        ProtoStatement::If(x) => {
            for s in &x.true_side {
                gather_bit_aware_outputs(s, out);
            }
            for s in &x.false_side {
                gather_bit_aware_outputs(s, out);
            }
        }
        ProtoStatement::For(x) => {
            for s in &x.body {
                gather_bit_aware_outputs(s, out);
            }
        }
        ProtoStatement::SequentialBlock(body) => {
            for s in body {
                gather_bit_aware_outputs(s, out);
            }
        }
        ProtoStatement::CompiledBlock(x) => {
            if !x.original_stmts.is_empty() {
                for s in &x.original_stmts {
                    gather_bit_aware_outputs(s, out);
                }
            } else {
                for &off in &x.output_offsets {
                    if !off.is_ff() {
                        out.push((VarOffset::Comb(off.raw()), None));
                    }
                }
            }
        }
        _ => {}
    }
}

/// Diagnostic: compute strongly-connected components of the stmt-level
/// dataflow graph (stmt A → stmt B when A writes a variable B reads).
/// Returns (num_nontrivial_sccs, max_scc_size, total_stmts_in_sccs).
/// Enabled by VERYL_SCC_DIAG=1.
///
/// When VERYL_SCC_NARROW=1, uses the conservative base+last array
/// dependency encoding so that cycles formed only by array-element
/// overlap are filtered out — what remains is scalar comb cycles
/// that would be flagged by a logic synthesis tool.
///
/// When VERYL_SCC_BITAWARE=1, treats partial-width writes (via
/// Assign.select bit ranges) as independent edges: a write to x[7:4]
/// does not create an edge to readers of x[3:0].  This eliminates
/// SCCs formed only by bit-lane overlap in the VarOffset-level IR.
fn compute_scc_stats(sorted: &[ProtoStatement]) -> (usize, usize, usize) {
    use daggy::petgraph::Graph;
    use daggy::petgraph::algo::tarjan_scc;

    let n = sorted.len();
    if n == 0 {
        return (0, 0, 0);
    }

    // Gather per-stmt I/O. Expanded by default (captures per-element
    // array deps); narrow mode uses base+last (what synthesis tools see).
    let narrow = std::env::var("VERYL_SCC_NARROW").is_ok();
    let bitaware = std::env::var("VERYL_SCC_BITAWARE").is_ok();
    let mut stmt_inputs: Vec<Vec<VarOffset>> = Vec::with_capacity(n);
    let mut stmt_outputs: Vec<Vec<VarOffset>> = Vec::with_capacity(n);
    let mut stmt_output_bits: Vec<Vec<(VarOffset, BitRange)>> = Vec::with_capacity(n);
    for s in sorted {
        let mut ins = vec![];
        let mut outs = vec![];
        if narrow {
            s.gather_variable_offsets(&mut ins, &mut outs);
        } else {
            s.gather_variable_offsets_expanded(&mut ins, &mut outs);
        }
        stmt_inputs.push(ins);
        stmt_outputs.push(outs);
        if bitaware {
            let mut bit_outs = vec![];
            gather_bit_aware_outputs(s, &mut bit_outs);
            stmt_output_bits.push(bit_outs);
        } else {
            stmt_output_bits.push(vec![]);
        }
    }

    // var → list of (writer stmt index, bit range for bit-aware mode).
    // In non-bitaware mode, bit_range is always None and overlap is trivial.
    let mut writers: HashMap<VarOffset, Vec<(usize, BitRange)>> = HashMap::default();
    if bitaware {
        for (i, outs) in stmt_output_bits.iter().enumerate() {
            for &(off, br) in outs {
                if off.is_ff() {
                    continue;
                }
                writers.entry(off).or_default().push((i, br));
            }
        }
    } else {
        for (i, outs) in stmt_outputs.iter().enumerate() {
            for &off in outs {
                if off.is_ff() {
                    continue;
                }
                writers.entry(off).or_default().push((i, None));
            }
        }
    }

    let mut graph: Graph<usize, ()> = Graph::new();
    let nodes: Vec<_> = (0..n).map(|i| graph.add_node(i)).collect();
    let mut edge_set: HashSet<(usize, usize)> = HashSet::default();
    // For bit-aware mode, we need to know the reader's bit range for this
    // offset. Currently ProtoExpression::Variable reads don't expose
    // per-field select in gather_variable_offsets, so we conservatively
    // treat reader ranges as None (= full width).  This still filters
    // out false cycles that arise from multiple writers on non-overlapping
    // bit slices, which is the common IR artifact.
    for (reader, ins) in stmt_inputs.iter().enumerate() {
        for &off in ins {
            if off.is_ff() {
                continue;
            }
            if let Some(ws) = writers.get(&off) {
                for &(w, wbr) in ws {
                    if w == reader {
                        continue;
                    }
                    if bitaware && !ranges_overlap(wbr, None) {
                        // Reader range is None (full-width) so this should
                        // never trigger, but kept for structural clarity.
                        continue;
                    }
                    if edge_set.insert((w, reader)) {
                        graph.add_edge(nodes[w], nodes[reader], ());
                    }
                }
            }
        }
    }

    let sccs = tarjan_scc(&graph);
    let mut nontrivial = 0usize;
    let mut max_size = 0usize;
    let mut total = 0usize;
    let mut size_hist: Vec<usize> = Vec::new();
    for scc in &sccs {
        if scc.len() > 1 {
            nontrivial += 1;
            total += scc.len();
            if scc.len() > max_size {
                max_size = scc.len();
            }
            size_hist.push(scc.len());
        }
    }
    size_hist.sort_unstable();
    size_hist.reverse();
    if nontrivial > 0 && std::env::var("VERYL_SCC_DIAG").is_ok() {
        let top: Vec<String> = size_hist.iter().take(10).map(|s| s.to_string()).collect();
        log::info!(
            "SCC stats: {} nontrivial SCCs, max={}, total_stmts_in_SCCs={}, top sizes=[{}]",
            nontrivial,
            max_size,
            total,
            top.join(", ")
        );
        // Position ranges of the largest SCCs to verify contiguity.
        let mut sccs_sorted = sccs.clone();
        sccs_sorted.sort_by_key(|scc| std::cmp::Reverse(scc.len()));
        for (i, scc) in sccs_sorted.iter().take(5).enumerate() {
            if scc.len() <= 1 {
                break;
            }
            let mut positions: Vec<usize> = scc.iter().map(|&idx| idx.index()).collect();
            positions.sort_unstable();
            let min_pos = positions[0];
            let max_pos = positions[positions.len() - 1];
            let range_span = max_pos - min_pos + 1;
            let density = scc.len() as f64 / range_span as f64;
            log::info!(
                "  SCC[{}]: size={}, position range=[{}..{}], span={}, density={:.2}",
                i,
                scc.len(),
                min_pos,
                max_pos,
                range_span,
                density
            );
        }

        // Count unique comb-output offsets written by the SCC stmts.
        // This tells us how narrow a snapshot/compare scope for
        // SCC-only convergence would be.
        let mut all_scc_outs: HashSet<VarOffset> = HashSet::default();
        for scc in &sccs {
            if scc.len() > 1 {
                for node in scc {
                    let idx = node.index();
                    for &off in &stmt_outputs[idx] {
                        if !off.is_ff() {
                            all_scc_outs.insert(off);
                        }
                    }
                }
            }
        }
        log::info!(
            "SCC comb outputs: {} unique offsets ({} stmts in SCCs)",
            all_scc_outs.len(),
            total
        );

        // Kind histogram + in/out offset histogram for the largest SCC.
        let largest = sccs_sorted.first().filter(|s| s.len() > 1);
        if let Some(scc) = largest {
            let mut kind_hist: HashMap<&'static str, usize> = HashMap::default();
            let mut out_counts: HashMap<VarOffset, usize> = HashMap::default();
            let mut in_counts: HashMap<VarOffset, usize> = HashMap::default();
            let mut source_hist: HashMap<String, usize> = HashMap::default();
            let mut line_samples: Vec<(String, u32)> = Vec::new();
            for node in scc {
                let idx = node.index();
                if let ProtoStatement::Assign(x) = &sorted[idx] {
                    let src = x.token.beg.source.to_string();
                    let line = x.token.beg.line;
                    *source_hist.entry(src.clone()).or_insert(0) += 1;
                    line_samples.push((src, line));
                }
            }
            let mut sources: Vec<_> = source_hist.into_iter().collect();
            sources.sort_by_key(|(_, c)| std::cmp::Reverse(*c));
            let src_str: Vec<String> = sources
                .iter()
                .take(15)
                .map(|(s, c)| format!("{}={}", s, c))
                .collect();
            log::info!("SCC[0] source file distribution: {}", src_str.join(", "));
            line_samples.sort();
            let uniq: Vec<String> = line_samples
                .iter()
                .take(10)
                .map(|(s, l)| format!("{}:{}", s, l))
                .collect();
            log::info!("SCC[0] first 10 (src:line): {:?}", uniq);

            for node in scc {
                let idx = node.index();
                let kind = match &sorted[idx] {
                    ProtoStatement::Assign(_) => "Assign",
                    ProtoStatement::AssignDynamic(_) => "AssignDynamic",
                    ProtoStatement::If(_) => "If",
                    ProtoStatement::For(_) => "For",
                    ProtoStatement::Break => "Break",
                    ProtoStatement::SystemFunctionCall(_) => "SystemFunctionCall",
                    ProtoStatement::CompiledBlock(_) => "CompiledBlock",
                    ProtoStatement::SequentialBlock(_) => "SequentialBlock",
                    ProtoStatement::TbMethodCall { .. } => "TbMethodCall",
                };
                *kind_hist.entry(kind).or_insert(0) += 1;
                for &off in &stmt_outputs[idx] {
                    if !off.is_ff() {
                        *out_counts.entry(off).or_insert(0) += 1;
                    }
                }
                for &off in &stmt_inputs[idx] {
                    if !off.is_ff() {
                        *in_counts.entry(off).or_insert(0) += 1;
                    }
                }
            }
            let mut kinds: Vec<_> = kind_hist.into_iter().collect();
            kinds.sort_by_key(|(_, c)| std::cmp::Reverse(*c));
            let kstr: Vec<String> = kinds.iter().map(|(k, c)| format!("{}={}", k, c)).collect();
            log::info!("SCC[0] kind histogram: {}", kstr.join(", "));

            // Find offsets that are BOTH written and read many times within
            // the SCC — these are the "pivots" forming the cycles.
            let mut pivots: Vec<(VarOffset, usize, usize)> = out_counts
                .iter()
                .filter_map(|(&off, &wc)| in_counts.get(&off).map(|&rc| (off, wc, rc)))
                .collect();
            pivots.sort_by_key(|(_, wc, rc)| std::cmp::Reverse(wc * rc));
            log::info!("SCC[0] top pivots (offset, writers, readers):");
            for (off, wc, rc) in pivots.iter().take(10) {
                // Collect the bit ranges of writers to this offset within the SCC.
                let mut bit_writers: Vec<BitRange> = Vec::new();
                for node in scc {
                    let idx = node.index();
                    let mut outs: Vec<(VarOffset, BitRange)> = Vec::new();
                    gather_bit_aware_outputs(&sorted[idx], &mut outs);
                    for (w_off, br) in &outs {
                        if w_off == off {
                            bit_writers.push(*br);
                        }
                    }
                }
                let full_count = bit_writers.iter().filter(|b| b.is_none()).count();
                let partial_count = bit_writers.len() - full_count;
                let ranges: Vec<String> = bit_writers
                    .iter()
                    .filter_map(|b| b.map(|(hi, lo)| format!("[{}:{}]", hi, lo)))
                    .take(8)
                    .collect();
                log::info!(
                    "    {:?}: {} writers ({} full, {} partial), {} readers; partial ranges: {:?}",
                    off,
                    wc,
                    full_count,
                    partial_count,
                    rc,
                    ranges
                );
            }
        }
    }
    (nontrivial, max_size, total)
}

/// Build a map from comb VarOffset → human-readable variable path.
/// Walks ModuleVariableMeta recursively and records the offset of each
/// VariableElement's `current` slot together with the module hierarchy
/// prefix.
fn build_offset_path_map(meta: &ModuleVariableMeta) -> HashMap<VarOffset, String> {
    let mut map = HashMap::default();
    fn walk(meta: &ModuleVariableMeta, prefix: &str, out: &mut HashMap<VarOffset, String>) {
        let name = meta.name.to_string();
        let mod_prefix = if prefix.is_empty() {
            name.clone()
        } else {
            format!("{}.{}", prefix, name)
        };
        for var_meta in meta.variable_meta.values() {
            let var_name = var_meta
                .path
                .0
                .iter()
                .map(|v| v.to_string())
                .collect::<Vec<_>>()
                .join(".");
            for (i, element) in var_meta.elements.iter().enumerate() {
                let display = if var_meta.elements.len() > 1 {
                    format!("{}.{}[{}]", mod_prefix, var_name, i)
                } else {
                    format!("{}.{}", mod_prefix, var_name)
                };
                out.insert(element.current, display);
            }
        }
        for child in &meta.children {
            walk(child, &mod_prefix, out);
        }
    }
    walk(meta, "", &mut map);
    map
}

/// Diagnostic: trace a concrete cycle in the largest SCC of the comb
/// dataflow graph and print it as a sequence of variable names.
/// Helps pinpoint the exact combinational loop in source.
fn trace_scc_cycles(sorted: &[ProtoStatement], meta: &ModuleVariableMeta) {
    use daggy::petgraph::Graph;
    use daggy::petgraph::algo::tarjan_scc;

    let n = sorted.len();
    if n == 0 {
        return;
    }

    let path_map = build_offset_path_map(meta);

    // Build stmt-level dataflow graph (same as compute_scc_stats).
    let mut stmt_inputs: Vec<Vec<VarOffset>> = Vec::with_capacity(n);
    let mut stmt_outputs: Vec<Vec<VarOffset>> = Vec::with_capacity(n);
    for s in sorted {
        let mut ins = vec![];
        let mut outs = vec![];
        s.gather_variable_offsets(&mut ins, &mut outs);
        stmt_inputs.push(ins);
        stmt_outputs.push(outs);
    }

    let mut writers: HashMap<VarOffset, Vec<usize>> = HashMap::default();
    for (i, outs) in stmt_outputs.iter().enumerate() {
        for &off in outs {
            if off.is_ff() {
                continue;
            }
            writers.entry(off).or_default().push(i);
        }
    }

    // adj[reader] = list of writer-stmt indices whose outputs the reader reads.
    // (Edge direction in trace: reader ← writer, but for cycle finding we
    // walk writer → reader.)
    let mut adj: Vec<Vec<(usize, VarOffset)>> = vec![vec![]; n];
    let mut graph: Graph<usize, ()> = Graph::new();
    let nodes: Vec<_> = (0..n).map(|i| graph.add_node(i)).collect();
    let mut edge_set: HashSet<(usize, usize)> = HashSet::default();
    for (reader, ins) in stmt_inputs.iter().enumerate() {
        for &off in ins {
            if off.is_ff() {
                continue;
            }
            if let Some(ws) = writers.get(&off) {
                for &w in ws {
                    if w != reader && edge_set.insert((w, reader)) {
                        graph.add_edge(nodes[w], nodes[reader], ());
                        adj[w].push((reader, off));
                    }
                }
            }
        }
    }

    let sccs = tarjan_scc(&graph);
    let mut sccs_sorted = sccs.clone();
    sccs_sorted.sort_by_key(|s| std::cmp::Reverse(s.len()));

    for (scc_idx, scc) in sccs_sorted.iter().enumerate() {
        if scc.len() <= 1 {
            break;
        }
        let member_set: HashSet<usize> = scc.iter().map(|n| n.index()).collect();

        // Find a concrete cycle: BFS from the first member, through
        // edges confined to the SCC, find shortest path back to start.
        let start = scc[0].index();
        let mut parent: HashMap<usize, (usize, VarOffset)> = HashMap::default();
        let mut queue: std::collections::VecDeque<usize> = Default::default();
        queue.push_back(start);
        let mut found_back_to_start = None;
        while let Some(u) = queue.pop_front() {
            for &(v, off) in &adj[u] {
                if !member_set.contains(&v) {
                    continue;
                }
                if v == start {
                    // Found cycle: start → ... → u → (off) → start
                    found_back_to_start = Some((u, off));
                    break;
                }
                if let std::collections::hash_map::Entry::Vacant(e) = parent.entry(v) {
                    e.insert((u, off));
                    queue.push_back(v);
                }
            }
            if found_back_to_start.is_some() {
                break;
            }
        }

        log::info!("SCC[{}] cycle trace (size={}):", scc_idx, scc.len());
        if let Some((last, last_off)) = found_back_to_start {
            // Rebuild path from start → last.
            let mut path: Vec<(usize, VarOffset)> = vec![(last, last_off)];
            let mut cur = last;
            while cur != start {
                if let Some(&(p, off)) = parent.get(&cur) {
                    path.push((p, off));
                    cur = p;
                } else {
                    break;
                }
            }
            path.reverse();
            let describe_offset = |off: VarOffset| -> String {
                path_map
                    .get(&off)
                    .cloned()
                    .unwrap_or_else(|| format!("{:?}", off))
            };
            let describe_stmt = |idx: usize| -> String {
                let (tok_beg, kind) = match &sorted[idx] {
                    ProtoStatement::Assign(x) => (Some(x.token.beg), "Assign"),
                    _ => (
                        None,
                        match &sorted[idx] {
                            ProtoStatement::If(_) => "If",
                            ProtoStatement::AssignDynamic(_) => "AssignDynamic",
                            ProtoStatement::For(_) => "For",
                            ProtoStatement::SequentialBlock(_) => "SeqBlock",
                            ProtoStatement::CompiledBlock(_) => "CompiledBlock",
                            ProtoStatement::SystemFunctionCall(_) => "SysFn",
                            ProtoStatement::TbMethodCall { .. } => "TbCall",
                            ProtoStatement::Break => "Break",
                            _ => "?",
                        },
                    ),
                };
                if let Some(tok) = tok_beg {
                    let src = tok.source.to_string();
                    let file = src.rsplit('/').next().unwrap_or(&src);
                    format!("[{}] {}:{}", kind, file, tok.line)
                } else {
                    format!("[{}] #{}", kind, idx)
                }
            };
            log::info!("  start at stmt {} ({})", start, describe_stmt(start));
            for (stmt_idx, via_off) in &path {
                log::info!(
                    "    ── writes {} ──→ stmt {} ({})",
                    describe_offset(*via_off),
                    stmt_idx,
                    describe_stmt(*stmt_idx)
                );
            }
            log::info!(
                "    ── writes {} ──→ back to start",
                describe_offset(last_off)
            );
        } else {
            log::info!("  (no cycle found from start; graph error?)");
        }

        // Also list the top pivot variables by name.
        let mut out_counts: HashMap<VarOffset, usize> = HashMap::default();
        let mut in_counts: HashMap<VarOffset, usize> = HashMap::default();
        for &idx in &member_set {
            for &off in &stmt_outputs[idx] {
                if !off.is_ff() {
                    *out_counts.entry(off).or_insert(0) += 1;
                }
            }
            for &off in &stmt_inputs[idx] {
                if !off.is_ff() {
                    *in_counts.entry(off).or_insert(0) += 1;
                }
            }
        }
        let mut pivots: Vec<(VarOffset, usize, usize)> = out_counts
            .iter()
            .filter_map(|(&off, &wc)| in_counts.get(&off).map(|&rc| (off, wc, rc)))
            .collect();
        pivots.sort_by_key(|(_, wc, rc)| std::cmp::Reverse(wc * rc));
        log::info!("  top pivot variables (by writers × readers):");
        for (off, wc, rc) in pivots.iter().take(10) {
            let name = path_map
                .get(off)
                .cloned()
                .unwrap_or_else(|| format!("{:?}", off));
            log::info!("    {}: {} writers, {} readers", name, wc, rc);
        }

        if scc_idx >= 3 {
            break; // Print at most a few SCCs.
        }
    }
}

fn compute_required_passes(sorted: &[ProtoStatement]) -> usize {
    let n = sorted.len();
    if n == 0 {
        return 1;
    }

    if std::env::var("VERYL_SCC_DIAG").is_ok() {
        compute_scc_stats(sorted);
    }

    // For each comb variable, record the position of its last writer.
    let mut var_last_writer: HashMap<VarOffset, usize> = HashMap::default();
    for (pos, stmt) in sorted.iter().enumerate() {
        let mut inputs = vec![];
        let mut outputs = vec![];
        stmt.gather_variable_offsets(&mut inputs, &mut outputs);
        for key in outputs {
            var_last_writer.insert(key, pos);
        }
    }

    // Reverse scan: for each statement, compute the maximum backward
    // chain depth. Because backward edges point from higher to lower
    // positions, delay[writer_pos] is already computed when we visit pos.
    let mut delay = vec![0usize; n];
    for pos in (0..n).rev() {
        let mut inputs = vec![];
        let mut outputs = vec![];
        sorted[pos].gather_variable_offsets(&mut inputs, &mut outputs);
        let output_set: HashSet<VarOffset> = outputs.iter().cloned().collect();

        for key in &inputs {
            if output_set.contains(key) {
                continue; // self-reference within same statement
            }
            if let Some(&writer_pos) = var_last_writer.get(key)
                && writer_pos > pos
            {
                delay[pos] = delay[pos].max(delay[writer_pos] + 1);
            }
        }
    }

    let max_delay = delay.iter().copied().max().unwrap_or(0);
    let passes = max_delay + 1;
    if passes > 1 {
        log::info!(
            "compute_required_passes: {} passes needed ({} stmts, {} backward edge chain depth)",
            passes,
            n,
            max_delay
        );
    }
    // SCC iteration depth is computed only as a diagnostic — `passes`
    // returned above uses DAG depth alone.  Counting backward edges into
    // the pass total would penalise every `settle_comb` call on designs
    // with false SCCs (e.g. multi-driver array writes the IR can't
    // disambiguate), and the regression is severe for large-memory
    // designs where each extra full pass walks every comb byte.
    if std::env::var("VERYL_SCC_DIAG").is_ok() {
        let scc_depth = compute_scc_iteration_depth(sorted);
        log::info!("  (diagnostic) SCC iteration depth: {}", scc_depth);
    }
    passes
}

/// Compute the max backward-edge chain depth inside any non-trivial SCC
/// of the comb dataflow graph. Returns 0 if no non-trivial SCCs exist.
///
/// Intuition: within an SCC, some edges must run "backward" in any topo
/// order (that's what makes it an SCC). The longest chain of such
/// backward edges is how many extra full passes the design needs to
/// settle the cycle.
fn compute_scc_iteration_depth(sorted: &[ProtoStatement]) -> usize {
    use daggy::petgraph::Graph;
    use daggy::petgraph::algo::tarjan_scc;

    let n = sorted.len();
    if n == 0 {
        return 0;
    }

    let mut stmt_inputs: Vec<Vec<VarOffset>> = Vec::with_capacity(n);
    let mut stmt_outputs: Vec<Vec<VarOffset>> = Vec::with_capacity(n);
    for s in sorted {
        let mut ins = vec![];
        let mut outs = vec![];
        s.gather_variable_offsets_expanded(&mut ins, &mut outs);
        stmt_inputs.push(ins);
        stmt_outputs.push(outs);
    }

    // Build stmt-level DAG edges (comb writer → comb reader) and find
    // SCCs.
    let mut writers: HashMap<VarOffset, Vec<usize>> = HashMap::default();
    for (i, outs) in stmt_outputs.iter().enumerate() {
        for &off in outs {
            if !off.is_ff() {
                writers.entry(off).or_default().push(i);
            }
        }
    }

    let mut graph: Graph<usize, ()> = Graph::new();
    let nodes: Vec<_> = (0..n).map(|i| graph.add_node(i)).collect();
    let mut edge_set: HashSet<(usize, usize)> = HashSet::default();
    for (reader, ins) in stmt_inputs.iter().enumerate() {
        for &off in ins {
            if off.is_ff() {
                continue;
            }
            if let Some(ws) = writers.get(&off) {
                for &w in ws {
                    if w != reader && edge_set.insert((w, reader)) {
                        graph.add_edge(nodes[w], nodes[reader], ());
                    }
                }
            }
        }
    }

    let sccs = tarjan_scc(&graph);
    let mut max_depth = 0usize;

    for scc in &sccs {
        if scc.len() <= 1 {
            continue;
        }
        // SCC members and their original positions.
        let member_positions: Vec<usize> = scc.iter().map(|&idx| idx.index()).collect();
        let mut member_set: HashSet<usize> = HashSet::default();
        for &p in &member_positions {
            member_set.insert(p);
        }

        // Within the SCC subgraph (restricted to members and their
        // edges), compute backward-chain depth using the same algorithm
        // as the DAG case. Use original sorted position as the topo
        // order — this is a topo order of the whole graph but may
        // include many "backward" edges inside the SCC (which is
        // expected; that's what iteration resolves).
        let mut sorted_positions = member_positions.clone();
        sorted_positions.sort_unstable();

        // Build a writer map restricted to SCC members.
        let mut scc_writers: HashMap<VarOffset, Vec<usize>> = HashMap::default();
        for &p in &sorted_positions {
            for &off in &stmt_outputs[p] {
                if !off.is_ff() {
                    scc_writers.entry(off).or_default().push(p);
                }
            }
        }

        // Map original position → internal order (0, 1, 2, ...).
        let mut pos_to_ord: HashMap<usize, usize> = HashMap::default();
        for (ord, &p) in sorted_positions.iter().enumerate() {
            pos_to_ord.insert(p, ord);
        }

        let scc_n = sorted_positions.len();
        let mut delay = vec![0usize; scc_n];
        // Reverse scan by internal order.
        for ord in (0..scc_n).rev() {
            let p = sorted_positions[ord];
            let output_set: HashSet<VarOffset> = stmt_outputs[p].iter().cloned().collect();
            for key in &stmt_inputs[p] {
                if output_set.contains(key) {
                    continue;
                }
                if let Some(ws) = scc_writers.get(key) {
                    // A backward edge exists if any writer's internal
                    // order is strictly greater than this stmt's order.
                    for &wp in ws {
                        if wp == p {
                            continue;
                        }
                        if !member_set.contains(&wp) {
                            continue;
                        }
                        if let Some(&wo) = pos_to_ord.get(&wp)
                            && wo > ord
                        {
                            delay[ord] = delay[ord].max(delay[wo] + 1);
                        }
                    }
                }
            }
        }

        // Add 1 for the safety of propagation through the cycle head:
        // the reverse-scan counts "backward edges along longest path"
        // but the cycle head needs one extra iteration for its own
        // stale-input read to settle.  Empirically matches heliodor
        // (measured K_runtime = 4, algo without margin returns 3).
        let scc_max = delay.iter().copied().max().unwrap_or(0) + 1;
        if scc_max > max_depth {
            max_depth = scc_max;
        }
    }

    max_depth
}

/// Compute dependency levels for sorted ProtoStatements and reorder within
/// each level so that CompiledBlocks with the same func pointer are adjacent.
/// This enables batching of same-function JIT calls.
fn reorder_by_level(sorted: Vec<ProtoStatement>) -> Vec<ProtoStatement> {
    // Level = max(var_level[input]) + 1. For CBs, use all offsets
    // (including FF) since gather_variable_offsets filters FF for DAG.
    let mut var_level: HashMap<VarOffset, usize> = HashMap::default();
    let mut levels: Vec<usize> = Vec::with_capacity(sorted.len());

    for stmt in &sorted {
        let mut inputs = vec![];
        let mut outputs = vec![];
        match stmt {
            ProtoStatement::CompiledBlock(x) => {
                if !x.stmt_deps.is_empty() {
                    for (ins, outs) in &x.stmt_deps {
                        inputs.extend_from_slice(ins);
                        outputs.extend_from_slice(outs);
                    }
                } else {
                    inputs.extend_from_slice(&x.input_offsets);
                    outputs.extend_from_slice(&x.output_offsets);
                }
            }
            _ => {
                stmt.gather_variable_offsets(&mut inputs, &mut outputs);
            }
        }

        let level = inputs
            .iter()
            .filter_map(|key| var_level.get(key))
            .copied()
            .max()
            .map(|l| l + 1)
            .unwrap_or(0);

        for key in &outputs {
            let e = var_level.entry(*key).or_insert(0);
            if level > *e {
                *e = level;
            }
        }

        levels.push(level);
    }

    // Group statements by level
    let max_level = levels.iter().copied().max().unwrap_or(0);
    let mut groups: Vec<Vec<ProtoStatement>> = vec![vec![]; max_level + 1];
    for (stmt, level) in sorted.into_iter().zip(levels) {
        groups[level].push(stmt);
    }

    // Within each level, topological sort by actual variable dependencies.
    for group in groups.iter_mut() {
        if group.len() <= 1 {
            continue;
        }
        *group = topo_sort_within_level(std::mem::take(group));
    }

    groups.into_iter().flatten().collect()
}

/// Local topological sort within a single level group.
///
/// Builds RAW dependency edges among the statements in this group and
/// performs a stable Kahn's-algorithm sort.  Statements with no intra-group
/// dependencies retain their original order (stable).  On cycle detection
/// the original order is preserved as a safe fallback.
fn topo_sort_within_level(stmts: Vec<ProtoStatement>) -> Vec<ProtoStatement> {
    let n = stmts.len();

    // Type priority for tie-breaking: CBs before Assigns when unordered.
    let type_priority: Vec<u8> = stmts
        .iter()
        .map(|s| match s {
            ProtoStatement::CompiledBlock(_) => 0,
            ProtoStatement::Assign(_) => 1,
            ProtoStatement::AssignDynamic(_) => 2,
            ProtoStatement::If(_) => 3,
            ProtoStatement::SequentialBlock(_) => 1,
            _ => 4,
        })
        .collect();

    let mut stmt_inputs: Vec<Vec<VarOffset>> = Vec::with_capacity(n);
    let mut stmt_outputs: Vec<Vec<VarOffset>> = Vec::with_capacity(n);
    for s in &stmts {
        let mut ins = vec![];
        let mut outs = vec![];
        s.gather_variable_offsets(&mut ins, &mut outs);
        stmt_inputs.push(ins);
        stmt_outputs.push(outs);
    }

    let mut var_writers: HashMap<VarOffset, Vec<usize>> = HashMap::default();
    for (i, outs) in stmt_outputs.iter().enumerate() {
        for key in outs {
            var_writers.entry(*key).or_default().push(i);
        }
    }

    // RAW edges: writer → reader (skip self-edges).
    let mut adj: Vec<HashSet<usize>> = vec![HashSet::default(); n];
    let mut in_degree = vec![0usize; n];
    for (reader, ins) in stmt_inputs.iter().enumerate() {
        for key in ins {
            if let Some(writers) = var_writers.get(key) {
                for &writer in writers {
                    if writer == reader {
                        continue; // skip self-edge
                    }
                    if adj[writer].insert(reader) {
                        in_degree[reader] += 1;
                    }
                }
            }
        }
    }

    // Kahn's with BTreeSet<(priority, index)> for stable tie-breaking.
    let mut queue: std::collections::BTreeSet<(u8, usize)> = std::collections::BTreeSet::new();
    for i in 0..n {
        if in_degree[i] == 0 {
            queue.insert((type_priority[i], i));
        }
    }

    let mut order: Vec<usize> = Vec::with_capacity(n);
    while let Some(&key) = queue.iter().next() {
        queue.remove(&key);
        let idx = key.1;
        order.push(idx);
        for &next in &adj[idx] {
            in_degree[next] -= 1;
            if in_degree[next] == 0 {
                queue.insert((type_priority[next], next));
            }
        }
    }

    if order.len() != n {
        let mut result = stmts;
        result.sort_by_key(|s| match s {
            ProtoStatement::CompiledBlock(_) => 0,
            ProtoStatement::Assign(_) => 1,
            ProtoStatement::AssignDynamic(_) => 2,
            ProtoStatement::If(_) => 3,
            ProtoStatement::SequentialBlock(_) => 1,
            _ => 4,
        });
        return result;
    }

    let mut indexed: Vec<Option<ProtoStatement>> = stmts.into_iter().map(Some).collect();
    order
        .into_iter()
        .map(|i| indexed[i].take().unwrap())
        .collect()
}

/// Cond-hoist transform.  See call site for rationale.  Walks `stmts`, and for
/// every top-level `If` whose cond is jittable but whose body contains a
/// non-jittable stmt (e.g. `$display`/`$write`), allocates a comb byte and
/// rewrites to `[Assign(temp = cond), If(temp, body)]`.  The Assign joins the
/// JIT chunk; the If stays interpreted but its cond is now a single byte load.
#[cfg(not(target_family = "wasm"))]
fn cond_hoist_transform(stmts: &mut Vec<ProtoStatement>, context: &mut Context) {
    use crate::ir::expression::ExpressionContext;
    use crate::ir::expression::ProtoExpression as PE;
    use crate::ir::native_bytes;
    use crate::ir::statement::{ProtoAssignStatement, ProtoIfStatement};
    use veryl_parser::token_range::TokenRange;
    let verbose = std::env::var("VERYL_COND_HOIST_VERBOSE").ok().as_deref() == Some("1");
    let mut hoisted = 0usize;
    let mut skipped_cond_nonjit = 0usize;
    let mut skipped_body_jit = 0usize;
    let original = std::mem::take(stmts);
    let mut result: Vec<ProtoStatement> = Vec::with_capacity(original.len() * 2);
    for stmt in original {
        match stmt {
            ProtoStatement::If(if_stmt) => {
                let body_jit = if_stmt.true_side.iter().all(|s| s.can_build_binary())
                    && if_stmt.false_side.iter().all(|s| s.can_build_binary());
                let cond_jit = match &if_stmt.cond {
                    Some(c) => c.can_build_binary(),
                    None => false,
                };
                if !cond_jit {
                    skipped_cond_nonjit += 1;
                    result.push(ProtoStatement::If(if_stmt));
                    continue;
                }
                if body_jit {
                    skipped_body_jit += 1;
                    result.push(ProtoStatement::If(if_stmt));
                    continue;
                }
                // Hoist: allocate a comb temp and split into Assign + If.
                let cond_expr = if_stmt.cond.clone().unwrap();
                let nb = native_bytes(1);
                let temp_offset = context.comb_total_bytes as isize;
                context.comb_total_bytes += nb;
                let temp_off = VarOffset::Comb(temp_offset);
                let ctx = ExpressionContext {
                    width: 1,
                    signed: false,
                };
                let assign = ProtoStatement::Assign(ProtoAssignStatement {
                    dst: temp_off,
                    dst_width: 1,
                    select: None,
                    dynamic_select: None,
                    rhs_select: None,
                    expr: cond_expr,
                    dst_ff_current_offset: 0,
                    token: TokenRange::default(),
                });
                let new_cond = PE::Variable {
                    var_offset: temp_off,
                    select: None,
                    dynamic_select: None,
                    width: 1,
                    var_full_width: 1,
                    expr_context: ctx,
                };
                let new_if = ProtoStatement::If(ProtoIfStatement {
                    cond: Some(new_cond),
                    true_side: if_stmt.true_side,
                    false_side: if_stmt.false_side,
                });
                result.push(assign);
                result.push(new_if);
                hoisted += 1;
            }
            other => result.push(other),
        }
    }
    *stmts = result;
    if verbose && hoisted > 0 {
        eprintln!(
            "[CondHoist] hoisted={hoisted} skipped_cond_nonjit={skipped_cond_nonjit} \
             skipped_body_jit={skipped_body_jit}"
        );
    }
}

/// Merge consecutive Binary statements with the same function pointer into BinaryBatch.
fn batch_binary_statements(stmts: Vec<Statement>) -> Vec<Statement> {
    let mut result: Vec<Statement> = Vec::with_capacity(stmts.len());

    for stmt in stmts {
        match stmt {
            Statement::Binary(func, ff, comb) => {
                let func_addr = func as usize;
                match result.last_mut() {
                    Some(Statement::BinaryBatch(batch_func, args))
                        if *batch_func as usize == func_addr =>
                    {
                        args.push((ff, comb));
                    }
                    Some(Statement::Binary(prev_func, prev_ff, prev_comb))
                        if *prev_func as usize == func_addr =>
                    {
                        let prev_ff = *prev_ff;
                        let prev_comb = *prev_comb;
                        let prev_func = *prev_func;
                        *result.last_mut().unwrap() = Statement::BinaryBatch(
                            prev_func,
                            vec![(prev_ff, prev_comb), (ff, comb)],
                        );
                    }
                    _ => {
                        result.push(Statement::Binary(func, ff, comb));
                    }
                }
            }
            other => result.push(other),
        }
    }

    result
}

impl Conv<&air::Module> for ProtoModule {
    fn conv(context: &mut Context, src: &air::Module) -> Result<Self, SimulatorError> {
        let mut analyzer_context = veryl_analyzer::conv::Context::default();
        analyzer_context.variables = src.variables.clone();
        analyzer_context.functions = src.functions.clone();

        let mut ff_table = air::FfTable::default();
        src.gather_ff(&mut analyzer_context, &mut ff_table);
        ff_table.update_is_ff();
        if context.config.disable_ff_opt {
            ff_table.force_all_ff();
        }

        // Comb-to-FF hoist: clone declarations and mutate them — move
        // comb-side `let` writes into the consuming FF block, rebuild
        // the FfTable on the hoisted form so all downstream simulator
        // processing runs against the hoisted IR.
        let mut hoisted_declarations = src.declarations.clone();
        {
            let plans = veryl_analyzer::ir::comb_to_ff_hoist::plan_hoists(
                &hoisted_declarations,
                &ff_table,
                &src.variables,
            );
            veryl_analyzer::ir::comb_to_ff_hoist::apply_hoists(
                &mut hoisted_declarations,
                &plans,
                &src.variables,
            );
            ff_table = air::FfTable::default();
            for (i, x) in hoisted_declarations.iter().enumerate() {
                x.gather_ff(&mut analyzer_context, &mut ff_table, i);
            }
            ff_table.update_is_ff();
            if context.config.disable_ff_opt {
                ff_table.force_all_ff();
            }
        }
        let declarations: &[air::Declaration] = &hoisted_declarations;

        let ff_start = context.ff_total_bytes as isize;
        let comb_start = context.comb_total_bytes as isize;
        let (variable_meta, ff_bytes, comb_bytes) = create_variable_meta(
            &src.variables,
            &ff_table,
            context.config.use_4state,
            ff_start,
            comb_start,
        )
        .unwrap();

        context.ff_total_bytes += ff_bytes;
        context.comb_total_bytes += comb_bytes;

        let scope = ScopeContext {
            variable_meta: variable_meta.clone(),
            analyzer_context,
            ff_table: ff_table.clone(),
        };
        context.scope_contexts.push(scope);

        let mut all_event_statements: HashMap<Event, Vec<ProtoStatement>> = HashMap::default();
        let mut all_comb_statements: Vec<ProtoStatement> = vec![];
        let mut all_post_comb_fns: Vec<ProtoStatement> = vec![];
        let mut all_child_modules: Vec<ModuleVariableMeta> = vec![];

        for decl in declarations {
            let proto_decl: ProtoDeclaration = Conv::conv(context, decl)?;

            for (event, mut stmts) in proto_decl.event_statements {
                all_event_statements
                    .entry(event)
                    .and_modify(|v| v.append(&mut stmts))
                    .or_insert(stmts);
            }
            all_comb_statements.append(&mut proto_decl.comb_statements.clone());
            all_post_comb_fns.extend(proto_decl.post_comb_fns);
            all_child_modules.extend(proto_decl.child_modules);
        }

        context.scope_contexts.pop();

        // Build unified comb list: execution-side only.
        // Merged-JIT children contribute their comb-only CB via `post_comb_fns`;
        // the originals are preserved inside each CB's `original_stmts` and
        // expanded on demand by `analyze_dependency` Phase 2 when fine-grained
        // ordering is needed.  This eliminates the false SCC artifact from
        // keeping both CB and its originals in the parent's `unified` list.
        let unified: Vec<ProtoStatement> = all_comb_statements
            .into_iter()
            .chain(all_post_comb_fns)
            .collect();

        let unified_sorted = analyze_dependency(unified)?;
        // No DCE/inlining: unified list includes internal child comb that would be incorrectly removed.
        let unified_sorted = reorder_by_level(unified_sorted);
        let required_comb_passes = compute_required_passes(&unified_sorted);

        // Invariant: `analyze_dependency` rejects real combinational loops
        // via `combinational_loop` error, so reaching this point means the
        // stmt-level graph is a well-formed DAG.  Any remaining non-trivial
        // SCC in the expanded dataflow view indicates duplicate
        // ProtoStatements in the simulator IR assembly.  We assert SCC == 0
        // in debug builds so any future regression that reintroduces this
        // class of bug surfaces immediately, and expose the count on
        // `Module`/`Ir` for test-local assertion.
        let nontrivial_comb_scc = compute_scc_stats(&unified_sorted).0;
        debug_assert_eq!(
            nontrivial_comb_scc, 0,
            "ProtoModule {:?}: {} nontrivial SCC(s) in unified_sorted. \
             analyze_dependency would have rejected a real combinational loop, \
             so this indicates duplicate ProtoStatements in the simulator IR.",
            src.name, nontrivial_comb_scc,
        );

        #[cfg(not(target_family = "wasm"))]
        let unified_sorted = super::dup_assign_dce::dce_aggressive(unified_sorted);

        // Snapshot unified_sorted before JIT consumes it: the worklist
        // schedule (built below) needs to walk the pre-JIT ProtoStatement
        // list because JIT CompiledBlocks don't expose stmt-level I/O to
        // `gather_variable_offsets`.
        let pre_jit_stmts = unified_sorted.clone();
        let comb_statements = try_jit_no_cache(context, unified_sorted);

        // Cond-hoist transform (disable with VERYL_COND_HOIST_DISABLE=1):
        // For each top-level `if cond { body }` whose body contains a
        // non-jittable stmt (e.g. `$display`/`$write`) but whose cond is
        // jittable, allocate a 1-bit comb temp and rewrite to
        //     temp = cond ? 1 : 0     (joins the JIT chunk)
        //     if temp != 0 { body }   (interp with a cheap byte-load cond)
        // so the per-cycle cond evaluation runs in JIT instead of through
        // the interpreter (Expression::eval + Op::eval_value_binary +
        // read_native_value etc).
        #[cfg(not(target_family = "wasm"))]
        {
            let cond_hoist_disabled =
                std::env::var("VERYL_COND_HOIST_DISABLE").ok().as_deref() == Some("1");
            if !cond_hoist_disabled {
                for (_event, stmts) in all_event_statements.iter_mut() {
                    cond_hoist_transform(stmts, context);
                }
            }
        }

        // Event statements preserve source order (no topological sorting).
        // NBA semantics: reads come from current, writes go to next, then
        // ff_commit copies next → current. Source order must be preserved
        // for sequential writes to the same variable.
        let event_statements: HashMap<Event, ProtoStatements> = all_event_statements
            .into_iter()
            .map(|(event, stmts)| (event, try_jit(context, stmts)))
            .collect();

        let module_variable_meta = ModuleVariableMeta {
            name: src.name,
            variable_meta,
            children: all_child_modules,
        };

        if std::env::var("VERYL_SCC_TRACE").is_ok() {
            trace_scc_cycles(&pre_jit_stmts, &module_variable_meta);
        }

        // Build an IrSchedule whose stmt ids align with the post-JIT
        // comb_statements.  Only build it when the worklist is actually
        // enabled — the build walks `gather_variable_offsets_expanded`,
        // which emits per-element offsets for DynamicVariable/AssignDynamic,
        // and for designs with large memory arrays (multi-MB DRAMs) this
        // costs seconds per ProtoModule even when the worklist is disabled.
        #[cfg(not(target_family = "wasm"))]
        let comb_schedule = if context.config.use_seeded_worklist {
            build_aligned_schedule(
                &pre_jit_stmts,
                context.config.use_jit,
                &module_variable_meta,
                context.config.use_4state,
            )
        } else {
            IrSchedule::empty()
        };
        #[cfg(target_family = "wasm")]
        let comb_schedule = IrSchedule::empty();

        Ok(ProtoModule {
            name: src.name,
            ports: src.ports.clone(),
            ff_bytes: context.ff_total_bytes,
            comb_bytes: context.comb_total_bytes,
            use_4state: context.config.use_4state,
            module_variable_meta,
            event_statements,
            comb_statements,
            required_comb_passes,
            comb_schedule,
            nontrivial_comb_scc,
        })
    }
}