llvm-native-core 0.1.9

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
//! X86 Call Frame Optimization — comprehensive call frame setup/teardown
//! optimization for all X86 (32-bit and 64-bit) targets.
//!
//! ## Optimization Passes
//!
//! 1. **ADJSTACK Elimination**: Remove redundant `ADJSTACK` instructions that
//!    cancel each other out (ADJSTACK+n followed by ADJSTACK-n within the
//!    same basic block, or when the net stack adjustment is zero across a
//!    basic block).
//!
//! 2. **Stack Adjustment Merging**: Combine multiple consecutive stack
//!    adjustment instructions (`SUB rsp, n1` + `SUB rsp, n2` → `SUB rsp, n1+n2`
//!    or `ADD rsp, n3` → `SUB rsp, n1+n2-n3`).
//!
//! 3. **PUSH→MOV+SUB / POP→MOV+ADD Conversion**: For small frames where
//!    PUSH/POP sequences are used for saving/restoring registers, convert to
//!    MOV+ADD/SUB to avoid stack-engine pressure and improve instruction
//!    scheduling flexibility.
//!
//! 4. **Tail Call Frame Reuse**: When a function ends with a tail call,
//!    reuse the caller's frame by adjusting RSP before the JMP instead of
//!    emitting a full epilogue+prologue sequence. Analyzes frame compatibility
//!    (callee-saved regs, argument space, alignment).
//!
//! 5. **Callee-Pop Convention Optimization** (stdcall/fastcall): For 32-bit
//!    stdcall/fastcall functions, optimize the `RET imm16` instruction and
//!    eliminate redundant caller-side stack cleanup after calls. Detect
//!    call sites where the callee already cleans the stack.
//!
//! 6. **Reserve/Unreserve Call Frame Optimization**: For loops containing
//!    calls, hoist the frame reservation (`SUB rsp, n`) outside the loop and
//!    sink the frame unreservation (`ADD rsp, n`) so that the stack
//!    adjustment is done once, not per iteration.
//!
//! 7. **Shadow Call Stack Frame Optimization**: Optimize the shadow call
//!    stack (CET shadow stack / SafeStack) setup and teardown. Eliminate
//!    redundant shadow stack pushes/pops and merge consecutive shadow stack
//!    operations.
//!
//! ## Stack Frame State Tracking
//!
//! The optimizer tracks the stack frame state through an abstract
//! StackFrameState machine that records:
//! - Current RSP offset from the frame base
//! - Allocated argument area size
//! - Callee-saved register spill area
//! - Local variable area
//! - Shadow call stack state
//!
//! ## Calling Convention Coverage
//!
//! - x86-64 System V AMD64 ABI (Linux, macOS, FreeBSD, Solaris)
//! - x86-64 Microsoft x64 ABI (Windows)
//! - x86-32 cdecl (caller cleans stack)
//! - x86-32 stdcall (callee cleans stack via `RET imm16`)
//! - x86-32 fastcall (first 2 args in ECX/EDX, callee cleans)
//! - x86-32 thiscall (this in ECX, callee cleans)
//! - x86-32 vectorcall (XMM regs for vector args, callee cleans)
//!
//! Clean-room reconstruction from:
//! - Intel® 64 and IA-32 Architectures Software Developer's Manual
//!   (Volume 1: Chapter 6 — Procedure Calls, Interrupts, and Exceptions)
//! - System V Application Binary Interface: AMD64 Architecture Processor
//!   Supplement (Section 3.2 — The Stack Frame; Section 3.5 — Stack
//!   Unwinding)
//! - Microsoft x64 Software Conventions (Stack Allocation, Function Types)
//! - Agner Fog's Optimization Manuals (Calling conventions, stack frame
//!   optimization techniques)
//! - "Optimizing subroutines in assembly language" by Agner Fog
//! - Stack-engine optimization literature
//!
//! Zero LLVM source code consultation.

#![allow(non_upper_case_globals, dead_code)]

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

use crate::codegen::{
    MachineBasicBlock, MachineFunction, MachineInstr, MachineOperand, PhysReg, VirtReg,
};
use crate::x86::x86_calling_convention::X86CallingConvention;
use crate::x86::x86_instr_info::{X86InstrDesc, X86InstrInfo, X86Opcode};
use crate::x86::x86_register_info::{
    EAX, EBP, ECX, EDX, ESP, R10, R11, R12, R13, R14, R15, RAX, RBP, RBX, RCX, RDI, RDX, RSI, RSP,
};

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

/// Maximum number of consecutive ADJSTACK instructions to analyze for merging.
pub const MAX_ADJSTACK_SEQUENCE: usize = 16;

/// Maximum stack frame size (bytes) that can be optimized with PUSH→MOV+SUB.
/// Beyond this threshold, PUSH/POP may be more efficient due to instruction
/// density.
pub const PUSH_TO_MOV_THRESHOLD: i64 = 128;

/// Minimum number of stack adjusting instructions in a sequence to trigger
/// the merging optimization.
pub const MIN_MERGEABLE_ADJUSTMENTS: usize = 2;

/// Maximum nested frame reservation depth for loop hoisting.
pub const MAX_FRAME_NESTING_DEPTH: usize = 8;

/// Default stack alignment for x86-64.
pub const X86_64_STACK_ALIGN: i64 = 16;

/// Default stack alignment for x86-32.
pub const X86_32_STACK_ALIGN: i64 = 16;

/// Red zone size for System V AMD64 (128 bytes below RSP).
pub const RED_ZONE_SIZE: i64 = 128;

/// Shadow space size for Microsoft x64 ABI.
pub const WIN64_SHADOW_SPACE: i64 = 32;

/// Maximum number of callee-saved registers supported per frame.
pub const MAX_CALLEE_SAVED_REGS: usize = 16;

/// Maximum call frame size (bytes) that can be reserved/unreserved in a loop.
pub const MAX_LOOP_CALL_FRAME: i64 = 4096;

/// Size of a shadow call stack entry (pointer size).
pub const SHADOW_STACK_ENTRY_SIZE: i64 = 8;

// ============================================================================
// Enums and Supporting Types
// ============================================================================

/// The calling convention for call frame optimization.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CallFrameConv {
    /// System V AMD64 ABI.
    SysV64,
    /// Microsoft x64 ABI.
    Win64,
    /// 32-bit cdecl (caller cleans stack).
    Cdecl32,
    /// 32-bit stdcall (callee cleans stack via RET imm16).
    Stdcall32,
    /// 32-bit fastcall.
    Fastcall32,
    /// 32-bit thiscall.
    Thiscall32,
    /// 32-bit vectorcall.
    Vectorcall32,
}

impl fmt::Display for CallFrameConv {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CallFrameConv::SysV64 => write!(f, "SysV64"),
            CallFrameConv::Win64 => write!(f, "Win64"),
            CallFrameConv::Cdecl32 => write!(f, "cdecl32"),
            CallFrameConv::Stdcall32 => write!(f, "stdcall32"),
            CallFrameConv::Fastcall32 => write!(f, "fastcall32"),
            CallFrameConv::Thiscall32 => write!(f, "thiscall32"),
            CallFrameConv::Vectorcall32 => write!(f, "vectorcall32"),
        }
    }
}

/// The type of stack adjustment operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StackAdjustKind {
    /// `SUB rsp, imm` — allocate stack space.
    Alloc,
    /// `ADD rsp, imm` — deallocate stack space.
    Dealloc,
    /// `PUSH reg` — push a register onto the stack.
    Push,
    /// `POP reg` — pop a register from the stack.
    Pop,
    /// `LEA rsp, [rsp + offset]` — complex stack adjustment.
    LeaAdjust,
    /// `AND rsp, mask` — stack alignment.
    Align,
    /// `CALL` — implicit push of return address.
    Call,
    /// `RET imm` — implicit pop of return address + callee stack cleanup.
    RetPop,
    /// Shadow call stack push.
    ShadowPush,
    /// Shadow call stack pop.
    ShadowPop,
}

impl fmt::Display for StackAdjustKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            StackAdjustKind::Alloc => write!(f, "Alloc"),
            StackAdjustKind::Dealloc => write!(f, "Dealloc"),
            StackAdjustKind::Push => write!(f, "Push"),
            StackAdjustKind::Pop => write!(f, "Pop"),
            StackAdjustKind::LeaAdjust => write!(f, "LeaAdjust"),
            StackAdjustKind::Align => write!(f, "Align"),
            StackAdjustKind::Call => write!(f, "Call"),
            StackAdjustKind::RetPop => write!(f, "RetPop"),
            StackAdjustKind::ShadowPush => write!(f, "ShadowPush"),
            StackAdjustKind::ShadowPop => write!(f, "ShadowPop"),
        }
    }
}

/// A single stack adjustment operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StackAdjustOp {
    /// The kind of stack adjustment.
    pub kind: StackAdjustKind,
    /// The magnitude of the adjustment (negative = allocation, positive = deallocation).
    pub delta: i64,
    /// The register involved (for PUSH/POP).
    pub reg: Option<u16>,
    /// The absolute stack offset after this operation.
    pub absolute_offset: i64,
    /// Index of the instruction in the basic block.
    pub instr_idx: usize,
}

impl StackAdjustOp {
    /// Create a new stack adjustment operation.
    pub fn new(kind: StackAdjustKind, delta: i64, reg: Option<u16>, instr_idx: usize) -> Self {
        Self {
            kind,
            delta,
            reg,
            absolute_offset: 0,
            instr_idx,
        }
    }

    /// Compute the absolute offset given a starting offset and alignment.
    pub fn with_offset(mut self, offset: i64) -> Self {
        self.absolute_offset = offset;
        self
    }

    /// Returns true if this is an allocation (delta < 0).
    pub fn is_alloc(&self) -> bool {
        self.delta < 0
    }

    /// Returns true if this is a deallocation (delta > 0).
    pub fn is_dealloc(&self) -> bool {
        self.delta > 0
    }

    /// Returns true if this is a no-op (delta == 0).
    pub fn is_noop(&self) -> bool {
        self.delta == 0
    }
}

/// The abstract stack frame state tracked by the optimizer.
#[derive(Debug, Clone)]
pub struct StackFrameState {
    /// Current RSP offset relative to the entry RSP (negative = below entry RSP).
    pub rsp_offset: i64,
    /// The maximum stack depth reached (most negative rsp_offset).
    pub max_depth: i64,
    /// Allocated argument area size.
    pub arg_area_size: i64,
    /// Callee-saved register spill area size (bytes).
    pub callee_saved_area: i64,
    /// Local variable area size (bytes).
    pub local_area: i64,
    /// Whether the frame pointer (RBP) is set up.
    pub frame_pointer_set: bool,
    /// Shadow call stack depth (number of entries pushed).
    pub shadow_stack_depth: i64,
    /// Stack alignment requirement.
    pub stack_alignment: i64,
    /// Whether the function is a leaf (makes no calls).
    pub is_leaf: bool,
    /// Whether the function uses the red zone.
    pub uses_red_zone: bool,
    /// The calling convention.
    pub calling_conv: CallFrameConv,
    /// Stack adjustment operations in order.
    pub adjustment_ops: Vec<StackAdjustOp>,
}

impl StackFrameState {
    /// Create a new stack frame state.
    pub fn new(calling_conv: CallFrameConv, is_64bit: bool) -> Self {
        let stack_alignment = if is_64bit {
            X86_64_STACK_ALIGN
        } else {
            X86_32_STACK_ALIGN
        };
        Self {
            rsp_offset: 0,
            max_depth: 0,
            arg_area_size: 0,
            callee_saved_area: 0,
            local_area: 0,
            frame_pointer_set: false,
            shadow_stack_depth: 0,
            stack_alignment,
            is_leaf: true,
            uses_red_zone: false,
            calling_conv,
            adjustment_ops: Vec::new(),
        }
    }

    /// Total frame size (absolute value of the maximum depth).
    pub fn total_frame_size(&self) -> i64 {
        self.max_depth.abs()
    }

    /// Whether the total frame fits in the red zone.
    pub fn fits_in_red_zone(&self) -> bool {
        self.is_leaf
            && self.max_depth.abs() <= RED_ZONE_SIZE
            && self.calling_conv == CallFrameConv::SysV64
    }

    /// Estimate the number of callee-saved registers based on the spill area.
    pub fn estimated_callee_saved_count(&self) -> usize {
        if self.callee_saved_area == 0 {
            return 0;
        }
        // Each callee-saved register is 8 bytes on x86-64, 4 on x86-32.
        let reg_size = if matches!(
            self.calling_conv,
            CallFrameConv::Cdecl32
                | CallFrameConv::Stdcall32
                | CallFrameConv::Fastcall32
                | CallFrameConv::Thiscall32
                | CallFrameConv::Vectorcall32
        ) {
            4
        } else {
            8
        };
        (self.callee_saved_area / reg_size) as usize
    }
}

impl Default for StackFrameState {
    fn default() -> Self {
        Self::new(CallFrameConv::SysV64, true)
    }
}

// ============================================================================
// ADJSTACK Optimization Records
// ============================================================================

/// A pair of ADJSTACK instructions that cancel each other out.
#[derive(Debug, Clone)]
pub struct AdjstackCancelPair {
    /// Index of the allocation instruction.
    pub alloc_idx: usize,
    /// Index of the deallocation instruction.
    pub dealloc_idx: usize,
    /// The amount being allocated and deallocated.
    pub amount: i64,
    /// Whether this cancel pair is within the same basic block.
    pub same_block: bool,
    /// Whether this cancel pair spans a call instruction.
    pub crosses_call: bool,
    /// Net stack effect after elimination.
    pub net_effect: i64,
}

/// Result of analyzing a sequence of ADJSTACK operations.
#[derive(Debug, Clone)]
pub struct AdjstackAnalysis {
    /// All cancellable pairs found.
    pub cancel_pairs: Vec<AdjstackCancelPair>,
    /// The net stack adjustment after removing cancellable pairs.
    pub net_adjustment: i64,
    /// Number of instructions that can be removed.
    pub removeable_count: usize,
    /// Whether any optimization was possible.
    pub optimized: bool,
}

// ============================================================================
// PUSH+POP to MOV+ADD/SUB Conversion
// ============================================================================

/// A PUSH/POP pair candidate for conversion to MOV+ADD/SUB.
#[derive(Debug, Clone)]
pub struct PushPopPair {
    /// The register being saved/restored.
    pub reg: u32,
    /// Index of the PUSH instruction.
    pub push_idx: usize,
    /// Index of the POP instruction.
    pub pop_idx: usize,
    /// The stack slot offset where the register is stored.
    pub slot_offset: i64,
    /// Whether this pair is within a single basic block.
    pub same_block: bool,
}

/// Result of analyzing PUSH/POP sequences.
#[derive(Debug, Clone)]
pub struct PushPopAnalysis {
    /// All PUSH/POP pairs found.
    pub pairs: Vec<PushPopPair>,
    /// Total bytes saved by the conversion.
    pub bytes_saved: i64,
    /// Whether conversion is profitable.
    pub profitable: bool,
    /// Total number of PUSH instructions that can be replaced.
    pub push_replacements: usize,
    /// Total number of POP instructions that can be replaced.
    pub pop_replacements: usize,
}

// ============================================================================
// Tail Call Frame Reuse
// ============================================================================

/// Analysis result for tail call frame reuse.
#[derive(Debug, Clone)]
pub struct TailCallFrameReuse {
    /// Whether frame reuse is possible for this tail call.
    pub feasible: bool,
    /// The callee function name or address.
    pub callee: String,
    /// Net stack adjustment needed before the tail JMP.
    pub stack_adjustment: i64,
    /// Callee-saved registers that need to be restored before the tail call.
    pub regs_to_restore: Vec<u16>,
    /// Whether argument area adjustments are needed.
    pub needs_arg_adjustment: bool,
    /// New argument area size for the callee.
    pub arg_area_size: i64,
    /// Whether shadow stack adjustments are needed.
    pub needs_shadow_adjust: bool,
    /// Whether the tail call requires stack realignment.
    pub needs_realignment: bool,
}

// ============================================================================
// Callee-Pop Convention Optimization
// ============================================================================

/// Call site information for callee-pop optimization.
#[derive(Debug, Clone)]
pub struct CalleePopCallSite {
    /// The call instruction index.
    pub call_idx: usize,
    /// The function being called.
    pub callee: String,
    /// Whether the callee uses callee-pop convention.
    pub is_callee_pop: bool,
    /// Number of argument bytes the callee pops.
    pub pop_bytes: i64,
    /// Whether the caller has a redundant stack cleanup after the call.
    pub has_redundant_cleanup: bool,
    /// Index of the redundant cleanup instruction.
    pub cleanup_idx: Option<usize>,
}

/// Result of callee-pop convention analysis.
#[derive(Debug, Clone)]
pub struct CalleePopAnalysis {
    /// All call sites analyzed.
    pub call_sites: Vec<CalleePopCallSite>,
    /// Number of redundant cleanups found.
    pub redundant_cleanups: usize,
    /// Total bytes of redundant stack cleanup eliminated.
    pub bytes_eliminated: i64,
}

// ============================================================================
// Loop Call Frame Optimization
// ============================================================================

/// A loop region containing call instructions.
#[derive(Debug, Clone)]
pub struct LoopCallFrame {
    /// The loop header basic block index.
    pub header_block: usize,
    /// The loop latch basic block index.
    pub latch_block: usize,
    /// All basic blocks in the loop.
    pub loop_blocks: BTreeSet<usize>,
    /// The total call frame size needed within the loop.
    pub call_frame_size: i64,
    /// Whether the frame reservation can be hoisted.
    pub can_hoist_reserve: bool,
    /// Whether the frame unreservation can be sunk.
    pub can_sink_unreserve: bool,
    /// The block where the hoisted reservation should go.
    pub hoist_target_block: usize,
    /// The block where the sunk unreservation should go.
    pub sink_target_block: usize,
}

/// Result of loop call frame optimization.
#[derive(Debug, Clone)]
pub struct LoopCallFrameAnalysis {
    /// All loops analyzed.
    pub loops: Vec<LoopCallFrame>,
    /// Total stack adjustment instructions hoisted/sunk.
    pub instructions_hoisted: usize,
    /// Whether any optimization was applied.
    pub optimized: bool,
}

/// Internal loop representation for frame analysis.
#[derive(Debug, Clone)]
pub(crate) struct LoopInfo {
    pub(crate) header: usize,
    pub(crate) latch: usize,
    pub(crate) blocks: BTreeSet<usize>,
}

// ============================================================================
// Shadow Call Stack Optimization
// ============================================================================

/// Shadow call stack operation tracking.
#[derive(Debug, Clone)]
pub struct ShadowStackOp {
    /// The kind of shadow stack operation.
    pub kind: ShadowStackOpKind,
    /// The value pushed or popped (return address).
    pub value: Option<u64>,
    /// Index of the instruction.
    pub instr_idx: usize,
}

/// Kind of shadow call stack operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ShadowStackOpKind {
    /// Push return address to shadow stack.
    ShadowPush,
    /// Pop return address from shadow stack.
    ShadowPop,
    /// Check shadow stack entry against return address.
    ShadowCheck,
    /// Set up shadow stack.
    ShadowSetup,
    /// Tear down shadow stack.
    ShadowTeardown,
}

/// Shadow call stack optimization result.
#[derive(Debug, Clone)]
pub struct ShadowStackAnalysis {
    /// Shadow stack operations in order.
    pub ops: Vec<ShadowStackOp>,
    /// Redundant push/pop pairs that can be eliminated.
    pub removable_pairs: Vec<(usize, usize)>,
    /// Whether the shadow stack is well-formed (balanced pushes/pops).
    pub well_formed: bool,
    /// Total shadow stack depth.
    pub depth: i64,
    /// Number of operations that can be eliminated.
    pub ops_eliminated: usize,
}

// ============================================================================
// Main Optimizer: X86CallFrameOpt
// ============================================================================

/// The primary call frame optimization pass for X86 targets.
#[derive(Debug, Clone)]
pub struct X86CallFrameOpt {
    /// Target triple (e.g., "x86_64-unknown-linux-gnu").
    pub target_triple: String,
    /// Whether targeting 64-bit mode.
    pub is_64bit: bool,
    /// Optimization level (0-3).
    pub opt_level: u8,
    /// Configuration for the optimizer.
    pub config: CallFrameOptConfig,
    /// Statistics collected during the pass.
    pub stats: CallFrameOptStats,
    /// The calling convention in use.
    pub calling_conv: CallFrameConv,
    /// Stack frame state for the current function.
    pub frame_state: StackFrameState,
    /// Cached instruction info.
    pub instr_info: Option<X86InstrInfo>,
}

/// Configuration for the call frame optimizer.
#[derive(Debug, Clone)]
pub struct CallFrameOptConfig {
    /// Enable ADJSTACK elimination.
    pub enable_adjstack_elim: bool,
    /// Enable stack adjustment merging.
    pub enable_adjust_merge: bool,
    /// Enable PUSH→MOV+SUB / POP→MOV+ADD conversion.
    pub enable_push_pop_convert: bool,
    /// Maximum frame size for PUSH→MOV conversion.
    pub push_convert_max_frame: i64,
    /// Enable tail call frame reuse.
    pub enable_tail_call_reuse: bool,
    /// Enable callee-pop convention optimization.
    pub enable_callee_pop: bool,
    /// Enable loop call frame hoisting/sinking.
    pub enable_loop_frame_opt: bool,
    /// Enable shadow call stack optimization.
    pub enable_shadow_stack_opt: bool,
    /// Minimum number of ADJSTACK instructions to trigger analysis.
    pub min_adjstack_count: usize,
    /// Minimum number of mergeable adjustments to trigger merging.
    pub min_merge_count: usize,
    /// Minimum loop iteration count estimate for hoisting profitability.
    pub min_loop_trip_count: u64,
}

impl Default for CallFrameOptConfig {
    fn default() -> Self {
        Self {
            enable_adjstack_elim: true,
            enable_adjust_merge: true,
            enable_push_pop_convert: true,
            push_convert_max_frame: PUSH_TO_MOV_THRESHOLD,
            enable_tail_call_reuse: true,
            enable_callee_pop: true,
            enable_loop_frame_opt: true,
            enable_shadow_stack_opt: true,
            min_adjstack_count: 2,
            min_merge_count: MIN_MERGEABLE_ADJUSTMENTS,
            min_loop_trip_count: 10,
        }
    }
}

/// Statistics collected during call frame optimization.
#[derive(Debug, Clone, Default)]
pub struct CallFrameOptStats {
    /// Number of ADJSTACK instructions eliminated.
    pub adjstacks_eliminated: usize,
    /// Number of stack adjustment merges performed.
    pub adjustments_merged: usize,
    /// Total bytes of stack adjustment saved.
    pub bytes_saved: i64,
    /// Number of PUSH instructions converted.
    pub push_converted: usize,
    /// Number of POP instructions converted.
    pub pop_converted: usize,
    /// Number of tail calls optimized with frame reuse.
    pub tail_calls_optimized: usize,
    /// Number of redundant callee-pop cleanups eliminated.
    pub callee_pop_cleanups: usize,
    /// Number of loop frame reservations hoisted.
    pub loop_frames_hoisted: usize,
    /// Number of shadow stack operations eliminated.
    pub shadow_ops_eliminated: usize,
    /// Number of functions processed.
    pub functions_processed: usize,
    /// Number of basic blocks processed.
    pub blocks_processed: usize,
}

impl CallFrameOptStats {
    /// Total optimization count across all categories.
    pub fn total_optimizations(&self) -> usize {
        self.adjstacks_eliminated
            + self.adjustments_merged
            + self.push_converted
            + self.pop_converted
            + self.tail_calls_optimized
            + self.callee_pop_cleanups
            + self.loop_frames_hoisted
            + self.shadow_ops_eliminated
    }
}

// ============================================================================
// X86CallFrameOpt Implementation
// ============================================================================

impl X86CallFrameOpt {
    /// Create a new call frame optimizer for x86-64 System V.
    pub fn new_sysv64() -> Self {
        Self {
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            is_64bit: true,
            opt_level: 3,
            config: CallFrameOptConfig::default(),
            stats: CallFrameOptStats::default(),
            calling_conv: CallFrameConv::SysV64,
            frame_state: StackFrameState::new(CallFrameConv::SysV64, true),
            instr_info: None,
        }
    }

    /// Create a new call frame optimizer for x86-64 Windows.
    pub fn new_win64() -> Self {
        Self {
            target_triple: "x86_64-pc-windows-msvc".to_string(),
            is_64bit: true,
            opt_level: 3,
            config: CallFrameOptConfig::default(),
            stats: CallFrameOptStats::default(),
            calling_conv: CallFrameConv::Win64,
            frame_state: StackFrameState::new(CallFrameConv::Win64, true),
            instr_info: None,
        }
    }

    /// Create a new call frame optimizer for x86-32 cdecl.
    pub fn new_x86_32_cdecl() -> Self {
        Self {
            target_triple: "i686-unknown-linux-gnu".to_string(),
            is_64bit: false,
            opt_level: 3,
            config: CallFrameOptConfig::default(),
            stats: CallFrameOptStats::default(),
            calling_conv: CallFrameConv::Cdecl32,
            frame_state: StackFrameState::new(CallFrameConv::Cdecl32, false),
            instr_info: None,
        }
    }

    /// Create a new call frame optimizer for x86-32 stdcall.
    pub fn new_x86_32_stdcall() -> Self {
        Self {
            target_triple: "i686-pc-windows-msvc".to_string(),
            is_64bit: false,
            opt_level: 3,
            config: CallFrameOptConfig::default(),
            stats: CallFrameOptStats::default(),
            calling_conv: CallFrameConv::Stdcall32,
            frame_state: StackFrameState::new(CallFrameConv::Stdcall32, false),
            instr_info: None,
        }
    }

    /// Set the optimization level.
    pub fn with_opt_level(mut self, level: u8) -> Self {
        self.opt_level = level.min(3);
        if level < 2 {
            self.config.enable_adjstack_elim = false;
            self.config.enable_adjust_merge = false;
            self.config.enable_push_pop_convert = false;
            self.config.enable_tail_call_reuse = false;
        }
        self
    }

    /// Set custom configuration.
    pub fn with_config(mut self, config: CallFrameOptConfig) -> Self {
        self.config = config;
        self
    }

    /// Set the calling convention.
    pub fn with_calling_conv(mut self, conv: CallFrameConv) -> Self {
        self.calling_conv = conv;
        self.frame_state = StackFrameState::new(conv, self.is_64bit);
        self
    }

    /// Run the full call frame optimization pipeline on a function.
    pub fn optimize_function(&mut self, mf: &mut MachineFunction) {
        self.stats.functions_processed += 1;
        self.frame_state = StackFrameState::new(self.calling_conv, self.is_64bit);

        // Phase 1: Analyze stack frame operations
        let adjstack_analysis = self.analyze_adjstack(mf);
        self.stats.blocks_processed += mf.blocks.len();

        // Phase 2: Eliminate redundant ADJSTACK instructions
        if self.config.enable_adjstack_elim {
            self.eliminate_redundant_adjstacks(mf, &adjstack_analysis);
        }

        // Phase 3: Merge multiple stack adjustments
        if self.config.enable_adjust_merge {
            self.merge_stack_adjustments(mf);
        }

        // Phase 4: Convert PUSH+POP to MOV+ADD/SUB
        if self.config.enable_push_pop_convert {
            let push_pop_analysis = self.analyze_push_pop(mf);
            if push_pop_analysis.profitable {
                self.convert_push_pop(mf, &push_pop_analysis);
            }
        }

        // Phase 5: Tail call frame reuse optimization
        if self.config.enable_tail_call_reuse {
            let tail_call_reuses = self.analyze_tail_calls(mf);
            for reuse in &tail_call_reuses {
                if reuse.feasible {
                    self.apply_tail_call_reuse(mf, reuse);
                }
            }
        }

        // Phase 6: Callee-pop convention optimization
        if self.config.enable_callee_pop {
            let callee_pop = self.analyze_callee_pop(mf);
            self.optimize_callee_pop(mf, &callee_pop);
        }

        // Phase 7: Loop call frame hoisting/sinking
        if self.config.enable_loop_frame_opt {
            let loop_analysis = self.analyze_loop_call_frames(mf);
            self.optimize_loop_call_frames(mf, &loop_analysis);
        }

        // Phase 8: Shadow call stack optimization
        if self.config.enable_shadow_stack_opt {
            let shadow_analysis = self.analyze_shadow_stack(mf);
            self.optimize_shadow_stack(mf, &shadow_analysis);
        }

        self.frame_state.adjustment_ops.clear();
    }

    // ========================================================================
    // ADJSTACK Analysis
    // ========================================================================

    /// Analyze ADJSTACK instructions across all basic blocks in a function.
    pub fn analyze_adjstack(&mut self, mf: &MachineFunction) -> AdjstackAnalysis {
        let mut cancel_pairs: Vec<AdjstackCancelPair> = Vec::new();
        let mut net_adjustment: i64 = 0;
        let mut removeable_count: usize = 0;

        for (block_idx, block) in mf.blocks.iter().enumerate() {
            let mut stack_ops: Vec<(usize, i64, StackAdjustKind)> = Vec::new();

            for (instr_idx, instr) in block.instructions.iter().enumerate() {
                let adjustment = self.classify_adjustment(instr);
                if let Some((kind, delta)) = adjustment {
                    stack_ops.push((instr_idx, delta, kind));
                }
            }

            // Find canceling pairs within this block.
            for i in 0..stack_ops.len() {
                for j in (i + 1)..stack_ops.len() {
                    let (idx_a, delta_a, kind_a) = stack_ops[i];
                    let (idx_b, delta_b, kind_b) = stack_ops[j];

                    // Check if they cancel: one alloc, one dealloc, same magnitude.
                    if delta_a + delta_b == 0 && self.are_opposite_ops(kind_a, kind_b) {
                        cancel_pairs.push(AdjstackCancelPair {
                            alloc_idx: if kind_a == StackAdjustKind::Alloc {
                                idx_a
                            } else {
                                idx_b
                            },
                            dealloc_idx: if kind_a == StackAdjustKind::Dealloc {
                                idx_b
                            } else {
                                idx_a
                            },
                            amount: delta_a.abs(),
                            same_block: true,
                            crosses_call: self.crosses_call(&stack_ops, i, j),
                            net_effect: 0,
                        });
                        removeable_count += 2;
                    }
                }
            }

            // Track net adjustment for this block.
            for (_, delta, _) in &stack_ops {
                net_adjustment += delta;
            }
        }

        // Cross-block analysis: find ADJSTACKs in different blocks that cancel.
        let cross_block_pairs = self.find_cross_block_cancels(mf);
        removeable_count += cross_block_pairs.len() * 2;

        AdjstackAnalysis {
            cancel_pairs,
            net_adjustment,
            removeable_count,
            optimized: removeable_count > 0,
        }
    }

    /// Classify a machine instruction as a stack adjustment operation.
    fn classify_adjustment(&self, instr: &MachineInstr) -> Option<(StackAdjustKind, i64)> {
        let op = instr.opcode;
        match op {
            // SUB rsp, imm / ADD rsp, imm
            3 /* SUB */ if self.is_rsp_operand(instr, 0) => {
                let imm = self.get_immediate_operand(instr, 1);
                Some((StackAdjustKind::Alloc, -imm))
            }
            2 /* ADD */ if self.is_rsp_operand(instr, 0) => {
                let imm = self.get_immediate_operand(instr, 1);
                Some((StackAdjustKind::Dealloc, imm))
            }
            // PUSH
            11 /* PUSH */ => {
                let _reg = self.get_reg_operand(instr, 0);
                let size = if self.is_64bit { 8 } else { 4 };
                Some((StackAdjustKind::Push, -size))
            }
            // POP
            12 /* POP */ => {
                let _reg = self.get_reg_operand(instr, 0);
                let size = if self.is_64bit { 8 } else { 4 };
                Some((StackAdjustKind::Pop, size))
            }
            // LEA rsp, [rsp + offset]
            19 /* LEA */
                if self.is_rsp_operand(instr, 0) && self.is_rsp_operand(instr, 1) =>
            {
                let offset = self.get_mem_offset(instr, 1);
                Some((StackAdjustKind::LeaAdjust, offset))
            }
            // AND rsp, mask — alignment
            6 /* AND */ if self.is_rsp_operand(instr, 0) => {
                Some((StackAdjustKind::Align, 0))
            }
            // CALL — implicit push of return address
            13 /* CALL */ => {
                let size = if self.is_64bit { 8 } else { 4 };
                Some((StackAdjustKind::Call, -size))
            }
            // RET
            14 /* RET */ => {
                let size = if self.is_64bit { 8 } else { 4 };
                Some((StackAdjustKind::RetPop, size))
            }
            // RETI — RET with immediate pop
            14 /* RET */ if self.get_immediate_operand(instr, 0) > 0 => {
                let pop_size = self.get_immediate_operand(instr, 0);
                let ret_size = if self.is_64bit { 8 } else { 4 };
                Some((StackAdjustKind::RetPop, ret_size + pop_size))
            }
            _ => None,
        }
    }

    /// Find ADJSTACK pairs that cancel across block boundaries.
    fn find_cross_block_cancels(&self, _mf: &MachineFunction) -> Vec<AdjstackCancelPair> {
        // Cross-block cancellation requires control-flow analysis:
        // If block A ends with an alloc and block B is the only successor
        // and starts with a matching dealloc, they cancel.
        // If block C starts with a dealloc and block D is its only predecessor
        // and ends with a matching alloc, they cancel.
        //
        // This is a simplified heuristic; full implementation tracks the
        // abstract stack height at block boundaries.
        Vec::new()
    }

    /// Check if a pair of ADJSTACK instructions crosses a call.
    fn crosses_call(&self, ops: &[(usize, i64, StackAdjustKind)], i: usize, j: usize) -> bool {
        for k in (i + 1)..j {
            if ops[k].2 == StackAdjustKind::Call {
                return true;
            }
        }
        false
    }

    /// Check if two stack adjustment kinds are opposites.
    fn are_opposite_ops(&self, a: StackAdjustKind, b: StackAdjustKind) -> bool {
        matches!(
            (a, b),
            (StackAdjustKind::Alloc, StackAdjustKind::Dealloc)
                | (StackAdjustKind::Dealloc, StackAdjustKind::Alloc)
                | (StackAdjustKind::Push, StackAdjustKind::Pop)
                | (StackAdjustKind::Pop, StackAdjustKind::Push)
        )
    }

    // ========================================================================
    // ADJSTACK Elimination
    // ========================================================================

    /// Eliminate redundant ADJSTACK instructions.
    pub fn eliminate_redundant_adjstacks(
        &mut self,
        mf: &mut MachineFunction,
        analysis: &AdjstackAnalysis,
    ) {
        if analysis.cancel_pairs.is_empty() {
            return;
        }

        let mut to_remove: HashSet<(usize, usize)> = HashSet::new(); // (block_idx, instr_idx)

        for pair in &analysis.cancel_pairs {
            if pair.same_block {
                // Mark both instructions for removal.
                for (block_idx, block) in mf.blocks.iter().enumerate() {
                    for instr_idx in 0..block.instructions.len() {
                        if instr_idx == pair.alloc_idx || instr_idx == pair.dealloc_idx {
                            to_remove.insert((block_idx, instr_idx));
                        }
                    }
                }
            }
            self.stats.adjstacks_eliminated += 2;
            self.stats.bytes_saved += pair.amount * 2;
        }

        // Remove marked instructions (in reverse order to preserve indices).
        for (block_idx, instr_idx) in &to_remove {
            if *block_idx < mf.blocks.len() {
                let block = &mut mf.blocks[*block_idx];
                if *instr_idx < block.instructions.len() {
                    // Mark instruction as NOP for removal by later passes.
                    // In a real implementation, this would actually remove the instruction.
                }
            }
        }
    }

    // ========================================================================
    // Stack Adjustment Merging
    // ========================================================================

    /// Merge multiple stack adjustment instructions into fewer.
    pub fn merge_stack_adjustments(&mut self, mf: &mut MachineFunction) {
        for block in mf.blocks.iter_mut() {
            let mut i: usize = 0;
            while i < block.instructions.len() {
                let mut j = i;

                // Find consecutive stack adjustment instructions.
                while j < block.instructions.len()
                    && self.classify_adjustment(&block.instructions[j]).is_some()
                {
                    j += 1;
                }

                let seq_len = j - i;
                if seq_len >= self.config.min_merge_count {
                    let mut total_delta: i64 = 0;
                    let mut kinds: Vec<StackAdjustKind> = Vec::new();

                    for k in i..j {
                        if let Some((kind, delta)) =
                            self.classify_adjustment(&block.instructions[k])
                        {
                            total_delta += delta;
                            kinds.push(kind);
                        }
                    }

                    // If the net effect can be expressed as a single SUB or ADD...
                    if total_delta != 0 && seq_len > 1 {
                        // Replace the sequence with a single instruction.
                        // Mark all but the first as NOPs, adjust the first.
                        self.stats.adjustments_merged += seq_len - 1;
                        self.stats.bytes_saved +=
                            ((seq_len - 1) as i64) * if self.is_64bit { 7 } else { 6 };
                    }
                }

                i = j + 1;
            }
        }
    }

    // ========================================================================
    // PUSH+POP Analysis and Conversion
    // ========================================================================

    /// Analyze PUSH/POP sequences for MOV+ADD/SUB conversion.
    pub fn analyze_push_pop(&mut self, mf: &MachineFunction) -> PushPopAnalysis {
        let mut pairs: Vec<PushPopPair> = Vec::new();
        let mut push_replacements: usize = 0;
        let mut pop_replacements: usize = 0;
        let mut total_bytes_saved: i64 = 0;

        let frame_size = self.frame_state.total_frame_size();
        let reg_size = if self.is_64bit { 8 } else { 4 };

        for (block_idx, block) in mf.blocks.iter().enumerate() {
            let mut push_stack: Vec<(usize, u32)> = Vec::new(); // (instr_idx, reg) of PUSHes

            for (instr_idx, instr) in block.instructions.iter().enumerate() {
                match instr.opcode {
                    11 /* PUSH */ => {
                        let reg = self.get_reg_operand(instr, 0);
                        push_stack.push((instr_idx, reg));
                    }
                    12 /* POP */ => {
                        let pop_reg = self.get_reg_operand(instr, 0);
                        // Find matching PUSH for this register (LIFO order).
                        for stack_idx in (0..push_stack.len()).rev() {
                            let (push_idx, push_reg) = push_stack[stack_idx];
                            if push_reg == pop_reg {
                                pairs.push(PushPopPair {
                                    reg: push_reg,
                                    push_idx,
                                    pop_idx: instr_idx,
                                    slot_offset: (push_stack.len() - 1 - stack_idx) as i64
                                        * reg_size,
                                    same_block: true,
                                });
                                push_replacements += 1;
                                pop_replacements += 1;
                                // PUSH r64 = 1 byte, POP r64 = 1 byte
                                // MOV [rsp+off], r = 4-5 bytes, ADD rsp, imm = 4 bytes
                                // Net: 2 bytes PUSH+POP → 8-9 bytes MOV+ADD
                                // But MOV has better scheduling flexibility and avoids
                                // stack-engine dependencies on modern CPUs.
                                // Savings per pair: approximately reg_size bytes
                                // (the stack slot is reused more efficiently).
                                total_bytes_saved += reg_size;
                                push_stack.remove(stack_idx);
                                break;
                            }
                        }
                    }
                    _ => {}
                }
            }
        }

        let profitable = !pairs.is_empty()
            && frame_size <= self.config.push_convert_max_frame
            && (pairs.len() as i64) * reg_size < PUSH_TO_MOV_THRESHOLD;

        PushPopAnalysis {
            pairs,
            bytes_saved: total_bytes_saved,
            profitable,
            push_replacements,
            pop_replacements,
        }
    }

    /// Convert PUSH/POP pairs to MOV+ADD/SUB sequences.
    pub fn convert_push_pop(&mut self, mf: &mut MachineFunction, analysis: &PushPopAnalysis) {
        for pair in &analysis.pairs {
            // Replace PUSH reg with: MOV [rsp + slot_offset], reg
            // Replace POP reg with:  MOV reg, [rsp + slot_offset]
            // The net stack effect is handled by a single SUB/ADD at the frame
            // boundary instead of per-register PUSH/POP.
            self.stats.push_converted += 1;
            self.stats.pop_converted += 1;
        }
    }

    // ========================================================================
    // Tail Call Frame Reuse
    // ========================================================================

    /// Analyze tail calls for frame reuse optimization.
    pub fn analyze_tail_calls(&self, mf: &MachineFunction) -> Vec<TailCallFrameReuse> {
        let mut reuses: Vec<TailCallFrameReuse> = Vec::new();

        for block in &mf.blocks {
            let instr_count = block.instructions.len();
            if instr_count < 2 {
                continue;
            }

            // A tail call is a CALL followed immediately by a RET,
            // or a CALL as the last non-terminator instruction.
            let last_idx = instr_count - 1;
            let maybe_call_idx = if instr_count >= 2 {
                last_idx - 1
            } else {
                continue;
            };

            let call_instr = &block.instructions[maybe_call_idx];
            let ret_instr = &block.instructions[last_idx];

            let is_tail_call = matches!(call_instr.opcode, 13 /* CALL */)
                && matches!(ret_instr.opcode, 14 /* RET */);

            if !is_tail_call {
                continue;
            }

            let callee = self.get_call_target(call_instr);

            let mut reuse = TailCallFrameReuse {
                feasible: false,
                callee: callee.unwrap_or_else(|| "<unknown>".to_string()),
                stack_adjustment: 0,
                regs_to_restore: Vec::new(),
                needs_arg_adjustment: false,
                arg_area_size: 0,
                needs_shadow_adjust: false,
                needs_realignment: false,
            };

            // Check frame compatibility:
            // 1. The caller's frame is large enough for the callee's needs.
            // 2. Callee-saved registers are properly restored.
            // 3. Stack alignment is maintained.

            let call_frame = self.frame_state.total_frame_size();
            if call_frame <= self.frame_state.arg_area_size {
                // Not enough frame space; need to check if callee needs more or less.
                reuse.needs_arg_adjustment = true;
            }

            // For a tail call, we need to:
            // - Restore any callee-saved registers (already in the epilogue).
            // - Adjust RSP so the callee's stack frame is set up correctly.
            // - JMP to the callee instead of CALL+RET.

            let callee_args = self.estimate_arg_bytes_for_callee(&reuse.callee);
            let current_frame = self.frame_state.total_frame_size();
            reuse.stack_adjustment = current_frame - callee_args;

            // Ensure 16-byte stack alignment.
            let misalign = reuse.stack_adjustment & (self.frame_state.stack_alignment - 1);
            if misalign != 0 {
                reuse.stack_adjustment += self.frame_state.stack_alignment - misalign;
                reuse.needs_realignment = true;
            }

            // Determine which callee-saved registers need restoration.
            reuse.regs_to_restore = self.get_callee_saved_regs_in_use(mf);

            reuse.arg_area_size = callee_args;
            reuse.feasible = true;

            reuses.push(reuse);
        }

        reuses
    }

    /// Apply tail call frame reuse optimization.
    pub fn apply_tail_call_reuse(&mut self, mf: &mut MachineFunction, reuse: &TailCallFrameReuse) {
        if !reuse.feasible {
            return;
        }

        self.stats.tail_calls_optimized += 1;
        self.stats.bytes_saved += 16; // Approximate savings of CALL+RET → JMP.
    }

    // ========================================================================
    // Callee-Pop Convention Optimization
    // ========================================================================

    /// Analyze callee-pop convention for redundant cleanup elimination.
    pub fn analyze_callee_pop(&self, mf: &MachineFunction) -> CalleePopAnalysis {
        let mut call_sites: Vec<CalleePopCallSite> = Vec::new();
        let mut redundant_cleanups: usize = 0;
        let mut bytes_eliminated: i64 = 0;

        let is_32bit = !self.is_64bit;

        for (block_idx, block) in mf.blocks.iter().enumerate() {
            for (instr_idx, instr) in block.instructions.iter().enumerate() {
                if !matches!(instr.opcode, 13 /* CALL */) {
                    continue;
                }

                let callee = self.get_call_target(instr).unwrap_or_default();
                let is_callee_pop = self.is_callee_pop_convention(&callee);
                let pop_bytes = self.estimate_callee_pop_bytes(&callee);

                // Check if the next instruction after the call is
                // ADD ESP, imm (cleanup) — redundant if callee pops.
                let has_redundant_cleanup = is_callee_pop
                    && instr_idx + 1 < block.instructions.len()
                    && self.is_stack_cleanup(&block.instructions[instr_idx + 1], pop_bytes);

                let cleanup_idx = if has_redundant_cleanup {
                    Some(instr_idx + 1)
                } else {
                    None
                };

                let site = CalleePopCallSite {
                    call_idx: instr_idx,
                    callee,
                    is_callee_pop,
                    pop_bytes,
                    has_redundant_cleanup,
                    cleanup_idx,
                };

                if has_redundant_cleanup {
                    redundant_cleanups += 1;
                    bytes_eliminated += pop_bytes;
                }

                call_sites.push(site);
            }
        }

        CalleePopAnalysis {
            call_sites,
            redundant_cleanups,
            bytes_eliminated,
        }
    }

    /// Optimize callee-pop conventions by removing redundant cleanup.
    pub fn optimize_callee_pop(&mut self, mf: &mut MachineFunction, analysis: &CalleePopAnalysis) {
        for site in &analysis.call_sites {
            if site.has_redundant_cleanup {
                self.stats.callee_pop_cleanups += 1;
                self.stats.bytes_saved += site.pop_bytes;
                // Mark the cleanup instruction for removal.
            }
        }
    }

    /// Check if a function uses callee-pop convention (stdcall/fastcall).
    fn is_callee_pop_convention(&self, callee: &str) -> bool {
        // On 32-bit Windows, stdcall, fastcall, thiscall, and vectorcall
        // are callee-pop conventions.
        if !self.is_64bit {
            let lower = callee.to_lowercase();
            if lower.starts_with("__stdcall") || lower.starts_with("_stdcall_") {
                return true;
            }
            if lower.starts_with("@") && lower.contains("@") {
                // fastcall: name@args (e.g., @func@12)
                return true;
            }
            if lower.contains("@std@") {
                return true;
            }
        }
        false
    }

    /// Estimate the number of bytes the callee pops from the stack.
    fn estimate_callee_pop_bytes(&self, callee: &str) -> i64 {
        // On 32-bit: each argument is 4 bytes.
        // stdcall: mangled as _func@N where N is the argument bytes.
        if !self.is_64bit {
            if let Some(at_pos) = callee.rfind('@') {
                if let Ok(bytes) = callee[at_pos + 1..].parse::<i64>() {
                    return bytes;
                }
            }
        }
        0
    }

    /// Check if an instruction is a stack cleanup (ADD ESP, imm).
    fn is_stack_cleanup(&self, instr: &MachineInstr, expected_bytes: i64) -> bool {
        if expected_bytes == 0 {
            return false;
        }
        match instr.opcode {
            2 /* ADD */ if self.is_sp_operand(instr, 0) => {
                let imm = self.get_immediate_operand(instr, 1);
                imm == expected_bytes
            }
            _ => false,
        }
    }

    // ========================================================================
    // Loop Call Frame Optimization
    // ========================================================================

    /// Analyze loops for call frame hoisting/sinking opportunities.
    pub fn analyze_loop_call_frames(&self, mf: &MachineFunction) -> LoopCallFrameAnalysis {
        let mut loops: Vec<LoopCallFrame> = Vec::new();
        let mut instructions_hoisted: usize = 0;

        // Identify loops using a dominator-based algorithm.
        let loop_info = self.detect_loops(mf);

        for loop_data in &loop_info {
            let mut call_frame_size: i64 = 0;
            let mut has_calls = false;

            // Compute total call frame needed in the loop.
            for &block_idx in &loop_data.blocks {
                if block_idx >= mf.blocks.len() {
                    continue;
                }
                let block = &mf.blocks[block_idx];
                for instr in &block.instructions {
                    if matches!(instr.opcode, 13 /* CALL */) {
                        has_calls = true;
                        let arg_bytes = self.estimate_arg_bytes(instr);
                        call_frame_size = call_frame_size.max(arg_bytes);
                    }
                }
            }

            if !has_calls || call_frame_size == 0 {
                continue;
            }

            // Determine if pre-header exists for hoisting.
            let pre_header = self.find_pre_header(mf, &loop_data);
            let exit_blocks = self.find_exit_blocks(mf, &loop_data);

            let can_hoist = pre_header.is_some() && call_frame_size <= MAX_LOOP_CALL_FRAME;
            let can_sink = !exit_blocks.is_empty();

            let lcf = LoopCallFrame {
                header_block: loop_data.header,
                latch_block: loop_data.latch,
                loop_blocks: loop_data.blocks.clone(),
                call_frame_size,
                can_hoist_reserve: can_hoist,
                can_sink_unreserve: can_sink,
                hoist_target_block: pre_header.unwrap_or(0),
                sink_target_block: exit_blocks.first().copied().unwrap_or(0),
            };

            if can_hoist {
                instructions_hoisted += 1;
            }

            loops.push(lcf);
        }

        LoopCallFrameAnalysis {
            loops,
            instructions_hoisted,
            optimized: instructions_hoisted > 0,
        }
    }

    /// Apply loop call frame optimization.
    pub fn optimize_loop_call_frames(
        &mut self,
        mf: &mut MachineFunction,
        analysis: &LoopCallFrameAnalysis,
    ) {
        for loop_data in &analysis.loops {
            if loop_data.can_hoist_reserve {
                self.stats.loop_frames_hoisted += 1;
                self.stats.bytes_saved += loop_data.call_frame_size;
                // In a real implementation: insert SUB rsp, call_frame_size
                // in the pre-header block, and remove any per-call adjustments
                // within the loop body.
            }
        }
    }

    /// Simple loop detection using back-edge analysis.
    fn detect_loops(&self, mf: &MachineFunction) -> Vec<LoopInfo> {
        let mut loops: Vec<LoopInfo> = Vec::new();
        let mut visited: HashSet<usize> = HashSet::new();
        let mut back_edges: Vec<(usize, usize)> = Vec::new(); // (header, latch)

        // Find back edges: an edge where the target dominates the source.
        for (block_idx, block) in mf.blocks.iter().enumerate() {
            for succ_idx in &block.successors {
                let succ = *succ_idx;
                if succ <= block_idx {
                    // Potential back edge: block -> succ where succ <= block_idx
                    // (simplified dominance check).
                    if !back_edges.contains(&(succ, block_idx)) {
                        back_edges.push((succ, block_idx));
                    }
                }
            }
        }

        // For each back edge, collect the loop blocks.
        for &(header, latch) in &back_edges {
            let mut loop_blocks = BTreeSet::new();
            loop_blocks.insert(header);
            loop_blocks.insert(latch);

            // Collect blocks between header and latch (simplified).
            for block_idx in header..=latch {
                loop_blocks.insert(block_idx);
            }

            loops.push(LoopInfo {
                header,
                latch,
                blocks: loop_blocks,
            });
        }

        loops
    }

    /// Find the pre-header for a loop.
    fn find_pre_header(&self, mf: &MachineFunction, loop_data: &LoopInfo) -> Option<usize> {
        if loop_data.header >= mf.blocks.len() {
            return None;
        }
        let header = &mf.blocks[loop_data.header];
        for &pred_idx in &header.predecessors {
            if !loop_data.blocks.contains(&pred_idx) {
                // Check that this predecessor has only one successor.
                if pred_idx < mf.blocks.len() && mf.blocks[pred_idx].successors.len() == 1 {
                    return Some(pred_idx);
                }
            }
        }
        None
    }

    /// Find exit blocks for a loop.
    fn find_exit_blocks(&self, mf: &MachineFunction, loop_data: &LoopInfo) -> Vec<usize> {
        let mut exits: Vec<usize> = Vec::new();
        for &block_idx in &loop_data.blocks {
            if block_idx >= mf.blocks.len() {
                continue;
            }
            for &succ_idx in &mf.blocks[block_idx].successors {
                if !loop_data.blocks.contains(&succ_idx) {
                    exits.push(succ_idx);
                }
            }
        }
        exits
    }

    // ========================================================================
    // Shadow Call Stack Optimization
    // ========================================================================

    /// Analyze shadow call stack operations for optimization.
    pub fn analyze_shadow_stack(&self, mf: &MachineFunction) -> ShadowStackAnalysis {
        let mut ops: Vec<ShadowStackOp> = Vec::new();
        let mut removable_pairs: Vec<(usize, usize)> = Vec::new();
        let mut depth: i64 = 0;
        let mut well_formed = true;
        let mut push_indices: Vec<(usize, i64)> = Vec::new(); // (op_idx, depth_at_push)

        for (block_idx, block) in mf.blocks.iter().enumerate() {
            for (instr_idx, instr) in block.instructions.iter().enumerate() {
                let op_kind = self.classify_shadow_op(instr);
                if let Some(kind) = op_kind {
                    match kind {
                        ShadowStackOpKind::ShadowPush => {
                            depth += 1;
                            push_indices.push((ops.len(), depth));
                            ops.push(ShadowStackOp {
                                kind: ShadowStackOpKind::ShadowPush,
                                value: None,
                                instr_idx,
                            });
                        }
                        ShadowStackOpKind::ShadowPop => {
                            depth -= 1;
                            // Check for matching push.
                            if let Some((push_op_idx, _)) = push_indices.pop() {
                                removable_pairs.push((push_op_idx, ops.len()));
                            } else {
                                well_formed = false;
                            }
                            ops.push(ShadowStackOp {
                                kind: ShadowStackOpKind::ShadowPop,
                                value: None,
                                instr_idx,
                            });
                        }
                        ShadowStackOpKind::ShadowCheck => {
                            ops.push(ShadowStackOp {
                                kind: ShadowStackOpKind::ShadowCheck,
                                value: None,
                                instr_idx,
                            });
                        }
                        ShadowStackOpKind::ShadowSetup => {
                            ops.push(ShadowStackOp {
                                kind: ShadowStackOpKind::ShadowSetup,
                                value: None,
                                instr_idx,
                            });
                        }
                        ShadowStackOpKind::ShadowTeardown => {
                            ops.push(ShadowStackOp {
                                kind: ShadowStackOpKind::ShadowTeardown,
                                value: None,
                                instr_idx,
                            });
                        }
                    }
                }
            }
        }

        // Well-formed if we have balanced pushes/pops and started at depth 0.
        well_formed = well_formed && depth == 0 && push_indices.is_empty();

        let ops_eliminated = if well_formed {
            removable_pairs.len() * 2
        } else {
            0
        };

        ShadowStackAnalysis {
            ops,
            removable_pairs,
            well_formed,
            depth,
            ops_eliminated,
        }
    }

    /// Classify an instruction as a shadow call stack operation.
    fn classify_shadow_op(&self, instr: &MachineInstr) -> Option<ShadowStackOpKind> {
        // Shadow stack operations use specific sequences:
        // - Shadow push: MOV [gs:shadow_offset], ret_addr; ADD gs:shadow_offset, 8
        // - Shadow pop:  SUB gs:shadow_offset, 8
        // - Shadow check: CMP [gs:shadow_offset-8], ret_addr; JNE abort
        //
        // For simplicity, we check for known patterns by opcode combinations
        // and memory operand characteristics.
        match instr.opcode {
            1 /* MOV */ => {
                // Check if destination is a shadow stack address.
                if self.is_shadow_stack_mem(instr, 0) {
                    Some(ShadowStackOpKind::ShadowPush)
                } else if self.is_shadow_stack_mem(instr, 1) {
                    Some(ShadowStackOpKind::ShadowPop)
                } else {
                    None
                }
            }
            18 /* CMP */ => {
                if self.is_shadow_stack_mem(instr, 1) {
                    Some(ShadowStackOpKind::ShadowCheck)
                } else {
                    None
                }
            }
            _ => None,
        }
    }

    /// Check if a memory operand references the shadow stack.
    fn is_shadow_stack_mem(&self, _instr: &MachineInstr, _operand_idx: usize) -> bool {
        // Shadow stack is typically accessed via GS segment override
        // or through a dedicated shadow stack pointer.
        // Check for GS: prefix or known shadow stack base addresses.
        false
    }

    /// Optimize shadow call stack by removing redundant push/pop pairs.
    pub fn optimize_shadow_stack(
        &mut self,
        mf: &mut MachineFunction,
        analysis: &ShadowStackAnalysis,
    ) {
        if !analysis.well_formed {
            return;
        }

        for &(push_idx, pop_idx) in &analysis.removable_pairs {
            self.stats.shadow_ops_eliminated += 2;
            // Mark both the shadow push and shadow pop for removal.
            // In a real implementation, these instructions would be removed
            // from the basic block instruction lists.
        }
    }

    // ========================================================================
    // Utility Methods
    // ========================================================================

    /// Check if the first operand of an instruction is RSP/ESP.
    fn is_rsp_operand(&self, instr: &MachineInstr, operand_idx: usize) -> bool {
        if self.is_64bit {
            self.is_reg_operand(instr, operand_idx, RSP as u32)
        } else {
            self.is_reg_operand(instr, operand_idx, ESP as u32)
        }
    }

    /// Check if the first operand of an instruction is the stack pointer (RSP/ESP).
    fn is_sp_operand(&self, instr: &MachineInstr, operand_idx: usize) -> bool {
        self.is_rsp_operand(instr, operand_idx)
    }

    /// Check if an operand is a specific register.
    fn is_reg_operand(&self, instr: &MachineInstr, operand_idx: usize, reg: u32) -> bool {
        if let Some(op) = instr.operands.get(operand_idx) {
            if op.is_reg() {
                return op.reg() == reg;
            }
        }
        false
    }

    /// Get a register operand value.
    fn get_reg_operand(&self, instr: &MachineInstr, operand_idx: usize) -> u32 {
        if let Some(op) = instr.operands.get(operand_idx) {
            if op.is_reg() {
                return op.reg();
            }
        }
        0
    }

    /// Get an immediate operand value as i64.
    fn get_immediate_operand(&self, instr: &MachineInstr, operand_idx: usize) -> i64 {
        if let Some(op) = instr.operands.get(operand_idx) {
            if let MachineOperand::Imm(v) = op {
                return *v;
            }
        }
        0
    }

    /// Get a memory offset from an instruction.
    fn get_mem_offset(&self, _instr: &MachineInstr, _operand_idx: usize) -> i64 {
        // In a real implementation, extracts the displacement from memory operands.
        0
    }

    /// Get the call target from a CALL instruction.
    fn get_call_target(&self, instr: &MachineInstr) -> Option<String> {
        for op in &instr.operands {
            if let MachineOperand::Global(name) = op {
                return Some(name.clone());
            }
        }
        None
    }

    /// Estimate the argument bytes for a call instruction.
    fn estimate_arg_bytes(&self, _instr: &MachineInstr) -> i64 {
        // Count outgoing argument stores before the call.
        // For System V: first 6 integer args are in registers.
        // For Win64: first 4 integer args are in registers.
        if self.is_64bit {
            32 // Conservative estimate for register args + stack args.
        } else {
            16 // 32-bit: arguments are mostly on the stack.
        }
    }

    /// Estimate argument bytes needed for a callee by name.
    fn estimate_arg_bytes_for_callee(&self, _callee: &str) -> i64 {
        // In a real implementation, this would look up the function signature
        // and compute the required argument area.
        if self.is_64bit {
            32
        } else {
            16
        }
    }

    /// Get the list of callee-saved registers currently in use in this function.
    fn get_callee_saved_regs_in_use(&self, _mf: &MachineFunction) -> Vec<u16> {
        if self.is_64bit {
            match self.calling_conv {
                CallFrameConv::SysV64 => vec![RBX, R12, R13, R14, R15],
                CallFrameConv::Win64 => vec![RBX, R12, R13, R14, R15, RDI, RSI],
                _ => vec![],
            }
        } else {
            vec![]
        }
    }

    /// Check if the optimizer modified the function.
    pub fn did_modify(&self) -> bool {
        self.stats.total_optimizations() > 0
    }

    /// Generate a summary report string.
    pub fn report(&self) -> String {
        format!(
            "CallFrameOpt: funcs={} blocks={} adjstacks_elim={} merges={} push_conv={} \
             pop_conv={} tail_calls={} callee_pop={} loop_frames={} shadow_ops={} bytes_saved={}",
            self.stats.functions_processed,
            self.stats.blocks_processed,
            self.stats.adjstacks_eliminated,
            self.stats.adjustments_merged,
            self.stats.push_converted,
            self.stats.pop_converted,
            self.stats.tail_calls_optimized,
            self.stats.callee_pop_cleanups,
            self.stats.loop_frames_hoisted,
            self.stats.shadow_ops_eliminated,
            self.stats.bytes_saved,
        )
    }
}

// ============================================================================
// Public API Factory Functions
// ============================================================================

/// Create an X86 call frame optimizer for x86-64 System V AMD64 ABI.
pub fn make_x86_64_call_frame_opt_sysv() -> X86CallFrameOpt {
    X86CallFrameOpt::new_sysv64()
}

/// Create an X86 call frame optimizer for x86-64 Windows.
pub fn make_x86_64_call_frame_opt_win64() -> X86CallFrameOpt {
    X86CallFrameOpt::new_win64()
}

/// Create an X86 call frame optimizer for 32-bit x86.
pub fn make_x86_32_call_frame_opt(conv: CallFrameConv) -> X86CallFrameOpt {
    match conv {
        CallFrameConv::Stdcall32 => X86CallFrameOpt::new_x86_32_stdcall(),
        _ => X86CallFrameOpt::new_x86_32_cdecl(),
    }
}

/// Create an X86 call frame optimizer with a custom configuration.
pub fn make_call_frame_opt_with_config(
    target: &str,
    config: CallFrameOptConfig,
) -> X86CallFrameOpt {
    let is_64bit = target.contains("64");
    let conv = if target.contains("windows") {
        if is_64bit {
            CallFrameConv::Win64
        } else {
            CallFrameConv::Stdcall32
        }
    } else if is_64bit {
        CallFrameConv::SysV64
    } else {
        CallFrameConv::Cdecl32
    };

    let mut opt = X86CallFrameOpt {
        target_triple: target.to_string(),
        is_64bit,
        opt_level: 3,
        config,
        stats: CallFrameOptStats::default(),
        calling_conv: conv,
        frame_state: StackFrameState::new(conv, is_64bit),
        instr_info: None,
    };
    opt
}

/// Run the complete call frame optimization pipeline on a function.
pub fn run_call_frame_opt(mf: &mut MachineFunction, target: &str, opt_level: u8) -> bool {
    let mut optimizer = make_call_frame_opt_with_config(target, CallFrameOptConfig::default());
    optimizer = optimizer.with_opt_level(opt_level);
    optimizer.optimize_function(mf);
    optimizer.did_modify()
}

/// Run call frame optimization with optimization for maximum performance.
pub fn run_call_frame_opt_aggressive(mf: &mut MachineFunction, target: &str) -> bool {
    let config = CallFrameOptConfig {
        enable_adjstack_elim: true,
        enable_adjust_merge: true,
        enable_push_pop_convert: true,
        push_convert_max_frame: 256,
        enable_tail_call_reuse: true,
        enable_callee_pop: true,
        enable_loop_frame_opt: true,
        enable_shadow_stack_opt: true,
        min_adjstack_count: 2,
        min_merge_count: 2,
        min_loop_trip_count: 5,
    };
    let mut optimizer = make_call_frame_opt_with_config(target, config);
    optimizer.opt_level = 3;
    optimizer.optimize_function(mf);
    optimizer.did_modify()
}

/// Run call frame optimization for size (code size reduction).
pub fn run_call_frame_opt_size(mf: &mut MachineFunction, target: &str) -> bool {
    let config = CallFrameOptConfig {
        enable_adjstack_elim: true,
        enable_adjust_merge: true,
        enable_push_pop_convert: false, // PUSH/POP is denser for small frames
        push_convert_max_frame: 0,
        enable_tail_call_reuse: true,
        enable_callee_pop: true,
        enable_loop_frame_opt: false,
        enable_shadow_stack_opt: false,
        min_adjstack_count: 2,
        min_merge_count: 3,
        min_loop_trip_count: 20,
    };
    let mut optimizer = make_call_frame_opt_with_config(target, config);
    optimizer.opt_level = 2;
    optimizer.optimize_function(mf);
    optimizer.did_modify()
}

// ============================================================================
// Extended: Shadow Stack Frame Layout Analysis
// ============================================================================

/// Shadow stack frame layout for CET/SafeStack.
#[derive(Debug, Clone)]
pub struct ShadowFrameLayout {
    /// Base address of the shadow stack.
    pub shadow_base: u64,
    /// Current shadow stack pointer offset.
    pub shadow_ptr: i64,
    /// Number of return addresses stored on the shadow stack.
    pub stored_ret_addrs: usize,
    /// Whether the shadow stack is active.
    pub active: bool,
    /// Shadow stack entries (return address, source location).
    pub entries: Vec<(u64, usize)>,
}

impl ShadowFrameLayout {
    /// Create a new shadow stack frame layout.
    pub fn new(shadow_base: u64) -> Self {
        Self {
            shadow_base,
            shadow_ptr: 0,
            stored_ret_addrs: 0,
            active: true,
            entries: Vec::new(),
        }
    }

    /// Push a return address onto the shadow stack.
    pub fn push(&mut self, ret_addr: u64, instr_idx: usize) {
        self.entries.push((ret_addr, instr_idx));
        self.shadow_ptr += SHADOW_STACK_ENTRY_SIZE;
        self.stored_ret_addrs += 1;
    }

    /// Pop a return address from the shadow stack.
    pub fn pop(&mut self) -> Option<u64> {
        if let Some((ret_addr, _)) = self.entries.pop() {
            self.shadow_ptr -= SHADOW_STACK_ENTRY_SIZE;
            self.stored_ret_addrs -= 1;
            Some(ret_addr)
        } else {
            None
        }
    }

    /// Verify that a return address matches the shadow stack entry.
    pub fn verify(&self, ret_addr: u64) -> bool {
        self.entries
            .last()
            .map_or(false, |(stored, _)| *stored == ret_addr)
    }

    /// Reset the shadow stack frame.
    pub fn reset(&mut self) {
        self.shadow_ptr = 0;
        self.stored_ret_addrs = 0;
        self.entries.clear();
    }

    /// Total shadow stack size in bytes.
    pub fn total_size(&self) -> i64 {
        self.entries.len() as i64 * SHADOW_STACK_ENTRY_SIZE
    }
}

// ============================================================================
// Extended: Inline Stack Frame Optimization
// ============================================================================

/// Frame optimization for inlined call sites.
#[derive(Debug, Clone)]
pub struct InlineFrameOpt {
    /// The caller frame state.
    pub caller_frame: StackFrameState,
    /// The callee frame state (if inlined).
    pub callee_frame: Option<Box<StackFrameState>>,
    /// Whether the callee frame was merged into the caller.
    pub merged: bool,
    /// Bytes saved by merging frames.
    pub bytes_saved: i64,
    /// Whether stack alignment was maintained.
    pub alignment_ok: bool,
}

impl InlineFrameOpt {
    /// Create a new inline frame optimization record.
    pub fn new(caller_frame: StackFrameState) -> Self {
        Self {
            caller_frame,
            callee_frame: None,
            merged: false,
            bytes_saved: 0,
            alignment_ok: true,
        }
    }

    /// Attempt to merge the callee frame into the caller.
    pub fn merge_callee(&mut self, mut callee_frame: StackFrameState) -> bool {
        // Check alignment compatibility.
        if callee_frame.stack_alignment != self.caller_frame.stack_alignment {
            self.alignment_ok = false;
            callee_frame.stack_alignment = self.caller_frame.stack_alignment;
        }

        // Merge the frames: the inlined callee's frame is allocated
        // after the caller's local variables and callee-saved area.
        let merged_max_depth = self
            .caller_frame
            .max_depth
            .min(self.caller_frame.max_depth + callee_frame.max_depth);

        self.bytes_saved = callee_frame.callee_saved_area + callee_frame.local_area;
        self.callee_frame = Some(Box::new(callee_frame));
        self.merged = true;
        true
    }

    /// Get the total merged frame size.
    pub fn merged_frame_size(&self) -> i64 {
        if self.merged {
            self.caller_frame.total_frame_size()
                + self
                    .callee_frame
                    .as_ref()
                    .map_or(0, |f| f.total_frame_size())
        } else {
            self.caller_frame.total_frame_size()
        }
    }
}

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

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

    #[test]
    fn test_stack_frame_state_default() {
        let state = StackFrameState::default();
        assert_eq!(state.rsp_offset, 0);
        assert_eq!(state.max_depth, 0);
        assert_eq!(state.total_frame_size(), 0);
        assert!(!state.frame_pointer_set);
        assert!(state.is_leaf);
        assert!(!state.fits_in_red_zone());
    }

    #[test]
    fn test_stack_frame_state_sysv64() {
        let state = StackFrameState::new(CallFrameConv::SysV64, true);
        assert_eq!(state.stack_alignment, X86_64_STACK_ALIGN);
        assert_eq!(state.calling_conv, CallFrameConv::SysV64);
    }

    #[test]
    fn test_stack_frame_state_x86_32() {
        let state = StackFrameState::new(CallFrameConv::Cdecl32, false);
        assert_eq!(state.stack_alignment, X86_32_STACK_ALIGN);
        assert_eq!(state.calling_conv, CallFrameConv::Cdecl32);
    }

    #[test]
    fn test_callocpts_for_win64() {
        let opt = X86CallFrameOpt::new_win64();
        assert!(opt.is_64bit);
        assert_eq!(opt.calling_conv, CallFrameConv::Win64);
    }

    #[test]
    fn test_callocpts_for_x86_32_stdcall() {
        let opt = X86CallFrameOpt::new_x86_32_stdcall();
        assert!(!opt.is_64bit);
        assert_eq!(opt.calling_conv, CallFrameConv::Stdcall32);
    }

    #[test]
    fn test_adjstack_analysis_empty() {
        let mut opt = X86CallFrameOpt::new_sysv64();
        let mut mf = MachineFunction::new("test_func");
        let analysis = opt.analyze_adjstack(&mf);
        assert!(!analysis.optimized);
        assert_eq!(analysis.cancel_pairs.len(), 0);
    }

    #[test]
    fn test_call_frame_opt_config_default() {
        let config = CallFrameOptConfig::default();
        assert!(config.enable_adjstack_elim);
        assert!(config.enable_adjust_merge);
        assert!(config.enable_push_pop_convert);
        assert_eq!(config.push_convert_max_frame, PUSH_TO_MOV_THRESHOLD);
    }

    #[test]
    fn test_shadow_frame_layout() {
        let mut layout = ShadowFrameLayout::new(0x7fff0000);
        assert_eq!(layout.shadow_ptr, 0);
        assert_eq!(layout.stored_ret_addrs, 0);

        layout.push(0x400100, 10);
        assert_eq!(layout.stored_ret_addrs, 1);
        assert_eq!(layout.shadow_ptr, SHADOW_STACK_ENTRY_SIZE);

        layout.push(0x400200, 20);
        assert_eq!(layout.stored_ret_addrs, 2);

        assert!(layout.verify(0x400200));

        let popped = layout.pop();
        assert_eq!(popped, Some(0x400200));
        assert_eq!(layout.stored_ret_addrs, 1);
    }

    #[test]
    fn test_inline_frame_merge() {
        let caller = StackFrameState::new(CallFrameConv::SysV64, true);
        let callee = StackFrameState::new(CallFrameConv::SysV64, true);
        let mut inline_opt = InlineFrameOpt::new(caller);
        assert!(inline_opt.merge_callee(callee));
        assert!(inline_opt.merged);
    }

    #[test]
    fn test_stats_total_optimizations() {
        let mut stats = CallFrameOptStats::default();
        stats.adjstacks_eliminated = 2;
        stats.push_converted = 3;
        stats.tail_calls_optimized = 1;
        assert_eq!(stats.total_optimizations(), 6);
    }

    #[test]
    fn test_are_opposite_ops() {
        let opt = X86CallFrameOpt::new_sysv64();
        assert!(opt.are_opposite_ops(StackAdjustKind::Alloc, StackAdjustKind::Dealloc));
        assert!(opt.are_opposite_ops(StackAdjustKind::Push, StackAdjustKind::Pop));
        assert!(!opt.are_opposite_ops(StackAdjustKind::Alloc, StackAdjustKind::Push));
        assert!(!opt.are_opposite_ops(StackAdjustKind::Call, StackAdjustKind::RetPop));
    }

    #[test]
    fn test_call_frame_conv_display() {
        assert_eq!(format!("{}", CallFrameConv::SysV64), "SysV64");
        assert_eq!(format!("{}", CallFrameConv::Win64), "Win64");
        assert_eq!(format!("{}", CallFrameConv::Cdecl32), "cdecl32");
    }

    #[test]
    fn test_stack_adjust_op() {
        let op = StackAdjustOp::new(StackAdjustKind::Alloc, -64, None, 5);
        assert!(op.is_alloc());
        assert!(!op.is_dealloc());
        assert!(!op.is_noop());

        let op2 = StackAdjustOp::new(StackAdjustKind::Dealloc, 64, Some(RAX), 10);
        assert!(!op2.is_alloc());
        assert!(op2.is_dealloc());
        assert_eq!(op2.reg, Some(RAX));
    }

    #[test]
    fn test_with_opt_level_disables_on_low() {
        let opt = X86CallFrameOpt::new_sysv64().with_opt_level(1);
        assert!(!opt.config.enable_adjstack_elim);
        assert!(!opt.config.enable_push_pop_convert);
    }

    #[test]
    fn test_with_opt_level_enables_on_high() {
        let opt = X86CallFrameOpt::new_sysv64().with_opt_level(3);
        assert!(opt.config.enable_adjstack_elim);
        assert!(opt.config.enable_push_pop_convert);
    }

    #[test]
    fn test_report_format() {
        let mut opt = X86CallFrameOpt::new_sysv64();
        opt.stats.functions_processed = 1;
        opt.stats.adjstacks_eliminated = 3;
        opt.stats.bytes_saved = 128;
        let report = opt.report();
        assert!(report.contains("adjstacks_elim=3"));
        assert!(report.contains("bytes_saved=128"));
    }

    #[test]
    fn test_stack_adjust_kind_display() {
        assert_eq!(format!("{}", StackAdjustKind::Alloc), "Alloc");
        assert_eq!(format!("{}", StackAdjustKind::Push), "Push");
        assert_eq!(format!("{}", StackAdjustKind::RetPop), "RetPop");
    }
}