ferrugocc 0.4.0

An experimental C compiler and obfuscating compiler written in Rust, targeting x86_64 SysV ABI
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
//! レジスタ割り当てパス(Chapter 20)
//!
//! Pseudo レジスタを含むアセンブリ命令列に対して、
//! グラフ彩色によるレジスタ割り当てを行う。
//!
//! # パイプライン
//! ```text
//! Asm(Pseudo) → [liveness] → [interference graph] → [coalescing] → [graph coloring]
//!             → [replace] → Asm(Reg+Stack) → [fixup] → Asm(valid) → [emit]
//! ```
//!
//! # アルゴリズム
//! 1. 生存解析(後方データフロー解析)で各命令時点の生存変数集合を計算
//! 2. 干渉グラフを構築(同時に生存する変数間に辺を張る、Mov 辺も収集)
//! 3. 保守的 Coalescing(Briggs/George 基準で Mov 辺のノードを合体、冗長 Mov 除去)
//! 4. Chaitin-Briggs アルゴリズムでグラフ彩色(レジスタ割り当て)
//! 5. Pseudo オペランドを Register または Stack(spill) に置換
//! 6. Fixup パスで無効なオペランド組み合わせを修正(Truncate 含む)+ プロローグ/エピローグ生成
//!
//! # スタックフレームレイアウト
//! ```text
//! push %rbp                    ← RBP 保存
//! movq %rsp, %rbp
//! push %rbx                   ← callee-saved (使用時のみ)
//! push %r12                   ← callee-saved (使用時のみ)
//! subq $N, %rsp               ← spill + ローカル変数領域
//! ──────────────────────
//!  -8(%rbp)  : callee-saved push 領域 (push %rbx 等)
//!  -(8+callee_bytes)(%rbp) 以降 : spill スロット・ローカル変数
//! ```
//! Fixup 時に全ての負オフセット Stack オペランドを callee-saved push 分だけ
//! 下方にシフトし、push 領域との重複を防ぐ(shift_stack_offsets)。

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};

use super::asm_ast::*;
use crate::parse::ast::Type;

// ────────────────────────────────────────────
// 公開インターフェース
// ────────────────────────────────────────────

/// レジスタ割り当て結果。
///
/// - `instructions`: Pseudo が全て解決された命令列
/// - `spill_bytes`: spill スロットに必要なスタックサイズ(バイト)
/// - `callee_saved_used`: 使用した callee-saved レジスタ(push/pop が必要)
pub struct RegAllocResult {
    pub instructions: Vec<Instruction>,
    pub spill_bytes: usize,
    pub callee_saved_used: Vec<Reg>,
}

/// レジスタ割り当てを実行する。
///
/// 整数 Pseudo と XMM Pseudo を分離し、それぞれ独立にグラフ彩色を行う。
/// 整数は GP_ALLOCATABLE(12個)、XMM は XMM_ALLOCATABLE(15個)から割り当てる。
/// 割り当てられなかった変数は spill(スタック退避)となる。
pub fn allocate_registers(
    instructions: Vec<Instruction>,
    var_types: &HashMap<String, Type>,
) -> RegAllocResult {
    // 整数 Pseudo と XMM Pseudo を分類
    let (gp_pseudos, xmm_pseudos) = classify_pseudos(&instructions, var_types);

    // 生存解析
    let liveness = analyze_liveness(&instructions);

    // 整数グラフの彩色(coalescing 付き)
    let gp_coloring = if !gp_pseudos.is_empty() {
        let mut graph = build_interference_graph(&instructions, &liveness, &gp_pseudos, false);
        let merge_map = coalesce_graph(&mut graph, GP_ALLOCATABLE.len());
        let mut coloring = color_graph(graph, &GP_ALLOCATABLE, false);
        apply_merge_map(&mut coloring, &merge_map);
        coloring
    } else {
        ColoringResult {
            assignments: HashMap::new(),
        }
    };

    // XMM グラフの彩色(coalescing 付き)
    let xmm_coloring = if !xmm_pseudos.is_empty() {
        let mut graph = build_interference_graph(&instructions, &liveness, &xmm_pseudos, true);
        let merge_map = coalesce_graph(&mut graph, XMM_ALLOCATABLE.len());
        let mut coloring = color_graph(graph, &XMM_ALLOCATABLE, true);
        apply_merge_map(&mut coloring, &merge_map);
        coloring
    } else {
        ColoringResult {
            assignments: HashMap::new(),
        }
    };

    // Pseudo 置換
    let mut assignments: HashMap<String, Operand> = HashMap::new();
    let mut callee_saved_set: HashSet<Reg> = HashSet::new();

    // 強制スタック変数(配列、構造体等)の最も深いオフセットを取得し、
    // スピル変数がそれらと重ならないようにする。
    let mut next_spill_offset: i32 = scan_min_stack_offset(&instructions);
    // ソート済みキーで反復し、スピルオフセットの割り当てを決定的にする
    let mut gp_keys: Vec<&String> = gp_coloring.assignments.keys().collect();
    gp_keys.sort();
    for name in gp_keys {
        let assignment = &gp_coloring.assignments[name];
        match assignment {
            Assignment::Register(reg) => {
                assignments.insert(name.clone(), Operand::Register(*reg));
                if GP_CALLEE_SAVED.contains(reg) {
                    callee_saved_set.insert(*reg);
                }
            }
            Assignment::Spill => {
                next_spill_offset -= 8;
                assignments.insert(name.clone(), Operand::Stack(next_spill_offset));
            }
        }
    }

    // XMM 割り当て結果をマージ(ソート済みキーで決定的に)
    let mut xmm_keys: Vec<&String> = xmm_coloring.assignments.keys().collect();
    xmm_keys.sort();
    for name in xmm_keys {
        let assignment = &xmm_coloring.assignments[name];
        match assignment {
            Assignment::Register(reg) => {
                assignments.insert(name.clone(), Operand::Register(*reg));
                // XMM はすべて caller-saved なので callee-saved に追加しない
            }
            Assignment::Spill => {
                next_spill_offset -= 8;
                assignments.insert(name.clone(), Operand::Stack(next_spill_offset));
            }
        }
    }

    // 命令列の Pseudo を置換
    let instructions = replace_pseudos(instructions, &assignments);

    // callee-saved の順序を固定(push/pop の一貫性のため)
    let mut callee_saved_used: Vec<Reg> = callee_saved_set.into_iter().collect();
    callee_saved_used.sort_by_key(|r| GP_CALLEE_SAVED.iter().position(|x| x == r).unwrap_or(99));

    RegAllocResult {
        instructions,
        spill_bytes: (-next_spill_offset) as usize,
        callee_saved_used,
    }
}

/// Fixup パス: 無効なオペランド組み合わせの修正 + プロローグ/エピローグ生成。
///
/// x86-64 では memory-memory 命令が不正なため、scratch レジスタ(R10/R11/XMM15)
/// 経由に展開する。また符号/ゼロ拡張命令(`movsbl`, `movslq`, `movzbl` 等)は
/// dst がメモリの場合も無効なため、レジスタ経由に展開する。
/// その後、spill サイズと使用した callee-saved レジスタに基づいて
/// プロローグ(push + subq)とエピローグ(addq + pop)を挿入する。
pub fn fixup_instructions(
    instructions: Vec<Instruction>,
    spill_bytes: usize,
    callee_saved_used: &[Reg],
) -> Vec<Instruction> {
    // 1. 無効なオペランド組み合わせを修正
    let mut fixed = Vec::new();
    for instr in instructions {
        fixup_instruction(instr, &mut fixed);
    }

    // 2. プロローグ/エピローグを挿入
    insert_prologue_epilogue(fixed, spill_bytes, callee_saved_used)
}

// ────────────────────────────────────────────
// 内部: Pseudo 分類
// ────────────────────────────────────────────

/// 命令列内の全 Pseudo を var_types に基づいて整数/XMM に分類する。
/// Double 型の変数は XMM グラフ、それ以外は整数グラフで彩色される。
fn classify_pseudos(
    instructions: &[Instruction],
    var_types: &HashMap<String, Type>,
) -> (HashSet<String>, HashSet<String>) {
    let mut gp = HashSet::new();
    let mut xmm = HashSet::new();

    for instr in instructions {
        for_each_operand(instr, |op| {
            if let Operand::Pseudo(name) = op {
                let ty = var_types.get(name);
                if ty.is_some_and(|t| t.is_floating()) {
                    xmm.insert(name.clone());
                } else {
                    gp.insert(name.clone());
                }
            }
        });
    }

    (gp, xmm)
}

// ────────────────────────────────────────────
// 内部: 生存解析
// ────────────────────────────────────────────

/// 干渉グラフのノード
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
enum GraphNode {
    Pseudo(String),
    HardReg(Reg),
}

/// 生存解析の結果
struct LivenessInfo {
    live_after: Vec<HashSet<GraphNode>>,
}

/// 命令が使用(use)するオペランドを収集
fn instruction_uses(instr: &Instruction) -> Vec<GraphNode> {
    let mut uses = Vec::new();

    match instr {
        Instruction::Mov { src, dst, .. } => {
            add_operand_nodes_for_use(src, &mut uses);
            // dst が Memory/MemoryOffset の場合、ベースレジスタはアドレス計算で読まれる
            add_memory_base_to_uses(dst, &mut uses);
        }
        Instruction::Unary { operand, .. } => {
            add_operand_nodes_for_use(operand, &mut uses);
        }
        Instruction::Cmp { src, dst, .. } => {
            add_operand_nodes_for_use(src, &mut uses);
            add_operand_nodes_for_use(dst, &mut uses);
        }
        Instruction::SetCC { operand, .. } => {
            // dst が Memory/MemoryOffset の場合、ベースレジスタはアドレス計算で読まれる
            add_memory_base_to_uses(operand, &mut uses);
        }
        Instruction::Binary { src, dst, .. } => {
            add_operand_nodes_for_use(src, &mut uses);
            add_operand_nodes_for_use(dst, &mut uses);
        }
        Instruction::Idiv { operand, .. } => {
            add_operand_nodes_for_use(operand, &mut uses);
            uses.push(GraphNode::HardReg(Reg::AX));
            uses.push(GraphNode::HardReg(Reg::DX));
        }
        Instruction::Div { operand, .. } => {
            add_operand_nodes_for_use(operand, &mut uses);
            uses.push(GraphNode::HardReg(Reg::AX));
            uses.push(GraphNode::HardReg(Reg::DX));
        }
        Instruction::SignExtend(_) => {
            uses.push(GraphNode::HardReg(Reg::AX));
        }
        Instruction::Movsx { src, dst, .. } => {
            add_operand_nodes_for_use(src, &mut uses);
            add_memory_base_to_uses(dst, &mut uses);
        }
        Instruction::MovsxByte { src, dst, .. } => {
            add_operand_nodes_for_use(src, &mut uses);
            add_memory_base_to_uses(dst, &mut uses);
        }
        Instruction::MovZeroExtend { src, dst, .. } => {
            add_operand_nodes_for_use(src, &mut uses);
            add_memory_base_to_uses(dst, &mut uses);
        }
        Instruction::MovZeroExtendByte { src, dst, .. } => {
            add_operand_nodes_for_use(src, &mut uses);
            add_memory_base_to_uses(dst, &mut uses);
        }
        Instruction::MovsxWord { src, dst, .. } => {
            add_operand_nodes_for_use(src, &mut uses);
            add_memory_base_to_uses(dst, &mut uses);
        }
        Instruction::MovZeroExtendWord { src, dst, .. } => {
            add_operand_nodes_for_use(src, &mut uses);
            add_memory_base_to_uses(dst, &mut uses);
        }
        Instruction::Truncate { src, dst, .. } => {
            add_operand_nodes_for_use(src, &mut uses);
            add_memory_base_to_uses(dst, &mut uses);
        }
        Instruction::Push(op) => {
            add_operand_nodes_for_use(op, &mut uses);
        }
        Instruction::Pop(op) => {
            // dst が Memory/MemoryOffset の場合、ベースレジスタはアドレス計算で読まれる
            add_memory_base_to_uses(op, &mut uses);
        }
        Instruction::Jmp(_) | Instruction::JmpCC(_, _) | Instruction::Label(_) => {}
        Instruction::AllocateStack(_) | Instruction::DeallocateStack(_) => {}
        Instruction::Call(_) => {}
        Instruction::Ret => {
            uses.push(GraphNode::HardReg(Reg::AX));
        }
        Instruction::Cvtsi2sd { src, dst, .. } => {
            add_operand_nodes_for_use(src, &mut uses);
            add_memory_base_to_uses(dst, &mut uses);
        }
        Instruction::Cvttsd2si { src, dst, .. } => {
            add_operand_nodes_for_use(src, &mut uses);
            add_memory_base_to_uses(dst, &mut uses);
        }
        Instruction::Cvtsi2ss { src, dst, .. } => {
            add_operand_nodes_for_use(src, &mut uses);
            add_memory_base_to_uses(dst, &mut uses);
        }
        Instruction::Cvttss2si { src, dst, .. } => {
            add_operand_nodes_for_use(src, &mut uses);
            add_memory_base_to_uses(dst, &mut uses);
        }
        Instruction::Cvtss2sd { src, dst } => {
            add_operand_nodes_for_use(src, &mut uses);
            add_memory_base_to_uses(dst, &mut uses);
        }
        Instruction::Cvtsd2ss { src, dst } => {
            add_operand_nodes_for_use(src, &mut uses);
            add_memory_base_to_uses(dst, &mut uses);
        }
        Instruction::Lea { src, dst, .. } => {
            add_operand_nodes_for_use(src, &mut uses);
            add_memory_base_to_uses(dst, &mut uses);
        }
        Instruction::JmpIndirect(op, _) => {
            add_operand_nodes_for_use(op, &mut uses);
        }
        Instruction::CallIndirect(op) => {
            add_operand_nodes_for_use(op, &mut uses);
        }
        Instruction::RawBytes(_) => {}
    }

    uses
}

/// 命令が定義(def)するオペランドを収集
fn instruction_defs(instr: &Instruction) -> Vec<GraphNode> {
    let mut defs = Vec::new();

    match instr {
        Instruction::Mov { dst, .. } => {
            add_operand_nodes_for_def(dst, &mut defs);
        }
        Instruction::Unary { operand, .. } => {
            add_operand_nodes_for_def(operand, &mut defs);
        }
        Instruction::Cmp { .. } => {}
        Instruction::SetCC { operand, .. } => {
            add_operand_nodes_for_def(operand, &mut defs);
        }
        Instruction::Binary { dst, .. } => {
            add_operand_nodes_for_def(dst, &mut defs);
        }
        Instruction::Idiv { .. } => {
            defs.push(GraphNode::HardReg(Reg::AX));
            defs.push(GraphNode::HardReg(Reg::DX));
        }
        Instruction::Div { .. } => {
            defs.push(GraphNode::HardReg(Reg::AX));
            defs.push(GraphNode::HardReg(Reg::DX));
        }
        Instruction::SignExtend(_) => {
            defs.push(GraphNode::HardReg(Reg::DX));
        }
        Instruction::Movsx { dst, .. } => {
            add_operand_nodes_for_def(dst, &mut defs);
        }
        Instruction::MovsxByte { dst, .. } => {
            add_operand_nodes_for_def(dst, &mut defs);
        }
        Instruction::MovZeroExtend { dst, .. } => {
            add_operand_nodes_for_def(dst, &mut defs);
        }
        Instruction::MovZeroExtendByte { dst, .. } => {
            add_operand_nodes_for_def(dst, &mut defs);
        }
        Instruction::MovsxWord { dst, .. } => {
            add_operand_nodes_for_def(dst, &mut defs);
        }
        Instruction::MovZeroExtendWord { dst, .. } => {
            add_operand_nodes_for_def(dst, &mut defs);
        }
        Instruction::Truncate { dst, .. } => {
            add_operand_nodes_for_def(dst, &mut defs);
        }
        Instruction::Push(_) => {}
        Instruction::Pop(op) => {
            add_operand_nodes_for_def(op, &mut defs);
        }
        Instruction::Jmp(_) | Instruction::JmpCC(_, _) | Instruction::Label(_) => {}
        Instruction::AllocateStack(_) | Instruction::DeallocateStack(_) => {}
        Instruction::Call(_) => {
            // Call destroys all caller-saved registers
            for &reg in &GP_CALLER_SAVED {
                defs.push(GraphNode::HardReg(reg));
            }
            for &reg in &XMM_ALL {
                defs.push(GraphNode::HardReg(reg));
            }
        }
        Instruction::Ret => {}
        Instruction::Cvtsi2sd { dst, .. } => {
            add_operand_nodes_for_def(dst, &mut defs);
        }
        Instruction::Cvttsd2si { dst, .. } => {
            add_operand_nodes_for_def(dst, &mut defs);
        }
        Instruction::Cvtsi2ss { dst, .. } => {
            add_operand_nodes_for_def(dst, &mut defs);
        }
        Instruction::Cvttss2si { dst, .. } => {
            add_operand_nodes_for_def(dst, &mut defs);
        }
        Instruction::Cvtss2sd { dst, .. } => {
            add_operand_nodes_for_def(dst, &mut defs);
        }
        Instruction::Cvtsd2ss { dst, .. } => {
            add_operand_nodes_for_def(dst, &mut defs);
        }
        Instruction::Lea { dst, .. } => {
            add_operand_nodes_for_def(dst, &mut defs);
        }
        Instruction::JmpIndirect(_, _) => {}
        Instruction::CallIndirect(_) => {
            // Same as Call: destroys all caller-saved registers
            for &reg in &GP_CALLER_SAVED {
                defs.push(GraphNode::HardReg(reg));
            }
            for &reg in &XMM_ALL {
                defs.push(GraphNode::HardReg(reg));
            }
        }
        Instruction::RawBytes(_) => {}
    }

    defs
}

/// オペランドを「使用(use)」として追加する。
/// Memory(reg) / MemoryOffset(reg, _) のベースレジスタはアドレス計算で読まれるので use に含める。
fn add_operand_nodes_for_use(op: &Operand, nodes: &mut Vec<GraphNode>) {
    match op {
        Operand::Register(reg) => nodes.push(GraphNode::HardReg(*reg)),
        Operand::Pseudo(name) => nodes.push(GraphNode::Pseudo(name.clone())),
        Operand::Memory(reg) => nodes.push(GraphNode::HardReg(*reg)),
        Operand::MemoryOffset(reg, _) => nodes.push(GraphNode::HardReg(*reg)),
        Operand::Imm(_) | Operand::Stack(_) | Operand::Data(_) => {}
    }
}

/// オペランドを「定義(def)」として追加する。
/// Memory(reg) / MemoryOffset(reg, _) はメモリへの書き込みであり、
/// ベースレジスタ自体は書き換えられないので def に含めない。
fn add_operand_nodes_for_def(op: &Operand, nodes: &mut Vec<GraphNode>) {
    match op {
        Operand::Register(reg) => nodes.push(GraphNode::HardReg(*reg)),
        Operand::Pseudo(name) => nodes.push(GraphNode::Pseudo(name.clone())),
        Operand::Memory(_) | Operand::MemoryOffset(_, _) => {
            // メモリへの書き込みはベースレジスタの定義ではない
        }
        Operand::Imm(_) | Operand::Stack(_) | Operand::Data(_) => {}
    }
}

/// Memory/MemoryOffset のベースレジスタだけを use に追加する。
/// dst が Memory(reg) の場合、アドレス計算でレジスタが読まれるため。
fn add_memory_base_to_uses(op: &Operand, nodes: &mut Vec<GraphNode>) {
    match op {
        Operand::Memory(reg) => nodes.push(GraphNode::HardReg(*reg)),
        Operand::MemoryOffset(reg, _) => nodes.push(GraphNode::HardReg(*reg)),
        _ => {}
    }
}

/// 命令がジャンプ先を持つ場合、そのラベルを返す
fn jump_targets(instr: &Instruction) -> Vec<String> {
    match instr {
        Instruction::Jmp(label) => vec![label.clone()],
        Instruction::JmpCC(_, label) => vec![label.clone()],
        // JmpIndirect: ジャンプテーブルの全エントリを CFG 後続として返す
        Instruction::JmpIndirect(_, targets) => targets.clone(),
        _ => vec![],
    }
}

/// 後方データフロー解析で各命令の直後の生存集合を計算する。
///
/// ラベル/ジャンプから CFG(制御フロー・グラフ)を構築し、
/// 不動点反復で各命令時点の `live_in`/`live_after` を求める。
///
/// ```text
/// live_after[i] = ∪ { live_in[s] | s は i の後続命令 }
/// live_in[i]    = uses[i] ∪ (live_after[i] - defs[i])
/// ```
fn analyze_liveness(instructions: &[Instruction]) -> LivenessInfo {
    let n = instructions.len();
    if n == 0 {
        return LivenessInfo { live_after: vec![] };
    }

    // ラベル→命令インデックスのマッピング
    let mut label_to_idx: HashMap<String, usize> = HashMap::new();
    for (i, instr) in instructions.iter().enumerate() {
        if let Instruction::Label(label) = instr {
            label_to_idx.insert(label.clone(), i);
        }
    }

    // 各命令の後続命令インデックス
    let mut successors: Vec<Vec<usize>> = vec![vec![]; n];
    for i in 0..n {
        let targets = jump_targets(&instructions[i]);
        for target in &targets {
            if let Some(&idx) = label_to_idx.get(target) {
                successors[i].push(idx);
            }
        }
        // フォールスルー(Jmp, JmpIndirect, Ret 以外)
        if !matches!(
            instructions[i],
            Instruction::Jmp(_) | Instruction::JmpIndirect(_, _) | Instruction::Ret
        ) && i + 1 < n
        {
            successors[i].push(i + 1);
        }
    }

    // 各命令の use/def を事前計算
    let uses: Vec<HashSet<GraphNode>> = instructions
        .iter()
        .map(|instr| instruction_uses(instr).into_iter().collect())
        .collect();
    let defs: Vec<HashSet<GraphNode>> = instructions
        .iter()
        .map(|instr| instruction_defs(instr).into_iter().collect())
        .collect();

    // live_in[i], live_after[i]
    let mut live_in: Vec<HashSet<GraphNode>> = vec![HashSet::new(); n];
    let mut live_after: Vec<HashSet<GraphNode>> = vec![HashSet::new(); n];

    // 不動点反復(後方から)
    let mut changed = true;
    while changed {
        changed = false;
        for i in (0..n).rev() {
            // live_after[i] = union of live_in[s] for s in successors[i]
            let mut new_after: HashSet<GraphNode> = HashSet::new();
            for &s in &successors[i] {
                for node in &live_in[s] {
                    new_after.insert(node.clone());
                }
            }

            // live_in[i] = uses[i] ∪ (live_after[i] - defs[i])
            let mut new_in: HashSet<GraphNode> = uses[i].clone();
            for node in &new_after {
                if !defs[i].contains(node) {
                    new_in.insert(node.clone());
                }
            }

            if new_in != live_in[i] || new_after != live_after[i] {
                changed = true;
                live_in[i] = new_in;
                live_after[i] = new_after;
            }
        }
    }

    LivenessInfo { live_after }
}

// ────────────────────────────────────────────
// 内部: 干渉グラフ
// ────────────────────────────────────────────

struct InterferenceGraph {
    /// 隣接リスト(BTreeMap で反復順序を決定的にする)
    adj: BTreeMap<GraphNode, BTreeSet<GraphNode>>,
    /// Mov 辺: coalescing 候補の (src, dst) ペア
    mov_edges: Vec<(GraphNode, GraphNode)>,
}

impl InterferenceGraph {
    fn new() -> Self {
        InterferenceGraph {
            adj: BTreeMap::new(),
            mov_edges: Vec::new(),
        }
    }

    fn add_node(&mut self, node: GraphNode) {
        self.adj.entry(node).or_default();
    }

    fn add_edge(&mut self, a: &GraphNode, b: &GraphNode) {
        if a == b {
            return;
        }
        self.adj.entry(a.clone()).or_default().insert(b.clone());
        self.adj.entry(b.clone()).or_default().insert(a.clone());
    }
}

/// 干渉グラフを構築する。
///
/// 各命令の定義変数と、その命令直後に生存している変数の間に干渉辺を張る。
/// Mov 系命令では src-dst 間に辺を張らない(将来の coalescing 最適化のため)。
///
/// - `relevant_pseudos`: このグラフに含める Pseudo 集合(整数 or XMM)
/// - `is_xmm`: true なら XMM レジスタのみ追跡、false なら整数レジスタのみ追跡
fn build_interference_graph(
    instructions: &[Instruction],
    liveness: &LivenessInfo,
    relevant_pseudos: &HashSet<String>,
    is_xmm: bool,
) -> InterferenceGraph {
    let mut graph = InterferenceGraph::new();

    // 関連するハードレジスタ集合
    let relevant_hard_regs: HashSet<Reg> = if is_xmm {
        XMM_ALL.iter().copied().collect()
    } else {
        let mut s: HashSet<Reg> = GP_ALLOCATABLE.iter().copied().collect();
        s.insert(Reg::R10);
        s.insert(Reg::R11);
        s
    };

    // フィルター関数: このグラフに含めるべきノードかどうか
    let is_relevant = |node: &GraphNode| -> bool {
        match node {
            GraphNode::Pseudo(name) => relevant_pseudos.contains(name),
            GraphNode::HardReg(reg) => relevant_hard_regs.contains(reg),
        }
    };

    // 全 Pseudo をノードとして追加
    for name in relevant_pseudos {
        graph.add_node(GraphNode::Pseudo(name.clone()));
    }

    // 各命令について干渉辺を追加
    for (i, instr) in instructions.iter().enumerate() {
        let defined = instruction_defs(instr);
        let live_after = &liveness.live_after[i];

        let is_mov = matches!(
            instr,
            Instruction::Mov { .. }
                | Instruction::Movsx { .. }
                | Instruction::MovsxByte { .. }
                | Instruction::MovsxWord { .. }
                | Instruction::MovZeroExtend { .. }
                | Instruction::MovZeroExtendByte { .. }
                | Instruction::MovZeroExtendWord { .. }
                | Instruction::Truncate { .. }
        );

        // Mov のソースを取得(coalescing のため干渉辺を張らない)
        let mov_src: Option<GraphNode> = if is_mov {
            let uses = instruction_uses(instr);
            uses.into_iter().next()
        } else {
            None
        };

        for d in &defined {
            if !is_relevant(d) {
                continue;
            }
            graph.add_node(d.clone());

            for v in live_after {
                if !is_relevant(v) {
                    continue;
                }
                if v == d {
                    continue;
                }
                // Mov の場合、src と dst の間には辺を張らない
                if is_mov
                    && let Some(ref src_node) = mov_src
                    && v == src_node
                {
                    continue;
                }
                graph.add_edge(d, v);
            }
        }

        // Mov 辺を収集(coalescing 候補 — plain Mov のみ)
        // Movsx/Truncate 等の型変換命令は値が変わるため coalescing しない。
        if matches!(instr, Instruction::Mov { .. })
            && let Some(ref src_node) = mov_src
        {
            for d in &defined {
                if is_relevant(src_node) && is_relevant(d) && src_node != d {
                    graph.mov_edges.push((src_node.clone(), d.clone()));
                }
            }
        }
    }

    graph
}

// ────────────────────────────────────────────
// 内部: Coalescing(レジスタ合体)
// ────────────────────────────────────────────

/// merge_map のルートを辿って正規ノードを返す。
fn find_canonical(merge_map: &HashMap<GraphNode, GraphNode>, node: &GraphNode) -> GraphNode {
    let mut current = node.clone();
    while let Some(next) = merge_map.get(&current) {
        current = next.clone();
    }
    current
}

/// 保守的 coalescing(Briggs + George 基準)を実行する。
///
/// Mov 辺で結ばれた非干渉ノードペアを合体し、冗長な Mov を除去する。
/// - **Briggs 基準** (Pseudo-Pseudo): 合体ノードの degree ≥ k な隣接ノード数 < k なら安全
/// - **George 基準** (Pseudo-HardReg): Pseudo の全隣接ノード t が、
///   HardReg とも干渉するか degree < k なら安全
///
/// 戻り値の merge_map は「このノードはあのノードに合体された」を記録する。
fn coalesce_graph(graph: &mut InterferenceGraph, k: usize) -> HashMap<GraphNode, GraphNode> {
    let mut merge_map: HashMap<GraphNode, GraphNode> = HashMap::new();

    let mut changed = true;
    while changed {
        changed = false;
        let mov_edges_snapshot = graph.mov_edges.clone();

        for (raw_u, raw_v) in &mov_edges_snapshot {
            let u = find_canonical(&merge_map, raw_u);
            let v = find_canonical(&merge_map, raw_v);
            if u == v {
                continue;
            } // 既に合体済み

            // 干渉していたら合体不可
            if graph.adj.get(&u).is_some_and(|s| s.contains(&v)) {
                continue;
            }

            let can_coalesce = match (&u, &v) {
                // Pseudo-Pseudo: Briggs 基準
                (GraphNode::Pseudo(_), GraphNode::Pseudo(_)) => briggs_criterion(graph, &u, &v, k),
                // Pseudo-HardReg: George 基準(Pseudo を HardReg に合体)
                (GraphNode::Pseudo(_), GraphNode::HardReg(_)) => george_criterion(graph, &u, &v, k),
                (GraphNode::HardReg(_), GraphNode::Pseudo(_)) => george_criterion(graph, &v, &u, k),
                // HardReg-HardReg: 同じレジスタでない限り合体不可
                (GraphNode::HardReg(_), GraphNode::HardReg(_)) => false,
            };

            if can_coalesce {
                // HardReg は常に into 側(正規ノード、グラフに残る)
                let (from, into) = match (&u, &v) {
                    (GraphNode::HardReg(_), _) => (v.clone(), u.clone()),
                    (_, GraphNode::HardReg(_)) => (u.clone(), v.clone()),
                    _ => (u.clone(), v.clone()),
                };
                merge_nodes(graph, &from, &into);
                merge_map.insert(from, into);
                changed = true;
                break; // グラフが変更されたので再走査
            }
        }
    }

    merge_map
}

/// Briggs 基準: 合体後のノードが k 未満の高次隣接ノードを持つか判定。
fn briggs_criterion(graph: &InterferenceGraph, u: &GraphNode, v: &GraphNode, k: usize) -> bool {
    let u_neighbors = graph.adj.get(u).cloned().unwrap_or_default();
    let v_neighbors = graph.adj.get(v).cloned().unwrap_or_default();
    let mut merged_neighbors: BTreeSet<GraphNode> = u_neighbors;
    merged_neighbors.extend(v_neighbors);
    merged_neighbors.remove(u);
    merged_neighbors.remove(v);

    let high_degree_count = merged_neighbors
        .iter()
        .filter(|n| match n {
            GraphNode::HardReg(_) => true, // precolored は常に高次
            GraphNode::Pseudo(_) => graph.adj.get(n).map_or(0, |s| s.len()) >= k,
        })
        .count();

    high_degree_count < k
}

/// George 基準: u (Pseudo) の全隣接ノードが v (HardReg) とも干渉するか低次か判定。
fn george_criterion(
    graph: &InterferenceGraph,
    u: &GraphNode, // Pseudo
    v: &GraphNode, // HardReg
    k: usize,
) -> bool {
    let u_neighbors = graph.adj.get(u).cloned().unwrap_or_default();
    let v_neighbors = graph.adj.get(v).cloned().unwrap_or_default();

    for t in &u_neighbors {
        if t == v {
            continue;
        }
        if v_neighbors.contains(t) {
            continue;
        } // t は v とも干渉 → OK
        match t {
            GraphNode::HardReg(_) => return false, // HardReg が v と非干渉 → 不安全
            GraphNode::Pseudo(_) => {
                if graph.adj.get(t).map_or(0, |s| s.len()) >= k {
                    return false; // 高次 Pseudo が v と非干渉 → 不安全
                }
            }
        }
    }
    true
}

/// ノード `from` を `into` に合体する。隣接リストを更新。
fn merge_nodes(graph: &mut InterferenceGraph, from: &GraphNode, into: &GraphNode) {
    let from_neighbors = graph.adj.remove(from).unwrap_or_default();

    for n in &from_neighbors {
        if n == into {
            continue;
        }
        // n の隣接リストから from を削除し into を追加
        if let Some(s) = graph.adj.get_mut(n) {
            s.remove(from);
            s.insert(into.clone());
        }
        // into の隣接リストに n を追加
        graph.adj.entry(into.clone()).or_default().insert(n.clone());
    }

    // into の隣接リストから from を削除(self-loop 防止)
    if let Some(s) = graph.adj.get_mut(into) {
        s.remove(from);
    }
}

/// coalescing の merge_map を彩色結果に適用する。
///
/// merge_map 内の各 (from → into) エントリについて、
/// from の Pseudo に into の割り当て(色)をコピーする。
fn apply_merge_map(coloring: &mut ColoringResult, merge_map: &HashMap<GraphNode, GraphNode>) {
    // ソート済みキーで反復し、割り当てを決定的にする
    let mut entries: Vec<_> = merge_map.iter().collect();
    entries.sort_by(|a, b| a.0.cmp(b.0));
    for (from, into) in entries {
        if let GraphNode::Pseudo(from_name) = from {
            let canonical = find_canonical(merge_map, into);
            match &canonical {
                GraphNode::Pseudo(canonical_name) => {
                    if let Some(assignment) = coloring.assignments.get(canonical_name).cloned() {
                        coloring.assignments.insert(from_name.clone(), assignment);
                    }
                }
                GraphNode::HardReg(reg) => {
                    coloring
                        .assignments
                        .insert(from_name.clone(), Assignment::Register(*reg));
                }
            }
        }
    }
}

// ────────────────────────────────────────────
// 内部: グラフ彩色(Chaitin-Briggs)
// ────────────────────────────────────────────

#[derive(Debug, Clone)]
enum Assignment {
    Register(Reg),
    Spill,
}

struct ColoringResult {
    assignments: HashMap<String, Assignment>,
}

/// Chaitin-Briggs アルゴリズムでグラフ彩色を行う。
///
/// 1. **Simplify**: degree < k のノードをスタックに push して除去
/// 2. **Potential Spill**: 全ノードが degree >= k なら、最大 degree のノードを
///    spill 候補としてマークし push
/// 3. **Select**: スタックから pop し、隣接ノードが使っていない色を割り当て。
///    spill 候補でも色が見つかれば割り当てる(楽観的彩色)。
///    色が見つからなければ実際に spill(スタック退避)。
fn color_graph(graph: InterferenceGraph, allocatable: &[Reg], _is_xmm: bool) -> ColoringResult {
    let k = allocatable.len();

    // オリジナルの隣接リストを保存
    let original_adj = graph.adj.clone();

    // Pseudo ノードだけをリストアップ(ソートして決定的に)
    let mut pseudo_nodes: Vec<String> = graph
        .adj
        .keys()
        .filter_map(|node| {
            if let GraphNode::Pseudo(name) = node {
                Some(name.clone())
            } else {
                None
            }
        })
        .collect();
    pseudo_nodes.sort();

    if pseudo_nodes.is_empty() {
        return ColoringResult {
            assignments: HashMap::new(),
        };
    }

    // Simplify + Potential Spill(working copy で)
    let mut working_adj: BTreeMap<GraphNode, BTreeSet<GraphNode>> = graph.adj;
    let mut stack: Vec<(String, bool)> = Vec::new();
    let mut remaining: BTreeSet<String> = pseudo_nodes.into_iter().collect();

    let working_degree = |adj: &BTreeMap<GraphNode, BTreeSet<GraphNode>>, name: &str| -> usize {
        let node = GraphNode::Pseudo(name.to_string());
        adj.get(&node).map_or(0, |s| s.len())
    };

    let remove_from_working = |adj: &mut BTreeMap<GraphNode, BTreeSet<GraphNode>>, name: &str| {
        let node = GraphNode::Pseudo(name.to_string());
        if let Some(neighbors) = adj.remove(&node) {
            for n in &neighbors {
                if let Some(s) = adj.get_mut(n) {
                    s.remove(&node);
                }
            }
        }
    };

    while !remaining.is_empty() {
        // Phase 1: degree < k のノードを除去
        let mut progress = true;
        while progress {
            progress = false;
            let candidates: Vec<String> = remaining
                .iter()
                .filter(|name| working_degree(&working_adj, name) < k)
                .cloned()
                .collect();

            for name in candidates {
                remove_from_working(&mut working_adj, &name);
                stack.push((name.clone(), false));
                remaining.remove(&name);
                progress = true;
            }
        }

        // Phase 2: spill 候補
        if !remaining.is_empty() {
            let spill_name = remaining
                .iter()
                .max_by_key(|name| working_degree(&working_adj, name))
                .cloned()
                .unwrap();

            remove_from_working(&mut working_adj, &spill_name);
            stack.push((spill_name.clone(), true));
            remaining.remove(&spill_name);
        }
    }

    // Select: スタックから pop して色を割り当て
    let mut assignments: HashMap<String, Assignment> = HashMap::new();
    // HardReg の「色」は自分自身
    let reg_to_color: HashMap<Reg, usize> = allocatable
        .iter()
        .enumerate()
        .map(|(i, &reg)| (reg, i))
        .collect();

    while let Some((name, _is_spill_candidate)) = stack.pop() {
        let node = GraphNode::Pseudo(name.clone());
        let original_neighbors = original_adj.get(&node).cloned().unwrap_or_default();

        // 隣接ノードが使っている色を収集
        let mut used_colors: HashSet<usize> = HashSet::new();
        for neighbor in &original_neighbors {
            match neighbor {
                GraphNode::HardReg(reg) => {
                    if let Some(&color) = reg_to_color.get(reg) {
                        used_colors.insert(color);
                    }
                }
                GraphNode::Pseudo(n) => {
                    if let Some(Assignment::Register(reg)) = assignments.get(n)
                        && let Some(&color) = reg_to_color.get(reg)
                    {
                        used_colors.insert(color);
                    }
                }
            }
        }

        // 空いている色を探す
        let mut assigned = false;
        for (color, &reg) in allocatable.iter().enumerate() {
            if !used_colors.contains(&color) {
                assignments.insert(name.clone(), Assignment::Register(reg));
                assigned = true;
                break;
            }
        }

        if !assigned {
            // Spill
            assignments.insert(name.clone(), Assignment::Spill);
        }
    }

    ColoringResult { assignments }
}

// ────────────────────────────────────────────
// 内部: Pseudo 置換
// ────────────────────────────────────────────

/// 全命令の Pseudo オペランドを彩色結果に基づいて置換する。
/// Register が割り当てられた Pseudo → `Operand::Register(reg)`
/// Spill された Pseudo → `Operand::Stack(offset)`
fn replace_pseudos(
    instructions: Vec<Instruction>,
    assignments: &HashMap<String, Operand>,
) -> Vec<Instruction> {
    instructions
        .into_iter()
        .map(|instr| replace_in_instruction(instr, assignments))
        .collect()
}

fn replace_operand(op: Operand, assignments: &HashMap<String, Operand>) -> Operand {
    match op {
        Operand::Pseudo(ref name) => assignments.get(name).cloned().unwrap_or(op),
        _ => op,
    }
}

fn replace_in_instruction(
    instr: Instruction,
    assignments: &HashMap<String, Operand>,
) -> Instruction {
    match instr {
        Instruction::Mov { asm_type, src, dst } => Instruction::Mov {
            asm_type,
            src: replace_operand(src, assignments),
            dst: replace_operand(dst, assignments),
        },
        Instruction::Unary {
            asm_type,
            op,
            operand,
        } => Instruction::Unary {
            asm_type,
            op,
            operand: replace_operand(operand, assignments),
        },
        Instruction::Cmp { asm_type, src, dst } => Instruction::Cmp {
            asm_type,
            src: replace_operand(src, assignments),
            dst: replace_operand(dst, assignments),
        },
        Instruction::SetCC { condition, operand } => Instruction::SetCC {
            condition,
            operand: replace_operand(operand, assignments),
        },
        Instruction::Binary {
            asm_type,
            op,
            src,
            dst,
        } => Instruction::Binary {
            asm_type,
            op,
            src: replace_operand(src, assignments),
            dst: replace_operand(dst, assignments),
        },
        Instruction::Idiv { asm_type, operand } => Instruction::Idiv {
            asm_type,
            operand: replace_operand(operand, assignments),
        },
        Instruction::Div { asm_type, operand } => Instruction::Div {
            asm_type,
            operand: replace_operand(operand, assignments),
        },
        Instruction::Movsx { src, dst } => Instruction::Movsx {
            src: replace_operand(src, assignments),
            dst: replace_operand(dst, assignments),
        },
        Instruction::MovsxByte { asm_type, src, dst } => Instruction::MovsxByte {
            asm_type,
            src: replace_operand(src, assignments),
            dst: replace_operand(dst, assignments),
        },
        Instruction::MovZeroExtend { src, dst } => Instruction::MovZeroExtend {
            src: replace_operand(src, assignments),
            dst: replace_operand(dst, assignments),
        },
        Instruction::MovZeroExtendByte { asm_type, src, dst } => Instruction::MovZeroExtendByte {
            asm_type,
            src: replace_operand(src, assignments),
            dst: replace_operand(dst, assignments),
        },
        Instruction::MovsxWord { asm_type, src, dst } => Instruction::MovsxWord {
            asm_type,
            src: replace_operand(src, assignments),
            dst: replace_operand(dst, assignments),
        },
        Instruction::MovZeroExtendWord { asm_type, src, dst } => Instruction::MovZeroExtendWord {
            asm_type,
            src: replace_operand(src, assignments),
            dst: replace_operand(dst, assignments),
        },
        Instruction::Truncate { src, dst } => Instruction::Truncate {
            src: replace_operand(src, assignments),
            dst: replace_operand(dst, assignments),
        },
        Instruction::Push(op) => Instruction::Push(replace_operand(op, assignments)),
        Instruction::Pop(op) => Instruction::Pop(replace_operand(op, assignments)),
        Instruction::Cvtsi2sd { asm_type, src, dst } => Instruction::Cvtsi2sd {
            asm_type,
            src: replace_operand(src, assignments),
            dst: replace_operand(dst, assignments),
        },
        Instruction::Cvttsd2si { asm_type, src, dst } => Instruction::Cvttsd2si {
            asm_type,
            src: replace_operand(src, assignments),
            dst: replace_operand(dst, assignments),
        },
        Instruction::Cvtsi2ss { asm_type, src, dst } => Instruction::Cvtsi2ss {
            asm_type,
            src: replace_operand(src, assignments),
            dst: replace_operand(dst, assignments),
        },
        Instruction::Cvttss2si { asm_type, src, dst } => Instruction::Cvttss2si {
            asm_type,
            src: replace_operand(src, assignments),
            dst: replace_operand(dst, assignments),
        },
        Instruction::Cvtss2sd { src, dst } => Instruction::Cvtss2sd {
            src: replace_operand(src, assignments),
            dst: replace_operand(dst, assignments),
        },
        Instruction::Cvtsd2ss { src, dst } => Instruction::Cvtsd2ss {
            src: replace_operand(src, assignments),
            dst: replace_operand(dst, assignments),
        },
        Instruction::Lea { src, dst } => Instruction::Lea {
            src: replace_operand(src, assignments),
            dst: replace_operand(dst, assignments),
        },
        Instruction::JmpIndirect(op, ref targets) => {
            Instruction::JmpIndirect(replace_operand(op, assignments), targets.clone())
        }
        Instruction::CallIndirect(op) => {
            Instruction::CallIndirect(replace_operand(op, assignments))
        }
        // These don't have operands to replace
        instr @ (Instruction::SignExtend(_)
        | Instruction::Jmp(_)
        | Instruction::JmpCC(_, _)
        | Instruction::Label(_)
        | Instruction::AllocateStack(_)
        | Instruction::DeallocateStack(_)
        | Instruction::Call(_)
        | Instruction::Ret
        | Instruction::RawBytes(_)) => instr,
    }
}

// ────────────────────────────────────────────
// 内部: Fixup パス
// ────────────────────────────────────────────

fn is_memory_operand(op: &Operand) -> bool {
    matches!(
        op,
        Operand::Stack(_) | Operand::Data(_) | Operand::Memory(_) | Operand::MemoryOffset(_, _)
    )
}

fn is_imm(op: &Operand) -> bool {
    matches!(op, Operand::Imm(_))
}

fn is_large_imm(op: &Operand) -> bool {
    if let Operand::Imm(v) = op {
        *v > i32::MAX as i64 || *v < i32::MIN as i64
    } else {
        false
    }
}

fn fixup_instruction(instr: Instruction, out: &mut Vec<Instruction>) {
    match instr {
        // Mov: memory,memory → via scratch
        Instruction::Mov {
            asm_type,
            ref src,
            ref dst,
        } if is_memory_operand(src) && is_memory_operand(dst) => {
            if asm_type == AsmType::Double || asm_type == AsmType::Float {
                out.push(Instruction::Mov {
                    asm_type,
                    src: src.clone(),
                    dst: Operand::Register(Reg::XMM15),
                });
                out.push(Instruction::Mov {
                    asm_type,
                    src: Operand::Register(Reg::XMM15),
                    dst: dst.clone(),
                });
            } else {
                out.push(Instruction::Mov {
                    asm_type,
                    src: src.clone(),
                    dst: Operand::Register(Reg::R10),
                });
                out.push(Instruction::Mov {
                    asm_type,
                    src: Operand::Register(Reg::R10),
                    dst: dst.clone(),
                });
            }
        }

        // Mov: large immediate to memory → via R10
        Instruction::Mov {
            asm_type,
            ref src,
            ref dst,
        } if is_large_imm(src) && is_memory_operand(dst) => {
            out.push(Instruction::Mov {
                asm_type: AsmType::Quadword,
                src: src.clone(),
                dst: Operand::Register(Reg::R10),
            });
            out.push(Instruction::Mov {
                asm_type,
                src: Operand::Register(Reg::R10),
                dst: dst.clone(),
            });
        }

        // Mov src,src (same register) → remove noop
        Instruction::Mov {
            ref src, ref dst, ..
        } if src == dst => {
            // Skip noop moves
        }

        // Binary: memory,memory → via scratch (non-double)
        Instruction::Binary {
            asm_type,
            op,
            ref src,
            ref dst,
        } if asm_type != AsmType::Double
            && asm_type != AsmType::Float
            && is_memory_operand(src)
            && is_memory_operand(dst) =>
        {
            // imul cannot have memory dst, so load dst into R11
            if matches!(op, AsmBinaryOp::Mult) {
                out.push(Instruction::Mov {
                    asm_type,
                    src: dst.clone(),
                    dst: Operand::Register(Reg::R11),
                });
                out.push(Instruction::Binary {
                    asm_type,
                    op,
                    src: src.clone(),
                    dst: Operand::Register(Reg::R11),
                });
                out.push(Instruction::Mov {
                    asm_type,
                    src: Operand::Register(Reg::R11),
                    dst: dst.clone(),
                });
            } else {
                out.push(Instruction::Mov {
                    asm_type,
                    src: src.clone(),
                    dst: Operand::Register(Reg::R10),
                });
                out.push(Instruction::Binary {
                    asm_type,
                    op,
                    src: Operand::Register(Reg::R10),
                    dst: dst.clone(),
                });
            }
        }

        // Binary: Quadword with large immediate (> 32-bit signed) → via R10
        Instruction::Binary {
            asm_type: AsmType::Quadword,
            op,
            src: Operand::Imm(v),
            ref dst,
        } if v > i32::MAX as i64 || v < i32::MIN as i64 => {
            out.push(Instruction::Mov {
                asm_type: AsmType::Quadword,
                src: Operand::Imm(v),
                dst: Operand::Register(Reg::R10),
            });
            out.push(Instruction::Binary {
                asm_type: AsmType::Quadword,
                op,
                src: Operand::Register(Reg::R10),
                dst: dst.clone(),
            });
        }

        // Binary: double with memory dst → dst must be XMM register.
        // Load dst into XMM15, operate (src can be memory), store back.
        Instruction::Binary {
            asm_type,
            op,
            ref src,
            ref dst,
        } if (asm_type == AsmType::Double || asm_type == AsmType::Float)
            && is_memory_operand(dst) =>
        {
            out.push(Instruction::Mov {
                asm_type,
                src: dst.clone(),
                dst: Operand::Register(Reg::XMM15),
            });
            out.push(Instruction::Binary {
                asm_type,
                op,
                src: src.clone(),
                dst: Operand::Register(Reg::XMM15),
            });
            out.push(Instruction::Mov {
                asm_type,
                src: Operand::Register(Reg::XMM15),
                dst: dst.clone(),
            });
        }

        // Binary: imul with memory dst → via R11
        Instruction::Binary {
            asm_type,
            op: AsmBinaryOp::Mult,
            ref src,
            ref dst,
        } if asm_type != AsmType::Double
            && asm_type != AsmType::Float
            && is_memory_operand(dst) =>
        {
            out.push(Instruction::Mov {
                asm_type,
                src: dst.clone(),
                dst: Operand::Register(Reg::R11),
            });
            out.push(Instruction::Binary {
                asm_type,
                op: AsmBinaryOp::Mult,
                src: src.clone(),
                dst: Operand::Register(Reg::R11),
            });
            out.push(Instruction::Mov {
                asm_type,
                src: Operand::Register(Reg::R11),
                dst: dst.clone(),
            });
        }

        // Cmp: memory,memory → via R10
        Instruction::Cmp {
            asm_type,
            ref src,
            ref dst,
        } if asm_type != AsmType::Double
            && asm_type != AsmType::Float
            && is_memory_operand(src)
            && is_memory_operand(dst) =>
        {
            out.push(Instruction::Mov {
                asm_type,
                src: dst.clone(),
                dst: Operand::Register(Reg::R10),
            });
            out.push(Instruction::Cmp {
                asm_type,
                src: src.clone(),
                dst: Operand::Register(Reg::R10),
            });
        }

        // Cmp: dst is immediate → load dst into R10
        Instruction::Cmp {
            asm_type,
            ref src,
            dst: Operand::Imm(v),
        } => {
            out.push(Instruction::Mov {
                asm_type,
                src: Operand::Imm(v),
                dst: Operand::Register(Reg::R10),
            });
            out.push(Instruction::Cmp {
                asm_type,
                src: src.clone(),
                dst: Operand::Register(Reg::R10),
            });
        }

        // Cmp: large immediate → via R10
        Instruction::Cmp {
            asm_type,
            ref src,
            ref dst,
        } if is_large_imm(src) => {
            out.push(Instruction::Mov {
                asm_type: AsmType::Quadword,
                src: src.clone(),
                dst: Operand::Register(Reg::R10),
            });
            out.push(Instruction::Cmp {
                asm_type,
                src: Operand::Register(Reg::R10),
                dst: dst.clone(),
            });
        }

        // Idiv/Div: immediate operand → via R10
        Instruction::Idiv {
            asm_type,
            ref operand,
        } if is_imm(operand) => {
            out.push(Instruction::Mov {
                asm_type,
                src: operand.clone(),
                dst: Operand::Register(Reg::R10),
            });
            out.push(Instruction::Idiv {
                asm_type,
                operand: Operand::Register(Reg::R10),
            });
        }
        Instruction::Div {
            asm_type,
            ref operand,
        } if is_imm(operand) => {
            out.push(Instruction::Mov {
                asm_type,
                src: operand.clone(),
                dst: Operand::Register(Reg::R10),
            });
            out.push(Instruction::Div {
                asm_type,
                operand: Operand::Register(Reg::R10),
            });
        }

        // Movsx: immediate → just a regular quadword mov (sign extension of a constant is a no-op)
        Instruction::Movsx { ref src, ref dst } if is_imm(src) => {
            out.push(Instruction::Mov {
                asm_type: AsmType::Quadword,
                src: src.clone(),
                dst: dst.clone(),
            });
        }

        // Movsx: dst is memory → via R11 (movslq requires register destination)
        Instruction::Movsx { ref src, ref dst } if is_memory_operand(dst) => {
            out.push(Instruction::Movsx {
                src: src.clone(),
                dst: Operand::Register(Reg::R11),
            });
            out.push(Instruction::Mov {
                asm_type: AsmType::Quadword,
                src: Operand::Register(Reg::R11),
                dst: dst.clone(),
            });
        }

        // MovsxByte: immediate → just a regular mov
        Instruction::MovsxByte {
            asm_type,
            ref src,
            ref dst,
        } if is_imm(src) => {
            out.push(Instruction::Mov {
                asm_type,
                src: src.clone(),
                dst: dst.clone(),
            });
        }

        // MovsxByte: dst is memory → via R11 (movsbl/movsbq requires register destination)
        Instruction::MovsxByte {
            asm_type,
            ref src,
            ref dst,
        } if is_memory_operand(dst) => {
            out.push(Instruction::MovsxByte {
                asm_type,
                src: src.clone(),
                dst: Operand::Register(Reg::R11),
            });
            out.push(Instruction::Mov {
                asm_type,
                src: Operand::Register(Reg::R11),
                dst: dst.clone(),
            });
        }

        // MovZeroExtend: immediate → just a regular mov
        Instruction::MovZeroExtend { ref src, ref dst } if is_imm(src) => {
            out.push(Instruction::Mov {
                asm_type: AsmType::Longword,
                src: src.clone(),
                dst: dst.clone(),
            });
        }

        // MovZeroExtend: dst is memory → via R11 (requires register destination)
        Instruction::MovZeroExtend { ref src, ref dst } if is_memory_operand(dst) => {
            out.push(Instruction::MovZeroExtend {
                src: src.clone(),
                dst: Operand::Register(Reg::R11),
            });
            out.push(Instruction::Mov {
                asm_type: AsmType::Quadword,
                src: Operand::Register(Reg::R11),
                dst: dst.clone(),
            });
        }

        // MovZeroExtendByte: immediate → just a regular mov
        Instruction::MovZeroExtendByte {
            asm_type,
            ref src,
            ref dst,
        } if is_imm(src) => {
            out.push(Instruction::Mov {
                asm_type,
                src: src.clone(),
                dst: dst.clone(),
            });
        }

        // MovZeroExtendByte: dst is memory → via R11 (movzbl/movzbq requires register destination)
        Instruction::MovZeroExtendByte {
            asm_type,
            ref src,
            ref dst,
        } if is_memory_operand(dst) => {
            out.push(Instruction::MovZeroExtendByte {
                asm_type,
                src: src.clone(),
                dst: Operand::Register(Reg::R11),
            });
            out.push(Instruction::Mov {
                asm_type,
                src: Operand::Register(Reg::R11),
                dst: dst.clone(),
            });
        }

        // MovsxWord: immediate → just a regular mov
        Instruction::MovsxWord {
            asm_type,
            ref src,
            ref dst,
        } if is_imm(src) => {
            out.push(Instruction::Mov {
                asm_type,
                src: src.clone(),
                dst: dst.clone(),
            });
        }

        // MovsxWord: dst is memory → via R11 (movswl/movswq requires register destination)
        Instruction::MovsxWord {
            asm_type,
            ref src,
            ref dst,
        } if is_memory_operand(dst) => {
            out.push(Instruction::MovsxWord {
                asm_type,
                src: src.clone(),
                dst: Operand::Register(Reg::R11),
            });
            out.push(Instruction::Mov {
                asm_type,
                src: Operand::Register(Reg::R11),
                dst: dst.clone(),
            });
        }

        // MovZeroExtendWord: immediate → just a regular mov
        Instruction::MovZeroExtendWord {
            asm_type,
            ref src,
            ref dst,
        } if is_imm(src) => {
            out.push(Instruction::Mov {
                asm_type,
                src: src.clone(),
                dst: dst.clone(),
            });
        }

        // MovZeroExtendWord: dst is memory → via R11 (movzwl/movzwq requires register destination)
        Instruction::MovZeroExtendWord {
            asm_type,
            ref src,
            ref dst,
        } if is_memory_operand(dst) => {
            out.push(Instruction::MovZeroExtendWord {
                asm_type,
                src: src.clone(),
                dst: Operand::Register(Reg::R11),
            });
            out.push(Instruction::Mov {
                asm_type,
                src: Operand::Register(Reg::R11),
                dst: dst.clone(),
            });
        }

        // Truncate: memory,memory → via R10
        Instruction::Truncate { ref src, ref dst }
            if is_memory_operand(src) && is_memory_operand(dst) =>
        {
            out.push(Instruction::Mov {
                asm_type: AsmType::Longword,
                src: src.clone(),
                dst: Operand::Register(Reg::R10),
            });
            out.push(Instruction::Mov {
                asm_type: AsmType::Longword,
                src: Operand::Register(Reg::R10),
                dst: dst.clone(),
            });
        }

        // Truncate: memory dst → via R10
        Instruction::Truncate { ref src, ref dst } if is_memory_operand(dst) => {
            out.push(Instruction::Truncate {
                src: src.clone(),
                dst: Operand::Register(Reg::R10),
            });
            out.push(Instruction::Mov {
                asm_type: AsmType::Longword,
                src: Operand::Register(Reg::R10),
                dst: dst.clone(),
            });
        }

        // Lea: memory,memory → via R10
        Instruction::Lea { ref src, ref dst } if is_memory_operand(dst) => {
            out.push(Instruction::Lea {
                src: src.clone(),
                dst: Operand::Register(Reg::R10),
            });
            out.push(Instruction::Mov {
                asm_type: AsmType::Quadword,
                src: Operand::Register(Reg::R10),
                dst: dst.clone(),
            });
        }

        // Cvtsi2sd: dst must be XMM register. Handle all problematic cases:
        // 1. immediate src → load to R10 first
        // 2. memory dst → use XMM15 as intermediate
        // 3. both → fix both
        Instruction::Cvtsi2sd {
            asm_type,
            ref src,
            ref dst,
        } if is_imm(src) || is_memory_operand(dst) => {
            let fixed_src = if is_imm(src) {
                out.push(Instruction::Mov {
                    asm_type,
                    src: src.clone(),
                    dst: Operand::Register(Reg::R10),
                });
                Operand::Register(Reg::R10)
            } else {
                src.clone()
            };
            if is_memory_operand(dst) {
                out.push(Instruction::Cvtsi2sd {
                    asm_type,
                    src: fixed_src,
                    dst: Operand::Register(Reg::XMM15),
                });
                out.push(Instruction::Mov {
                    asm_type: AsmType::Double,
                    src: Operand::Register(Reg::XMM15),
                    dst: dst.clone(),
                });
            } else {
                out.push(Instruction::Cvtsi2sd {
                    asm_type,
                    src: fixed_src,
                    dst: dst.clone(),
                });
            }
        }

        // Cvttsd2si: memory dst → via R11
        Instruction::Cvttsd2si {
            asm_type,
            ref src,
            ref dst,
        } if is_memory_operand(dst) => {
            out.push(Instruction::Cvttsd2si {
                asm_type,
                src: src.clone(),
                dst: Operand::Register(Reg::R11),
            });
            out.push(Instruction::Mov {
                asm_type,
                src: Operand::Register(Reg::R11),
                dst: dst.clone(),
            });
        }

        // Cvtsi2ss: same fixup as Cvtsi2sd but for float
        Instruction::Cvtsi2ss {
            asm_type,
            ref src,
            ref dst,
        } if is_imm(src) || is_memory_operand(dst) => {
            let fixed_src = if is_imm(src) {
                out.push(Instruction::Mov {
                    asm_type,
                    src: src.clone(),
                    dst: Operand::Register(Reg::R10),
                });
                Operand::Register(Reg::R10)
            } else {
                src.clone()
            };
            if is_memory_operand(dst) {
                out.push(Instruction::Cvtsi2ss {
                    asm_type,
                    src: fixed_src,
                    dst: Operand::Register(Reg::XMM15),
                });
                out.push(Instruction::Mov {
                    asm_type: AsmType::Float,
                    src: Operand::Register(Reg::XMM15),
                    dst: dst.clone(),
                });
            } else {
                out.push(Instruction::Cvtsi2ss {
                    asm_type,
                    src: fixed_src,
                    dst: dst.clone(),
                });
            }
        }

        // Cvttss2si: memory dst → via R11
        Instruction::Cvttss2si {
            asm_type,
            ref src,
            ref dst,
        } if is_memory_operand(dst) => {
            out.push(Instruction::Cvttss2si {
                asm_type,
                src: src.clone(),
                dst: Operand::Register(Reg::R11),
            });
            out.push(Instruction::Mov {
                asm_type,
                src: Operand::Register(Reg::R11),
                dst: dst.clone(),
            });
        }

        // Cvtss2sd: XMM src → XMM dst. Fix memory dst → via XMM15
        Instruction::Cvtss2sd { ref src, ref dst } if is_memory_operand(dst) => {
            out.push(Instruction::Cvtss2sd {
                src: src.clone(),
                dst: Operand::Register(Reg::XMM15),
            });
            out.push(Instruction::Mov {
                asm_type: AsmType::Double,
                src: Operand::Register(Reg::XMM15),
                dst: dst.clone(),
            });
        }

        // Cvtsd2ss: XMM src → XMM dst. Fix memory dst → via XMM15
        Instruction::Cvtsd2ss { ref src, ref dst } if is_memory_operand(dst) => {
            out.push(Instruction::Cvtsd2ss {
                src: src.clone(),
                dst: Operand::Register(Reg::XMM15),
            });
            out.push(Instruction::Mov {
                asm_type: AsmType::Float,
                src: Operand::Register(Reg::XMM15),
                dst: dst.clone(),
            });
        }

        // JmpIndirect: memory operand → load via R10
        Instruction::JmpIndirect(ref op, ref targets) if is_memory_operand(op) => {
            out.push(Instruction::Mov {
                asm_type: AsmType::Quadword,
                src: op.clone(),
                dst: Operand::Register(Reg::R10),
            });
            out.push(Instruction::JmpIndirect(
                Operand::Register(Reg::R10),
                targets.clone(),
            ));
        }

        // Default: no fixup needed
        other => out.push(other),
    }
}

// ────────────────────────────────────────────
// 内部: プロローグ/エピローグ
// ────────────────────────────────────────────

/// プロローグとエピローグを命令列に挿入する。
///
/// **プロローグ**(命令列の先頭に挿入):
/// ```text
/// push %rbp
/// movq %rsp, %rbp
/// push <callee-saved>...     // 使用した callee-saved のみ
/// subq $N, %rsp              // spill スロット確保(16B アラインメント調整済み)
/// ```
///
/// **エピローグ**(各 `Ret` の前に挿入):
/// ```text
/// addq $N, %rsp
/// pop <callee-saved>...      // push の逆順
/// pop %rbp
/// ret
/// ```
///
/// アラインメント: `call` の return address (8B) + `push %rbp` (8B) = 16B で整列。
/// その後 `callee_count * 8 + alloc_size` が 16 の倍数になるよう調整する。
fn insert_prologue_epilogue(
    instructions: Vec<Instruction>,
    spill_bytes: usize,
    callee_saved_used: &[Reg],
) -> Vec<Instruction> {
    let callee_count = callee_saved_used.len();

    // アラインメント計算
    // call main の return address (8B) + pushq %rbp (8B) で 16B(0 mod 16 に戻る)。
    // その後 callee-saved push が callee_count * 8 バイト。
    // RSP を 0 mod 16 に保つには callee_count * 8 + alloc_size が 16 の倍数である必要がある。
    let callee_bytes = callee_count * 8;

    // 全命令の Stack() オペランドをスキャンし、最も深い負オフセットを取得。
    // これはスピル変数と強制スタック変数の両方を含む実際のスタック使用量を反映する。
    let min_stack_offset = scan_min_stack_offset(&instructions);
    let stack_bytes_from_scan = if min_stack_offset < 0 {
        (-min_stack_offset) as usize
    } else {
        0
    };
    let needed_stack = std::cmp::max(spill_bytes, stack_bytes_from_scan);

    let total = callee_bytes + needed_stack;
    let aligned_total = (total + 15) & !15;
    let alloc_size = aligned_total - callee_bytes;

    // ── スタックオフセット補正 ──
    // Spill 変数と強制スタック変数は -8(%rbp), -16(%rbp), ... に割り当てられるが、
    // callee-saved レジスタの push も同じ領域を使う。
    // callee_bytes 分だけ下にシフトして衝突を回避する。
    let shift = -(callee_bytes as i32);
    let instructions: Vec<Instruction> = if callee_bytes > 0 {
        instructions
            .into_iter()
            .map(|instr| shift_stack_offsets(instr, shift))
            .collect()
    } else {
        instructions
    };

    let mut result = Vec::new();

    // プロローグ
    result.push(Instruction::Push(Operand::Register(Reg::BP)));
    result.push(Instruction::Mov {
        asm_type: AsmType::Quadword,
        src: Operand::Register(Reg::SP),
        dst: Operand::Register(Reg::BP),
    });
    for &reg in callee_saved_used {
        result.push(Instruction::Push(Operand::Register(reg)));
    }
    if alloc_size > 0 {
        result.push(Instruction::AllocateStack(alloc_size));
    }

    // 命令列(Ret をエピローグに置換)
    for instr in instructions {
        if matches!(instr, Instruction::Ret) {
            // エピローグ
            if alloc_size > 0 {
                result.push(Instruction::DeallocateStack(alloc_size));
            }
            for &reg in callee_saved_used.iter().rev() {
                result.push(Instruction::Pop(Operand::Register(reg)));
            }
            result.push(Instruction::Pop(Operand::Register(Reg::BP)));
            result.push(Instruction::Ret);
        } else {
            result.push(instr);
        }
    }

    result
}

/// Stack(offset) の負オフセットを shift 分だけずらす。
/// 正オフセット(スタック渡し引数)はそのまま維持する。
fn shift_stack_op(op: Operand, shift: i32) -> Operand {
    match op {
        Operand::Stack(offset) if offset <= 0 => Operand::Stack(offset + shift),
        other => other,
    }
}

fn shift_stack_offsets(instr: Instruction, shift: i32) -> Instruction {
    match instr {
        Instruction::Mov { asm_type, src, dst } => Instruction::Mov {
            asm_type,
            src: shift_stack_op(src, shift),
            dst: shift_stack_op(dst, shift),
        },
        Instruction::Unary {
            asm_type,
            op,
            operand,
        } => Instruction::Unary {
            asm_type,
            op,
            operand: shift_stack_op(operand, shift),
        },
        Instruction::Cmp { asm_type, src, dst } => Instruction::Cmp {
            asm_type,
            src: shift_stack_op(src, shift),
            dst: shift_stack_op(dst, shift),
        },
        Instruction::SetCC { condition, operand } => Instruction::SetCC {
            condition,
            operand: shift_stack_op(operand, shift),
        },
        Instruction::Binary {
            asm_type,
            op,
            src,
            dst,
        } => Instruction::Binary {
            asm_type,
            op,
            src: shift_stack_op(src, shift),
            dst: shift_stack_op(dst, shift),
        },
        Instruction::Idiv { asm_type, operand } => Instruction::Idiv {
            asm_type,
            operand: shift_stack_op(operand, shift),
        },
        Instruction::Div { asm_type, operand } => Instruction::Div {
            asm_type,
            operand: shift_stack_op(operand, shift),
        },
        Instruction::Movsx { src, dst } => Instruction::Movsx {
            src: shift_stack_op(src, shift),
            dst: shift_stack_op(dst, shift),
        },
        Instruction::MovsxByte { asm_type, src, dst } => Instruction::MovsxByte {
            asm_type,
            src: shift_stack_op(src, shift),
            dst: shift_stack_op(dst, shift),
        },
        Instruction::MovZeroExtend { src, dst } => Instruction::MovZeroExtend {
            src: shift_stack_op(src, shift),
            dst: shift_stack_op(dst, shift),
        },
        Instruction::MovZeroExtendByte { asm_type, src, dst } => Instruction::MovZeroExtendByte {
            asm_type,
            src: shift_stack_op(src, shift),
            dst: shift_stack_op(dst, shift),
        },
        Instruction::MovsxWord { asm_type, src, dst } => Instruction::MovsxWord {
            asm_type,
            src: shift_stack_op(src, shift),
            dst: shift_stack_op(dst, shift),
        },
        Instruction::MovZeroExtendWord { asm_type, src, dst } => Instruction::MovZeroExtendWord {
            asm_type,
            src: shift_stack_op(src, shift),
            dst: shift_stack_op(dst, shift),
        },
        Instruction::Truncate { src, dst } => Instruction::Truncate {
            src: shift_stack_op(src, shift),
            dst: shift_stack_op(dst, shift),
        },
        Instruction::Push(op) => Instruction::Push(shift_stack_op(op, shift)),
        Instruction::Pop(op) => Instruction::Pop(shift_stack_op(op, shift)),
        Instruction::Cvtsi2sd { asm_type, src, dst } => Instruction::Cvtsi2sd {
            asm_type,
            src: shift_stack_op(src, shift),
            dst: shift_stack_op(dst, shift),
        },
        Instruction::Cvttsd2si { asm_type, src, dst } => Instruction::Cvttsd2si {
            asm_type,
            src: shift_stack_op(src, shift),
            dst: shift_stack_op(dst, shift),
        },
        Instruction::Cvtsi2ss { asm_type, src, dst } => Instruction::Cvtsi2ss {
            asm_type,
            src: shift_stack_op(src, shift),
            dst: shift_stack_op(dst, shift),
        },
        Instruction::Cvttss2si { asm_type, src, dst } => Instruction::Cvttss2si {
            asm_type,
            src: shift_stack_op(src, shift),
            dst: shift_stack_op(dst, shift),
        },
        Instruction::Cvtss2sd { src, dst } => Instruction::Cvtss2sd {
            src: shift_stack_op(src, shift),
            dst: shift_stack_op(dst, shift),
        },
        Instruction::Cvtsd2ss { src, dst } => Instruction::Cvtsd2ss {
            src: shift_stack_op(src, shift),
            dst: shift_stack_op(dst, shift),
        },
        Instruction::Lea { src, dst } => Instruction::Lea {
            src: shift_stack_op(src, shift),
            dst: shift_stack_op(dst, shift),
        },
        Instruction::JmpIndirect(op, targets) => {
            Instruction::JmpIndirect(shift_stack_op(op, shift), targets)
        }
        Instruction::CallIndirect(op) => Instruction::CallIndirect(shift_stack_op(op, shift)),
        instr @ (Instruction::SignExtend(_)
        | Instruction::Jmp(_)
        | Instruction::JmpCC(_, _)
        | Instruction::Label(_)
        | Instruction::AllocateStack(_)
        | Instruction::DeallocateStack(_)
        | Instruction::Call(_)
        | Instruction::Ret
        | Instruction::RawBytes(_)) => instr,
    }
}

// ────────────────────────────────────────────
// ユーティリティ
// ────────────────────────────────────────────

/// 全命令の Stack() オペランドをスキャンし、最も深い(最も負の)オフセットを返す。
/// Stack() オペランドがない場合は 0 を返す。
fn scan_min_stack_offset(instructions: &[Instruction]) -> i32 {
    let mut min_offset: i32 = 0;
    for instr in instructions {
        for_each_operand(instr, |op| {
            if let Operand::Stack(offset) = op
                && *offset < min_offset
            {
                min_offset = *offset;
            }
        });
    }
    min_offset
}

/// 命令の全オペランドに対してクロージャを適用
fn for_each_operand<F: FnMut(&Operand)>(instr: &Instruction, mut f: F) {
    match instr {
        Instruction::Mov { src, dst, .. } => {
            f(src);
            f(dst);
        }
        Instruction::Unary { operand, .. } => {
            f(operand);
        }
        Instruction::Cmp { src, dst, .. } => {
            f(src);
            f(dst);
        }
        Instruction::SetCC { operand, .. } => {
            f(operand);
        }
        Instruction::Binary { src, dst, .. } => {
            f(src);
            f(dst);
        }
        Instruction::Idiv { operand, .. } => {
            f(operand);
        }
        Instruction::Div { operand, .. } => {
            f(operand);
        }
        Instruction::Movsx { src, dst } => {
            f(src);
            f(dst);
        }
        Instruction::MovsxByte { src, dst, .. } => {
            f(src);
            f(dst);
        }
        Instruction::MovZeroExtend { src, dst } => {
            f(src);
            f(dst);
        }
        Instruction::MovZeroExtendByte { src, dst, .. } => {
            f(src);
            f(dst);
        }
        Instruction::MovsxWord { src, dst, .. } => {
            f(src);
            f(dst);
        }
        Instruction::MovZeroExtendWord { src, dst, .. } => {
            f(src);
            f(dst);
        }
        Instruction::Truncate { src, dst } => {
            f(src);
            f(dst);
        }
        Instruction::Push(op) | Instruction::Pop(op) => {
            f(op);
        }
        Instruction::Cvtsi2sd { src, dst, .. } => {
            f(src);
            f(dst);
        }
        Instruction::Cvttsd2si { src, dst, .. } => {
            f(src);
            f(dst);
        }
        Instruction::Cvtsi2ss { src, dst, .. } => {
            f(src);
            f(dst);
        }
        Instruction::Cvttss2si { src, dst, .. } => {
            f(src);
            f(dst);
        }
        Instruction::Cvtss2sd { src, dst } => {
            f(src);
            f(dst);
        }
        Instruction::Cvtsd2ss { src, dst } => {
            f(src);
            f(dst);
        }
        Instruction::Lea { src, dst } => {
            f(src);
            f(dst);
        }
        Instruction::JmpIndirect(op, _) => {
            f(op);
        }
        Instruction::CallIndirect(op) => {
            f(op);
        }
        Instruction::SignExtend(_)
        | Instruction::Jmp(_)
        | Instruction::JmpCC(_, _)
        | Instruction::Label(_)
        | Instruction::AllocateStack(_)
        | Instruction::DeallocateStack(_)
        | Instruction::Call(_)
        | Instruction::Ret
        | Instruction::RawBytes(_) => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// merge_nodes で Pseudo を HardReg にマージしたとき、
    /// 干渉グラフの隣接が対称 (adj[a]∋b ⇔ adj[b]∋a) を維持するか検証する。
    ///
    /// 再現シナリオ:
    ///   - Pseudo("x") と HardReg(DI) の間に Mov 辺(干渉辺なし)
    ///   - Pseudo("tmp") と Pseudo("x") の間に干渉辺あり
    ///   - x を DI にマージ → DI-tmp 間に干渉辺が対称に転写されること
    #[test]
    fn merge_nodes_keeps_adjacency_symmetric() {
        let mut graph = InterferenceGraph::new();

        let di = GraphNode::HardReg(Reg::DI);
        let x = GraphNode::Pseudo("x".into());
        let tmp = GraphNode::Pseudo("tmp".into());

        // ノード追加(Pseudo は add_node で初期化、HardReg は辺追加時のみ)
        graph.add_node(x.clone());
        graph.add_node(tmp.clone());
        // DI には add_node しない — 実際のビルドと同じ状況

        // 干渉辺: tmp ↔ x
        graph.add_edge(&tmp, &x);

        // 前提確認
        assert!(graph.adj.get(&tmp).unwrap().contains(&x));
        assert!(graph.adj.get(&x).unwrap().contains(&tmp));
        assert!(
            !graph.adj.contains_key(&di),
            "DI should have no adj entry before merge"
        );

        // x → DI にマージ
        merge_nodes(&mut graph, &x, &di);

        // マージ後: DI ↔ tmp が対称であること
        assert!(
            graph.adj.get(&di).is_some_and(|s| s.contains(&tmp)),
            "adj[DI] must contain tmp after merging x→DI"
        );
        assert!(
            graph.adj.get(&tmp).is_some_and(|s| s.contains(&di)),
            "adj[tmp] must contain DI after merging x→DI"
        );

        // x の旧エントリは削除されていること
        assert!(
            !graph.adj.contains_key(&x),
            "adj[x] should be removed after merge"
        );
        // tmp の旧辺 (tmp→x) は消えていること
        assert!(
            !graph.adj.get(&tmp).unwrap().contains(&x),
            "adj[tmp] should no longer contain x after merge"
        );
    }

    /// マージ先 (into) に既存の隣接がある場合も対称性を維持するか検証。
    #[test]
    fn merge_nodes_symmetric_with_existing_edges() {
        let mut graph = InterferenceGraph::new();

        let di = GraphNode::HardReg(Reg::DI);
        let x = GraphNode::Pseudo("x".into());
        let tmp = GraphNode::Pseudo("tmp".into());
        let count = GraphNode::Pseudo("count".into());

        graph.add_node(x.clone());
        graph.add_node(tmp.clone());
        graph.add_node(count.clone());

        // 干渉辺: tmp ↔ x, count ↔ x
        graph.add_edge(&tmp, &x);
        graph.add_edge(&count, &x);

        // DI に既存辺を作る (count ↔ DI)
        graph.add_edge(&count, &di);

        // x → DI にマージ
        merge_nodes(&mut graph, &x, &di);

        // DI ↔ tmp が対称
        assert!(graph.adj.get(&di).unwrap().contains(&tmp));
        assert!(graph.adj.get(&tmp).unwrap().contains(&di));

        // DI ↔ count も維持
        assert!(graph.adj.get(&di).unwrap().contains(&count));
        assert!(graph.adj.get(&count).unwrap().contains(&di));

        // self-loop なし
        assert!(!graph.adj.get(&di).unwrap().contains(&di));
    }
}