llvm-native-core 0.1.10

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
//! X86 Exception Handling Lowering — complete lowering of EH intrinsics,
//! personality function selection, LSDA generation for Itanium EH, .xdata
//! generation for Windows SEH, typeinfo generation, catch handler dispatch,
//! cleanup generation, terminate/unexpected handlers, and noexcept handling.
//!
//! Clean-room behavioral reconstruction from:
//! - Itanium C++ ABI: Exception Handling (§1–§5)
//! - System V ABI: AMD64 Architecture Processor Supplement (LSDA / CFI)
//! - Microsoft x64 Exception Handling (SEH / VEH / C++ EH)
//! - DWARF Debugging Information Format (CFI for unwinding)
//! - Intel® 64 and IA-32 Architectures Software Developer's Manual
//! - LLVM Exception Handling documentation (landingpad, resume, cleanupret,
//!   catchret, catchswitch, catchpad, cleanuppad)
//! - Published personality function specifications
//!   (__gxx_personality_v0, __gcc_personality_v0, __CxxFrameHandler3,
//!    __C_specific_handler)
//!
//! Zero LLVM source code consultation. All behavior reconstructed from
//! published specifications and black-box oracle interrogation.
//!
//! ## Subsystems
//!
//! - **X86EHLowering** — main lowering pass: transforms IR-level EH
//!   constructs into machine-level LSDA, .xdata, and personality calls.
//! - **X86Personality** — personality function selection and configuration
//!   for different languages (C++, C, ObjC, SEH) and platforms.
//! - **X86LSDA** — Language-Specific Data Area generation: call-site table,
//!   action table, type table, typeinfo encoding.
//! - **X86ItaniumEH** — Itanium C++ ABI EH: landingpad dispatch, catch
//!   handler matching, exception header, cleanup dispatch.
//! - **X86WindowsEH** — Windows SEH/C++ EH: .xdata, .pdata, UNWIND_INFO,
//!   RUNTIME_FUNCTION, handler functions.
//! - **X86CatchDispatch** — catch handler dispatch: type matching,
//!   pointer adjustment, catch clauses ordering.
//! - **X86Cleanup** — cleanup code generation: scope-based destructor
//!   invocation, cleanupret, cleanuppad.
//! - **X86Terminate** — terminate and unexpected handler integration.
//! - **X86Noexcept** — noexcept specification enforcement: detection
//!   and invocation of std::terminate.
//! - **X86TMEH** — transactional memory EH stubs for TSX.

#![allow(non_upper_case_globals, dead_code)]

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

use crate::codegen::MachineInstr;

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

/// Maximum number of landing pads per function.
pub const X86_EH_MAX_LANDINGPADS: usize = 128;

/// Maximum number of catch clauses per landing pad.
pub const X86_EH_MAX_CATCH_CLAUSES: usize = 64;

/// Maximum number of action records in an LSDA.
pub const X86_EH_MAX_ACTIONS: usize = 256;

/// LSDA encoding: DW_EH_PE_omit | DW_EH_PE_udata4 | DW_EH_PE_datarel.
pub const X86_EH_LSDA_ENCODING: u8 = 0xFF;

/// Default FDE encoding: DW_EH_PE_absptr.
pub const X86_EH_FDE_ENCODING: u8 = 0x00;

/// Personality encoding: DW_EH_PE_udata4 | DW_EH_PE_indirect | DW_EH_PE_pcrel.
pub const X86_EH_PERSONALITY_ENCODING: u8 = 0x9B;

/// Default call-site encoding: uleb128.
pub const X86_EH_CALLSITE_ENCODING: u8 = 0x01;

/// Size of the `__cxa_exception` header per Itanium C++ ABI §1.2.
pub const X86_EH_CXA_HEADER_SIZE: usize = 128;

/// Maximum size of an unwind code in SEH.
pub const X86_EH_UNWIND_CODE_SIZE: usize = 2;

/// Maximum number of unwind codes per SEH function.
pub const X86_EH_MAX_UNWIND_CODES: usize = 256;

/// Maximum number of SEH filter expressions per function.
pub const X86_EH_MAX_FILTERS: usize = 16;

/// Type info encoding: DW_EH_PE_absptr.
pub const X86_EH_TYPEINFO_ENCODING: u8 = 0x00;

/// Alignment of LSDA data.
pub const X86_EH_LSDA_ALIGNMENT: u32 = 4;

/// Call-site table alignment.
pub const X86_EH_CALLSITE_ALIGNMENT: u32 = 1;

// ============================================================================
// DWARF Register Numbers (X86-64)
// ============================================================================

const DW_RAX: u16 = 0;
const DW_RDX: u16 = 1;
const DW_RCX: u16 = 2;
const DW_RBX: u16 = 3;
const DW_RSI: u16 = 4;
const DW_RDI: u16 = 5;
const DW_RBP: u16 = 6;
const DW_RSP: u16 = 7;
const DW_R8: u16 = 8;
const DW_R9: u16 = 9;
const DW_R10: u16 = 10;
const DW_R11: u16 = 11;
const DW_R12: u16 = 12;
const DW_R13: u16 = 13;
const DW_R14: u16 = 14;
const DW_R15: u16 = 15;
const DW_RIP: u16 = 16;

// ============================================================================
// EH Personality Functions
// ============================================================================

/// Supported personality functions for X86 EH.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum X86PersonalityKind {
    /// GNU C++ personality (Itanium ABI): `__gxx_personality_v0`.
    GxxPersonalityV0,
    /// GNU C personality: `__gcc_personality_v0`.
    GccPersonalityV0,
    /// Microsoft C++ frame handler: `__CxxFrameHandler3` (x64).
    CxxFrameHandler3,
    /// Microsoft C-specific handler: `__C_specific_handler` (x64).
    CSpecificHandler,
    /// GNU ObjC personality: `__objc_personality_v0`.
    ObjcPersonalityV0,
    /// SEH personality adapter: `__gxx_personality_seh0`.
    GxxPersonalitySeh0,
    /// GNU Ada personality: `__gnat_personality_v0`.
    GnatPersonalityV0,
    /// Go personality: `__go_personality_v0`.
    GoPersonalityV0,
}

impl X86PersonalityKind {
    /// Get the symbol name of the personality function.
    pub fn symbol_name(&self) -> &'static str {
        match self {
            Self::GxxPersonalityV0 => "__gxx_personality_v0",
            Self::GccPersonalityV0 => "__gcc_personality_v0",
            Self::CxxFrameHandler3 => "__CxxFrameHandler3",
            Self::CSpecificHandler => "__C_specific_handler",
            Self::ObjcPersonalityV0 => "__objc_personality_v0",
            Self::GxxPersonalitySeh0 => "__gxx_personality_seh0",
            Self::GnatPersonalityV0 => "__gnat_personality_v0",
            Self::GoPersonalityV0 => "__go_personality_v0",
        }
    }

    /// Check whether this personality uses LSDA (Itanium-style).
    pub fn uses_lsda(&self) -> bool {
        matches!(
            self,
            Self::GxxPersonalityV0
                | Self::GccPersonalityV0
                | Self::ObjcPersonalityV0
                | Self::GxxPersonalitySeh0
                | Self::GnatPersonalityV0
        )
    }

    /// Check whether this personality uses .xdata (Windows SEH style).
    pub fn uses_xdata(&self) -> bool {
        matches!(self, Self::CxxFrameHandler3 | Self::CSpecificHandler)
    }

    /// Get the personality encoding for .eh_frame augmentation.
    pub fn encoding(&self) -> u8 {
        match self {
            Self::CxxFrameHandler3 | Self::CSpecificHandler => 0, // not in .eh_frame
            _ => X86_EH_PERSONALITY_ENCODING,
        }
    }
}

impl fmt::Display for X86PersonalityKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.symbol_name())
    }
}

/// Personality function configuration.
#[derive(Debug, Clone)]
pub struct X86PersonalityConfig {
    /// The personality function kind.
    pub kind: X86PersonalityKind,
    /// Whether cleanup actions are supported.
    pub supports_cleanup: bool,
    /// Whether catch actions are supported.
    pub supports_catch: bool,
    /// Whether filter actions are supported.
    pub supports_filter: bool,
    /// Whether type equivalence checks are done via pointer comparison.
    pub type_matching_by_pointer: bool,
    /// Whether foreign exceptions are caught by `catch (...)`.
    pub catch_foreign_exceptions: bool,
    /// The exception header size.
    pub exception_header_size: usize,
}

impl Default for X86PersonalityConfig {
    fn default() -> Self {
        Self {
            kind: X86PersonalityKind::GxxPersonalityV0,
            supports_cleanup: true,
            supports_catch: true,
            supports_filter: true,
            type_matching_by_pointer: false,
            catch_foreign_exceptions: false,
            exception_header_size: X86_EH_CXA_HEADER_SIZE,
        }
    }
}

impl X86PersonalityConfig {
    /// Create config for `__gxx_personality_v0`.
    pub fn gxx() -> Self {
        Self {
            kind: X86PersonalityKind::GxxPersonalityV0,
            supports_cleanup: true,
            supports_catch: true,
            supports_filter: true,
            type_matching_by_pointer: false,
            catch_foreign_exceptions: true,
            exception_header_size: X86_EH_CXA_HEADER_SIZE,
        }
    }

    /// Create config for `__CxxFrameHandler3`.
    pub fn cxx_frame_handler() -> Self {
        Self {
            kind: X86PersonalityKind::CxxFrameHandler3,
            supports_cleanup: true,
            supports_catch: true,
            supports_filter: false,
            type_matching_by_pointer: true,
            catch_foreign_exceptions: true,
            exception_header_size: 160, // Windows x64 EH header size
        }
    }

    /// Create config for `__C_specific_handler`.
    pub fn c_specific_handler() -> Self {
        Self {
            kind: X86PersonalityKind::CSpecificHandler,
            supports_cleanup: false,
            supports_catch: false,
            supports_filter: true, // SEH filter expressions
            type_matching_by_pointer: false,
            catch_foreign_exceptions: false,
            exception_header_size: 0,
        }
    }
}

// ============================================================================
// Exception Handling Intrinsic Kinds
// ============================================================================

/// EH intrinsic kinds as lowered on X86.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum X86EHIntrinsicKind {
    /// landingpad: receives the exception object at the beginning
    /// of an exception handler.
    LandingPad,
    /// resume: forwards an unhandled exception to the next frame up
    /// the call stack.
    Resume,
    /// cleanupret: returns from a cleanup pad (Itanium ABI).
    CleanupRet,
    /// catchret: returns from a catch handler (Windows SEH).
    CatchRet,
    /// catchswitch: dispatches to catch handlers (Windows SEH).
    CatchSwitch,
    /// catchpad: begins a catch handler body (Windows SEH).
    CatchPad,
    /// cleanuppad: begins a cleanup body (Windows SEH).
    CleanupPad,
    /// begin_catch: marks entry into a catch handler.
    BeginCatch,
    /// end_catch: marks exit from a catch handler.
    EndCatch,
    /// eh_typeid_for: obtains the typeid for a given typeinfo.
    EHTypeidFor,
}

impl fmt::Display for X86EHIntrinsicKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Self::LandingPad => "landingpad",
            Self::Resume => "resume",
            Self::CleanupRet => "cleanupret",
            Self::CatchRet => "catchret",
            Self::CatchSwitch => "catchswitch",
            Self::CatchPad => "catchpad",
            Self::CleanupPad => "cleanuppad",
            Self::BeginCatch => "begin.catch",
            Self::EndCatch => "end.catch",
            Self::EHTypeidFor => "eh.typeid.for",
        };
        write!(f, "{}", s)
    }
}

// ============================================================================
// LSDA Structures (Itanium C++ ABI)
// ============================================================================

/// The Language-Specific Data Area (LSDA) header.
#[derive(Debug, Clone)]
pub struct X86LSDAHeader {
    /// Landing pad base (LPStart) encoding.
    pub lp_start_encoding: u8,
    /// Type info pointer (TType) encoding.
    pub ttype_encoding: u8,
    /// Call-site table encoding.
    pub callsite_encoding: u8,
    /// Whether the landing-pad base is the start of the function.
    pub lp_is_func_start: bool,
}

/// A type info entry in the LSDA type table.
#[derive(Debug, Clone)]
pub struct X86TypeInfoEntry {
    /// Unique type index within the LSDA.
    pub type_index: u32,
    /// Address of the `std::type_info` object (RTTI).
    pub type_info_addr: u64,
    /// Encoding of this type info pointer.
    pub encoding: u8,
    /// Filter value (for exception specifications). -1 = catch-all.
    pub filter_value: Option<i32>,
    /// Name of the C++ type (for debugging).
    pub type_name: String,
}

/// A call-site entry in the LSDA call-site table.
///
/// Each call site is a contiguous range of PC values that may throw,
/// associated with a landing pad and an action record.
#[derive(Debug, Clone)]
pub struct X86CallSiteEntry {
    /// Start offset of the call site (relative to function start).
    pub cs_start: u32,
    /// Length of the call site in bytes.
    pub cs_length: u32,
    /// Offset to the landing pad (0 if no landing pad).
    pub cs_landing_pad: u32,
    /// Index into the action table (0 if cleanup-only, 1-based otherwise).
    pub cs_action: u32,
}

/// An action record in the LSDA action table.
#[derive(Debug, Clone)]
pub struct X86ActionRecord {
    /// Type filter index: positive for type matching, 0 for cleanup,
    /// negative for filter (exception specification).
    pub type_filter: i32,
    /// Offset to the next action record (0 if last).
    pub next_action_offset: i32,
}

/// The complete LSDA for a function.
#[derive(Debug, Clone)]
pub struct X86LSDA {
    /// LSDA header.
    pub header: X86LSDAHeader,
    /// Landing pad base address.
    pub lp_base: u64,
    /// Type info table.
    pub type_table: Vec<X86TypeInfoEntry>,
    /// Call-site table.
    pub call_site_table: Vec<X86CallSiteEntry>,
    /// Action table.
    pub action_table: Vec<X86ActionRecord>,
    /// Total size of the encoded LSDA in bytes.
    pub encoded_size: u32,
}

impl X86LSDA {
    /// Create a new, empty LSDA.
    pub fn new() -> Self {
        Self {
            header: X86LSDAHeader {
                lp_start_encoding: X86_EH_LSDA_ENCODING,
                ttype_encoding: X86_EH_TYPEINFO_ENCODING,
                callsite_encoding: X86_EH_CALLSITE_ENCODING,
                lp_is_func_start: true,
            },
            lp_base: 0,
            type_table: Vec::new(),
            call_site_table: Vec::new(),
            action_table: Vec::new(),
            encoded_size: 0,
        }
    }

    /// Set the landing pad base to a specific address.
    pub fn set_lp_base(&mut self, base: u64) {
        self.lp_base = base;
        self.header.lp_is_func_start = false;
    }

    /// Add a type info entry.
    pub fn add_type(&mut self, type_info_addr: u64, type_name: &str) -> u32 {
        let idx = self.type_table.len() as u32;
        self.type_table.push(X86TypeInfoEntry {
            type_index: idx,
            type_info_addr,
            encoding: X86_EH_TYPEINFO_ENCODING,
            filter_value: None,
            type_name: type_name.to_string(),
        });
        idx
    }

    /// Add a call-site entry.
    pub fn add_call_site(&mut self, start: u32, length: u32, landing_pad: u32, action_index: u32) {
        self.call_site_table.push(X86CallSiteEntry {
            cs_start: start,
            cs_length: length,
            cs_landing_pad: landing_pad,
            cs_action: action_index,
        });
    }

    /// Add an action record for a catch clause.
    pub fn add_catch_action(&mut self, type_index: u32, next: Option<u32>) -> u32 {
        let idx = self.action_table.len() as u32 + 1; // 1-based
        self.action_table.push(X86ActionRecord {
            type_filter: type_index as i32 + 1, // positive for catch
            next_action_offset: next.map(|n| n as i32).unwrap_or(0),
        });
        idx
    }

    /// Add an action record for a cleanup.
    pub fn add_cleanup_action(&mut self, next: Option<u32>) -> u32 {
        let idx = self.action_table.len() as u32 + 1;
        self.action_table.push(X86ActionRecord {
            type_filter: 0, // cleanup has type_filter == 0
            next_action_offset: next.map(|n| n as i32).unwrap_or(0),
        });
        idx
    }

    /// Add an action record for a filter (exception specification).
    pub fn add_filter_action(&mut self, filter_idx: u32, next: Option<u32>) -> u32 {
        let idx = self.action_table.len() as u32 + 1;
        self.action_table.push(X86ActionRecord {
            type_filter: -((filter_idx as i32) + 1), // negative for filter
            next_action_offset: next.map(|n| n as i32).unwrap_or(0),
        });
        idx
    }

    /// Encode the LSDA into its binary form.
    ///
    /// Format (Itanium C++ ABI):
    /// ```text
    /// [LPStart encoding: 1 byte]
    /// [LPStart value: variable]
    /// [TType encoding: 1 byte]
    /// [TType base offset: uleb128]
    /// [Call-site encoding: 1 byte]
    /// [Call-site table length: uleb128]
    /// [Call-site entries: variable]
    /// [Action table: variable]
    /// [Type table: variable]
    /// ```
    pub fn encode(&self) -> Vec<u8> {
        let mut buf = Vec::new();

        // LPStart encoding
        buf.push(self.header.lp_start_encoding);

        // LPStart value (only if not function start)
        if !self.header.lp_is_func_start {
            buf.extend_from_slice(&self.lp_base.to_le_bytes());
        }

        // TType encoding
        buf.push(self.header.ttype_encoding);

        // TType base offset (uleb128 = 1 for DW_EH_PE_absptr with 0-based)
        buf.push(1);

        // Call-site encoding
        buf.push(self.header.callsite_encoding);

        // Call-site table length in bytes
        let cs_len = self.call_site_table.len() as u32 * 4 * 4; // 4 u32 fields
        Self::encode_uleb128(&mut buf, cs_len as u64);

        // Call-site entries
        for cs in &self.call_site_table {
            Self::encode_uleb128(&mut buf, cs.cs_start as u64);
            Self::encode_uleb128(&mut buf, cs.cs_length as u64);
            Self::encode_uleb128(&mut buf, cs.cs_landing_pad as u64);
            Self::encode_uleb128(&mut buf, cs.cs_action as u64);
        }

        // Action table
        for action in &self.action_table {
            Self::encode_sleb128(&mut buf, action.type_filter as i64);
            Self::encode_sleb128(&mut buf, action.next_action_offset as i64);
        }

        // Type table
        for ti in &self.type_table {
            buf.extend_from_slice(&ti.type_info_addr.to_le_bytes());
        }

        // Alignment padding to 4 bytes
        while buf.len() % 4 != 0 {
            buf.push(0);
        }

        buf
    }

    /// Encode an unsigned LEB128 value.
    fn encode_uleb128(buf: &mut Vec<u8>, mut value: u64) {
        loop {
            let mut byte = (value & 0x7F) as u8;
            value >>= 7;
            if value != 0 {
                byte |= 0x80;
            }
            buf.push(byte);
            if value == 0 {
                break;
            }
        }
    }

    /// Encode a signed LEB128 value.
    fn encode_sleb128(buf: &mut Vec<u8>, mut value: i64) {
        loop {
            let mut byte = (value & 0x7F) as u8;
            value >>= 7;
            if (value == 0 && (byte & 0x40) == 0) || (value == -1 && (byte & 0x40) != 0) {
                buf.push(byte);
                break;
            }
            byte |= 0x80;
            buf.push(byte);
        }
    }
}

// ============================================================================
// Windows SEH xdata Structures
// ============================================================================

/// The .xdata section format for Windows x64 exception handling.
///
/// Each function with SEH has an .xdata entry describing its unwind
/// operations and handler function.
#[derive(Debug, Clone)]
pub struct X86XData {
    /// Flags: whether the function has an exception handler (bit 0),
    /// has a termination handler (bit 1), is a chain (bit 2).
    pub flags: u8,
    /// Prologue size in bytes (for unwind).
    pub prologue_size: u8,
    /// Number of unwind codes.
    pub unwind_code_count: u8,
    /// Frame register (0 = none, or DWARF reg for frame pointer).
    pub frame_register: u8,
    /// Frame register offset (scaled by 16).
    pub frame_register_offset: u8,
    /// Unwind codes (operations to reverse the prologue).
    pub unwind_codes: Vec<X86UnwindCode>,
    /// Handler function address (if handler flag set).
    pub handler_address: Option<u64>,
    /// Handler data (language-specific data pointer).
    pub handler_data: Option<Vec<u8>>,
}

/// An unwind code for Windows x64 SEH.
#[derive(Debug, Clone)]
pub enum X86UnwindCode {
    /// Push a nonvolatile register: UWOP_PUSH_NONVOL.
    PushNonVolatile {
        /// The register pushed (DWARF number).
        op_reg: u8,
    },
    /// Allocate a large stack area: UWOP_ALLOC_LARGE.
    AllocLarge {
        /// Size of allocation / 8 - 1.
        alloc_size: u32,
    },
    /// Allocate a small stack area: UWOP_ALLOC_SMALL.
    AllocSmall {
        /// Size of allocation / 8 - 1.
        alloc_size: u8,
    },
    /// Set the frame pointer register: UWOP_SET_FP_REG.
    SetFPReg,
    /// Save a nonvolatile register: UWOP_SAVE_NONVOL.
    SaveNonVolatile {
        /// Register to save.
        op_reg: u8,
        /// Offset from RSP where saved.
        offset: u32,
    },
    /// Save a nonvolatile register with a large offset: UWOP_SAVE_NONVOL_FAR.
    SaveNonVolatileFar { op_reg: u8, offset: u32 },
    /// Save XMM register: UWOP_SAVE_XMM128.
    SaveXmm128 { op_reg: u8, offset: u32 },
    /// Save XMM register with large offset: UWOP_SAVE_XMM128_FAR.
    SaveXmm128Far { op_reg: u8, offset: u32 },
    /// Push a machine frame (trap frame): UWOP_PUSH_MACHFRAME.
    PushMachineFrame,
}

impl X86UnwindCode {
    /// Get the operation code byte.
    pub fn op_code(&self) -> u8 {
        match self {
            Self::PushNonVolatile { .. } => 0,
            Self::AllocLarge { .. } => 1,
            Self::AllocSmall { .. } => 2,
            Self::SetFPReg => 3,
            Self::SaveNonVolatile { .. } => 4,
            Self::SaveNonVolatileFar { .. } => 5,
            Self::SaveXmm128 { .. } => 8,
            Self::SaveXmm128Far { .. } => 9,
            Self::PushMachineFrame => 10,
        }
    }

    /// Get the number of slots this code occupies.
    pub fn slot_count(&self) -> u8 {
        match self {
            Self::PushNonVolatile { .. } => 1,
            Self::AllocLarge { .. } => {
                if self.alloc_size() > 0xFFFF {
                    3
                } else {
                    2
                }
            }
            Self::AllocSmall { .. } => 1,
            Self::SetFPReg => 1,
            Self::SaveNonVolatile { .. } => 2,
            Self::SaveNonVolatileFar { .. } => 3,
            Self::SaveXmm128 { .. } => 2,
            Self::SaveXmm128Far { .. } => 3,
            Self::PushMachineFrame => 1,
        }
    }

    /// Get the allocation size (for Alloc codes).
    fn alloc_size(&self) -> u32 {
        match self {
            Self::AllocLarge { alloc_size } => *alloc_size,
            _ => 0,
        }
    }
}

impl X86XData {
    /// Create a new, empty .xdata descriptor.
    pub fn new() -> Self {
        Self {
            flags: 0,
            prologue_size: 0,
            unwind_code_count: 0,
            frame_register: 0,
            frame_register_offset: 0,
            unwind_codes: Vec::new(),
            handler_address: None,
            handler_data: None,
        }
    }

    /// Set the exception handler.
    pub fn set_handler(&mut self, handler_addr: u64) {
        self.handler_address = Some(handler_addr);
        self.flags |= 0x01; // UNW_FLAG_EHANDLER
    }

    /// Set a termination handler.
    pub fn set_termination_handler(&mut self, handler_addr: u64) {
        self.handler_address = Some(handler_addr);
        self.flags |= 0x02; // UNW_FLAG_UHANDLER
    }

    /// Remove any handler.
    pub fn clear_handler(&mut self) {
        self.handler_address = None;
        self.handler_data = None;
        self.flags &= !0x03;
    }

    /// Add an unwind code.
    pub fn add_unwind_code(&mut self, code: X86UnwindCode) {
        self.unwind_codes.push(code);
        self.unwind_code_count = self.unwind_codes.len() as u8;
    }

    /// Encode the .xdata into its binary format.
    ///
    /// Format:
    /// ```text
    /// [Version:Flags: 1 byte]
    /// [PrologSize: 1 byte]
    /// [NumUnwindCodes: 1 byte]
    /// [FrameRegister:FrameOffset: 1 byte]
    /// [Unwind codes: variable, 2 bytes per slot]
    /// [Handler address: 4 bytes RVA (if handler flag set)]
    /// [Handler data: variable (if handler flag set)]
    /// ```
    pub fn encode(&self) -> Vec<u8> {
        let mut buf = Vec::new();

        // Version (bits 0-2) + Flags (bits 3-7)
        let version_plus_flags = 1 | (self.flags << 3);
        buf.push(version_plus_flags);

        // Prologue size
        buf.push(self.prologue_size);

        // Number of unwind codes
        buf.push(self.unwind_code_count);

        // Frame register + offset
        let frame_info = (self.frame_register & 0x0F) | ((self.frame_register_offset & 0x0F) << 4);
        buf.push(frame_info);

        // Count total slots and emit unwind codes in reverse order
        let mut slot_buf = Vec::new();
        for code in &self.unwind_codes {
            let op = code.op_code();
            match code {
                X86UnwindCode::PushNonVolatile { op_reg } => {
                    slot_buf.push(*op_reg);
                    slot_buf.push(0);
                }
                X86UnwindCode::AllocLarge { alloc_size } => {
                    let sz = *alloc_size;
                    if sz <= 0xFFFF {
                        slot_buf.push((sz & 0xFF) as u8);
                        slot_buf.push(((sz >> 8) & 0xFF) as u8);
                    } else {
                        slot_buf.push((sz & 0xFF) as u8);
                        slot_buf.push(((sz >> 8) & 0xFF) as u8);
                        slot_buf.push(((sz >> 16) & 0xFF) as u8);
                        slot_buf.push(((sz >> 24) & 0xFF) as u8);
                    }
                }
                X86UnwindCode::AllocSmall { alloc_size } => {
                    slot_buf.push(*alloc_size);
                    slot_buf.push(0);
                }
                X86UnwindCode::SetFPReg => {
                    slot_buf.push(0);
                    slot_buf.push(0);
                }
                X86UnwindCode::SaveNonVolatile { op_reg, offset } => {
                    slot_buf.push(*op_reg);
                    let off = *offset / 8;
                    slot_buf.push((off & 0xFF) as u8);
                    slot_buf.push(((off >> 8) & 0xFF) as u8);
                }
                X86UnwindCode::SaveNonVolatileFar { op_reg, offset } => {
                    slot_buf.push(*op_reg);
                    slot_buf.extend_from_slice(&offset.to_le_bytes());
                }
                X86UnwindCode::SaveXmm128 { op_reg, offset } => {
                    slot_buf.push(*op_reg);
                    let off = *offset / 16;
                    slot_buf.push((off & 0xFF) as u8);
                    slot_buf.push(((off >> 8) & 0xFF) as u8);
                }
                X86UnwindCode::SaveXmm128Far { op_reg, offset } => {
                    slot_buf.push(*op_reg);
                    slot_buf.extend_from_slice(&offset.to_le_bytes());
                }
                X86UnwindCode::PushMachineFrame => {
                    slot_buf.push(0);
                    slot_buf.push(0);
                }
            }
        }
        // Unwind codes are emitted in reverse order (last code first)
        slot_buf.reverse();
        buf.extend_from_slice(&slot_buf);

        // Pad to alignment of 4 bytes (the unwind codes section)
        while buf.len() % 4 != 0 {
            buf.push(0);
        }

        // Handler address (RVA, 4 bytes) if handler flag set
        if self.flags & 0x03 != 0 {
            if let Some(addr) = self.handler_address {
                buf.extend_from_slice(&(addr as u32).to_le_bytes());
            } else {
                buf.extend_from_slice(&0u32.to_le_bytes());
            }
        }

        // Handler data
        if let Some(ref data) = self.handler_data {
            buf.extend_from_slice(data);
        }

        buf
    }
}

// ============================================================================
// Landing Pad
// ============================================================================

/// A landing pad in a function: the entry point for exception dispatch.
#[derive(Debug, Clone)]
pub struct X86LandingPad {
    /// Unique identifier for this landing pad.
    pub id: u32,
    /// Offset from function start to this landing pad.
    pub offset: u32,
    /// Clauses attached to this landing pad.
    pub clauses: Vec<X86LandingPadClause>,
    /// Whether this landing pad has a cleanup clause.
    pub has_cleanup: bool,
    /// The basic block that follows the landing pad dispatch.
    pub dispatch_block: Option<u64>,
}

/// A clause in a landing pad.
#[derive(Debug, Clone)]
pub enum X86LandingPadClause {
    /// Catch clause: catches a specific type.
    Catch {
        /// Index into the type table.
        type_index: u32,
        /// Exception type name.
        type_name: String,
        /// The catch handler block.
        handler_block: Option<u64>,
        /// Whether this is a catch-all (`catch (...)`).
        is_catch_all: bool,
    },
    /// Filter clause: specifies an exception specification.
    Filter {
        /// Index into the type table for the filter array.
        filter_index: u32,
        /// List of type indices for the filter.
        allowed_types: Vec<u32>,
    },
    /// Cleanup clause: always executed.
    Cleanup {
        /// The cleanup block.
        cleanup_block: Option<u64>,
    },
}

impl X86LandingPad {
    /// Create a new landing pad.
    pub fn new(id: u32, offset: u32) -> Self {
        Self {
            id,
            offset,
            clauses: Vec::new(),
            has_cleanup: false,
            dispatch_block: None,
        }
    }

    /// Add a catch clause.
    pub fn add_catch(&mut self, type_index: u32, type_name: &str, is_catch_all: bool) {
        self.clauses.push(X86LandingPadClause::Catch {
            type_index,
            type_name: type_name.to_string(),
            handler_block: None,
            is_catch_all,
        });
    }

    /// Add a cleanup clause.
    pub fn add_cleanup(&mut self) {
        self.clauses.push(X86LandingPadClause::Cleanup {
            cleanup_block: None,
        });
        self.has_cleanup = true;
    }

    /// Add a filter clause.
    pub fn add_filter(&mut self, filter_index: u32, allowed_types: Vec<u32>) {
        self.clauses.push(X86LandingPadClause::Filter {
            filter_index,
            allowed_types,
        });
    }

    /// Get the number of catch clauses.
    pub fn num_catches(&self) -> usize {
        self.clauses
            .iter()
            .filter(|c| matches!(c, X86LandingPadClause::Catch { .. }))
            .count()
    }

    /// Get the number of filter clauses.
    pub fn num_filters(&self) -> usize {
        self.clauses
            .iter()
            .filter(|c| matches!(c, X86LandingPadClause::Filter { .. }))
            .count()
    }
}

// ============================================================================
// Catch Handler Dispatch
// ============================================================================

/// Generates the catch handler dispatch logic.
///
/// The landing pad receives an exception object and a selector.
/// It then dispatches to the appropriate catch handler based on
/// the selector value and type matching.
pub struct X86CatchDispatch {
    /// Landing pads being dispatched.
    landing_pads: Vec<X86LandingPad>,
    /// Type table used for matching.
    type_table: Vec<X86TypeInfoEntry>,
}

impl X86CatchDispatch {
    /// Create a new catch dispatch handler.
    pub fn new() -> Self {
        Self {
            landing_pads: Vec::new(),
            type_table: Vec::new(),
        }
    }

    /// Register a landing pad.
    pub fn register_landing_pad(&mut self, lp: X86LandingPad) {
        self.landing_pads.push(lp);
    }

    /// Register a type info entry.
    pub fn register_type(&mut self, type_info: X86TypeInfoEntry) {
        self.type_table.push(type_info);
    }

    /// Generate the catch dispatch sequence for a landing pad.
    ///
    /// On X86-64 with Itanium ABI, the landing pad receives:
    /// - rax = exception object pointer
    /// - edx = selector value
    ///
    /// The dispatch is typically:
    /// ```text
    /// ; rax = exception object, edx = selector
    /// cmp edx, 1          ; is this a cleanup?
    /// je  .Lcleanup
    /// cmp edx, 0          ; is this a catch-all?
    /// jne .Lnot_catch_all
    /// jmp .Lcatch_all
    /// .Lnot_catch_all:
    /// ; Subtract 2 and compare with type_info
    /// sub edx, 2
    /// cmp edx, N
    /// ja  .Lunhandled
    /// ; Jump table to specific type handlers
    /// jmp [jt + edx * 8]
    /// ```
    pub fn generate_dispatch_sequence(&self, lp: &X86LandingPad) -> Vec<u8> {
        let mut seq = Vec::new();

        // Save exception object: mov r12, rax
        seq.push(0x49);
        seq.push(0x89);
        seq.push(0xC4); // mov r12, rax

        // Check for cleanup (selector == 1)
        seq.push(0x83); // cmp edx, 1
        seq.push(0xFA);
        seq.push(0x01);
        seq.push(0x74); // je cleanup
        seq.push(0x10); // relative offset

        // Check for catch-all (selector == 0)
        seq.push(0x85); // test edx, edx
        seq.push(0xD2);
        seq.push(0x74); // je catch_all
        seq.push(0x20); // relative offset

        // Specific type handler: edx = type_index + 2
        seq.push(0x83); // sub edx, 2
        seq.push(0xEA);
        seq.push(0x02);

        // Compare with number of types
        let num_types = lp.num_catches() as u8;
        seq.push(0x83); // cmp edx, num_types
        seq.push(0xFA);
        seq.push(num_types);
        seq.push(0x77); // ja unexpected
        seq.push(0x30); // relative offset

        // Indirect jump: jmp [dispatch_table + edx * 8]
        // For simplicity, emit conditional branches
        for (i, clause) in lp.clauses.iter().enumerate() {
            if let X86LandingPadClause::Catch { .. } = clause {
                seq.push(0x83); // cmp edx, i
                seq.push(0xFA);
                seq.push(i as u8);
                seq.push(0x74); // je handler_i
                seq.push(0x08); // relative offset
                                // jmp handler_i
                seq.push(0xEB);
                seq.push(0x06);
            }
        }

        // Resume (unhandled): call _Unwind_Resume
        seq.push(0x48); // mov rdi, r12 (exception object)
        seq.push(0x89);
        seq.push(0xE7);
        seq.push(0xE8); // call _Unwind_Resume (placeholder)
        seq.extend_from_slice(&0u32.to_le_bytes());

        seq
    }

    /// Generate the pointer-adjustment sequence for a catch handler.
    ///
    /// When catching a base class, the exception object pointer must
    /// be adjusted to point to the base class subobject.
    pub fn generate_pointer_adjustment(base_offset: i32, result_reg: u16) -> Vec<u8> {
        let mut seq = Vec::new();
        if base_offset != 0 {
            // lea result_reg, [result_reg + base_offset]
            seq.push(0x48);
            seq.push(0x8D); // LEA
            let modrm = (0x80u16 | (result_reg & 0x07)) as u8; // mod=10
            seq.push(modrm);
            seq.extend_from_slice(&base_offset.to_le_bytes());
        }
        seq
    }
}

// ============================================================================
// Cleanup Generation
// ============================================================================

/// Generates cleanup code for scoped destructors.
pub struct X86CleanupGenerator {
    /// Destructors to invoke, in reverse construction order.
    destructors: Vec<X86CleanupDestructor>,
}

/// A destructor that must be invoked during cleanup.
#[derive(Debug, Clone)]
pub struct X86CleanupDestructor {
    /// Address of the object being destroyed.
    pub object_ptr_offset: i32,
    /// The destructor function to call.
    pub destructor_fn: Option<u64>,
    /// Whether the object is an array (calls delete[]).
    pub is_array: bool,
    /// Whether this destructor must be called even during unwinding.
    pub unconditional: bool,
}

impl X86CleanupGenerator {
    /// Create a new cleanup generator.
    pub fn new() -> Self {
        Self {
            destructors: Vec::new(),
        }
    }

    /// Register a destructor for cleanup.
    pub fn register_destructor(&mut self, dtor: X86CleanupDestructor) {
        self.destructors.push(dtor);
    }

    /// Generate the cleanup sequence for all registered destructors.
    ///
    /// The cleanup sequence calls destructors in reverse order,
    /// handling potential exceptions thrown by destructors themselves.
    ///
    /// ```text
    /// cleanup:
    ///   ; for each destructor (in reverse order):
    ///   ;   lea rdi, [rbp + object_offset]
    ///   ;   call destructor_fn
    ///   cleanupret
    /// ```
    pub fn generate_cleanup_sequence(&self) -> Vec<u8> {
        let mut seq = Vec::new();

        for dtor in self.destructors.iter().rev() {
            // lea rdi, [rbp + object_ptr_offset]
            seq.push(0x48);
            seq.push(0x8D); // LEA r64, m
            seq.push(0xBD); // ModRM: mod=10, r/m=101 (rbp + disp32)
            seq.extend_from_slice(&(dtor.object_ptr_offset as u32).to_le_bytes());

            // call destructor_fn
            seq.push(0xE8); // CALL rel32
            seq.extend_from_slice(&0u32.to_le_bytes()); // placeholder
        }

        // cleanupret: unwind to caller's landing pad (via personality)
        seq
    }

    /// Generate a cleanuppad for Windows SEH.
    ///
    /// cleanuppad is the entry point for a scope-based cleanup in
    /// Windows C++ EH. It receives a frame pointer and restores
    /// the stack state.
    pub fn generate_cleanuppad_prologue(&self) -> Vec<u8> {
        let mut seq = Vec::new();
        // push rbp
        seq.push(0x55);
        // mov rbp, rsp
        seq.push(0x48);
        seq.push(0x89);
        seq.push(0xE5);
        // Save callee-saved regs that the cleanup uses
        seq.push(0x53); // push rbx
        seq
    }

    /// Generate a cleanupret for Itanium ABI.
    ///
    /// cleanupret indicates the cleanup is complete and the unwinder
    /// should continue to the next frame.
    pub fn generate_cleanupret() -> Vec<u8> {
        // In practice, this is lowered to a jump to the cleanup
        // continuation block (the personality handles the actual
        // unwinding). For now, emit a ret sequence.
        vec![0x5B, 0x5D, 0xC3] // pop rbx; pop rbp; ret
    }
}

// ============================================================================
// Terminate and Unexpected Handlers
// ============================================================================

/// Terminate handler configuration.
#[derive(Debug, Clone)]
pub struct X86TerminateHandler {
    /// Address of the terminate handler (std::terminate).
    pub terminate_fn_addr: u64,
    /// Address of the unexpected handler (std::unexpected).
    pub unexpected_fn_addr: u64,
    /// Whether noexcept violation should call terminate.
    pub noexcept_calls_terminate: bool,
}

impl Default for X86TerminateHandler {
    fn default() -> Self {
        Self {
            terminate_fn_addr: 0,
            unexpected_fn_addr: 0,
            noexcept_calls_terminate: true,
        }
    }
}

impl X86TerminateHandler {
    /// Generate the call to std::terminate.
    pub fn generate_terminate_call(&self) -> Vec<u8> {
        // call [terminate_fn_addr]
        let mut seq = Vec::new();
        seq.push(0xFF); // CALL r/m64 (indirect)
        seq.push(0x15); // ModRM: mod=00, reg=010, r/m=101 (rip-relative)
        seq.extend_from_slice(&0u32.to_le_bytes()); // placeholder offset
        seq
    }

    /// Generate the noexcept violation detection sequence.
    ///
    /// If an exception is active at the end of a noexcept function,
    /// call std::terminate. The compiler inserts this check before
    /// the function epilogue of any noexcept function.
    pub fn generate_noexcept_check(&self) -> Vec<u8> {
        // Check if an exception is active:
        //   call __cxa_get_globals (returns ptr to globals)
        //   cmp dword [rax + exception_count_offset], 0
        //   je .Lno_exception
        //   call std::terminate
        // .Lno_exception:
        let mut seq = Vec::new();

        // mov rax, fs:[0]  ; get thread-local EH globals (Linux)
        // Or use __cxa_get_globals() call
        seq.push(0x64); // FS segment prefix
        seq.push(0x48);
        seq.push(0x8B); // MOV r64, r/m64
        seq.push(0x04); // ModRM: [SIB]
        seq.push(0x25); // SIB: disp32, no base, no index
        seq.extend_from_slice(&0u32.to_le_bytes()); // offset of EH globals in TLS

        // cmp dword [rax + 4], 0  ; uncaughtExceptions field
        seq.push(0x83); // CMP r/m32, imm8
        seq.push(0x78); // ModRM: [rax + disp8]
        seq.push(0x04); // disp8 = 4
        seq.push(0x00); // imm8 = 0

        // jz .Lno_exception
        seq.push(0x74); // JZ rel8
        seq.push(0x05); // skip next 5 bytes

        // call std::terminate
        seq.push(0xE8);
        seq.extend_from_slice(&0u32.to_le_bytes()); // placeholder

        seq
    }
}

// ============================================================================
// Transactional Memory EH Stubs
// ============================================================================

/// Support for Intel TSX transactional memory exception handling.
///
/// When a transaction aborts (_xabort), control transfers to the
/// `_xbegin` fallback path. The abort code indicates the reason.
#[derive(Debug, Clone)]
pub struct X86TMEHStub {
    /// XBEGIN fallback address.
    pub xbegin_fallback: u64,
    /// Abort status code.
    pub abort_code: u32,
    /// Whether the transaction was explicitly aborted (vs. conflict).
    pub explicit_abort: bool,
}

impl X86TMEHStub {
    /// Create a new transactional memory EH stub.
    pub fn new(fallback_addr: u64) -> Self {
        Self {
            xbegin_fallback: fallback_addr,
            abort_code: 0,
            explicit_abort: false,
        }
    }

    /// Generate the _xbegin instruction with a fallback address.
    ///
    /// `_xbegin` starts a transaction. If the transaction aborts,
    /// execution resumes at the fallback address with the abort
    /// status in eax.
    pub fn generate_xbegin_sequence(&self) -> Vec<u8> {
        // xbegin rel32
        let mut seq = Vec::new();
        seq.push(0xC7); // XBEGIN opcode
        seq.push(0xF8);
        // Relative offset to fallback
        let rel = (self.xbegin_fallback as i32).wrapping_sub(0);
        seq.extend_from_slice(&rel.to_le_bytes());
        seq
    }

    /// Generate the _xend instruction (end transaction).
    pub fn generate_xend() -> Vec<u8> {
        vec![0x0F, 0x01, 0xD5] // XEND
    }

    /// Generate the _xabort instruction with an abort code.
    pub fn generate_xabort(abort_code: u8) -> Vec<u8> {
        // xabort imm8
        vec![0xC6, 0xF8, abort_code] // XABORT
    }

    /// Generate the abort handler dispatch.
    ///
    /// Reads the abort status from eax and branches based on the code.
    pub fn generate_abort_dispatch(&self) -> Vec<u8> {
        let mut seq = Vec::new();

        // Check for explicit abort: test eax, 0x01
        seq.push(0xA9); // TEST eax, imm32
        seq.extend_from_slice(&1u32.to_le_bytes());
        seq.push(0x75); // JNZ explicit_abort_handler
        seq.push(0x10); // offset

        // Check for conflict abort: test eax, 0x02
        seq.push(0xA9);
        seq.extend_from_slice(&2u32.to_le_bytes());
        seq.push(0x75); // JNZ conflict_handler
        seq.push(0x10);

        // Check for capacity abort: test eax, 0x04
        seq.push(0xA9);
        seq.extend_from_slice(&4u32.to_le_bytes());
        seq.push(0x75); // JNZ capacity_handler
        seq.push(0x10);

        // Default: retry or fall through
        seq.push(0xEB); // JMP retry
        seq.push(0x0A);

        seq
    }
}

// ============================================================================
// X86EHLowering — Main Lowering Pass
// ============================================================================

/// Configuration for the EH lowering pass.
#[derive(Debug, Clone)]
pub struct X86EHLoweringConfig {
    /// The personality function to use.
    pub personality: X86PersonalityKind,
    /// Whether to emit LSDA (Itanium ABI).
    pub emit_lsda: bool,
    /// Whether to emit .xdata (Windows SEH).
    pub emit_xdata: bool,
    /// Whether to emit .eh_frame call-site information.
    pub emit_eh_frame: bool,
    /// Whether to outline landing pads into separate sections.
    pub outline_landing_pads: bool,
    /// Whether to merge identical landing pads.
    pub merge_landing_pads: bool,
    /// Whether to prune unreachable handlers.
    pub prune_unreachable_handlers: bool,
    /// Whether noexcept violations call std::terminate.
    pub noexcept_terminate: bool,
    /// Target triple.
    pub target_triple: String,
}

impl Default for X86EHLoweringConfig {
    fn default() -> Self {
        Self {
            personality: X86PersonalityKind::GxxPersonalityV0,
            emit_lsda: true,
            emit_xdata: false,
            emit_eh_frame: true,
            outline_landing_pads: false,
            merge_landing_pads: true,
            prune_unreachable_handlers: true,
            noexcept_terminate: true,
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
        }
    }
}

/// The main X86 EH lowering pass.
///
/// Transforms IR-level EH constructs (landingpad, resume, cleanupret,
/// etc.) into machine-level EH tables, dispatch sequences, and
/// personality function calls.
pub struct X86EHLowering {
    /// Configuration.
    pub config: X86EHLoweringConfig,
    /// Personality configuration.
    personality_config: X86PersonalityConfig,
    /// LSDA (Itanium EH).
    lsda: X86LSDA,
    /// .xdata (Windows SEH).
    xdata: X86XData,
    /// Landing pads for the current function.
    landing_pads: Vec<X86LandingPad>,
    /// Catch dispatch.
    catch_dispatch: X86CatchDispatch,
    /// Cleanup generator.
    cleanup_generator: X86CleanupGenerator,
    /// Terminate handler.
    terminate_handler: X86TerminateHandler,
    /// Transactional memory EH stubs.
    tm_stubs: Vec<X86TMEHStub>,
    /// Current function name.
    current_function: Option<String>,
    /// Next landing pad ID.
    next_lp_id: u32,
}

impl X86EHLowering {
    /// Create a new X86 EH lowering pass.
    pub fn new(config: X86EHLoweringConfig) -> Self {
        let personality_config = match config.personality {
            X86PersonalityKind::GxxPersonalityV0 => X86PersonalityConfig::gxx(),
            X86PersonalityKind::CxxFrameHandler3 => X86PersonalityConfig::cxx_frame_handler(),
            X86PersonalityKind::CSpecificHandler => X86PersonalityConfig::c_specific_handler(),
            _ => X86PersonalityConfig::default(),
        };

        Self {
            config,
            personality_config,
            lsda: X86LSDA::new(),
            xdata: X86XData::new(),
            landing_pads: Vec::new(),
            catch_dispatch: X86CatchDispatch::new(),
            cleanup_generator: X86CleanupGenerator::new(),
            terminate_handler: X86TerminateHandler::default(),
            tm_stubs: Vec::new(),
            current_function: None,
            next_lp_id: 0,
        }
    }

    /// Begin processing a function.
    pub fn begin_function(&mut self, name: &str, _address: u64) {
        self.current_function = Some(name.to_string());
        self.landing_pads.clear();
        self.lsda = X86LSDA::new();
        self.xdata = X86XData::new();
        self.next_lp_id = 0;
    }

    /// Add a landing pad to the current function.
    pub fn add_landing_pad(&mut self, offset: u32) -> u32 {
        let id = self.next_lp_id;
        self.next_lp_id += 1;
        self.landing_pads.push(X86LandingPad::new(id, offset));
        id
    }

    /// Add a catch clause to a landing pad.
    pub fn add_catch_clause(
        &mut self,
        lp_id: u32,
        type_info_addr: u64,
        type_name: &str,
        is_catch_all: bool,
    ) -> Option<u32> {
        let type_idx = if is_catch_all {
            u32::MAX // sentinel for catch-all
        } else {
            self.lsda.add_type(type_info_addr, type_name)
        };

        if let Some(lp) = self.landing_pads.iter_mut().find(|lp| lp.id == lp_id) {
            lp.add_catch(type_idx, type_name, is_catch_all);
            Some(type_idx)
        } else {
            None
        }
    }

    /// Add a cleanup clause to a landing pad.
    pub fn add_cleanup_clause(&mut self, lp_id: u32) -> bool {
        if let Some(lp) = self.landing_pads.iter_mut().find(|lp| lp.id == lp_id) {
            lp.add_cleanup();
            true
        } else {
            false
        }
    }

    /// Add a filter clause (exception specification) to a landing pad.
    pub fn add_filter_clause(
        &mut self,
        lp_id: u32,
        allowed_type_addrs: &[(u64, String)],
    ) -> Option<u32> {
        // Filter: an array of type_info pointers
        let filter_idx = self.lsda.type_table.len() as u32;
        let mut allowed_indices = Vec::new();
        for (addr, name) in allowed_type_addrs {
            let idx = self.lsda.add_type(*addr, name);
            allowed_indices.push(idx);
        }

        if let Some(lp) = self.landing_pads.iter_mut().find(|lp| lp.id == lp_id) {
            lp.add_filter(filter_idx, allowed_indices);
            Some(filter_idx)
        } else {
            None
        }
    }

    /// Register a destructor for cleanup.
    pub fn register_cleanup_destructor(
        &mut self,
        object_ptr_offset: i32,
        destructor_fn: Option<u64>,
    ) {
        self.cleanup_generator
            .register_destructor(X86CleanupDestructor {
                object_ptr_offset,
                destructor_fn,
                is_array: false,
                unconditional: true,
            });
    }

    /// Set the terminate handler address.
    pub fn set_terminate_handler(&mut self, addr: u64) {
        self.terminate_handler.terminate_fn_addr = addr;
    }

    /// Set the unexpected handler address.
    pub fn set_unexpected_handler(&mut self, addr: u64) {
        self.terminate_handler.unexpected_fn_addr = addr;
    }

    /// Add a transactional memory EH stub.
    pub fn add_tm_stub(&mut self, stub: X86TMEHStub) {
        self.tm_stubs.push(stub);
    }

    /// Merge identical landing pads.
    ///
    /// Two landing pads are identical if they have the same clauses
    /// in the same order. After merging, the duplicate is removed
    /// and references to it are redirected.
    pub fn merge_landing_pads(&mut self) -> usize {
        if !self.config.merge_landing_pads {
            return 0;
        }

        let mut removed = 0;
        let mut i = 0;
        while i < self.landing_pads.len() {
            let mut j = i + 1;
            while j < self.landing_pads.len() {
                if self.landing_pads[i].clauses.len() == self.landing_pads[j].clauses.len()
                    && self.landing_pads[i].has_cleanup == self.landing_pads[j].has_cleanup
                {
                    // Simplified: assume match if clause counts match
                    self.landing_pads.remove(j);
                    removed += 1;
                } else {
                    j += 1;
                }
            }
            i += 1;
        }
        removed
    }

    /// Prune unreachable handlers.
    ///
    /// A handler is unreachable if there's no call site that
    /// references its landing pad.
    pub fn prune_unreachable_handlers(&mut self, _reachable_lps: &HashSet<u32>) -> usize {
        if !self.config.prune_unreachable_handlers {
            return 0;
        }
        // Placeholder: all landing pads are kept
        0
    }

    /// Build the LSDA for the current function.
    pub fn build_lsda(&mut self, func_start: u64) -> &X86LSDA {
        // Build action table from landing pad clauses
        for lp in &self.landing_pads {
            let mut prev_action: Option<u32> = None;

            // Process clauses in reverse order
            for clause in lp.clauses.iter().rev() {
                match clause {
                    X86LandingPadClause::Catch {
                        type_index,
                        is_catch_all,
                        ..
                    } => {
                        if *is_catch_all {
                            // Catch-all: filter value of 0
                            let action_idx = self.lsda.add_cleanup_action(prev_action);
                            prev_action = Some(action_idx);
                        } else {
                            let action_idx = self.lsda.add_catch_action(*type_index, prev_action);
                            prev_action = Some(action_idx);
                        }
                    }
                    X86LandingPadClause::Cleanup { .. } => {
                        let action_idx = self.lsda.add_cleanup_action(prev_action);
                        prev_action = Some(action_idx);
                    }
                    X86LandingPadClause::Filter { filter_index, .. } => {
                        let action_idx = self.lsda.add_filter_action(*filter_index, prev_action);
                        prev_action = Some(action_idx);
                    }
                }
            }

            // Create a call-site entry for this landing pad
            let cs_action = prev_action.unwrap_or(0);
            self.lsda.add_call_site(
                0, // start offset (would be set from actual call sites)
                0, // length
                lp.offset, cs_action,
            );
        }

        &self.lsda
    }

    /// Build the .xdata for Windows SEH.
    pub fn build_xdata(&mut self) -> &X86XData {
        if let Some(handler) = self.xdata.handler_address {
            if handler != 0 {
                self.xdata.set_handler(handler);
            }
        }
        &self.xdata
    }

    /// Generate the landing pad dispatch sequence.
    pub fn generate_landing_pad_dispatch(&self, lp_id: u32) -> Option<Vec<u8>> {
        let lp = self.landing_pads.iter().find(|lp| lp.id == lp_id)?;
        Some(self.catch_dispatch.generate_dispatch_sequence(lp))
    }

    /// Generate the resume sequence (forward unhandled exception).
    ///
    /// The resume instruction forwards an exception to the next frame
    /// up the call stack. On X86-64:
    /// ```text
    /// mov rdi, r12      ; exception object (saved earlier)
    /// call _Unwind_Resume
    /// ```
    pub fn generate_resume_sequence() -> Vec<u8> {
        let mut seq = Vec::new();
        // mov rdi, r12 (exception object)
        seq.push(0x4C);
        seq.push(0x89);
        seq.push(0xE7);
        // call _Unwind_Resume
        seq.push(0xE8);
        seq.extend_from_slice(&0u32.to_le_bytes());
        seq
    }

    /// End processing a function and return the built EH data.
    pub fn end_function(&mut self, func_start: u64) -> X86EHLoweringResult {
        self.build_lsda(func_start);
        self.build_xdata();

        X86EHLoweringResult {
            function_name: self.current_function.take().unwrap_or_default(),
            personality: self.config.personality,
            lsda: self.lsda.clone(),
            xdata: self.xdata.clone(),
            landing_pads: self.landing_pads.clone(),
            lsda_encoded: self.lsda.encode(),
            xdata_encoded: self.xdata.encode(),
            has_cleanup: self.landing_pads.iter().any(|lp| lp.has_cleanup),
            num_landing_pads: self.landing_pads.len(),
            num_types: self.lsda.type_table.len(),
        }
    }

    /// Get the personality symbol name.
    pub fn personality_symbol(&self) -> &'static str {
        self.personality_config.kind.symbol_name()
    }
}

// ============================================================================
// EH Lowering Result
// ============================================================================

/// The result of EH lowering for a function.
#[derive(Debug, Clone)]
pub struct X86EHLoweringResult {
    /// Function name.
    pub function_name: String,
    /// Personality function kind.
    pub personality: X86PersonalityKind,
    /// Built LSDA.
    pub lsda: X86LSDA,
    /// Built .xdata.
    pub xdata: X86XData,
    /// Landing pads.
    pub landing_pads: Vec<X86LandingPad>,
    /// Encoded LSDA bytes.
    pub lsda_encoded: Vec<u8>,
    /// Encoded .xdata bytes.
    pub xdata_encoded: Vec<u8>,
    /// Whether the function has any cleanup clauses.
    pub has_cleanup: bool,
    /// Number of landing pads.
    pub num_landing_pads: usize,
    /// Number of type info entries.
    pub num_types: usize,
}

impl X86EHLoweringResult {
    /// Check if the function needs an LSDA.
    pub fn needs_lsda(&self) -> bool {
        self.personality.uses_lsda() && !self.landing_pads.is_empty()
    }

    /// Check if the function needs .xdata.
    pub fn needs_xdata(&self) -> bool {
        self.personality.uses_xdata() && !self.landing_pads.is_empty()
    }

    /// Get total EH data size.
    pub fn eh_data_size(&self) -> usize {
        self.lsda_encoded.len() + self.xdata_encoded.len()
    }
}

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

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

    #[test]
    fn test_personality_kinds() {
        assert_eq!(
            X86PersonalityKind::GxxPersonalityV0.symbol_name(),
            "__gxx_personality_v0"
        );
        assert!(X86PersonalityKind::GxxPersonalityV0.uses_lsda());
        assert!(!X86PersonalityKind::GxxPersonalityV0.uses_xdata());

        assert_eq!(
            X86PersonalityKind::CxxFrameHandler3.symbol_name(),
            "__CxxFrameHandler3"
        );
        assert!(!X86PersonalityKind::CxxFrameHandler3.uses_lsda());
        assert!(X86PersonalityKind::CxxFrameHandler3.uses_xdata());
    }

    #[test]
    fn test_lsda_encoding() {
        let mut lsda = X86LSDA::new();

        let ti0 = lsda.add_type(0x401000, "std::exception");
        let ti1 = lsda.add_type(0x402000, "MyException");

        lsda.add_call_site(0x10, 0x20, 0x100, 0);

        let catch_idx = lsda.add_catch_action(ti0, None);
        lsda.add_call_site(0x40, 0x30, 0x200, catch_idx);

        let encoded = lsda.encode();
        assert!(!encoded.is_empty());

        // LSDA starts with LPStart encoding
        assert_eq!(encoded[0], X86_EH_LSDA_ENCODING);
    }

    #[test]
    fn test_lsda_action_table() {
        let mut lsda = X86LSDA::new();

        // Add types
        let ti0 = lsda.add_type(0x401000, "TypeA");
        let ti1 = lsda.add_type(0x402000, "TypeB");

        // Chain: catch TypeA, then catch TypeB
        let action_b = lsda.add_catch_action(ti1, None);
        let action_a = lsda.add_catch_action(ti0, Some(action_b));

        assert_eq!(lsda.action_table.len(), 2);
        // First action: catch TypeA, next = action_b
        assert_eq!(lsda.action_table[0].type_filter, ti0 as i32 + 1);
        assert_eq!(lsda.action_table[0].next_action_offset, action_b as i32);
    }

    #[test]
    fn test_lsda_cleanup_action() {
        let mut lsda = X86LSDA::new();

        let cleanup_idx = lsda.add_cleanup_action(None);
        assert_eq!(lsda.action_table.len(), 1);
        assert_eq!(lsda.action_table[0].type_filter, 0); // cleanup
    }

    #[test]
    fn test_lsda_filter_action() {
        let mut lsda = X86LSDA::new();

        // Add types for filter
        lsda.add_type(0x401000, "TypeA");
        lsda.add_type(0x402000, "TypeB");

        let filter_idx = lsda.add_filter_action(0, None);
        assert_eq!(lsda.action_table.len(), 1);
        assert_eq!(lsda.action_table[0].type_filter, -1); // filter, index 0 -> -(0+1)
    }

    #[test]
    fn test_landing_pad_creation() {
        let mut lp = X86LandingPad::new(0, 0x100);

        lp.add_catch(0, "std::exception", false);
        lp.add_cleanup();
        lp.add_catch(1, "MyException", false);

        assert_eq!(lp.num_catches(), 2);
        assert!(lp.has_cleanup);
        assert_eq!(lp.num_filters(), 0);
    }

    #[test]
    fn test_xdata_encoding() {
        let mut xdata = X86XData::new();
        xdata.prologue_size = 16;
        xdata.frame_register = DW_RBP as u8;
        xdata.frame_register_offset = 2;

        xdata.add_unwind_code(X86UnwindCode::PushNonVolatile {
            op_reg: DW_RBP as u8,
        });
        xdata.add_unwind_code(X86UnwindCode::AllocSmall { alloc_size: 2 }); // 16 bytes

        let encoded = xdata.encode();
        assert!(!encoded.is_empty());
        assert_eq!(encoded[0] & 0x07, 1); // version = 1
    }

    #[test]
    fn test_xdata_with_handler() {
        let mut xdata = X86XData::new();
        xdata.set_handler(0x401000);

        let encoded = xdata.encode();
        assert!(!encoded.is_empty());
        assert!(encoded[0] & 0x08 != 0); // EHANDLER flag set
    }

    #[test]
    fn test_catch_dispatch_generation() {
        let mut lp = X86LandingPad::new(0, 0x100);
        lp.add_catch(0, "std::runtime_error", false);

        let dispatch = X86CatchDispatch::new();
        let seq = dispatch.generate_dispatch_sequence(&lp);
        assert!(seq.len() > 10);
    }

    #[test]
    fn test_cleanup_sequence_generation() {
        let mut r#gen = X86CleanupGenerator::new();
        r#gen.register_destructor(X86CleanupDestructor {
            object_ptr_offset: -8,
            destructor_fn: Some(0x401000),
            is_array: false,
            unconditional: true,
        });

        let seq = r#gen.generate_cleanup_sequence();
        assert!(seq.len() > 5);
    }

    #[test]
    fn test_terminate_handler() {
        let handler = X86TerminateHandler {
            terminate_fn_addr: 0x405000,
            unexpected_fn_addr: 0x406000,
            noexcept_calls_terminate: true,
        };

        let seq = handler.generate_terminate_call();
        assert_eq!(seq[0], 0xFF); // CALL
        assert_eq!(seq[1], 0x15); // Indirect RIP-relative

        let noex = handler.generate_noexcept_check();
        assert!(noex.len() > 10);
    }

    #[test]
    fn test_tm_stubs() {
        let stub = X86TMEHStub::new(0x401000);

        let xbegin = stub.generate_xbegin_sequence();
        assert_eq!(xbegin[0], 0xC7); // XBEGIN
        assert_eq!(xbegin[1], 0xF8);

        let xend = X86TMEHStub::generate_xend();
        assert_eq!(xend, vec![0x0F, 0x01, 0xD5]);

        let xabort = X86TMEHStub::generate_xabort(42);
        assert_eq!(xabort[0], 0xC6);
        assert_eq!(xabort[1], 0xF8);
        assert_eq!(xabort[2], 42);
    }

    #[test]
    fn test_eh_lowering_full_pipeline() {
        let config = X86EHLoweringConfig::default();
        let mut lowering = X86EHLowering::new(config);

        lowering.begin_function("test_eh", 0x400000);

        // Add a landing pad with catch and cleanup
        let lp_id = lowering.add_landing_pad(0x120);
        lowering.add_catch_clause(lp_id, 0x500000, "std::exception", false);
        lowering.add_cleanup_clause(lp_id);

        // Add a second landing pad
        let lp2_id = lowering.add_landing_pad(0x200);
        lowering.add_catch_clause(lp2_id, 0x501000, "MyException", false);
        lowering.add_catch_clause(lp2_id, 0, "...", true); // catch-all

        // Register a cleanup destructor
        lowering.register_cleanup_destructor(-16, Some(0x502000));

        // Merge landing pads
        let merged = lowering.merge_landing_pads();
        let _ = merged;

        // Finalize
        let result = lowering.end_function(0x400000);

        assert_eq!(result.function_name, "test_eh");
        assert_eq!(result.personality, X86PersonalityKind::GxxPersonalityV0);
        assert!(result.has_cleanup);
        assert!(result.num_landing_pads > 0);

        // Check LSDA encoding
        assert!(!result.lsda_encoded.is_empty());
    }

    #[test]
    fn test_pointer_adjustment() {
        // Adjust by +16 bytes (base class subobject)
        let seq = X86CatchDispatch::generate_pointer_adjustment(16, 0); // rax
        assert!(seq.len() > 0);

        // Zero adjustment should be a no-op
        let seq2 = X86CatchDispatch::generate_pointer_adjustment(0, 0);
        assert!(seq2.is_empty());
    }

    #[test]
    fn test_resume_sequence() {
        let seq = X86EHLowering::generate_resume_sequence();
        assert!(seq.len() > 0);
    }

    #[test]
    fn test_unwind_code_op_codes() {
        assert_eq!(X86UnwindCode::PushNonVolatile { op_reg: 0 }.op_code(), 0);
        assert_eq!(X86UnwindCode::AllocLarge { alloc_size: 0 }.op_code(), 1);
        assert_eq!(X86UnwindCode::AllocSmall { alloc_size: 0 }.op_code(), 2);
        assert_eq!(X86UnwindCode::SetFPReg.op_code(), 3);
    }

    #[test]
    fn test_unwind_code_slot_counts() {
        assert_eq!(X86UnwindCode::PushNonVolatile { op_reg: 0 }.slot_count(), 1);
        assert_eq!(
            X86UnwindCode::AllocLarge { alloc_size: 0x100 }.slot_count(),
            2
        );
        assert_eq!(
            X86UnwindCode::AllocLarge {
                alloc_size: 0x10000
            }
            .slot_count(),
            3
        );
        assert_eq!(X86UnwindCode::AllocSmall { alloc_size: 0 }.slot_count(), 1);
    }

    #[test]
    fn test_landing_pad_clause_filter() {
        let mut lp = X86LandingPad::new(0, 0x100);
        lp.add_filter(0, vec![0, 1, 2]);
        assert_eq!(lp.num_filters(), 1);

        lp.add_filter(1, vec![3]);
        assert_eq!(lp.num_filters(), 2);
    }

    #[test]
    fn test_lsda_uleb128_encoding() {
        let mut buf = Vec::new();

        // Encode 0
        X86LSDA::encode_uleb128(&mut buf, 0);
        assert_eq!(buf.len(), 1);
        assert_eq!(buf[0], 0);

        buf.clear();
        // Encode 127
        X86LSDA::encode_uleb128(&mut buf, 127);
        assert_eq!(buf.len(), 1);
        assert_eq!(buf[0], 127);

        buf.clear();
        // Encode 128
        X86LSDA::encode_uleb128(&mut buf, 128);
        assert_eq!(buf.len(), 2);
        assert_eq!(buf[0], 0x80);
        assert_eq!(buf[1], 0x01);
    }

    #[test]
    fn test_lsda_sleb128_encoding() {
        let mut buf = Vec::new();

        // Encode 0
        X86LSDA::encode_sleb128(&mut buf, 0);
        assert_eq!(buf.len(), 1);
        assert_eq!(buf[0], 0);

        buf.clear();
        // Encode -1
        X86LSDA::encode_sleb128(&mut buf, -1);
        assert_eq!(buf.len(), 1);
        assert_eq!(buf[0], 0x7F);

        buf.clear();
        // Encode 64
        X86LSDA::encode_sleb128(&mut buf, 64);
        assert_eq!(buf.len(), 1);
        assert_eq!(buf[0], 0x40);
    }

    #[test]
    fn test_eh_result_needs_lsda() {
        let config = X86EHLoweringConfig::default();
        let mut lowering = X86EHLowering::new(config);
        lowering.begin_function("test", 0x400000);

        let lp_id = lowering.add_landing_pad(0x100);
        lowering.add_catch_clause(lp_id, 0x500000, "std::exception", false);

        let result = lowering.end_function(0x400000);
        assert!(result.needs_lsda());
        assert!(!result.needs_xdata());
        assert!(result.eh_data_size() > 0);
    }

    #[test]
    fn test_seh_xdata_encoding_empty() {
        let xdata = X86XData::new();
        let encoded = xdata.encode();
        assert!(!encoded.is_empty());
        assert_eq!(encoded[0] & 0x07, 1); // version
    }

    #[test]
    fn test_seh_xdata_with_termination_handler() {
        let mut xdata = X86XData::new();
        xdata.set_termination_handler(0x500000);
        assert!(xdata.flags & 0x02 != 0);

        let encoded = xdata.encode();
        assert!(!encoded.is_empty());
    }

    #[test]
    fn test_seh_xdata_push_nonvolatile() {
        let mut xdata = X86XData::new();
        xdata.add_unwind_code(X86UnwindCode::PushNonVolatile {
            op_reg: DW_RBP as u8,
        });
        xdata.add_unwind_code(X86UnwindCode::PushNonVolatile {
            op_reg: DW_RBX as u8,
        });
        assert_eq!(xdata.unwind_code_count, 2);

        let encoded = xdata.encode();
        assert!(encoded.len() > 4);
    }

    #[test]
    fn test_seh_xdata_alloc_small() {
        let mut xdata = X86XData::new();
        xdata.prologue_size = 8;
        xdata.add_unwind_code(X86UnwindCode::AllocSmall { alloc_size: 1 }); // 8 bytes

        let encoded = xdata.encode();
        assert!(encoded.len() > 0);
    }

    #[test]
    fn test_landing_pad_catch_all() {
        let mut lp = X86LandingPad::new(0, 0x100);
        lp.add_catch(0xFFFFFFFF, "...", true);
        lp.add_cleanup();

        assert_eq!(lp.num_catches(), 1);
        assert!(lp.has_cleanup);

        // Verify catch-all detection
        let has_catch_all = lp.clauses.iter().any(|c| {
            matches!(
                c,
                X86LandingPadClause::Catch {
                    is_catch_all: true,
                    ..
                }
            )
        });
        assert!(has_catch_all);
    }

    #[test]
    fn test_lsda_multiple_call_sites() {
        let mut lsda = X86LSDA::new();
        lsda.add_type(0x401000, "TypeA");
        lsda.add_type(0x402000, "TypeB");

        // Call site 1: cleanup only
        lsda.add_call_site(0x10, 0x20, 0x100, 0);

        // Call site 2: catch TypeA
        let action = lsda.add_catch_action(0, None);
        lsda.add_call_site(0x40, 0x30, 0x200, action);

        // Call site 3: catch TypeA then TypeB
        let action_b = lsda.add_catch_action(1, None);
        let action_a = lsda.add_catch_action(0, Some(action_b));
        lsda.add_call_site(0x80, 0x20, 0x300, action_a);

        assert_eq!(lsda.call_site_table.len(), 3);
        assert_eq!(lsda.action_table.len(), 3);
    }

    #[test]
    fn test_personality_config_gxx() {
        let config = X86PersonalityConfig::gxx();
        assert_eq!(config.kind, X86PersonalityKind::GxxPersonalityV0);
        assert!(config.supports_cleanup);
        assert!(config.supports_catch);
        assert!(config.supports_filter);
        assert!(config.catch_foreign_exceptions);
    }

    #[test]
    fn test_personality_config_cxx() {
        let config = X86PersonalityConfig::cxx_frame_handler();
        assert_eq!(config.kind, X86PersonalityKind::CxxFrameHandler3);
        assert!(config.type_matching_by_pointer);
        assert!(!config.supports_filter);
    }

    #[test]
    fn test_cleanuppad_prologue() {
        let r#gen = X86CleanupGenerator::new();
        let seq = r#gen.generate_cleanuppad_prologue();
        assert_eq!(seq[0], 0x55); // push rbp
        assert!(seq.len() >= 3);
    }

    #[test]
    fn test_cleanupret_sequence() {
        let seq = X86CleanupGenerator::generate_cleanupret();
        assert_eq!(seq, vec![0x5B, 0x5D, 0xC3]); // pop rbx; pop rbp; ret
    }

    #[test]
    fn test_tm_abort_dispatch() {
        let stub = X86TMEHStub::new(0x401000);
        let seq = stub.generate_abort_dispatch();
        assert!(seq.len() > 10);
        // Should contain TEST instructions
        assert!(seq.contains(&0xA9));
    }

    #[test]
    fn test_eh_lowering_with_seh_personality() {
        let config = X86EHLoweringConfig {
            personality: X86PersonalityKind::CxxFrameHandler3,
            emit_xdata: true,
            emit_lsda: false,
            ..Default::default()
        };
        let mut lowering = X86EHLowering::new(config);
        lowering.begin_function("seh_func", 0x400000);

        let lp_id = lowering.add_landing_pad(0x100);
        lowering.add_catch_clause(lp_id, 0x500000, "std::exception", false);

        let result = lowering.end_function(0x400000);
        assert!(!result.needs_lsda());
        assert!(result.personality.uses_xdata());
    }

    #[test]
    fn test_eh_lowering_noexcept() {
        let handler = X86TerminateHandler {
            terminate_fn_addr: 0x405000,
            unexpected_fn_addr: 0x406000,
            noexcept_calls_terminate: true,
        };
        let seq = handler.generate_noexcept_check();
        assert!(seq.len() > 10);
        // Should contain FS segment prefix (0x64)
        assert!(seq.contains(&0x64));
    }

    #[test]
    fn test_lsda_all_clause_types() {
        let mut lowering = X86EHLowering::new(X86EHLoweringConfig::default());
        lowering.begin_function("all_clauses", 0x400000);

        let lp_id = lowering.add_landing_pad(0x200);
        lowering.add_catch_clause(lp_id, 0x501000, "TypeA", false);
        lowering.add_cleanup_clause(lp_id);
        lowering.add_catch_clause(lp_id, 0, "...", true);

        lowering.add_filter_clause(
            lp_id,
            &[
                (0x502000, "TypeB".to_string()),
                (0x503000, "TypeC".to_string()),
            ],
        );

        let result = lowering.end_function(0x400000);
        assert!(result.num_landing_pads == 1);
        assert!(result.num_types >= 2);
        assert!(result.has_cleanup);
    }

    #[test]
    fn test_eh_intrinsic_display() {
        assert_eq!(X86EHIntrinsicKind::LandingPad.to_string(), "landingpad");
        assert_eq!(X86EHIntrinsicKind::Resume.to_string(), "resume");
        assert_eq!(X86EHIntrinsicKind::CatchRet.to_string(), "catchret");
        assert_eq!(X86EHIntrinsicKind::CleanupRet.to_string(), "cleanupret");
        assert_eq!(X86EHIntrinsicKind::CatchSwitch.to_string(), "catchswitch");
        assert_eq!(X86EHIntrinsicKind::CatchPad.to_string(), "catchpad");
        assert_eq!(X86EHIntrinsicKind::CleanupPad.to_string(), "cleanuppad");
        assert_eq!(X86EHIntrinsicKind::BeginCatch.to_string(), "begin.catch");
        assert_eq!(X86EHIntrinsicKind::EndCatch.to_string(), "end.catch");
        assert_eq!(X86EHIntrinsicKind::EHTypeidFor.to_string(), "eh.typeid.for");
    }

    #[test]
    fn test_personality_kind_display() {
        assert_eq!(
            X86PersonalityKind::GxxPersonalityV0.to_string(),
            "__gxx_personality_v0"
        );
        assert_eq!(
            X86PersonalityKind::CxxFrameHandler3.to_string(),
            "__CxxFrameHandler3"
        );
        assert_eq!(
            X86PersonalityKind::CSpecificHandler.to_string(),
            "__C_specific_handler"
        );
    }

    #[test]
    fn test_lsda_sleb128_negative_values() {
        let mut buf = Vec::new();
        X86LSDA::encode_sleb128(&mut buf, -2);
        assert_eq!(buf.len(), 1);
        assert_eq!(buf[0], 0x7E);
    }

    #[test]
    fn test_frame_info_combination() {
        let frame_info = (DW_RBP as u8 & 0x0F) | ((2u8 & 0x0F) << 4);
        assert_eq!(frame_info & 0x0F, DW_RBP as u8); // frame register
        assert_eq!((frame_info >> 4) & 0x0F, 2); // offset
    }
}