celox-backend-x86 0.3.1

Celox x86-64 machine-code backend
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
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
//! Braun--Hack sections 4.2 and 4.3: W/S states and coupling plan.

use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet};

use crate::HashMap;
use crate::native::mir::{BlockId, MFunction, MInst, PackedStateHome, VReg};

use super::assignment::clobbers;
use super::cfg::NormalizedCfg;
use super::next_use::{NextUseAnalysis, NextUseDistance};
use super::reload::{EdgeUse, PlanningRecipes, PointUse, ReloadRecipeAnalysis, ResolvedRecipe};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub(super) struct LogicalValue(pub u32);

/// Sparse logical-value set with the same ascending iteration order as a
/// `BTreeSet`, stored contiguously for the allocator's small W/S frontiers.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(super) struct LogicalSet(Vec<LogicalValue>);

impl LogicalSet {
    fn new() -> Self {
        Self::default()
    }

    #[cfg(test)]
    pub(super) fn clear(&mut self) {
        self.0.clear();
    }

    pub(super) fn contains(&self, value: &LogicalValue) -> bool {
        self.0.binary_search(value).is_ok()
    }

    pub(super) fn insert(&mut self, value: LogicalValue) -> bool {
        let Err(index) = self.0.binary_search(&value) else {
            return false;
        };
        self.0.insert(index, value);
        true
    }

    fn remove(&mut self, value: &LogicalValue) -> bool {
        let Ok(index) = self.0.binary_search(value) else {
            return false;
        };
        self.0.remove(index);
        true
    }

    fn len(&self) -> usize {
        self.0.len()
    }

    fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    fn iter(&self) -> std::slice::Iter<'_, LogicalValue> {
        self.0.iter()
    }

    fn retain(&mut self, mut keep: impl FnMut(&LogicalValue) -> bool) {
        self.0.retain(|value| keep(value));
    }

    fn difference<'a>(&'a self, other: &'a Self) -> impl Iterator<Item = &'a LogicalValue> + 'a {
        self.0.iter().filter(|value| !other.contains(value))
    }
}

impl FromIterator<LogicalValue> for LogicalSet {
    fn from_iter<T: IntoIterator<Item = LogicalValue>>(iter: T) -> Self {
        let mut values = iter.into_iter().collect::<Vec<_>>();
        values.sort_unstable();
        values.dedup();
        Self(values)
    }
}

impl Extend<LogicalValue> for LogicalSet {
    fn extend<T: IntoIterator<Item = LogicalValue>>(&mut self, iter: T) {
        for value in iter {
            self.insert(value);
        }
    }
}

impl IntoIterator for LogicalSet {
    type Item = LogicalValue;
    type IntoIter = std::vec::IntoIter<LogicalValue>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a> IntoIterator for &'a LogicalSet {
    type Item = &'a LogicalValue;
    type IntoIter = std::slice::Iter<'a, LogicalValue>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub(super) struct SpillHome(pub u32);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum PointSide {
    Before,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct ProgramPoint {
    pub block: BlockId,
    pub instruction: usize,
    pub side: PointSide,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum PlannedOp {
    Spill {
        value: LogicalValue,
        home: SpillHome,
    },
    Reload {
        value: LogicalValue,
        home: SpillHome,
    },
    SpillPhi {
        value: LogicalValue,
        home: SpillHome,
    },
}

/// Materialization on one CFG edge.
///
/// A point operation reads or writes the home of one logical SSA value.  A
/// phi edge is different: it transfers a predecessor value into the
/// successor's logical identity.  Keeping both identities explicit prevents
/// a reload from accidentally reading the successor home when only the
/// predecessor home is valid.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum PlannedEdgeOp {
    Spill {
        source: LogicalValue,
        destination: LogicalValue,
        destination_home: SpillHome,
    },
    Reload {
        source: LogicalValue,
        source_home: SpillHome,
        destination: LogicalValue,
    },
}

pub(super) fn edge_reload_uses_transferred_home(
    operations: &[PlannedEdgeOp],
    reload_index: usize,
) -> bool {
    let Some(PlannedEdgeOp::Reload {
        source,
        source_home,
        destination,
    }) = operations.get(reload_index).copied()
    else {
        return false;
    };
    operations[..reload_index].iter().any(|operation| {
        matches!(
            operation,
            PlannedEdgeOp::Spill {
                source: spill_source,
                destination: spill_destination,
                destination_home,
            } if *spill_source == source
                && *spill_destination == destination
                && *destination_home == source_home
        )
    })
}

#[derive(Debug)]
pub(super) struct SpillPlan {
    pub logical: LogicalValues,
    pub homes: SpillHomes,
    pub point_ops: Vec<(ProgramPoint, PlannedOp)>,
    pub edge_ops: BTreeMap<(usize, usize), Vec<PlannedEdgeOp>>,
    /// Point reloads whose value is supplied by an independently verified
    /// path-specific MemorySSA recipe rather than a persistent spill home.
    pub recipe_reloads: BTreeSet<(BlockId, usize, LogicalValue)>,
    /// Phi-congruence homes whose complete selected reload set is supplied by
    /// exact rematerialization recipes instead of a stack slot.
    pub recipe_homes: BTreeSet<SpillHome>,
    /// Phi-congruence homes assigned to allocator-managed packed SimState
    /// words.  These homes remain ordinary W/S homes: unlike recipe-only
    /// homes, every path must execute the planned spill before a reload.
    pub state_homes: BTreeMap<SpillHome, PackedStateHome>,
    /// Exact MemorySSA recipe for every reload assigned to `state_homes`.
    /// Keys retain the pre-reconstruction insertion point; reconstruction
    /// independently proves the emitted load against final MIR.
    pub state_reload_recipes: BTreeMap<(BlockId, usize, LogicalValue), ResolvedRecipe>,
    pub w_entry: Vec<LogicalSet>,
    pub w_exit: Vec<LogicalSet>,
    pub s_entry: Vec<LogicalSet>,
    pub s_exit: Vec<LogicalSet>,
}

#[derive(Debug)]
struct BlockTransition {
    point_ops: Vec<(ProgramPoint, PlannedOp)>,
    recipe_reloads: BTreeSet<(BlockId, usize, LogicalValue)>,
    w_exit: LogicalSet,
    s_exit: LogicalSet,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct SpillPlanError {
    pub rule: &'static str,
    pub block: Option<BlockId>,
    pub instruction: Option<usize>,
    pub values: Vec<VReg>,
    pub message: String,
}

impl SpillPlanError {
    fn new(
        rule: &'static str,
        block: Option<BlockId>,
        instruction: Option<usize>,
        values: Vec<VReg>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            rule,
            block,
            instruction,
            values,
            message: message.into(),
        }
    }
}

#[derive(Debug)]
pub(super) struct LogicalValues {
    count: u32,
}

impl LogicalValues {
    fn build(func: &MFunction) -> Self {
        Self {
            count: func.vregs.count(),
        }
    }

    pub(super) fn of(&self, value: VReg) -> LogicalValue {
        LogicalValue(value.0)
    }

    fn checked_of(
        &self,
        value: VReg,
        block: Option<BlockId>,
        instruction: Option<usize>,
    ) -> Result<LogicalValue, SpillPlanError> {
        if value.0 >= self.count {
            return Err(SpillPlanError::new(
                "SPILL_PLAN.VALUE_RANGE",
                block,
                instruction,
                vec![value],
                format!(
                    "v{} is outside the spill plan's {} logical values",
                    value.0, self.count
                ),
            ));
        }
        Ok(LogicalValue(value.0))
    }
}

#[derive(Debug)]
pub(super) struct SpillHomes {
    count: u32,
}

impl SpillHomes {
    fn build(func: &MFunction) -> Result<Self, SpillPlanError> {
        let count = func.vregs.count() as usize;
        for block in &func.blocks {
            for phi in &block.phis {
                if phi.dst.0 as usize >= count {
                    return Err(SpillPlanError::new(
                        "SPILL_PLAN.VALUE_RANGE",
                        Some(block.id),
                        None,
                        vec![phi.dst],
                        format!(
                            "phi destination v{} is outside the function's {count} virtual registers",
                            phi.dst.0
                        ),
                    ));
                }
                for &(_, source) in &phi.sources {
                    if source.0 as usize >= count {
                        return Err(SpillPlanError::new(
                            "SPILL_PLAN.VALUE_RANGE",
                            Some(block.id),
                            None,
                            vec![source],
                            format!(
                                "phi source v{} is outside the function's {count} virtual registers",
                                source.0
                            ),
                        ));
                    }
                }
            }
        }
        Ok(Self {
            count: count as u32,
        })
    }

    pub(super) fn of_vreg(&self, value: VReg) -> SpillHome {
        debug_assert!(value.0 < self.count);
        SpillHome(value.0)
    }

    pub(super) fn of_logical(&self, value: LogicalValue) -> SpillHome {
        debug_assert!(value.0 < self.count);
        SpillHome(value.0)
    }

    pub(super) fn members(&self, home: SpillHome) -> impl Iterator<Item = VReg> + '_ {
        (home.0 < self.count).then_some(VReg(home.0)).into_iter()
    }
}

#[derive(Debug, Default)]
struct EdgeTranslation {
    to_successor: HashMap<LogicalValue, Vec<LogicalValue>>,
    to_predecessor: HashMap<LogicalValue, LogicalValue>,
}

/// Indexed logical-value translation across normalized phi edges.
///
/// Building the two directions in one pass over phi operands avoids rescanning
/// every phi (and its predecessor list) for every member of W/S. A destination
/// has exactly one source on an edge. One source may feed several phi
/// destinations, so the forward relation is one-to-many.
#[derive(Debug)]
struct EdgeTranslations {
    by_edge: HashMap<(usize, usize), EdgeTranslation>,
}

impl EdgeTranslations {
    fn build(
        func: &MFunction,
        cfg: &NormalizedCfg,
        logical: &LogicalValues,
    ) -> Result<Self, SpillPlanError> {
        let mut by_edge = HashMap::<(usize, usize), EdgeTranslation>::default();
        for (successor, block) in func.blocks.iter().enumerate() {
            for phi in &block.phis {
                let destination = logical.checked_of(phi.dst, Some(block.id), None)?;
                for &(predecessor_id, source) in &phi.sources {
                    let Some(&predecessor) = cfg.block_index.get(&predecessor_id) else {
                        return Err(SpillPlanError::new(
                            "SPILL_PLAN.PHI_PREDECESSOR",
                            Some(block.id),
                            None,
                            vec![source, phi.dst],
                            format!(
                                "phi source predecessor {predecessor_id} is absent from the normalized CFG"
                            ),
                        ));
                    };
                    if !cfg
                        .successors
                        .get(predecessor)
                        .is_some_and(|successors| successors.contains(&successor))
                    {
                        return Err(SpillPlanError::new(
                            "SPILL_PLAN.EDGE_EXISTS",
                            Some(predecessor_id),
                            None,
                            vec![source, phi.dst],
                            format!(
                                "phi edge {predecessor_id} -> {} is absent from the normalized CFG",
                                block.id
                            ),
                        ));
                    }
                    let source = logical.checked_of(source, Some(predecessor_id), None)?;
                    let translation = by_edge.entry((predecessor, successor)).or_default();
                    translation
                        .to_successor
                        .entry(source)
                        .or_default()
                        .push(destination);
                    if translation
                        .to_predecessor
                        .insert(destination, source)
                        .is_some()
                    {
                        return Err(SpillPlanError::new(
                            "SPILL_PLAN.PHI_DESTINATION_UNIQUE",
                            Some(predecessor_id),
                            None,
                            vec![VReg(source.0), VReg(destination.0)],
                            format!(
                                "phi destination v{} has duplicate source for {predecessor_id}",
                                destination.0
                            ),
                        ));
                    }
                }
            }
        }
        Ok(Self { by_edge })
    }

    fn to_successors(
        &self,
        predecessor: usize,
        successor: usize,
        value: LogicalValue,
    ) -> impl Iterator<Item = LogicalValue> + '_ {
        let destinations = self
            .by_edge
            .get(&(predecessor, successor))
            .and_then(|translation| translation.to_successor.get(&value))
            .map(Vec::as_slice)
            .unwrap_or_default();
        destinations
            .iter()
            .copied()
            .chain(destinations.is_empty().then_some(value))
    }

    fn to_predecessor(
        &self,
        predecessor: usize,
        successor: usize,
        value: LogicalValue,
    ) -> LogicalValue {
        self.by_edge
            .get(&(predecessor, successor))
            .and_then(|translation| translation.to_predecessor.get(&value))
            .copied()
            .unwrap_or(value)
    }
}

#[cfg(test)]
pub(super) fn plan(
    func: &MFunction,
    cfg: &NormalizedCfg,
    next_use: &NextUseAnalysis,
    registers: usize,
) -> Result<SpillPlan, SpillPlanError> {
    let planning_recipes = PlanningRecipes::stack_only(func.vregs.count());
    plan_with_recipe_costs(func, cfg, next_use, &planning_recipes, registers)
}

#[cfg(test)]
pub(super) fn plan_with_recipe_costs(
    func: &MFunction,
    cfg: &NormalizedCfg,
    next_use: &NextUseAnalysis,
    planning_recipes: &PlanningRecipes,
    registers: usize,
) -> Result<SpillPlan, SpillPlanError> {
    let mut working = func.clone();
    plan_internal(
        &mut working,
        cfg,
        next_use,
        planning_recipes,
        registers,
        None,
    )
}

pub(super) fn plan_with_integrated_schedule(
    func: &mut MFunction,
    cfg: &NormalizedCfg,
    next_use: &NextUseAnalysis,
    planning_recipes: &PlanningRecipes,
    registers: usize,
    constraints: &super::constraints::ConstraintModel,
) -> Result<SpillPlan, SpillPlanError> {
    plan_internal(
        func,
        cfg,
        next_use,
        planning_recipes,
        registers,
        Some(constraints),
    )
}

fn plan_internal(
    func: &mut MFunction,
    cfg: &NormalizedCfg,
    next_use: &NextUseAnalysis,
    planning_recipes: &PlanningRecipes,
    registers: usize,
    constraints: Option<&super::constraints::ConstraintModel>,
) -> Result<SpillPlan, SpillPlanError> {
    let logical = LogicalValues::build(func);
    let homes = SpillHomes::build(func)?;
    let edge_translations = EdgeTranslations::build(func, cfg, &logical)?;
    let mut result = SpillPlan {
        logical,
        homes,
        point_ops: Vec::new(),
        edge_ops: BTreeMap::new(),
        recipe_reloads: BTreeSet::new(),
        recipe_homes: BTreeSet::new(),
        state_homes: BTreeMap::new(),
        state_reload_recipes: BTreeMap::new(),
        w_entry: vec![LogicalSet::new(); func.blocks.len()],
        w_exit: vec![LogicalSet::new(); func.blocks.len()],
        s_entry: vec![LogicalSet::new(); func.blocks.len()],
        s_exit: vec![LogicalSet::new(); func.blocks.len()],
    };
    for block in 0..func.blocks.len() {
        let entry = if let Some(region) = next_use.region_at_entry(block) {
            init_loop_region(func, next_use, &result, block, region, registers)?
        } else {
            init_usual(
                func,
                cfg,
                next_use,
                planning_recipes,
                &result,
                &edge_translations,
                block,
                registers,
            )
        };
        let mut entry = entry;
        let live_entry = next_use.entry[block]
            .keys()
            .copied()
            .map(|value| {
                result
                    .logical
                    .checked_of(value, Some(func.blocks[block].id), Some(0))
            })
            .collect::<Result<LogicalSet, _>>()?;
        let exit_reload_costs = constraints
            .map(|_| {
                exit_reload_costs(
                    func,
                    cfg,
                    next_use,
                    planning_recipes,
                    &result.logical,
                    &edge_translations,
                    block,
                )
            })
            .transpose()?
            .unwrap_or_default();
        let (spilled, transition, order) = loop {
            // S means that a valid home exists on every path.  Every live
            // value omitted from W_entry therefore requires a home; edge
            // coupling below materializes any missing predecessor store.  A
            // resident value keeps an existing home only when every
            // predecessor already has one.
            let spilled =
                spilled_at_entry(cfg, &result, &edge_translations, block, &live_entry, &entry);
            let (transition, order) = if let Some(constraints) = constraints {
                let instruction_constraints =
                    constraints.instructions.get(block).ok_or_else(|| {
                        SpillPlanError::new(
                            "SPILL_PLAN.SCHEDULE_ORDER",
                            Some(func.blocks[block].id),
                            None,
                            Vec::new(),
                            "allocation constraints do not cover this block",
                        )
                    })?;
                let (transition, order) = plan_scheduled_block_transition(
                    func,
                    next_use,
                    planning_recipes,
                    &result.logical,
                    &result.homes,
                    block,
                    registers,
                    &entry,
                    spilled.clone(),
                    instruction_constraints,
                    &exit_reload_costs,
                )?;
                (transition, Some(order))
            } else {
                (
                    plan_block_transition(
                        func,
                        next_use,
                        planning_recipes,
                        &result.logical,
                        &result.homes,
                        block,
                        registers,
                        &entry,
                        spilled.clone(),
                    )?,
                    None,
                )
            };
            let rejected = entry_residents_evicted_before_first_use(
                func,
                next_use,
                block,
                &entry,
                &transition,
                order.as_deref(),
            );
            if rejected.is_empty() {
                break (spilled, transition, order);
            }
            entry.retain(|value| !rejected.contains(value));
        };
        if let Some(order) = order {
            let original = func.blocks[block].insts.clone();
            func.blocks[block].insts = order
                .into_iter()
                .map(|source| original[source].clone())
                .collect();
        }
        result.w_entry[block] = entry;
        result.s_entry[block] = spilled;
        result.point_ops.extend(transition.point_ops);
        result.recipe_reloads.extend(transition.recipe_reloads);
        result.w_exit[block] = transition.w_exit;
        result.s_exit[block] = transition.s_exit;
    }

    // Section 4.3.  Delaying this until every W/S exit is known is equivalent
    // to the paper's deferred handling of not-yet-processed backedges.
    let spilled_phis = result
        .point_ops
        .iter()
        .filter_map(|(_, operation)| match operation {
            PlannedOp::SpillPhi { value, .. } => Some(*value),
            _ => None,
        })
        .collect::<LogicalSet>();
    for successor in 0..func.blocks.len() {
        for &predecessor in &cfg.predecessors[successor] {
            let mut resident_spills = Vec::new();
            let mut home_transfers = Vec::new();
            let mut scratch_reloads = Vec::new();
            let mut resident_reloads = Vec::new();
            let predecessor_w = result.w_exit[predecessor].clone();
            let predecessor_s = result.s_exit[predecessor].clone();
            for &successor_value in &result.w_entry[successor] {
                let value =
                    edge_translations.to_predecessor(predecessor, successor, successor_value);
                if !predecessor_w.contains(&value) {
                    resident_reloads.push(PlannedEdgeOp::Reload {
                        source: value,
                        source_home: result.homes.of_logical(value),
                        destination: successor_value,
                    });
                }
            }
            for &successor_value in &result.s_entry[successor] {
                let value =
                    edge_translations.to_predecessor(predecessor, successor, successor_value);
                let source_home = result.homes.of_logical(value);
                let destination_home = result.homes.of_logical(successor_value);
                if source_home == destination_home && predecessor_s.contains(&value) {
                    continue;
                }
                if predecessor_w.contains(&value) {
                    resident_spills.push(PlannedEdgeOp::Spill {
                        source: value,
                        destination: successor_value,
                        destination_home,
                    });
                } else if predecessor_s.contains(&value) {
                    // A phi transfer between independent homes is a short
                    // edge-local reload/store pair.  Keeping the predecessor
                    // SSA value live merely to copy its successor home would
                    // recreate the phi-web live range this representation is
                    // intended to remove.
                    home_transfers.push(PlannedEdgeOp::Reload {
                        source: value,
                        source_home,
                        destination: successor_value,
                    });
                    home_transfers.push(PlannedEdgeOp::Spill {
                        source: successor_value,
                        destination: successor_value,
                        destination_home,
                    });
                }
            }
            for phi in &func.blocks[successor].phis {
                let destination = result.logical.of(phi.dst);
                if !spilled_phis.contains(&destination) {
                    continue;
                }
                let source = edge_translations.to_predecessor(predecessor, successor, destination);
                let source_home = result.homes.of_logical(source);
                let destination_home = result.homes.of_logical(destination);
                if source_home == destination_home && predecessor_s.contains(&source) {
                    continue;
                }
                if predecessor_w.contains(&source) {
                    resident_spills.push(PlannedEdgeOp::Spill {
                        source,
                        destination,
                        destination_home,
                    });
                } else if predecessor_s.contains(&source) {
                    home_transfers.push(PlannedEdgeOp::Reload {
                        source,
                        source_home,
                        destination,
                    });
                    home_transfers.push(PlannedEdgeOp::Spill {
                        source: destination,
                        destination,
                        destination_home,
                    });
                }
            }
            // A reload/store home transfer needs one transient register.
            // When every successor-resident value already survives in
            // predecessor W, no ordinary edge spill or reload creates that
            // slot.  Explicitly park one such value across all home
            // transfers.  Treating edge operations as free parallel copies
            // here produces NUM_REGS + 1 live values after reconstruction.
            if !home_transfers.is_empty() {
                let surviving_residents = result.w_entry[successor]
                    .iter()
                    .copied()
                    .filter_map(|destination| {
                        let source =
                            edge_translations.to_predecessor(predecessor, successor, destination);
                        predecessor_w
                            .contains(&source)
                            .then_some((source, destination))
                    })
                    .collect::<Vec<_>>();
                if surviving_residents.len() == registers {
                    let (source, destination) = surviving_residents[0];
                    let destination_home = result.homes.of_logical(destination);
                    if !resident_spills.iter().any(|operation| {
                        matches!(
                            operation,
                            PlannedEdgeOp::Spill {
                                source: spill_source,
                                destination: spill_destination,
                                destination_home: spill_home,
                            } if *spill_source == source
                                && *spill_destination == destination
                                && *spill_home == destination_home
                        )
                    }) {
                        resident_spills.push(PlannedEdgeOp::Spill {
                            source,
                            destination,
                            destination_home,
                        });
                    }
                    scratch_reloads.push(PlannedEdgeOp::Reload {
                        // The reload is physically read from the successor
                        // home, but it must split the predecessor logical
                        // live range.  Using `destination` as both identities
                        // leaves the original phi source live across every
                        // home transfer and reconstruction reaches
                        // NUM_REGS + 1 pressure despite the scratch spill.
                        source,
                        source_home: destination_home,
                        destination,
                    });
                }
            }
            // Consume edge-resident values before introducing reload
            // temporaries or successor live-ins.  Otherwise one transient
            // transfer can raise an already-full W_exit above capacity.
            let mut operations = resident_spills;
            operations.extend(home_transfers);
            operations.extend(scratch_reloads);
            operations.extend(resident_reloads);
            if !operations.is_empty() {
                result.edge_ops.insert((predecessor, successor), operations);
            }
        }
    }
    Ok(result)
}

#[allow(clippy::too_many_arguments)]
fn exit_reload_costs(
    func: &MFunction,
    cfg: &NormalizedCfg,
    next_use: &NextUseAnalysis,
    planning_recipes: &PlanningRecipes,
    logical: &LogicalValues,
    edge_translations: &EdgeTranslations,
    block: usize,
) -> Result<HashMap<LogicalValue, u32>, SpillPlanError> {
    let mut costs = HashMap::<LogicalValue, u32>::default();
    for &successor in &cfg.successors[block] {
        let mut demanded = LogicalSet::new();
        for &value in next_use.entry[successor].keys() {
            let destination =
                logical.checked_of(value, Some(func.blocks[successor].id), Some(0))?;
            demanded.insert(edge_translations.to_predecessor(block, successor, destination));
        }
        for phi in &func.blocks[successor].phis {
            if let Some((_, source)) = phi
                .sources
                .iter()
                .find(|(predecessor, _)| *predecessor == func.blocks[block].id)
            {
                demanded.insert(logical.checked_of(
                    *source,
                    Some(func.blocks[block].id),
                    Some(func.blocks[block].insts.len()),
                )?);
            }
        }
        for value in demanded {
            let reload = u32::from(reload_cost_on_edge(
                func,
                planning_recipes,
                block,
                successor,
                value,
            ));
            costs
                .entry(value)
                .and_modify(|cost| *cost = cost.saturating_add(reload))
                .or_insert(reload);
        }
    }
    Ok(costs)
}

fn spilled_at_entry(
    cfg: &NormalizedCfg,
    plan: &SpillPlan,
    edge_translations: &EdgeTranslations,
    block: usize,
    live_entry: &LogicalSet,
    resident: &LogicalSet,
) -> LogicalSet {
    let mut spilled = live_entry
        .difference(resident)
        .copied()
        .collect::<LogicalSet>();
    if !cfg.predecessors[block].is_empty() {
        spilled.extend(resident.iter().copied().filter(|value| {
            cfg.predecessors[block].iter().all(|predecessor| {
                let predecessor_value =
                    edge_translations.to_predecessor(*predecessor, block, *value);
                plan.s_exit[*predecessor].contains(&predecessor_value)
            })
        }));
    }
    spilled
}

/// Remove optimistic entry residents that do not survive to their first local
/// use.  Keeping such a value in W moves its inevitable store from the incoming
/// edge into the block and occupies a register before providing any use.  S is
/// therefore no more expensive on the executed path and can reuse an already
/// valid predecessor home.
///
/// Replanning is bounded by the initial W size, which is at most the target's
/// fixed register count.  Each iteration removes at least one value, so this
/// remains linear in MIR size for a fixed ISA and needs no CFG-sized copy.
fn entry_residents_evicted_before_first_use(
    func: &MFunction,
    next_use: &NextUseAnalysis,
    block: usize,
    resident: &LogicalSet,
    transition: &BlockTransition,
    order: Option<&[usize]>,
) -> LogicalSet {
    let first_use = |value: LogicalValue| {
        order.map_or_else(
            || next_use.next_local_use(block, 0, VReg(value.0)),
            |order| {
                order.iter().position(|&source| {
                    func.blocks[block].insts[source]
                        .uses()
                        .contains(&VReg(value.0))
                })
            },
        )
    };
    transition
        .point_ops
        .iter()
        .filter_map(|(point, operation)| match *operation {
            PlannedOp::Spill { value, .. }
                if resident.contains(&value)
                    && first_use(value).is_none_or(|first_use| point.instruction < first_use) =>
            {
                Some(value)
            }
            PlannedOp::Reload { value, .. }
                if resident.contains(&value)
                    && !transition.recipe_reloads.contains(&(
                        func.blocks[block].id,
                        point.instruction,
                        value,
                    ))
                    && first_use(value) == Some(point.instruction) =>
            {
                Some(value)
            }
            _ => None,
        })
        .collect()
}

#[allow(clippy::too_many_arguments)]
fn plan_block_transition(
    func: &MFunction,
    next_use: &NextUseAnalysis,
    planning_recipes: &PlanningRecipes,
    logical: &LogicalValues,
    homes: &SpillHomes,
    block: usize,
    registers: usize,
    w_entry: &LogicalSet,
    spilled: LogicalSet,
) -> Result<BlockTransition, SpillPlanError> {
    let mut planner = BlockTransitionPlanner::new(
        func,
        next_use,
        planning_recipes,
        logical,
        homes,
        block,
        registers,
        w_entry,
        spilled,
    )?;
    for (instruction, inst) in func.blocks[block].insts.iter().enumerate() {
        planner.step(
            TransitionPoint {
                output: instruction,
                source: instruction,
            },
            inst,
        )?;
    }
    planner.finish()
}

#[derive(Debug, Clone, Copy)]
struct TransitionPoint {
    /// Instruction position in the final block order.
    output: usize,
    /// Stable position in the order consumed by next-use and planning-recipe
    /// analysis.
    source: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct AllocationCandidateScore {
    blocked_by_deferred_reload: bool,
    pressure_delta: isize,
    continuation_tie: std::cmp::Reverse<bool>,
    resident_operand_tie: std::cmp::Reverse<usize>,
    operand_tie: std::cmp::Reverse<usize>,
    materialization_cost: u32,
    preferred_rank: usize,
    source: usize,
}

struct AllocationReadyQueue {
    ordered: BTreeSet<(AllocationCandidateScore, usize)>,
    by_source: BTreeSet<(usize, usize)>,
    scores: Vec<Option<AllocationCandidateScore>>,
}

impl AllocationReadyQueue {
    fn new(instructions: usize) -> Self {
        Self {
            ordered: BTreeSet::new(),
            by_source: BTreeSet::new(),
            scores: vec![None; instructions],
        }
    }

    fn insert(&mut self, instruction: usize, score: AllocationCandidateScore) {
        debug_assert!(self.scores[instruction].is_none());
        self.ordered.insert((score, instruction));
        self.by_source.insert((score.source, instruction));
        self.scores[instruction] = Some(score);
    }

    fn refresh(&mut self, instruction: usize, score: AllocationCandidateScore) {
        let Some(previous) = self.scores[instruction].replace(score) else {
            return;
        };
        self.ordered.remove(&(previous, instruction));
        self.ordered.insert((score, instruction));
    }

    fn pop(
        &mut self,
        current_resident: usize,
        register_capacity: usize,
        demanded: Option<usize>,
    ) -> Option<(AllocationCandidateScore, usize)> {
        let &(source, source_instruction) = self.by_source.first()?;
        let source_score = self.scores[source_instruction]?;
        debug_assert_eq!(source, source_score.source);
        let source_projected = if source_score.pressure_delta < 0 {
            current_resident.saturating_sub(source_score.pressure_delta.unsigned_abs())
        } else {
            current_resident.saturating_add(source_score.pressure_delta as usize)
        };
        let &(best_score, best_instruction) = self.ordered.first()?;
        let demanded = demanded.and_then(|instruction| {
            let score = self.scores[instruction]?;
            let projected = if score.pressure_delta < 0 {
                current_resident.saturating_sub(score.pressure_delta.unsigned_abs())
            } else {
                current_resident.saturating_add(score.pressure_delta as usize)
            };
            (!score.blocked_by_deferred_reload && projected <= register_capacity)
                .then_some((score, instruction))
        });
        let best_projected = if best_score.pressure_delta < 0 {
            current_resident.saturating_sub(best_score.pressure_delta.unsigned_abs())
        } else {
            current_resident.saturating_add(best_score.pressure_delta as usize)
        };
        let best_is_legal =
            !best_score.blocked_by_deferred_reload && best_projected <= register_capacity;
        let (score, instruction) = if let Some(demanded) = demanded {
            demanded
        } else if best_is_legal
            && (best_score.continuation_tie.0 || current_resident >= register_capacity)
        {
            (best_score, best_instruction)
        } else if !source_score.blocked_by_deferred_reload && source_projected <= register_capacity
        {
            (source_score, source_instruction)
        } else {
            (best_score, best_instruction)
        };
        self.ordered.remove(&(score, instruction));
        self.by_source.remove(&(score.source, instruction));
        self.scores[instruction] = None;
        Some((score, instruction))
    }

    fn contains(&self, instruction: usize) -> bool {
        self.scores.get(instruction).is_some_and(Option::is_some)
    }
}

struct DependencyDemandFrame {
    instruction: usize,
    next_dependency: usize,
}

struct DependencyDemand {
    target: usize,
    stack: Vec<DependencyDemandFrame>,
}

impl DependencyDemand {
    fn new(target: usize) -> Self {
        Self {
            target,
            stack: vec![DependencyDemandFrame {
                instruction: target,
                next_dependency: 0,
            }],
        }
    }

    /// Follow one unfinished sink packet backwards until its next ready
    /// prerequisite. Each dependency edge in this demand is scanned once.
    fn next_ready(&mut self, region: &super::schedule::ForwardReadyRegion) -> Option<usize> {
        loop {
            let frame_index = self.stack.len().checked_sub(1)?;
            let instruction = self.stack[frame_index].instruction;
            if region.is_emitted(instruction) {
                self.stack.pop();
                continue;
            }
            let dependency = {
                let dependencies = region.dependencies(instruction);
                let frame = &mut self.stack[frame_index];
                let mut dependency = None;
                while frame.next_dependency != dependencies.len() {
                    let candidate = dependencies[frame.next_dependency];
                    frame.next_dependency += 1;
                    if !region.is_emitted(candidate) {
                        dependency = Some(candidate);
                        break;
                    }
                }
                dependency
            };
            if let Some(dependency) = dependency {
                self.stack.push(DependencyDemandFrame {
                    instruction: dependency,
                    next_dependency: 0,
                });
                continue;
            }
            return region.is_ready(instruction).then_some(instruction);
        }
    }
}

struct ScheduledStepDelta {
    resident: Vec<LogicalValue>,
    deferred: Vec<LogicalValue>,
    remaining_uses: Vec<LogicalValue>,
    continuation: Vec<LogicalValue>,
}

#[allow(clippy::too_many_arguments)]
fn plan_scheduled_block_transition(
    func: &MFunction,
    next_use: &NextUseAnalysis,
    planning_recipes: &PlanningRecipes,
    logical: &LogicalValues,
    homes: &SpillHomes,
    block: usize,
    registers: usize,
    w_entry: &LogicalSet,
    spilled: LogicalSet,
    constraints: &[super::constraints::InstructionConstraints],
    exit_reload_costs: &HashMap<LogicalValue, u32>,
) -> Result<(BlockTransition, Vec<usize>), SpillPlanError> {
    let instructions = &func.blocks[block].insts;
    if instructions.len() != constraints.len() {
        return Err(SpillPlanError::new(
            "SPILL_PLAN.SCHEDULE_ORDER",
            Some(func.blocks[block].id),
            None,
            Vec::new(),
            "allocation constraints do not cover every block instruction",
        ));
    }
    let original_spilled = spilled.clone();
    let mut remaining =
        RemainingBlockUses::build(func, next_use, logical, block, exit_reload_costs, None)?;
    let mut planner = BlockTransitionPlanner::new(
        func,
        next_use,
        planning_recipes,
        logical,
        homes,
        block,
        registers,
        w_entry,
        spilled,
    )?;
    let mut order = Vec::with_capacity(instructions.len());
    let mut cursor = 0usize;
    while cursor != instructions.len() {
        if !super::schedule::is_allocation_schedulable_at(instructions, constraints, cursor) {
            let output = order.len();
            planner.step_scheduled(
                TransitionPoint {
                    output,
                    source: cursor,
                },
                &instructions[cursor],
                &mut remaining,
            )?;
            order.push(cursor);
            cursor += 1;
            continue;
        }

        let start = cursor;
        while cursor != instructions.len()
            && super::schedule::is_allocation_schedulable_at(instructions, constraints, cursor)
        {
            cursor += 1;
        }
        let end = cursor;
        let region = &instructions[start..end];
        let mut ready = super::schedule::ForwardReadyRegion::build(region).ok_or_else(|| {
            SpillPlanError::new(
                "SPILL_PLAN.SCHEDULE_DEPENDENCY",
                Some(func.blocks[block].id),
                Some(start),
                Vec::new(),
                "movable region does not have a forward dependency order",
            )
        })?;
        let mut queue = AllocationReadyQueue::new(region.len());
        let sinks = ready.sinks().to_vec();
        let mut next_sink = 0usize;
        let mut demand = sinks.first().copied().map(DependencyDemand::new);
        for &local in ready.ready() {
            let source = start + local;
            queue.insert(
                local,
                planner.candidate_score(source, &instructions[source], &remaining)?,
            );
        }
        while !ready.is_complete() {
            let demanded = demand.as_mut().and_then(|demand| demand.next_ready(&ready));
            let Some((score, local)) =
                queue.pop(planner.resident.len(), planner.registers, demanded)
            else {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.SCHEDULE_DEPENDENCY",
                    Some(func.blocks[block].id),
                    Some(start),
                    Vec::new(),
                    "movable region has no dependency-ready allocation candidate",
                ));
            };
            let source = start + local;
            if score.blocked_by_deferred_reload {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.RECIPE_RELOAD_ORDER",
                    Some(func.blocks[block].id),
                    Some(source),
                    instructions[source].uses().to_vec(),
                    "every dependency-ready instruction precedes an allocator-selected recipe reload point",
                ));
            }
            let output = order.len();
            let delta = planner.step_scheduled(
                TransitionPoint { output, source },
                &instructions[source],
                &mut remaining,
            )?;
            let newly_ready = ready.emit(local).ok_or_else(|| {
                SpillPlanError::new(
                    "SPILL_PLAN.SCHEDULE_DEPENDENCY",
                    Some(func.blocks[block].id),
                    Some(source),
                    Vec::new(),
                    "selected instruction was not dependency-ready",
                )
            })?;
            order.push(source);
            if demand.as_ref().is_some_and(|demand| demand.target == local) {
                next_sink += 1;
                while sinks
                    .get(next_sink)
                    .is_some_and(|&sink| ready.is_emitted(sink))
                {
                    next_sink += 1;
                }
                demand = sinks.get(next_sink).copied().map(DependencyDemand::new);
            }

            let mut refresh = BTreeSet::<usize>::new();
            for local in newly_ready {
                refresh.insert(local);
            }
            for value in delta
                .resident
                .into_iter()
                .chain(delta.deferred)
                .chain(delta.remaining_uses)
                .chain(delta.continuation)
            {
                for &candidate in ready.use_candidates(VReg(value.0)) {
                    if ready.is_ready(candidate) {
                        refresh.insert(candidate);
                    }
                }
            }
            for local in refresh {
                let source = start + local;
                let candidate =
                    planner.candidate_score(source, &instructions[source], &remaining)?;
                if queue.contains(local) {
                    queue.refresh(local, candidate);
                } else {
                    queue.insert(local, candidate);
                }
            }
        }
    }
    let transition = planner.finish()?;
    let identity = (0..instructions.len()).collect::<Vec<_>>();
    let live_out = next_use.exit[block]
        .keys()
        .copied()
        .collect::<BTreeSet<_>>();
    if super::schedule::preserves_original_pressure(instructions, &order, &live_out, registers) {
        return Ok((transition, order));
    }

    // The allocator's ready walk is intentionally local, so it can avoid one
    // immediate eviction by creating a much wider live wavefront later in the
    // block. Give a bottom-up pressure scheduler one chance to recover such a
    // block before preserving source order. The pressure scheduler itself
    // falls back to identity whenever its complete order is worse.
    let fallback = super::schedule::pressure_preferred_block_order(
        instructions,
        constraints,
        live_out.iter().copied(),
        registers,
    )
    .unwrap_or(identity);
    let transition = plan_explicit_block_order(
        func,
        next_use,
        planning_recipes,
        logical,
        homes,
        block,
        registers,
        w_entry,
        original_spilled,
        exit_reload_costs,
        &fallback,
    )?;
    Ok((transition, fallback))
}

#[allow(clippy::too_many_arguments)]
fn plan_explicit_block_order(
    func: &MFunction,
    next_use: &NextUseAnalysis,
    planning_recipes: &PlanningRecipes,
    logical: &LogicalValues,
    homes: &SpillHomes,
    block: usize,
    registers: usize,
    w_entry: &LogicalSet,
    spilled: LogicalSet,
    exit_reload_costs: &HashMap<LogicalValue, u32>,
    order: &[usize],
) -> Result<BlockTransition, SpillPlanError> {
    let instructions = &func.blocks[block].insts;
    let mut remaining = RemainingBlockUses::build(
        func,
        next_use,
        logical,
        block,
        exit_reload_costs,
        Some(order),
    )?;
    let mut planner = BlockTransitionPlanner::new(
        func,
        next_use,
        planning_recipes,
        logical,
        homes,
        block,
        registers,
        w_entry,
        spilled,
    )?;
    for (output, &source) in order.iter().enumerate() {
        let inst = instructions.get(source).ok_or_else(|| {
            SpillPlanError::new(
                "SPILL_PLAN.SCHEDULE_ORDER",
                Some(func.blocks[block].id),
                Some(source),
                Vec::new(),
                "explicit schedule references an instruction outside the block",
            )
        })?;
        planner.step_scheduled(TransitionPoint { output, source }, inst, &mut remaining)?;
    }
    planner.finish()
}

struct BlockTransitionPlanner<'a> {
    func: &'a MFunction,
    next_use: &'a NextUseAnalysis,
    planning_recipes: &'a PlanningRecipes,
    logical: &'a LogicalValues,
    homes: &'a SpillHomes,
    block: usize,
    registers: usize,
    transition: BlockTransition,
    resident: LogicalSet,
    spilled: LogicalSet,
    deferred_recipe_reloads: BTreeMap<LogicalValue, PointUse>,
    last_definition: Option<LogicalValue>,
}

impl<'a> BlockTransitionPlanner<'a> {
    #[allow(clippy::too_many_arguments)]
    fn new(
        func: &'a MFunction,
        next_use: &'a NextUseAnalysis,
        planning_recipes: &'a PlanningRecipes,
        logical: &'a LogicalValues,
        homes: &'a SpillHomes,
        block: usize,
        registers: usize,
        w_entry: &LogicalSet,
        mut spilled: LogicalSet,
    ) -> Result<Self, SpillPlanError> {
        let mut transition = BlockTransition {
            point_ops: Vec::new(),
            recipe_reloads: BTreeSet::new(),
            w_exit: LogicalSet::new(),
            s_exit: LogicalSet::new(),
        };
        let resident = w_entry.clone();
        for phi in &func.blocks[block].phis {
            let value = logical.checked_of(phi.dst, Some(func.blocks[block].id), Some(0))?;
            if !resident.contains(&value) {
                transition.point_ops.push((
                    ProgramPoint {
                        block: func.blocks[block].id,
                        instruction: 0,
                        side: PointSide::Before,
                    },
                    PlannedOp::SpillPhi {
                        value,
                        home: homes.of_logical(value),
                    },
                ));
                spilled.insert(value);
            }
        }
        Ok(Self {
            func,
            next_use,
            planning_recipes,
            logical,
            homes,
            block,
            registers,
            transition,
            resident,
            spilled,
            deferred_recipe_reloads: BTreeMap::new(),
            last_definition: None,
        })
    }

    fn step(&mut self, point: TransitionPoint, inst: &MInst) -> Result<(), SpillPlanError> {
        let before = LinearFutureUses {
            func: self.func,
            next_use: self.next_use,
            block: self.block,
            instruction: point.source,
        };
        let uses = self.begin_step(point, inst, &before)?;
        let after = LinearFutureUses {
            func: self.func,
            next_use: self.next_use,
            block: self.block,
            instruction: point.source + 1,
        };
        self.finish_step(point, inst, &uses, &after)
    }

    fn step_scheduled(
        &mut self,
        point: TransitionPoint,
        inst: &MInst,
        remaining: &mut RemainingBlockUses<'_>,
    ) -> Result<ScheduledStepDelta, SpillPlanError> {
        let resident_before = self.resident.iter().copied().collect::<Vec<_>>();
        let deferred_before = self
            .deferred_recipe_reloads
            .iter()
            .map(|(&value, &point)| (value, point))
            .collect::<Vec<_>>();
        let last_definition_before = self.last_definition;
        let uses = {
            let before = DynamicFutureUses(remaining);
            self.begin_step(point, inst, &before)?
        };
        let remaining_uses = remaining.emit(point.source, inst, self.logical)?;
        {
            let after = DynamicFutureUses(remaining);
            self.finish_step(point, inst, &uses, &after)?;
        }
        let mut resident = resident_before
            .iter()
            .copied()
            .filter(|value| !self.resident.contains(value))
            .chain(
                self.resident
                    .iter()
                    .copied()
                    .filter(|value| resident_before.binary_search(value).is_err()),
            )
            .collect::<Vec<_>>();
        resident.sort_unstable();

        let mut deferred = Vec::new();
        let (mut before_index, mut after) =
            (0usize, self.deferred_recipe_reloads.iter().peekable());
        while before_index < deferred_before.len() || after.peek().is_some() {
            match (deferred_before.get(before_index), after.peek().copied()) {
                (Some(&(before_value, before_point)), Some((&after_value, &after_point))) => {
                    match before_value.cmp(&after_value) {
                        Ordering::Less => {
                            deferred.push(before_value);
                            before_index += 1;
                        }
                        Ordering::Equal => {
                            if before_point != after_point {
                                deferred.push(before_value);
                            }
                            before_index += 1;
                            after.next();
                        }
                        Ordering::Greater => {
                            deferred.push(after_value);
                            after.next();
                        }
                    }
                }
                (Some(&(before_value, _)), None) => {
                    deferred.push(before_value);
                    before_index += 1;
                }
                (None, Some((&after_value, _))) => {
                    deferred.push(after_value);
                    after.next();
                }
                (None, None) => break,
            }
        }

        let mut continuation = [last_definition_before, self.last_definition]
            .into_iter()
            .flatten()
            .collect::<Vec<_>>();
        continuation.sort_unstable();
        continuation.dedup();
        Ok(ScheduledStepDelta {
            resident,
            deferred,
            remaining_uses,
            continuation,
        })
    }

    fn candidate_score(
        &self,
        source: usize,
        inst: &MInst,
        remaining: &RemainingBlockUses<'_>,
    ) -> Result<AllocationCandidateScore, SpillPlanError> {
        let block_id = self.func.blocks[self.block].id;
        let mut uses = inst
            .uses()
            .iter()
            .copied()
            .map(|value| self.logical.checked_of(value, Some(block_id), Some(source)))
            .collect::<Result<Vec<_>, _>>()?;
        uses.sort_unstable();
        uses.dedup();
        let mut blocked_by_deferred_reload = false;
        let mut missing = 0usize;
        let mut resident_operands = 0usize;
        let mut materialization_cost = 0u32;
        let costs = super::cost::MachineSpillCosts::with_recipes(self.func, self.planning_recipes);
        for &value in &uses {
            if self.resident.contains(&value) {
                resident_operands += 1;
                continue;
            }
            missing += 1;
            let point = PointUse {
                block: block_id,
                instruction: source,
                value: VReg(value.0),
            };
            if let Some(&expected) = self.deferred_recipe_reloads.get(&value) {
                if expected != point {
                    blocked_by_deferred_reload = true;
                    continue;
                }
                materialization_cost = materialization_cost.saturating_add(u32::from(
                    self.planning_recipes
                        .point_specific_materialization_cost(point)
                        .unwrap_or_else(|| costs.persistent_reload(VReg(value.0))),
                ));
            } else {
                materialization_cost = materialization_cost
                    .saturating_add(u32::from(costs.persistent_reload(VReg(value.0))));
            }
        }
        let dying = uses
            .iter()
            .filter(|&&value| remaining.remaining_uses(value) == 1 && !remaining.is_live_out(value))
            .count();
        let definition_live = inst
            .def()
            .map(|value| self.logical.checked_of(value, Some(block_id), Some(source)))
            .transpose()?
            .is_some_and(|value| {
                remaining.remaining_uses(value) != 0 || remaining.is_live_out(value)
            });
        let pressure_delta = isize::try_from(missing + usize::from(definition_live))
            .unwrap_or(isize::MAX)
            .saturating_sub(isize::try_from(dying).unwrap_or(isize::MAX));
        Ok(AllocationCandidateScore {
            blocked_by_deferred_reload,
            pressure_delta,
            continuation_tie: std::cmp::Reverse(
                self.last_definition
                    .is_some_and(|value| uses.contains(&value)),
            ),
            // Reusing an operand already in W closes the residency cluster
            // which made that value worth keeping.  Rank this before a new
            // root with no operands; otherwise a stream of cheap Loads fills
            // W, spills those very results, and only then visits their uses.
            resident_operand_tie: std::cmp::Reverse(resident_operands),
            // Once W is full, an operand-bearing instruction closes existing
            // work (resident, spilled, or rematerializable).  A zero-input
            // root only creates another value which must displace such work.
            operand_tie: std::cmp::Reverse(uses.len()),
            materialization_cost,
            // Preserve the incoming ISel order as the deterministic final
            // tie-breaker after dependency locality and the current W/S
            // transition have made no distinction.
            preferred_rank: source,
            source,
        })
    }

    fn begin_step(
        &mut self,
        point: TransitionPoint,
        inst: &MInst,
        future_uses: &impl FutureUses,
    ) -> Result<Vec<LogicalValue>, SpillPlanError> {
        let block_id = self.func.blocks[self.block].id;
        let mut uses = inst
            .uses()
            .into_iter()
            .map(|value| {
                self.logical
                    .checked_of(value, Some(block_id), Some(point.output))
            })
            .collect::<Result<Vec<_>, _>>()?;
        uses.sort_unstable();
        uses.dedup();
        for &value in &uses {
            if self.resident.insert(value) {
                if let Some(expected) = self.deferred_recipe_reloads.remove(&value) {
                    let actual = PointUse {
                        block: block_id,
                        instruction: point.source,
                        value: VReg(value.0),
                    };
                    if expected != actual {
                        return Err(SpillPlanError::new(
                            "SPILL_PLAN.RECIPE_RELOAD_POINT",
                            Some(block_id),
                            Some(point.output),
                            vec![VReg(value.0)],
                            format!(
                                "deferred recipe reload expected {expected:?} but reached {actual:?}"
                            ),
                        ));
                    }
                    self.transition
                        .recipe_reloads
                        .insert((block_id, point.output, value));
                }
                self.transition.point_ops.push((
                    ProgramPoint {
                        block: block_id,
                        instruction: point.output,
                        side: PointSide::Before,
                    },
                    PlannedOp::Reload {
                        value,
                        home: self.homes.of_logical(value),
                    },
                ));
            }
        }
        limit(
            self.func,
            self.planning_recipes,
            self.homes,
            &mut self.transition.point_ops,
            self.block,
            point.output,
            self.registers,
            &uses,
            &mut self.resident,
            &mut self.spilled,
            &mut self.deferred_recipe_reloads,
            future_uses,
        )?;
        Ok(uses)
    }

    fn finish_step(
        &mut self,
        point: TransitionPoint,
        inst: &MInst,
        uses: &[LogicalValue],
        future_uses: &impl FutureUses,
    ) -> Result<(), SpillPlanError> {
        let block_id = self.func.blocks[self.block].id;
        let clobbered = clobbers(inst).len();
        if clobbered > self.registers {
            return Err(SpillPlanError::new(
                "SPILL_PLAN.CLOBBER_CAPACITY",
                Some(block_id),
                Some(point.output),
                inst.uses().to_vec(),
                format!(
                    "instruction clobbers {clobbered} registers but the allocator has only {}",
                    self.registers
                ),
            ));
        }
        if clobbered != 0 {
            limit_live_through_clobber(
                self.func,
                self.planning_recipes,
                self.homes,
                &mut self.transition.point_ops,
                self.block,
                point.output,
                self.registers.saturating_sub(clobbered),
                &mut self.resident,
                &mut self.spilled,
                &mut self.deferred_recipe_reloads,
                future_uses,
            )?;
        }
        if let Some(definition) = inst.def() {
            let definition =
                self.logical
                    .checked_of(definition, Some(block_id), Some(point.output))?;
            if !self.resident.contains(&definition) && self.resident.len() == self.registers {
                let Some(maximum) = self.registers.checked_sub(1) else {
                    return Err(SpillPlanError::new(
                        "SPILL_PLAN.OPERAND_PRESSURE",
                        Some(block_id),
                        Some(point.output),
                        vec![VReg(definition.0)],
                        "an instruction result requires a register but no registers are available",
                    ));
                };
                limit(
                    self.func,
                    self.planning_recipes,
                    self.homes,
                    &mut self.transition.point_ops,
                    self.block,
                    point.output,
                    maximum,
                    uses,
                    &mut self.resident,
                    &mut self.spilled,
                    &mut self.deferred_recipe_reloads,
                    future_uses,
                )?;
            }
            self.resident.insert(definition);
            self.last_definition = Some(definition);
        } else {
            self.last_definition = None;
        }
        self.resident
            .retain(|value| !future_uses.distance(*value).is_dead());
        Ok(())
    }

    fn finish(mut self) -> Result<BlockTransition, SpillPlanError> {
        if !self.deferred_recipe_reloads.is_empty() {
            return Err(SpillPlanError::new(
                "SPILL_PLAN.RECIPE_RELOAD_POINT",
                Some(self.func.blocks[self.block].id),
                None,
                self.deferred_recipe_reloads
                    .keys()
                    .map(|value| VReg(value.0))
                    .collect(),
                "deferred recipe reload did not reach its final local use",
            ));
        }
        self.transition.w_exit = self.resident;
        self.transition.s_exit = self.spilled;
        Ok(self.transition)
    }
}

#[allow(clippy::too_many_arguments)]
fn limit_live_through_clobber(
    func: &MFunction,
    planning_recipes: &PlanningRecipes,
    homes: &SpillHomes,
    point_ops: &mut Vec<(ProgramPoint, PlannedOp)>,
    block: usize,
    point_instruction: usize,
    capacity: usize,
    resident: &mut LogicalSet,
    spilled: &mut LogicalSet,
    deferred_recipe_reloads: &mut BTreeMap<LogicalValue, PointUse>,
    future_uses: &impl FutureUses,
) -> Result<(), SpillPlanError> {
    let mut live_through = resident
        .iter()
        .copied()
        .filter(|value| !future_uses.distance(*value).is_dead())
        .collect::<BTreeSet<_>>();
    while live_through.len() > capacity {
        let Some(victim) = live_through.iter().copied().max_by(|left, right| {
            compare_eviction_candidates(
                func,
                planning_recipes,
                spilled,
                future_uses,
                (*left, future_uses.distance(*left)),
                (*right, future_uses.distance(*right)),
            )
        }) else {
            return Err(SpillPlanError::new(
                "SPILL_PLAN.MIN_VICTIM",
                Some(func.blocks[block].id),
                Some(point_instruction),
                Vec::new(),
                "clobber pressure exceeded capacity but MIN had no live-through victim",
            ));
        };
        evict_value(
            func,
            planning_recipes,
            homes,
            point_ops,
            block,
            point_instruction,
            victim,
            spilled,
            deferred_recipe_reloads,
            future_uses,
        )?;
        live_through.remove(&victim);
        resident.remove(&victim);
    }
    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn init_usual(
    func: &MFunction,
    cfg: &NormalizedCfg,
    next_use: &NextUseAnalysis,
    planning_recipes: &PlanningRecipes,
    plan: &SpillPlan,
    edge_translations: &EdgeTranslations,
    block: usize,
    registers: usize,
) -> LogicalSet {
    let processed = cfg.predecessors[block]
        .iter()
        .copied()
        .filter(|predecessor| *predecessor < block)
        .collect::<Vec<_>>();
    if processed.is_empty() {
        return LogicalSet::new();
    }
    if processed.len() == 1 && cfg.predecessors[block].len() == 1 {
        let predecessor = processed[0];
        return plan.w_exit[predecessor]
            .iter()
            .copied()
            .flat_map(|value| edge_translations.to_successors(predecessor, block, value))
            .collect();
    }
    let mut frequency = HashMap::<LogicalValue, usize>::default();
    for predecessor in &processed {
        for &value in &plan.w_exit[*predecessor] {
            for value in edge_translations.to_successors(*predecessor, block, value) {
                *frequency.entry(value).or_default() += 1;
            }
        }
    }
    let mut candidates = frequency
        .keys()
        .copied()
        .filter_map(|value| {
            let mut keep_cost = 0u128;
            let mut drop_cost = 0u128;
            for &predecessor in &processed {
                let predecessor_value = edge_translations.to_predecessor(predecessor, block, value);
                if plan.w_exit[predecessor].contains(&predecessor_value) {
                    if !plan.s_exit[predecessor].contains(&predecessor_value) {
                        drop_cost = drop_cost
                            .saturating_add(u128::from(spill_cost(func, predecessor_value)));
                    }
                } else {
                    keep_cost = keep_cost.saturating_add(u128::from(reload_cost_on_edge(
                        func,
                        planning_recipes,
                        predecessor,
                        block,
                        predecessor_value,
                    )));
                }
            }
            if next_use.anticipated_at_entry(block, VReg(value.0)) {
                drop_cost = drop_cost.saturating_add((processed.len() as u128).saturating_mul(
                    local_use_cluster_cost(func, next_use, planning_recipes, block, 0, value),
                ));
            }
            let savings = drop_cost
                .checked_sub(keep_cost)
                .filter(|saving| *saving != 0)?;
            Some((
                value,
                savings,
                logical_entry_distance(func, next_use, block, value),
            ))
        })
        .collect::<Vec<_>>();
    candidates.sort_by(|left, right| compare_join_retention_candidates(*left, *right));
    candidates
        .into_iter()
        .take(registers)
        .map(|(value, _, _)| value)
        .collect()
}

/// Prefer the values for which entry residency avoids the most coupling and
/// guaranteed-use work per instruction of live-range occupancy.  Loop exits
/// dominate straight-line distance, matching global next-use ordering.
fn compare_join_retention_candidates(
    left: (LogicalValue, u128, NextUseDistance),
    right: (LogicalValue, u128, NextUseDistance),
) -> Ordering {
    match (left.2, right.2) {
        (NextUseDistance::Dead, NextUseDistance::Dead) => left.0.cmp(&right.0),
        (NextUseDistance::Dead, _) => Ordering::Greater,
        (_, NextUseDistance::Dead) => Ordering::Less,
        (
            NextUseDistance::Finite {
                loop_exits: left_exits,
                instructions: left_instructions,
            },
            NextUseDistance::Finite {
                loop_exits: right_exits,
                instructions: right_instructions,
            },
        ) => left_exits.cmp(&right_exits).then_with(|| {
            let left_span = left_instructions as u128 + 1;
            let right_span = right_instructions as u128 + 1;
            right
                .1
                .saturating_mul(left_span)
                .cmp(&left.1.saturating_mul(right_span))
                .then_with(|| left_instructions.cmp(&right_instructions))
                .then_with(|| left.0.cmp(&right.0))
        }),
    }
}

fn init_loop_region(
    func: &MFunction,
    next_use: &NextUseAnalysis,
    plan: &SpillPlan,
    block: usize,
    region: usize,
    registers: usize,
) -> Result<LogicalSet, SpillPlanError> {
    let mut alive = next_use.entry[block]
        .keys()
        .copied()
        .map(|value| {
            plan.logical
                .checked_of(value, Some(func.blocks[block].id), Some(0))
        })
        .collect::<Result<LogicalSet, _>>()?;
    for phi in &func.blocks[block].phis {
        alive.insert(
            plan.logical
                .checked_of(phi.dst, Some(func.blocks[block].id), Some(0))?,
        );
    }
    let Some(facts) = next_use.loop_regions.get(region) else {
        return Err(SpillPlanError::new(
            "SPILL_PLAN.NEXT_USE_REGION",
            Some(func.blocks[block].id),
            Some(0),
            Vec::new(),
            format!("next-use analysis references absent loop region {region}"),
        ));
    };
    let (mut candidates, mut live_through): (Vec<_>, Vec<_>) = alive
        .into_iter()
        .partition(|value| next_use.used_in_region(region, VReg(value.0)));
    candidates.sort_by_key(|value| logical_entry_distance(func, next_use, block, *value));
    if candidates.len() >= registers {
        return Ok(candidates.into_iter().take(registers).collect());
    }
    let internal_pressure = facts.max_pressure.saturating_sub(live_through.len());
    let free_loop = registers.saturating_sub(internal_pressure);
    live_through.sort_by_key(|value| logical_entry_distance(func, next_use, block, *value));
    Ok(candidates
        .into_iter()
        .chain(live_through.into_iter().take(free_loop))
        .take(registers)
        .collect())
}

trait FutureUses {
    fn distance(&self, value: LogicalValue) -> NextUseDistance;
    fn next_point(&self, value: LogicalValue) -> Option<PointUse>;
    fn exit_reload_cost(&self, _value: LogicalValue) -> u32 {
        0
    }
}

struct LinearFutureUses<'a> {
    func: &'a MFunction,
    next_use: &'a NextUseAnalysis,
    block: usize,
    instruction: usize,
}

impl FutureUses for LinearFutureUses<'_> {
    fn distance(&self, value: LogicalValue) -> NextUseDistance {
        self.next_use
            .distance_at(self.func, self.block, self.instruction, VReg(value.0))
    }

    fn next_point(&self, value: LogicalValue) -> Option<PointUse> {
        let instruction =
            self.next_use
                .next_local_use(self.block, self.instruction, VReg(value.0))?;
        Some(PointUse {
            block: self.func.blocks[self.block].id,
            instruction,
            value: VReg(value.0),
        })
    }
}

#[derive(Default)]
struct RemainingUses {
    points: Vec<(usize, usize)>,
    next: usize,
    count: usize,
}

struct RemainingBlockUses<'a> {
    block: BlockId,
    preferred_rank: Vec<usize>,
    remaining: HashMap<LogicalValue, RemainingUses>,
    exit: &'a HashMap<VReg, NextUseDistance>,
    exit_reload_costs: &'a HashMap<LogicalValue, u32>,
    emitted: Vec<bool>,
    emitted_count: usize,
}

impl<'a> RemainingBlockUses<'a> {
    fn build(
        func: &MFunction,
        next_use: &'a NextUseAnalysis,
        logical: &LogicalValues,
        block: usize,
        exit_reload_costs: &'a HashMap<LogicalValue, u32>,
        preferred_order: Option<&[usize]>,
    ) -> Result<Self, SpillPlanError> {
        let instructions = func.blocks[block].insts.len();
        let preferred_rank = if let Some(order) = preferred_order {
            if order.len() != instructions {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.SCHEDULE_ORDER",
                    Some(func.blocks[block].id),
                    None,
                    Vec::new(),
                    "explicit order does not cover every block instruction",
                ));
            }
            let mut ranks = vec![usize::MAX; instructions];
            for (rank, &source) in order.iter().enumerate() {
                let Some(slot) = ranks.get_mut(source) else {
                    return Err(SpillPlanError::new(
                        "SPILL_PLAN.SCHEDULE_ORDER",
                        Some(func.blocks[block].id),
                        Some(source),
                        Vec::new(),
                        "explicit order references an instruction outside the block",
                    ));
                };
                if std::mem::replace(slot, rank) != usize::MAX {
                    return Err(SpillPlanError::new(
                        "SPILL_PLAN.SCHEDULE_ORDER",
                        Some(func.blocks[block].id),
                        Some(source),
                        Vec::new(),
                        "explicit order references one instruction more than once",
                    ));
                }
            }
            ranks
        } else {
            (0..instructions).collect::<Vec<_>>()
        };
        let mut remaining = HashMap::<LogicalValue, RemainingUses>::default();
        for (source, inst) in func.blocks[block].insts.iter().enumerate() {
            let mut uses = inst.uses().to_vec();
            uses.sort_unstable();
            uses.dedup();
            for value in uses {
                let value = logical.checked_of(value, Some(func.blocks[block].id), Some(source))?;
                remaining
                    .entry(value)
                    .or_default()
                    .points
                    .push((preferred_rank[source], source));
            }
        }
        for uses in remaining.values_mut() {
            uses.points.sort_unstable();
            uses.count = uses.points.len();
        }
        for &value in next_use.exit[block].keys() {
            logical.checked_of(value, Some(func.blocks[block].id), Some(instructions))?;
        }
        Ok(Self {
            block: func.blocks[block].id,
            preferred_rank,
            remaining,
            exit: &next_use.exit[block],
            exit_reload_costs,
            emitted: vec![false; instructions],
            emitted_count: 0,
        })
    }

    fn emit(
        &mut self,
        source: usize,
        inst: &MInst,
        logical: &LogicalValues,
    ) -> Result<Vec<LogicalValue>, SpillPlanError> {
        if source >= self.emitted.len() || std::mem::replace(&mut self.emitted[source], true) {
            return Err(SpillPlanError::new(
                "SPILL_PLAN.SCHEDULE_ORDER",
                Some(self.block),
                Some(source),
                Vec::new(),
                "a source instruction was committed more than once",
            ));
        }
        self.emitted_count += 1;
        let mut uses = inst.uses().to_vec();
        uses.sort_unstable();
        uses.dedup();
        let mut changed = Vec::with_capacity(uses.len());
        for value in uses {
            let value = logical.checked_of(value, Some(self.block), Some(source))?;
            let uses = self.remaining.get_mut(&value).ok_or_else(|| {
                SpillPlanError::new(
                    "SPILL_PLAN.SCHEDULE_ORDER",
                    Some(self.block),
                    Some(source),
                    vec![VReg(value.0)],
                    "committed use has no remaining-use entry",
                )
            })?;
            let point = (self.preferred_rank[source], source);
            if uses.points.binary_search(&point).is_err() || uses.count == 0 {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.SCHEDULE_ORDER",
                    Some(self.block),
                    Some(source),
                    vec![VReg(value.0)],
                    "committed use was absent from its remaining-use set",
                ));
            }
            uses.count -= 1;
            while uses
                .points
                .get(uses.next)
                .is_some_and(|&(_, instruction)| self.emitted[instruction])
            {
                uses.next += 1;
            }
            changed.push(value);
        }
        Ok(changed)
    }

    fn remaining_uses(&self, value: LogicalValue) -> usize {
        self.remaining.get(&value).map_or(0, |uses| uses.count)
    }

    fn is_live_out(&self, value: LogicalValue) -> bool {
        self.exit.contains_key(&VReg(value.0))
    }

    fn distance(&self, value: LogicalValue) -> NextUseDistance {
        if let Some((rank, _)) = self
            .remaining
            .get(&value)
            .and_then(|uses| uses.points.get(uses.next))
            .copied()
        {
            return NextUseDistance::Finite {
                loop_exits: 0,
                instructions: rank.saturating_sub(self.emitted_count),
            };
        }
        let remaining_instructions = self.emitted.len().saturating_sub(self.emitted_count);
        match self.exit.get(&VReg(value.0)).copied() {
            Some(NextUseDistance::Finite {
                loop_exits,
                instructions,
            }) => NextUseDistance::Finite {
                loop_exits,
                instructions: instructions.saturating_add(remaining_instructions),
            },
            _ => NextUseDistance::Dead,
        }
    }

    fn next_point(&self, value: LogicalValue) -> Option<PointUse> {
        let uses = self.remaining.get(&value)?;
        let &(_, instruction) = uses.points.get(uses.next)?;
        Some(PointUse {
            block: self.block,
            instruction,
            value: VReg(value.0),
        })
    }

    fn exit_reload_cost(&self, value: LogicalValue) -> u32 {
        self.exit_reload_costs.get(&value).copied().unwrap_or(0)
    }
}

struct DynamicFutureUses<'view, 'data>(&'view RemainingBlockUses<'data>);

impl FutureUses for DynamicFutureUses<'_, '_> {
    fn distance(&self, value: LogicalValue) -> NextUseDistance {
        self.0.distance(value)
    }

    fn next_point(&self, value: LogicalValue) -> Option<PointUse> {
        self.0.next_point(value)
    }

    fn exit_reload_cost(&self, value: LogicalValue) -> u32 {
        self.0.exit_reload_cost(value)
    }
}

#[allow(clippy::too_many_arguments)]
fn limit(
    func: &MFunction,
    planning_recipes: &PlanningRecipes,
    homes: &SpillHomes,
    point_ops: &mut Vec<(ProgramPoint, PlannedOp)>,
    block: usize,
    point_instruction: usize,
    maximum: usize,
    pinned: &[LogicalValue],
    resident: &mut LogicalSet,
    spilled: &mut LogicalSet,
    deferred_recipe_reloads: &mut BTreeMap<LogicalValue, PointUse>,
    future_uses: &impl FutureUses,
) -> Result<(), SpillPlanError> {
    while resident.len() > maximum {
        let Some(victim) = resident
            .iter()
            .copied()
            .filter(|value| !pinned.contains(value))
            .max_by(|left, right| {
                compare_eviction_candidates(
                    func,
                    planning_recipes,
                    spilled,
                    future_uses,
                    (*left, future_uses.distance(*left)),
                    (*right, future_uses.distance(*right)),
                )
            })
        else {
            return Err(SpillPlanError::new(
                "SPILL_PLAN.OPERAND_PRESSURE",
                Some(func.blocks[block].id),
                Some(point_instruction),
                pinned.iter().map(|value| VReg(value.0)).collect(),
                format!(
                    "{} simultaneously pinned operands exceed the {maximum}-register capacity",
                    pinned.len()
                ),
            ));
        };
        evict_value(
            func,
            planning_recipes,
            homes,
            point_ops,
            block,
            point_instruction,
            victim,
            spilled,
            deferred_recipe_reloads,
            future_uses,
        )?;
        resident.remove(&victim);
    }
    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn evict_value(
    func: &MFunction,
    planning_recipes: &PlanningRecipes,
    homes: &SpillHomes,
    point_ops: &mut Vec<(ProgramPoint, PlannedOp)>,
    block: usize,
    point_instruction: usize,
    value: LogicalValue,
    spilled: &mut LogicalSet,
    deferred_recipe_reloads: &mut BTreeMap<LogicalValue, PointUse>,
    future_uses: &impl FutureUses,
) -> Result<(), SpillPlanError> {
    if spilled.contains(&value) {
        return Ok(());
    }
    if let Some((point, recipe_cost)) = next_use_point_recipe(planning_recipes, value, future_uses)
    {
        let stack_cost =
            spill_cost(func, value).saturating_add(reload_cost(func, planning_recipes, value));
        if recipe_cost < stack_cost {
            if let Some(previous) = deferred_recipe_reloads.insert(value, point) {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.RECIPE_RELOAD_POINT",
                    Some(func.blocks[block].id),
                    Some(point_instruction),
                    vec![VReg(value.0)],
                    format!("logical value already had deferred recipe reload {previous:?}"),
                ));
            }
            return Ok(());
        }
    }
    spilled.insert(value);
    point_ops.push((
        ProgramPoint {
            block: func.blocks[block].id,
            instruction: point_instruction,
            side: PointSide::Before,
        },
        PlannedOp::Spill {
            value,
            home: homes.of_logical(value),
        },
    ));
    Ok(())
}

/// Return the exact MemorySSA recipe at the next local use.
///
/// One eviction-to-reload interval is an independent residency cluster.  The
/// value does not need a persistent stack home merely because it has another
/// use after that reload: once reloaded it is resident again, and a later
/// eviction makes a fresh home decision against the MemorySSA version at that
/// later use.
fn next_use_point_recipe(
    planning_recipes: &PlanningRecipes,
    value: LogicalValue,
    future_uses: &impl FutureUses,
) -> Option<(PointUse, u16)> {
    let point = future_uses.next_point(value)?;
    planning_recipes
        .point_specific_materialization_cost(point)
        .map(|cost| (point, cost))
}

/// Compare two possible split points by the cost density of keeping the value
/// resident until its next use.  Braun--Hack MIN is the equal-cost special
/// case: with equal spill/reload costs, the farther next use is still evicted.
/// For target values with different rematerialization and memory costs, the
/// numerator is the machine-instruction cost avoided by retaining the value,
/// and the denominator is the register occupancy until that use.
fn compare_eviction_candidates(
    func: &MFunction,
    planning_recipes: &PlanningRecipes,
    spilled: &LogicalSet,
    future_uses: &impl FutureUses,
    left: (LogicalValue, NextUseDistance),
    right: (LogicalValue, NextUseDistance),
) -> Ordering {
    match (left.1, right.1) {
        (NextUseDistance::Dead, NextUseDistance::Dead) => left.0.cmp(&right.0),
        (NextUseDistance::Dead, _) => Ordering::Greater,
        (_, NextUseDistance::Dead) => Ordering::Less,
        (
            NextUseDistance::Finite {
                loop_exits: left_exits,
                instructions: left_instructions,
            },
            NextUseDistance::Finite {
                loop_exits: right_exits,
                instructions: right_instructions,
            },
        ) => left_exits.cmp(&right_exits).then_with(|| {
            let left_cost =
                eviction_cost(func, planning_recipes, spilled, left.0, future_uses) as u128;
            let right_cost =
                eviction_cost(func, planning_recipes, spilled, right.0, future_uses) as u128;
            let left_span = left_instructions as u128 + 1;
            let right_span = right_instructions as u128 + 1;
            // Lower avoided-cost density is the better eviction candidate.
            // Cross multiplication keeps the decision deterministic and free
            // of floating-point rounding.
            (right_cost * left_span)
                .cmp(&(left_cost * right_span))
                .then_with(|| left_instructions.cmp(&right_instructions))
                .then_with(|| left.0.cmp(&right.0))
        }),
    }
}

fn eviction_cost(
    func: &MFunction,
    planning_recipes: &PlanningRecipes,
    spilled: &LogicalSet,
    value: LogicalValue,
    future_uses: &impl FutureUses,
) -> u32 {
    let has_persistent_home = spilled.contains(&value);
    let local_reload =
        reload_cost_at_next_local_use(func, planning_recipes, value, future_uses).map(u32::from);
    let reload_cost = local_reload.unwrap_or_else(|| {
        let exit_cost = future_uses.exit_reload_cost(value);
        if exit_cost == 0 {
            u32::from(reload_cost(func, planning_recipes, value))
        } else {
            exit_cost
        }
    });
    let persistent_cost = reload_cost.saturating_add(if has_persistent_home {
        0
    } else {
        u32::from(spill_cost(func, value))
    });
    if has_persistent_home {
        return persistent_cost;
    }
    next_use_point_recipe(planning_recipes, value, future_uses)
        .map_or(persistent_cost, |(_, recipe_cost)| {
            persistent_cost.min(u32::from(recipe_cost))
        })
}

fn reload_cost_at_next_local_use(
    func: &MFunction,
    planning_recipes: &PlanningRecipes,
    value: LogicalValue,
    future_uses: &impl FutureUses,
) -> Option<u16> {
    let costs = super::cost::MachineSpillCosts::with_recipes(func, planning_recipes);
    future_uses
        .next_point(value)
        .map(|point| costs.reload_at_point(point))
}

/// Cost the complete guaranteed straight-line use cluster for a value which
/// is absent at block entry.  Point-specific MemorySSA recipes may differ
/// between uses, so every concrete point is queried independently.  If the
/// first guaranteed use lies beyond this block, retain the existing
/// cross-block fallback rather than assigning a zero cost.
fn local_use_cluster_cost(
    func: &MFunction,
    next_use: &NextUseAnalysis,
    planning_recipes: &PlanningRecipes,
    block: usize,
    instruction: usize,
    value: LogicalValue,
) -> u128 {
    let value = VReg(value.0);
    let uses = next_use.local_uses_from(block, instruction, value);
    if uses.is_empty() {
        return u128::from(reload_cost(func, planning_recipes, LogicalValue(value.0)));
    }
    let costs = super::cost::MachineSpillCosts::with_recipes(func, planning_recipes);
    uses.iter().fold(0u128, |cost, &instruction| {
        let reload = costs.reload_at_point(PointUse {
            block: func.blocks[block].id,
            instruction,
            value,
        });
        cost.saturating_add(u128::from(reload))
    })
}

fn reload_cost_on_edge(
    func: &MFunction,
    planning_recipes: &PlanningRecipes,
    predecessor: usize,
    successor: usize,
    value: LogicalValue,
) -> u16 {
    let value = VReg(value.0);
    super::cost::MachineSpillCosts::with_recipes(func, planning_recipes).reload_on_edge(EdgeUse {
        predecessor: func.blocks[predecessor].id,
        successor: func.blocks[successor].id,
        value,
    })
}

fn reload_cost(func: &MFunction, planning_recipes: &PlanningRecipes, value: LogicalValue) -> u16 {
    super::cost::MachineSpillCosts::with_recipes(func, planning_recipes)
        .persistent_reload(VReg(value.0))
}

fn spill_cost(func: &MFunction, value: LogicalValue) -> u16 {
    super::cost::MachineSpillCosts::from_descriptors(func).spill(VReg(value.0))
}

fn logical_entry_distance(
    func: &MFunction,
    next_use: &NextUseAnalysis,
    block: usize,
    value: LogicalValue,
) -> NextUseDistance {
    next_use.distance_at(func, block, 0, VReg(value.0))
}

impl SpillPlan {
    /// Finalize whole-home rematerialization after the W/S plan has exposed
    /// every concrete point and edge reload.  Reconstruction must materialize
    /// this decision; it may no longer infer a different home kind on its own.
    pub(super) fn select_recipe_homes(
        &mut self,
        func: &MFunction,
        cfg: &NormalizedCfg,
        analysis: &ReloadRecipeAnalysis,
    ) -> Result<(), SpillPlanError> {
        let base_costs = super::cost::MachineSpillCosts::from_descriptors(func);
        let mut candidates = BTreeSet::<SpillHome>::new();
        let mut rejected = BTreeSet::<SpillHome>::new();
        let mut baseline_costs = BTreeMap::<SpillHome, u128>::new();
        let mut recipe_costs = BTreeMap::<SpillHome, u128>::new();
        for &(point, operation) in &self.point_ops {
            match operation {
                PlannedOp::Reload { value, home } => {
                    candidates.insert(home);
                    let query = PointUse {
                        block: point.block,
                        instruction: point.instruction,
                        value: VReg(value.0),
                    };
                    if let Some(recipe) = analysis.resolved_recipe_at_point(query) {
                        let cost = u128::try_from(recipe.steps.len().saturating_add(1))
                            .unwrap_or(u128::MAX);
                        let baseline = baseline_costs.entry(home).or_default();
                        *baseline = baseline.saturating_add(
                            if self.recipe_reloads.contains(&(
                                point.block,
                                point.instruction,
                                value,
                            )) {
                                cost
                            } else {
                                u128::from(base_costs.persistent_reload(VReg(value.0)))
                            },
                        );
                        let total = recipe_costs.entry(home).or_default();
                        *total = total.saturating_add(cost);
                    } else {
                        let baseline = baseline_costs.entry(home).or_default();
                        *baseline = baseline.saturating_add(u128::from(
                            base_costs.persistent_reload(VReg(value.0)),
                        ));
                        rejected.insert(home);
                    }
                }
                PlannedOp::Spill { value, home } => {
                    let total = baseline_costs.entry(home).or_default();
                    *total = total.saturating_add(u128::from(spill_cost(func, value)));
                }
                PlannedOp::SpillPhi { value, home } => {
                    let Some(&block) = cfg.block_index.get(&point.block) else {
                        return Err(SpillPlanError::new(
                            "SPILL_PLAN.RECIPE_HOME_PHI",
                            Some(point.block),
                            Some(point.instruction),
                            vec![VReg(value.0)],
                            "recipe-home SpillPhi block is outside the normalized CFG",
                        ));
                    };
                    let Some(phi) = func.blocks[block]
                        .phis
                        .iter()
                        .find(|phi| phi.dst.0 == value.0)
                    else {
                        return Err(SpillPlanError::new(
                            "SPILL_PLAN.RECIPE_HOME_PHI",
                            Some(point.block),
                            Some(point.instruction),
                            vec![VReg(value.0)],
                            "recipe-home SpillPhi has no matching MIR phi",
                        ));
                    };
                    for &(predecessor, source) in &phi.sources {
                        let Some(&predecessor) = cfg.block_index.get(&predecessor) else {
                            return Err(SpillPlanError::new(
                                "SPILL_PLAN.RECIPE_HOME_PHI",
                                Some(point.block),
                                Some(point.instruction),
                                vec![VReg(value.0), source],
                                "recipe-home SpillPhi source is outside the normalized CFG",
                            ));
                        };
                        let source = LogicalValue(source.0);
                        if !self.s_exit[predecessor].contains(&source) {
                            let total = baseline_costs.entry(home).or_default();
                            *total = total.saturating_add(u128::from(spill_cost(func, source)));
                        }
                    }
                }
            }
        }
        for (&(predecessor, successor), operations) in &self.edge_ops {
            let Some(predecessor_block) = func.blocks.get(predecessor) else {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.RECIPE_HOME_EDGE",
                    None,
                    None,
                    Vec::new(),
                    format!("recipe-home predecessor index {predecessor} is outside function"),
                ));
            };
            if func.blocks.get(successor).is_none() {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.RECIPE_HOME_EDGE",
                    Some(predecessor_block.id),
                    None,
                    Vec::new(),
                    format!("recipe-home successor index {successor} is outside function"),
                ));
            }
            let insertion = super::cfg::edge_insertion_point(func, cfg, predecessor, successor)
                .ok_or_else(|| {
                    SpillPlanError::new(
                        "SPILL_PLAN.RECIPE_HOME_EDGE",
                        Some(predecessor_block.id),
                        None,
                        Vec::new(),
                        "recipe-home edge has no single-edge materialization point",
                    )
                })?;
            let insertion_block = &func.blocks[insertion.block];
            if insertion.instruction >= insertion_block.insts.len() {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.RECIPE_HOME_EDGE",
                    Some(insertion_block.id),
                    Some(insertion.instruction),
                    Vec::new(),
                    "recipe-home edge insertion point is outside its MIR block",
                ));
            }
            for &operation in operations {
                match operation {
                    PlannedEdgeOp::Reload {
                        source,
                        source_home,
                        ..
                    } => {
                        candidates.insert(source_home);
                        let total = baseline_costs.entry(source_home).or_default();
                        *total = total.saturating_add(u128::from(
                            base_costs.persistent_reload(VReg(source.0)),
                        ));
                        let query = PointUse {
                            block: insertion_block.id,
                            instruction: insertion.instruction,
                            value: VReg(source.0),
                        };
                        if let Some(recipe) = analysis.resolved_recipe_at_point(query) {
                            let cost = u128::try_from(recipe.steps.len().saturating_add(1))
                                .unwrap_or(u128::MAX);
                            let total = recipe_costs.entry(source_home).or_default();
                            *total = total.saturating_add(cost);
                        } else {
                            rejected.insert(source_home);
                        }
                    }
                    PlannedEdgeOp::Spill {
                        source,
                        destination_home,
                        ..
                    } => {
                        let total = baseline_costs.entry(destination_home).or_default();
                        *total = total.saturating_add(u128::from(spill_cost(func, source)));
                    }
                }
            }
        }
        candidates.retain(|home| {
            !self.state_homes.contains_key(home)
                && !rejected.contains(home)
                && recipe_costs.get(home).copied().unwrap_or(u128::MAX)
                    < baseline_costs.get(home).copied().unwrap_or_default()
        });
        self.recipe_homes = candidates;
        Ok(())
    }

    /// Independently prove that every reload assigned to a recipe-only home
    /// has an exact recipe at its final insertion point.  This verifier does
    /// not trust the candidate/rejection sets used by selection.
    pub(super) fn verify_recipe_homes(
        &self,
        func: &MFunction,
        cfg: &NormalizedCfg,
        analysis: &ReloadRecipeAnalysis,
    ) -> Result<(), SpillPlanError> {
        for &home in &self.recipe_homes {
            let mut reloads = 0usize;
            for &(point, operation) in &self.point_ops {
                let PlannedOp::Reload {
                    value,
                    home: reload_home,
                } = operation
                else {
                    continue;
                };
                if reload_home != home {
                    continue;
                }
                reloads += 1;
                let query = PointUse {
                    block: point.block,
                    instruction: point.instruction,
                    value: VReg(value.0),
                };
                if analysis.resolved_recipe_at_point(query).is_none() {
                    return Err(SpillPlanError::new(
                        "SPILL_PLAN.RECIPE_HOME_POINT",
                        Some(point.block),
                        Some(point.instruction),
                        vec![VReg(value.0)],
                        format!("recipe home {home:?} has a point reload without an exact recipe"),
                    ));
                }
            }
            for (&(predecessor, successor), operations) in &self.edge_ops {
                let Some(predecessor_block) = func.blocks.get(predecessor) else {
                    return Err(SpillPlanError::new(
                        "SPILL_PLAN.RECIPE_HOME_EDGE",
                        None,
                        None,
                        Vec::new(),
                        format!("recipe home {home:?} references absent predecessor {predecessor}"),
                    ));
                };
                let Some(successor_block) = func.blocks.get(successor) else {
                    return Err(SpillPlanError::new(
                        "SPILL_PLAN.RECIPE_HOME_EDGE",
                        Some(predecessor_block.id),
                        None,
                        Vec::new(),
                        format!("recipe home {home:?} references absent successor {successor}"),
                    ));
                };
                let insertion = super::cfg::edge_insertion_point(func, cfg, predecessor, successor)
                    .ok_or_else(|| {
                        SpillPlanError::new(
                            "SPILL_PLAN.RECIPE_HOME_EDGE",
                            Some(predecessor_block.id),
                            None,
                            Vec::new(),
                            "recipe-home edge has no single-edge materialization point",
                        )
                    })?;
                let insertion_block = &func.blocks[insertion.block];
                for &operation in operations {
                    let PlannedEdgeOp::Reload {
                        source,
                        source_home: reload_home,
                        ..
                    } = operation
                    else {
                        continue;
                    };
                    if reload_home != home {
                        continue;
                    }
                    reloads += 1;
                    let query = PointUse {
                        block: insertion_block.id,
                        instruction: insertion.instruction,
                        value: VReg(source.0),
                    };
                    if analysis.resolved_recipe_at_point(query).is_none() {
                        return Err(SpillPlanError::new(
                            "SPILL_PLAN.RECIPE_HOME_EDGE",
                            Some(predecessor_block.id),
                            None,
                            vec![VReg(source.0)],
                            format!(
                                "recipe home {home:?} has no exact recipe on edge {} -> {}",
                                predecessor_block.id, successor_block.id
                            ),
                        ));
                    }
                }
            }
            if reloads == 0 {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.RECIPE_HOME_RELOAD",
                    None,
                    None,
                    Vec::new(),
                    format!("recipe home {home:?} has no selected reload"),
                ));
            }
        }
        Ok(())
    }

    pub(super) fn verify(
        &self,
        func: &MFunction,
        cfg: &NormalizedCfg,
        registers: usize,
    ) -> Result<(), SpillPlanError> {
        let block_count = func.blocks.len();
        if self.w_entry.len() != block_count
            || self.w_exit.len() != block_count
            || self.s_entry.len() != block_count
            || self.s_exit.len() != block_count
        {
            return Err(SpillPlanError::new(
                "SPILL_PLAN.STATE_SHAPE",
                None,
                None,
                Vec::new(),
                format!(
                    "spill-plan state tables must all contain {block_count} rows (W_entry={}, W_exit={}, S_entry={}, S_exit={})",
                    self.w_entry.len(),
                    self.w_exit.len(),
                    self.s_entry.len(),
                    self.s_exit.len()
                ),
            ));
        }
        if self.logical.count != func.vregs.count() || self.homes.count != self.logical.count {
            return Err(SpillPlanError::new(
                "SPILL_PLAN.STATE_SHAPE",
                None,
                None,
                Vec::new(),
                format!(
                    "spill-plan value tables cover {} logical values and {} homes, but the function has {} virtual registers",
                    self.logical.count,
                    self.homes.count,
                    func.vregs.count()
                ),
            ));
        }

        for (block, state) in self.w_entry.iter().enumerate() {
            if state.len() > registers {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.PRESSURE",
                    Some(func.blocks[block].id),
                    Some(0),
                    state.iter().map(|value| VReg(value.0)).collect(),
                    format!(
                        "W_entry contains {} residents but only {registers} registers are available",
                        state.len()
                    ),
                ));
            }
        }
        for (block, state) in self.w_exit.iter().enumerate() {
            if state.len() > registers {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.PRESSURE",
                    Some(func.blocks[block].id),
                    Some(func.blocks[block].insts.len()),
                    state.iter().map(|value| VReg(value.0)).collect(),
                    format!(
                        "W_exit contains {} residents but only {registers} registers are available",
                        state.len()
                    ),
                ));
            }
        }

        for (block, states) in (0..block_count).map(|block| {
            (
                block,
                [
                    &self.w_entry[block],
                    &self.w_exit[block],
                    &self.s_entry[block],
                    &self.s_exit[block],
                ],
            )
        }) {
            for state in states {
                if let Some(value) = state.iter().find(|value| value.0 >= self.logical.count) {
                    return Err(SpillPlanError::new(
                        "SPILL_PLAN.VALUE_RANGE",
                        Some(func.blocks[block].id),
                        None,
                        vec![VReg(value.0)],
                        format!(
                            "spill-plan state references logical value {} but the plan contains {} values",
                            value.0, self.logical.count
                        ),
                    ));
                }
            }
        }

        for (&(predecessor, successor), operations) in &self.edge_ops {
            let Some(predecessor_block) = func.blocks.get(predecessor) else {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.EDGE_EXISTS",
                    None,
                    None,
                    Vec::new(),
                    format!("edge operation predecessor index {predecessor} is out of range"),
                ));
            };
            let Some(successor_block) = func.blocks.get(successor) else {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.EDGE_EXISTS",
                    Some(predecessor_block.id),
                    None,
                    Vec::new(),
                    format!("edge operation successor index {successor} is out of range"),
                ));
            };
            if !cfg.successors[predecessor].contains(&successor) {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.EDGE_EXISTS",
                    Some(predecessor_block.id),
                    None,
                    Vec::new(),
                    format!(
                        "planned edge operation targets {}, which is not a CFG successor",
                        successor_block.id
                    ),
                ));
            }
            if super::cfg::edge_insertion_point(func, cfg, predecessor, successor).is_none() {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.EDGE_ISOLATED",
                    Some(predecessor_block.id),
                    None,
                    Vec::new(),
                    "edge operation has no single-edge materialization point",
                ));
            }
            if operations.is_empty() {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.EDGE_EXISTS",
                    Some(predecessor_block.id),
                    None,
                    Vec::new(),
                    format!(
                        "edge-operation list for {} -> {} is empty",
                        predecessor_block.id, successor_block.id
                    ),
                ));
            }
            for (index, &operation) in operations.iter().enumerate() {
                self.verify_edge_operation(
                    operation,
                    Some(predecessor_block.id),
                    edge_reload_uses_transferred_home(operations, index),
                )?;
            }
        }
        for &(point, operation) in &self.point_ops {
            let Some(&block) = cfg.block_index.get(&point.block) else {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.POINT_RANGE",
                    Some(point.block),
                    Some(point.instruction),
                    Vec::new(),
                    "planned operation references a block absent from the normalized CFG",
                ));
            };
            if point.instruction > func.blocks[block].insts.len() {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.POINT_RANGE",
                    Some(point.block),
                    Some(point.instruction),
                    Vec::new(),
                    format!(
                        "planned operation is outside the block's {} instructions",
                        func.blocks[block].insts.len()
                    ),
                ));
            }
            self.verify_operation(operation, Some(point.block), Some(point.instruction))?;
        }
        for &(block, instruction, value) in &self.recipe_reloads {
            let matching_reload = self.point_ops.iter().any(|(point, operation)| {
                point.block == block
                    && point.instruction == instruction
                    && matches!(operation, PlannedOp::Reload { value: reload, .. } if *reload == value)
            });
            if !matching_reload {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.RECIPE_RELOAD_POINT",
                    Some(block),
                    Some(instruction),
                    vec![VReg(value.0)],
                    "recipe-reload annotation has no matching point reload",
                ));
            }
        }
        for &home in &self.recipe_homes {
            if home.0 >= self.logical.count {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.RECIPE_HOME_RANGE",
                    None,
                    None,
                    Vec::new(),
                    format!(
                        "recipe home {} is outside the plan's {} logical values",
                        home.0, self.logical.count
                    ),
                ));
            }
            let has_reload = self
                .point_ops
                .iter()
                .any(|(_, operation)| {
                    matches!(operation, PlannedOp::Reload { home: reload_home, .. } if *reload_home == home)
                })
                || self.edge_ops.values().flatten().any(|operation| {
                    matches!(operation, PlannedEdgeOp::Reload { source_home, .. } if *source_home == home)
                });
            if !has_reload {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.RECIPE_HOME_RELOAD",
                    None,
                    None,
                    Vec::new(),
                    format!("recipe home {home:?} has no selected reload"),
                ));
            }
        }
        Ok(())
    }

    fn verify_operation(
        &self,
        operation: PlannedOp,
        block: Option<BlockId>,
        instruction: Option<usize>,
    ) -> Result<(), SpillPlanError> {
        let (value, home) = match operation {
            PlannedOp::Spill { value, home }
            | PlannedOp::Reload { value, home }
            | PlannedOp::SpillPhi { value, home } => (value, home),
        };
        if value.0 >= self.logical.count {
            return Err(SpillPlanError::new(
                "SPILL_PLAN.VALUE_RANGE",
                block,
                instruction,
                vec![VReg(value.0)],
                format!(
                    "planned operation references logical value {} but the plan contains {} values",
                    value.0, self.logical.count
                ),
            ));
        }
        let expected = self.homes.of_logical(value);
        if home != expected {
            return Err(SpillPlanError::new(
                "SPILL_PLAN.HOME",
                block,
                instruction,
                vec![VReg(value.0)],
                format!(
                    "planned operation uses spill home {} but logical value {} belongs to home {}",
                    home.0, value.0, expected.0
                ),
            ));
        }
        Ok(())
    }

    fn verify_edge_operation(
        &self,
        operation: PlannedEdgeOp,
        block: Option<BlockId>,
        transferred_home: bool,
    ) -> Result<(), SpillPlanError> {
        let (source, destination, home, expected_home) = match operation {
            PlannedEdgeOp::Reload {
                source,
                source_home,
                destination,
            } => (
                source,
                destination,
                source_home,
                self.homes.of_logical(source),
            ),
            PlannedEdgeOp::Spill {
                source,
                destination,
                destination_home,
            } => (
                source,
                destination,
                destination_home,
                self.homes.of_logical(destination),
            ),
        };
        for value in [source, destination] {
            if value.0 >= self.logical.count {
                return Err(SpillPlanError::new(
                    "SPILL_PLAN.VALUE_RANGE",
                    block,
                    None,
                    vec![VReg(value.0)],
                    format!(
                        "planned edge operation references logical value {} but the plan contains {} values",
                        value.0, self.logical.count
                    ),
                ));
            }
        }
        if home != expected_home && !transferred_home {
            return Err(SpillPlanError::new(
                "SPILL_PLAN.HOME_CLASS",
                block,
                None,
                vec![VReg(source.0), VReg(destination.0)],
                format!("planned edge operation names home {home:?}, expected {expected_home:?}"),
            ));
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::native::mir::{BaseReg, MBlock, MInst, OpSize, PhiNode, SpillDesc, VRegAllocator};

    #[test]
    fn integrated_ready_walk_closes_resident_lanes_before_starting_new_roots() {
        const LANES: usize = 32;
        let mut vregs = VRegAllocator::new();
        let roots = (0..LANES).map(|_| vregs.alloc()).collect::<Vec<_>>();
        let results = (0..LANES).map(|_| vregs.alloc()).collect::<Vec<_>>();
        let mut func = MFunction::new(vregs, vec![SpillDesc::transient(); LANES * 2]);
        let mut block = MBlock::new(BlockId(0));
        for (lane, &root) in roots.iter().enumerate() {
            block.push(MInst::LoadImm {
                dst: root,
                value: lane as u64,
            });
        }
        for (&root, &result) in roots.iter().zip(&results) {
            block.push(MInst::AndImm {
                dst: result,
                src: root,
                imm: 1,
            });
        }
        block.push(MInst::Return);
        func.push_block(block);

        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let constraints = super::super::constraints::ConstraintModel::build(&func, &cfg).unwrap();
        let next_use = super::super::next_use::analyze(&func, &cfg).unwrap();
        let logical = LogicalValues::build(&func);
        let homes = SpillHomes::build(&func).unwrap();
        let recipes = PlanningRecipes::stack_only(func.vregs.count());
        let (_, order) = plan_scheduled_block_transition(
            &func,
            &next_use,
            &recipes,
            &logical,
            &homes,
            0,
            4,
            &LogicalSet::new(),
            LogicalSet::new(),
            &constraints.instructions[0],
            &HashMap::default(),
        )
        .unwrap();

        let mut outstanding = BTreeSet::new();
        assert!(
            order
                .iter()
                .position(|source| *source >= LANES)
                .is_some_and(|position| position <= 4),
            "a direct consumer must run no later than the resident-capacity boundary"
        );
        for &source in &order[..order.len() - 1] {
            if source < LANES {
                outstanding.insert(source);
            } else {
                assert!(
                    outstanding.remove(&(source - LANES)),
                    "a lane consumer must follow its root"
                );
            }
        }
        assert!(outstanding.is_empty());
        assert_eq!(order.last(), Some(&(LANES * 2)));
    }

    #[test]
    fn integrated_ready_walk_builds_the_earliest_bounded_sink_packet() {
        let mut vregs = VRegAllocator::new();
        let long_root = vregs.alloc();
        let short_root = vregs.alloc();
        let short_result = vregs.alloc();
        let filler_root = vregs.alloc();
        let filler_result = vregs.alloc();
        let long_result = vregs.alloc();
        let mut func = MFunction::new(vregs, vec![SpillDesc::transient(); 6]);
        let mut block = MBlock::new(BlockId(0));
        // Root source order starts `long_root` and keeps it resident while
        // the independent short cluster executes. Sink-directed order starts
        // from the earliest result and first tries to close its dependency
        // cone without exceeding the physical register capacity.
        block.push(MInst::LoadImm {
            dst: long_root,
            value: 1,
        });
        block.push(MInst::LoadImm {
            dst: short_root,
            value: 2,
        });
        block.push(MInst::AndImm {
            dst: short_result,
            src: short_root,
            imm: 1,
        });
        block.push(MInst::LoadImm {
            dst: filler_root,
            value: 3,
        });
        block.push(MInst::AndImm {
            dst: filler_result,
            src: filler_root,
            imm: 1,
        });
        block.push(MInst::AndImm {
            dst: long_result,
            src: long_root,
            imm: 1,
        });
        block.push(MInst::Return);
        func.push_block(block);

        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let constraints = super::super::constraints::ConstraintModel::build(&func, &cfg).unwrap();
        let next_use = super::super::next_use::analyze(&func, &cfg).unwrap();
        let logical = LogicalValues::build(&func);
        let homes = SpillHomes::build(&func).unwrap();
        let recipes = PlanningRecipes::stack_only(func.vregs.count());
        let (_, order) = plan_scheduled_block_transition(
            &func,
            &next_use,
            &recipes,
            &logical,
            &homes,
            0,
            4,
            &LogicalSet::new(),
            LogicalSet::new(),
            &constraints.instructions[0],
            &HashMap::default(),
        )
        .unwrap();

        assert_eq!(&order[..2], &[1, 2]);
        assert!(
            order.iter().position(|source| *source == 0)
                < order.iter().position(|source| *source == 5)
        );
        assert_eq!(order.last(), Some(&6));
    }

    #[test]
    fn bounded_sink_packet_materializes_a_shared_producer_once_for_adjacent_sinks() {
        let mut vregs = VRegAllocator::new();
        let distant_root = vregs.alloc();
        let shared_root = vregs.alloc();
        let first_result = vregs.alloc();
        let second_result = vregs.alloc();
        let filler_root = vregs.alloc();
        let filler_result = vregs.alloc();
        let distant_result = vregs.alloc();
        let mut func = MFunction::new(vregs, vec![SpillDesc::transient(); 7]);
        let mut block = MBlock::new(BlockId(0));
        block.push(MInst::LoadImm {
            dst: distant_root,
            value: 1,
        });
        block.push(MInst::LoadImm {
            dst: shared_root,
            value: 2,
        });
        block.push(MInst::AndImm {
            dst: first_result,
            src: shared_root,
            imm: 1,
        });
        block.push(MInst::AndImm {
            dst: second_result,
            src: shared_root,
            imm: 2,
        });
        block.push(MInst::LoadImm {
            dst: filler_root,
            value: 3,
        });
        block.push(MInst::AndImm {
            dst: filler_result,
            src: filler_root,
            imm: 1,
        });
        block.push(MInst::AndImm {
            dst: distant_result,
            src: distant_root,
            imm: 1,
        });
        block.push(MInst::Return);
        func.push_block(block);

        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let constraints = super::super::constraints::ConstraintModel::build(&func, &cfg).unwrap();
        let next_use = super::super::next_use::analyze(&func, &cfg).unwrap();
        let logical = LogicalValues::build(&func);
        let homes = SpillHomes::build(&func).unwrap();
        let recipes = PlanningRecipes::stack_only(func.vregs.count());
        let (_, order) = plan_scheduled_block_transition(
            &func,
            &next_use,
            &recipes,
            &logical,
            &homes,
            0,
            4,
            &LogicalSet::new(),
            LogicalSet::new(),
            &constraints.instructions[0],
            &HashMap::default(),
        )
        .unwrap();

        assert_eq!(&order[..3], &[1, 2, 3]);
        assert_eq!(order.iter().filter(|&&source| source == 1).count(), 1);
        assert_eq!(order.last(), Some(&7));
    }

    #[test]
    fn exit_reload_price_is_deduplicated_per_edge_and_summed_across_edges() {
        let mut vregs = VRegAllocator::new();
        let condition = vregs.alloc();
        let source = vregs.alloc();
        let true_value = vregs.alloc();
        let false_value = vregs.alloc();
        let mut func = MFunction::new(vregs, vec![SpillDesc::transient(); 4]);

        let mut entry = MBlock::new(BlockId(0));
        entry.push(MInst::LoadImm {
            dst: condition,
            value: 1,
        });
        entry.push(MInst::LoadImm {
            dst: source,
            value: 2,
        });
        entry.push(MInst::Branch {
            cond: condition,
            true_bb: BlockId(1),
            false_bb: BlockId(2),
        });

        let mut true_block = MBlock::new(BlockId(1));
        true_block.phis.push(PhiNode {
            dst: true_value,
            sources: vec![(BlockId(0), source)],
        });
        true_block.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 0,
            src: true_value,
            size: OpSize::S64,
        });
        true_block.push(MInst::Return);

        let mut false_block = MBlock::new(BlockId(2));
        false_block.phis.push(PhiNode {
            dst: false_value,
            sources: vec![(BlockId(0), source)],
        });
        false_block.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 8,
            src: false_value,
            size: OpSize::S64,
        });
        false_block.push(MInst::Return);
        func.blocks = vec![entry, true_block, false_block];

        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let next_use = super::super::next_use::analyze(&func, &cfg).unwrap();
        let logical = LogicalValues::build(&func);
        let translations = EdgeTranslations::build(&func, &cfg, &logical).unwrap();
        let recipes = PlanningRecipes::stack_only(func.vregs.count());
        let entry = cfg.block_index[&BlockId(0)];
        let true_block = cfg.block_index[&BlockId(1)];
        let false_block = cfg.block_index[&BlockId(2)];
        let costs = exit_reload_costs(
            &func,
            &cfg,
            &next_use,
            &recipes,
            &logical,
            &translations,
            entry,
        )
        .unwrap();
        let source = LogicalValue(source.0);
        let expected = u32::from(reload_cost_on_edge(
            &func, &recipes, entry, true_block, source,
        ))
        .saturating_add(u32::from(reload_cost_on_edge(
            &func,
            &recipes,
            entry,
            false_block,
            source,
        )));

        assert_eq!(costs.get(&source), Some(&expected));
        assert_eq!(costs.len(), 1, "only the shared phi source is live out");
    }

    #[test]
    fn entry_value_evicted_before_first_use_is_planned_as_a_memory_phi() {
        let mut vregs = VRegAllocator::new();
        let initial = vregs.alloc();
        let merged = vregs.alloc();
        let pressure_a = vregs.alloc();
        let pressure_b = vregs.alloc();
        let next = vregs.alloc();
        let mut func = MFunction::new(vregs, vec![SpillDesc::transient(); 5]);

        let mut entry = MBlock::new(BlockId(0));
        entry.push(MInst::LoadImm {
            dst: initial,
            value: 1,
        });
        entry.push(MInst::Jump { target: BlockId(1) });

        let mut header = MBlock::new(BlockId(1));
        header.phis.push(PhiNode {
            dst: merged,
            sources: vec![(BlockId(0), initial), (BlockId(2), next)],
        });
        header.push(MInst::LoadImm {
            dst: pressure_a,
            value: 2,
        });
        header.push(MInst::LoadImm {
            dst: pressure_b,
            value: 3,
        });
        header.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 0,
            src: pressure_a,
            size: OpSize::S64,
        });
        header.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 8,
            src: pressure_b,
            size: OpSize::S64,
        });
        header.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 16,
            src: merged,
            size: OpSize::S64,
        });
        header.push(MInst::Jump { target: BlockId(2) });

        let mut latch = MBlock::new(BlockId(2));
        latch.push(MInst::Mov {
            dst: next,
            src: merged,
        });
        latch.push(MInst::Branch {
            cond: merged,
            true_bb: BlockId(1),
            false_bb: BlockId(3),
        });

        let mut exit = MBlock::new(BlockId(3));
        exit.push(MInst::Return);
        func.blocks = vec![entry, header, latch, exit];

        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let next_use = super::super::next_use::analyze(&func, &cfg).unwrap();
        let plan = plan(&func, &cfg, &next_use, 2).unwrap();
        plan.verify(&func, &cfg, 2).unwrap();

        let header = cfg.block_index[&BlockId(1)];
        let merged = LogicalValue(merged.0);
        assert!(next_use.region_at_entry(header).is_some());
        assert!(!plan.w_entry[header].contains(&merged));
        assert!(plan.point_ops.iter().any(|(point, operation)| {
            point.block == BlockId(1)
                && matches!(operation, PlannedOp::SpillPhi { value, .. } if *value == merged)
        }));
        assert!(plan.point_ops.iter().any(|(point, operation)| {
            point.block == BlockId(1)
                && point.instruction == 4
                && matches!(operation, PlannedOp::Reload { value, .. } if *value == merged)
        }));
        assert!(plan.point_ops.iter().all(|(point, operation)| {
            point.block != BlockId(1)
                || !matches!(operation, PlannedOp::Spill { value, .. } if *value == merged)
        }));
        let merged_home = plan.homes.of_logical(merged);
        for &(predecessor_id, source) in &func.blocks[header].phis[0].sources {
            let predecessor = cfg.block_index[&predecessor_id];
            assert!(
                plan.edge_ops
                    .get(&(predecessor, header))
                    .is_some_and(|operations| operations.iter().any(|operation| {
                        matches!(
                            operation,
                            PlannedEdgeOp::Spill {
                                destination,
                                destination_home,
                                ..
                            } if *destination == merged && *destination_home == merged_home
                        )
                    })),
                "missing explicit transfer into the loop-phi home: {plan:#?}"
            );
            assert_ne!(plan.homes.of_vreg(source), merged_home);
        }
    }

    #[test]
    fn single_predecessor_inherits_residency_without_edge_reconciliation() {
        let mut vregs = VRegAllocator::new();
        let value = vregs.alloc();
        let mut func = MFunction::new(vregs, vec![SpillDesc::transient()]);

        let mut predecessor = MBlock::new(BlockId(0));
        predecessor.push(MInst::LoadImm {
            dst: value,
            value: 1,
        });
        predecessor.push(MInst::Jump { target: BlockId(1) });
        let mut successor = MBlock::new(BlockId(1));
        successor.push(MInst::Return);
        func.blocks = vec![predecessor, successor];

        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let next_use = super::super::next_use::analyze(&func, &cfg).unwrap();
        let logical = LogicalValues::build(&func);
        let homes = SpillHomes::build(&func).unwrap();
        let translations = EdgeTranslations::build(&func, &cfg, &logical).unwrap();
        let mut plan = SpillPlan {
            logical,
            homes,
            point_ops: Vec::new(),
            edge_ops: BTreeMap::new(),
            recipe_reloads: BTreeSet::new(),
            recipe_homes: BTreeSet::new(),
            state_homes: BTreeMap::new(),
            state_reload_recipes: BTreeMap::new(),
            w_entry: vec![LogicalSet::new(); func.blocks.len()],
            w_exit: vec![LogicalSet::new(); func.blocks.len()],
            s_entry: vec![LogicalSet::new(); func.blocks.len()],
            s_exit: vec![LogicalSet::new(); func.blocks.len()],
        };
        let predecessor = cfg.block_index[&BlockId(0)];
        let successor = cfg.block_index[&BlockId(1)];
        let logical_value = LogicalValue(value.0);
        plan.w_exit[predecessor].insert(logical_value);
        plan.s_exit[predecessor].insert(logical_value);

        assert!(!next_use.anticipated_at_entry(successor, value));
        let planning_recipes = PlanningRecipes::stack_only(func.vregs.count());
        let inherited = init_usual(
            &func,
            &cfg,
            &next_use,
            &planning_recipes,
            &plan,
            &translations,
            successor,
            1,
        );

        assert_eq!(inherited, LogicalSet::from_iter([logical_value]));
    }

    #[test]
    fn join_retention_pays_for_guaranteed_use_but_delays_one_arm_use() {
        let mut vregs = VRegAllocator::new();
        let condition = vregs.alloc();
        let conditional = vregs.alloc();
        let guaranteed = vregs.alloc();
        let mut func = MFunction::new(vregs, vec![SpillDesc::transient(); 3]);

        let mut entry = MBlock::new(BlockId(0));
        entry.push(MInst::LoadImm {
            dst: condition,
            value: 1,
        });
        entry.push(MInst::LoadImm {
            dst: conditional,
            value: 2,
        });
        entry.push(MInst::LoadImm {
            dst: guaranteed,
            value: 3,
        });
        entry.push(MInst::Branch {
            cond: condition,
            true_bb: BlockId(1),
            false_bb: BlockId(2),
        });
        let mut first = MBlock::new(BlockId(1));
        first.push(MInst::Jump { target: BlockId(3) });
        let mut second = MBlock::new(BlockId(2));
        second.push(MInst::Jump { target: BlockId(3) });
        let mut join = MBlock::new(BlockId(3));
        join.push(MInst::Branch {
            cond: condition,
            true_bb: BlockId(4),
            false_bb: BlockId(5),
        });
        let mut use_arm = MBlock::new(BlockId(4));
        use_arm.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 0,
            src: conditional,
            size: OpSize::S64,
        });
        use_arm.push(MInst::Jump { target: BlockId(6) });
        let mut skip_arm = MBlock::new(BlockId(5));
        skip_arm.push(MInst::Jump { target: BlockId(6) });
        let mut tail = MBlock::new(BlockId(6));
        tail.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 8,
            src: guaranteed,
            size: OpSize::S64,
        });
        tail.push(MInst::Return);
        func.blocks = vec![entry, first, second, join, use_arm, skip_arm, tail];

        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let next_use = super::super::next_use::analyze(&func, &cfg).unwrap();
        next_use.verify(&func, &cfg).unwrap();
        let logical = LogicalValues::build(&func);
        let homes = SpillHomes::build(&func).unwrap();
        let translations = EdgeTranslations::build(&func, &cfg, &logical).unwrap();
        let mut plan = SpillPlan {
            logical,
            homes,
            point_ops: Vec::new(),
            edge_ops: BTreeMap::new(),
            recipe_reloads: BTreeSet::new(),
            recipe_homes: BTreeSet::new(),
            state_homes: BTreeMap::new(),
            state_reload_recipes: BTreeMap::new(),
            w_entry: vec![LogicalSet::new(); func.blocks.len()],
            w_exit: vec![LogicalSet::new(); func.blocks.len()],
            s_entry: vec![LogicalSet::new(); func.blocks.len()],
            s_exit: vec![LogicalSet::new(); func.blocks.len()],
        };
        let join = cfg.block_index[&BlockId(3)];
        let predecessors = &cfg.predecessors[join];
        assert_eq!(predecessors.len(), 2);
        assert!(predecessors.iter().all(|predecessor| *predecessor < join));
        plan.w_exit[predecessors[0]]
            .extend([LogicalValue(conditional.0), LogicalValue(guaranteed.0)]);

        assert!(!next_use.anticipated_at_entry(join, conditional));
        assert!(next_use.anticipated_at_entry(join, guaranteed));
        let planning_recipes = PlanningRecipes::stack_only(func.vregs.count());
        let retained = init_usual(
            &func,
            &cfg,
            &next_use,
            &planning_recipes,
            &plan,
            &translations,
            join,
            1,
        );

        assert_eq!(
            retained,
            LogicalSet::from_iter([LogicalValue(guaranteed.0)])
        );
    }

    #[test]
    fn join_retention_prices_every_use_in_a_straight_line_cluster() {
        let mut vregs = VRegAllocator::new();
        let condition = vregs.alloc();
        let single_use = vregs.alloc();
        let repeated_use = vregs.alloc();
        let sum = vregs.alloc();
        let mut func = MFunction::new(vregs, vec![SpillDesc::transient(); 4]);

        let mut entry = MBlock::new(BlockId(0));
        entry.push(MInst::LoadImm {
            dst: condition,
            value: 1,
        });
        entry.push(MInst::LoadImm {
            dst: single_use,
            value: 2,
        });
        entry.push(MInst::LoadImm {
            dst: repeated_use,
            value: 3,
        });
        entry.push(MInst::Branch {
            cond: condition,
            true_bb: BlockId(1),
            false_bb: BlockId(2),
        });
        let mut first = MBlock::new(BlockId(1));
        first.push(MInst::Jump { target: BlockId(3) });
        let mut second = MBlock::new(BlockId(2));
        second.push(MInst::Jump { target: BlockId(3) });
        let mut join = MBlock::new(BlockId(3));
        // Both values have the same first-use point.  A first-use-only model
        // therefore chooses the lower VReg tie-break (`single_use`), while the
        // complete local cluster must retain `repeated_use`.
        join.push(MInst::Add {
            dst: sum,
            lhs: single_use,
            rhs: repeated_use,
        });
        join.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 0,
            src: repeated_use,
            size: OpSize::S64,
        });
        join.push(MInst::Return);
        func.blocks = vec![entry, first, second, join];

        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let next_use = super::super::next_use::analyze(&func, &cfg).unwrap();
        let logical = LogicalValues::build(&func);
        let homes = SpillHomes::build(&func).unwrap();
        let translations = EdgeTranslations::build(&func, &cfg, &logical).unwrap();
        let mut plan = SpillPlan {
            logical,
            homes,
            point_ops: Vec::new(),
            edge_ops: BTreeMap::new(),
            recipe_reloads: BTreeSet::new(),
            recipe_homes: BTreeSet::new(),
            state_homes: BTreeMap::new(),
            state_reload_recipes: BTreeMap::new(),
            w_entry: vec![LogicalSet::new(); func.blocks.len()],
            w_exit: vec![LogicalSet::new(); func.blocks.len()],
            s_entry: vec![LogicalSet::new(); func.blocks.len()],
            s_exit: vec![LogicalSet::new(); func.blocks.len()],
        };
        let join = cfg.block_index[&BlockId(3)];
        let predecessors = &cfg.predecessors[join];
        plan.w_exit[predecessors[0]]
            .extend([LogicalValue(single_use.0), LogicalValue(repeated_use.0)]);
        let planning_recipes = PlanningRecipes::stack_only(func.vregs.count());

        let retained = init_usual(
            &func,
            &cfg,
            &next_use,
            &planning_recipes,
            &plan,
            &translations,
            join,
            1,
        );

        assert_eq!(
            retained,
            LogicalSet::from_iter([LogicalValue(repeated_use.0)])
        );
        next_use.verify(&func, &cfg).unwrap();
    }

    #[test]
    fn reused_edge_source_maps_to_every_destination() {
        let mut vregs = VRegAllocator::new();
        let source = vregs.alloc();
        let first = vregs.alloc();
        let second = vregs.alloc();
        let mut func = MFunction::new(vregs, vec![SpillDesc::transient(); 3]);
        let mut predecessor = MBlock::new(BlockId(0));
        predecessor.push(MInst::LoadImm {
            dst: source,
            value: 1,
        });
        predecessor.push(MInst::Jump { target: BlockId(1) });
        let mut successor = MBlock::new(BlockId(1));
        successor.phis = vec![
            PhiNode {
                dst: first,
                sources: vec![(BlockId(0), source)],
            },
            PhiNode {
                dst: second,
                sources: vec![(BlockId(0), source)],
            },
        ];
        successor.push(MInst::Return);
        func.blocks = vec![predecessor, successor];
        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let logical = LogicalValues::build(&func);

        let translations = EdgeTranslations::build(&func, &cfg, &logical).unwrap();
        let mapped = translations
            .to_successors(0, 1, LogicalValue(source.0))
            .collect::<Vec<_>>();

        assert_eq!(mapped, [LogicalValue(first.0), LogicalValue(second.0)]);
        assert_eq!(
            translations.to_predecessor(0, 1, LogicalValue(first.0)),
            LogicalValue(source.0)
        );
        assert_eq!(
            translations.to_predecessor(0, 1, LogicalValue(second.0)),
            LogicalValue(source.0)
        );
    }

    #[test]
    fn scratch_reload_splits_the_predecessor_phi_source_identity() {
        let source = LogicalValue(3);
        let destination = LogicalValue(9);
        let destination_home = SpillHome(9);
        let operations = [
            PlannedEdgeOp::Spill {
                source,
                destination,
                destination_home,
            },
            PlannedEdgeOp::Reload {
                source,
                source_home: destination_home,
                destination,
            },
        ];

        assert!(edge_reload_uses_transferred_home(&operations, 1));
        assert!(matches!(
            operations[1],
            PlannedEdgeOp::Reload {
                source: reload_source,
                destination: reload_destination,
                ..
            } if reload_source == source && reload_destination == destination
        ));
    }

    #[test]
    fn excessive_operand_pressure_is_a_structured_error() {
        let mut vregs = VRegAllocator::new();
        let left = vregs.alloc();
        let right = vregs.alloc();
        let result = vregs.alloc();
        let mut func = MFunction::new(vregs, vec![SpillDesc::transient(); 3]);
        let mut block = MBlock::new(BlockId(0));
        block.push(MInst::LoadImm {
            dst: left,
            value: 1,
        });
        block.push(MInst::LoadImm {
            dst: right,
            value: 2,
        });
        block.push(MInst::Add {
            dst: result,
            lhs: left,
            rhs: right,
        });
        block.push(MInst::Return);
        func.blocks.push(block);
        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let next_use = super::super::next_use::analyze(&func, &cfg).unwrap();

        let error = plan(&func, &cfg, &next_use, 1).unwrap_err();

        assert_eq!(error.rule, "SPILL_PLAN.OPERAND_PRESSURE");
        assert_eq!(error.block, Some(BlockId(0)));
        assert_eq!(error.instruction, Some(2));
        assert_eq!(error.values, vec![left, right]);
    }

    #[test]
    fn excessive_clobber_pressure_is_a_structured_error() {
        let mut vregs = VRegAllocator::new();
        let input = vregs.alloc();
        let result = vregs.alloc();
        let mut func = MFunction::new(vregs, vec![SpillDesc::transient(); 2]);
        let mut block = MBlock::new(BlockId(0));
        block.push(MInst::LoadImm {
            dst: input,
            value: 1,
        });
        block.push(MInst::UDiv {
            dst: result,
            lhs: input,
            rhs: input,
        });
        block.push(MInst::Return);
        func.blocks.push(block);
        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let next_use = super::super::next_use::analyze(&func, &cfg).unwrap();

        let error = plan(&func, &cfg, &next_use, 1).unwrap_err();

        assert_eq!(error.rule, "SPILL_PLAN.CLOBBER_CAPACITY");
        assert_eq!(error.block, Some(BlockId(0)));
        assert_eq!(error.instruction, Some(1));
    }

    #[test]
    fn eviction_uses_target_cost_density_and_preserves_min_as_tie_breaker() {
        let mut vregs = VRegAllocator::new();
        let cheap = vregs.alloc();
        let costly = vregs.alloc();
        let mut func = MFunction::new(vregs, vec![SpillDesc::remat(1), SpillDesc::transient()]);
        let mut block = MBlock::new(BlockId(0));
        block.push(MInst::Return);
        func.push_block(block);
        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let next_use = super::super::next_use::analyze(&func, &cfg).unwrap();
        let planning_recipes = PlanningRecipes::stack_only(func.vregs.count());
        let spilled = LogicalSet::new();
        let future = LinearFutureUses {
            func: &func,
            next_use: &next_use,
            block: 0,
            instruction: 0,
        };
        let local = |instructions| NextUseDistance::Finite {
            loop_exits: 0,
            instructions,
        };

        assert_eq!(
            compare_eviction_candidates(
                &func,
                &planning_recipes,
                &spilled,
                &future,
                (LogicalValue(cheap.0), local(1)),
                (LogicalValue(costly.0), local(1)),
            ),
            Ordering::Greater,
            "equal spans must evict the cheaper rematerializable value"
        );
        assert_eq!(
            compare_eviction_candidates(
                &func,
                &planning_recipes,
                &spilled,
                &future,
                (LogicalValue(cheap.0), local(1)),
                (LogicalValue(costly.0), local(15)),
            ),
            Ordering::Less,
            "a sufficiently long occupancy interval must outweigh a larger split cost"
        );

        let mut equal_cost = MFunction::new(
            func.vregs.clone(),
            vec![SpillDesc::transient(), SpillDesc::transient()],
        );
        let mut block = MBlock::new(BlockId(0));
        block.push(MInst::Return);
        equal_cost.push_block(block);
        let equal_cfg = super::super::cfg::normalize(&mut equal_cost).unwrap();
        let equal_next_use = super::super::next_use::analyze(&equal_cost, &equal_cfg).unwrap();
        let equal_recipes = PlanningRecipes::stack_only(equal_cost.vregs.count());
        let equal_future = LinearFutureUses {
            func: &equal_cost,
            next_use: &equal_next_use,
            block: 0,
            instruction: 0,
        };
        assert_eq!(
            compare_eviction_candidates(
                &equal_cost,
                &equal_recipes,
                &spilled,
                &equal_future,
                (LogicalValue(cheap.0), local(2)),
                (LogicalValue(costly.0), local(8)),
            ),
            Ordering::Less,
            "equal target costs must reduce to furthest-next-use MIN"
        );
        let exact_recipes = PlanningRecipes::with_global_costs(vec![Some(1), None]);
        assert_eq!(
            compare_eviction_candidates(
                &equal_cost,
                &exact_recipes,
                &spilled,
                &equal_future,
                (LogicalValue(cheap.0), local(2)),
                (LogicalValue(costly.0), local(2)),
            ),
            Ordering::Greater,
            "an exact reload recipe must override the stale transient descriptor cost"
        );
    }

    #[test]
    fn point_specific_memoryssa_cost_changes_the_allocator_owned_split() {
        let mut vregs = VRegAllocator::new();
        let state_backed = vregs.alloc();
        let stack_backed = vregs.alloc();
        let near_use = vregs.alloc();
        let pressure = vregs.alloc();
        let sum = vregs.alloc();
        let mut func = MFunction::new(vregs, vec![SpillDesc::transient(); 5]);
        let mut block = MBlock::new(BlockId(0));
        block.push(MInst::Load {
            dst: state_backed,
            base: BaseReg::StackFrame,
            offset: 0,
            size: OpSize::S64,
        });
        block.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 40,
            src: state_backed,
            size: OpSize::S64,
        });
        block.push(MInst::Load {
            dst: stack_backed,
            base: BaseReg::StackFrame,
            offset: 8,
            size: OpSize::S64,
        });
        block.push(MInst::Load {
            dst: near_use,
            base: BaseReg::StackFrame,
            offset: 16,
            size: OpSize::S64,
        });
        block.push(MInst::LoadImm {
            dst: pressure,
            value: 0,
        });
        block.push(MInst::Store {
            base: BaseReg::StackFrame,
            offset: 24,
            src: near_use,
            size: OpSize::S64,
        });
        block.push(MInst::Add {
            dst: sum,
            lhs: state_backed,
            rhs: stack_backed,
        });
        block.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 48,
            src: sum,
            size: OpSize::S64,
        });
        block.push(MInst::Return);
        func.push_block(block);
        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let next_use = super::super::next_use::analyze(&func, &cfg).unwrap();
        let exact = super::super::reload::analyze_for_planning(&func, &cfg).unwrap();
        let stack_only = PlanningRecipes::stack_only(func.vregs.count());

        let exact_plan = plan_with_recipe_costs(&func, &cfg, &next_use, &exact, 3).unwrap();
        let stack_plan = plan_with_recipe_costs(&func, &cfg, &next_use, &stack_only, 3).unwrap();
        let split_at_pressure = |plan: &SpillPlan| {
            plan.point_ops.iter().find_map(|(point, operation)| {
                (point.block == BlockId(0) && point.instruction == 4)
                    .then_some(operation)
                    .and_then(|operation| match operation {
                        PlannedOp::Spill { value, .. } => Some(*value),
                        _ => None,
                    })
            })
        };

        assert_eq!(split_at_pressure(&exact_plan), None);
        assert!(
            exact_plan
                .recipe_reloads
                .contains(&(BlockId(0), 6, LogicalValue(state_backed.0)))
        );
        assert!(exact_plan.point_ops.iter().any(|(point, operation)| {
            point.block == BlockId(0)
                && point.instruction == 6
                && matches!(
                    operation,
                    PlannedOp::Reload { value, .. }
                        if *value == LogicalValue(state_backed.0)
                )
        }));
        assert_eq!(
            split_at_pressure(&stack_plan),
            Some(LogicalValue(stack_backed.0)),
            "without a point recipe equal-cost MIN uses the deterministic VReg tie-break"
        );
    }

    #[test]
    fn point_recipe_splits_one_cluster_before_a_later_invalidated_use() {
        let mut vregs = VRegAllocator::new();
        let stored = vregs.alloc();
        let pressure = vregs.alloc();
        let overwrite = vregs.alloc();
        let mut func = MFunction::new(vregs, vec![SpillDesc::transient(); 3]);
        let mut block = MBlock::new(BlockId(0));
        block.push(MInst::Load {
            dst: stored,
            base: BaseReg::StackFrame,
            offset: 0,
            size: OpSize::S64,
        });
        block.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 40,
            src: stored,
            size: OpSize::S64,
        });
        block.push(MInst::Load {
            dst: pressure,
            base: BaseReg::StackFrame,
            offset: 8,
            size: OpSize::S64,
        });
        block.push(MInst::Store {
            base: BaseReg::StackFrame,
            offset: 24,
            src: pressure,
            size: OpSize::S64,
        });
        block.push(MInst::Store {
            base: BaseReg::StackFrame,
            offset: 32,
            src: stored,
            size: OpSize::S64,
        });
        block.push(MInst::Load {
            dst: overwrite,
            base: BaseReg::StackFrame,
            offset: 16,
            size: OpSize::S64,
        });
        block.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 40,
            src: overwrite,
            size: OpSize::S64,
        });
        block.push(MInst::Store {
            base: BaseReg::StackFrame,
            offset: 40,
            src: stored,
            size: OpSize::S64,
        });
        block.push(MInst::Return);
        func.push_block(block);
        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let next_use = super::super::next_use::analyze(&func, &cfg).unwrap();
        let recipes = super::super::reload::analyze_for_planning(&func, &cfg).unwrap();

        let plan = plan_with_recipe_costs(&func, &cfg, &next_use, &recipes, 1).unwrap();

        assert!(
            plan.recipe_reloads
                .contains(&(BlockId(0), 4, LogicalValue(stored.0)))
        );
        assert!(plan.point_ops.iter().any(|(point, operation)| {
            point.block == BlockId(0)
                && point.instruction == 5
                && matches!(
                    operation,
                    PlannedOp::Spill { value, .. } if *value == LogicalValue(stored.0)
                )
        }));
        assert!(!plan.point_ops.iter().any(|(point, operation)| {
            point.block == BlockId(0)
                && point.instruction == 2
                && matches!(
                    operation,
                    PlannedOp::Spill { value, .. } if *value == LogicalValue(stored.0)
                )
        }));
    }

    #[test]
    fn stable_recipe_identity_materializes_at_the_output_position() {
        let mut vregs = VRegAllocator::new();
        let stored = vregs.alloc();
        let pressure = vregs.alloc();
        let mut func = MFunction::new(vregs, vec![SpillDesc::transient(); 2]);
        let mut block = MBlock::new(BlockId(0));
        block.push(MInst::Load {
            dst: stored,
            base: BaseReg::StackFrame,
            offset: 0,
            size: OpSize::S64,
        });
        block.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 40,
            src: stored,
            size: OpSize::S64,
        });
        block.push(MInst::Load {
            dst: pressure,
            base: BaseReg::StackFrame,
            offset: 8,
            size: OpSize::S64,
        });
        block.push(MInst::Store {
            base: BaseReg::StackFrame,
            offset: 16,
            src: pressure,
            size: OpSize::S64,
        });
        block.push(MInst::Store {
            base: BaseReg::StackFrame,
            offset: 24,
            src: stored,
            size: OpSize::S64,
        });
        block.push(MInst::Return);
        func.push_block(block);
        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let next_use = super::super::next_use::analyze(&func, &cfg).unwrap();
        let recipes = super::super::reload::analyze_for_planning(&func, &cfg).unwrap();
        let logical = LogicalValues::build(&func);
        let homes = SpillHomes::build(&func).unwrap();
        let mut planner = BlockTransitionPlanner::new(
            &func,
            &next_use,
            &recipes,
            &logical,
            &homes,
            0,
            1,
            &LogicalSet::new(),
            LogicalSet::new(),
        )
        .unwrap();
        for (source, inst) in func.blocks[0].insts.iter().enumerate() {
            planner
                .step(
                    TransitionPoint {
                        output: if source >= 4 { source + 3 } else { source },
                        source,
                    },
                    inst,
                )
                .unwrap();
        }
        let transition = planner.finish().unwrap();
        let stored = LogicalValue(stored.0);

        assert!(transition.recipe_reloads.contains(&(BlockId(0), 7, stored)));
        assert!(transition.point_ops.iter().any(|(point, operation)| {
            point.instruction == 7
                && matches!(operation, PlannedOp::Reload { value, .. } if *value == stored)
        }));
    }

    #[test]
    fn whole_recipe_home_requires_an_exact_recipe_at_every_selected_reload() {
        let mut vregs = VRegAllocator::new();
        let stored = vregs.alloc();
        let overwrite = vregs.alloc();
        let mut func = MFunction::new(vregs, vec![SpillDesc::transient(); 2]);
        let mut block = MBlock::new(BlockId(0));
        block.push(MInst::Load {
            dst: stored,
            base: BaseReg::StackFrame,
            offset: 0,
            size: OpSize::S64,
        });
        block.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 40,
            src: stored,
            size: OpSize::S64,
        });
        block.push(MInst::Store {
            base: BaseReg::StackFrame,
            offset: 16,
            src: stored,
            size: OpSize::S64,
        });
        block.push(MInst::Load {
            dst: overwrite,
            base: BaseReg::StackFrame,
            offset: 8,
            size: OpSize::S64,
        });
        block.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 40,
            src: overwrite,
            size: OpSize::S64,
        });
        block.push(MInst::Store {
            base: BaseReg::StackFrame,
            offset: 24,
            src: stored,
            size: OpSize::S64,
        });
        block.push(MInst::Return);
        func.push_block(block);
        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let next_use = super::super::next_use::analyze(&func, &cfg).unwrap();
        let mut plan = plan(&func, &cfg, &next_use, 2).unwrap();
        plan.point_ops.clear();
        plan.edge_ops.clear();
        plan.recipe_reloads.clear();
        plan.recipe_homes.clear();
        let logical = LogicalValue(stored.0);
        let home = plan.homes.of_logical(logical);
        let reload = |instruction| {
            (
                ProgramPoint {
                    block: BlockId(0),
                    instruction,
                    side: PointSide::Before,
                },
                PlannedOp::Reload {
                    value: logical,
                    home,
                },
            )
        };
        plan.point_ops.extend([reload(2), reload(5)]);
        let requested = super::super::ssa::planner_reload_queries(&func, &cfg, &plan).unwrap();
        let recipes = super::super::reload::analyze_with_queries(&func, &cfg, &requested).unwrap();

        plan.select_recipe_homes(&func, &cfg, &recipes).unwrap();
        assert!(plan.recipe_homes.is_empty());

        plan.point_ops.pop();
        plan.select_recipe_homes(&func, &cfg, &recipes).unwrap();
        assert_eq!(plan.recipe_homes, BTreeSet::from([home]));
        plan.verify_recipe_homes(&func, &cfg, &recipes).unwrap();

        plan.point_ops.push(reload(5));
        let error = plan.verify_recipe_homes(&func, &cfg, &recipes).unwrap_err();
        assert_eq!(error.rule, "SPILL_PLAN.RECIPE_HOME_POINT");
        assert_eq!(error.block, Some(BlockId(0)));
        assert_eq!(error.instruction, Some(5));
    }

    #[test]
    fn whole_recipe_home_uses_the_existing_mixed_plan_as_its_baseline() {
        let mut vregs = VRegAllocator::new();
        let base = vregs.alloc();
        let first = vregs.alloc();
        let value = vregs.alloc();
        let overwrite = vregs.alloc();
        let mut spill_descs = vec![SpillDesc::transient(); 4];
        spill_descs[value.0 as usize].spill_cost = 1;
        let mut func = MFunction::new(vregs, spill_descs);
        let mut block = MBlock::new(BlockId(0));
        block.push(MInst::Load {
            dst: base,
            base: BaseReg::SimState,
            offset: 40,
            size: OpSize::S64,
        });
        block.push(MInst::BitNot {
            dst: first,
            src: base,
        });
        block.push(MInst::BitNot {
            dst: value,
            src: first,
        });
        block.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 48,
            src: value,
            size: OpSize::S64,
        });
        block.push(MInst::Store {
            base: BaseReg::StackFrame,
            offset: 0,
            src: value,
            size: OpSize::S64,
        });
        block.push(MInst::Load {
            dst: overwrite,
            base: BaseReg::StackFrame,
            offset: 8,
            size: OpSize::S64,
        });
        block.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 48,
            src: overwrite,
            size: OpSize::S64,
        });
        block.push(MInst::Store {
            base: BaseReg::StackFrame,
            offset: 16,
            src: value,
            size: OpSize::S64,
        });
        block.push(MInst::Return);
        func.push_block(block);

        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let next_use = super::super::next_use::analyze(&func, &cfg).unwrap();
        let mut plan = plan(&func, &cfg, &next_use, 4).unwrap();
        plan.point_ops.clear();
        plan.edge_ops.clear();
        plan.recipe_reloads.clear();
        plan.recipe_homes.clear();
        let logical = LogicalValue(value.0);
        let home = plan.homes.of_logical(logical);
        let point = |instruction| ProgramPoint {
            block: BlockId(0),
            instruction,
            side: PointSide::Before,
        };
        plan.point_ops.extend([
            (
                point(3),
                PlannedOp::Spill {
                    value: logical,
                    home,
                },
            ),
            (
                point(4),
                PlannedOp::Reload {
                    value: logical,
                    home,
                },
            ),
            (
                point(7),
                PlannedOp::Reload {
                    value: logical,
                    home,
                },
            ),
        ]);
        plan.recipe_reloads.insert((BlockId(0), 4, logical));
        let requested = super::super::ssa::planner_reload_queries(&func, &cfg, &plan).unwrap();
        let recipes = super::super::reload::analyze_with_queries(&func, &cfg, &requested).unwrap();
        let recipe_cost = |instruction| {
            recipes
                .resolved_recipe_at_point(PointUse {
                    block: BlockId(0),
                    instruction,
                    value,
                })
                .map(|recipe| recipe.steps.len() + 1)
        };
        assert_eq!(recipe_cost(4), Some(1));
        assert_eq!(recipe_cost(7), Some(3));

        plan.select_recipe_homes(&func, &cfg, &recipes).unwrap();
        assert!(
            plan.recipe_homes.is_empty(),
            "the all-recipe cost ties the selected point-recipe, stack-reload, and spill baseline"
        );
    }

    #[test]
    fn whole_recipe_home_compares_complete_stack_and_recipe_costs() {
        let mut vregs = VRegAllocator::new();
        let base = vregs.alloc();
        let first = vregs.alloc();
        let value = vregs.alloc();
        let mut func = MFunction::new(vregs, vec![SpillDesc::transient(); 3]);
        let mut block = MBlock::new(BlockId(0));
        block.push(MInst::Load {
            dst: base,
            base: BaseReg::SimState,
            offset: 40,
            size: OpSize::S64,
        });
        block.push(MInst::BitNot {
            dst: first,
            src: base,
        });
        block.push(MInst::BitNot {
            dst: value,
            src: first,
        });
        block.push(MInst::Store {
            base: BaseReg::StackFrame,
            offset: 0,
            src: value,
            size: OpSize::S64,
        });
        block.push(MInst::Return);
        func.push_block(block);
        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let next_use = super::super::next_use::analyze(&func, &cfg).unwrap();
        let mut plan = plan(&func, &cfg, &next_use, 3).unwrap();
        plan.point_ops.clear();
        plan.edge_ops.clear();
        plan.recipe_reloads.clear();
        plan.recipe_homes.clear();
        let logical = LogicalValue(value.0);
        let home = plan.homes.of_logical(logical);
        let point = ProgramPoint {
            block: BlockId(0),
            instruction: 3,
            side: PointSide::Before,
        };
        plan.point_ops.push((
            point,
            PlannedOp::Reload {
                value: logical,
                home,
            },
        ));
        let requested = super::super::ssa::planner_reload_queries(&func, &cfg, &plan).unwrap();
        let recipes = super::super::reload::analyze_with_queries(&func, &cfg, &requested).unwrap();

        plan.select_recipe_homes(&func, &cfg, &recipes).unwrap();
        assert!(
            plan.recipe_homes.is_empty(),
            "a three-instruction pure recipe must not replace a two-cost stack reload"
        );

        plan.point_ops.push((
            point,
            PlannedOp::Spill {
                value: logical,
                home,
            },
        ));
        plan.select_recipe_homes(&func, &cfg, &recipes).unwrap();
        assert_eq!(
            plan.recipe_homes,
            BTreeSet::from([home]),
            "avoiding the spill and reload makes the three-instruction recipe cheaper"
        );
        plan.verify_recipe_homes(&func, &cfg, &recipes).unwrap();
    }

    #[test]
    fn stale_state_table_is_a_structured_error() {
        let mut func = MFunction::new(VRegAllocator::new(), Vec::new());
        let mut block = MBlock::new(BlockId(0));
        block.push(MInst::Return);
        func.blocks.push(block);
        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let next_use = super::super::next_use::analyze(&func, &cfg).unwrap();
        let mut plan = plan(&func, &cfg, &next_use, 1).unwrap();
        plan.w_entry.pop();

        let error = plan.verify(&func, &cfg, 1).unwrap_err();

        assert_eq!(error.rule, "SPILL_PLAN.STATE_SHAPE");
        assert_eq!(error.block, None);
    }

    #[test]
    fn descending_large_phi_web_keeps_independent_homes_without_recursion() {
        const MEMBERS: u32 = 50_000;

        let mut vregs = VRegAllocator::new();
        for _ in 0..MEMBERS {
            vregs.alloc();
        }
        let mut func = MFunction::new(vregs, Vec::new());
        let mut block = MBlock::new(BlockId(0));
        for destination in (1..MEMBERS).rev() {
            block.phis.push(PhiNode {
                dst: VReg(destination),
                sources: vec![(BlockId(0), VReg(destination - 1))],
            });
        }
        func.blocks.push(block);

        let homes = SpillHomes::build(&func).unwrap();

        assert_eq!(homes.of_vreg(VReg(0)), SpillHome(0));
        assert_eq!(homes.of_vreg(VReg(MEMBERS - 1)), SpillHome(MEMBERS - 1));
        assert_eq!(homes.members(SpillHome(0)).count(), 1);
    }

    #[test]
    fn large_phi_join_is_indexed_once_in_both_directions() {
        const PREDECESSORS: usize = 64;
        const PHIS: usize = 512;
        const INTERNAL_BLOCKS: usize = PREDECESSORS - 1;
        const TREE_BLOCKS: usize = PREDECESSORS * 2 - 1;
        let join_id = BlockId(TREE_BLOCKS as u32);
        let mut vregs = VRegAllocator::new();
        let condition = vregs.alloc();
        let mut expected = Vec::with_capacity(PREDECESSORS * PHIS);
        let mut phis = Vec::with_capacity(PHIS);
        let mut leaf_definitions = (0..PREDECESSORS)
            .map(|_| Vec::with_capacity(PHIS))
            .collect::<Vec<_>>();
        for _ in 0..PHIS {
            let mut sources = Vec::with_capacity(PREDECESSORS);
            for (predecessor, definitions) in leaf_definitions.iter_mut().enumerate() {
                let source = vregs.alloc();
                let predecessor_id = BlockId((INTERNAL_BLOCKS + predecessor) as u32);
                sources.push((predecessor_id, source));
                definitions.push(source);
            }
            let destination = vregs.alloc();
            expected.extend(
                sources
                    .iter()
                    .map(|&(predecessor, source)| (predecessor, source, destination)),
            );
            phis.push(PhiNode {
                dst: destination,
                sources,
            });
        }

        let spill_descs = vec![SpillDesc::transient(); vregs.count() as usize];
        let mut func = MFunction::new(vregs, spill_descs);
        // A complete binary branch tree makes every one of the 64 eventual
        // join predecessors reachable from the single MIR entry block.
        for block_index in 0..INTERNAL_BLOCKS {
            let mut block = MBlock::new(BlockId(block_index as u32));
            if block_index == 0 {
                block.push(MInst::LoadImm {
                    dst: condition,
                    value: 1,
                });
            }
            block.push(MInst::Branch {
                cond: condition,
                true_bb: BlockId((block_index * 2 + 1) as u32),
                false_bb: BlockId((block_index * 2 + 2) as u32),
            });
            func.blocks.push(block);
        }
        for (predecessor, definitions) in leaf_definitions.iter().enumerate() {
            let predecessor_id = BlockId((INTERNAL_BLOCKS + predecessor) as u32);
            let mut block = MBlock::new(predecessor_id);
            for &source in definitions {
                block.push(MInst::LoadImm {
                    dst: source,
                    value: source.0 as u64,
                });
            }
            block.push(MInst::Jump { target: join_id });
            func.blocks.push(block);
        }
        let mut join = MBlock::new(join_id);
        join.phis = phis;
        join.push(MInst::Return);
        func.blocks.push(join);
        func.verify();
        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        func.verify();

        let logical = LogicalValues::build(&func);
        let translations = EdgeTranslations::build(&func, &cfg, &logical).unwrap();

        let join = cfg.block_index[&join_id];
        for (predecessor_id, source, destination) in expected {
            let predecessor = cfg.block_index[&predecessor_id];
            assert!(
                translations
                    .to_successors(predecessor, join, LogicalValue(source.0))
                    .any(|value| value == LogicalValue(destination.0))
            );
            assert_eq!(
                translations.to_predecessor(predecessor, join, LogicalValue(destination.0),),
                LogicalValue(source.0)
            );
        }
    }

    #[test]
    fn irreducible_scc_entries_prioritize_values_used_in_the_region() {
        use crate::native::mir::{BaseReg, OpSize, SpillDesc};
        use crate::native::regalloc::next_use::{self, LoopRegionKind};

        let mut vregs = VRegAllocator::new();
        let hot = vregs.alloc();
        let live_through = vregs.alloc();
        let mut func = MFunction::new(vregs, vec![SpillDesc::transient(); 2]);

        let mut entry = MBlock::new(BlockId(0));
        entry.push(MInst::LoadImm { dst: hot, value: 1 });
        entry.push(MInst::LoadImm {
            dst: live_through,
            value: 2,
        });
        entry.push(MInst::Branch {
            cond: hot,
            true_bb: BlockId(1),
            false_bb: BlockId(2),
        });

        let mut left_entry = MBlock::new(BlockId(1));
        left_entry.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 0,
            src: hot,
            size: OpSize::S64,
        });
        left_entry.push(MInst::Branch {
            cond: hot,
            true_bb: BlockId(2),
            false_bb: BlockId(3),
        });

        let mut right_entry = MBlock::new(BlockId(2));
        right_entry.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 8,
            src: hot,
            size: OpSize::S64,
        });
        right_entry.push(MInst::Branch {
            cond: hot,
            true_bb: BlockId(1),
            false_bb: BlockId(3),
        });

        let mut exit = MBlock::new(BlockId(3));
        exit.push(MInst::Store {
            base: BaseReg::SimState,
            offset: 16,
            src: live_through,
            size: OpSize::S64,
        });
        exit.push(MInst::Return);
        func.blocks = vec![entry, left_entry, right_entry, exit];

        let cfg = super::super::cfg::normalize(&mut func).unwrap();
        let next_use = next_use::analyze(&func, &cfg).unwrap();
        let plan = plan(&func, &cfg, &next_use, 1).unwrap();
        let left = cfg.block_index[&BlockId(1)];
        let right = cfg.block_index[&BlockId(2)];
        let region = next_use.region_at_entry(left).unwrap();
        assert_eq!(next_use.region_at_entry(right), Some(region));
        assert_eq!(
            next_use.loop_regions[region].kind,
            LoopRegionKind::IrreducibleScc
        );
        for entry in [left, right] {
            assert_eq!(
                plan.w_entry[entry],
                LogicalSet::from_iter([LogicalValue(hot.0)])
            );
            assert!(!plan.w_entry[entry].contains(&LogicalValue(live_through.0)));
        }
    }
}