bitwright 0.32.14

Hash-consed fixed-width bit-vector expressions: exact evaluation, bit-level facts, and verified simplification.
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
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
//! The MBA phase: lowering, the solver, the evidence gate, lifting (see [`crate::mba`]).

mod cofactors;
mod field_guard;
mod guard_domain;
mod opaque_predicate;
mod output_set;
mod selector_cube;
pub(super) use opaque_predicate::{equal_sums, truncated_constant};

use super::{Fin, PassKind, Runner, Step, Stop, discard, finish, shrinks};
use crate::engine::Exhausted;
use crate::engine::budget::Counter;
use crate::expr::{Context, OpCode};
use crate::hash::combine;
use crate::mba::certify;
use crate::mba::{
    Bindings, CacheEntry, CacheKey, Claim, LOWERING_VERSION, MOp, MbaAnswer, MbaConfig, MbaExpr,
    Reading, Refusal, Verdict, lift_id, lower_id, lower_id_over, lower_id_reading, lower_id_whole,
    shared_nodes, shared_nodes_whole,
};
use crate::{BinOp, UnOp};

/// An answer owned by this call. A sample result belongs to this exact answer and the
/// structurally equal lowered input (hence the same point seed), never just their cache key.
struct CachedAnswer {
    answer: MbaAnswer,
    sample: Option<(MbaExpr, bool)>,
}

/// The MBA phase's state for a call: what it asked, and how deep it goes.
#[derive(Default)]
pub(crate) struct State {
    /// The MBA solver's answers in this call, by question.
    answers: crate::hash::IdMap<CacheKey, CachedAnswer>,
    /// Questions whose answers the evidence gate could not prove in this call (see `pass::mba::ask`).
    pub(crate) unproved: crate::hash::IdMap<crate::mba::CacheKey, ()>,
    /// Questions the solver ran out of steps on in this call, each with the steps it had (see
    /// `pass::mba::ask`).
    pub(crate) exhausted: crate::hash::IdMap<crate::mba::CacheKey, u64>,
    /// The roots of fragments the MBA phase asked about in this call and kept as they are:
    /// `true` when declined by a monotonic size cap, step exhaustion, or `NoSimpler` past
    /// `KEPT_STEPS` (a larger question would pay for that normal form again), `false` when kept
    /// locally (`not_smaller` or `proof_unknown`), which only blocks ancestors that do not
    /// combine the kept core with another branch sharing its atoms.
    pub(crate) kept: crate::hash::IdMap<u32, bool>,
    /// How deep the MBA phase's own questions go in this round (see `pass::mba::depth`): the
    /// rounds ask within a few steps each until one changes nothing, and only then deeper.
    pub(crate) depth: u8,
    /// Whether a question of this round ran out of steps at that depth (or was not asked for
    /// holding one that did), so a deeper round has something to ask.
    pub(crate) deeper: bool,
    /// The roots of the fragments whose questions ran out of steps at this round's depth:
    /// a fragment holding one is not asked at this depth either (see `pass::mba::ask`).
    pub(crate) shallow: crate::hash::IdMap<u32, ()>,
    /// The opaque-constant candidates whose readings were asked in this call and decided
    /// nothing: atoms to the readings of every candidate above them (see
    /// `pass::mba::readings_prove`).
    pub(crate) undecided: crate::hash::IdMap<u32, ()>,
    /// The opaque-constant sweep's result for every node it examined in this call (the node
    /// itself where it found nothing), so a sweep of another root or of one side of a case
    /// reads the nodes it shares with an earlier sweep instead of asking about them again (see
    /// `pass::mba::sweep`).
    pub(crate) swept: crate::hash::IdMap<u32, u32>,
    /// Inputs at which a candidate of the opaque-constant sweep was found to differ from what
    /// its samples showed (see `pass::mba::Witness`).
    pub(crate) witnesses: Vec<Witness>,
    /// The blocks the opaque-constant sweep asked the solver about in this call with a node
    /// cut off and got no answer to within its steps: the blocks' roots, by the cut (see
    /// `pass::mba::sweep_cut_at`).
    pub(crate) cut_declined: crate::hash::IdMap<u32, crate::hash::IdMap<u32, ()>>,
    /// The opaque-constant sweep's enumerations' buffers (see `pass::mba::Exhaust`).
    pub(crate) exhaust: Exhaust,
    /// The pass work the evidence gate's certificates that proved nothing have taken in this
    /// call (see `pass::mba::exact`).
    pub(crate) missed: u64,
    /// The pass work the sweep's certificates took once the call's MBA solver steps were
    /// gone (see `pass::mba::readings_prove`).
    pub(crate) sweep_borrowed: u64,
    /// What [`sliced`] made of each node it was asked about in this call (by the node and the
    /// size limit). The arena only grows, so a node's fragment is the same every time and the
    /// nodes written for it are there already: the walk asks the same nodes in every round,
    /// four times and more in a measured call, and the second answer made no node.
    pub(crate) sliced: crate::hash::IdMap<(u32, u32), Option<u32>>,
    /// The shared nodes of each fragment asked for in this call with no node kept out of it
    /// (see [`shared`]): by the root, the size limit, how many, and whether casts are read.
    pub(crate) shared: crate::hash::IdMap<(u32, u32, u32, bool), Vec<u32>>,
}

impl Drop for State {
    /// The call's enumeration buffers outlive it, for the next call on this thread (see
    /// [`Exhaust::ready`]).
    fn drop(&mut self) {
        Exhaust::keep(std::mem::take(&mut self.exhaust));
    }
}

/// [`shared_nodes`] of `root` (with `whole`, [`shared_nodes_whole`]), read once per call: the
/// list is a function of the nodes below `root`, which do not change.
fn shared(
    r: &mut Runner<'_, '_>,
    cx: &Context,
    cfg: &MbaConfig,
    root: u32,
    n: usize,
    whole: bool,
) -> Vec<u32> {
    r.mba
        .shared
        .entry((root, cfg.limits.max_nodes, n as u32, whole))
        .or_insert_with(|| match whole {
            true => shared_nodes_whole(cx, root, &cfg.limits, n),
            false => shared_nodes(cx, root, &cfg.limits, n, &Default::default()),
        })
        .clone()
}

/// Points for the always-on refutation check and for trusted sampling.
const SAMPLE_POINTS: u32 = certify::SAMPLE_POINTS as u32;

fn mixed_op(op: OpCode) -> bool {
    matches!(
        op,
        OpCode::Add
            | OpCode::Sub
            | OpCode::Mul
            | OpCode::Neg
            | OpCode::And
            | OpCode::Or
            | OpCode::Xor
            | OpCode::Not
    )
}

/// Charges `evals` evaluations of both sides (their node counts) as pass work.
fn charge(r: &mut Runner<'_, '_>, a: &MbaExpr, b: &MbaExpr, evals: u64) -> Result<(), Stop> {
    let per = (a.nodes().len() + b.nodes().len()) as u64;
    r.meter
        .charge(Counter::PassWork, per.saturating_mul(evals))
        .map_err(Stop::Exhausted)
}

/// Whether `a` and `b` agree at the refutation sample: zero, all-ones, one and the signed
/// minimum, the constants of both sides and their neighbours, single bit positions, and seeded
/// random points (see [`certify::sample_points`]). A filter, never evidence on its own.
fn sampled(r: &mut Runner<'_, '_>, a: &MbaExpr, b: &MbaExpr, seed: u64) -> Result<bool, Stop> {
    charge(r, a, b, u64::from(SAMPLE_POINTS))?;
    Ok(agrees_at_sample(a, b, seed))
}

fn agrees_at_sample(a: &MbaExpr, b: &MbaExpr, seed: u64) -> bool {
    let points = certify::sample_points(a.vars(), &[a, b], seed);
    certify::refute(a, b, &points).is_none()
}

/// Pass work as a certificate's meter, at most `share` of it.
struct Gate<'x, 'r, 'a> {
    r: &'x mut Runner<'r, 'a>,
    share: u64,
}

impl<'x, 'r, 'a> Gate<'x, 'r, 'a> {
    /// A meter for the certificate of `a == b`: at most [`GATE_SHARE`] of the call's pass
    /// work, and at most [`GATE_MISSED_SHARE`] once the certificates that proved nothing have
    /// taken [`GATE_MISSED`] in the call; or what a direct test of the pair costs (twice:
    /// with its casts taken out and without) where that is more.
    fn new(r: &'x mut Runner<'r, 'a>, a: &MbaExpr, b: &MbaExpr, part: u64) -> Self {
        let limit = r.meter.limit.pass_work;
        let direct = certify::direct_cost(a, b).unwrap_or(0).saturating_mul(2);
        let mut share = (limit / part).max(GATE_SHARE_MIN / (part / GATE_SHARE));
        if r.mba.missed >= GATE_MISSED {
            share = share.min(GATE_MISSED_SHARE);
        }
        Gate {
            r,
            share: share.max(direct),
        }
    }
}

/// The pass work undecided certificates may take in a call before the next ones are held to
/// [`GATE_MISSED_SHARE`]. An answer no test decides goes through several of them, and where
/// limb arithmetic asks hundreds of questions an expression, two such answers at half the
/// call's pass work each were the whole of it.
const GATE_MISSED: u64 = 1 << 24;

/// See [`GATE_MISSED`].
const GATE_MISSED_SHARE: u64 = 1 << 23;

/// One answer's certificate spends at most this fraction of the call's pass work (and at least
/// [`GATE_SHARE_MIN`] units), unless a direct test, which decides when it runs, costs more.
/// Without a share one answer the tests cannot decide took the whole call: a compositional
/// test over two variables and 112 nodes spent 7.5M of a call's 8.4M units, undecided, and the
/// phases after it had none left. A compositional proof can need much of a call (a sparse test
/// on a skeleton over three 32-bit variables, 20M of 67M units), so the share is half.
const GATE_SHARE: u64 = 2;

/// See [`GATE_SHARE`].
const GATE_SHARE_MIN: u64 = 1 << 20;

impl certify::Meter for Gate<'_, '_, '_> {
    type Err = Stop;
    fn left(&self) -> u64 {
        self.r.meter.left_in(|b| b.pass_work).min(self.share)
    }
    fn charge(&mut self, units: u64) -> Result<(), Stop> {
        self.share = self.share.saturating_sub(units);
        self.r
            .meter
            .charge(Counter::PassWork, units)
            .map_err(Stop::Exhausted)
    }
}

/// bitwright's own exact evidence about `a == b`: the cheapest certificate that applies (the
/// corner signature, single bit positions, sparse points for degree `d`, the pure-polynomial
/// grid, exhaustive evaluation; equal polynomials over symbols first where that test would
/// take far longer), over abstracted atoms when a side leaves the polynomial fragment. Charged
/// as pass work, a block at a time, so a budget or deadline can stop it; a certificate larger
/// than what is left is not started (reported as over budget).
fn exact(
    r: &mut Runner<'_, '_>,
    a: &MbaExpr,
    b: &MbaExpr,
    part: u64,
) -> Result<certify::Report, Stop> {
    let before = r.meter.spent.pass_work;
    let report = certify::prove(a, b, &mut Gate::new(r, a, b, part))?;
    if report.verdict != crate::mba::Verdict::Proved {
        r.mba.missed += r.meter.spent.pass_work - before;
    }
    count(r).certificates.record(&report);
    Ok(report)
}

fn count<'x>(r: &'x mut Runner<'_, '_>) -> &'x mut crate::engine::MbaStats {
    &mut r.stats.mba
}

/// Whether the MBA phase asks the question at `n`: its operator is one it asks at and its
/// fragment is one it lowers (within the limits); remembered for the phase run. A link of a
/// chain below `n` is then not asked (see `pass::mba_step`).
pub(super) fn asks(
    r: &mut Runner<'_, '_>,
    cx: &Context,
    cfg: &MbaConfig,
    n: u32,
) -> Result<bool, Stop> {
    if let Some(&a) = r.asks.get(&n) {
        return Ok(a);
    }
    let poly = r.inner.mba.solver.polynomial_fragments();
    let op = cx.node(n).op;
    let qualifies = |op: OpCode| mixed_op(op) || (poly && op == OpCode::Shl);
    let a = if qualifies(op) {
        match crate::mba::fits_nodes(cx, n, &cfg.limits) {
            Ok(order) => {
                r.meter.charge(Counter::PassWork, order.len() as u64)?;
                // A fragment within the limits: so is the fragment of every node inside it
                // (a part of it), which is not scanned again when the walk reaches it (along
                // a chain of n sums that was n scans of n links).
                for &i in &order {
                    if i != n && qualifies(cx.node(i).op) {
                        r.asks.entry(i).or_insert(true);
                    }
                }
                true
            }
            Err(_) => false,
        }
    } else {
        false
    };
    r.asks.insert(n, a);
    Ok(a)
}

/// opaque constants. Obfuscators hide constants (a dispatch target, a key, a hash
/// multiplier) as MBA over values that cancel, often values the code never wrote, and build
/// later constants from earlier ones: a hash of a hidden value, every round a hidden
/// multiplier. The normal form sees such a chain only whole, and a certificate over the whole
/// takes a value read through a right shift or a high byte for an independent atom, so neither
/// decides it; the phases before the MBA phase spend their work on the noise.
///
/// So before the first phase, one sweep over the DAG below `root`, operands first: the
/// engine's verification samples (each node evaluated once per call) name constant and
/// two-valued candidates. A node whose operands are all constants is that value (a function of
/// them). Any other constant is taken only when bitwright's exact certificate proves its
/// fragment, with the constants found below it written as constants, equal to the value.
/// Agreement by chance costs one certificate, never an answer. A varying block is reconstructed
/// as a select only after each side is separately proved constant. The DAG is rebuilt once over
/// every proved result.
///
/// A node that varies is also an MBA block over noise when it is a sum (the obfuscator writes
/// `t ^ k`, or `t` itself beside noise that cancels, as `Σ cᵢ·fᵢ(t, n)`) over a subterm `t`
/// that is no atom to the solver (a rotate, a cast): it is asked with its most shared subterm
/// cut off as one atom ([`sweep_cut`]), and replaced by the answer before the nodes above it are
/// read. The constants above then take few readings.
pub(super) fn sweep(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    cfg: &MbaConfig,
    root: u32,
) -> Result<u32, Stop> {
    sweep_inner(r, cx, cfg, root, true)
}

/// Give the cheap linear signatures one operands-first walk before the sweep spends
/// visits sampling and reducing the cones of individual candidates. For a large DAG
/// with many scalar-weighted sums, folding one varying sum to its sole surviving
/// word can expose two inverse rotations and fixed fields in *later* sums. In this
/// walk a rotation is taken only when every bit is a wire (or its complement).
fn large_affine(
    r: &mut Runner<'_, '_>, cx: &mut Context, root: u32, order: &[u32],
) -> Result<Option<u32>, Stop> {
    let scan = order.len() as u64;
    let budget = (r.meter.left_in(|b| b.pass_work) / 2).min(1 << 18);
    if order.len() <= 4096 || 8 * scan >= budget || cx.wid(root) != 1 {
        return Ok(None);
    }
    r.meter.charge(Counter::PassWork, scan)?;
    let add = |op| matches!(op, OpCode::Add | OpCode::Sub);
    let mut tops = super::Lease::new(cx.len());
    let mut weighted = 0;
    for &i in order {
        let n = cx.node(i);
        if add(n.op) {
            if n.children().any(|c| {
                let t = cx.node(c);
                t.op == OpCode::Mul && cx.node(t.b).op == OpCode::Const
            }) { weighted += 1; }
        } else {
            for c in n.children().filter(|&c| add(cx.node(c).op)) { tops.insert(c, 0); }
        }
    }
    if weighted < order.len() / 64 { return Ok(None); }
    // Includes rebuilding, the memoized slice reads, and the final bounded size
    // check. Candidate walks and every row of their signatures are charged below.
    r.meter.charge(Counter::PassWork, 7 * scan)?;
    let available = budget - 8 * scan;
    let mut left = available;
    let mut subs = super::Lease::new(cx.len());
    let mut slices = SliceMemo::new(cx);
    for &i in order {
        let mut kids = [0; 3];
        let mut changed = false;
        for (j, c) in cx.node(i).children().enumerate() {
            kids[j] = subs.get(c).unwrap_or(c);
            changed |= kids[j] != c;
        }
        let mut cur = if changed { r.build(cx, |cx| cx.rebuild(i, kids))? } else { i };
        if tops.contains(i) && let Some(e) = super::linear_mba::one_word(r, cx, cur, &mut left)? {
            cur = e;
        }
        let n = cx.node(cur);
        if n.width <= 64 && matches!(n.op, OpCode::And | OpCode::Or | OpCode::Xor | OpCode::RotL | OpCode::Not) {
            let ones = u64::MAX >> (64 - n.width);
            let s = slice_of(cx, cur, &mut slices, 0);
            if s.base != cur && s.mask == 0 {
                cur = r.build(cx, |cx| cx.mk_const_u64(n.width, s.flip))?;
            } else if s.base != cur && s.mask == ones && (s.flip == 0 || s.flip == ones) {
                cur = r.build(cx, |cx| {
                    let x = if s.rot == 0 { s.base } else {
                        let k = cx.mk_const_u64(n.width, u64::from(s.rot))?;
                        cx.c_bin(BinOp::RotL, s.base, k)?
                    };
                    if s.flip == 0 { Ok(x) } else { cx.c_un(UnOp::Not, x) }
                })?;
            }
        }
        let n = cx.node(cur);
        if r.assumptions.is_none() && n.width <= 64
            && (n.op == OpCode::Extract || (n.op == OpCode::And && cx.node(n.b).op == OpCode::Const))
            && let (Some([z, o]), _) = super::known_words(r, cx, cur)?
            && (z | o) == u64::MAX >> (64 - n.width)
        {
            cur = r.build(cx, |cx| cx.mk_const_u64(n.width, o))?;
        }
        if cur != i { subs.insert(i, cur); }
    }
    r.meter.charge(Counter::PassWork, available - left)?;
    let Some(out) = subs.get(root) else { return Ok(None) };
    Ok(matches!(cx.dag_size(&[cx.handle(out)], order.len() as u32 - 1).map_err(Stop::Error)?,
        crate::expr::Bounded::Exact(_)).then_some(out))
}

/// [`sweep`], optionally reconstructing piecewise constants. A case side disables that recursion:
/// the selected condition is gone, and its ordinary opaque-constant sweep is the useful part.
fn sweep_inner(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    cfg: &MbaConfig,
    root: u32,
    fold_cases: bool,
) -> Result<u32, Stop> {
    // The DAG below `root`, operands first.
    let mut order: Vec<u32> = Vec::new();
    let mut seen: crate::hash::IdMap<u32, ()> = crate::hash::IdMap::default();
    let mut stack: Vec<(u32, bool)> = vec![(root, false)];
    while let Some((i, expanded)) = stack.pop() {
        if expanded {
            order.push(i);
            continue;
        }
        if seen.insert(i, ()).is_some() {
            continue;
        }
        stack.push((i, true));
        for c in cx.node(i).children() {
            stack.push((c, false));
        }
    }
    r.meter.charge(Counter::PassWork, order.len() as u64)?;
    if fold_cases && cfg.opaque_sweep
        && let Some(e) = large_affine(r, cx, root, &order)?
    {
        r.emit_part(cx, crate::engine::Stage::Sweep, root, e);
        return Ok(e);
    }
    if fold_cases && output_set::covered(r, cx, root)? {
        let e = r.build(cx, |cx| cx.mk_const_u64(1, 1))?;
        count(r).opaque_proved += 1;
        r.emit_part(cx, crate::engine::Stage::Sweep, root, e);
        return Ok(e);
    }
    if fold_cases && (32..=4096).contains(&order.len())
        && let Some(e) = guard_domain::specialize(r, cx, cfg, root, &order)?
    {
        r.emit_part(cx, crate::engine::Stage::Sweep, root, e);
        return Ok(e);
    }
    if fold_cases && (32..=4096).contains(&order.len())
        && let Some(e) = field_guard::specialize(r, cx, root, &order)?
    {
        r.emit_part(cx, crate::engine::Stage::Sweep, root, e);
        return Ok(e);
    }
    let root = if fold_cases && cfg.opaque_sweep
        && let Some(e) = cofactors::reduce(r, cx, root, &order)?
    {
        r.emit_part(cx, crate::engine::Stage::Sweep, root, e);
        order = cx.post_order_ids(&[e]);
        r.meter.charge(Counter::PassWork, order.len() as u64)?;
        e
    } else {
        root
    };
    if fold_cases && let Some(e) = opaque_predicate::reduce_columns(r, cx, root, &order)? {
        r.emit_part(cx, crate::engine::Stage::Sweep, root, e);
        return Ok(e);
    }
    // On a large equality, inspecting every apparently constant subexpression first can
    // consume the whole call before the linear and demanded-bit passes get a turn.
    // Skip the speculative scan when there is less than one modest certificate per node.
    // A later round can sweep the smaller expression; no search or rewrite is accepted
    // merely because this estimate declined the scan.
    // A cofactor is temporary: the demanded-bits phase will never see its root.
    if fold_cases && cfg.opaque_sweep && !cfg.known_atoms && !cfg.noise_forms
        && matches!(cx.node(root).op, OpCode::Eq | OpCode::Ne)
        && matches!(cx.node(cx.node(root).a).op,
            OpCode::And | OpCode::Or | OpCode::Not | OpCode::Extract | OpCode::RotL | OpCode::RotR)
        && cx.const_val(cx.node(root).b).is_some()
        && order.len() > 192
        && r.inner.strategy.phases.iter().any(|p| matches!(p, crate::engine::Phase::Demanded))
        && r.meter.left_in(|b| b.pass_work) / (order.len() as u64) < 1024
    {
        return Ok(root);
    }
    if fold_cases && let Some(e) = opaque_predicate::reduce_product(r, cx, root, &order)? {
        r.emit_part(cx, crate::engine::Stage::Sweep, root, e);
        return Ok(e);
    }
    if fold_cases && order.len() <= 1024
        && let Some(k) = guard_domain::comparison(r, cx, root, &order)?
    {
        let e = r.build(cx, |cx| cx.mk_const(&k))?;
        count(r).opaque_proved += 1;
        r.emit_part(cx, crate::engine::Stage::Sweep, root, e);
        return Ok(e);
    }
    r.sample(cx, root)?;
    // A small varying root can be a field of one symbol hidden by arithmetic. Read the
    // whole field before the questions on its parts consume the solver budget.
    let samples = &r.samples[&root];
    let k = samples[0];
    let uniform = samples.iter().all(|v| *v == k);
    // A masked input can feed a long straight-line encoding. Try its Boolean
    // output once, rather than enumerating the same inputs at every inner node.
    if fold_cases && uniform && cx.node(root).width == 1
        && (96..=1024).contains(&order.len())
        && !r.mba.swept.contains_key(&root)
        && order.iter().filter(|&&i| cx.node(i).op == OpCode::Sym).take(2).count() == 1
        && exhaustive(r, cx, root, &k)? == Some(true)
    {
        let e = r.build(cx, |cx| cx.mk_const(&k))?;
        count(r).opaque_exhausted += 1;
        count(r).opaque_proved += 1;
        r.emit_part(cx, crate::engine::Stage::Sweep, root, e);
        r.mba.swept.insert(root, e);
        return Ok(e);
    }
    if (12..=96).contains(&order.len())
        && !r.mba.swept.contains_key(&root)
        && !uniform
        && let Some(e) = narrow_field(r, cx, root, &order)?
    {
        r.emit_part(cx, crate::engine::Stage::Sweep, root, e);
        r.mba.swept.insert(root, e);
        return Ok(e);
    }
    if cx.node(root).width == 1
        && (8..=256).contains(&order.len())
        && !r.mba.swept.contains_key(&root)
        && uniform
    {
        let proved = opaque_predicate::folded(r, cx, root, &k)?;
        #[cfg(feature = "prove")]
        let proved = proved || (order.len() <= 192 && opaque_predicate::circuit(r, cx, root, &k)?);
        if proved {
            let e = r.build(cx, |cx| cx.mk_const(&k))?;
            count(r).opaque_proved += 1;
            r.emit_part(cx, crate::engine::Stage::Sweep, root, e);
            r.mba.swept.insert(root, e);
            return Ok(e);
        }
    }
    // Preserve the stock constant-proof schedule on an apparently uniform output.
    // The optional noise-forms profile is an alternative reading of that same goal;
    // there it can expose guards even when all the samples happened to agree.
    let root = if fold_cases && (!uniform || cfg.noise_forms)
        && let Some(e) = selector_cube::reduce(r, cx, &order)?
    {
        r.emit_part(cx, crate::engine::Stage::Sweep, root, e);
        order = cx.post_order_ids(&[e]);
        r.meter.charge(Counter::PassWork, order.len() as u64)?;
        r.sample(cx, e)?;
        e
    } else {
        root
    };
    // links of a chain of sums, every user of which is a sum too: a noise block is
    // asked about only at the top of its chain (see `sweep_cut`).
    let mut links: crate::hash::IdMap<u32, bool> = crate::hash::IdMap::default();
    for &i in &order {
        let additive = matches!(cx.node(i).op, OpCode::Add | OpCode::Sub | OpCode::Neg);
        for c in cx.node(i).children() {
            let all = links.entry(c).or_insert(true);
            *all &= additive;
        }
    }
    // Each node rebuilt over its operands' results (the constructors fold what constants make
    // trivial: `t & 0`, a product with zero), then asked about.
    let mut to: crate::hash::IdMap<u32, u32> = crate::hash::IdMap::default();
    let mut shapes: crate::hash::IdMap<u32, u64> = crate::hash::IdMap::default();
    let mut failures = 0usize;
    // A varying noise block that has one value on each side of a selector is reconstructed as
    // that selector after both sides are proved constant. Keep this narrow: the sweep already
    // visits every node, while a side proof asks several readings.
    let mut case_attempts = 0usize;
    // The varying nodes met so far by their samples, and the related pairs no proof was found
    // for (see `Classes`).
    let mut classes = Classes::default();
    let mut unrelated = 0usize;
    // For each node, the nodes it or one below it was asked to be related to with no proof
    // found (see `related`).
    let mut unproved: crate::hash::IdMap<u32, Vec<u32>> = crate::hash::IdMap::default();
    // the run's budget ending in a question keeps what the sweep proved before it;
    // the nodes left are rebuilt over those results, not asked about.
    let mut spent = false;
    // The node examined last, recorded in `r.mba.swept` once the next one begins (unless the
    // budget ended while it was asked about, which left it unexamined).
    let mut pending: Option<u32> = None;
    macro_rules! asked {
        ($l:lifetime, $e:expr) => {
            match $e {
                Ok(v) => v,
                // Out of solver steps: the node is left unexamined, and the ones after it
                // are still asked what a certificate on pass work decides.
                Err(Stop::Exhausted(Exhausted::MbaSteps)) => {
                    pending = None;
                    continue $l;
                }
                Err(Stop::Exhausted(_)) => {
                    spent = true;
                    continue $l;
                }
                Err(e) => return Err(e),
            }
        };
    }
    'nodes: for &i in &order {
        if let Some(p) = pending.take()
            && !spent
        {
            r.mba.swept.insert(p, to.get(&p).copied().unwrap_or(p));
        }
        // Examined by an earlier sweep of this call (of another root, or of a case's other
        // side): its result is equal to it, and asking again finds what that sweep found.
        if let Some(&done) = r.mba.swept.get(&i) {
            r.emit_part(cx, crate::engine::Stage::Sweep, i, done);
            to.insert(i, done);
            if done == i {
                classes.note(&r.samples[&i], i);
            }
            continue;
        }
        let node = cx.node(i);
        let mut kids = [0u32; 3];
        let mut changed = false;
        for (k, c) in node.children().enumerate() {
            kids[k] = to.get(&c).copied().unwrap_or(c);
            changed |= kids[k] != c;
        }
        let cur = if changed {
            r.build(cx, |cx| cx.rebuild(i, kids))?
        } else {
            i
        };
        to.insert(i, cur);
        if spent || cx.const_val(cur).is_some() {
            continue;
        }
        // A leaf is never taken (a symbol's samples follow what the host declared of it), nor
        // an extension operator (it may not be a function of its operands alone).
        if node.children().next().is_none() || node.op.as_ext().is_some() {
            if cur == i {
                classes.note(&r.samples[&i], i);
            }
            continue;
        }
        pending = Some(i);
        let vals = &r.samples[&i];
        let k = vals[0];
        if vals.iter().any(|v| *v != k) {
            // A node the samples relate to one met before it (see `related`).
            let found = match unrelated < SWEEP_UNRELATED {
                true => classes.find(vals),
                false => Vec::new(),
            };
            // What the nodes below this one were not proved related to.
            let mut below: Vec<u32> = Vec::new();
            for c in cx.node(cur).children() {
                for &x in unproved.get(&c).map_or(&[][..], |v| v) {
                    if !below.contains(&x) && below.len() < SWEEP_UNPROVED {
                        below.push(x);
                    }
                }
            }
            if !below.is_empty() {
                unproved.insert(cur, below.clone());
            }
            let reps: Vec<u32> = found.iter().map(|f| f.0).collect();
            for (rep, relation, d) in found {
                // A node below this one was asked to be related to `rep` (or to a node the
                // samples relate to it as they do this one) and no proof was found: this one,
                // built on it, would be asked the same thing through it, and is not. Where
                // `f(a)` could not be proved to be `rep + d`, `g(f(a))` failed for the same
                // reason at the cost of a full certificate (of 5,030 such questions in 140
                // measured calls, 124 had been proved). It counts as a pair left open.
                if below.contains(&rep) {
                    unrelated += 1;
                    break;
                }
                let rep = to.get(&rep).copied().unwrap_or(rep);
                match asked!('nodes, related(r, cx, cfg, cur, rep, relation, &d)) {
                    Related::Proved(e) => {
                        r.emit_part(cx, crate::engine::Stage::Sweep, cur, e);
                        to.insert(i, e);
                        continue 'nodes;
                    }
                    Related::Written => {}
                    Related::Open => {
                        unrelated += 1;
                        let v = unproved.entry(cur).or_default();
                        for &x in &reps {
                            if !v.contains(&x) && v.len() < SWEEP_UNPROVED {
                                v.push(x);
                            }
                        }
                        break;
                    }
                }
            }
            classes.note(&r.samples[&i], i);
            let vals = &r.samples[&i];
            let top = !links.get(&i).copied().unwrap_or(false);
            let mut rewritten = None;
            if top
                && fold_cases
                && cfg.known_atoms
                && case_attempts < SWEEP_CASE_BLOCKS
                && exactly_two(vals)
            {
                rewritten = asked!('nodes, cases_fold(r, cx, cfg, cur, &mut case_attempts)
                );
            }
            if rewritten.is_none() && top {
                rewritten = asked!('nodes, sweep_cut(r, cx, cfg, cur));
            }
            if let Some(e) = rewritten {
                r.emit_part(cx, crate::engine::Stage::Sweep, cur, e);
                to.insert(i, e);
            }
            continue;
        }
        let op = cx.node(cur).op;
        let all_constant = cx.node(cur).children().all(|c| cx.const_val(c).is_some());
        let mixed = mixed_op(op) || op == OpCode::Shl;
        // a one-bit node of any operator (an opaque predicate: one bit of an MBA
        // block, a compare) is taken too, for the known bits and the enumeration only. A masked
        // dispatch selector can pick an arm by `select(extract<13, 1>(…), a, b)`, the bit 1 over
        // 13 bits of one word.
        //
        // And a truncation, for the same: the low bits of a product that only a few bits of
        // its operands reach are a shift count an obfuscator computes, constant where the
        // product is not. Not a slice above the low bits: those are the fields of one value,
        // read together again by what joins them, and with some of them folded and others
        // not, the value under the rest is rewritten on the bits they read and what proved
        // the whole no longer applies (six of 47 measured constants were lost that way).
        let predicate =
            cx.width_of(cur).bits() == 1 || (op == OpCode::Extract && cx.node(cur).b == 0);
        if !all_constant && (!(mixed || predicate) || failures >= SWEEP_FAILURES) {
            continue;
        }
        // Not `k` at an input an earlier candidate differed at: no constant.
        if !all_constant && asked!('nodes, witnessed(r, cx, cur, &k)) {
            continue;
        }
        // Over constants alone it is that value. Otherwise its fragment is read several ways:
        // whole; semi-linear, semi-linear over bitwise functions of atoms, linear, and
        // semi-linear with a subterm many of its nodes read cut off as one atom (every other
        // subterm an independent atom, so an identity of a reading holds for the node). The cheapest first by the test it takes
        // (`2^t` corners for a linear reading, else `64·(2^t − 1)` single-bit points, times its
        // nodes), and none over a certificate's share of the work, so one large question does
        // not starve the others. A refutation decides only for the whole fragment: the other
        // readings free more atoms.
        let mut decided = all_constant;
        let mut refuted = false;
        // a node whose bits are all known is that value, which no reading needs
        // proving (`~(x & k) >>u 42` over a 32-bit `x` keeps only `k`'s bits).
        if !decided
            && let (Some(kb), _) = asked!('nodes, super::known(r, cx, cur))
            && kb.known().is_ones()
            && kb.known_one() == k
        {
            decided = true;
            count(r).opaque_known += 1;
        }
        // the candidate with each operand taken on the bits its users read, and
        // folded where those are known (the half of a rotate a shift keeps); its readings are of
        // what is left, and a few bits of symbols left are enumerated.
        let mut subject = cur;
        if !decided {
            subject = asked!('nodes, super::demanded::reduced(r, cx, cur, SWEEP_DEMAND_VISITS, true)
            );
            if let Some(v) = cx.const_val(subject) {
                if v == k {
                    decided = true;
                    count(r).opaque_known += 1;
                } else {
                    refuted = true;
                }
            } else if let Some(holds) = asked!('nodes, exhaustive(r, cx, subject, &k)) {
                if holds {
                    decided = true;
                    count(r).opaque_exhausted += 1;
                } else {
                    refuted = true;
                }
            }
        }
        // A shape whose questions a store of results has only ever seen fail is not asked
        // again (the store's caller chose that; see `Remembered`). Not counted as a failure:
        // it cost nothing.
        let shape = cx.sweep.wanted().then(|| cx.shape_into(cur, &mut shapes));
        if !decided && !refuted && mixed && shape.is_some_and(|s| cx.sweep.fruitless(s)) {
            count(r).opaque_skipped += 1;
            continue;
        }
        let mut budget_starved = false;
        if !decided
            && !refuted
            && mixed
            && (asked!('nodes, opaque_predicate::constant_word(r, cx, subject, &k))
                || (subject != cur
                    && asked!('nodes, opaque_predicate::constant_word(r, cx, cur, &k))))
        {
            count(r).opaque_asked += 1;
            decided = true;
        }
        if !decided && !refuted && mixed {
            let seen;
            (decided, refuted, seen, budget_starved) =
                asked!('nodes, readings_prove(r, cx, cfg, subject, &k, SWEEP_SHARE));
            // The candidate as it is written, where the reduced one was not decided: taking
            // each operand on the bits its user reads writes one value read under several
            // masks once per mask, each a variable of its own, and what the terms cancel
            // through (the one value they all read) is gone.
            if !decided && !refuted && subject != cur {
                let again = asked!('nodes, readings_prove(r, cx, cfg, cur, &k, SWEEP_SHARE));
                decided = again.0;
                budget_starved |= again.3;
            }
            // the root, a constant some reading's free atoms refute, one case of
            // the condition it tests at a time (see `cases_prove`). The root only: inner
            // candidates are what the readings fold, and splitting each of them doubled the
            // sweep's time on the slow retries for no other constant.
            if !decided && !refuted && seen && cfg.known_atoms && i == root {
                decided = asked!('nodes, cases_prove(r, cx, cfg, subject, &k));
                if decided {
                    count(r).opaque_cases += 1;
                }
            }
        }
        if mixed
            && !all_constant
            && (decided || !budget_starved)
            && let Some(s) = shape
        {
            cx.sweep.note(s, decided);
        }
        if decided {
            if !all_constant {
                count(r).opaque_proved += 1;
            }
            let e = asked!('nodes, r.build(cx, |cx| cx.mk_const(&k)));
            // (Of the candidate as the constants found below it left it: that is what was
            // proved, and what a replay of the parts in order comes to.)
            r.emit_part(cx, crate::engine::Stage::Sweep, cur, e);
            to.insert(i, e);
        } else if !refuted {
            failures += 1;
        }
    }
    if let Some(p) = pending
        && !spent
    {
        r.mba.swept.insert(p, to.get(&p).copied().unwrap_or(p));
    }
    Ok(to.get(&root).copied().unwrap_or(root))
}

/// How the samples relate a node to one met before it: `rep + d`, `d − rep` or `rep ^ d`.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Relation {
    Sum,
    Difference,
    Xor,
}

/// The varying nodes of a sweep by their samples, up to a constant: the nodes met with each
/// sequence of differences from the first sample (`v[j] − v[0]`; the first met with each
/// `v[j] ^ v[0]`), each with its first sample. Two nodes a constant apart (added, or xored), or
/// whose sum is constant, agree there; so do two that are equal, a constant of zero apart.
///
/// A sequence is kept as a 128-bit digest of its values, not the values: two sequences that
/// collide name a pair that is not related, which costs the proof that fails and no answer.
#[derive(Default)]
struct Classes {
    sums: crate::hash::IdMap<[u64; 2], Vec<(u32, crate::BitVec)>>,
    xors: crate::hash::IdMap<[u64; 2], (u32, crate::BitVec)>,
}

impl Classes {
    fn key(vals: &[crate::BitVec], op: BinOp, flip: bool) -> [u64; 2] {
        let first = &vals[0];
        let mut h = [u64::from(first.width().bits()), 0x9e37_79b9_7f4a_7c15];
        for v in vals {
            let d = match flip {
                false => crate::BitVec::bin_unchecked(op, v, first),
                true => crate::BitVec::bin_unchecked(op, first, v),
            };
            for &l in d.limbs() {
                h[0] = combine(h[0], l);
                h[1] = combine(h[1] ^ l, h[0]);
            }
        }
        h
    }

    /// Whether nodes of this width are kept: a narrow one takes few values, and agrees with
    /// many others on every sample.
    fn kept(vals: &[crate::BitVec]) -> bool {
        vals.first()
            .is_some_and(|v| v.width().bits() >= SWEEP_RELATED_BITS)
    }

    /// Records `i` (samples `vals`).
    fn note(&mut self, vals: &[crate::BitVec], i: u32) {
        if !Self::kept(vals) || vals.iter().all(|v| *v == vals[0]) {
            return;
        }
        let class = self
            .sums
            .entry(Self::key(vals, BinOp::Sub, false))
            .or_default();
        if class.len() < SWEEP_CLASS {
            class.push((i, vals[0]));
        }
        self.xors
            .entry(Self::key(vals, BinOp::Xor, false))
            .or_insert((i, vals[0]));
    }

    /// The nodes recorded that a node with samples `vals` is related to on every sample, how,
    /// and the constant `d` of each relation: one equal to it, one that is its complement,
    /// then the first met a constant from it, the first met whose sum with it is constant, the
    /// first met a constant xored from it.
    fn find(&self, vals: &[crate::BitVec]) -> Vec<(u32, Relation, crate::BitVec)> {
        use crate::BitVec;
        let mut found = Vec::new();
        if !Self::kept(vals) {
            return found;
        }
        let same = self.sums.get(&Self::key(vals, BinOp::Sub, false));
        let opposite = self.sums.get(&Self::key(vals, BinOp::Sub, true));
        let zero = BitVec::zero(vals[0].width());
        if let Some(&(rep, _)) = same.and_then(|c| c.iter().find(|(_, first)| *first == vals[0])) {
            found.push((rep, Relation::Sum, zero));
        }
        let sum = |first: &BitVec| BitVec::bin_unchecked(BinOp::Add, &vals[0], first);
        if let Some(&(rep, first)) =
            opposite.and_then(|c| c.iter().find(|(_, first)| sum(first).is_ones()))
        {
            found.push((rep, Relation::Difference, sum(&first)));
        }
        if let Some(&(rep, first)) = same.and_then(|c| c.first())
            && first != vals[0]
        {
            let d = BitVec::bin_unchecked(BinOp::Sub, &vals[0], &first);
            found.push((rep, Relation::Sum, d));
        }
        if let Some(&(rep, first)) = opposite.and_then(|c| c.first())
            && !sum(&first).is_ones()
        {
            found.push((rep, Relation::Difference, sum(&first)));
        }
        if let Some((rep, first)) = self.xors.get(&Self::key(vals, BinOp::Xor, false)) {
            let d = BitVec::bin_unchecked(BinOp::Xor, &vals[0], first);
            found.push((*rep, Relation::Xor, d));
        }
        found
    }
}

/// What [`related`] found of a node and the one its samples relate it to.
enum Related {
    /// Proved: the node written over the other.
    Proved(u32),
    /// The node is already written over the other.
    Written,
    /// No proof.
    Open,
}

/// One value written twice. An obfuscator computes a value again where it reads it again:
/// `(t ^ a) + b` here, `c − (t ^ a')` there, `~(e − (t ^ a))` in a third place, equal through the
/// bits known of `t`. Each is its own atom to every reading above, so a sum over them that
/// cancels is not seen to (the certificate takes atoms for independent), and no rule relates
/// two nodes it is not looking at. The samples do: `cur`, which they show to be `rep + d`,
/// `d − rep` or `rep ^ d` for a node `rep` met before it, is asked about as an opaque constant
/// is (the difference of the two, whether it is zero), and written that way once proved. The
/// sums above then read one atom, and the linear passes collect its terms.
fn related(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    cfg: &MbaConfig,
    cur: u32,
    rep: u32,
    relation: Relation,
    d: &crate::BitVec,
) -> Result<Related, Stop> {
    // Written over `rep` and constants alone: nothing to relate.
    let node = cx.node(cur);
    if cur == rep
        || (node.children().any(|c| c == rep)
            && node
                .children()
                .all(|c| c == rep || cx.const_val(c).is_some()))
    {
        return Ok(Related::Written);
    }
    let zero = crate::BitVec::zero(d.width());
    let e = r.build(cx, |cx| {
        let k = cx.mk_const(d)?;
        match relation {
            Relation::Sum if d.is_zero() => Ok(rep),
            Relation::Sum => cx.c_bin(BinOp::Add, rep, k),
            Relation::Difference if d.is_zero() => cx.c_un(UnOp::Neg, rep),
            Relation::Difference if d.is_ones() => cx.c_un(UnOp::Not, rep),
            Relation::Difference => cx.c_bin(BinOp::Sub, k, rep),
            Relation::Xor => cx.c_bin(BinOp::Xor, rep, k),
        }
    })?;
    if e == cur {
        return Ok(Related::Written);
    }
    let op = match relation {
        Relation::Xor => BinOp::Xor,
        _ => BinOp::Sub,
    };
    let diff = r.build(cx, |cx| cx.c_bin(op, cur, e))?;
    let proved = |v: crate::BitVec| match v.is_zero() {
        true => Related::Proved(e),
        false => Related::Open,
    };
    if let Some(v) = cx.const_val(diff) {
        return Ok(proved(v));
    }
    if witnessed(r, cx, diff, &zero)? {
        return Ok(Related::Open);
    }
    let whole_sums = relation != Relation::Xor;
    let subject = super::demanded::reduced(r, cx, diff, SWEEP_DEMAND_VISITS, whole_sums)?;
    if let Some(v) = cx.const_val(subject) {
        return Ok(proved(v));
    }
    if let Some(holds) = exhaustive(r, cx, subject, &zero)? {
        count(r).opaque_exhausted += u64::from(holds);
        return Ok(if holds {
            Related::Proved(e)
        } else {
            Related::Open
        });
    }
    // The difference as it is written first, within a small share: taking each operand on
    // the bits its user reads writes one value read under several masks once per mask (a sum
    // with a constant becomes a sum of its own for each), and a relation that is a bitwise
    // identity over that value, which a cut at it shows at once, is then one over several
    // carry chains. Of the relations proved in a measured call, the readings of the reduced
    // difference took a thousand steps for half of them and the whole share for the ones
    // they could not prove.
    if subject != diff {
        let (first, _, _, _) = readings_prove(r, cx, cfg, diff, &zero, RELATED_FIRST_SHARE)?;
        if first {
            count(r).opaque_proved += 1;
            return Ok(Related::Proved(e));
        }
    }
    let (decided, _, _, _) = readings_prove(r, cx, cfg, subject, &zero, SWEEP_SHARE)?;
    if decided {
        count(r).opaque_proved += 1;
        return Ok(Related::Proved(e));
    }
    Ok(Related::Open)
}

/// The share of the readings of a relation's difference as written, before those of its
/// reduction take [`SWEEP_SHARE`] (see [`related`]). At an eighth, one measured call asked
/// with an eighth of the usual fuel went from 312 nodes to 80 in half the time, and 44
/// others took a third less time; at a quarter and at a thirty-second it stopped at 186.
const RELATED_FIRST_SHARE: u64 = SWEEP_SHARE / 8;

/// The most nodes kept per node of those it was not proved related to (see `sweep_inner`).
const SWEEP_UNPROVED: usize = 8;

/// The related pairs a sweep asks about without a proof before it asks about no more.
const SWEEP_UNRELATED: usize = 64;

/// The most nodes a sweep keeps of those a constant apart.
const SWEEP_CLASS: usize = 16;

/// The narrowest node a sweep relates to another by its samples.
const SWEEP_RELATED_BITS: u16 = 8;

/// Recognize `zext(extract(x, lo, len)) << shift ^ k` in a small arithmetic block. The
/// demanded-bit transfer proves independence of the bits omitted from the enumeration;
/// every assignment of the remaining bits is checked, including mixed assignments. The
/// candidate may not read any omitted bits either.
fn narrow_field(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    root: u32,
    order: &[u32],
) -> Result<Option<u32>, Stop> {
    let mut sym = None;
    let (mut arithmetic, mut bitwise) = (false, false);
    for &i in order {
        let n = cx.node(i);
        if n.width > 64 {
            return Ok(None);
        }
        if n.op == OpCode::Sym && sym.replace(i).is_some() {
            return Ok(None);
        }
        arithmetic |= matches!(n.op, OpCode::Mul | OpCode::Add | OpCode::Sub);
        bitwise |= matches!(n.op, OpCode::Xor | OpCode::Or | OpCode::And);
    }
    let Some(x) = sym.filter(|_| arithmetic && bitwise) else {
        return Ok(None);
    };
    r.meter.charge(Counter::PassWork, order.len() as u64)?;
    r.mba.exhaust.ready();
    let sc = &mut r.mba.exhaust;
    if sc.sweep(cx, root) != Swept::Whole {
        return Ok(None);
    }
    let support = sc.demand[sc.place[x as usize] as usize];
    let bits = support.count_ones();
    if !(1..=8).contains(&bits) {
        return Ok(None);
    }
    let points = 1usize << bits;
    let steps = (points as u64 * (1 + order.len() as u64))
        .div_ceil(WORD_EVALS * EVALS_PER_STEP);
    if steps > r.meter.left_in(|b| b.mba_steps) {
        return Ok(None);
    }
    r.meter.charge(Counter::MbaSteps, steps)?;
    sc.bases.clear();
    sc.above(None);
    if !sc.program(cx) {
        return Ok(None);
    }
    sc.lanes_for(points as u64);
    debug_assert_eq!(sc.most, points);
    sc.pass_of(points);
    let slot = sc.inputs[0].0 as usize * points;
    sc.lanes[slot..slot + points].copy_from_slice(&sc.spreads[..points]);
    run_lanes(&sc.prog, &mut sc.lanes, points);
    let row = &sc.lanes[sc.root * points..][..points];
    let k = row[0];
    // The nonzero basis columns of a copied field mark its source positions and its
    // lowest destination position. They only propose a field, never prove one.
    let mut mask = 0u64;
    let mut dst = 64;
    for j in 0..bits {
        let p = 1usize << j;
        let column = row[p] ^ k;
        if column != 0 {
            mask |= sc.spreads[p];
            dst = dst.min(column.trailing_zeros());
        }
    }
    if mask == 0 {
        return Ok(None);
    }
    let lo = mask.trailing_zeros();
    let len = mask.count_ones();
    if mask >> lo != (1u64 << len) - 1 || dst + len > u32::from(cx.wid(root)) {
        return Ok(None);
    }
    if row.iter().zip(&sc.spreads).any(|(&out, &v)| {
        out != ((((v & mask) >> lo) << dst) ^ k)
    }) {
        return Ok(None);
    }
    let before = cx.len() as u32;
    let w = cx.width_of(root);
    let e = r.build(cx, |cx| {
        let field = cx.c_extract(x, lo as u16, len as u16)?;
        let mut v = cx.c_zext(field, w.bits())?;
        if dst != 0 {
            let s = cx.mk_const(&crate::BitVec::wrapping_from_u64(w, u64::from(dst)))?;
            v = cx.c_bin(BinOp::Shl, v, s)?;
        }
        if k != 0 {
            let c = cx.mk_const(&crate::BitVec::wrapping_from_u64(w, k))?;
            v = cx.c_bin(BinOp::Xor, v, c)?;
        }
        Ok(v)
    })?;
    if shrinks(r, cx, root, e, &[x])?.is_err() {
        discard(r, cx, before);
        return Ok(None);
    }
    Ok(Some(e))
}

/// whether `root` is `k` at every point, decided by evaluating it at every value of
/// the bits of its symbols that reach it, when those number at most [`EXHAUSTIVE_BITS`]: a byte
/// `trunc<8>(x)` of a symbol is 256 values whatever `x`'s width, and `zext<64>(x) & m` reads
/// `m`'s bits of `x`. The bits that reach the root are what the demanded-bits transfers below let
/// through from the root down (each a superset); a symbol's other bits are taken as zero, which
/// no node can tell from any other value. Charged to the MBA solver's steps as the sweep's
/// certificates are, within [`EXHAUSTIVE_SHARE`], for the points it evaluates: an enumeration
/// that would not fit is not begun, and one that meets a difference stops there. `None` when it
/// does not apply or would cost more.
fn exhaustive(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    root: u32,
    k: &crate::BitVec,
) -> Result<Option<bool>, Stop> {
    // The call's buffers, taken for the decision (nothing below asks another).
    r.mba.exhaust.ready();
    let mut sc = std::mem::take(&mut r.mba.exhaust);
    let out = exhaustive_in(r, cx, &mut sc, root, k);
    r.mba.exhaust = sc;
    out
}

/// [`exhaustive`], over the call's buffers.
fn exhaustive_in(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    sc: &mut Exhaust,
    root: u32,
    k: &crate::BitVec,
) -> Result<Option<bool>, Stop> {
    use crate::BitVec;
    // The DAG below `root`, operands first, every node at most 64 bits; and the bits of each
    // node that reach the root, from the root down.
    let swept = sc.sweep(cx, root);
    match swept {
        Swept::Wide | Swept::Open => return Ok(None),
        // Not met with (a node is made after its operands): the same by a walk from the root.
        Swept::Unordered => {
            if !sc.walk(cx, root) {
                return Ok(None);
            }
            sc.demands(cx);
        }
        Swept::Whole => {}
    }
    let total: u32 = sc.syms.iter().map(|(_, m)| m.count_ones()).sum();
    // The points of an enumeration over several symbols are numbered by the symbols' bits in
    // the order a walk from the root meets the symbols.
    if total <= EXHAUSTIVE_BITS && swept == Swept::Whole && sc.syms.len() > 1 {
        sc.walk(cx, root);
        sc.demands(cx);
    }
    // Too many symbol bits: places every demanded path from them passes through, with few
    // bits of their own, are enumerated instead. First one place, over the values the bits
    // known of it leave; then, where the root differs at one of those (a value the place may
    // never take), several places nearer the symbols.
    if total > EXHAUSTIVE_BITS {
        let one = bottleneck(&sc.below, &sc.demand, &mut sc.live, &mut sc.over);
        if let Some(c) = one {
            // Over the values it can take: the bits known of it are those values' (a sum
            // that is constant only for them is constant), and a value it never takes
            // refutes nothing.
            let [z, o] = super::known_words(r, cx, sc.order[c])?.0.unwrap_or([0, 0]);
            sc.syms.clear();
            sc.syms.push((c as u32, sc.demand[c] & !(z | o)));
            sc.bases.clear();
            sc.bases.push(o & sc.demand[c]);
            sc.above(Some(c));
            match enumerated(r, cx, sc, k)? {
                Some(None) => return Ok(Some(true)),
                Some(Some(_)) => {}
                None => return Ok(None),
            }
        }
        let Some(mut front) = frontier(&sc.below, &sc.demand, &mut sc.over) else {
            return Ok(None);
        };
        // The one place again: no more an answer.
        if let ([(p, _)], Some(c)) = (&front[..], one)
            && *p as usize == c
        {
            return Ok(None);
        }
        sc.bases.clear();
        for (p, m) in front.iter_mut() {
            let [z, o] = match sc.below[*p as usize].0.op {
                OpCode::Sym => [0, 0],
                _ => super::known_words(r, cx, sc.order[*p as usize])?
                    .0
                    .unwrap_or([0, 0]),
            };
            sc.bases.push(o & *m);
            *m &= !(z | o);
        }
        sc.syms = front;
        sc.above_inputs();
        // A value the root differs at: of places that may not take it together, no answer.
        return Ok(match enumerated(r, cx, sc, k)? {
            Some(None) => Some(true),
            _ => None,
        });
    }
    sc.bases.clear();
    sc.above(None);
    let Some(missed) = enumerated(r, cx, sc, k)? else {
        return Ok(None);
    };
    let Some(p) = missed else {
        return Ok(Some(true));
    };
    // The symbols' values there are an input the root is not `k` at: kept, for the candidates
    // after this one that differ there too (an obfuscator builds one value from another, and
    // a chain of them that are `k` but for one value of a 16-bit field was enumerated up to
    // that value at every link).
    let mut left = p;
    let fixed = sc
        .syms
        .iter()
        .map(|&(place, m)| {
            let s = sc.order[place as usize];
            let v = spread(&mut left, m);
            (s, BitVec::wrapping_from_u64(cx.width_of(s), v))
        })
        .collect();
    note_witness(r, cx, fixed);
    // A value of the symbols the root differs at: a refutation.
    Ok(Some(false))
}

/// The enumeration of [`exhaustive`] over the places of `sc.syms`, each at its base (of
/// `sc.bases`, zero where there is none) with every value of its bits there, of the places
/// `sc.kept`: the first point the root is not `k` at (`Some(None)` when it is `k` at all of
/// them), or `None` when the points would cost more than [`EXHAUSTIVE_SHARE`] or the steps
/// left.
fn enumerated(
    r: &mut Runner<'_, '_>,
    cx: &Context,
    sc: &mut Exhaust,
    k: &crate::BitVec,
) -> Result<Option<Option<u64>>, Stop> {
    use crate::BitVec;
    let total: u32 = sc.syms.iter().map(|(_, m)| m.count_ones()).sum();
    let points = 1u64 << total;
    let word = sc.program(cx);
    // A word program's evaluation costs a fraction of a generic one's (measured, see
    // [`WORD_EVALS`]); charged as that many generic evaluations.
    let rate = if word { WORD_EVALS } else { 1 };
    let len = sc.kept.len();
    let cost = |n: u64| n.saturating_mul(len as u64).div_ceil(rate);
    let mut meter = Steps::new(r, EXHAUSTIVE_SHARE);
    if cost(points) > certify::Meter::left(&meter) {
        return Ok(None);
    }
    let ku = k.to_u64();
    // The point the enumeration ended at, where the root differs.
    let missed = if word {
        sc.lanes_for(points);
        first_miss(&mut meter, total, &cost, |span| {
            Ok(match span {
                Span::At(points) => sc.miss_at(points, ku),
                Span::From(start, count) => sc.miss_from(start, count, ku),
            })
        })
    } else {
        let sc = &*sc;
        let mut vals: Vec<BitVec> = vec![BitVec::zero(crate::Width::W1); len];
        // Whether the root is `k` at point `p`, its bits spread over each input's bits that
        // reach the root.
        let mut agrees = |p: u64| -> Result<bool, Stop> {
            let mut left = p;
            for (j, &(place, m)) in sc.syms.iter().enumerate() {
                let v = sc.bases.get(j).copied().unwrap_or(0) | spread(&mut left, m);
                let s = sc.order[place as usize];
                vals[sc.slot[place as usize] as usize] =
                    BitVec::wrapping_from_u64(cx.width_of(s), v);
            }
            for (slot, &place) in sc.kept.iter().enumerate() {
                if sc.input[place as usize] {
                    continue;
                }
                // A symbol that is no input: zero, as in the word program.
                vals[slot] = cx
                    .eval_node(
                        sc.order[place as usize],
                        |j| vals[sc.slot[sc.place[j as usize] as usize] as usize],
                        |_, w| Some(BitVec::zero(w)),
                    )
                    .map_err(Stop::Error)?;
            }
            Ok(vals[len - 1] == *k)
        };
        first_miss(&mut meter, total, &cost, |span| {
            match span {
                Span::At(points) => {
                    for &p in points {
                        if !agrees(p)? {
                            return Ok(Some(p));
                        }
                    }
                }
                Span::From(start, count) => {
                    for p in start..start + count {
                        if !agrees(p)? {
                            return Ok(Some(p));
                        }
                    }
                }
            }
            Ok(None)
        })
    };
    Ok(Some(missed?))
}

/// The low bits of `left`, one for each bit of `m` from its lowest, at `m`'s bits; they are
/// taken from `left`.
fn spread(left: &mut u64, m: u64) -> u64 {
    let (mut v, mut mm) = (0u64, m);
    while mm != 0 {
        if *left & 1 == 1 {
            v |= mm & mm.wrapping_neg();
        }
        *left >>= 1;
        mm &= mm - 1;
    }
    v
}

/// The points [`first_miss`] asks about at once: the ones listed, or `.1` of them from `.0` up.
enum Span<'a> {
    At(&'a [u64]),
    From(u64, u64),
}

/// The first point of [`exhaustive`]'s enumeration of `2^total` that `miss` finds in a span
/// (the first of the span the root is not `k` at), each span charged to `meter` by `cost`
/// before it is asked about.
fn first_miss(
    meter: &mut Steps<'_, '_, '_>,
    total: u32,
    cost: &dyn Fn(u64) -> u64,
    mut miss: impl FnMut(Span<'_>) -> Result<Option<u64>, Stop>,
) -> Result<Option<u64>, Stop> {
    let points = 1u64 << total;
    let mut missed: Option<u64> = None;
    // The points a candidate that is not `k` most often differs at, before the enumeration is
    // paid for: each bit alone, all of them, and a few mixed. The samples leave candidates that
    // are `k` unless some one bit is set, and counting up from zero reaches an input's top bit
    // only at half the points (87 of 98 enumerations in one measured question ended there, and
    // were four fifths of its sweep's steps).
    if total > EXHAUSTIVE_SCREEN_BITS {
        let mixed = (1..=EXHAUSTIVE_MIXED)
            .map(|j: u64| j.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> (64 - total));
        let mut probes = [0u64; (EXHAUSTIVE_BITS as usize) + 1 + (EXHAUSTIVE_MIXED as usize)];
        let mut count = 0usize;
        for p in (0..total)
            .map(|j| 1u64 << j)
            .chain(std::iter::once(points - 1))
            .chain(mixed)
        {
            probes[count] = p;
            count += 1;
        }
        certify::Meter::charge(meter, cost(u64::from(total) + 1 + EXHAUSTIVE_MIXED))?;
        missed = miss(Span::At(&probes[..count]))?;
    }
    let mut start = 0u64;
    while missed.is_none() && start < points {
        let n = EXHAUSTIVE_BLOCK.min(points - start);
        certify::Meter::charge(meter, cost(n))?;
        missed = miss(Span::From(start, n))?;
        start += n;
    }
    Ok(missed)
}

/// An input at which a candidate of the opaque-constant sweep was found to differ from what
/// its samples showed: the symbols it fixes (every other symbol has its value at one of the
/// verification points), and the nodes evaluated at it so far. The samples are few, and a value
/// that is constant but for one input of `2^16` is constant on all of them; what tells it
/// from a constant is that input, and it tells the same of every node built on that value.
#[derive(Default)]
pub(crate) struct Witness {
    fixed: crate::hash::IdMap<u32, crate::BitVec>,
    point: usize,
    vals: crate::hash::IdMap<u32, crate::BitVec>,
}

/// The most witnesses a call keeps.
const WITNESSES: usize = 32;

/// Keeps the input that gives the symbols `fixed` their values there as a witness of the call.
fn note_witness(r: &mut Runner<'_, '_>, cx: &Context, fixed: Vec<(u32, crate::BitVec)>) {
    if r.mba.witnesses.len() >= WITNESSES {
        return;
    }
    // A symbol's value agrees with what the host declared of it, as its samples do.
    let fixed: crate::hash::IdMap<u32, crate::BitVec> = fixed
        .into_iter()
        .map(|(s, v)| (s, cx.declared_at(s).map_or(v, |d| d.fit(&v))))
        .collect();
    if r.mba.witnesses.iter().any(|w| w.fixed == fixed) {
        return;
    }
    r.mba.witnesses.push(Witness {
        fixed,
        point: 2 + r.mba.witnesses.len(),
        vals: crate::hash::IdMap::default(),
    });
}

/// Whether `n` is not `k` at one of the call's witnesses (each node is evaluated once at
/// each, charged as pass work).
fn witnessed(
    r: &mut Runner<'_, '_>,
    cx: &Context,
    n: u32,
    k: &crate::BitVec,
) -> Result<bool, Stop> {
    for w in 0..r.mba.witnesses.len() {
        let mut wit = std::mem::take(&mut r.mba.witnesses[w]);
        let mut work = 0u64;
        let mut out = Ok(());
        let mut stack: Vec<(u32, bool)> = vec![(n, false)];
        while let Some((i, expanded)) = stack.pop() {
            if wit.vals.contains_key(&i) {
                continue;
            }
            if !expanded {
                stack.push((i, true));
                for c in cx.node(i).children() {
                    if !wit.vals.contains_key(&c) {
                        stack.push((c, false));
                    }
                }
                continue;
            }
            work += 1;
            let v = match wit.fixed.get(&i) {
                Some(v) => Ok(*v),
                None => {
                    let seed = cx.meta[i as usize].shash;
                    let declared = cx.declared_at(i);
                    cx.eval_node(
                        i,
                        |j| wit.vals[&j],
                        |_, w| {
                            let v = crate::engine::point_value(seed, w, wit.point);
                            Some(declared.map_or(v, |d| d.fit(&v)))
                        },
                    )
                }
            };
            match v {
                Ok(v) => {
                    wit.vals.insert(i, v);
                }
                Err(e) => {
                    out = Err(Stop::Error(e));
                    break;
                }
            }
        }
        let differs = wit.vals.get(&n).is_some_and(|v| v != k);
        r.mba.witnesses[w] = wit;
        r.meter.charge(Counter::PassWork, work)?;
        out?;
        if differs {
            return Ok(true);
        }
    }
    Ok(false)
}

/// The fewest bits [`exhaustive`] screens an enumeration of (fewer are as cheap to enumerate).
const EXHAUSTIVE_SCREEN_BITS: u32 = 6;

/// The mixed points of [`exhaustive`]'s screen.
const EXHAUSTIVE_MIXED: u64 = 16;

/// The points [`exhaustive`] is charged for at a time.
const EXHAUSTIVE_BLOCK: u64 = 1 << 10;

/// No place: of a node that is not evaluated.
const NO_PLACE: u32 = u32::MAX;

/// A node of the DAG below [`exhaustive`]'s root, with its operands' places in that DAG's order.
type Placed = (crate::expr::Node, [u32; 3]);

/// [`exhaustive`]'s working storage, the call's. A sweep asks it of thousands of candidates
/// over one DAG, each time of the DAG below the candidate, and most enumerate nothing: tables
/// keyed by node, built for each, were most of what those cost. What is kept per node while the
/// DAG is read is in tables over the arena that are left clear (or stamped, never cleared), and
/// everything after is indexed by a node's place among those read.
#[derive(Default)]
pub(crate) struct Exhaust {
    /// Per arena node: whether the sweep under way has met it and not yet reached it (a bit
    /// each, and a bit for each word of those that has one set), and the bits of it found to
    /// reach the root so far. All zero between sweeps.
    marks: Vec<u64>,
    heads: Vec<u64>,
    reach: Vec<u64>,
    /// Per arena node: its place in `order`, of the nodes in it.
    place: Vec<u32>,
    /// Per arena node: the walk that met it last.
    met: Vec<u32>,
    walk: u32,
    stack: Vec<(u32, bool)>,
    /// The DAG below the root, operands first (the root last).
    order: Vec<u32>,
    /// Each node of `order`, with its operands' places.
    below: Vec<Placed>,
    /// The bits of each that reach the root.
    demand: Vec<u64>,
    /// The places enumerated (the symbols, a bottleneck, or a cut of several places), with the
    /// bits enumerated of each; and for each, the bits set in every value enumerated of it
    /// (none, for all zero).
    syms: Vec<(u32, u64)>,
    bases: Vec<u64>,
    /// Of [`bottleneck`]: whether a place is on a demanded path from a symbol to the root, and
    /// the steps of those paths that begin to pass over places at each place, less those that
    /// cease to.
    live: Vec<bool>,
    over: Vec<u32>,
    /// The places evaluated (all, or those the root reads without passing below a
    /// bottleneck), and each place's index among them ([`NO_PLACE`] of the others).
    kept: Vec<u32>,
    slot: Vec<u32>,
    /// Whether a place is enumerated.
    input: Vec<bool>,
    /// The places evaluated as a program over words (see [`Exhaust::program`]).
    prog: Vec<Ins>,
    /// Per place evaluated: whether its value is the same at every point (1; 2 when an
    /// instruction reads it as lanes), and the value.
    fixed: Vec<(u8, u64)>,
    /// Per place evaluated: the place whose lanes hold its values (its own, or those of the
    /// operand it is at every point: a zero extension's), and the root's.
    home: Vec<u32>,
    root: usize,
    /// The places enumerated that take more than one value: index among those evaluated, the
    /// bits enumerated and the bits set in every value.
    inputs: Vec<(u32, u64, u64)>,
    /// For each of `inputs`, its bits at the first `most` points.
    spreads: Vec<u64>,
    /// The values of every place evaluated at the `width` points of a pass, a place's side by
    /// side; `most` is the widest pass of the enumeration under way.
    lanes: Vec<u64>,
    width: usize,
    most: usize,
}

/// What [`Exhaust::sweep`] came to.
#[derive(PartialEq)]
enum Swept {
    /// The whole DAG.
    Whole,
    /// A node of more than 64 bits.
    Wide,
    /// More bits of the symbols than are enumerated, and no bottleneck.
    Open,
    /// An operand numbered after its user.
    Unordered,
}

/// The bits of each operand of `n` that reach its bits `m` (a superset; of the operand's width
/// or more), given to `give` by the operand's index. `konst` is an operand's value where it is
/// a constant, `wide` its width.
fn demanded(
    n: &crate::expr::Node,
    m: u64,
    konst: impl Fn(usize) -> Option<u64>,
    wide: impl Fn(usize) -> u16,
    mut give: impl FnMut(usize, u64),
) {
    let ones = |w: u16| if w >= 64 { u64::MAX } else { (1u64 << w) - 1 };
    let w = n.width;
    let low_prefix = ones(64 - m.leading_zeros() as u16);
    match n.op {
        OpCode::And | OpCode::Or => {
            for (c, o) in [(0, 1), (1, 0)] {
                let d = match (konst(o), n.op) {
                    (Some(k), OpCode::And) => m & k,
                    (Some(k), _) => m & !k,
                    _ => m,
                };
                give(c, d);
            }
        }
        OpCode::Xor => {
            give(0, m);
            give(1, m);
        }
        OpCode::Not => give(0, m),
        OpCode::Add | OpCode::Sub | OpCode::Mul => {
            give(0, low_prefix);
            give(1, low_prefix);
        }
        OpCode::Neg => give(0, low_prefix),
        OpCode::Shl | OpCode::LShr if konst(1).is_some_and(|s| s < u64::from(w)) => {
            let s = konst(1).unwrap_or(0);
            give(
                0,
                if n.op == OpCode::Shl {
                    m >> s
                } else {
                    (m << s) & ones(w)
                },
            );
            give(1, u64::MAX);
        }
        OpCode::Zext => give(0, m),
        // A `select` reads its condition, and of its arms the bits read of it.
        OpCode::Select => {
            give(0, 1);
            give(1, m);
            give(2, m);
        }
        // An operand of more than 64 bits keeps its low 64 in the mask: a slice at 64 or above
        // reads none of them (the sweep stops at that operand).
        OpCode::Extract => give(0, m.checked_shl(n.b).unwrap_or(0)),
        // a rotate by a constant moves the demand the other way; a `concat`
        // splits it between its halves.
        OpCode::RotL | OpCode::RotR if konst(1).is_some() && w <= 64 && w > 0 => {
            let s = (konst(1).unwrap_or(0) % u64::from(w)) as u32;
            let rot = |v: u64, by: u32, left: bool| {
                let by = by % u32::from(w);
                if by == 0 {
                    return v;
                }
                let v = v & ones(w);
                if left {
                    ((v << by) | (v >> (u32::from(w) - by))) & ones(w)
                } else {
                    ((v >> by) | (v << (u32::from(w) - by))) & ones(w)
                }
            };
            give(0, rot(m, s, n.op == OpCode::RotR));
            give(1, u64::MAX);
        }
        OpCode::Concat => {
            let wl = wide(1);
            give(1, m & ones(wl));
            give(0, if wl >= 64 { 0 } else { m >> wl });
        }
        _ => {
            for j in 0..n.op.arity() {
                give(j, u64::MAX);
            }
        }
    }
}

/// The value of a constant node of at most 64 bits (which is stored in the node).
fn word_of(cx: &Context, i: u32, n: &crate::expr::Node) -> Option<u64> {
    if n.op != OpCode::Const {
        return None;
    }
    if n.aux & crate::expr::AUX_POOLED != 0 {
        return cx.const_val(i).and_then(|v| v.to_u64());
    }
    Some(u64::from(n.a) | (u64::from(n.b) << 32))
}

std::thread_local! {
    /// The arena-sized buffers of the last call on this thread that used them (see
    /// [`Exhaust::ready`]).
    static EXHAUST_FREE: core::cell::RefCell<Option<Exhaust>> =
        const { core::cell::RefCell::new(None) };
}

impl Exhaust {
    /// Takes this thread's kept buffers when these have none yet. They are sized to the
    /// arena (a mark, a demand and a place per node) and are all zero between sweeps, which a
    /// sweep restores before it returns; in a context kept across calls, making them anew
    /// was a fill of the whole arena per call.
    fn ready(&mut self) {
        if self.reach.is_empty()
            && self.met.is_empty()
            && let Ok(Some(kept)) = EXHAUST_FREE.try_with(|f| f.borrow_mut().take())
        {
            *self = kept;
        }
    }

    /// Keeps `ex`'s buffers for the next call on this thread (the larger of two).
    fn keep(ex: Exhaust) {
        if ex.reach.is_empty() && ex.met.is_empty() {
            return;
        }
        let _ = EXHAUST_FREE.try_with(|f| {
            let mut g = f.borrow_mut();
            if g.as_ref()
                .is_none_or(|o| o.reach.len() + o.met.len() <= ex.reach.len() + ex.met.len())
            {
                *g = Some(ex);
            }
        });
    }

    /// The DAG below `root` into `order` and `below`, operands first, with the bits of each
    /// node that reach the root in `demand`, and the symbols with theirs. A node is numbered
    /// after its operands, so from the highest number down every node comes after its users,
    /// with all the bits they read of it: one pass, no walk. Stops short at a node of more than
    /// 64 bits, and where no enumeration can follow: more than [`EXHAUSTIVE_BITS`] bits of the
    /// symbols already reach the root, and no node reached so far but the root has as few of
    /// its own. (A [`bottleneck`] is such a node on every demanded path from the symbols to the
    /// root; a node not yet reached is not on the path that gave a symbol its bits.)
    fn sweep(&mut self, cx: &Context, root: u32) -> Swept {
        let ones = |w: u16| if w >= 64 { u64::MAX } else { (1u64 << w) - 1 };
        let len = cx.nodes.len();
        if self.reach.len() < len {
            self.reach.resize(len, 0);
            self.place.resize(len, 0);
            self.marks.resize(len.div_ceil(64), 0);
            self.heads.resize(len.div_ceil(64).div_ceil(64), 0);
        }
        let Exhaust {
            marks,
            heads,
            reach,
            place,
            order,
            below,
            demand,
            syms,
            ..
        } = self;
        order.clear();
        below.clear();
        demand.clear();
        syms.clear();
        // The highest node marked at or below word `at`, unmarked.
        fn next(marks: &mut [u64], heads: &mut [u64], at: &mut usize) -> u32 {
            if marks[*at] == 0 {
                let mut h = *at / 64;
                let mut word = heads[h] & (u64::MAX >> (63 - *at % 64));
                while word == 0 {
                    h -= 1;
                    word = heads[h];
                }
                *at = h * 64 + 63 - word.leading_zeros() as usize;
            }
            let bit = 63 - marks[*at].leading_zeros();
            marks[*at] &= !(1u64 << bit);
            if marks[*at] == 0 {
                heads[*at / 64] &= !(1u64 << (*at % 64));
            }
            (*at * 64) as u32 + bit
        }
        let mut at = root as usize / 64;
        marks[at] |= 1u64 << (root % 64);
        heads[at / 64] |= 1u64 << (at % 64);
        reach[root as usize] = ones(cx.node(root).width);
        // The nodes marked, the symbols' bits that reach the root so far, and whether a node
        // that could be a bottleneck was met.
        let (mut marked, mut bits, mut narrow) = (1usize, 0u32, false);
        let mut out = Swept::Whole;
        'nodes: while marked > 0 {
            let i = next(marks, heads, &mut at);
            marked -= 1;
            let n = cx.node(i);
            let m = std::mem::take(&mut reach[i as usize]);
            if n.width > 64 {
                out = Swept::Wide;
                break;
            }
            order.push(i);
            below.push((n, [0; 3]));
            demand.push(m);
            let kids = [n.a, n.b, n.c];
            let arity = n.op.arity();
            for &c in &kids[..arity] {
                if c >= i {
                    out = Swept::Unordered;
                    break 'nodes;
                }
                let (word, bit) = (c as usize / 64, 1u64 << (c % 64));
                marked += usize::from(marks[word] & bit == 0);
                marks[word] |= bit;
                heads[word / 64] |= 1u64 << (word % 64);
            }
            if m == 0 || arity == 0 {
                continue;
            }
            narrow |= i != root && m.count_ones() <= EXHAUSTIVE_BITS;
            demanded(
                &n,
                m,
                |j| word_of(cx, kids[j], &cx.node(kids[j])),
                |j| cx.node(kids[j]).width,
                |j, d| {
                    let c = cx.node(kids[j]);
                    let had = reach[kids[j] as usize];
                    let now = had | (d & ones(c.width));
                    if c.op == OpCode::Sym {
                        bits += now.count_ones() - had.count_ones();
                    }
                    reach[kids[j] as usize] = now;
                },
            );
            if bits > EXHAUSTIVE_BITS && !narrow {
                out = Swept::Open;
                break;
            }
        }
        while marked > 0 {
            let i = next(marks, heads, &mut at);
            reach[i as usize] = 0;
            marked -= 1;
        }
        if out != Swept::Whole {
            return out;
        }
        order.reverse();
        below.reverse();
        demand.reverse();
        for (p, &i) in order.iter().enumerate() {
            place[i as usize] = p as u32;
        }
        for (p, (n, kids)) in below.iter_mut().enumerate() {
            for (k, c) in n.children().enumerate() {
                kids[k] = place[c as usize];
            }
            if n.op == OpCode::Sym {
                syms.push((p as u32, demand[p]));
            }
        }
        out
    }

    /// The DAG below `root` into `order` and `below`, operands first, in the order a walk from
    /// the root leaves its nodes; `false` at a node of more than 64 bits.
    fn walk(&mut self, cx: &Context, root: u32) -> bool {
        if self.met.len() < cx.nodes.len() {
            self.met.resize(cx.nodes.len(), 0);
        }
        if self.place.len() < cx.nodes.len() {
            self.place.resize(cx.nodes.len(), 0);
        }
        self.walk = self.walk.wrapping_add(1);
        if self.walk == 0 {
            self.met.fill(0);
            self.walk = 1;
        }
        let walk = self.walk;
        self.order.clear();
        self.below.clear();
        self.stack.clear();
        self.stack.push((root, false));
        while let Some((i, expanded)) = self.stack.pop() {
            let n;
            if expanded {
                n = cx.node(i);
            } else {
                if self.met[i as usize] == walk {
                    continue;
                }
                self.met[i as usize] = walk;
                n = cx.node(i);
                if n.width > 64 {
                    return false;
                }
                if n.op.arity() != 0 {
                    self.stack.push((i, true));
                    for c in n.children() {
                        if self.met[c as usize] != walk {
                            self.stack.push((c, false));
                        }
                    }
                    continue;
                }
            }
            let mut kids = [0u32; 3];
            for (k, c) in n.children().enumerate() {
                kids[k] = self.place[c as usize];
            }
            self.place[i as usize] = self.order.len() as u32;
            self.order.push(i);
            self.below.push((n, kids));
        }
        true
    }

    /// The bits of each node of a [`walk`](Exhaust::walk) that reach the root, from the root
    /// down, and the symbols with theirs.
    fn demands(&mut self, cx: &Context) {
        let ones = |w: u16| if w >= 64 { u64::MAX } else { (1u64 << w) - 1 };
        let (order, below, demand) = (&self.order, &self.below, &mut self.demand);
        let last = below.len() - 1;
        demand.clear();
        demand.resize(below.len(), 0);
        demand[last] = ones(below[last].0.width);
        for idx in (0..=last).rev() {
            let m = demand[idx];
            if m == 0 {
                continue;
            }
            let (n, kids) = &below[idx];
            demanded(
                n,
                m,
                |j| word_of(cx, order[kids[j] as usize], &below[kids[j] as usize].0),
                |j| below[kids[j] as usize].0.width,
                |j, d| demand[kids[j] as usize] |= d & ones(below[kids[j] as usize].0.width),
            );
        }
        self.syms.clear();
        for (idx, (n, _)) in below.iter().enumerate() {
            if n.op == OpCode::Sym {
                self.syms.push((idx as u32, demand[idx]));
            }
        }
    }

    /// The places evaluated into `kept` and `slot`: every place, or with a bottleneck at `cut`
    /// the ones the root reads without passing below it.
    fn above(&mut self, cut: Option<usize>) {
        let n = self.below.len();
        self.kept.clear();
        self.slot.clear();
        let Some(cut) = cut else {
            self.kept.extend(0..n as u32);
            self.slot.extend(0..n as u32);
            return;
        };
        // Users first: a place read is marked before it is reached.
        self.slot.resize(n, NO_PLACE);
        self.slot[n - 1] = 0;
        for p in (0..n).rev() {
            if self.slot[p] == NO_PLACE || p == cut {
                continue;
            }
            let (node, kids) = self.below[p];
            for &c in &kids[..node.op.arity()] {
                self.slot[c as usize] = 0;
            }
        }
        for p in 0..n {
            if self.slot[p] != NO_PLACE {
                self.slot[p] = self.kept.len() as u32;
                self.kept.push(p as u32);
            }
        }
    }

    /// [`above`](Exhaust::above) with the places of `syms` for the cut (see [`frontier`]): the
    /// places the root reads without passing below one of them.
    fn above_inputs(&mut self) {
        let n = self.below.len();
        self.kept.clear();
        self.slot.clear();
        self.input.clear();
        self.input.resize(n, false);
        for &(p, _) in &self.syms {
            self.input[p as usize] = true;
        }
        self.slot.resize(n, NO_PLACE);
        self.slot[n - 1] = 0;
        for p in (0..n).rev() {
            if self.slot[p] == NO_PLACE || self.input[p] {
                continue;
            }
            let (node, kids) = self.below[p];
            for &c in &kids[..node.op.arity()] {
                self.slot[c as usize] = 0;
            }
        }
        for p in 0..n {
            if self.slot[p] != NO_PLACE {
                self.slot[p] = self.kept.len() as u32;
                self.kept.push(p as u32);
            }
        }
    }

    /// The places evaluated (operands first, every node at most 64 bits) as a program over
    /// `u64` words, each instruction with its node's width mask; `false` when an operator is
    /// not one it evaluates. A place enumerated is given its words before each run; a value
    /// that is the same at every point (a constant, a symbol past a bottleneck, a place
    /// enumerated with no bit unknown, which is its base) is an instruction's operand where the
    /// instruction has a form that takes one, and is written out once otherwise.
    fn program(&mut self, cx: &Context) -> bool {
        use crate::{BinOp, CmpOp, UnOp};
        let ones = |w: u16| if w >= 64 { u64::MAX } else { (1u64 << w) - 1 };
        let Exhaust {
            order,
            below,
            syms,
            bases,
            kept,
            slot,
            input,
            prog,
            fixed,
            home,
            inputs,
            ..
        } = self;
        prog.clear();
        inputs.clear();
        fixed.clear();
        fixed.resize(kept.len(), (0, 0));
        home.clear();
        home.extend(0..kept.len() as u32);
        input.clear();
        input.resize(below.len(), false);
        for (j, &(p, m)) in syms.iter().enumerate() {
            input[p as usize] = true;
            let s = slot[p as usize];
            let base = bases.get(j).copied().unwrap_or(0);
            if m == 0 {
                fixed[s as usize] = (1, base);
            } else {
                inputs.push((s, m, base));
            }
        }
        // An operand read as lanes: one that is the same at every point is written out.
        fn lane(fixed: &mut [(u8, u64)], s: u32) -> u32 {
            if fixed[s as usize].0 == 1 {
                fixed[s as usize].0 = 2;
            }
            s
        }
        let known = |fixed: &[(u8, u64)], s: u32| {
            let (is, v) = fixed[s as usize];
            (is != 0).then_some(v)
        };
        for (s, &p) in kept.iter().enumerate() {
            if input[p as usize] {
                continue;
            }
            let (n, kids) = below[p as usize];
            let (w, mask) = (u32::from(n.width), ones(n.width));
            if w == 0 {
                return false;
            }
            let wide = |j: usize| below[kids[j] as usize].0.width;
            let arg = |j: usize| home[slot[kids[j] as usize] as usize];
            // A node that is its operand `j` at every point: the operand's lanes, or its value.
            macro_rules! same {
                ($j:expr) => {{
                    let a = arg($j);
                    match known(fixed, a) {
                        Some(v) => fixed[s] = (1, v),
                        None => home[s] = a,
                    }
                    continue;
                }};
            }
            let ins = |kind: Kind, sh: u32, a: u32, b: u32, c: u32, k: u64| Ins {
                kind,
                sh,
                dst: s as u32,
                a,
                b,
                c,
                mask,
                k,
            };
            let one = |fixed: &mut [(u8, u64)], kind: Kind, sh: u32, k: u64| {
                ins(kind, sh, lane(fixed, arg(0)), 0, 0, k)
            };
            let two = |fixed: &mut [(u8, u64)], kind: Kind, sh: u32| {
                ins(kind, sh, lane(fixed, arg(0)), lane(fixed, arg(1)), 0, 0)
            };
            let i = match n.op {
                // A symbol past a bottleneck cut that is no input reaches the root only through
                // a node with no demanded bits: any value, zero as the uncut enumeration gives it.
                OpCode::Sym => {
                    fixed[s] = (1, 0);
                    continue;
                }
                OpCode::Const => {
                    let Some(v) = word_of(cx, order[p as usize], &n) else {
                        return false;
                    };
                    fixed[s] = (1, v & mask);
                    continue;
                }
                OpCode::Zext => same!(0),
                OpCode::Sext => one(fixed, Kind::Sext, u32::from(wide(0)), 0),
                OpCode::Extract => one(fixed, Kind::Extract, u32::from(n.b as u16), 0),
                OpCode::Select => {
                    let (c, t, f) = (
                        lane(fixed, arg(0)),
                        lane(fixed, arg(1)),
                        lane(fixed, arg(2)),
                    );
                    ins(Kind::Select, 0, c, t, f, 0)
                }
                // `concat(hi, lo)`, shifted by the low half's width.
                OpCode::Concat if wide(1) >= 64 => same!(1),
                OpCode::Concat => two(fixed, Kind::Concat, u32::from(wide(1))),
                op => {
                    if let Some(u) = op.as_un() {
                        match u {
                            UnOp::Not => one(fixed, Kind::Not, 0, 0),
                            UnOp::Neg => one(fixed, Kind::Neg, 0, 0),
                            _ => return false,
                        }
                    } else if let Some(b) = op.as_bin() {
                        let (x, y) = (known(fixed, arg(0)), known(fixed, arg(1)));
                        // The other operand's lanes, with the known one as the instruction's.
                        let with = |fixed: &mut [(u8, u64)], kind: Kind, plain: Kind| match (x, y) {
                            (_, Some(y)) => ins(kind, 0, lane(fixed, arg(0)), 0, 0, y),
                            (Some(x), _) => ins(kind, 0, lane(fixed, arg(1)), 0, 0, x),
                            _ => two(fixed, plain, 0),
                        };
                        match (b, y) {
                            (BinOp::Add, _) => with(fixed, Kind::AddK, Kind::Add),
                            (BinOp::Mul, _) => with(fixed, Kind::MulK, Kind::Mul),
                            (BinOp::And, _) => with(fixed, Kind::AndK, Kind::And),
                            (BinOp::Or, _) => with(fixed, Kind::OrK, Kind::Or),
                            (BinOp::Xor, _) => with(fixed, Kind::XorK, Kind::Xor),
                            (BinOp::Sub, Some(y)) => one(fixed, Kind::AddK, 0, y.wrapping_neg()),
                            (BinOp::Sub, None) => match x {
                                Some(x) => ins(Kind::RSubK, 0, lane(fixed, arg(1)), 0, 0, x),
                                None => two(fixed, Kind::Sub, 0),
                            },
                            // A count of the width or more leaves nothing.
                            (BinOp::Shl | BinOp::LShr, Some(y)) if y >= u64::from(w) => {
                                fixed[s] = (1, 0);
                                continue;
                            }
                            (BinOp::Shl, Some(y)) => one(fixed, Kind::ShlK, y as u32, 0),
                            (BinOp::LShr, Some(y)) => one(fixed, Kind::LShrK, y as u32, 0),
                            (BinOp::AShr, Some(y)) => {
                                one(fixed, Kind::AShrK, y.min(u64::from(w) - 1) as u32, 0)
                            }
                            (BinOp::RotL | BinOp::RotR, Some(y)) => {
                                let by = (y % u64::from(w)) as u32;
                                let by = if b == BinOp::RotR { (w - by) % w } else { by };
                                match by {
                                    0 => same!(0),
                                    _ => one(fixed, Kind::RotK, by, 0),
                                }
                            }
                            (BinOp::Shl, None) => two(fixed, Kind::Shl, 0),
                            (BinOp::LShr, None) => two(fixed, Kind::LShr, 0),
                            (BinOp::AShr, None) => two(fixed, Kind::AShr, 0),
                            (BinOp::RotL, None) => two(fixed, Kind::RotL, 0),
                            (BinOp::RotR, None) => two(fixed, Kind::RotR, 0),
                            _ => return false,
                        }
                    } else {
                        let Some(c) = op.as_cmp() else {
                            return false;
                        };
                        let (x, y) = (known(fixed, arg(0)), known(fixed, arg(1)));
                        let wa = u32::from(wide(0));
                        match (c, x, y) {
                            (CmpOp::Eq, _, Some(y)) => one(fixed, Kind::EqK, 0, y),
                            (CmpOp::Ne, _, Some(y)) => one(fixed, Kind::NeK, 0, y),
                            (CmpOp::Eq, Some(x), _) => {
                                ins(Kind::EqK, 0, lane(fixed, arg(1)), 0, 0, x)
                            }
                            (CmpOp::Ne, Some(x), _) => {
                                ins(Kind::NeK, 0, lane(fixed, arg(1)), 0, 0, x)
                            }
                            (CmpOp::Eq, ..) => two(fixed, Kind::Eq, 0),
                            (CmpOp::Ne, ..) => two(fixed, Kind::Ne, 0),
                            (CmpOp::Ult, ..) => two(fixed, Kind::Ult, 0),
                            (CmpOp::Ule, ..) => two(fixed, Kind::Ule, 0),
                            (CmpOp::Slt, ..) => two(fixed, Kind::Slt, wa),
                            (CmpOp::Sle, ..) => two(fixed, Kind::Sle, wa),
                        }
                    }
                }
            };
            prog.push(i);
        }
        // The root's lanes are read at every point.
        self.root = lane(fixed, home[kept.len() - 1]) as usize;
        true
    }

    /// Sets the most points a pass of the program evaluates, for an enumeration of `points`.
    fn lanes_for(&mut self, points: u64) {
        let len = self.kept.len();
        let fit = (EXHAUSTIVE_LANE_WORDS / len).clamp(1, EXHAUSTIVE_LANES);
        // A power of two, as `points` is: a block is whole passes.
        let most = (1usize << fit.ilog2()).min(usize::try_from(points).unwrap_or(usize::MAX));
        self.most = most;
        self.width = 0;
        if self.lanes.len() < len * most {
            self.lanes.resize(len * most, 0);
        }
        // The inputs' bits at the first `most` points: at a point `p + l` past a multiple `p`
        // of `most`, an input's are its bits at `p` with its bits at `l`. Counted up in the
        // inputs' bits (`(v | !m) + 1 & m` is the next value of the bits `m`, zero after the
        // last, when the next input counts).
        self.spreads.clear();
        self.spreads.resize(self.inputs.len() * most, 0);
        for l in 1..most {
            let mut carry = true;
            for (j, &(_, m, _)) in self.inputs.iter().enumerate() {
                let was = self.spreads[j * most + l - 1];
                let now = if carry {
                    (was | !m).wrapping_add(1) & m
                } else {
                    was
                };
                carry &= now == 0;
                self.spreads[j * most + l] = now;
            }
        }
    }

    /// Lays the lanes out for passes of `width` points (at most `most`), with the values that
    /// are the same at every point written out.
    fn pass_of(&mut self, width: usize) {
        if self.width == width {
            return;
        }
        self.width = width;
        for (s, &(is, v)) in self.fixed.iter().enumerate() {
            if is == 2 {
                self.lanes[s * width..][..width].fill(v);
            }
        }
    }

    /// The first lane of the first `valid` at which the root is not `k`, after a pass.
    fn differs(&self, valid: usize, k: Option<u64>) -> Option<usize> {
        let Some(k) = k else {
            return Some(0);
        };
        let root = &self.lanes[self.root * self.width..][..valid];
        if root.iter().fold(0, |any, &x| any | (x ^ k)) == 0 {
            return None;
        }
        root.iter().position(|&x| x != k)
    }

    /// The first of `points` the root is not `k` at.
    fn miss_at(&mut self, points: &[u64], k: Option<u64>) -> Option<u64> {
        // A pass no wider than the points: a pass's cost is its width's.
        let width = points.len().min(self.most);
        self.pass_of(width);
        for pass in points.chunks(width) {
            for l in 0..width {
                // A short pass evaluates its last point again.
                let mut left = pass[l.min(pass.len() - 1)];
                for &(s, m, base) in &self.inputs {
                    self.lanes[s as usize * width + l] = base | spread(&mut left, m);
                }
            }
            run_lanes(&self.prog, &mut self.lanes, width);
            if let Some(l) = self.differs(pass.len(), k) {
                return Some(pass[l]);
            }
        }
        None
    }

    /// The first of the `count` points from `start` up the root is not `k` at; `start` is a
    /// multiple of `most`.
    fn miss_from(&mut self, start: u64, count: u64, k: Option<u64>) -> Option<u64> {
        let width = self.most;
        self.pass_of(width);
        let (mut p, end) = (start, start + count);
        while p < end {
            let mut left = p;
            for (j, &(s, m, base)) in self.inputs.iter().enumerate() {
                let at = base | spread(&mut left, m);
                let out = &mut self.lanes[s as usize * width..][..width];
                for (o, &low) in out.iter_mut().zip(&self.spreads[j * width..][..width]) {
                    *o = at | low;
                }
            }
            run_lanes(&self.prog, &mut self.lanes, width);
            let valid = (end - p).min(width as u64) as usize;
            if let Some(l) = self.differs(valid, k) {
                return Some(p + l as u64);
            }
            p += width as u64;
        }
        None
    }
}

/// The most points one pass of a word program evaluates ([`run_lanes`]): a block
/// ([`EXHAUSTIVE_BLOCK`]), and a power of two. An instruction's operator is read once a pass,
/// which is most of what a narrow pass costs: on programs of 30 to 2,000 instructions a point
/// took 0.33 to 0.40 ns an instruction at 64 points a pass, 0.25 to 0.29 ns at 256, and a
/// little less at 1,024.
const EXHAUSTIVE_LANES: usize = EXHAUSTIVE_BLOCK as usize;

/// The words of lanes a pass works in while it can, fewer points at once for a longer program:
/// past a few megabytes a pass was slower for being wider.
const EXHAUSTIVE_LANE_WORDS: usize = 1 << 17;

/// the place of `below` (operands first, the root last) that every demanded path
/// from the symbols to the root passes through, nearest the symbols with at most
/// [`EXHAUSTIVE_BITS`] demanded bits; not the root or a symbol. The root is a function of its
/// demanded bits alone. A reconstructed address can take a few bits of sums over `k - t` and
/// `t + k'`: 22 bits of the two symbols in `t` reach them, 11 bits of `t`.
fn bottleneck(
    below: &[Placed],
    demand: &[u64],
    live: &mut Vec<bool>,
    over: &mut Vec<u32>,
) -> Option<usize> {
    let n = below.len();
    let root = n.checked_sub(1)?;
    live.clear();
    live.resize(n, false);
    over.clear();
    over.resize(n + 1, 0);
    // A place is on a demanded path from a symbol to the root when it has demanded bits and is
    // a symbol or reads a place that is on one. A step of such a path, from a place to one it
    // reads, passes over the places between the two in the order; a symbol's path begins below
    // every place, so passes over all before the symbol. `over` takes one at the first place a
    // step passes over and gives one back past the last.
    for (p, (node, kids)) in below.iter().enumerate() {
        if demand[p] == 0 {
            continue;
        }
        if node.op == OpCode::Sym {
            live[p] = true;
            over[0] = over[0].wrapping_add(1);
            over[p] = over[p].wrapping_sub(1);
            continue;
        }
        for &c in &kids[..node.op.arity()] {
            let c = c as usize;
            if live[c] {
                live[p] = true;
                over[c + 1] = over[c + 1].wrapping_add(1);
                over[p] = over[p].wrapping_sub(1);
            }
        }
    }
    // A place on a demanded path that no step passes over is on every one of them (a path
    // that missed it would step over it); the first such is the nearest the symbols.
    let mut open = 0u32;
    for p in 0..root {
        open = open.wrapping_add(over[p]);
        if open == 0
            && live[p]
            && below[p].0.op != OpCode::Sym
            && demand[p].count_ones() <= EXHAUSTIVE_BITS
        {
            return Some(p);
        }
    }
    None
}

/// The most bits [`exhaustive`] enumerates of a cut of several places (see [`frontier`]), and
/// the most places it reads to find one. A cut is tried after an enumeration over one place
/// failed, and a deeper one costs its points whether or not it decides.
const FRONTIER_BITS: u32 = 10;
const FRONTIER_STEPS: usize = 256;

/// places of `below` (operands first, the root last) that every demanded path from
/// the symbols to the root passes through one of, with at most [`FRONTIER_BITS`] demanded
/// bits between them: each with those bits. The root is a function of the demanded bits of
/// such places alone, so one that is `k` at every value of them is `k`; they are taken as
/// free, where the places may take fewer values together, so a value the root differs at
/// decides nothing. (A [`bottleneck`] is one place; a shift count read from the low bits of a
/// product of a value two unrelated conditions each give one bit of has none that takes only
/// the values it can.)
///
/// The cut starts at the root's operands and moves toward the symbols a place at a time (the
/// place whose operands add the fewest bits first), while that adds no bits or leaves the
/// cut within the limit: the values the root takes over a cut nearer the symbols are among
/// those it takes over one above it, so the deepest cut that can be enumerated decides the
/// most. `mark` is scratch.
fn frontier(below: &[Placed], demand: &[u64], mark: &mut Vec<u32>) -> Option<Vec<(u32, u64)>> {
    let n = below.len();
    let root = n.checked_sub(1)?;
    // 0: not reached; 1: in the cut; 2: above it.
    mark.clear();
    mark.resize(n, 0);
    let bits = |p: usize| demand[p].count_ones() as i64;
    let leaf = |p: usize| matches!(below[p].0.op, OpCode::Sym | OpCode::Const);
    let mut front: Vec<usize> = Vec::new();
    let mut total = 0i64;
    // Moves the cut below `p`: the bits that adds.
    let open = |mark: &mut [u32], front: &mut Vec<usize>, p: usize| -> i64 {
        let (node, kids) = &below[p];
        let mut delta = if mark[p] == 1 { -bits(p) } else { 0 };
        mark[p] = 2;
        front.retain(|&q| q != p);
        for &c in &kids[..node.op.arity()] {
            let c = c as usize;
            if mark[c] == 0 && below[c].0.op != OpCode::Const {
                mark[c] = 1;
                front.push(c);
                delta += bits(c);
            }
        }
        delta
    };
    total += open(mark, &mut front, root);
    for _ in 0..FRONTIER_STEPS {
        // The place of the cut whose operands add the fewest bits; the nearest the root of
        // those.
        let mut best: Option<(i64, usize)> = None;
        for &p in &front {
            if leaf(p) {
                continue;
            }
            let (node, kids) = &below[p];
            let mut delta = -bits(p);
            let mut met = [usize::MAX; 3];
            for (j, &c) in kids[..node.op.arity()].iter().enumerate() {
                let c = c as usize;
                if mark[c] == 0 && below[c].0.op != OpCode::Const && !met.contains(&c) {
                    met[j] = c;
                    delta += bits(c);
                }
            }
            if best.is_none_or(|(d, q)| delta < d || (delta == d && p > q)) {
                best = Some((delta, p));
            }
        }
        let Some((delta, p)) = best else {
            break;
        };
        if delta > 0 && total + delta > i64::from(FRONTIER_BITS) {
            break;
        }
        total += open(mark, &mut front, p);
    }
    if total > i64::from(FRONTIER_BITS) {
        return None;
    }
    front.sort_unstable();
    Some(front.into_iter().map(|p| (p as u32, demand[p])).collect())
}

/// What an instruction of a word program computes ([`Ins`]); the forms in `K` take the
/// instruction's own word for an operand that is the same at every point, or its count for a
/// shift by one.
#[derive(Clone, Copy)]
enum Kind {
    Add,
    Sub,
    Mul,
    And,
    Or,
    Xor,
    Shl,
    LShr,
    AShr,
    RotL,
    RotR,
    AddK,
    /// `k - a`.
    RSubK,
    MulK,
    AndK,
    OrK,
    XorK,
    ShlK,
    LShrK,
    AShrK,
    /// A rotate left by `sh`, neither zero nor the width.
    RotK,
    Not,
    Neg,
    /// From `sh` bits.
    Sext,
    /// From bit `sh` up.
    Extract,
    Eq,
    Ne,
    Ult,
    Ule,
    /// Of `sh` bits.
    Slt,
    Sle,
    EqK,
    NeK,
    /// `a`'s low bit picks `b` or `c`.
    Select,
    /// `a` above the `sh` bits of `b`.
    Concat,
}

/// One instruction of a word program ([`Exhaust::program`]): the place it computes and its
/// operands' are indices among the places evaluated, operands before, and every value is kept
/// masked to its node's width.
#[derive(Clone, Copy)]
struct Ins {
    kind: Kind,
    sh: u32,
    dst: u32,
    a: u32,
    b: u32,
    c: u32,
    mask: u64,
    k: u64,
}

/// Runs a word program at `width` points at once: `lanes` holds `width` words for each place
/// (the inputs' and the fixed values' already set), and each instruction is one loop over its
/// operands' lanes, its operator read once.
fn run_lanes(prog: &[Ins], lanes: &mut [u64], width: usize) {
    #[inline(always)]
    fn one(v: &mut [u64], n: usize, d: u32, a: u32) -> (&mut [u64], &[u64]) {
        let (lo, hi) = v.split_at_mut(d as usize * n);
        (&mut hi[..n], &lo[a as usize * n..][..n])
    }
    #[inline(always)]
    fn two(v: &mut [u64], n: usize, d: u32, a: u32, b: u32) -> (&mut [u64], &[u64], &[u64]) {
        let (lo, hi) = v.split_at_mut(d as usize * n);
        (
            &mut hi[..n],
            &lo[a as usize * n..][..n],
            &lo[b as usize * n..][..n],
        )
    }
    let sext = |v: u64, w: u32| -> i64 {
        let sh = 64 - w;
        ((v << sh) as i64) >> sh
    };
    for i in prog {
        let (m, k, sh) = (i.mask, i.k, i.sh);
        let w = 64 - m.leading_zeros();
        macro_rules! un {
            (|$x:ident| $e:expr) => {{
                let (o, a) = one(lanes, width, i.dst, i.a);
                for (o, &$x) in o.iter_mut().zip(a) {
                    *o = ($e) & m;
                }
            }};
        }
        macro_rules! bin {
            (|$x:ident, $y:ident| $e:expr) => {{
                let (o, a, b) = two(lanes, width, i.dst, i.a, i.b);
                for ((o, &$x), &$y) in o.iter_mut().zip(a).zip(b) {
                    *o = ($e) & m;
                }
            }};
        }
        match i.kind {
            Kind::Add => bin!(|x, y| x.wrapping_add(y)),
            Kind::Sub => bin!(|x, y| x.wrapping_sub(y)),
            Kind::Mul => bin!(|x, y| x.wrapping_mul(y)),
            Kind::And => bin!(|x, y| x & y),
            Kind::Or => bin!(|x, y| x | y),
            Kind::Xor => bin!(|x, y| x ^ y),
            Kind::Shl => bin!(|x, y| if y >= u64::from(w) { 0 } else { x << y }),
            Kind::LShr => bin!(|x, y| if y >= u64::from(w) { 0 } else { x >> y }),
            Kind::AShr => bin!(|x, y| (sext(x, w) >> y.min(u64::from(w) - 1)) as u64),
            Kind::RotL | Kind::RotR => {
                let right = matches!(i.kind, Kind::RotR);
                bin!(|x, y| {
                    let by = (y % u64::from(w)) as u32;
                    let by = if right { (w - by) % w } else { by };
                    if by == 0 {
                        x
                    } else {
                        (x << by) | (x >> (w - by))
                    }
                })
            }
            Kind::AddK => un!(|x| x.wrapping_add(k)),
            Kind::RSubK => un!(|x| k.wrapping_sub(x)),
            Kind::MulK => un!(|x| x.wrapping_mul(k)),
            Kind::AndK => un!(|x| x & k),
            Kind::OrK => un!(|x| x | k),
            Kind::XorK => un!(|x| x ^ k),
            Kind::ShlK => un!(|x| x << sh),
            Kind::LShrK => un!(|x| x >> sh),
            Kind::AShrK => un!(|x| (sext(x, w) >> sh) as u64),
            Kind::RotK => un!(|x| (x << sh) | (x >> (w - sh))),
            Kind::Not => un!(|x| !x),
            Kind::Neg => un!(|x| x.wrapping_neg()),
            Kind::Sext => un!(|x| sext(x, sh) as u64),
            Kind::Extract => un!(|x| x >> sh),
            Kind::Eq => bin!(|x, y| u64::from(x == y)),
            Kind::Ne => bin!(|x, y| u64::from(x != y)),
            Kind::Ult => bin!(|x, y| u64::from(x < y)),
            Kind::Ule => bin!(|x, y| u64::from(x <= y)),
            Kind::Slt => bin!(|x, y| u64::from(sext(x, sh) < sext(y, sh))),
            Kind::Sle => bin!(|x, y| u64::from(sext(x, sh) <= sext(y, sh))),
            Kind::EqK => un!(|x| u64::from(x == k)),
            Kind::NeK => un!(|x| u64::from(x != k)),
            Kind::Concat => bin!(|x, y| (x << sh) | y),
            Kind::Select => {
                let (lo, hi) = lanes.split_at_mut(i.dst as usize * width);
                let o = &mut hi[..width];
                let c = &lo[i.a as usize * width..][..width];
                let t = &lo[i.b as usize * width..][..width];
                let f = &lo[i.c as usize * width..][..width];
                for (((o, &c), &t), &f) in o.iter_mut().zip(c).zip(t).zip(f) {
                    let pick = (c & 1).wrapping_neg();
                    *o = ((t & pick) | (f & !pick)) & m;
                }
            }
        }
    }
}

/// Word-program evaluations ([`run_lanes`]) charged as one generic node evaluation
/// (`Context::eval_node`). On representative reconstructed addresses (44 and 71 nodes, 4,096
/// points) a word program run point by point was 4 to 38 times as fast as the generic
/// evaluator, and run a block of points at a time it is about twenty times as fast again
/// (the same enumerations took a twentieth of the time); this charges the low end of the
/// two together. Charged at the point-by-point rate, enumerations that take a millisecond
/// were declined for their cost, and six of 140 measured questions ran out of steps a
/// third of the way from where they now finish.
const WORD_EVALS: u64 = 64;

/// The most bits [`exhaustive`] enumerates.
const EXHAUSTIVE_BITS: u32 = 16;

/// The node evaluations one [`exhaustive`] decision may take: `2^13` points of a 64-node
/// candidate.
const EXHAUSTIVE_SHARE: u64 = 1 << 20;

/// the varying sum `n` with its most shared subterm cut off as one atom,
/// simplified (`Σ cᵢ·fᵢ(t)` over a rotated value `t` is `t ^ k`). `Some` node when the solver's
/// answer is smaller and passes the gates the phase's answers do: agreement at the refutation
/// sample, and an exact certificate within the sweep's share. Within the limits below, so a
/// sweep asks only blocks the size an obfuscator writes, each at a small fixed cost.
fn sweep_cut(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    cfg: &MbaConfig,
    n: u32,
) -> Result<Option<u32>, Stop> {
    if !matches!(cx.node(n).op, OpCode::Add | OpCode::Sub) {
        return Ok(None);
    }
    for c in shared(r, cx, cfg, n, SWEEP_CUTS, false) {
        if let Some(e) = sweep_cut_at(r, cx, cfg, n, c)? {
            return Ok(Some(e));
        }
    }
    drop_noise(r, cx, cfg, n)
}

/// the block `n` with each atom it does not depend on written as zero, read with
/// arithmetic under its bitwise operators as atoms (the two halves of a rotate, `t << 22` and
/// `t >>u 42`, each with its known bits) and every atom through the bits known of it: noise that
/// cancels only given those bits (a value mixed in that cancels for `t`'s low 22 bits zero). An
/// exact certificate proves each drop; the solver need not find the simpler form, and the
/// constants above no longer read the noise.
fn drop_noise(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    cfg: &MbaConfig,
    n: u32,
) -> Result<Option<u32>, Stop> {
    let Ok((m, bindings)) = lower_id_reading(cx, n, &cfg.limits, Reading::Shallow) else {
        return Ok(None);
    };

    if m.nodes().len() < SWEEP_CUT_NODES || m.vars().len() > SWEEP_DROP_VARS || !m.shape().mixed {
        return Ok(None);
    }
    let mut read = m;
    for (v, &atom) in bindings.atoms.iter().enumerate() {
        if let (Some(kb), _) = super::known(r, cx, atom)?
            && !kb.known().is_zero()
            && let Some(m2) = with_known_bits(&read, v as u32, &kb.unknown_mask(), &kb.known_one())
        {
            read = m2;
        }
    }
    let mut dropped = false;
    for v in 0..read.vars().len() as u32 {
        // One input first: a block whose value there changes when the atom is zero reads
        // the atom, and no certificate proves the drop. (Nearly every atom is read: the
        // refutation sample of 64 points, built and evaluated for each, was three quarters
        // of the time spent here.)
        if reads_var(r, &read, v)? {
            continue;
        }
        let Some(m0) = with_constant(&read, v) else {
            continue;
        };
        let agree = sampled(r, &read, &m0, read.key()[0])?;
        if !agree {
            continue;
        }
        let report = certify::prove(&read, &m0, &mut Steps::new(r, SWEEP_SHARE))?;
        count(r).certificates.record(&report);
        if report.verdict == Verdict::Proved {
            read = m0;
            dropped = true;
        }
    }
    if !dropped {
        return Ok(None);
    }
    count(r).noise_atoms += 1;
    Ok(Some(r.build(cx, |cx| lift_id(cx, &read, &bindings))?))
}

/// Whether `m` is seen to read variable `v`: its value at one input (pseudo-random, splitmix64
/// of each variable's index) differs from its value there with `v` zero. Charged as pass work.
/// A filter, never evidence: `false` says nothing.
fn reads_var(r: &mut Runner<'_, '_>, m: &MbaExpr, v: u32) -> Result<bool, Stop> {
    let Some(&width) = m.vars().get(v as usize) else {
        return Ok(false);
    };
    charge(r, m, m, 1)?;
    let mut at: Vec<crate::BitVec> = m
        .vars()
        .iter()
        .zip(0u64..)
        .map(|(&w, i)| {
            let mut z = i.wrapping_add(1).wrapping_mul(0x9e37_79b9_7f4a_7c15);
            z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
            z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
            crate::BitVec::wrapping_from_u64(w, z ^ (z >> 31))
        })
        .collect();
    let with = m.eval(&at);
    at[v as usize] = crate::BitVec::zero(width);
    let without = m.eval(&at);
    Ok(matches!((with, without), (Some(a), Some(b)) if a != b))
}

/// The most atoms [`drop_noise`] reads a block over.
const SWEEP_DROP_VARS: usize = 6;

/// [`sweep_cut`] with `c` cut off.
fn sweep_cut_at(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    cfg: &MbaConfig,
    n: u32,
    c: u32,
) -> Result<Option<u32>, Stop> {
    let Ok((m, bindings)) = lower_id_reading(cx, n, &cfg.limits, Reading::CutWhole(c)) else {
        return Ok(None);
    };

    if m.nodes().len() < SWEEP_CUT_NODES || m.vars().len() > SWEEP_CUT_VARS || !m.shape().mixed {
        return Ok(None);
    }
    let size = m.nodes().len();
    // A block that contains one the solver was asked about with the same node cut off, and
    // ran out of its steps on (or does not take), is not asked about: the inner block is
    // part of this question as it was asked, and the solver has no more steps for the whole
    // than it had for the part. The sweep meets a tower of blocks operands first, each a
    // top of its own chain of sums, and each fragment holds the ones below it whole: a
    // tower of `k` blocks the solver cannot take was `k` questions of growing size. (Of
    // 3,404 questions in 140 slow questions, 1,066 held a block declined at the same cut:
    // asked all the same, none of those was answered; 333 of the others were.)
    let over = over_declined(r, cx, n, c, &bindings.atoms);
    if over {
        r.mba.cut_declined.entry(c).or_default().insert(n, ());
        return Ok(None);
    }
    let answer = cut_answer(r, &m, size, cfg, SWEEP_CUT_STEPS)?;
    match answer {
        Cut::Proved(expr) => Ok(Some(r.build(cx, |cx| lift_id(cx, &expr, &bindings))?)),
        Cut::Declined => {
            r.mba.cut_declined.entry(c).or_default().insert(n, ());
            Ok(None)
        }
        Cut::Open => Ok(None),
    }
}

/// Whether the block `n` with `c` cut off (the atoms of its lowering are `atoms`) is, or
/// holds, a block the solver declined in this call with `c` cut off (`Runner::cut_declined`).
/// A declined block's root is above its cut, so it is found only inside the fragment: not
/// below the cut, nor below an atom.
fn over_declined(r: &Runner<'_, '_>, cx: &Context, n: u32, c: u32, atoms: &[u32]) -> bool {
    let Some(declined) = r.mba.cut_declined.get(&c) else {
        return false;
    };
    let mut seen: crate::hash::IdMap<u32, ()> = crate::hash::IdMap::default();
    let mut stack = vec![n];
    while let Some(i) = stack.pop() {
        if i == c || atoms.contains(&i) || seen.insert(i, ()).is_some() {
            continue;
        }
        if declined.contains_key(&i) {
            return true;
        }
        stack.extend(cx.node(i).children());
    }
    false
}

/// What [`cut_answer`] has of a noise block.
enum Cut {
    /// A smaller equivalent, proved.
    Proved(MbaExpr),
    /// The solver did not answer: it ran out of its steps, or does not take the block.
    Declined,
    /// An answer that is no smaller or not proved, or no steps left to ask with.
    Open,
}

/// `m` with variable `v` replaced by zero.
fn with_constant(m: &MbaExpr, v: u32) -> Option<MbaExpr> {
    let w = *m.vars().get(v as usize)?;
    let mut out = MbaExpr::new(m.vars().to_vec());
    let mut map: Vec<u32> = Vec::with_capacity(m.nodes().len());
    for n in m.nodes() {
        let args: Vec<u32> = n.args[..n.op.arity()]
            .iter()
            .map(|&k| map[k as usize])
            .collect();
        let id = match n.op {
            MOp::Var(i) if i == v => out.push(MOp::Const(crate::BitVec::zero(w)), &[]).ok()?,
            MOp::Zext | MOp::Sext | MOp::Trunc => out.push_cast(n.op, args[0], n.width).ok()?,
            op => out.push(op, &args).ok()?,
        };
        map.push(id);
    }
    Some(out)
}

/// The solver's answer to the noise block `m`, when it has fewer nodes than `size` and passes
/// the refutation sample and an exact certificate within the sweep's share.
fn cut_answer(
    r: &mut Runner<'_, '_>,
    m: &MbaExpr,
    size: usize,
    cfg: &MbaConfig,
    steps: u64,
) -> Result<Cut, Stop> {
    let limit = steps.min(r.meter.left_in(|b| b.mba_steps));
    if limit == 0 {
        return Ok(Cut::Open);
    }
    let budget = cfg.budget.with_evidence(false).with_steps(limit);
    let (answer, spent) = r.inner.mba.solver.solve_counted(m, &budget);
    let spent = spent.min(r.meter.left_in(|b| b.mba_steps));
    r.meter.charge(Counter::MbaSteps, spent)?;
    let expr = match answer {
        MbaAnswer::Simplified { expr, .. } => expr,
        MbaAnswer::Exhausted | MbaAnswer::Unsupported(_) => {
            return Ok(Cut::Declined);
        }
        MbaAnswer::NoSimpler => {
            return Ok(Cut::Open);
        }
    };
    if expr.vars() != m.vars() || expr.width() != m.width() || expr.nodes().len() >= size {
        return Ok(Cut::Open);
    }
    if !sampled(r, m, &expr, m.key()[0])? {
        return Ok(Cut::Open);
    }
    let report = certify::prove(m, &expr, &mut Steps::new(r, SWEEP_SHARE))?;
    count(r).certificates.record(&report);
    if report.verdict != Verdict::Proved {
        return Ok(Cut::Open);
    }
    count(r).noise_blocks += 1;
    Ok(Cut::Proved(expr))
}

/// the sweep's readings of `subject` asked whether it is `k`: whether one proves it
/// (`decided`), whether its whole fragment is refuted (`refuted`), and whether some narrower
/// reading was refuted over its free atoms (a constant only through how its atoms relate) or
/// the readings were cut short.
///
/// A candidate below `subject` whose readings were asked in this call and decided nothing is
/// an atom to every reading here (`Runner::mba_undecided`). The sweep meets a constant's
/// operands first, and an obfuscator builds one constant from another: where the lower one
/// stays open, each node above it that the samples hold constant holds its fragment whole,
/// and the certificates would spend a share on the same question at every one of them (ten
/// links of one chain in a measured question, a share each; nine tenths of what the sweeps
/// of 140 questions spent went to certificates that decided nothing, most of it this way).
/// What an upper constant is beyond the open one, the readings over it as an atom still
/// prove; a `subject` that is itself open is not asked again.
///
/// The readings are asked cheapest first, and they end at the first whose certificate takes
/// most of its share and leaves the question open: the ones after it are larger. (Of 22,555
/// proofs in the sweeps of those questions, six came after such a reading of the same
/// candidate; half of what the undecided certificates spent did.)
fn readings_prove(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    cfg: &MbaConfig,
    subject: u32,
    k: &crate::BitVec,
    share: u64,
) -> Result<(bool, bool, bool, bool), Stop> {
    let (mut decided, mut refuted, mut seen, mut budget_starved) = (false, false, false, false);
    // Each reading with its cost, and whether a refutation of it is one of `subject` (the
    // whole fragment, no open candidate cut out of it).
    let mut readings: Vec<(u64, bool, MbaExpr, Bindings)> = Vec::new();
    if r.mba.undecided.contains_key(&subject) {
        return Ok((false, false, false, false));
    }
    let cuts = match r.mba.undecided.is_empty() {
        true => shared(r, cx, cfg, subject, SWEEP_CUTS, false),
        false => shared_nodes(cx, subject, &cfg.limits, SWEEP_CUTS, &r.mba.undecided),
    };
    let open = &r.mba.undecided;
    let kinds = [Reading::SemiLinear, Reading::Shallow, Reading::Linear];
    let all = std::iter::once(None)
        .chain(kinds.into_iter().map(Some))
        .chain(
            cuts.into_iter()
                .flat_map(|c| [Some(Reading::Cut(c)), Some(Reading::CutWhole(c))]),
        );
    // A fragment that is semi-linear as it is has one lowering for the whole and the
    // semi-linear reading, and one per cut.
    let mut semi = false;
    for reading in all {
        let lowered = match reading {
            None => lower_id_whole(cx, subject, &cfg.limits, open).map(|(m, bindings, s)| {
                semi = s;
                (m, bindings)
            }),
            Some(Reading::SemiLinear | Reading::CutWhole(_)) if semi => continue,
            _ => lower_id_over(cx, subject, &cfg.limits, reading, open),
        };
        let Ok((m, bindings)) = lowered else {
            continue;
        };
        if readings.iter().any(|(_, _, o, _)| *o == m) {
            continue;
        }
        let t = m.vars().len().min(32) as u32;
        let points = match reading {
            Some(Reading::Linear) => 1u64 << t,
            _ => 64 * ((1u64 << t) - 1),
        };
        let whole = reading.is_none() && bindings.atoms.iter().all(|a| !open.contains_key(a));
        readings.push((
            points.saturating_mul(m.nodes().len() as u64),
            whole,
            m,
            bindings,
        ));
    }
    // Whether a certificate was asked and left the question open.
    let mut open_asked = false;
    readings.sort_by_key(|(cost, _, _, _)| *cost);
    'readings: for (cost, whole, m, bindings) in readings {
        if cost > share {
            break;
        }
        let mut c = MbaExpr::new(m.vars().to_vec());
        if c.push(MOp::Const(*k), &[]).is_err() {
            continue;
        }
        // a narrower reading refuted over free atoms is asked again with its atoms
        // read through the bits known of them, where asked and where no input with those bits
        // is seen to refute it (see `known_reading`). A reading the certificate could not
        // decide is no easier with more nodes, and asking every refuted one again spends the
        // run's steps (1,500 times in one measured question, none proved, with two constants
        // left unfolded).
        let mut m = m;
        let mut known = false;
        loop {
            count(r).opaque_asked += 1;
            // With the call's solver steps gone (fewer left than such a certificate's
            // share), a certificate is charged as pass work, as
            // the gate's are, within a small share and a part of the call's pass work in
            // all (see `BORROW_SHARE`): what decides a sum over one value under masks is a
            // comparison of two forms, a few hundred evaluations.
            let requested_share = share;
            let steps = r.meter.left_in(|b| b.mba_steps);
            let (report, rest, share) = if steps.saturating_mul(EVALS_PER_STEP) < BORROW_SHARE {
                let room =
                    (r.meter.limit.pass_work / BORROW_PART).saturating_sub(r.mba.sweep_borrowed);
                let share = share.min(BORROW_SHARE).min(room);
                let before = r.meter.spent.pass_work;
                let mut meter = Gate { r, share };
                let report = certify::prove(&m, &c, &mut meter);
                let rest = meter.share;
                r.mba.sweep_borrowed += r.meter.spent.pass_work - before;
                (report?, rest, share)
            } else {
                let mut meter = Steps::new(r, share);
                let effective = meter.share;
                let report = certify::prove(&m, &c, &mut meter)?;
                (report, meter.share, effective)
            };
            if report.over_budget && share < requested_share {
                budget_starved = true;
            }
            // The certificate took most of its share and left the question open: the readings
            // not yet asked are larger, and theirs would too. (Not the same reading asked
            // again through its atoms' known bits: that is one more question of this
            // reading, and the next reading has its own.)
            let burned = !known && rest < share / 2;
            count(r).certificates.record(&report);
            match report.verdict {
                Verdict::Proved => {
                    decided = true;
                    break 'readings;
                }
                Verdict::Refuted if whole => {
                    refuted = true;
                    break 'readings;
                }
                Verdict::Refuted if !known => {
                    open_asked = true;
                    seen = true;
                    if !cfg.known_atoms {
                        break;
                    }
                    known = true;
                    let Some(at) = report.counterexample.as_deref() else {
                        break;
                    };
                    match known_reading(r, cx, &m, &bindings, at, k)? {
                        Some(read) => m = read,
                        None => break,
                    }
                }
                _ => {
                    open_asked = true;
                    if burned {
                        // What the readings left unasked might have been refuted over their
                        // free atoms: the root's cases are tried as if one was.
                        seen = true;
                        break 'readings;
                    }
                    break;
                }
            }
        }
    }
    if !decided && !refuted && open_asked && !budget_starved {
        r.mba.undecided.insert(subject, ());
    }
    Ok((decided, refuted, seen, budget_starved))
}

/// Whether `values` contains exactly two distinct values.
fn exactly_two(values: &[crate::BitVec]) -> bool {
    let Some((&first, rest)) = values.split_first() else {
        return false;
    };
    let Some(second) = rest.iter().copied().find(|v| *v != first) else {
        return false;
    };
    values.iter().all(|v| *v == first || *v == second)
}

/// A varying block proved constant on each side of its most-used condition, reconstructed as a
/// select of those constants. Sampling only admits a candidate; each side needs exact evidence.
/// `attempts` counts the blocks whose sides were built.
fn cases_fold(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    cfg: &MbaConfig,
    n: u32,
    attempts: &mut usize,
) -> Result<Option<u32>, Stop> {
    let Some(c) = r.build(cx, |cx| super::context::most_tested(cx, n))? else {
        return Ok(None);
    };
    // The samples first, before a side is built or swept: a side that varies at them is not
    // proved constant, and its sweep keeps its value (wherever the run's assumptions hold,
    // so only the samples where they do are read), so it varies after its sweep as before.
    // (Of 3,404 blocks with a condition in 140 slow questions, 2,658 were swept to find a
    // side that varied at the samples it began with: five sixths of the time spent here.)
    //
    // Before the sides are built, the block's own samples: where `c` holds the first side
    // is `n`, elsewhere the second is (`context::sides_on`), so a block with two values
    // where `c` holds, or two where it does not, has a side with both.
    r.sample(cx, n)?;
    r.sample(cx, c)?;
    let points = r.samples[&n].len();
    let held = held_points(r, cx, points)?;
    let (vn, vc) = (&r.samples[&n], &r.samples[&c]);
    let where_c = |holds: bool| -> Vec<bool> {
        let at = |(held, c): (&bool, &crate::BitVec)| *held && c.is_zero() != holds;
        held.iter().zip(vc.iter()).map(at).collect()
    };
    if varies_at(vn, &where_c(true)) || varies_at(vn, &where_c(false)) {
        return Ok(None);
    }
    let got = r.build(cx, |cx| super::context::sides_on(cx, n, c))?;
    let Some((t, f)) = got else {
        return Ok(None);
    };
    *attempts += 1;
    let mut sides = [t, f];
    // Then each side's samples (those where the other case holds too).
    for side in sides {
        if cx.const_val(side).is_some() {
            continue;
        }
        r.sample(cx, side)?;
        if varies_at(&r.samples[&side], &held) {
            return Ok(None);
        }
    }
    // Each side swept and proved before the other is swept: a first side left unproved
    // ends the attempt, and the second side's sweep with it (548 of the 654 blocks whose
    // sides were constant at the samples and not proved ended at the first side, after
    // both were swept). What proves a side does not read the other's sweep: the nodes below
    // it are all examined by its own.
    let mut values = [crate::BitVec::zero(cx.width_of(n)); 2];
    for (slot, side) in values.iter_mut().zip(&mut sides) {
        // A side an earlier sweep of this call examined (the side of a block below this
        // one, where the condition fixes what the two differ in) is that sweep's result:
        // every node below it was examined before it, and a sweep would only walk them.
        *side = match r.mba.swept.get(side) {
            Some(&done) => done,
            None => sweep_inner(r, cx, cfg, *side, false)?,
        };
        if let Some(k) = cx.const_val(*side) {
            *slot = k;
            continue;
        }
        r.sample(cx, *side)?;
        let samples = &r.samples[side];
        let Some(&k) = samples.first() else {
            return Ok(None);
        };
        if samples.iter().any(|v| *v != k) {
            return Ok(None);
        }
        *slot = k;
        let proved = readings_prove(r, cx, cfg, *side, &k, SWEEP_SHARE)?.0;
        if !proved {
            return Ok(None);
        }
    }
    let e = r.build(cx, |cx| {
        let t = cx.mk_const(&values[0])?;
        let f = cx.mk_const(&values[1])?;
        cx.c_select(c, t, f)
    })?;
    if e == n {
        return Ok(None);
    }
    count(r).piecewise_blocks += 1;
    Ok(Some(e))
}

/// Whether every constraint of the run's assumptions holds, at each of the `points` sample
/// points (all of them without assumptions): where a rewrite that relies on them keeps a
/// node's value.
fn held_points(r: &mut Runner<'_, '_>, cx: &Context, points: usize) -> Result<Vec<bool>, Stop> {
    use crate::facts::Reliance;
    let Some(a) = r.assumptions else {
        return Ok(vec![true; points]);
    };
    let all = a.constraints().fold(Reliance::NONE, |rel, (id, _, _)| {
        rel.union(Reliance::of(id))
    });
    r.constraints_hold(cx, all, points)
}

/// Whether `vals` differ at two of the sample points `at` keeps.
fn varies_at(vals: &[crate::BitVec], at: &[bool]) -> bool {
    let mut kept = vals.iter().zip(at).filter(|(_, at)| **at).map(|(v, _)| v);
    kept.next().is_some_and(|k| kept.any(|v| v != k))
}

/// whether `n` is `k` one case of a condition at a time: the condition its selects
/// test most, each side `n` with what that case fixes put in (`context::sides`), each proved `k`
/// by the readings (their atoms' known bits included). Sound as `select(c, n[c], n[!c])` is `n`.
/// Obfuscated expressions can mix one condition (`trunc<32>(x) == 0`) through a constant's
/// noise: on either side the selects are gone and the low half of `x` is known, and both are
/// `k`. Each side must be `k` at every sample point before a certificate is asked.
fn cases_prove(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    cfg: &MbaConfig,
    n: u32,
    k: &crate::BitVec,
) -> Result<bool, Stop> {
    let Some((_, t, f)) = r.build(cx, |cx| super::context::sides(cx, n))? else {
        return Ok(false);
    };
    for side in [t, f] {
        if cx.const_val(side).is_some() {
            if cx.const_val(side) != Some(*k) {
                return Ok(false);
            }
            continue;
        }
        r.sample(cx, side)?;
        if r.samples[&side].iter().any(|v| v != k) {
            return Ok(false);
        }
    }
    for side in [t, f] {
        if cx.const_val(side).is_none() && !readings_prove(r, cx, cfg, side, k, SWEEP_SHARE)?.0 {
            return Ok(false);
        }
    }
    Ok(true)
}

/// the reading `m` of a fragment with each atom some of whose bits are known read
/// as `(v & unknown) | ones` ([`with_known_bits`]), to be proved equal to `k`; `None` when no
/// atom's bits are known, or an input with them is seen where `m` is not `k`: the input `at`
/// that refuted `m` and [`KNOWN_SCREEN`] others, each with every atom's known bits written in.
/// An opaque constant is often one only through such bits: under its bitwise operators,
/// `(x & 0xffffffff00000000) * 0x8000001 + 0xc00081fe00001000` (low byte 0) and a rotate's
/// product (low byte 0x52) cancel to a constant, as two free atoms they do not.
fn known_reading(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    m: &MbaExpr,
    bindings: &Bindings,
    at: &[crate::BitVec],
    k: &crate::BitVec,
) -> Result<Option<MbaExpr>, Stop> {
    use crate::facts::known::{bv_and, bv_or};
    let mut read: Option<MbaExpr> = None;
    let mut bits: Vec<Option<(crate::BitVec, crate::BitVec)>> = vec![None; m.vars().len()];
    for (v, &atom) in bindings.atoms.iter().enumerate() {
        if let (Some(kb), _) = super::known(r, cx, atom)?
            && !kb.known().is_zero()
            && let Some(m2) = with_known_bits(
                read.as_ref().unwrap_or(m),
                v as u32,
                &kb.unknown_mask(),
                &kb.known_one(),
            )
        {
            bits[v] = Some((kb.unknown_mask(), kb.known_one()));
            read = Some(m2);
        }
    }
    if read.is_none() || at.len() != m.vars().len() {
        return Ok(None);
    }
    // `at`, then pseudo-random points (splitmix64 of the variable and the point), each atom's
    // value with its known bits written in.
    let point = |p: u64| -> Vec<crate::BitVec> {
        (0..m.vars().len())
            .map(|v| {
                let x = if p == 0 {
                    at[v]
                } else {
                    let mut z = ((v as u64) << 32 ^ p).wrapping_add(0x9e37_79b9_7f4a_7c15);
                    z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
                    z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
                    crate::BitVec::wrapping_from_u64(m.vars()[v], z ^ (z >> 31))
                };
                match &bits[v] {
                    Some((unknown, ones)) => bv_or(&bv_and(&x, unknown), ones),
                    None => x,
                }
            })
            .collect()
    };
    for p in 0..=KNOWN_SCREEN {
        if m.eval(&point(p)).is_some_and(|v| v != *k) {
            return Ok(None);
        }
    }
    Ok(read)
}

/// Pseudo-random inputs [`known_reading`] screens a reading at, besides its counterexample.
const KNOWN_SCREEN: u64 = 8;

/// `m` with variable `v` read as `(v & unknown) | ones`, its known bits written out.
/// An identity of the result holds for every value with those known bits, so for the atom the
/// variable stands for, which has them.
fn with_known_bits(
    m: &MbaExpr,
    v: u32,
    unknown: &crate::BitVec,
    ones: &crate::BitVec,
) -> Option<MbaExpr> {
    let mut out = MbaExpr::new(m.vars().to_vec());
    let x = out.push(MOp::Var(v), &[]).ok()?;
    let u = out.push(MOp::Const(*unknown), &[]).ok()?;
    let a = out.push(MOp::And, &[x, u]).ok()?;
    let o = out.push(MOp::Const(*ones), &[]).ok()?;
    let read = out.push(MOp::Or, &[a, o]).ok()?;
    let mut map: Vec<u32> = Vec::with_capacity(m.nodes().len());
    for n in m.nodes() {
        let args: Vec<u32> = n.args[..n.op.arity()]
            .iter()
            .map(|&k| map[k as usize])
            .collect();
        let id = match n.op {
            MOp::Var(i) if i == v => read,
            MOp::Zext | MOp::Sext | MOp::Trunc => out.push_cast(n.op, args[0], n.width).ok()?,
            op => out.push(op, &args).ok()?,
        };
        map.push(id);
    }
    Some(out)
}

/// The fewest nodes a block [`sweep_cut`] asks about has.
const SWEEP_CUT_NODES: usize = 16;

/// The most atoms a block [`sweep_cut`] asks about has. (With four, the solver was asked
/// about several hundred more blocks in 140 measured questions and answered none of them.)
const SWEEP_CUT_VARS: usize = 3;

/// The pass work one certificate of the sweep takes once the call's solver steps are gone
/// (see [`readings_prove`]), and the part of the call's pass work all of them take: one in
/// [`BORROW_PART`].
const BORROW_SHARE: u64 = 1 << 15;
const BORROW_PART: u64 = 8;

/// The solver steps one [`sweep_cut`] question takes.
const SWEEP_CUT_STEPS: u64 = 1 << 12;

/// The most nodes the sweep's demanded-bits reduction of one candidate visits.
const SWEEP_DEMAND_VISITS: u32 = 4096;

/// The most candidates per sweep that certificates leave undecided before the rest are left to
/// the phases (a refuted one is decided, and cheap). 256, not 16. The run's budget
/// bounds the sweep, and a sweep it stops keeps what it proved. Behind 16 undecided candidates,
/// a large dispatch expression kept the constants its address guards are built of: six of its ten
/// guards fold with them (about 450,000 MBA steps each).
const SWEEP_FAILURES: usize = 256;

/// The most shared subterms a sweep cuts a candidate's fragment at, one reading each.
const SWEEP_CUTS: usize = 3;

/// The most two-valued blocks one sweep tries to prove piecewise.
const SWEEP_CASE_BLOCKS: usize = 256;

/// The node evaluations one sweep certificate may take.
const SWEEP_SHARE: u64 = 1 << 18;

/// Node evaluations per MBA solver step: a sweep certificate is charged as the normal-form
/// solver charges its own (batched evaluations, a fraction of a nanosecond each).
const EVALS_PER_STEP: u64 = 32;

/// A sweep certificate's meter: node evaluations, charged to the run's MBA solver steps at
/// [`EVALS_PER_STEP`], at most `share` of them.
struct Steps<'x, 'r, 'a> {
    r: &'x mut Runner<'r, 'a>,
    share: u64,
    /// Evaluations not yet charged as a whole step.
    owed: u64,
}

impl<'x, 'r, 'a> Steps<'x, 'r, 'a> {
    fn new(r: &'x mut Runner<'r, 'a>, share: u64) -> Self {
        Steps { r, share, owed: 0 }
    }
}

impl certify::Meter for Steps<'_, '_, '_> {
    type Err = Stop;
    fn left(&self) -> u64 {
        let steps = self.r.meter.left_in(|b| b.mba_steps);
        steps
            .saturating_mul(EVALS_PER_STEP)
            .saturating_sub(self.owed)
            .min(self.share)
    }
    fn charge(&mut self, units: u64) -> Result<(), Stop> {
        self.share = self.share.saturating_sub(units);
        self.owed += units;
        let steps = self.owed / EVALS_PER_STEP;
        self.owed %= EVALS_PER_STEP;
        self.r
            .meter
            .charge(Counter::MbaSteps, steps)
            .map_err(Stop::Exhausted)
    }
}

/// The MBA phase at `n`.
pub(super) fn step(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    cfg: &MbaConfig,
    n: u32,
) -> Result<Step, Stop> {
    step_with(r, cx, cfg, n, false)
}

/// The MBA phase at `n`, one side of a case split (see `cases::by_cases`): [`step`], asked
/// also with the values its nodes share through casts cut off (see below). The side reads
/// what the select's sides were made of, which other nodes read too.
pub(super) fn step_side(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    cfg: &MbaConfig,
    n: u32,
) -> Result<Step, Stop> {
    step_with(r, cx, cfg, n, true)
}

fn step_with(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    cfg: &MbaConfig,
    n: u32,
    side: bool,
) -> Result<Step, Stop> {
    // A solver that takes polynomials is also asked at constant left shifts (the arena spells
    // `2^k·t` as `t << k`).
    let poly = r.inner.mba.solver.polynomial_fragments();
    let op = cx.node(n).op;
    if !(mixed_op(op) || (poly && op == OpCode::Shl)) {
        return Ok(Step::Normal(Fin::FINAL));
    }
    let unshrunk = count(r).not_smaller;
    let held = count(r).unsupported;
    let out = ask(r, cx, cfg, n, n, None, depth(r))?;
    // Whether the question was not one the solver answers whole: it holds a fragment kept
    // as it is (see `holds_kept`), or the solver declined it for its size.
    let held = count(r).unsupported != held;
    // An answer that was not smaller for what the fragment shares with others is no answer
    // either: the readings below keep a shared value as it is.
    let unshrunk = count(r).not_smaller != unshrunk;
    if let Step::Normal(fin) = out
        && (fin.done || unshrunk)
    {
        // a fragment that reads slices of one rotated value, asked again with them
        // written as masks of that rotation (see [`sliced`]), within the steps of a retried
        // question: the answers taken in 140 measured questions took under 9,000 steps, and
        // without the limit thirteen that took the node's own share left eleven of those
        // questions out of steps.
        let before = cx.len() as u32;
        // What a question asked another way declines for what the fragment shares
        // contributes to the result (see the linear pass's `step`). Not where it ran out of
        // the steps or the certificate share it is given: those are its own by design (see
        // [`Cap::Steps`]), and its answer within them is what it is.
        let kept = |fin: Fin, f: Fin| match f.why {
            None => fin.and(f),
            Some(_) => fin,
        };
        let mut fin = fin;
        let asked = (n, cfg.limits.max_nodes);
        let mut slices = match r.mba.sliced.get(&asked).copied() {
            // (Through `build` all the same: it checks the budget, and makes no node.)
            Some(known) => r.build(cx, |_| Ok(known))?,
            None => {
                let made = r.build(cx, |cx| sliced(cx, n, cfg.limits.max_nodes))?;
                r.mba.sliced.insert(asked, made);
                made
            }
        };
        if let Some(root) = slices {
            match ask(r, cx, cfg, n, root, None, Cap::Steps(CUT_STEPS))? {
                Step::Normal(f) => fin = kept(fin, f),
                again => return Ok(again),
            }
            // The fragment over that rotation is the answer where writing it made it smaller
            // and left the solver no question: `(x >>u 57 & 0x74) - (rotl(x, 7) & 0x74)` is
            // one slice less itself, a constant the builder folds, and a constant is no
            // fragment to ask about.
            match sliced_itself(r, cx, cfg, n, root, before)? {
                Some(Step::Normal(f)) => {
                    fin = kept(fin, f);
                    slices = None;
                }
                Some(to) => return Ok(to),
                None => {}
            }
        }
        // A fragment too large to lower whole (more variables than a question takes), or one
        // not answered whole for what it holds, with the arithmetic its bitwise operators
        // read as atoms (see [`Reading::Shallow`]): a sum of bitwise functions of values that
        // are sums and products themselves is a linear MBA over those values. An obfuscator
        // writes `(a & b) + (b & c) - 2·(a & b & c)`, which is `(a ^ c) & b`, over an `a`
        // and a `b` that are products of one value: read whole it is a question about that
        // value, costly and declined, and every sum that holds it was then not asked at all.
        // (Asked of every fragment, the answers over atoms took the place of the whole
        // fragment's and three of 47 measured constants were not found.)
        if !asks(r, cx, cfg, n)? || held {
            match ask(
                r,
                cx,
                cfg,
                n,
                n,
                Some(Reading::Shallow),
                Cap::Steps(CUT_STEPS),
            )? {
                Step::Normal(f) => fin = kept(fin, f),
                again => return Ok(again),
            }
        }
        // And with a value most of its terms read cut off as one atom: an obfuscator writes
        // `Σ cᵢ·fᵢ(t)` over a `t` that is a fragment of its own, and the whole question is
        // then over what `t` is made of, where the cut one is over `t` alone.
        for root in slices.into_iter().chain([n]) {
            let cuts = shared(r, cx, cfg, root, CUTS, false);
            for c in cuts {
                match ask(
                    r,
                    cx,
                    cfg,
                    n,
                    root,
                    Some(Reading::Cut(c)),
                    Cap::Steps(CUT_STEPS),
                )? {
                    Step::Normal(f) => fin = kept(fin, f),
                    again => return Ok(again),
                }
            }
        }
        // And with a value several of its nodes read through casts too cut off, the casts
        // kept: `(zext(t) | k) + zext(t & k)` is `zext(t) + k` over `t`, where the whole
        // question is over what `t` is made of and its answer writes `t` another way. Only
        // for a fragment whose answer did that, or a side of a case split: asked of every
        // fragment kept from its question, 140 measured calls took 15% longer.
        if unshrunk || side {
            for c in shared(r, cx, cfg, n, CUTS, true) {
                match ask(
                    r,
                    cx,
                    cfg,
                    n,
                    n,
                    Some(Reading::CutWhole(c)),
                    Cap::Steps(CUT_STEPS),
                )? {
                    Step::Normal(f) => fin = kept(fin, f),
                    again => return Ok(again),
                }
            }
        }
        discard(r, cx, before);
        return Ok(Step::Normal(fin));
    }
    Ok(out)
}

/// The MBA phase at `n`, a part of a question written another way (a sum with its common
/// factor taken out): the node's own question alone, within the steps a retried one takes
/// (see [`CUT_STEPS`]). What an obfuscator scaled is a small question; what is not takes the
/// steps the questions after it need.
pub(super) fn step_part(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    cfg: &MbaConfig,
    n: u32,
) -> Result<Step, Stop> {
    let poly = r.inner.mba.solver.polynomial_fragments();
    let op = cx.node(n).op;
    if !(mixed_op(op) || (poly && op == OpCode::Shl)) {
        return Ok(Step::Normal(Fin::FINAL));
    }
    ask(r, cx, cfg, n, n, None, Cap::Steps(CUT_STEPS))
}

/// The MBA phase at `n`, one of the two cofactor sums of a sum multiplied out over a factor
/// its products share (see `linear::by_multiplicand`): asked with the arithmetic its
/// bitwise operators read as atoms first ([`Reading::Shallow`]), then whole, each within the
/// steps a retried question takes (see [`CUT_STEPS`]). The sum is linear over the atoms of
/// its terms, which is the first question; the whole one is over what those atoms are made
/// of, and is the same question where they are variables.
pub(super) fn step_cofactor(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    cfg: &MbaConfig,
    n: u32,
) -> Result<Step, Stop> {
    let poly = r.inner.mba.solver.polynomial_fragments();
    let op = cx.node(n).op;
    if !(mixed_op(op) || (poly && op == OpCode::Shl)) {
        return Ok(Step::Normal(Fin::FINAL));
    }
    let shallow = Some(Reading::Shallow);
    let fin = match ask(r, cx, cfg, n, n, shallow, Cap::Steps(CUT_STEPS))? {
        Step::Normal(f) => f,
        to => return Ok(to),
    };
    Ok(match ask(r, cx, cfg, n, n, None, Cap::Steps(CUT_STEPS))? {
        Step::Normal(f) => Step::Normal(fin.and(f)),
        to => to,
    })
}

/// The steps a question takes at most, besides the call's share (see [`SOLVE_SHARE`]).
#[derive(Copy, Clone)]
enum Cap {
    /// A question asked another way, or a part of one: these steps, and its answer then is
    /// what it is.
    Steps(u64),
    /// A node's own question: these steps in this round, and more in a later one (see
    /// [`depth`]).
    Depth(u64),
}

/// The steps a node's own question takes in this round: [`DEPTH_STEPS`] in the rounds until one
/// changes nothing, then [`DEPTH_FACTOR`] times as many in each round after one that changed
/// nothing, up to the question's share of the call (see [`SOLVE_SHARE`]).
///
/// The questions that fold an obfuscated value are small ones (of the answers committed in 140
/// measured calls, 570 of 601 took under 65,536 steps and 395 under 16,384), and the ones the
/// solver runs out of steps on are found among them in no order. Asked at the full share where
/// they stand, a few of those took the steps of a call before the rest of it was asked
/// anything; asked this way, a call spends what it has on the cheapest questions first.
fn depth(r: &Runner<'_, '_>) -> Cap {
    let times = DEPTH_FACTOR.checked_pow(u32::from(r.mba.depth));
    Cap::Depth(times.map_or(u64::MAX, |t| DEPTH_STEPS.saturating_mul(t)))
}

/// See [`depth`].
const DEPTH_STEPS: u64 = 1 << 16;

/// See [`depth`].
const DEPTH_FACTOR: u64 = 8;

/// The most shared values the MBA phase cuts a fragment at, one question each.
const CUTS: usize = 2;

/// The solver steps one of those questions takes. (At four times this, the questions that
/// ran out left 140 measured calls twice the nodes; at a quarter, they answered half as many.)
const CUT_STEPS: u64 = 1 << 14;

/// The share of the call's pass work the certificate of a retried question's answer takes
/// (see [`GATE_SHARE`]): one in this many.
const RETRY_GATE_SHARE: u64 = 32;

/// A node as bits of one rotation of another: `(rotl(base, rot) & mask) ^ flip`, at the
/// node's width (at most 64 bits). Every node built over one value by shifts and rotations by
/// constants, complements, and `& | ^` with constants or with another such node of the same
/// rotation of the same value has this shape: each of its bits is 0, 1, a bit of the rotation
/// or that bit's complement. A left shift by `k` is the rotation by `k` with its low `k` bits
/// cleared, a logical right shift the rotation by `−k` with its high `k` bits cleared.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
struct Slice {
    base: u32,
    rot: u32,
    mask: u64,
    flip: u64,
}

/// The slices [`slice_of`] has read in one walk, by node.
struct SliceMemo {
    at: super::Lease,
    slices: Vec<Slice>,
}

impl SliceMemo {
    fn new(cx: &Context) -> SliceMemo {
        SliceMemo {
            at: super::Lease::new(cx.len()),
            slices: Vec::with_capacity(64),
        }
    }

    #[inline]
    fn get(&self, i: u32) -> Option<Slice> {
        self.at.get(i).map(|k| self.slices[k as usize])
    }

    #[inline]
    fn insert(&mut self, i: u32, s: Slice) {
        self.at.insert(i, self.slices.len() as u32);
        self.slices.push(s);
    }
}

/// How many parts of a fragment can be read at each rotation of each value. (Most are read
/// unrotated, one count per node met: those are in a leased table.)
struct Readers {
    whole: super::Lease,
    rotated: crate::hash::IdMap<(u32, u32), u32>,
}

impl Readers {
    fn new(cx: &Context) -> Readers {
        Readers {
            whole: super::Lease::new(cx.len()),
            rotated: crate::hash::IdMap::default(),
        }
    }

    #[inline]
    fn add(&mut self, base: u32, rot: u32) {
        if rot == 0 {
            self.whole.bump(base);
        } else {
            *self.rotated.entry((base, rot)).or_default() += 1;
        }
    }

    #[inline]
    fn get(&self, base: u32, rot: u32) -> u32 {
        if rot == 0 {
            self.whole.get(base).unwrap_or(0)
        } else {
            self.rotated.get(&(base, rot)).copied().unwrap_or(0)
        }
    }
}

/// The most operators one [`slice_of`] reads below a node.
const SLICE_DEPTH: u32 = 48;

/// Node `i` as a [`Slice`]; a node that is no such function of another is its own base, whole
/// (`rot` 0, every bit, no flip).
fn slice_of(cx: &Context, i: u32, memo: &mut SliceMemo, depth: u32) -> Slice {
    let w = u32::from(cx.width_of(i).bits());
    let ones = if w >= 64 { u64::MAX } else { (1u64 << w) - 1 };
    let whole = Slice {
        base: i,
        rot: 0,
        mask: ones,
        flip: 0,
    };
    if w > 64 || depth > SLICE_DEPTH {
        return whole;
    }
    if let Some(s) = memo.get(i) {
        return s;
    }
    let n = cx.node(i);
    let konst = |j: u32| cx.const_val(j).and_then(|c| c.to_u64());
    let rotl = |m: u64, by: u32| match by % w {
        0 => m,
        b => (m << b | m >> (w - b)) & ones,
    };
    // A shift or rotation count: a constant below the width, of an operand of the same width.
    let count = |j: u32| {
        konst(j)
            .filter(|&k| k > 0 && k < u64::from(w))
            .map(|k| k as u32)
    };
    let same_width = |j: u32| cx.width_of(j) == cx.width_of(i);
    let s = match n.op {
        OpCode::Not => {
            let a = slice_of(cx, n.a, memo, depth + 1);
            Slice {
                flip: !a.flip & ones,
                ..a
            }
        }
        OpCode::And | OpCode::Or | OpCode::Xor => {
            let (x, k) = match (konst(n.a), konst(n.b)) {
                (None, Some(k)) => (n.a, Some(k)),
                (Some(k), None) => (n.b, Some(k)),
                _ => (n.a, None),
            };
            let a = slice_of(cx, x, memo, depth + 1);
            // The other operand at each bit of the rotation: a constant's bit either way, or
            // another slice of the same rotation.
            let other = match k {
                Some(k) => Some((0, k)),
                None if konst(n.a).is_none() => {
                    let b = slice_of(cx, n.b, memo, depth + 1);
                    (b.base == a.base && b.rot == a.rot).then_some((b.mask, b.flip))
                }
                None => None,
            };
            match other {
                Some((mb, fb)) => {
                    let op = |p: u64, q: u64| match n.op {
                        OpCode::And => p & q,
                        OpCode::Or => p | q,
                        _ => p ^ q,
                    };
                    // The value where the rotation's bit is 0, and where it is 1.
                    let at0 = op(a.flip, fb);
                    let at1 = op(a.flip ^ a.mask, fb ^ mb);
                    Slice {
                        mask: (at0 ^ at1) & ones,
                        flip: at0 & ones,
                        ..a
                    }
                }
                None => whole,
            }
        }
        OpCode::Shl if same_width(n.a) => match count(n.b) {
            Some(k) => {
                let a = slice_of(cx, n.a, memo, depth + 1);
                Slice {
                    base: a.base,
                    rot: (a.rot + k) % w,
                    mask: a.mask << k & ones,
                    flip: a.flip << k & ones,
                }
            }
            None => whole,
        },
        OpCode::LShr if same_width(n.a) => match count(n.b) {
            Some(k) => {
                let a = slice_of(cx, n.a, memo, depth + 1);
                Slice {
                    base: a.base,
                    rot: (a.rot + w - k) % w,
                    mask: a.mask >> k,
                    flip: a.flip >> k,
                }
            }
            None => whole,
        },
        OpCode::RotL | OpCode::RotR if same_width(n.a) => match count(n.b) {
            Some(k) => {
                let k = if n.op == OpCode::RotL { k } else { w - k };
                let a = slice_of(cx, n.a, memo, depth + 1);
                Slice {
                    base: a.base,
                    rot: (a.rot + k) % w,
                    mask: rotl(a.mask, k),
                    flip: rotl(a.flip, k),
                }
            }
            None => whole,
        },
        _ => whole,
    };
    memo.insert(i, s);
    s
}

/// node `n`'s fragment (its MBA operators, down to their atoms) with every part that reads
/// one rotation of one value written over that rotation: `(rotl(x, r) & mask) ^ flip` (see
/// [`Slice`]). `rotl(x, 32) >>u 30`, `rotl(x, 32) << 34` and `rotl(x, 2)` are the low 34
/// bits, the high 30 bits and the whole of `rotl(x, 2)`, but three unrelated atoms to the
/// solver: obfuscators write a rotate as such shifts beside the rotate itself in MBAs that
/// cancel, and mask and complement the halves before they shift them.
///
/// A part whose low `k` bits are clear is also that many bits lower of the rotation by `k`
/// less, shifted up (`rotl(x, 9) & 0x…42` is `(rotl(x, 8) & 0x…21) << 1`), and a product by a
/// constant with low zero bits is its operand shifted up times the rest
/// (`(x & m) · (c · 2^k)` is `((x & m) << k) · c`). Each part is read at the rotation the
/// most parts of the fragment can be read at, so a term an obfuscator doubled, or a pass
/// wrote as a shift, stays a multiple of the atom the other terms read.
///
/// `None` when no two parts read one rotation of one value, when the fragment is written
/// that way already, or past `max_nodes`.
fn sliced(cx: &mut Context, n: u32, max_nodes: u32) -> Result<Option<u32>, crate::Error> {
    use crate::ops::BinOp;
    /// One part of the fragment: the node; the slice its operand is (the node's own, for a
    /// part that is no product); and for a product, its constant.
    struct Part {
        node: u32,
        slice: Slice,
        factor: Option<u64>,
    }
    // (Leased tables, not hash maps and an ordered one: the walk is made at every candidate
    // of a call and reads up to `max_nodes` nodes each time, and the maps were most of its
    // cost.)
    let mut memo = SliceMemo::new(cx);
    let mut parts: Vec<Part> = Vec::new();
    // How many parts can be read at each rotation of each value.
    let mut readers = Readers::new(cx);
    let mut seen = super::Lease::new(cx.len());
    let mut met = 0u32;
    let mut stack = vec![n];
    while let Some(i) = stack.pop() {
        if seen.insert(i, 0) {
            continue;
        }
        met += 1;
        if cx.const_val(i).is_some() {
            continue;
        }
        if met > max_nodes {
            return Ok(None);
        }
        let node = cx.node(i);
        let slice = slice_of(cx, i, &mut memo, 0);
        if slice.base != i {
            if slice.mask | slice.flip != 0 {
                parts.push(Part {
                    node: i,
                    slice,
                    factor: None,
                });
            }
            // What the part is a slice of is read too: a value of the fragment's own
            // (`(a & b) ^ k`, over two slices of another value) has parts below it.
            stack.push(slice.base);
            continue;
        }
        // Read as it is: one reader of itself, unrotated.
        readers.add(i, 0);
        if mixed_op(node.op) {
            if node.op == OpCode::Mul && cx.width_of(i).bits() <= 64 {
                let konst = |j: u32| cx.const_val(j).and_then(|c| c.to_u64());
                let product = match (konst(node.a), konst(node.b)) {
                    (None, Some(c)) => Some((node.a, c)),
                    (Some(c), None) => Some((node.b, c)),
                    _ => None,
                };
                if let Some((x, c)) = product
                    && c != 0
                    && c & 1 == 0
                {
                    parts.push(Part {
                        node: i,
                        slice: slice_of(cx, x, &mut memo, 0),
                        factor: Some(c),
                    });
                }
            }
            stack.extend(node.children());
        }
    }
    // The readings of a part: the slice at each rotation it can be read at, with the shift
    // that makes the part of it (a product's operand shifted up by `k` of its constant's low
    // zero bits, the rest of the constant a factor; any other part's slice `k` bits lower,
    // shifted up).
    let readings = |cx: &Context, p: &Part| -> Vec<(Slice, u32)> {
        let w = u32::from(cx.width_of(p.node).bits());
        let ones = if w >= 64 { u64::MAX } else { (1u64 << w) - 1 };
        let s = p.slice;
        match p.factor {
            Some(c) => (0..=c.trailing_zeros().min(w - 1))
                .map(|k| {
                    let up = Slice {
                        rot: (s.rot + k) % w,
                        mask: s.mask << k & ones,
                        flip: s.flip << k & ones,
                        ..s
                    };
                    (up, k)
                })
                .filter(|(up, _)| up.mask | up.flip != 0)
                .collect(),
            None => (0..=(s.mask | s.flip).trailing_zeros().min(w - 1))
                .map(|k| {
                    let down = Slice {
                        rot: (s.rot + w - k) % w,
                        mask: s.mask >> k,
                        flip: s.flip >> k,
                        ..s
                    };
                    (down, k)
                })
                .collect(),
        }
    };
    for p in &parts {
        for (s, _) in readings(cx, p) {
            readers.add(s.base, s.rot);
        }
    }
    // A slice as a node over its rotation.
    let over = |cx: &mut Context, s: &Slice| -> Result<u32, crate::Error> {
        let w = cx.width_of(s.base).bits();
        let ones = if w >= 64 { u64::MAX } else { (1u64 << w) - 1 };
        let mut v = match s.rot {
            0 => s.base,
            r => {
                let k = cx.mk_const_u64(w, u64::from(r))?;
                cx.c_bin(BinOp::RotL, s.base, k)?
            }
        };
        if s.mask != ones {
            let k = cx.mk_const_u64(w, s.mask)?;
            v = cx.c_bin(BinOp::And, v, k)?;
        }
        if s.flip != 0 {
            let k = cx.mk_const_u64(w, s.flip)?;
            v = cx.c_bin(BinOp::Xor, v, k)?;
        }
        Ok(v)
    };
    let mut repl: crate::hash::IdMap<u32, u32> = crate::hash::IdMap::default();
    // Whether some part is read through a shift or a rotation (else the fragment reads its
    // values as they are, and there is nothing to relate).
    let mut moved = false;
    for p in &parts {
        // The rotation the most parts read, the part's own first among equals.
        let best = readings(cx, p)
            .into_iter()
            .map(|(s, k)| (readers.get(s.base, s.rot), s, k))
            .filter(|(votes, _, _)| *votes >= 2)
            .min_by_key(|(votes, _, k)| (u32::MAX - votes, *k));
        let Some((_, s, k)) = best else {
            continue;
        };
        if p.factor.is_some() && k == 0 {
            continue;
        }
        let w = cx.width_of(p.node).bits();
        let x = over(cx, &s)?;
        let v = match p.factor {
            Some(c) => {
                let rest = cx.mk_const_u64(w, c >> k)?;
                cx.c_bin(BinOp::Mul, x, rest)?
            }
            None if k == 0 => x,
            None => {
                let by = cx.mk_const_u64(w, u64::from(k))?;
                cx.c_bin(BinOp::Shl, x, by)?
            }
        };
        moved |= s.rot != 0 || k != 0;
        if v != p.node {
            repl.insert(p.node, v);
        }
    }
    if repl.is_empty() || !moved {
        return Ok(None);
    }
    let root = cx.substitute_ids(&[n], &repl)?[0];
    Ok((root != n).then_some(root))
}

/// Commits `root`, node `n`'s fragment as [`sliced`] wrote it (built from arena index
/// `before` on), where that alone makes the DAG smaller: the parts that were one slice of one
/// rotation are one node, and what the builder folds over it is gone. `None` when it is no
/// smaller (nothing is retired: the readings asked next are over `root`), else the step: a
/// rejection has retired `root`'s nodes.
///
/// [`sliced`] rewrites by construction (each part is the bits its [`Slice`] says); the two
/// are compared at the run's sample points as a lifted answer is.
fn sliced_itself(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    cfg: &MbaConfig,
    n: u32,
    root: u32,
    before: u32,
) -> Result<Option<Step>, Stop> {
    let Ok((_, bindings)) = lower_id(cx, n, &cfg.limits) else {
        return Ok(None);
    };
    if !super::margin(r, cx, n, root, &bindings.atoms)?.is_some_and(|m| m > 0) {
        return Ok(None);
    }
    r.sample(cx, n)?;
    r.sample(cx, root)?;
    if r.samples[&n] != r.samples[&root] {
        count(r).refuted += 1;
        discard(r, cx, before);
        return Ok(Some(Step::Normal(Fin::FINAL)));
    }
    r.explain_with(|| crate::engine::Explanation::Mba {
        atoms: bindings.atoms.iter().map(|&a| cx.handle(a)).collect(),
        evidence: "slices",
        test: None,
        points: 0,
    });
    let out = finish(
        r,
        cx,
        PassKind::Mba,
        n,
        root,
        before,
        &bindings.atoms,
        Fin::FINAL,
    )?;
    if matches!(out, Step::To(..)) {
        count(r).simplified += 1;
    }
    Ok(Some(out))
}

/// Whether the fragment under `root` holds, below `root`, one the MBA phase asked about in
/// this call and kept as it is (`Runner::mba_kept`): the solver declined it for its size (too
/// many atoms, variables or bit classes), ran out of steps on it, or spent `KEPT_STEPS` or more
/// finding it had no simpler form, which keeps every larger fragment back; or its answer would
/// not have made the DAG smaller, or the gate could not prove it, which keeps back only a
/// `root` that wraps it alone (no other branch of `root` reads one of its atoms, where the two
/// could cancel when solved whole: `core − core'`). The larger fragment is then not asked. It has as many
/// atoms as the one inside it; the solver would pay for the inner fragment's normal form
/// again, at a cost that grows with the fragment; and what kept the inner answer back (its
/// nodes are shared, its normal form is as large, no certificate decides it) keeps back an
/// answer that holds it. An obfuscated value read by a chain of operations asks once at the
/// first of them where it asked at every one (27 questions of 820 nodes in one measured
/// question, 310,000 steps each, half the run's steps), and so do fragments that share a core
/// whose answer was no smaller (five of 110 to 197 nodes in another, 2.5 million steps and no
/// rewrite). `root` itself is asked again: the call remembers its answer, and what kept it
/// back may be gone in a later round.
///
/// One whose question ran out of steps at this round's depth (`Runner::mba_shallow`) keeps the
/// larger fragment back for the round only: [`Kept::Shallow`], where nothing below is kept
/// for the call.
fn holds_kept(r: &Runner<'_, '_>, cx: &Context, root: u32, bindings: &Bindings) -> Option<Kept> {
    if r.mba.kept.is_empty() && r.mba.shallow.is_empty() {
        return None;
    }
    let mut found = None;
    let mut local_kept: Vec<u32> = Vec::new();
    let mut seen = super::Lease::new(cx.len());
    for &a in &bindings.atoms {
        seen.insert(a, 0);
    }
    let mut stack: Vec<u32> = cx.node(root).children().collect();
    while let Some(i) = stack.pop() {
        if seen.insert(i, 0) {
            continue;
        }
        if let Some(&hard) = r.mba.kept.get(&i) {
            if hard {
                return Some(Kept::Whole);
            }
            local_kept.push(i);
        }
        if r.mba.shallow.contains_key(&i) {
            found = Some(Kept::Shallow);
        }
        stack.extend(cx.node(i).children());
    }
    if !local_kept.is_empty() {
        // A locally kept sub-fragment (`not_smaller`, `proof_unknown`) only keeps `root` back
        // when `root` is an isolated wrapper over it: no atom of `i` is reachable from `root`
        // bypassing `i`. Where another branch of `root` reads one, the two branches can cancel
        // or shrink together when solved whole.
        //
        // One walk gives every interior node a slot: the atoms below it (bit `k` for
        // `bindings.atoms[k]`, the first 64) and its users here. The atoms reachable bypassing
        // `i` are those below the operands of `i`'s users (up to `root`) that do not lead to
        // `i`, so each kept fragment reads its users, not the whole fragment again.
        let mut atom_idx = super::Lease::new(cx.len());
        for (idx, &a) in bindings.atoms.iter().enumerate() {
            atom_idx.insert(a, idx as u32);
        }
        let mut slot = super::Lease::new(cx.len());
        let (mut nodes, mut below) = (Vec::<u32>::new(), Vec::<u64>::new());
        let atoms_of = |c: u32, slot: &super::Lease, below: &[u64]| match atom_idx.get(c) {
            Some(k) if k < 64 => 1u64 << k,
            Some(_) => 0,
            None => slot.get(c).map_or(0, |s| below[s as usize]),
        };
        // (In post-order: a node is left once every operand has been.)
        let mut walk = vec![(root, false)];
        while let Some((x, left)) = walk.pop() {
            if left {
                let m = (cx.node(x).children()).fold(0, |m, c| m | atoms_of(c, &slot, &below));
                if let Some(s) = slot.get(x) {
                    below[s as usize] = m;
                }
                continue;
            }
            if slot.get(x).is_some() {
                continue;
            }
            slot.insert(x, nodes.len() as u32);
            nodes.push(x);
            below.push(0);
            walk.push((x, true));
            let operands = cx.node(x).children().filter(|&c| atom_idx.get(c).is_none());
            walk.extend(operands.map(|c| (c, false)));
        }
        let mut users: Vec<Vec<u32>> = vec![Vec::new(); nodes.len()];
        for &x in &nodes {
            for c in cx.node(x).children() {
                if let Some(s) = slot.get(c) {
                    users[s as usize].push(x);
                }
            }
        }
        for i in local_kept {
            let Some(si) = slot.get(i) else {
                continue;
            };
            let inner = below[si as usize];
            // `i`'s users up to `root`, each once.
            let mut up = super::Lease::new(cx.len());
            let (mut todo, mut ancestors) = (vec![si], Vec::new());
            while let Some(s) = todo.pop() {
                for &u in &users[s as usize] {
                    if !up.insert(u, 0)
                        && let Some(su) = slot.get(u)
                    {
                        ancestors.push(u);
                        todo.push(su);
                    }
                }
            }
            let mut outer = 0u64;
            for &u in &ancestors {
                for c in cx.node(u).children() {
                    if c != i && up.get(c).is_none() {
                        outer |= atoms_of(c, &slot, &below);
                    }
                }
            }
            if outer & inner == 0 {
                return Some(Kept::Whole);
            }
        }
    }
    found
}

/// What [`holds_kept`] found below a fragment's root.
enum Kept {
    /// A fragment kept as it is for the call.
    Whole,
    /// One whose question a deeper round asks again.
    Shallow,
}

/// One question to the solver takes at most this fraction of the call's solver steps (and at
/// least [`SOLVE_SHARE_MIN`]). The solver's own limit is a million steps whatever the call
/// has, so in a call of two million one question that ran out took half of them, a fragment
/// holding it took the other half, and the rounds after had none. Of the answers committed
/// in 140 measured questions none took more than a quarter of its call's steps; 26 questions
/// that took more than that ended with nothing (out of steps, not smaller, or unproved).
const SOLVE_SHARE: u64 = 4;

/// See [`SOLVE_SHARE`].
const SOLVE_SHARE_MIN: u64 = 1 << 16;

/// The part of a call's solver steps the MBA phase's questions leave to the sweep that runs
/// after the round: one in this many. What a round leaves is often a sum the sweep's
/// certificates decide in a few hundred steps (one value under masks, the constant it adds up
/// to), where the solver's last questions of the round had taken every step: a call asked
/// with an eighth of the usual fuel stopped at 80 nodes, and at 42 with the part kept.
const SWEEP_RESERVE: u64 = 16;

/// [`step`]'s question at node `n`, lowered from `root` (`n` itself, or an equal rewrite of it):
/// the answer replaces `n`.
fn ask(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    cfg: &MbaConfig,
    n: u32,
    root: u32,
    reading: Option<Reading>,
    cap: Cap,
) -> Result<Step, Stop> {
    // Lease the per-call table so that the gate can borrow its stored input and answer
    // while charging the runner and checking the live host DAG. Neither the solver nor
    // the gate recursively asks the MBA phase.
    let mut answers = std::mem::take(&mut r.mba.answers);
    let result = ask_with_answers(r, cx, cfg, n, root, reading, cap, &mut answers);
    r.mba.answers = answers;
    result
}

#[allow(clippy::too_many_arguments)]
fn ask_with_answers(
    r: &mut Runner<'_, '_>,
    cx: &mut Context,
    cfg: &MbaConfig,
    n: u32,
    root: u32,
    reading: Option<Reading>,
    cap: Cap,
    answers: &mut crate::hash::IdMap<CacheKey, CachedAnswer>,
) -> Result<Step, Stop> {
    use std::collections::hash_map::Entry;

    let poly = r.inner.mba.solver.polynomial_fragments();
    // The whole fragment, or a narrower reading of it: semi-linear with a node cut off as
    // an atom (and an operand that is the atom less a constant written over it, see
    // `lower_id_over`), or with the arithmetic under its bitwise operators atoms.
    let lowered = match reading {
        None => lower_id(cx, root, &cfg.limits),
        Some(_) => lower_id_over(
            cx,
            root,
            &cfg.limits,
            reading,
            &crate::hash::IdMap::default(),
        ),
    };
    let (m, bindings) = match lowered {
        Ok(x) => x,
        Err(why) => {
            count(r).refused(&why);
            return Ok(Step::Normal(Fin::FINAL));
        }
    };
    let shape = m.shape();
    // Mixed fragments, and polynomials (a product of two non-constants) for a solver that asks
    // for them. A fragment whose casts hide the mix (`sext(a) + sext(~a)` is a xor, a
    // subtraction and a mask once its sign extensions are written out) is judged without them
    // (see `decast`), as the solver and the certificates read it.
    let mixed = shape.mixed
        || crate::mba::decast(&m).is_some_and(|d| {
            let s = d.shape();
            s.mixed || (s.degree >= 2 && poly)
        });
    if !mixed && !(shape.degree >= 2 && poly) {
        return Ok(Step::Normal(Fin::FINAL));
    }
    if shape.nodes < cfg.limits.min_nodes {
        count(r).refused(&Refusal::TooSmall);
        return Ok(Step::Normal(Fin::FINAL));
    }
    r.meter.charge(Counter::PassWork, u64::from(shape.nodes))?;
    // (Not the reading over atoms where it is another question than the whole fragment's: it
    // is asked where that one is not, within the steps of a retried question, and what made
    // the fragment it holds costly is arithmetic this reading does not look into.)
    let kept = match reading {
        Some(Reading::Shallow) if crate::mba::cuts(cx, &bindings) => None,
        _ => holds_kept(r, cx, root, &bindings),
    };
    match kept {
        Some(Kept::Whole) => {
            count(r).unsupported += 1;
            return Ok(Step::Normal(Fin::FINAL));
        }
        // No smaller a question than the one inside it that ran out of steps at this round's
        // depth: asked when that one has been.
        Some(Kept::Shallow) => {
            r.mba.deeper = true;
            return Ok(Step::Normal(Fin::PROVISIONAL));
        }
        None => {}
    }
    let inner = r.inner;
    let prover_id = inner.mba.prover.as_ref().map_or("", |p| p.id());
    // The question's content hash, once (it hashes every node).
    let mk = m.key();
    let mut kh = combine(mk[0], mk[1]);
    for b in inner.mba.solver.id().bytes().chain(prover_id.bytes()) {
        kh = combine(kh, u64::from(b));
    }
    // The trust setting is part of the key: an answer accepted on the backend's word or on
    // sampling must never be reused where that evidence is not accepted.
    kh = combine(
        combine(kh, u64::from(cfg.trust.backend_certificates)),
        u64::from(cfg.trust.sampled),
    );
    let key = CacheKey([
        combine(kh, LOWERING_VERSION),
        combine(kh ^ 0x6361_6368, mk[1]),
    ]);
    // An answer the gate could not prove earlier in this call (not for lack of budget): the
    // same question would get the same answer and the same verdict.
    if r.mba.unproved.contains_key(&key) {
        return Ok(Step::Normal(Fin::FINAL));
    }
    // What vouched for the answer (for an explanation): an answer from the cache was proved
    // when it was found.
    let mut evidence: (&'static str, Option<&'static str>, u64) = ("cache", None, 0);
    let (e, before) = match inner.mba.cache.get(&key) {
        Some(CacheEntry::NoSimpler) => {
            count(r).cache_hits += 1;
            return Ok(Step::Normal(Fin::FINAL));
        }
        Some(CacheEntry::Simplified(e)) if e.vars() == m.vars() => {
            count(r).cache_hits += 1;
            let before = cx.len() as u32;
            (r.build(cx, |cx| lift_id(cx, &e, &bindings))?, before)
        }
        _ => {
            // A question asked earlier in this call whose answer was not committed then (not
            // smaller, say): the same answer (every answer but running short is complete).
            let clock = r.mba_rejections.as_ref().map(|(c, _)| *c);
            let start = || clock.map(|c| c.now_ticks());
            let elapsed = |t| clock.zip(t).map(|(c, t)| c.now_ticks().saturating_sub(t));
            let mut solve = None;
            let cached = match answers.entry(key) {
                Entry::Occupied(hit) => {
                    count(r).cache_hits += 1;
                    hit.into_mut()
                }
                Entry::Vacant(slot) => {
                    // The solver works within its own limit and what is left of the run's
                    // account of its steps, and is charged the steps it spent. With nothing
                    // left the question is not asked: over budget, so not final.
                    //
                    // One question takes at most a share of the call's steps (see
                    // `SOLVE_SHARE`), and one the solver ran out of steps on is not asked
                    // again in this call with no more of them: the answer is the same.
                    let share = (r.meter.limit.mba_steps / SOLVE_SHARE).max(SOLVE_SHARE_MIN);
                    let full = cfg.budget.steps.min(share);
                    let (steps, deepens) = match cap {
                        Cap::Steps(s) => (s, false),
                        Cap::Depth(s) => (s, s < full),
                    };
                    // (Where a sweep runs after the round, the phase leaves it a part of
                    // the call's steps, see `SWEEP_RESERVE`.)
                    let reserve = match cfg.opaque_sweep || cfg.noise_forms || cfg.known_atoms {
                        true => r.meter.limit.mba_steps / SWEEP_RESERVE,
                        false => 0,
                    };
                    let left = r.meter.left_in(|b| b.mba_steps).saturating_sub(reserve);
                    let limit = full.min(steps).min(left);
                    // Whether a deeper round asks this question with more steps than it has
                    // here: running out of these is not the call's budget running out.
                    let shallow = deepens && limit == steps;
                    if limit == 0 || r.mba.exhausted.get(&key).is_some_and(|&l| limit <= l) {
                        count(r).exhausted += 1;
                        if shallow {
                            r.mba.shallow.insert(root, ());
                            r.mba.deeper = true;
                            return Ok(Step::Normal(Fin::PROVISIONAL));
                        }
                        return Ok(Step::Normal(Fin::capped(Exhausted::MbaSteps)));
                    }
                    // Out of calls, as out of steps: the question is not asked, and the rest of
                    // the call (the passes after this phase, the later rounds) goes on within
                    // its own limits. Stopping the call here left a question the prover
                    // simplifies as it was after one round, where the word pass of the next
                    // round finishes it.
                    if r.meter.left_in(|b| b.mba_calls) == 0 {
                        count(r).exhausted += 1;
                        return Ok(Step::Normal(Fin::capped(Exhausted::MbaCalls)));
                    }
                    r.meter.charge(Counter::MbaCalls, 1)?;
                    count(r).calls += 1;
                    // The solver's own evidence counts only where backend certificates are
                    // trusted: elsewhere the gate proves every answer itself.
                    let budget = cfg
                        .budget
                        .with_evidence(cfg.budget.evidence && cfg.trust.backend_certificates)
                        .with_steps(limit);
                    let began = start();
                    let (a, spent) = inner.mba.solver.solve_counted(&m, &budget);
                    solve = elapsed(began);
                    let spent = spent.min(r.meter.left_in(|b| b.mba_steps));
                    r.meter.charge(Counter::MbaSteps, spent)?;
                    if a == MbaAnswer::Exhausted {
                        r.mba.exhausted.insert(key, limit);
                        count(r).exhausted += 1;
                        if shallow {
                            r.mba.shallow.insert(root, ());
                            r.mba.deeper = true;
                            return Ok(Step::Normal(Fin::PROVISIONAL));
                        }
                        // A fragment that holds this one is no smaller a question.
                        r.mba.kept.insert(root, true);
                        let reason = if limit < cfg.budget.steps {
                            Exhausted::MbaSteps
                        } else {
                            Exhausted::MbaCalls
                        };
                        return Ok(Step::Normal(Fin::capped(reason)));
                    }
                    let kept = match &a {
                        MbaAnswer::Unsupported(why) => why.starts_with("too many").then_some(true),
                        MbaAnswer::NoSimpler => {
                            (spent >= r.inner.strategy.kept_steps).then_some(true)
                        }
                        _ => None,
                    };
                    if let Some(hard) = kept {
                        r.mba.kept.insert(root, hard);
                    }
                    slot.insert(CachedAnswer {
                        answer: a,
                        sample: None,
                    })
                }
            };
            match &cached.answer {
                MbaAnswer::Simplified { expr, claim } => {
                    if expr.vars() != m.vars() || expr.width() != m.width() {
                        count(r).refuted += 1;
                        return Ok(Step::Normal(Fin::FINAL));
                    }
                    // Charge the same pass work on a hit, including the deadline check.
                    // Only the deterministic point evaluation is reused, never a proof,
                    // a lifted node, or its sharing-sensitive cost.
                    let began = start();
                    charge(r, &m, expr, u64::from(SAMPLE_POINTS))?;
                    let reused = cached.sample.as_ref().is_some_and(|(input, _)| input == &m);
                    if !reused {
                        let agrees = agrees_at_sample(&m, expr, mk[0]);
                        cached.sample = Some((m, agrees));
                    }
                    let (m, agrees) = cached.sample.as_ref().expect("sample checked");
                    let sample = elapsed(began);
                    if !agrees {
                        count(r).refuted += 1;
                        return Ok(Step::Normal(Fin::FINAL));
                    }
                    // Cheap before expensive: an answer that would not make the DAG smaller is
                    // not worth proving (every check is still required to commit one).
                    let before = cx.len() as u32;
                    let e = r.build(cx, |cx| lift_id(cx, expr, &bindings))?;
                    if e == n {
                        return Ok(Step::Normal(Fin::FINAL));
                    }
                    let began = start();
                    if let Err(fin) = shrinks(r, cx, n, e, &bindings.atoms)? {
                        if let (Some((_, p)), Some(sample), Some(shrink)) =
                            (r.mba_rejections.as_mut(), sample, elapsed(began))
                        {
                            let cost = match (solve.is_some(), cap) {
                                (true, Cap::Depth(_)) => &mut p.fresh_whole,
                                (false, Cap::Depth(_)) => &mut p.cached_whole,
                                (true, Cap::Steps(_)) => &mut p.fresh_retry,
                                (false, Cap::Steps(_)) => &mut p.cached_retry,
                            };
                            cost.shrink += shrink;
                            cost.sample += sample;
                            cost.solve += solve.unwrap_or(0);
                            cost.count += 1;
                            cost.sample_hits += u64::from(reused);
                        }
                        r.mba.kept.insert(root, false);
                        count(r).not_smaller += 1;
                        r.stats.passes.entry("mba").or_default().rejected_cost += 1;
                        discard(r, cx, before);
                        return Ok(Step::Normal(fin));
                    }
                    // A question asked again another way (slices, a cut) proves its answer
                    // within a smaller share: the node's own question had the large one, and
                    // two retries that each took half the call's pass work left the root as
                    // it was (eleven of 140 measured questions).
                    let part = match reading.is_some() || root != n {
                        true => RETRY_GATE_SHARE,
                        false => GATE_SHARE,
                    };
                    let own = exact(r, m, expr, part)?;
                    if own.verdict == Verdict::Refuted {
                        count(r).refuted += 1;
                        discard(r, cx, before);
                        return Ok(Step::Normal(Fin::FINAL));
                    }
                    let by =
                        if own.verdict == Verdict::Proved {
                            Some("certificate")
                        } else if inner.mba.prover.as_ref().is_some_and(|p| {
                            p.prove_equal(m, expr, &cfg.budget) == Verdict::Proved
                        }) {
                            Some("prover")
                        } else if cfg.trust.backend_certificates && *claim >= Claim::Proved {
                            Some("backend")
                        } else if cfg.trust.sampled {
                            Some("sampled")
                        } else {
                            None
                        };
                    let proved = by.is_some();
                    if let Some(by) = by {
                        let test = own
                            .cert
                            .filter(|_| by == "certificate")
                            .map(crate::mba::certify::Cert::name);
                        evidence = (by, test, own.points);
                    }
                    if !proved {
                        count(r).proof_unknown += 1;
                        discard(r, cx, before);
                        // A certificate skipped for lack of budget might decide with more:
                        // not final.
                        let fin = if own.over_budget {
                            Fin::capped(Exhausted::PassWork)
                        } else {
                            r.mba.unproved.insert(key, ());
                            r.mba.kept.insert(root, false);
                            Fin::FINAL
                        };
                        return Ok(Step::Normal(fin));
                    }
                    inner
                        .mba
                        .cache
                        .put(&key, &CacheEntry::Simplified(expr.clone()));
                    (e, before)
                }
                MbaAnswer::NoSimpler => {
                    count(r).no_simpler += 1;
                    inner.mba.cache.put(&key, &CacheEntry::NoSimpler);
                    return Ok(Step::Normal(Fin::FINAL));
                }
                MbaAnswer::Unsupported(_) => {
                    count(r).unsupported += 1;
                    return Ok(Step::Normal(Fin::FINAL));
                }
                MbaAnswer::Exhausted => {
                    unreachable!("exhausted answers are never cached")
                }
            }
        }
    };
    // The lifted result must agree with the original term (checks lowering and lifting).
    if e != n {
        r.sample(cx, n)?;
        r.sample(cx, e)?;
        if r.samples[&n] != r.samples[&e] {
            count(r).refuted += 1;
            discard(r, cx, before);
            return Ok(Step::Normal(Fin::FINAL));
        }
    }
    r.explain_with(|| crate::engine::Explanation::Mba {
        atoms: bindings.atoms.iter().map(|&a| cx.handle(a)).collect(),
        evidence: evidence.0,
        test: evidence.1,
        points: evidence.2,
    });
    let out = finish(
        r,
        cx,
        PassKind::Mba,
        n,
        e,
        before,
        &bindings.atoms,
        Fin::FINAL,
    )?;
    if matches!(out, Step::To(..)) {
        count(r).simplified += 1;
    } else if e != n {
        count(r).not_smaller += 1;
        r.mba.kept.insert(root, false);
    }
    Ok(out)
}