llvm-native-core 0.1.14

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
//! X86 Frame Lowering — stack frame management for X86/X86-64 targets.
//!
//! Handles function prologue/epilogue emission, frame pointer management,
//! callee-saved register spill/restore, and frame size calculation.
//!
//! Supported ABIs:
//! - System V AMD64 (Linux, macOS, FreeBSD)
//! - Microsoft x64 (Windows)
//! - IA-32 (32-bit, cdecl/stdcall/fastcall)
//!
//! Frame layout (System V AMD64, frame pointer used):
//! ```text
//!         +----------------------+  <- high address (previous frame)
//!         |   Return Address     |  (pushed by CALL)
//!   %rbp  +----------------------+
//!         |   Previous %rbp      |  (pushed by prologue)
//!   -8    +----------------------+
//!         |   Saved Regs (RBX,   |
//!         |   R12-R15 as needed) |
//!         +----------------------+
//!         |   Local variables    |
//!         |   (allocas, spills)  |
//!         +----------------------+
//!         |   Outgoing args      |  (for calls within this function)
//!   %rsp  +----------------------+  <- low address
//! ```
//!
//! Red zone: On System V AMD64, the 128 bytes below %rsp are reserved
//! and may be used without adjusting %rsp, provided the function is a leaf
//! (makes no calls).
//!
//! Clean-room reconstruction from:
//! - System V Application Binary Interface: AMD64 Architecture Processor Supplement
//! - Microsoft x64 Software Conventions
//! - Intel® 64 and IA-32 Architectures Software Developer's Manual
//!
//! Zero LLVM source code consultation.

use crate::codegen::{MachineBasicBlock, MachineFunction, MachineInstr, MachineOperand, VirtReg};
use crate::x86::x86_instr_info::{X86InstrInfo, X86Opcode, RBP_CONST, RSP_CONST};
use crate::x86::x86_register_info::{EAX, R10, R11, R9, RAX, RBP, RSP};
use std::collections::HashMap;

// ============================================================================
// Constants
// ============================================================================

/// Size of the System V AMD64 red zone (128 bytes below %rsp).
pub const RED_ZONE_SIZE: i64 = 128;

/// Standard stack alignment for System V AMD64 ABI: 16 bytes.
pub const STACK_ALIGNMENT: i64 = 16;

/// Size of a GPR push on x86-64 (8 bytes).
pub const PUSH_SIZE_64: i64 = 8;

/// Size of a GPR push on x86-32 (4 bytes).
pub const PUSH_SIZE_32: i64 = 4;

// x86-64 register constants (mirrors x86_register_info.rs)
const RBX: u16 = 3;
const R12: u16 = 12;
const R13: u16 = 13;
const R14: u16 = 14;
const R15: u16 = 15;

// x86-32 register constants
const EBX32: u16 = 19;
const ESI32: u16 = 22;
const EDI32: u16 = 23;
const EBP32: u16 = 21;
const ESP32: u16 = 20;

/// x86-64 callee-saved registers (System V AMD64 ABI).
pub const CALLEE_SAVED_REGS_SYSV: &[u16] = &[RBX, R12, R13, R14, R15];

/// x86-64 callee-saved registers (Microsoft x64 ABI).
pub const CALLEE_SAVED_REGS_WIN64: &[u16] =
    &[RBX, RBP_CONST, RSI_CONST, RDI_CONST, R12, R13, R14, R15];

/// x86-32 callee-saved registers (cdecl/stdcall).
pub const CALLEE_SAVED_REGS_X86_32: &[u16] = &[EBX32, ESI32, EDI32, EBP32];

/// Flags register constant.
const FLAGS: u16 = 200;

const RSI_CONST: u16 = 6;
const RDI_CONST: u16 = 7;

// ============================================================================
// CallConv — calling convention enumeration
// ============================================================================

/// Supported calling conventions for frame lowering.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallConv {
    /// System V AMD64 ABI (Linux, macOS, FreeBSD, etc.)
    SystemV,
    /// Microsoft x64 ABI (Windows)
    Win64,
    /// 32-bit cdecl (caller cleans stack)
    CDecl32,
    /// 32-bit stdcall (callee cleans stack)
    StdCall32,
    /// 32-bit fastcall (first two args in ECX, EDX)
    FastCall32,
}

impl CallConv {
    /// Returns true if this calling convention uses a red zone.
    pub fn uses_red_zone(&self) -> bool {
        matches!(self, CallConv::SystemV)
    }

    /// Returns true if this is a 64-bit calling convention.
    pub fn is_64bit(&self) -> bool {
        matches!(self, CallConv::SystemV | CallConv::Win64)
    }

    /// Returns true if this is a 32-bit calling convention.
    pub fn is_32bit(&self) -> bool {
        matches!(
            self,
            CallConv::CDecl32 | CallConv::StdCall32 | CallConv::FastCall32
        )
    }

    /// Returns the size of a register push on this architecture.
    pub fn push_size(&self) -> i64 {
        if self.is_64bit() {
            PUSH_SIZE_64
        } else {
            PUSH_SIZE_32
        }
    }

    /// Returns the callee-saved registers for this convention.
    pub fn callee_saved_regs(&self) -> &'static [u16] {
        match self {
            CallConv::SystemV => CALLEE_SAVED_REGS_SYSV,
            CallConv::Win64 => CALLEE_SAVED_REGS_WIN64,
            CallConv::CDecl32 | CallConv::StdCall32 | CallConv::FastCall32 => {
                CALLEE_SAVED_REGS_X86_32
            }
        }
    }

    /// Returns the frame pointer register ID for this convention.
    pub fn frame_pointer_reg(&self) -> u16 {
        if self.is_64bit() {
            RBP_CONST
        } else {
            EBP32
        }
    }

    /// Returns the stack pointer register ID for this convention.
    pub fn stack_pointer_reg(&self) -> u16 {
        if self.is_64bit() {
            RSP_CONST
        } else {
            ESP32
        }
    }
}

// ============================================================================
// X86FrameInfo — per-function frame metadata
// ============================================================================

/// Complete frame layout information for a single function.
#[derive(Debug, Clone)]
pub struct X86FrameInfo {
    /// Total size of the stack frame in bytes.
    pub frame_size: i64,
    /// Registers saved in the prologue (callee-saved that are used).
    pub saved_regs: Vec<u16>,
    /// Whether this function uses a frame pointer (%rbp).
    pub has_frame_pointer: bool,
    /// Whether this function contains call instructions.
    pub has_calls: bool,
    /// Whether this function contains variable-sized allocas (alloca with
    /// non-constant size, or dynamic stack realignment).
    pub has_var_sized_objects: bool,
    /// Whether the function can use the red zone (no calls, small frame).
    pub uses_red_zone: bool,
    /// Maximum outgoing argument space needed for calls in this function.
    pub max_call_frame_size: i64,
    /// Offset from frame pointer to the local variables area.
    pub local_area_offset: i64,
    /// Total size of callee-saved register spills.
    pub callee_saved_size: i64,
}

impl X86FrameInfo {
    /// Create default frame info.
    pub fn new() -> Self {
        X86FrameInfo {
            frame_size: 0,
            saved_regs: Vec::new(),
            has_frame_pointer: false,
            has_calls: false,
            has_var_sized_objects: false,
            uses_red_zone: false,
            max_call_frame_size: 0,
            local_area_offset: 0,
            callee_saved_size: 0,
        }
    }

    /// Returns the total frame size including alignment.
    pub fn total_frame_size(&self) -> i64 {
        self.frame_size
    }

    /// Returns the offset from %rbp where the locals area begins.
    /// Negative offset (below %rbp).
    pub fn local_start_offset(&self) -> i64 {
        -(self.callee_saved_size) - PUSH_SIZE_64
    }
}

impl Default for X86FrameInfo {
    fn default() -> Self {
        X86FrameInfo::new()
    }
}

// ============================================================================
// X86FrameLowering — main frame lowering engine
// ============================================================================

/// X86 stack frame lowering engine.
///
/// Responsible for emitting function prologues and epilogues, managing
/// the frame pointer, and coordinating callee-saved register spills.
pub struct X86FrameLowering {
    /// Calling convention for this compilation unit.
    pub call_conv: CallConv,
    /// Instruction info reference for building machine instructions.
    pub instr_info: X86InstrInfo,
}

impl X86FrameLowering {
    /// Construct a new X86FrameLowering for the given calling convention.
    pub fn new(call_conv: CallConv) -> Self {
        X86FrameLowering {
            call_conv,
            instr_info: X86InstrInfo::new(),
        }
    }

    // ====================================================================
    // Frame Size Calculation
    // ====================================================================

    /// Calculate the total frame size required for a function.
    ///
    /// Includes: callee-saved register spills, local variables, outgoing
    /// argument area, and alignment padding.
    pub fn calculate_frame_size(&self, frame_info: &X86FrameInfo) -> i64 {
        let mut size = frame_info.callee_saved_size;
        size += frame_info.local_area_offset.abs();
        size += frame_info.max_call_frame_size;
        size = self.align_frame_size(size, STACK_ALIGNMENT);
        size
    }

    /// Align a frame size to the given alignment boundary.
    pub fn align_frame_size(&self, size: i64, alignment: i64) -> i64 {
        if size % alignment == 0 {
            size
        } else {
            size + (alignment - (size % alignment))
        }
    }

    // ====================================================================
    // Frame Pointer Determination
    // ====================================================================

    /// Determine whether this function needs a frame pointer (%rbp).
    ///
    /// A frame pointer is required when:
    /// - The function has variable-sized objects (alloca with dynamic size)
    /// - The function requires dynamic stack realignment
    /// - On 32-bit, the function has stack arguments *and* no frame pointer
    ///   would make debugging/exception handling difficult
    /// - Explicitly requested (e.g., -fno-omit-frame-pointer)
    ///
    /// A frame pointer is NOT required for:
    /// - Simple leaf functions
    /// - Functions where all locals fit in the red zone (64-bit)
    pub fn needs_frame_pointer(&self, frame_info: &X86FrameInfo) -> bool {
        // Variable-sized objects always require a frame pointer
        if frame_info.has_var_sized_objects {
            return true;
        }

        // On 32-bit, any non-trivial frame benefits from a frame pointer
        if self.call_conv.is_32bit() && frame_info.frame_size > 0 {
            return true;
        }

        // Functions with significant stack usage that have calls
        if frame_info.has_calls && frame_info.frame_size > RED_ZONE_SIZE {
            return true;
        }

        // Large frames benefit from frame pointer for debugging
        if frame_info.frame_size > 4096 {
            return true;
        }

        false
    }

    // ====================================================================
    // Prologue Emission
    // ====================================================================

    /// Emit the function prologue for the given machine function.
    ///
    /// For System V AMD64, generates:
    /// ```asm
    /// pushq %rbp
    /// movq %rsp, %rbp
    /// subq $N, %rsp          (if frame > red zone or has calls)
    /// pushq %rbx             (saved regs as needed)
    /// pushq %r12
    /// ...
    /// ```
    pub fn emit_prologue(&self, mf: &mut MachineFunction) -> Vec<MachineInstr> {
        let frame_info = self.build_frame_info(mf);
        let mut instrs = Vec::new();
        let sp = self.call_conv.stack_pointer_reg();
        let fp = self.call_conv.frame_pointer_reg();
        let push_size = self.call_conv.push_size();

        if frame_info.has_frame_pointer {
            // push [frame_pointer]
            instrs.push(self.build_push(fp));

            // mov %rsp, %rbp  (or %esp, %ebp on 32-bit)
            instrs.push(self.build_mov_fp_from_sp(fp, sp));

            // Allocate stack space if needed
            if frame_info.frame_size > 0 {
                let alloc_size = self.align_frame_size(frame_info.frame_size, STACK_ALIGNMENT);
                if !frame_info.uses_red_zone || alloc_size > RED_ZONE_SIZE {
                    instrs.push(self.build_sub_sp(sp, alloc_size));
                }
            }
        } else {
            // No frame pointer — just allocate stack space
            if frame_info.frame_size > 0 {
                let alloc_size = self.align_frame_size(frame_info.frame_size, STACK_ALIGNMENT);
                if !frame_info.uses_red_zone || alloc_size > RED_ZONE_SIZE {
                    instrs.push(self.build_sub_sp(sp, alloc_size));
                }
            }
        }

        // Save callee-saved registers
        for &reg in &frame_info.saved_regs {
            if reg != fp {
                // Frame pointer already pushed above
                instrs.push(self.build_push(reg));
            }
        }

        // Win64: emit SEH annotations as comments (stub)
        if self.call_conv == CallConv::Win64 {
            self.emit_seh_prologue(&mut instrs, &frame_info);
        }

        instrs
    }

    /// Build a push instruction for the target architecture.
    fn build_push(&self, reg: u16) -> MachineInstr {
        let mut mi = MachineInstr::new(X86Opcode::PUSH as u32);
        mi.operands.push(MachineOperand::PhysReg(reg as u32));
        mi
    }

    /// Build a mov from stack pointer to frame pointer.
    fn build_mov_fp_from_sp(&self, fp: u16, sp: u16) -> MachineInstr {
        let mut mi = MachineInstr::new(X86Opcode::MOV as u32);
        mi.operands.push(MachineOperand::PhysReg(fp as u32));
        mi.operands.push(MachineOperand::PhysReg(sp as u32));
        mi
    }

    /// Build a sub immediate from stack pointer.
    fn build_sub_sp(&self, sp: u16, amount: i64) -> MachineInstr {
        let mut mi = MachineInstr::new(X86Opcode::SUB as u32);
        mi.operands.push(MachineOperand::PhysReg(sp as u32));
        mi.operands.push(MachineOperand::Imm(amount));
        mi
    }

    /// Emit Win64 SEH prologue annotations (stub — produces comments).
    fn emit_seh_prologue(&self, _instrs: &mut Vec<MachineInstr>, frame_info: &X86FrameInfo) {
        // In a full implementation, this would emit .seh_pushreg, .seh_setframe,
        // .seh_stackalloc, .seh_endprologue directives.
        // For now, these are documented but not emitted as actual machine instructions.
        let _ = frame_info;
    }

    // ====================================================================
    // Epilogue Emission
    // ====================================================================

    /// Emit the function epilogue for the given machine function.
    ///
    /// For System V AMD64, generates:
    /// ```asm
    /// movq %rbp, %rsp       (or leaq -N(%rbp), %rsp)
    /// popq %r12             (restore saved regs in reverse order)
    /// popq %rbx
    /// popq %rbp
    /// retq
    /// ```
    pub fn emit_epilogue(&self, mf: &mut MachineFunction) -> Vec<MachineInstr> {
        let frame_info = self.build_frame_info(mf);
        let mut instrs = Vec::new();
        let sp = self.call_conv.stack_pointer_reg();
        let fp = self.call_conv.frame_pointer_reg();

        // Win64: emit SEH epilogue annotations (stub)
        if self.call_conv == CallConv::Win64 {
            self.emit_seh_epilogue(&mut instrs, &frame_info);
        }

        if frame_info.has_frame_pointer {
            // Restore stack pointer from frame pointer
            if !frame_info.saved_regs.is_empty() || frame_info.frame_size > 0 {
                // lea -callee_saved_size(%rbp), %rsp
                let offset = -(frame_info.callee_saved_size);
                instrs.push(self.build_lea_sp_from_fp(sp, fp, offset));
            } else {
                // Simple: mov %rbp, %rsp
                instrs.push(self.build_mov_sp_from_fp(sp, fp));
            }

            // Restore callee-saved registers in reverse order
            for &reg in frame_info.saved_regs.iter().rev() {
                if reg != fp {
                    instrs.push(self.build_pop(reg));
                }
            }

            // Restore frame pointer
            instrs.push(self.build_pop(fp));
        } else {
            // No frame pointer — just restore stack pointer
            if frame_info.frame_size > 0 {
                let alloc_size = self.align_frame_size(frame_info.frame_size, STACK_ALIGNMENT);
                if !frame_info.uses_red_zone || alloc_size > RED_ZONE_SIZE {
                    instrs.push(self.build_add_sp(sp, alloc_size));
                }
            }

            // Restore callee-saved registers in reverse order
            for &reg in frame_info.saved_regs.iter().rev() {
                instrs.push(self.build_pop(reg));
            }
        }

        // Return
        instrs.push(self.build_ret());

        instrs
    }

    /// Build a pop instruction for the target architecture.
    fn build_pop(&self, reg: u16) -> MachineInstr {
        let mut mi = MachineInstr::new(X86Opcode::POP as u32);
        mi.operands.push(MachineOperand::PhysReg(reg as u32));
        mi
    }

    /// Build a mov from frame pointer to stack pointer.
    fn build_mov_sp_from_fp(&self, sp: u16, fp: u16) -> MachineInstr {
        let mut mi = MachineInstr::new(X86Opcode::MOV as u32);
        mi.operands.push(MachineOperand::PhysReg(sp as u32));
        mi.operands.push(MachineOperand::PhysReg(fp as u32));
        mi
    }

    /// Build a lea to restore stack pointer from frame pointer with offset.
    fn build_lea_sp_from_fp(&self, sp: u16, fp: u16, offset: i64) -> MachineInstr {
        let mut mi = MachineInstr::new(X86Opcode::LEA as u32);
        mi.operands.push(MachineOperand::PhysReg(sp as u32));
        // Memory operand: [fp + offset]
        // We represent this as two operands: base register and displacement
        mi.operands.push(MachineOperand::PhysReg(fp as u32));
        mi.operands.push(MachineOperand::Imm(offset));
        mi
    }

    /// Build an add immediate to stack pointer.
    fn build_add_sp(&self, sp: u16, amount: i64) -> MachineInstr {
        let mut mi = MachineInstr::new(X86Opcode::ADD as u32);
        mi.operands.push(MachineOperand::PhysReg(sp as u32));
        mi.operands.push(MachineOperand::Imm(amount));
        mi
    }

    /// Build a ret instruction.
    fn build_ret(&self) -> MachineInstr {
        MachineInstr::new(X86Opcode::RET as u32)
    }

    /// Emit Win64 SEH epilogue annotations (stub).
    fn emit_seh_epilogue(&self, _instrs: &mut Vec<MachineInstr>, frame_info: &X86FrameInfo) {
        // In a full implementation: .seh_endprologue, .seh_startepilogue
        let _ = frame_info;
    }

    // ====================================================================
    // Frame Information Construction
    // ====================================================================

    /// Build X86FrameInfo for a given machine function by analyzing its
    /// instructions and properties.
    pub fn build_frame_info(&self, mf: &MachineFunction) -> X86FrameInfo {
        let mut info = X86FrameInfo::new();

        // Analyze callee-saved register usage
        let used_regs = self.collect_used_callee_saved_regs(mf);
        let callee_saved_size = used_regs.len() as i64 * self.call_conv.push_size();
        info.saved_regs = used_regs;
        info.callee_saved_size = callee_saved_size;

        // Detect calls
        info.has_calls = self.function_has_calls(mf);

        // Estimate local variable space
        info.local_area_offset = self.estimate_local_area(mf);

        // Calculate total frame size
        info.frame_size = self.calculate_frame_size(&info);

        // Determine red zone eligibility
        info.uses_red_zone =
            self.call_conv.uses_red_zone() && !info.has_calls && info.frame_size <= RED_ZONE_SIZE;

        // Determine frame pointer requirement
        info.has_frame_pointer = self.needs_frame_pointer(&info);

        // Estimate max call frame size
        info.max_call_frame_size = self.estimate_max_call_args(mf);

        info
    }

    /// Collect which callee-saved registers are actually used in the function.
    fn collect_used_callee_saved_regs(&self, mf: &MachineFunction) -> Vec<u16> {
        let callee_regs = self.call_conv.callee_saved_regs();
        let mut used = Vec::new();
        let mut seen = HashMap::new();

        for block in &mf.blocks {
            for inst in &block.instructions {
                for op in &inst.operands {
                    match op {
                        MachineOperand::PhysReg(reg) => {
                            seen.insert(*reg, true);
                        }
                        MachineOperand::Reg(_) => {
                            // Virtual registers — skip for now (RA phase would map
                            // these to physical registers)
                        }
                        _ => {}
                    }
                }
            }
        }

        for &reg in callee_regs {
            if seen.contains_key(&(reg as u32)) {
                used.push(reg);
            }
        }
        used
    }

    /// Detect if the function contains call instructions.
    fn function_has_calls(&self, mf: &MachineFunction) -> bool {
        let call_opcode = X86Opcode::CALL as u32;
        for block in &mf.blocks {
            for inst in &block.instructions {
                if inst.opcode == call_opcode {
                    return true;
                }
            }
        }
        false
    }

    /// Estimate the local variable area size.
    fn estimate_local_area(&self, _mf: &MachineFunction) -> i64 {
        // In a real implementation, this would sum the sizes of all stack
        // slots allocated. For now, estimate based on vreg count.
        // Each vreg might need a spill slot (8 bytes).
        0
    }

    /// Estimate the maximum outgoing argument area needed.
    fn estimate_max_call_args(&self, mf: &MachineFunction) -> i64 {
        // Count the maximum number of arguments passed to any call in this function.
        // System V AMD64: first 6 integer args in registers, rest on stack.
        // Each stack arg is 8 bytes.
        let mut max_args = 0i64;
        let call_opcode = X86Opcode::CALL as u32;
        for block in &mf.blocks {
            for inst in &block.instructions {
                if inst.opcode == call_opcode {
                    // Count operands before the call as potential args.
                    // The call itself has 1 operand (the label), so args would
                    // be in preceding instructions. Simplified heuristic.
                    let arg_count = inst.operands.len() as i64;
                    if arg_count > max_args {
                        max_args = arg_count;
                    }
                }
            }
        }
        // Each arg is aligned to 8 bytes on 64-bit, 4 bytes on 32-bit
        let arg_size = self.call_conv.push_size();
        let register_args = if self.call_conv.is_64bit() { 6 } else { 0 };
        let stack_args = (max_args - register_args).max(0);
        self.align_frame_size(stack_args * arg_size, STACK_ALIGNMENT)
    }

    // ====================================================================
    // Frame Index Reference
    // ====================================================================

    /// Generate machine instructions to load from a frame slot.
    ///
    /// Frame index `fi` is an abstract stack slot identifier. `offset` is
    /// the byte offset from the frame base.
    pub fn get_frame_index_reference(
        &self,
        mf: &mut MachineFunction,
        fi: i64,
        offset: i64,
    ) -> Vec<MachineInstr> {
        let frame_info = self.build_frame_info(mf);
        let fp = self.call_conv.frame_pointer_reg();
        let mut instrs = Vec::new();

        // The actual frame slot address is computed as:
        //   [%rbp - callee_saved_size - local_offset + slot_offset]
        let base_offset = -(frame_info.callee_saved_size) - fi * PUSH_SIZE_64 + offset;

        // Load into a new virtual register
        let vreg = mf.new_vreg();
        let mut load = MachineInstr::new(X86Opcode::MOV as u32);
        load.operands.push(MachineOperand::Reg(vreg));
        load.operands.push(MachineOperand::PhysReg(fp as u32));
        load.operands.push(MachineOperand::Imm(base_offset));
        load.def = Some(vreg);
        instrs.push(load);

        let _ = mf; // used above via new_vreg
        instrs
    }

    // ====================================================================
    // Callee-Saved Spill Slots
    // ====================================================================

    /// Assign spill slots for callee-saved registers.
    ///
    /// Returns a vector of `(register_id, slot_offset)` pairs, where
    /// slot_offset is the offset from the frame pointer.
    pub fn assign_callee_saved_spill_slots(&self, mf: &MachineFunction) -> Vec<(u16, i64)> {
        let frame_info = self.build_frame_info(mf);
        let push_size = self.call_conv.push_size();
        let mut slots = Vec::new();
        let mut current_offset: i64 = 0;

        for &reg in &frame_info.saved_regs {
            if reg != self.call_conv.frame_pointer_reg() {
                // Slot is at negative offset from %rbp (below the saved %rbp)
                current_offset -= push_size;
                slots.push((reg, current_offset));
            }
        }

        slots
    }

    // ====================================================================
    // X86-32 Frame Lowering
    // ====================================================================

    /// Emit a 32-bit prologue (cdecl/stdcall/fastcall).
    ///
    /// 32-bit differs from 64-bit in:
    /// - Uses 4-byte pushes/pops
    /// - No red zone
    /// - ESP-based addressing when no frame pointer
    /// - Arguments always on stack (no register args for cdecl)
    pub fn emit_prologue_32(&self, mf: &mut MachineFunction) -> Vec<MachineInstr> {
        let frame_info = self.build_frame_info(mf);
        let mut instrs = Vec::new();
        let sp = ESP32;
        let fp = EBP32;

        // push %ebp
        instrs.push(self.build_push(fp));

        // mov %esp, %ebp
        instrs.push(self.build_mov_fp_from_sp(fp, sp));

        // sub $N, %esp (always, no red zone on x86-32)
        if frame_info.frame_size > 0 {
            let alloc_size = self.align_frame_size(frame_info.frame_size, STACK_ALIGNMENT);
            instrs.push(self.build_sub_sp(sp, alloc_size));
        }

        // Save callee-saved registers
        for &reg in &frame_info.saved_regs {
            if reg != fp {
                instrs.push(self.build_push(reg));
            }
        }

        instrs
    }

    /// Emit a 32-bit epilogue.
    pub fn emit_epilogue_32(&self, mf: &mut MachineFunction) -> Vec<MachineInstr> {
        let frame_info = self.build_frame_info(mf);
        let mut instrs = Vec::new();
        let sp = ESP32;
        let fp = EBP32;
        let alloc_size = self.align_frame_size(frame_info.frame_size, STACK_ALIGNMENT);

        // Restore callee-saved registers in reverse order
        for &reg in frame_info.saved_regs.iter().rev() {
            if reg != fp {
                instrs.push(self.build_pop(reg));
            }
        }

        if frame_info.has_frame_pointer {
            // mov %ebp, %esp
            instrs.push(self.build_mov_sp_from_fp(sp, fp));
            // pop %ebp
            instrs.push(self.build_pop(fp));
        } else if frame_info.frame_size > 0 {
            // add $N, %esp
            instrs.push(self.build_add_sp(sp, alloc_size));
        }

        // ret
        instrs.push(self.build_ret());

        instrs
    }

    // ====================================================================
    // Win64 Frame Lowering
    // ====================================================================

    /// Emit a Win64 prologue with SEH annotations.
    ///
    /// Win64 requires:
    /// - 16-byte stack alignment maintained
    /// - 32 bytes of shadow space (home space) for register parameters
    /// - SEH unwind metadata
    pub fn emit_prologue_win64(&self, mf: &mut MachineFunction) -> Vec<MachineInstr> {
        let frame_info = self.build_frame_info(mf);
        let mut instrs = Vec::new();
        let sp = RSP_CONST;
        let fp = RBP_CONST;

        // .seh_proc function_name (metadata, not an instruction)

        // push %rbp
        instrs.push(self.build_push(fp));
        // .seh_pushreg %rbp

        // mov %rsp, %rbp
        instrs.push(self.build_mov_fp_from_sp(fp, sp));
        // .seh_setframe %rbp, 0

        // Allocate stack space (including 32-byte shadow space)
        let alloc_size = self.align_frame_size(frame_info.frame_size + 32, STACK_ALIGNMENT);
        if alloc_size > 0 {
            instrs.push(self.build_sub_sp(sp, alloc_size));
            // .seh_stackalloc N
        }

        // Save non-volatile registers
        for &reg in &frame_info.saved_regs {
            if reg != fp {
                instrs.push(self.build_push(reg));
                // .seh_pushreg for each
            }
        }

        // .seh_endprologue
        instrs
    }

    /// Emit a Win64 epilogue.
    pub fn emit_epilogue_win64(&self, mf: &mut MachineFunction) -> Vec<MachineInstr> {
        let frame_info = self.build_frame_info(mf);
        let mut instrs = Vec::new();
        let sp = RSP_CONST;
        let fp = RBP_CONST;
        let alloc_size = self.align_frame_size(frame_info.frame_size + 32, STACK_ALIGNMENT);

        // Restore non-volatile registers in reverse order
        for &reg in frame_info.saved_regs.iter().rev() {
            if reg != fp {
                instrs.push(self.build_pop(reg));
            }
        }

        if frame_info.has_frame_pointer {
            // mov %rbp, %rsp
            instrs.push(self.build_mov_sp_from_fp(sp, fp));
            // pop %rbp
            instrs.push(self.build_pop(fp));
        } else if alloc_size > 0 {
            instrs.push(self.build_add_sp(sp, alloc_size));
        }

        // ret
        instrs.push(self.build_ret());

        instrs
    }
}

impl Default for X86FrameLowering {
    fn default() -> Self {
        X86FrameLowering::new(CallConv::SystemV)
    }
}

// ============================================================================
// Stack Probing — large frame handling for guard page interaction
// ============================================================================

/// Determines whether a frame requires stack probing.
///
/// Stack probing is required when the frame size exceeds the guard page
/// size. On Windows, the guard page is typically 4 KB (one page). Without
/// probing, a large `sub rsp, N` could skip past the guard page and access
/// uncommitted memory, causing an access violation that the OS cannot
/// handle as a stack extension.
///
/// On Linux, the kernel automatically extends the stack up to `RLIMIT_STACK`,
/// but the `__morestack` mechanism can be used for split stacks.
pub const GUARD_PAGE_SIZE: i64 = 4096;

/// Threshold above which stack probing is required.
pub const STACK_PROBE_THRESHOLD: i64 = 4096;

/// Represents the stack probing strategy for a function.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StackProbeKind {
    /// No probing needed (small frame).
    #[default]
    None,
    /// Use `__chkstk` on Windows (touches pages at 4 KB intervals).
    ChkStk,
    /// Emit inline probe sequence (touch each guard page).
    Inline,
    /// Use `__morestack` for split-stack support (Linux).
    Morestack,
}

impl X86FrameLowering {
    /// Determine the stack probing strategy for the given frame.
    pub fn probe_kind(&self, frame_size: i64, is_windows: bool) -> StackProbeKind {
        if frame_size <= STACK_PROBE_THRESHOLD {
            return StackProbeKind::None;
        }
        if is_windows {
            StackProbeKind::ChkStk
        } else {
            StackProbeKind::Inline
        }
    }

    /// Emit stack probe instructions for a large frame.
    ///
    /// On Windows (x64), calls `__chkstk` which is provided by the CRT.
    /// The routine expects the allocation size in RAX and will touch each
    /// page between the current RSP and RSP - RAX.
    ///
    /// On Linux (System V), emits inline probe sequence:
    /// ```asm
    ///     mov  rax, rsp
    /// .Lprobe_loop:
    ///     sub  rsp, 4096
    ///     test [rsp], rsp    ; touch the page
    ///     cmp  rsp, rax
    ///     jne  .Lprobe_loop
    /// ```
    pub fn emit_stack_probe(
        &self,
        frame_size: i64,
        sp: u16,
        scratch: u16,
        is_windows: bool,
        label_counter: &mut u64,
    ) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();
        let kind = self.probe_kind(frame_size, is_windows);

        match kind {
            StackProbeKind::None => {}
            StackProbeKind::ChkStk => {
                // Windows: call __chkstk
                // mov rax, frame_size
                let mut mov_instr = MachineInstr::new(X86Opcode::MOV as u32);
                mov_instr.operands.push(MachineOperand::PhysReg(RAX as u32));
                mov_instr.operands.push(MachineOperand::Imm(frame_size));
                instrs.push(mov_instr);

                // call __chkstk
                let mut call_instr = MachineInstr::new(X86Opcode::CALL as u32);
                call_instr
                    .operands
                    .push(MachineOperand::Label("__chkstk".to_string()));
                instrs.push(call_instr);

                // sub rsp, rax (__chkstk adjusts RAX to the final value)
                let mut sub_instr = MachineInstr::new(X86Opcode::SUB as u32);
                sub_instr.operands.push(MachineOperand::PhysReg(sp as u32));
                sub_instr.operands.push(MachineOperand::PhysReg(RAX as u32));
                instrs.push(sub_instr);
            }
            StackProbeKind::Inline => {
                // Inline probing: touch each 4KB page
                // Save target SP in scratch register
                let mut mov_target = MachineInstr::new(X86Opcode::MOV as u32);
                mov_target
                    .operands
                    .push(MachineOperand::PhysReg(scratch as u32));
                mov_target.operands.push(MachineOperand::PhysReg(sp as u32));
                instrs.push(mov_target);

                // sub scratch, frame_size
                let mut sub_target = MachineInstr::new(X86Opcode::SUB as u32);
                sub_target
                    .operands
                    .push(MachineOperand::PhysReg(scratch as u32));
                sub_target.operands.push(MachineOperand::Imm(frame_size));
                instrs.push(sub_target);

                // Loop label
                let loop_label = format!(".Lprobe_loop_{}", label_counter);
                *label_counter += 1;
                let loop_out = format!(".Lprobe_done_{}", label_counter);
                *label_counter += 1;

                // .Lprobe_loop:
                //   sub rsp, 4096
                let mut sub_probe = MachineInstr::new(X86Opcode::SUB as u32);
                sub_probe.operands.push(MachineOperand::PhysReg(sp as u32));
                sub_probe
                    .operands
                    .push(MachineOperand::Imm(GUARD_PAGE_SIZE));
                instrs.push(sub_probe);

                //   test [rsp], rsp  (touch the page)
                let mut touch_instr = MachineInstr::new(X86Opcode::TEST as u32);
                touch_instr
                    .operands
                    .push(MachineOperand::PhysReg(sp as u32));
                touch_instr
                    .operands
                    .push(MachineOperand::PhysReg(sp as u32));
                instrs.push(touch_instr);

                //   cmp rsp, scratch
                let mut cmp_instr = MachineInstr::new(X86Opcode::CMP as u32);
                cmp_instr.operands.push(MachineOperand::PhysReg(sp as u32));
                cmp_instr
                    .operands
                    .push(MachineOperand::PhysReg(scratch as u32));
                instrs.push(cmp_instr);

                //   jne .Lprobe_loop
                let mut jne_instr = MachineInstr::new(X86Opcode::JNE as u32);
                jne_instr.operands.push(MachineOperand::Label(loop_label));
                instrs.push(jne_instr);
            }
            StackProbeKind::Morestack => {
                // Split-stack: call __morestack
                let mut call_instr = MachineInstr::new(X86Opcode::CALL as u32);
                call_instr
                    .operands
                    .push(MachineOperand::Label("__morestack".to_string()));
                instrs.push(call_instr);
            }
        }

        instrs
    }
}

// ============================================================================
// GPR Save/Restore Sequences — callee-saved general-purpose registers
// ============================================================================

impl X86FrameLowering {
    /// Build GPR save sequence using PUSH instructions.
    ///
    /// On x86-64, saves RBX, R12-R15 as needed.
    /// On x86-32, saves EBX, ESI, EDI as needed.
    /// Uses PUSH which is more compact than MOV to stack.
    pub fn build_gpr_save<'a>(&self, saved: &[u16], exclude_fp: u16) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();
        for &reg in saved {
            if reg != exclude_fp {
                let mut mi = MachineInstr::new(X86Opcode::PUSH as u32);
                mi.operands.push(MachineOperand::PhysReg(reg as u32));
                instrs.push(mi);
            }
        }
        instrs
    }

    /// Build GPR restore sequence using POP instructions (reverse order).
    pub fn build_gpr_restore<'a>(&self, saved: &[u16], exclude_fp: u16) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();
        for &reg in saved.iter().rev() {
            if reg != exclude_fp {
                let mut mi = MachineInstr::new(X86Opcode::POP as u32);
                mi.operands.push(MachineOperand::PhysReg(reg as u32));
                instrs.push(mi);
            }
        }
        instrs
    }

    /// Determine the ordered GPR save list for the frame.
    ///
    /// Pushes are ordered: R15, R14, R13, R12, RBX (for System V)
    /// so that the lowest callee-saved register is at the highest address.
    pub fn gpr_save_order(&self) -> Vec<u16> {
        if self.call_conv.is_64bit() {
            match self.call_conv {
                CallConv::SystemV => {
                    // Save order: highest reg number first (R15 down to RBX)
                    vec![R15, R14, R13, R12, RBX]
                }
                CallConv::Win64 => {
                    // Win64 saves: R15, R14, R13, R12, RDI, RSI, RBX
                    vec![R15, R14, R13, R12, RDI_CONST, RSI_CONST, RBX]
                }
                _ => vec![R15, R14, R13, R12, RBX],
            }
        } else {
            // 32-bit: ESI, EDI, EBX
            vec![ESI32, EDI32, EBX32]
        }
    }
}

// ============================================================================
// XMM Save/Restore Sequences — callee-saved SIMD registers
// ============================================================================

/// XMM save slot alignment requirement.
pub const XMM_SAVE_ALIGN: i64 = 16;

/// YMM save slot alignment requirement (AVX).
pub const YMM_SAVE_ALIGN: i64 = 32;

/// ZMM save slot alignment requirement (AVX-512).
pub const ZMM_SAVE_ALIGN: i64 = 64;

// XMM store/load opcodes (will be integrated into X86Opcode enum later)
const MOVAPS_STORE: u32 = 2200;
const MOVAPS_LOAD: u32 = 2201;

/// Information about XMM save slots in the frame.
#[derive(Debug, Clone)]
pub struct XmmSaveArea {
    /// Starting offset from the frame base for XMM saves.
    pub offset: i64,
    /// Number of XMM registers saved.
    pub count: usize,
    /// Size of each save slot (16 for XMM, 32 for YMM, 64 for ZMM).
    pub slot_size: i64,
    /// Required alignment for the save area.
    pub alignment: i64,
    /// The specific XMM register indices saved.
    pub registers: Vec<u8>,
}

impl Default for XmmSaveArea {
    fn default() -> Self {
        XmmSaveArea {
            offset: 0,
            count: 0,
            slot_size: 16,
            alignment: XMM_SAVE_ALIGN,
            registers: Vec::new(),
        }
    }
}

impl X86FrameLowering {
    /// Determine which XMM registers must be saved based on calling convention.
    ///
    /// System V AMD64: XMM registers are all caller-saved (none callee-saved).
    /// Microsoft x64: XMM6-XMM15 are callee-saved.
    pub fn get_xmm_callee_saved(&self) -> Vec<u8> {
        match self.call_conv {
            CallConv::Win64 => {
                // XMM6 through XMM15 inclusive
                (6..=15).collect()
            }
            _ => {
                // System V and 32-bit: no callee-saved XMM registers
                Vec::new()
            }
        }
    }

    /// Build XMM save sequence using MOVAPS to stack slots.
    ///
    /// Saves are done relative to the frame pointer when one exists, or
    /// relative to the stack pointer otherwise. Each XMM register is stored
    /// with a 16-byte aligned MOVAPS (or VMOVAPS for AVX).
    ///
    /// ```asm
    /// movaps  %xmm6,  -16(%rbp)
    /// movaps  %xmm7,  -32(%rbp)
    /// ...
    /// ```
    pub fn build_xmm_save(
        &self,
        xmm_regs: &[u8],
        base_reg: u16,
        base_offset: i64,
        slot_size: i64,
        has_frame_pointer: bool,
    ) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();
        let fp = if has_frame_pointer { -1i64 } else { 0i64 };
        let _ = fp; // marker for future frame-relative vs SP-relative

        for (i, &xmm_idx) in xmm_regs.iter().enumerate() {
            let offset = base_offset - (i as i64 + 1) * slot_size;
            // XMM physical register: XMM0 is at some index; here we use
            // the x86_register_info convention where XMM0 = 48, etc.
            let xmm_reg_id: u16 = 48u16 + xmm_idx as u16;

            let mut mi = MachineInstr::new(MOVAPS_STORE);
            // Destination: memory [base_reg + offset]
            mi.operands.push(MachineOperand::PhysReg(base_reg as u32));
            mi.operands.push(MachineOperand::Imm(offset));
            // Source: XMM register
            mi.operands.push(MachineOperand::PhysReg(xmm_reg_id as u32));
            instrs.push(mi);
        }

        instrs
    }

    /// Build XMM restore sequence using MOVAPS from stack slots.
    pub fn build_xmm_restore(
        &self,
        xmm_regs: &[u8],
        base_reg: u16,
        base_offset: i64,
        slot_size: i64,
    ) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();

        for (i, &xmm_idx) in xmm_regs.iter().enumerate() {
            let offset = base_offset - (i as i64 + 1) * slot_size;
            let xmm_reg_id: u16 = 48u16 + xmm_idx as u16;

            let mut mi = MachineInstr::new(MOVAPS_LOAD);
            // Destination: XMM register
            mi.operands.push(MachineOperand::PhysReg(xmm_reg_id as u32));
            // Source: memory [base_reg + offset]
            mi.operands.push(MachineOperand::PhysReg(base_reg as u32));
            mi.operands.push(MachineOperand::Imm(offset));
            instrs.push(mi);
        }

        instrs
    }

    /// Compute total XMM save area size including alignment padding.
    pub fn xmm_save_area_size(&self, xmm_regs: &[u8], slot_size: i64, alignment: i64) -> i64 {
        let raw_size = xmm_regs.len() as i64 * slot_size;
        if raw_size % alignment == 0 {
            raw_size
        } else {
            raw_size + (alignment - (raw_size % alignment))
        }
    }
}

// ============================================================================
// Stack Realignment — dynamic stack alignment for over-aligned locals
// ============================================================================

/// Maximum stack alignment supported by the x86 backend.
pub const MAX_STACK_ALIGNMENT: i64 = 64;

/// Information about stack realignment needs.
#[derive(Debug, Clone)]
pub struct StackRealignInfo {
    /// Whether stack realignment is required.
    pub needs_realignment: bool,
    /// Required alignment (e.g., 32 for AVX, 64 for AVX-512).
    pub alignment: i64,
    /// Scratch register used for alignment computation.
    pub scratch_reg: u16,
    /// Offset where the realignment adjustment is stored.
    pub adjustment_offset: i64,
}

impl Default for StackRealignInfo {
    fn default() -> Self {
        StackRealignInfo {
            needs_realignment: false,
            alignment: STACK_ALIGNMENT,
            scratch_reg: RAX,
            adjustment_offset: 0,
        }
    }
}

impl X86FrameLowering {
    /// Determine if stack realignment is required.
    ///
    /// Realignment is needed when:
    /// - A local variable requires alignment greater than the ABI default (16 bytes)
    /// - AVX/AVX-512 locals need 32/64 byte alignment
    /// - The function uses over-aligned allocas
    pub fn requires_stack_realignment(
        &self,
        frame_info: &X86FrameInfo,
        local_alignment: i64,
    ) -> bool {
        local_alignment > STACK_ALIGNMENT
            || frame_info.has_var_sized_objects
            || (self.call_conv == CallConv::Win64 && frame_info.frame_size > RED_ZONE_SIZE)
    }

    /// Emit stack realignment prologue.
    ///
    /// When the incoming stack is aligned to 16 bytes but we need 32 or 64,
    /// we must dynamically realign. The sequence is:
    /// ```asm
    /// push  rbp
    /// mov   rbp, rsp
    /// push  rbx             ; save scratch register
    /// mov   rbx, rsp        ; remember original RSP
    /// and   rsp, -ALIGN     ; align RSP down
    /// sub   rsp, frame_size ; allocate frame from aligned RSP
    /// ```
    pub fn emit_realign_prologue(
        &self,
        frame_size: i64,
        sp: u16,
        fp: u16,
        scratch: u16,
        alignment: i64,
    ) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();

        // push rbp
        let mut push_fp = MachineInstr::new(X86Opcode::PUSH as u32);
        push_fp.operands.push(MachineOperand::PhysReg(fp as u32));
        instrs.push(push_fp);

        // mov rbp, rsp
        let mut mov_fp = MachineInstr::new(X86Opcode::MOV as u32);
        mov_fp.operands.push(MachineOperand::PhysReg(fp as u32));
        mov_fp.operands.push(MachineOperand::PhysReg(sp as u32));
        instrs.push(mov_fp);

        // push scratch (save the register we'll use for alignment)
        let mut push_scratch = MachineInstr::new(X86Opcode::PUSH as u32);
        push_scratch
            .operands
            .push(MachineOperand::PhysReg(scratch as u32));
        instrs.push(push_scratch);

        // mov scratch, rsp  (remember original RSP)
        let mut mov_scratch = MachineInstr::new(X86Opcode::MOV as u32);
        mov_scratch
            .operands
            .push(MachineOperand::PhysReg(scratch as u32));
        mov_scratch
            .operands
            .push(MachineOperand::PhysReg(sp as u32));
        instrs.push(mov_scratch);

        // and rsp, -alignment  (align RSP down)
        let mut and_align = MachineInstr::new(X86Opcode::AND as u32);
        and_align.operands.push(MachineOperand::PhysReg(sp as u32));
        and_align.operands.push(MachineOperand::Imm(-alignment));
        instrs.push(and_align);

        // sub rsp, frame_size  (allocate frame from aligned position)
        if frame_size > 0 {
            let mut sub_frame = MachineInstr::new(X86Opcode::SUB as u32);
            sub_frame.operands.push(MachineOperand::PhysReg(sp as u32));
            sub_frame.operands.push(MachineOperand::Imm(frame_size));
            instrs.push(sub_frame);
        }

        instrs
    }

    /// Emit stack realignment epilogue.
    ///
    /// Restores RSP from the saved scratch register and pops saved registers.
    /// ```asm
    /// lea   rsp, [rbp - scratch_save_offset]
    /// pop   scratch
    /// pop   rbp
    /// ret
    /// ```
    pub fn emit_realign_epilogue(
        &self,
        sp: u16,
        fp: u16,
        scratch: u16,
        scratch_offset: i64,
    ) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();

        // lea rsp, [rbp + scratch_offset]
        let mut lea_instr = MachineInstr::new(X86Opcode::LEA as u32);
        lea_instr.operands.push(MachineOperand::PhysReg(sp as u32));
        lea_instr.operands.push(MachineOperand::PhysReg(fp as u32));
        lea_instr.operands.push(MachineOperand::Imm(scratch_offset));
        instrs.push(lea_instr);

        // Restore the alignment scratch register
        let mut pop_scratch = MachineInstr::new(X86Opcode::POP as u32);
        pop_scratch
            .operands
            .push(MachineOperand::PhysReg(scratch as u32));
        instrs.push(pop_scratch);

        // pop rbp
        let mut pop_fp = MachineInstr::new(X86Opcode::POP as u32);
        pop_fp.operands.push(MachineOperand::PhysReg(fp as u32));
        instrs.push(pop_fp);

        // ret
        instrs.push(self.build_ret());

        instrs
    }

    /// Find a suitable scratch register for stack realignment.
    ///
    /// Preference order: RAX (most common scratch), then R11, then R10.
    /// Avoids registers that are used for parameter passing.
    pub fn find_realignment_scratch(&self, used_regs: &[u16]) -> u16 {
        let candidates = if self.call_conv.is_64bit() {
            vec![RAX, R11, R10, R9]
        } else {
            vec![EAX]
        };

        for &cand in &candidates {
            if !used_regs.contains(&cand) {
                return cand;
            }
        }

        // Fallback: use RAX (caller must ensure it's saved/restored)
        if self.call_conv.is_64bit() {
            RAX
        } else {
            EAX
        }
    }
}

// ============================================================================
// Variable-Sized Object Frame — alloca/VLA dynamic stack adjustment
// ============================================================================

/// Metadata for variable-sized stack objects.
#[derive(Debug, Clone)]
pub struct VarSizedFrameInfo {
    /// Whether this function has dynamic allocas.
    pub has_dynamic_alloca: bool,
    /// Register holding the dynamic allocation size.
    pub size_reg: Option<VirtReg>,
    /// Total static frame size (excluding dynamic portion).
    pub static_frame_size: i64,
    /// Offset from frame pointer where dynamic area begins.
    pub dynamic_area_offset: i64,
}

impl Default for VarSizedFrameInfo {
    fn default() -> Self {
        VarSizedFrameInfo {
            has_dynamic_alloca: false,
            size_reg: None,
            static_frame_size: 0,
            dynamic_area_offset: 0,
        }
    }
}

impl X86FrameLowering {
    /// Detect if the function contains dynamic alloca instructions.
    pub fn has_dynamic_alloca(&self, mf: &MachineFunction) -> bool {
        for bb in &mf.blocks {
            for mi in &bb.instructions {
                // Check for alloca-like patterns: SUB RSP, reg (dynamic adjustment)
                // or explicit ALLOCA pseudo-instruction
                if mi.opcode == 3000u32 {
                    // Check if the size operand is not an immediate constant
                    if mi.operands.len() >= 2 {
                        if let MachineOperand::Reg(_) = mi.operands[1] {
                            return true;
                        }
                    }
                }
            }
        }
        false
    }

    /// Emit prologue for functions with variable-sized objects.
    ///
    /// The frame pointer is set up as usual, but SP is adjusted by a
    /// dynamic amount computed at runtime. The dynamic adjustment is
    /// stored relative to the frame pointer.
    ///
    /// ```asm
    /// push  rbp
    /// mov   rbp, rsp
    /// sub   rsp, static_frame_size
    /// push  rbx            ; saved regs...
    /// ; ... dynamic SP adjustment happens in the function body ...
    /// ```
    pub fn emit_var_sized_prologue(
        &self,
        static_frame_size: i64,
        sp: u16,
        fp: u16,
        saved_regs: &[u16],
    ) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();

        // push rbp
        instrs.push(self.build_push(fp));

        // mov rbp, rsp
        instrs.push(self.build_mov_fp_from_sp(fp, sp));

        // Allocate static portion of frame
        if static_frame_size > 0 {
            instrs.push(self.build_sub_sp(sp, static_frame_size));
        }

        // Save callee-saved GPRs
        for &reg in saved_regs {
            if reg != fp {
                instrs.push(self.build_push(reg));
            }
        }

        instrs
    }

    /// Emit epilogue for functions with variable-sized objects.
    ///
    /// Uses `mov rsp, rbp` to restore SP regardless of dynamic adjustments.
    pub fn emit_var_sized_epilogue(
        &self,
        sp: u16,
        fp: u16,
        saved_regs: &[u16],
    ) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();

        // Restore SP from FP (handles both static and dynamic frame)
        instrs.push(self.build_mov_sp_from_fp(sp, fp));

        // Restore callee-saved registers in reverse order
        for &reg in saved_regs.iter().rev() {
            if reg != fp {
                instrs.push(self.build_pop(reg));
            }
        }

        // Pop frame pointer
        instrs.push(self.build_pop(fp));

        // Return
        instrs.push(self.build_ret());

        instrs
    }

    /// Emit dynamic SP adjustment for alloca.
    ///
    /// ```asm
    /// mov   rax, alloca_size_reg
    /// add   rax, 15          ; align to 16 bytes
    /// and   rax, -16
    /// sub   rsp, rax
    /// mov   alloca_ptr_reg, rsp
    /// ```
    pub fn emit_dynamic_alloca(
        &self,
        size_reg: VirtReg,
        result_reg: VirtReg,
        sp: u16,
    ) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();

        // mov RAX, size_reg
        let mut mov_size = MachineInstr::new(X86Opcode::MOV as u32);
        mov_size.operands.push(MachineOperand::PhysReg(RAX as u32));
        mov_size.operands.push(MachineOperand::Reg(size_reg));
        mov_size.def = Some(result_reg);
        instrs.push(mov_size);

        // add RAX, 15  (for 16-byte alignment)
        let mut add_align = MachineInstr::new(X86Opcode::ADD as u32);
        add_align.operands.push(MachineOperand::PhysReg(RAX as u32));
        add_align.operands.push(MachineOperand::Imm(15));
        instrs.push(add_align);

        // and RAX, -16
        let mut and_align = MachineInstr::new(X86Opcode::AND as u32);
        and_align.operands.push(MachineOperand::PhysReg(RAX as u32));
        and_align.operands.push(MachineOperand::Imm(-16));
        instrs.push(and_align);

        // sub RSP, RAX
        let mut sub_sp = MachineInstr::new(X86Opcode::SUB as u32);
        sub_sp.operands.push(MachineOperand::PhysReg(sp as u32));
        sub_sp.operands.push(MachineOperand::PhysReg(RAX as u32));
        instrs.push(sub_sp);

        // mov result_reg, RSP  (return alloca pointer in result_reg)
        let mut mov_result = MachineInstr::new(X86Opcode::MOV as u32);
        mov_result.operands.push(MachineOperand::Reg(result_reg));
        mov_result.operands.push(MachineOperand::PhysReg(sp as u32));
        mov_result.def = Some(result_reg);
        instrs.push(mov_result);

        instrs
    }
}

// ============================================================================
// SEH (Structured Exception Handling) — Windows x64 unwind metadata
// ============================================================================

/// SEH unwind opcodes for Windows x64 exception handling.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SehUnwindOp {
    /// push a nonvolatile register: UWOP_PUSH_NONVOL
    PushNonVol(u16),
    /// allocate large stack: UWOP_ALLOC_LARGE
    AllocLarge(i64),
    /// allocate small stack: UWOP_ALLOC_SMALL
    AllocSmall(i64),
    /// set frame pointer register: UWOP_SET_FPREG
    SetFpReg,
    /// save nonvolatile register with MOV: UWOP_SAVE_NONVOL
    SaveNonVol(u16, i64),
    /// save XMM register: UWOP_SAVE_XMM128
    SaveXmm128(u16, i64),
    /// push machine frame (interrupt/trap): UWOP_PUSH_MACHFRAME
    PushMachFrame,
    /// end of prologue marker
    EndPrologue,
}

/// Complete Win64 unwind information for a function.
#[derive(Debug, Clone)]
pub struct Win64UnwindInfo {
    /// Version of the unwind info (1 or 2).
    pub version: u8,
    /// Flags (UNW_FLAG_EHANDLER, UNW_FLAG_UHANDLER, UNW_FLAG_CHAININFO).
    pub flags: u8,
    /// Size of the function prologue in bytes.
    pub prologue_size: u8,
    /// Number of unwind code slots.
    pub unwind_code_count: u8,
    /// Frame register (0 if none).
    pub frame_register: u8,
    /// Frame register offset (scaled by 16).
    pub frame_register_offset: u8,
    /// Unwind codes array.
    pub unwind_codes: Vec<SehUnwindOp>,
    /// Handler routine (RVA, 0 if none).
    pub exception_handler: u32,
    /// Handler data (RVA, 0 if none).
    pub handler_data: u32,
}

impl Default for Win64UnwindInfo {
    fn default() -> Self {
        Win64UnwindInfo {
            version: 1,
            flags: 0,
            prologue_size: 0,
            unwind_code_count: 0,
            frame_register: 0,
            frame_register_offset: 0,
            unwind_codes: Vec::new(),
            exception_handler: 0,
            handler_data: 0,
        }
    }
}

impl X86FrameLowering {
    /// Build complete Win64 unwind information for a function.
    ///
    /// This generates the .pdata and .xdata entries required by the Windows
    /// x64 exception handling mechanism. The unwind codes describe how to
    /// reverse the prologue to unwind the stack.
    pub fn build_win64_unwind_info(
        &self,
        frame_info: &X86FrameInfo,
        prologue_size: u8,
    ) -> Win64UnwindInfo {
        let mut info = Win64UnwindInfo::default();
        info.version = 1;
        info.prologue_size = prologue_size;

        // Build unwind codes in reverse order (as required by the spec)
        let mut codes = Vec::new();

        // End of prologue (always first in the reverse-order list)
        codes.push(SehUnwindOp::EndPrologue);

        // Frame pointer setup
        if frame_info.has_frame_pointer {
            codes.push(SehUnwindOp::SetFpReg);
            info.frame_register = RBP as u8;
            // Frame register offset = (RSP - RBP) / 16 after prologue
            // For a simple push rbp; mov rbp, rsp: offset is 0
            info.frame_register_offset = 0;
        }

        // Stack allocation
        if frame_info.frame_size > 0 {
            let alloc_size = self.align_frame_size(frame_info.frame_size, STACK_ALIGNMENT);
            if alloc_size <= 128 {
                codes.push(SehUnwindOp::AllocSmall(alloc_size));
            } else if alloc_size <= 524280 {
                codes.push(SehUnwindOp::AllocLarge(alloc_size));
            }
        }

        // Register saves (pushed in reverse order for unwind codes)
        // The unwind codes list is processed LIFO, so we list saves in
        // the order they would be undone (last push = first in list)
        for &reg in frame_info.saved_regs.iter() {
            if reg != self.call_conv.frame_pointer_reg() {
                codes.push(SehUnwindOp::PushNonVol(reg));
            }
        }

        // Push of frame pointer register (if used)
        if frame_info.has_frame_pointer {
            codes.push(SehUnwindOp::PushNonVol(self.call_conv.frame_pointer_reg()));
        }

        info.unwind_code_count = codes.len() as u8;
        info.unwind_codes = codes;

        info
    }

    /// Generate SEH .xdata assembly directives.
    pub fn emit_seh_directives(&self, unwind_info: &Win64UnwindInfo) -> Vec<String> {
        let mut directives = Vec::new();

        directives.push(format!(".seh_proc main",));

        for code in &unwind_info.unwind_codes {
            match *code {
                SehUnwindOp::PushNonVol(reg) => {
                    directives.push(format!(".seh_pushreg {}", reg));
                }
                SehUnwindOp::AllocLarge(size) => {
                    directives.push(format!(".seh_stackalloc {}", size));
                }
                SehUnwindOp::AllocSmall(size) => {
                    directives.push(format!(".seh_stackalloc {}", size));
                }
                SehUnwindOp::SetFpReg => {
                    directives.push(".seh_setframe %rbp, 0".to_string());
                }
                SehUnwindOp::SaveNonVol(reg, offset) => {
                    directives.push(format!(".seh_savereg {}, {}", reg, offset));
                }
                SehUnwindOp::SaveXmm128(reg, offset) => {
                    directives.push(format!(".seh_savexmm {}, {}", reg, offset));
                }
                SehUnwindOp::PushMachFrame => {
                    directives.push(".seh_pushframe".to_string());
                }
                SehUnwindOp::EndPrologue => {
                    directives.push(".seh_endprologue".to_string());
                }
            }
        }

        if unwind_info.exception_handler != 0 {
            directives.push(format!(".seh_handler __C_specific_handler, @except",));
        }

        directives.push(".seh_endproc".to_string());

        directives
    }
}

// ============================================================================
// Shrink Wrapping — move callee-save spills to cold path
// ============================================================================

/// Analysis result for shrink wrapping.
#[derive(Debug, Clone)]
pub struct ShrinkWrapInfo {
    /// Whether shrink wrapping is profitable for this function.
    pub profitable: bool,
    /// The basic block where saves should be placed (instead of entry).
    pub save_block: Option<usize>,
    /// The basic block where restores should be placed.
    pub restore_block: Option<usize>,
    /// Registers that can be shrink-wrapped (not used on early-exit paths).
    pub shrinkable_regs: Vec<u16>,
}

impl Default for ShrinkWrapInfo {
    fn default() -> Self {
        ShrinkWrapInfo {
            profitable: false,
            save_block: None,
            restore_block: None,
            shrinkable_regs: Vec::new(),
        }
    }
}

impl X86FrameLowering {
    /// Analyze whether shrink wrapping is beneficial.
    ///
    /// Shrink wrapping moves callee-saved register saves/restores from the
    /// function entry/exit to colder code paths. This is profitable when:
    /// - The function has early-exit paths (guard checks, fast returns)
    /// - Those early-exit paths don't use the callee-saved registers
    /// - The function has enough basic blocks to justify the complexity
    ///
    /// Returns a `ShrinkWrapInfo` describing where saves/restores should move.
    pub fn analyze_shrink_wrap(&self, mf: &MachineFunction) -> ShrinkWrapInfo {
        let mut info = ShrinkWrapInfo::default();

        // Don't shrink-wrap trivial functions
        if mf.blocks.len() < 2 {
            return info;
        }

        // Identify early-exit blocks (blocks that return and are
        // reachable without going through the main body)
        let callee_saved = self.call_conv.callee_saved_regs().to_vec();

        // For each callee-saved register, check if it's used in all
        // paths. If some paths don't use it, it's a shrink-wrap candidate.
        for &reg in &callee_saved {
            let mut used_in_all = true;

            for (block_idx, bb) in mf.blocks.iter().enumerate() {
                // Skip entry block (always uses saved regs if any)
                if block_idx == 0 {
                    continue;
                }

                // Check if this block is an early return (has RET)
                let is_ret_block = bb
                    .instructions
                    .iter()
                    .any(|mi| mi.opcode == X86Opcode::RET as u32);

                if is_ret_block {
                    let reg_used = bb.instructions.iter().any(|mi| {
                        mi.operands.iter().any(|op| {
                            if let MachineOperand::PhysReg(r) = *op {
                                r == reg as u32
                            } else {
                                false
                            }
                        })
                    });

                    if !reg_used {
                        used_in_all = false;
                        break;
                    }
                }
            }

            if !used_in_all {
                info.shrinkable_regs.push(reg);
            }
        }

        info.profitable = !info.shrinkable_regs.is_empty();

        // Determine save/restore placement
        if info.profitable {
            // Find the first block after entry that uses any callee-saved reg
            let mut first_use_block: Option<usize> = None;
            for (idx, bb) in mf.blocks.iter().enumerate().skip(1) {
                let uses_any = info.shrinkable_regs.iter().any(|&sr| {
                    bb.instructions.iter().any(|mi| {
                        mi.operands.iter().any(|op| {
                            if let MachineOperand::PhysReg(r) = *op {
                                r == sr as u32
                            } else {
                                false
                            }
                        })
                    })
                });
                if uses_any {
                    first_use_block = Some(idx);
                    break;
                }
            }

            if let Some(idx) = first_use_block {
                info.save_block = Some(idx);
                info.restore_block = Some(mf.blocks.len() - 1); // last block (usually has RET)
            }
        }

        info
    }

    /// Emit shrink-wrapped save sequence at a specific block.
    pub fn emit_shrink_wrapped_saves(&self, regs: &[u16], fp: u16) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();
        for &reg in regs {
            if reg != fp {
                instrs.push(self.build_push(reg));
            }
        }
        instrs
    }

    /// Emit shrink-wrapped restore sequence at a specific block.
    pub fn emit_shrink_wrapped_restores(&self, regs: &[u16], fp: u16) -> Vec<MachineInstr> {
        let mut instrs = Vec::new();
        for &reg in regs.iter().rev() {
            if reg != fp {
                instrs.push(self.build_pop(reg));
            }
        }
        instrs
    }
}

// ============================================================================
// DWARF Call Frame Information — .cfi_* directives
// ============================================================================

/// DWARF CFI directive for call frame unwinding.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CfiDirective {
    /// Define CFA rule: .cfi_def_cfa register, offset
    DefCfa(u16, i64),
    /// CFA offset: .cfi_def_cfa_offset offset
    DefCfaOffset(i64),
    /// CFA register: .cfi_def_cfa_register register
    DefCfaRegister(u16),
    /// Register offset from CFA: .cfi_offset register, offset
    Offset(u16, i64),
    /// Register is same value: .cfi_same_value register
    SameValue(u16),
    /// Register value: .cfi_register register, register2
    Register(u16, u16),
    /// Restore register to initial rule: .cfi_restore register
    Restore(u16),
    /// Remember state: .cfi_remember_state
    RememberState,
    /// Restore state: .cfi_restore_state
    RestoreState,
    /// Undefined register: .cfi_undefined register
    Undefined(u16),
    /// Escape bytes: .cfi_escape bytes...
    Escape(Vec<u8>),
    /// GNU window save: .cfi_window_save
    WindowSave,
    /// Argument pointer: .cfi_arg_pointer register
    ArgPointer(u16),
    /// Return address register: .cfi_return_column register
    ReturnColumn(u16),
    /// Signal frame: .cfi_signal_frame
    SignalFrame,
}

/// Call frame information for a function.
#[derive(Debug, Clone)]
pub struct CallFrameInfo {
    /// CFA (Canonical Frame Address) register.
    pub cfa_register: u16,
    /// CFA offset (from CFA register to CFA).
    pub cfa_offset: i64,
    /// Register offset rules: maps register to offset from CFA.
    pub reg_offsets: HashMap<u16, i64>,
    /// Register rules: maps register to the register holding its value.
    pub reg_rules: HashMap<u16, u16>,
    /// Return address column.
    pub return_column: u16,
}

impl Default for CallFrameInfo {
    fn default() -> Self {
        CallFrameInfo {
            cfa_register: RSP,
            cfa_offset: PUSH_SIZE_64, // return address pushed by CALL
            reg_offsets: HashMap::new(),
            reg_rules: HashMap::new(),
            return_column: 16, // RIP is DWARF register 16 on x86-64
        }
    }
}

impl X86FrameLowering {
    /// Build DWARF CFI directives for the function prologue.
    ///
    /// Generates a sequence of `.cfi_*` directives that describe how to
    /// unwind the stack at each point in the prologue.
    pub fn build_cfi_prologue(
        &self,
        frame_info: &X86FrameInfo,
        use_dwarf: bool,
    ) -> Vec<CfiDirective> {
        if !use_dwarf {
            return Vec::new();
        }

        let mut cfi = Vec::new();
        let fp = self.call_conv.frame_pointer_reg();

        if frame_info.has_frame_pointer {
            // Step 1: push rbp
            // CFA is now at RSP + 16 (return address 8 + saved RBP 8)
            cfi.push(CfiDirective::DefCfaOffset(PUSH_SIZE_64 * 2));
            cfi.push(CfiDirective::Offset(fp, -(PUSH_SIZE_64 * 2)));

            // Step 2: mov rbp, rsp
            // CFA is now [RBP + 16]
            cfi.push(CfiDirective::DefCfaRegister(fp));
        } else {
            // No frame pointer: CFA stays at RSP + adjustment
            if frame_info.frame_size > 0 {
                let alloc_size = self.align_frame_size(frame_info.frame_size, STACK_ALIGNMENT);
                cfi.push(CfiDirective::DefCfaOffset(PUSH_SIZE_64 + alloc_size));
            }
        }

        // Callee-saved register offsets (from CFA)
        let mut offset_from_cfa = if frame_info.has_frame_pointer {
            PUSH_SIZE_64 * 2
        } else {
            PUSH_SIZE_64
        };

        for &reg in &frame_info.saved_regs {
            if reg != fp {
                cfi.push(CfiDirective::Offset(reg, -offset_from_cfa));
                offset_from_cfa += self.call_conv.push_size();
            }
        }

        // Return address
        cfi.push(CfiDirective::Offset(16, -PUSH_SIZE_64));

        cfi
    }

    /// Build DWARF CFI directives for the function epilogue.
    ///
    /// Generates directives to restore the CFA and register states.
    pub fn build_cfi_epilogue(
        &self,
        frame_info: &X86FrameInfo,
        use_dwarf: bool,
    ) -> Vec<CfiDirective> {
        if !use_dwarf {
            return Vec::new();
        }

        let mut cfi = Vec::new();
        let fp = self.call_conv.frame_pointer_reg();
        let sp = self.call_conv.stack_pointer_reg();

        // Restore all callee-saved registers
        for &reg in &frame_info.saved_regs {
            cfi.push(CfiDirective::Restore(reg));
        }

        if frame_info.has_frame_pointer {
            // Pop rbp restores CFA to RSP + 8
            cfi.push(CfiDirective::Restore(fp));
            cfi.push(CfiDirective::DefCfa(sp, PUSH_SIZE_64));
        } else {
            // Restore SP
            cfi.push(CfiDirective::DefCfa(sp, PUSH_SIZE_64));
        }

        cfi
    }

    /// Emit CFI directives as assembly directives for the assembler.
    pub fn emit_cfi_directives(&self, cfi: &[CfiDirective]) -> Vec<String> {
        let mut lines = Vec::new();

        for directive in cfi {
            match *directive {
                CfiDirective::DefCfa(reg, offset) => {
                    lines.push(format!(".cfi_def_cfa {}, {}", reg, offset));
                }
                CfiDirective::DefCfaOffset(offset) => {
                    lines.push(format!(".cfi_def_cfa_offset {}", offset));
                }
                CfiDirective::DefCfaRegister(reg) => {
                    lines.push(format!(".cfi_def_cfa_register {}", reg));
                }
                CfiDirective::Offset(reg, offset) => {
                    lines.push(format!(".cfi_offset {}, {}", reg, offset));
                }
                CfiDirective::SameValue(reg) => {
                    lines.push(format!(".cfi_same_value {}", reg));
                }
                CfiDirective::Register(reg1, reg2) => {
                    lines.push(format!(".cfi_register {}, {}", reg1, reg2));
                }
                CfiDirective::Restore(reg) => {
                    lines.push(format!(".cfi_restore {}", reg));
                }
                CfiDirective::RememberState => {
                    lines.push(".cfi_remember_state".to_string());
                }
                CfiDirective::RestoreState => {
                    lines.push(".cfi_restore_state".to_string());
                }
                CfiDirective::Undefined(reg) => {
                    lines.push(format!(".cfi_undefined {}", reg));
                }
                CfiDirective::Escape(ref bytes) => {
                    let hex_bytes: Vec<String> =
                        bytes.iter().map(|b| format!("{:02x}", b)).collect();
                    lines.push(format!(".cfi_escape {}", hex_bytes.join(", ")));
                }
                CfiDirective::WindowSave => {
                    lines.push(".cfi_window_save".to_string());
                }
                CfiDirective::ArgPointer(reg) => {
                    lines.push(format!(".cfi_arg_pointer {}", reg));
                }
                CfiDirective::ReturnColumn(reg) => {
                    lines.push(format!(".cfi_return_column {}", reg));
                }
                CfiDirective::SignalFrame => {
                    lines.push(".cfi_signal_frame".to_string());
                }
            }
        }

        lines
    }
}

// ============================================================================
// Spill Slot Computation — assigning stack slots to virtual registers
// ============================================================================

/// Represents a stack slot assigned to a virtual register spill.
#[derive(Debug, Clone)]
pub struct SpillSlot {
    /// The virtual register this slot is for.
    pub vreg: VirtReg,
    /// Offset from the frame base (negative for below FP/RSP).
    pub offset: i64,
    /// Size of the spill slot in bytes.
    pub size: i64,
    /// Required alignment for this slot.
    pub alignment: i64,
    /// Register class of the spilled register.
    pub reg_class: SpillSlotClass,
    /// Whether this slot is fixed (cannot be moved).
    pub fixed: bool,
}

/// Register class for spill slot sizing and alignment.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpillSlotClass {
    /// 8-byte GPR (RBX, R12, etc.)
    Gpr64,
    /// 4-byte GPR (EBX, etc.)
    Gpr32,
    /// 2-byte GPR
    Gpr16,
    /// 1-byte GPR
    Gpr8,
    /// 16-byte XMM register
    Xmm128,
    /// 32-byte YMM register (AVX)
    Ymm256,
    /// 64-byte ZMM register (AVX-512)
    Zmm512,
    /// 8-byte x87 FPU
    X87,
    /// 8-byte MMX
    Mmx64,
}

impl SpillSlotClass {
    /// Returns the size in bytes for this register class.
    pub fn size(&self) -> i64 {
        match self {
            SpillSlotClass::Gpr64 | SpillSlotClass::X87 | SpillSlotClass::Mmx64 => 8,
            SpillSlotClass::Gpr32 => 4,
            SpillSlotClass::Gpr16 => 2,
            SpillSlotClass::Gpr8 => 1,
            SpillSlotClass::Xmm128 => 16,
            SpillSlotClass::Ymm256 => 32,
            SpillSlotClass::Zmm512 => 64,
        }
    }

    /// Returns the required alignment for this register class.
    pub fn alignment(&self) -> i64 {
        match self {
            SpillSlotClass::Gpr64
            | SpillSlotClass::Gpr32
            | SpillSlotClass::Gpr16
            | SpillSlotClass::Gpr8 => PUSH_SIZE_64,
            SpillSlotClass::Xmm128 => XMM_SAVE_ALIGN,
            SpillSlotClass::Ymm256 => YMM_SAVE_ALIGN,
            SpillSlotClass::Zmm512 => ZMM_SAVE_ALIGN,
            SpillSlotClass::X87 | SpillSlotClass::Mmx64 => 8,
        }
    }
}

impl X86FrameLowering {
    /// Compute spill slot assignments for all spilled virtual registers.
    ///
    /// Allocates stack space for each spilled register, packing them
    /// efficiently while respecting alignment constraints. Returns a
    /// mapping from virtual register to its spill slot.
    pub fn compute_spill_slots(
        &self,
        spilled: &[(VirtReg, SpillSlotClass)],
        base_offset: i64,
    ) -> HashMap<VirtReg, SpillSlot> {
        let mut slots = HashMap::new();
        let mut current_offset = base_offset;

        // Sort by alignment (largest first) for optimal packing
        let mut sorted: Vec<_> = spilled.to_vec();
        sorted.sort_by(|a, b| b.1.alignment().cmp(&a.1.alignment()));

        for &(vreg, class) in &sorted {
            let align = class.alignment();
            let size = class.size();

            // Align the offset downward
            current_offset = self.align_frame_size(current_offset, align);

            slots.insert(
                vreg,
                SpillSlot {
                    vreg,
                    offset: current_offset,
                    size,
                    alignment: align,
                    reg_class: class,
                    fixed: false,
                },
            );

            current_offset += size;
        }

        slots
    }

    /// Compute the total spill area size for a set of registers.
    pub fn compute_spill_area_size(&self, spills: &[(VirtReg, SpillSlotClass)]) -> i64 {
        let slots = self.compute_spill_slots(spills, 0);

        if slots.is_empty() {
            return 0;
        }

        let max_end = slots.values().map(|s| s.offset + s.size).max().unwrap_or(0);

        self.align_frame_size(max_end, STACK_ALIGNMENT)
    }

    /// Decide the register class for a virtual register based on its usage.
    pub fn classify_spill_slot(&self, bit_width: u16) -> SpillSlotClass {
        match bit_width {
            1..=8 => SpillSlotClass::Gpr8,
            9..=16 => SpillSlotClass::Gpr16,
            17..=32 => SpillSlotClass::Gpr32,
            33..=64 => SpillSlotClass::Gpr64,
            65..=128 => SpillSlotClass::Xmm128,
            129..=256 => SpillSlotClass::Ymm256,
            257..=512 => SpillSlotClass::Zmm512,
            _ => SpillSlotClass::Gpr64, // default
        }
    }
}

// ============================================================================
// Frame Pointer Elimination — when to omit FP and use SP-relative
// ============================================================================

/// Decision information for frame pointer elimination.
#[derive(Debug, Clone)]
pub struct FramePointerElimInfo {
    /// Whether frame pointer elimination is performed.
    pub eliminated: bool,
    /// Reason for keeping the frame pointer (if not eliminated).
    pub reason: Option<FpElimReason>,
    /// Total frame offset to track instead of FP-relative.
    pub sp_offset: i64,
}

/// Reasons for keeping the frame pointer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FpElimReason {
    /// Variable-sized stack objects (alloca/VLA).
    VarSizedObjects,
    /// Inline assembly that clobbers the stack pointer.
    InlineAsmClobberSp,
    /// Dynamic stack realignment required.
    StackRealignment,
    /// Function has too many locals for SP-relative addressing (x86-32).
    ManyLocals32,
    /// Debugging or profiling requires frame pointer.
    DebugInfo,
    /// Explicitly requested (e.g., -fno-omit-frame-pointer).
    ExplicitRequest,
}

impl X86FrameLowering {
    /// Determine whether frame pointer elimination can be performed.
    ///
    /// The frame pointer can be eliminated (omitted) when:
    /// - No variable-sized objects (alloca with dynamic size, VLAs)
    /// - No inline assembly that clobbers the stack pointer
    /// - No dynamic stack realignment requirement
    /// - The function's frame fits within SP-relative addressing
    /// - Debug info doesn't require FP (or we use DWARF CFI instead)
    pub fn can_eliminate_frame_pointer(
        &self,
        frame_info: &X86FrameInfo,
        has_inline_asm: bool,
        force_frame_pointer: bool,
        max_sp_offset: i64,
    ) -> FramePointerElimInfo {
        let mut info = FramePointerElimInfo {
            eliminated: false,
            reason: None,
            sp_offset: 0,
        };

        if force_frame_pointer {
            info.reason = Some(FpElimReason::ExplicitRequest);
            return info;
        }

        if frame_info.has_var_sized_objects {
            info.reason = Some(FpElimReason::VarSizedObjects);
            return info;
        }

        if has_inline_asm {
            // Conservative: assume inline asm may clobber SP
            info.reason = Some(FpElimReason::InlineAsmClobberSp);
            return info;
        }

        // On 32-bit, SP-relative addressing is limited to addressing modes
        // that may not cover large frames well
        if self.call_conv.is_32bit() && frame_info.frame_size > max_sp_offset {
            info.reason = Some(FpElimReason::ManyLocals32);
            return info;
        }

        // On 64-bit, SP-relative with large displacements works fine
        info.eliminated = true;
        info.sp_offset = frame_info.frame_size;
        info
    }

    /// Adjust SP-relative offset tracking throughout the function.
    ///
    /// When the frame pointer is eliminated, the compiler must track
    /// the current SP offset after every instruction that modifies SP.
    /// This function computes the adjusted offset.
    pub fn adjust_sp_offset(
        &self,
        current_offset: i64,
        opcode: u32,
        operands: &[MachineOperand],
    ) -> i64 {
        // Match against known X86Opcode discriminants
        match opcode {
            11u32 => current_offset + self.call_conv.push_size(), // PUSH
            12u32 => current_offset - self.call_conv.push_size(), // POP
            3u32 => {
                // SUB: If SUB targets RSP with an immediate, adjust offset
                if operands.len() >= 2 {
                    if let (MachineOperand::PhysReg(reg), MachineOperand::Imm(amount)) =
                        (&operands[0], &operands[1])
                    {
                        if *reg == self.call_conv.stack_pointer_reg() as u32 {
                            return current_offset + amount;
                        }
                    }
                }
                current_offset
            }
            2u32 => {
                // ADD: If ADD targets RSP with an immediate, adjust offset
                if operands.len() >= 2 {
                    if let (MachineOperand::PhysReg(reg), MachineOperand::Imm(amount)) =
                        (&operands[0], &operands[1])
                    {
                        if *reg == self.call_conv.stack_pointer_reg() as u32 {
                            return current_offset - amount;
                        }
                    }
                }
                current_offset
            }
            14u32 => {
                // CALL: pushes return address, but callee restores
                // SP before returning, so offset remains unchanged
                current_offset
            }
            _ => current_offset,
        }
    }
}

// ============================================================================
// Red Zone Handling — skip SP adjustment for leaf functions
// ============================================================================

impl X86FrameLowering {
    /// Determine if the function can use the red zone for its entire frame.
    ///
    /// The red zone is the 128 bytes below RSP that are reserved by the
    /// System V AMD64 ABI and can be used without adjusting RSP. Conditions:
    /// - Calling convention is System V (Linux, macOS)
    /// - Function is a leaf (makes no calls)
    /// - Frame size fits within the red zone (128 bytes)
    /// - No signal handlers or interrupt handlers in the function
    pub fn can_use_red_zone(&self, frame_info: &X86FrameInfo, is_signal_handler: bool) -> bool {
        if !self.call_conv.uses_red_zone() {
            return false;
        }
        if is_signal_handler {
            return false; // signal handlers must not use red zone
        }
        if frame_info.has_calls {
            return false; // calls clobber the red zone
        }
        if frame_info.has_var_sized_objects {
            return false; // dynamic SP adjustment cannot use red zone
        }
        frame_info.frame_size <= RED_ZONE_SIZE
    }

    /// Compute the effective red zone usage for a leaf function.
    ///
    /// Returns the amount of red zone that can be safely used. If the
    /// function can use the red zone, emit a NOP-adjusted prologue that
    /// doesn't modify RSP (just pushes RBP and maybe saves registers).
    pub fn compute_red_zone_usage(
        &self,
        frame_info: &X86FrameInfo,
        is_signal_handler: bool,
    ) -> i64 {
        if self.can_use_red_zone(frame_info, is_signal_handler) {
            frame_info.frame_size
        } else {
            0
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    // === Helper functions ===

    fn make_empty_mf(name: &str) -> MachineFunction {
        MachineFunction::new(name)
    }

    #[allow(dead_code)]
    fn make_leaf_mf(name: &str) -> MachineFunction {
        let mut mf = MachineFunction::new(name);
        let mut bb = MachineBasicBlock {
            name: "entry".to_string(),
            instructions: Vec::new(),
            successors: Vec::new(),
        };
        // Add some ALU instructions that use callee-saved regs
        bb.instructions.push({
            let mut mi = MachineInstr::new(X86Opcode::ADD as u32);
            mi.operands.push(MachineOperand::PhysReg(RBX as u32));
            mi.operands.push(MachineOperand::PhysReg(R12 as u32));
            mi
        });
        bb.instructions.push({
            let mut mi = MachineInstr::new(X86Opcode::RET as u32);
            mi
        });
        mf.push_block(bb);
        mf
    }

    fn make_mf_with_calls(name: &str) -> MachineFunction {
        let mut mf = MachineFunction::new(name);
        let mut bb = MachineBasicBlock {
            name: "entry".to_string(),
            instructions: Vec::new(),
            successors: Vec::new(),
        };
        bb.instructions.push({
            let mut mi = MachineInstr::new(X86Opcode::CALL as u32);
            mi.operands
                .push(MachineOperand::Label("other_func".to_string()));
            mi
        });
        bb.instructions.push({
            let mut mi = MachineInstr::new(X86Opcode::RET as u32);
            mi
        });
        mf.push_block(bb);
        mf
    }

    // === CallConv Tests ===

    #[test]
    fn test_call_conv_uses_red_zone() {
        assert!(CallConv::SystemV.uses_red_zone());
        assert!(!CallConv::Win64.uses_red_zone());
        assert!(!CallConv::CDecl32.uses_red_zone());
    }

    #[test]
    fn test_call_conv_is_64bit() {
        assert!(CallConv::SystemV.is_64bit());
        assert!(CallConv::Win64.is_64bit());
        assert!(!CallConv::CDecl32.is_64bit());
        assert!(!CallConv::StdCall32.is_64bit());
    }

    #[test]
    fn test_call_conv_is_32bit() {
        assert!(!CallConv::SystemV.is_32bit());
        assert!(!CallConv::Win64.is_32bit());
        assert!(CallConv::CDecl32.is_32bit());
        assert!(CallConv::FastCall32.is_32bit());
    }

    #[test]
    fn test_call_conv_push_size() {
        assert_eq!(CallConv::SystemV.push_size(), 8);
        assert_eq!(CallConv::Win64.push_size(), 8);
        assert_eq!(CallConv::CDecl32.push_size(), 4);
        assert_eq!(CallConv::StdCall32.push_size(), 4);
    }

    #[test]
    fn test_call_conv_callee_saved_regs() {
        let sysv = CallConv::SystemV.callee_saved_regs();
        assert!(sysv.contains(&RBX));
        assert!(sysv.contains(&R12));
        assert!(sysv.contains(&R15));

        let win64 = CallConv::Win64.callee_saved_regs();
        assert!(win64.contains(&RBX));
        assert!(win64.contains(&RDI_CONST));
        assert!(win64.contains(&RSI_CONST));

        let cdecl32 = CallConv::CDecl32.callee_saved_regs();
        assert!(cdecl32.contains(&EBX32));
        assert!(cdecl32.contains(&ESI32));
    }

    // === X86FrameInfo Tests ===

    #[test]
    fn test_frame_info_default() {
        let info = X86FrameInfo::new();
        assert_eq!(info.frame_size, 0);
        assert_eq!(info.saved_regs.len(), 0);
        assert!(!info.has_frame_pointer);
        assert!(!info.has_calls);
        assert!(!info.uses_red_zone);
    }

    #[test]
    fn test_frame_info_total_frame_size() {
        let mut info = X86FrameInfo::new();
        info.frame_size = 48;
        assert_eq!(info.total_frame_size(), 48);
    }

    // === X86FrameLowering Tests ===

    #[test]
    fn test_frame_lowering_new() {
        let fl = X86FrameLowering::new(CallConv::SystemV);
        assert_eq!(fl.call_conv, CallConv::SystemV);
    }

    #[test]
    fn test_frame_lowering_default() {
        let fl = X86FrameLowering::default();
        assert_eq!(fl.call_conv, CallConv::SystemV);
    }

    #[test]
    fn test_align_frame_size() {
        let fl = X86FrameLowering::new(CallConv::SystemV);
        assert_eq!(fl.align_frame_size(0, 16), 0);
        assert_eq!(fl.align_frame_size(16, 16), 16);
        assert_eq!(fl.align_frame_size(17, 16), 32);
        assert_eq!(fl.align_frame_size(20, 16), 32);
        assert_eq!(fl.align_frame_size(31, 16), 32);
        assert_eq!(fl.align_frame_size(32, 16), 32);
        assert_eq!(fl.align_frame_size(33, 16), 48);
    }

    #[test]
    fn test_calculate_frame_size() {
        let fl = X86FrameLowering::new(CallConv::SystemV);
        let mut info = X86FrameInfo::new();
        info.callee_saved_size = 16; // 2 saved regs
        info.local_area_offset = -24;
        info.max_call_frame_size = 8;
        let size = fl.calculate_frame_size(&info);
        // 16 + 24 + 8 = 48, already aligned to 16
        assert_eq!(size, 48);

        // Unaligned case
        let mut info2 = X86FrameInfo::new();
        info2.callee_saved_size = 8; // 1 saved reg
        info2.local_area_offset = -10;
        info2.max_call_frame_size = 0;
        let size2 = fl.calculate_frame_size(&info2);
        // 8 + 10 = 18 -> aligned to 32
        assert_eq!(size2, 32);
    }

    #[test]
    fn test_needs_frame_pointer_var_sized() {
        let fl = X86FrameLowering::new(CallConv::SystemV);
        let mut info = X86FrameInfo::new();
        info.has_var_sized_objects = true;
        assert!(fl.needs_frame_pointer(&info));
    }

    #[test]
    fn test_needs_frame_pointer_large_frame_with_calls() {
        let fl = X86FrameLowering::new(CallConv::SystemV);
        let mut info = X86FrameInfo::new();
        info.has_calls = true;
        info.frame_size = 256;
        assert!(fl.needs_frame_pointer(&info));
    }

    #[test]
    fn test_needs_frame_pointer_small_leaf() {
        let fl = X86FrameLowering::new(CallConv::SystemV);
        let mut info = X86FrameInfo::new();
        info.has_calls = false;
        info.frame_size = 64; // fits in red zone
        assert!(!fl.needs_frame_pointer(&info));
    }

    #[test]
    fn test_needs_frame_pointer_32bit() {
        let fl = X86FrameLowering::new(CallConv::CDecl32);
        let mut info = X86FrameInfo::new();
        info.frame_size = 16;
        assert!(fl.needs_frame_pointer(&info));
    }

    #[test]
    fn test_needs_frame_pointer_huge_frame() {
        let fl = X86FrameLowering::new(CallConv::SystemV);
        let mut info = X86FrameInfo::new();
        info.frame_size = 8192;
        assert!(fl.needs_frame_pointer(&info));
    }

    #[test]
    fn test_build_frame_info_leaf() {
        let fl = X86FrameLowering::new(CallConv::SystemV);
        let mf = make_leaf_mf("leaf_func");
        let info = fl.build_frame_info(&mf);
        assert!(!info.has_calls);
        // Leaf function with used callee-saved regs should detect them
        assert!(!info.saved_regs.is_empty());
        assert!(info.uses_red_zone || info.frame_size <= RED_ZONE_SIZE);
    }

    #[test]
    fn test_build_frame_info_with_calls() {
        let fl = X86FrameLowering::new(CallConv::SystemV);
        let mf = make_mf_with_calls("caller_func");
        let info = fl.build_frame_info(&mf);
        assert!(info.has_calls);
        assert!(!info.uses_red_zone);
    }

    #[test]
    fn test_emit_prologue_basic() {
        let fl = X86FrameLowering::new(CallConv::SystemV);
        let mut mf = make_leaf_mf("basic_func");
        // Manually set up some frame info expectations
        let instrs = fl.emit_prologue(&mut mf);
        // Even for a trivial function, we should get prologue instructions
        assert!(!instrs.is_empty(), "Prologue should emit instructions");
    }

    #[test]
    fn test_emit_epilogue_basic() {
        let fl = X86FrameLowering::new(CallConv::SystemV);
        let mut mf = make_empty_mf("basic_func");
        let instrs = fl.emit_epilogue(&mut mf);
        assert!(!instrs.is_empty(), "Epilogue should emit instructions");
        // Last instruction should be RET
        let last = instrs.last().unwrap();
        assert_eq!(last.opcode, X86Opcode::RET as u32);
    }

    #[test]
    fn test_emit_prologue_win64() {
        let fl = X86FrameLowering::new(CallConv::Win64);
        let mut mf = make_leaf_mf("win64_func");
        let instrs = fl.emit_prologue(&mut mf);
        assert!(!instrs.is_empty());
        // Win64 should use 64-bit push (check opcode)
        let push_count = instrs
            .iter()
            .filter(|i| i.opcode == X86Opcode::PUSH as u32)
            .count();
        assert!(
            push_count > 0,
            "Win64 prologue should contain push instructions"
        );
    }

    #[test]
    fn test_emit_prologue_32() {
        let fl = X86FrameLowering::new(CallConv::CDecl32);
        let mut mf = make_empty_mf("cdecl32_func");
        let instrs = fl.emit_prologue_32(&mut mf);
        assert!(!instrs.is_empty());
        let push_count = instrs
            .iter()
            .filter(|i| i.opcode == X86Opcode::PUSH as u32)
            .count();
        assert!(
            push_count > 0,
            "32-bit prologue should contain push instructions"
        );
    }

    #[test]
    fn test_emit_epilogue_32() {
        let fl = X86FrameLowering::new(CallConv::CDecl32);
        let mut mf = make_empty_mf("cdecl32_func");
        let instrs = fl.emit_epilogue_32(&mut mf);
        assert!(!instrs.is_empty());
        let last = instrs.last().unwrap();
        assert_eq!(last.opcode, X86Opcode::RET as u32);
    }

    #[test]
    fn test_assign_callee_saved_spill_slots() {
        let fl = X86FrameLowering::new(CallConv::SystemV);
        let mf = make_leaf_mf("spill_test");
        let slots = fl.assign_callee_saved_spill_slots(&mf);
        // Should have slots for used callee-saved regs (RBX and R12 from make_leaf_mf)
        assert!(!slots.is_empty(), "Should have spill slots for used regs");
        // Verify offsets are negative
        for (_reg, offset) in &slots {
            assert!(*offset < 0, "Spill slot offsets should be negative");
        }
    }

    #[test]
    fn test_get_frame_index_reference() {
        let fl = X86FrameLowering::new(CallConv::SystemV);
        let mut mf = make_empty_mf("fi_test");
        let instrs = fl.get_frame_index_reference(&mut mf, 0, 0);
        assert!(!instrs.is_empty());
        // Should produce a load instruction
        let load = &instrs[0];
        assert_eq!(load.opcode, X86Opcode::MOV as u32);
        assert!(load.def.is_some(), "Load should define a virtual register");
    }

    #[test]
    fn test_prologue_epilogue_roundtrip() {
        let fl = X86FrameLowering::new(CallConv::SystemV);
        let mut mf = make_empty_mf("roundtrip");
        let prologue = fl.emit_prologue(&mut mf);
        let epilogue = fl.emit_epilogue(&mut mf);

        // Prologue should save things, epilogue should restore them
        let prologue_pushes: Vec<_> = prologue
            .iter()
            .filter(|i| i.opcode == X86Opcode::PUSH as u32)
            .collect();
        let epilogue_pops: Vec<_> = epilogue
            .iter()
            .filter(|i| i.opcode == X86Opcode::POP as u32)
            .collect();
        // Number of saves should match number of restores (roughly)
        assert!(
            epilogue_pops.len() >= prologue_pushes.len(),
            "Epilogue should restore at least as many regs as prologue saves"
        );
    }

    #[test]
    fn test_red_zone_detection() {
        let fl = X86FrameLowering::new(CallConv::SystemV);
        let mf = make_leaf_mf("red_zone_test");
        let info = fl.build_frame_info(&mf);
        // Leaf functions with small frames should use red zone
        // The actual result depends on frame size calculation
        if !info.has_calls {
            // Red zone will be used if frame size is small enough
            assert!(
                info.uses_red_zone || info.frame_size > RED_ZONE_SIZE,
                "Leaf with small frame should use red zone, or frame_size exceeded red zone"
            );
        }
    }
}