llvm-native-core 0.1.15

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
//! X86 Coroutine Lowering — complete C++20 coroutine lowering for X86 targets
//! including frame layout, suspend/resume/destroy functions, ramp function,
//! symmetric transfer optimization, heap elision, and coroutine-specific ABI.
//!
//! Clean-room behavioral reconstruction from:
//! - C++20 Coroutines Technical Specification (N4861, [dcl.fct.def.coroutine])
//! - LLVM Coroutine intrinsics documentation (coro.id, coro.begin, coro.end,
//!   coro.suspend, coro.free, coro.alloc, coro.frame, coro.save, coro.promise,
//!   coro.size, coro.align, coro.resume, coro.destroy)
//! - System V AMD64 ABI (register conventions, stack alignment)
//! - Intel® 64 and IA-32 Architectures Software Developer's Manual
//! - "Asymmetric Transfer" and "Symmetric Transfer" coroutine optimization
//!   literature (Gor Nishanov, Lewis Baker)
//! - Published coroutine frame layout descriptions
//!
//! Zero LLVM source code consultation. All behavior reconstructed from
//! published specifications and black-box oracle interrogation.
//!
//! ## Subsystems
//!
//! - **X86CoroLowering** — main lowering pass: splits coroutine into resume,
//!   destroy, cleanup, and ramp functions.
//! - **X86CoroFrame** — coroutine frame layout computation: promise,
//!   parameters, locals, spills, suspend-index, and resume-address fields.
//! - **X86CoroSuspend** — suspension point lowering: state numbering,
//!   switch dispatch, spill/reload of live values.
//! - **X86CoroResume** — resume function generation: dispatch to the correct
//!   suspend point via switch on the resume index.
//! - **X86CoroDestroy** — destroy function generation: cleanup active
//!   scopes (destructors) and deallocate the frame.
//! - **X86CoroRamp** — ramp function: allocates frame, stores parameters,
//!   invokes the coroutine body, returns handle.
//! - **X86CoroHeapElision** — heap elision optimization: allocates the
//!   coroutine frame on the caller's stack when the coroutine lifetime
//!   is bounded by the caller.
//! - **X86CoroSymmetricTransfer** — symmetric transfer optimization:
//!   `coro.resume` of another coroutine becomes a tail call, avoiding
//!   stack growth in chains of coroutine resumptions.
//! - **X86CoroFrameABI** — coroutine ABI for X86-64: handle layout,
//!   promise access, destroy/resume function pointers.

#![allow(non_upper_case_globals, dead_code)]

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

use crate::codegen::MachineInstr;

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

/// Default coroutine frame alignment (must be at least 2*sizeof(void*)).
pub const X86_CORO_FRAME_ALIGNMENT: u32 = 16;

/// Minimum coroutine frame size (header + space for at least one value).
pub const X86_CORO_MIN_FRAME_SIZE: u32 = 64;

/// Default size of the coroutine frame header (resume fn ptr, destroy fn
/// ptr, promise offset, state index, flags).
pub const X86_CORO_FRAME_HEADER_SIZE: u32 = 40;

/// Default alignment of the promise object within the frame.
pub const X86_CORO_PROMISE_ALIGNMENT: u32 = 16;

/// Maximum number of suspend points per coroutine.
pub const X86_CORO_MAX_SUSPEND_POINTS: usize = 256;

/// Maximum number of spills per coroutine.
pub const X86_CORO_MAX_SPILLS: usize = 512;

/// State value representing "not started."
pub const X86_CORO_STATE_NOT_STARTED: u32 = 0;

/// State value representing "completed / final suspend."
pub const X86_CORO_STATE_DONE: u32 = 0xFFFFFFFF;

/// The number of reserved state values before user suspend points.
pub const X86_CORO_STATE_RESERVED: u32 = 2;

/// Max frame size for heap elision (bytes). Frames larger than this
/// are always heap-allocated.
pub const X86_CORO_HEAP_ELISION_MAX_SIZE: u32 = 4096;

/// Default alignment for coroutine handle on the stack during ramp.
pub const X86_CORO_HANDLE_ALIGNMENT: u32 = 8;

// ============================================================================
// Coroutine Intrinsic Kinds
// ============================================================================

/// Identifiers for coroutine intrinsics as lowered on X86.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum X86CoroIntrinsicKind {
    /// coro.id: creates a token that identifies this coroutine.
    CoroId,
    /// coro.id.retcon: creates a token for a "return continuation" coroutine.
    CoroIdRetcon,
    /// coro.id.retcon.once: one-shot return continuation.
    CoroIdRetconOnce,
    /// coro.begin: initializes the coroutine frame from a coro.id token.
    CoroBegin,
    /// coro.end: marks the logical end of the coroutine body.
    CoroEnd,
    /// coro.suspend: suspends the coroutine at the given point.
    CoroSuspend,
    /// coro.suspend.retcon: suspension for return-continuation coroutines.
    CoroSuspendRetcon,
    /// coro.free: deallocates the coroutine frame memory.
    CoroFree,
    /// coro.alloc: allocates memory for the coroutine frame.
    CoroAlloc,
    /// coro.frame: returns a pointer to the coroutine frame.
    CoroFrame,
    /// coro.save: saves the current coroutine state before a suspend.
    CoroSave,
    /// coro.promise: returns the address of the promise object.
    /// Takes (align, from) as parameters.
    CoroPromise,
    /// coro.size: returns the required size of the coroutine frame.
    /// Takes an alignment as a parameter.
    CoroSize,
    /// coro.align: returns the required alignment of the coroutine frame.
    CoroAlign,
    /// coro.resume: resumes the coroutine from the last suspend point.
    CoroResume,
    /// coro.destroy: destroys the coroutine, running cleanups.
    CoroDestroy,
    /// coro.done: checks whether the coroutine has completed.
    CoroDone,
}

impl fmt::Display for X86CoroIntrinsicKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Self::CoroId => "coro.id",
            Self::CoroIdRetcon => "coro.id.retcon",
            Self::CoroIdRetconOnce => "coro.id.retcon.once",
            Self::CoroBegin => "coro.begin",
            Self::CoroEnd => "coro.end",
            Self::CoroSuspend => "coro.suspend",
            Self::CoroSuspendRetcon => "coro.suspend.retcon",
            Self::CoroFree => "coro.free",
            Self::CoroAlloc => "coro.alloc",
            Self::CoroFrame => "coro.frame",
            Self::CoroSave => "coro.save",
            Self::CoroPromise => "coro.promise",
            Self::CoroSize => "coro.size",
            Self::CoroAlign => "coro.align",
            Self::CoroResume => "coro.resume",
            Self::CoroDestroy => "coro.destroy",
            Self::CoroDone => "coro.done",
        };
        write!(f, "{}", s)
    }
}

// ============================================================================
// Coroutine Frame Layout
// ============================================================================

/// Describes the in-memory layout of the coroutine frame on X86.
///
/// The frame layout (from low to high addresses) is:
/// ```text
/// +----------------------------------------+
/// | Resume function pointer (8 bytes)       |  <- frame pointer
/// +----------------------------------------+
/// | Destroy function pointer (8 bytes)      |
/// +----------------------------------------+
/// | Flags / Index (4 bytes)                 |
/// +----------------------------------------+
/// | Promise alignment padding (variable)    |
/// +----------------------------------------+
/// | Promise object (variable size)          |
/// +----------------------------------------+
/// | Copy of coroutine parameters (variable) |
/// +----------------------------------------+
/// | Local variable spills (variable)        |
/// +----------------------------------------+
/// | Stack space for nested calls (variable) |
/// +----------------------------------------+
/// ```
#[derive(Debug, Clone)]
pub struct X86CoroFrameLayout {
    /// Total frame size in bytes.
    pub total_size: u32,
    /// Frame alignment.
    pub alignment: u32,
    /// Offset of the resume function pointer from frame start.
    pub resume_fn_offset: u32,
    /// Offset of the destroy function pointer.
    pub destroy_fn_offset: u32,
    /// Offset of the state index / flags field.
    pub index_offset: u32,
    /// Offset of the promise object.
    pub promise_offset: u32,
    /// Size of the promise object.
    pub promise_size: u32,
    /// Number of parameter spills.
    pub num_params: u32,
    /// Offset where parameter spills begin.
    pub params_offset: u32,
    /// Number of local variable spills.
    pub num_locals: u32,
    /// Offset where local variable spills begin.
    pub locals_offset: u32,
    /// Number of additional spill slots.
    pub num_spills: u32,
    /// Offset where additional spill slots begin.
    pub spills_offset: u32,
    /// Whether the frame is heap-allocated.
    pub is_heap: bool,
    /// Frame size before heap elision decision (may differ if elided).
    pub unelided_size: u32,
}

impl Default for X86CoroFrameLayout {
    fn default() -> Self {
        Self {
            total_size: X86_CORO_MIN_FRAME_SIZE,
            alignment: X86_CORO_FRAME_ALIGNMENT,
            resume_fn_offset: 0,
            destroy_fn_offset: 8,
            index_offset: 16,
            promise_offset: 24,
            promise_size: 0,
            num_params: 0,
            params_offset: 0,
            num_locals: 0,
            locals_offset: 0,
            num_spills: 0,
            spills_offset: 0,
            is_heap: true,
            unelided_size: X86_CORO_MIN_FRAME_SIZE,
        }
    }
}

impl X86CoroFrameLayout {
    /// Compute offsets based on promise size and the number of each
    /// variable category.
    pub fn compute(
        promise_size: u32,
        promise_alignment: u32,
        num_params: u32,
        params_total_size: u32,
        num_locals: u32,
        locals_total_size: u32,
        num_spills: u32,
        spills_total_size: u32,
    ) -> Self {
        let mut layout = Self::default();

        // Header fixed fields:
        //   resume_fn: 8 bytes at offset 0
        //   destroy_fn: 8 bytes at offset 8
        //   index/flags: 4 bytes at offset 16
        let mut offset = 24u32;

        // Align for promise
        let align = promise_alignment.max(layout.alignment);
        offset = (offset + align - 1) & !(align - 1);
        layout.promise_offset = offset;
        layout.promise_size = promise_size;
        offset += promise_size;

        // Parameters
        if num_params > 0 {
            layout.num_params = num_params;
            layout.params_offset = offset;
            offset += params_total_size;
        }

        // Local variable spills
        if num_locals > 0 {
            layout.num_locals = num_locals;
            layout.locals_offset = offset;
            offset += locals_total_size;
        }

        // Additional spills
        if num_spills > 0 {
            layout.num_spills = num_spills;
            layout.spills_offset = offset;
            offset += spills_total_size;
        }

        // Final size and alignment
        layout.total_size = (offset + layout.alignment - 1) & !(layout.alignment - 1);
        layout.unelided_size = layout.total_size;
        layout.alignment = layout.alignment.max(align);

        layout
    }

    /// Get the total size rounded up to alignment.
    pub fn aligned_size(&self) -> u32 {
        (self.total_size + self.alignment - 1) & !(self.alignment - 1)
    }

    /// Read the current state index from the frame.
    /// Access pattern: `mov eax, [frame + index_offset]`
    pub fn generate_read_state(&self, frame_reg: u16) -> Vec<u8> {
        self.generate_mov_from_frame(frame_reg, self.index_offset, 4)
    }

    /// Write a new state index into the frame.
    pub fn generate_set_state(&self, frame_reg: u16, new_state: u32) -> Vec<u8> {
        let mut seq = Vec::new();
        // mov dword [frame_reg + index_offset], new_state
        if frame_reg >= 8 {
            seq.push(0x41); // REX.B prefix
        }
        seq.push(0xC7); // MOV r/m32, imm32
        let modrm = if frame_reg == 4 {
            // RSP needs SIB
            0x44 // mod=01, reg=000, r/m=100 (SIB follows)
        } else {
            (0x40u16 | (frame_reg & 0x07)) as u8 // mod=01, reg=000, r/m=frame_reg
        };
        seq.push(modrm);
        if frame_reg == 4 {
            seq.push(0x24); // SIB: scale=00, index=100 (none), base=100 (RSP)
        }
        let disp = self.index_offset as u8;
        seq.push(disp);
        seq.extend_from_slice(&new_state.to_le_bytes());
        seq
    }

    /// Load the resume function pointer.
    pub fn generate_load_resume_fn(&self, frame_reg: u16, dest_reg: u16) -> Vec<u8> {
        // mov dest_reg, [frame_reg + resume_fn_offset]
        let mut seq = Vec::new();
        // REX.W + REX.R
        let rex: u8 =
            0x48 | if dest_reg >= 8 { 0x04 } else { 0 } | if frame_reg >= 8 { 0x01 } else { 0 };
        seq.push(rex);
        seq.push(0x8B); // MOV r64, r/m64
        let modrm = (0x40u16 | ((dest_reg & 0x07) << 3) | (frame_reg & 0x07)) as u8;
        seq.push(modrm);
        let disp = self.resume_fn_offset as u8;
        seq.push(disp);
        seq
    }

    /// Load the destroy function pointer.
    pub fn generate_load_destroy_fn(&self, frame_reg: u16, dest_reg: u16) -> Vec<u8> {
        let mut seq = Vec::new();
        let rex: u8 =
            0x48 | if dest_reg >= 8 { 0x04 } else { 0 } | if frame_reg >= 8 { 0x01 } else { 0 };
        seq.push(rex);
        seq.push(0x8B); // MOV r64, r/m64
        let modrm = (0x40u16 | ((dest_reg & 0x07) << 3) | (frame_reg & 0x07)) as u8;
        seq.push(modrm);
        let disp = self.destroy_fn_offset as u8;
        seq.push(disp);
        seq
    }

    /// Generate a memory access: `mov dest_reg, [frame_reg + offset]`
    fn generate_mov_from_frame(&self, frame_reg: u16, offset: u32, size: u32) -> Vec<u8> {
        let mut seq = Vec::new();
        let rex: u8 = if size == 8 { 0x48 } else { 0 };
        seq.push(rex);
        seq.push(if size == 8 { 0x8B } else { 0x8B }); // MOV
                                                       // Simplified: for full generality, handle all addressing modes.
        seq.push((0x40u16 | (frame_reg & 0x07)) as u8);
        seq.push(offset as u8);
        seq
    }
}

// ============================================================================
// Suspend Point
// ============================================================================

/// Flags describing a suspend point.
#[derive(Debug, Clone, Copy)]
pub struct X86CoroSuspendFlags {
    /// This is a final suspend (coroutine completes after this).
    pub is_final: bool,
    /// The suspend may throw or unwind.
    pub may_unwind: bool,
    /// This is a "retcon" (return continuation) suspend.
    pub is_retcon: bool,
    /// Values across this suspend can be elided.
    pub can_elide: bool,
}

impl Default for X86CoroSuspendFlags {
    fn default() -> Self {
        Self {
            is_final: false,
            may_unwind: false,
            is_retcon: false,
            can_elide: false,
        }
    }
}

/// A suspension point in a coroutine.
///
/// Each coro.suspend becomes a suspend point. The coroutine saves its
/// state before the suspend and the resume function switches on the
/// state index to jump to the correct resume point.
#[derive(Debug, Clone)]
pub struct X86CoroSuspendPoint {
    /// Unique identifier for this suspend point.
    pub id: u32,
    /// The state value written to the frame before suspending.
    pub state_value: u32,
    /// Resume label / offset within the resume function.
    pub resume_offset: u32,
    /// Flags for this suspend point.
    pub flags: X86CoroSuspendFlags,
    /// Values that must be spilled across this suspend.
    pub spills: Vec<X86CoroSpillSlot>,
    /// Values that must be reloaded on resume.
    pub reloads: Vec<X86CoroSpillSlot>,
    /// Whether the coroutine handle is returned as-is or wrapped.
    pub passes_handle: bool,
}

// ============================================================================
// Spill Slots
// ============================================================================

/// A value that is spilled across a suspend point.
#[derive(Debug, Clone)]
pub struct X86CoroSpillSlot {
    /// Identifier for this spill.
    pub id: u32,
    /// Offset within the coroutine frame where the value is stored.
    pub frame_offset: u32,
    /// Size of the value in bytes.
    pub size: u32,
    /// Alignment of the value.
    pub alignment: u32,
    /// Original SSA value being spilled (for debugging).
    pub original_value: Option<u64>,
    /// The suspend point that owns this spill.
    pub owner_suspend_id: u32,
    /// Whether this value is a GC pointer (needs GC tracking).
    pub is_gc_pointer: bool,
    /// The DWARF register where this value was held.
    pub dwarf_reg: Option<u16>,
}

// ============================================================================
// Coroutine Handle
// ============================================================================

/// The coroutine handle is a pointer to the frame.
/// The frame begins with function pointers, so the handle can be used
/// to call resume() and destroy() directly.
#[derive(Debug, Clone)]
pub struct X86CoroHandle {
    /// Raw pointer to the coroutine frame (in memory).
    pub frame_ptr: u64,
    /// Size of the handle in bytes (sizeof(void*)).
    pub handle_size: u32,
    /// Whether the handle is valid.
    pub is_valid: bool,
}

impl X86CoroHandle {
    /// Create a new handle from a frame pointer.
    pub fn new(frame_ptr: u64) -> Self {
        Self {
            frame_ptr,
            handle_size: 8,
            is_valid: true,
        }
    }

    /// Create a null (empty) handle.
    pub fn null() -> Self {
        Self {
            frame_ptr: 0,
            handle_size: 8,
            is_valid: false,
        }
    }

    /// Generate code to load the resume function pointer via the handle.
    /// `mov rax, [handle]; call [rax]`
    pub fn generate_resume_call(&self, layout: &X86CoroFrameLayout) -> Vec<u8> {
        let mut seq = Vec::new();
        // Load the resume function pointer (the first 8 bytes of the frame)
        seq.push(0x48); // REX.W
        seq.push(0x8B); // MOV r64, r/m64
        seq.push(0x00); // ModRM: [rax]
                        // call rax
        seq.push(0xFF); // CALL r/m64
        seq.push(0xD0); // ModRM: call rax
        seq
    }

    /// Generate code to destroy the coroutine via the handle.
    pub fn generate_destroy_call(&self, layout: &X86CoroFrameLayout) -> Vec<u8> {
        let mut seq = Vec::new();
        // Load destroy function pointer: mov rax, [handle + 8]
        seq.push(0x48);
        seq.push(0x8B);
        seq.push(0x40); // ModRM: [rax + disp8]
        seq.push(0x08); // disp8 = 8
                        // call rax
        seq.push(0xFF);
        seq.push(0xD0);
        seq
    }
}

// ============================================================================
// Ramp Function
// ============================================================================

/// The ramp function is the user-visible entry point. It:
/// 1. Allocates the coroutine frame (heap or stack).
/// 2. Stores parameters into the frame.
/// 3. Initializes the promise (calls the promise constructor).
/// 4. Invokes the coroutine body.
/// 5. Returns the coroutine handle to the caller.
#[derive(Debug, Clone)]
pub struct X86CoroRampFunction {
    /// Name of the ramp function.
    pub name: String,
    /// The frame layout.
    pub frame_layout: X86CoroFrameLayout,
    /// Whether heap elision was applied.
    pub heap_elided: bool,
    /// Parameters passed to the coroutine.
    pub parameters: Vec<X86CoroParameter>,
    /// The promise type information.
    pub promise_type: Option<X86CoroPromiseType>,
    /// Starting address of the ramp function body.
    pub body_address: Option<u64>,
    /// Prologue size (bytes before the first user instruction).
    pub prologue_size: u32,
}

/// A parameter saved into the coroutine frame.
#[derive(Debug, Clone)]
pub struct X86CoroParameter {
    /// Name (if available) or index.
    pub name: String,
    /// Size of the parameter in bytes.
    pub size: u32,
    /// Offset in the coroutine frame where the copy is stored.
    pub frame_offset: u32,
    /// Whether the parameter was originally passed by value.
    pub by_value: bool,
    /// DWARF register if passed in register (otherwise memory).
    pub register: Option<u16>,
}

/// Promise type descriptor.
#[derive(Debug, Clone)]
pub struct X86CoroPromiseType {
    /// Size of the promise object in bytes.
    pub size: u32,
    /// Alignment of the promise object.
    pub alignment: u32,
    /// Name of the promise type (for debugging).
    pub type_name: String,
    /// Whether promise has a get_return_object method.
    pub has_get_return_object: bool,
    /// Whether promise has an initial_suspend method.
    pub has_initial_suspend: bool,
    /// Whether promise has a final_suspend method.
    pub has_final_suspend: bool,
    /// Whether promise has an unhandled_exception method.
    pub has_unhandled_exception: bool,
    /// Whether promise has a return_void / return_value method.
    pub has_return_value: bool,
}

impl X86CoroRampFunction {
    /// Create a new ramp function descriptor.
    pub fn new(name: &str, frame_layout: X86CoroFrameLayout) -> Self {
        Self {
            name: name.to_string(),
            frame_layout,
            heap_elided: false,
            parameters: Vec::new(),
            promise_type: None,
            body_address: None,
            prologue_size: 0,
        }
    }

    /// Add a parameter that is saved into the frame.
    pub fn add_parameter(&mut self, param: X86CoroParameter) {
        self.parameters.push(param);
    }

    /// Set the promise type.
    pub fn set_promise(&mut self, promise: X86CoroPromiseType) {
        self.promise_type = Some(promise);
    }

    /// Generate the X86-64 prologue for the ramp function.
    ///
    /// The prologue:
    /// 1. Pushes callee-saved registers.
    /// 2. Calls coro.alloc (or alloca for heap elision).
    /// 3. Stores parameters into the frame.
    /// 4. Initializes the promise.
    pub fn generate_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);
        // push rbx (callee-saved, used for frame pointer)
        seq.push(0x53);

        // Frame allocation:
        //   mov edi, frame_size
        //   mov esi, frame_alignment
        //   call operator new(size, align)   // or alloca for stack
        if self.frame_layout.is_heap && !self.heap_elided {
            // Heap allocation via operator new
            seq.push(0xBF); // mov edi, imm32
            seq.extend_from_slice(&self.frame_layout.total_size.to_le_bytes());
            seq.push(0xBE); // mov esi, imm32
            seq.extend_from_slice(&self.frame_layout.alignment.to_le_bytes());
            // call operator new
            seq.push(0xE8);
            seq.extend_from_slice(&0u32.to_le_bytes()); // placeholder rel32
        } else {
            // Stack allocation via alloca-like mechanism:
            // sub rsp, frame_size
            seq.push(0x48);
            seq.push(0x81);
            seq.push(0xEC);
            seq.extend_from_slice(&self.frame_layout.total_size.to_le_bytes());
        }

        // Store frame pointer in rbx (callee-saved across calls)
        // mov rbx, rax (result of allocation)
        seq.push(0x48);
        seq.push(0x89);
        seq.push(0xC3); // mov rbx, rax

        // Store parameters into the frame
        for param in &self.parameters {
            // mov [rbx + param.frame_offset], param_reg
            if let Some(reg) = param.register {
                let rex = 0x48u8 | if reg >= 8 { 0x04 } else { 0 };
                seq.push(rex);
                seq.push(0x89); // MOV r/m64, r64
                let modrm = (0x83u16 | ((reg & 0x07) << 3)) as u8; // mod=10 (disp32), r/m=011 (rbx)
                seq.push(modrm);
                seq.extend_from_slice(&param.frame_offset.to_le_bytes());
            }
        }

        // Initialize the frame header: store function pointers and initial state
        // mov qword [rbx + 0], resume_fn_addr
        // mov qword [rbx + 8], destroy_fn_addr
        // mov dword [rbx + 16], X86_CORO_STATE_NOT_STARTED

        // Store initial state
        seq.push(0xC7); // MOV r/m32, imm32
        seq.push(0x43); // ModRM: mod=01, reg=000, r/m=011 (rbx+disp8)
        seq.push(self.frame_layout.index_offset as u8);
        seq.extend_from_slice(&X86_CORO_STATE_NOT_STARTED.to_le_bytes());

        seq
    }

    /// Generate the epilogue: returns the coroutine handle.
    pub fn generate_epilogue(&self) -> Vec<u8> {
        let mut seq = Vec::new();
        // mov rax, rbx  ; return the frame pointer as the handle
        seq.push(0x48);
        seq.push(0x89);
        seq.push(0xD8); // mov rax, rbx
                        // pop rbx
        seq.push(0x5B);
        // pop rbp
        seq.push(0x5D);
        // ret
        seq.push(0xC3);
        seq
    }
}

// ============================================================================
// Resume Function
// ============================================================================

/// The resume function resumes execution from the last suspend point.
///
/// It reads the state index from the frame and dispatches via a switch
/// to the correct resume block.
#[derive(Debug, Clone)]
pub struct X86CoroResumeFunction {
    /// Name of the resume function.
    pub name: String,
    /// The frame layout.
    pub frame_layout: X86CoroFrameLayout,
    /// Suspend points in order of state value.
    pub suspend_points: Vec<X86CoroSuspendPoint>,
    /// Whether symmetric transfer is enabled.
    pub symmetric_transfer: bool,
}

impl X86CoroResumeFunction {
    /// Create a new resume function descriptor.
    pub fn new(name: &str, frame_layout: X86CoroFrameLayout) -> Self {
        Self {
            name: name.to_string(),
            frame_layout,
            suspend_points: Vec::new(),
            symmetric_transfer: false,
        }
    }

    /// Add a suspend point.
    pub fn add_suspend_point(&mut self, sp: X86CoroSuspendPoint) -> u32 {
        let state = sp.state_value;
        self.suspend_points.push(sp);
        state
    }

    /// Generate the resume function body.
    ///
    /// Structure:
    /// ```text
    /// resume_fn(frame_ptr):
    ///   load state = frame_ptr->index
    ///   switch (state):
    ///     case 0:  goto initial
    ///     case 1:  goto resume_point_1
    ///     case 2:  goto resume_point_2
    ///     ...
    ///     default: unreachable
    /// ```
    pub fn generate_body(&self) -> Vec<u8> {
        let mut seq = Vec::new();

        // Prologue: push rbp; mov rbp, rsp
        seq.push(0x55);
        seq.push(0x48);
        seq.push(0x89);
        seq.push(0xE5);

        // Save frame_ptr (passed in rdi) into a callee-saved register
        // push rbx; mov rbx, rdi
        seq.push(0x53);
        seq.push(0x48);
        seq.push(0x89);
        seq.push(0xFB); // mov rbx, rdi

        // Load state: mov eax, [rbx + index_offset]
        seq.push(0x8B);
        seq.push(0x43);
        seq.push(self.frame_layout.index_offset as u8);

        // Switch dispatch using a jump table:
        // Check bounds: cmp eax, num_suspend_points
        let num_points = self.suspend_points.len() as u32;
        seq.push(0x83);
        seq.push(0xF8); // cmp eax, imm8
        seq.push((num_points.max(1) - 1) as u8);
        seq.push(0x77); // ja (jump if above default)
        seq.push(0x20); // relative offset to default case

        // Jump table: jmp [jt_base + rax * 8]
        // For simplicity, emit individual compare-and-branch for each case.
        for sp in &self.suspend_points {
            let state = sp.state_value;
            if state < 128 {
                seq.push(0x83); // cmp eax, imm8
                seq.push(0xF8);
                seq.push(state as u8);
            } else {
                seq.push(0x3D); // cmp eax, imm32
                seq.extend_from_slice(&state.to_le_bytes());
            }
            seq.push(0x74); // je rel8
            seq.push(0x08); // skip next jmp

            // jmp resume_point (relative)
            seq.push(0xE9);
            seq.extend_from_slice(&0u32.to_le_bytes()); // placeholder
        }

        // Epilogue for resume function
        seq.push(0x5B); // pop rbx
        seq.push(0x5D); // pop rbp
        seq.push(0xC3); // ret

        seq
    }

    /// Generate a single resume point block.
    ///
    /// This reloads spilled values from the frame and continues execution.
    pub fn generate_resume_point(&self, sp: &X86CoroSuspendPoint) -> Vec<u8> {
        let mut seq = Vec::new();

        // Reload spilled values
        for reload in &sp.reloads {
            if let Some(reg) = reload.dwarf_reg {
                // mov reg, [rbx + reload.frame_offset]
                let rex: u8 = 0x48 | if reg >= 8 { 0x04 } else { 0 };
                seq.push(rex);
                seq.push(0x8B); // MOV r64, r/m64
                let modrm = (0x83u16 | ((reg & 0x07) << 3)) as u8; // [rbx + disp32]
                seq.push(modrm);
                seq.extend_from_slice(&reload.frame_offset.to_le_bytes());
            }
        }

        seq
    }
}

// ============================================================================
// Destroy Function
// ============================================================================

/// The destroy function cleans up active scopes and deallocates the frame.
#[derive(Debug, Clone)]
pub struct X86CoroDestroyFunction {
    /// Name of the destroy function.
    pub name: String,
    /// The frame layout.
    pub frame_layout: X86CoroFrameLayout,
    /// Destructors to run (in reverse order of construction).
    pub destructors: Vec<X86CoroDestructor>,
    /// Whether the frame is heap-allocated (needs operator delete).
    pub needs_deallocation: bool,
}

/// A destructor that must be invoked during destroy.
#[derive(Debug, Clone)]
pub struct X86CoroDestructor {
    /// The state threshold: this destructor runs if state >= threshold.
    pub state_threshold: u32,
    /// Address of the object to destroy (offset into the frame).
    pub object_offset: u32,
    /// Function pointer for the destructor.
    pub destructor_fn: Option<u64>,
    /// Size of the object to destroy.
    pub object_size: u32,
}

impl X86CoroDestroyFunction {
    /// Create a new destroy function descriptor.
    pub fn new(name: &str, frame_layout: X86CoroFrameLayout) -> Self {
        Self {
            name: name.to_string(),
            frame_layout,
            destructors: Vec::new(),
            needs_deallocation: true,
        }
    }

    /// Add a destructor for a local object.
    pub fn add_destructor(&mut self, dtor: X86CoroDestructor) {
        self.destructors.push(dtor);
    }

    /// Generate the destroy function body.
    ///
    /// Structure:
    /// ```text
    /// destroy_fn(frame_ptr):
    ///   state = frame_ptr->index
    ///   for each destructor (in reverse order):
    ///     if state >= dtor.threshold:
    ///       call dtor.fn(object)
    ///   if needs_deallocation:
    ///     operator delete(frame_ptr)
    /// ```
    pub fn generate_body(&self) -> Vec<u8> {
        let mut seq = Vec::new();

        // Prologue: push rbp; mov rbp, rsp; push rbx
        seq.push(0x55);
        seq.push(0x48);
        seq.push(0x89);
        seq.push(0xE5);
        seq.push(0x53);

        // Save frame_ptr: mov rbx, rdi
        seq.push(0x48);
        seq.push(0x89);
        seq.push(0xFB);

        // Load state: mov eax, [rbx + index_offset]
        seq.push(0x8B);
        seq.push(0x43);
        seq.push(self.frame_layout.index_offset as u8);

        // Run destructors in reverse order
        for dtor in self.destructors.iter().rev() {
            // cmp eax, dtor.state_threshold
            // jl skip_dtor
            seq.push(0x3D); // cmp eax, imm32
            seq.extend_from_slice(&dtor.state_threshold.to_le_bytes());
            seq.push(0x7C); // jl rel8
            seq.push(0x0F); // skip 15 bytes (approximate)

            // lea rdi, [rbx + object_offset]
            seq.push(0x48);
            seq.push(0x8D);
            seq.push(0xBB); // lea rdi, [rbx + disp32]
            seq.extend_from_slice(&dtor.object_offset.to_le_bytes());

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

        // Deallocate frame if heap-allocated
        if self.needs_deallocation && self.frame_layout.is_heap {
            // mov rdi, rbx
            seq.push(0x48);
            seq.push(0x89);
            seq.push(0xDF);
            // call operator delete
            seq.push(0xE8);
            seq.extend_from_slice(&0u32.to_le_bytes()); // placeholder
        }

        // Epilogue
        seq.push(0x5B); // pop rbx
        seq.push(0x5D); // pop rbp
        seq.push(0xC3); // ret

        seq
    }
}

// ============================================================================
// Symmetric Transfer Optimization
// ============================================================================

/// Symmetric transfer optimization: when a coroutine resumes another
/// coroutine and immediately suspends itself, the resume can become
/// a tail call, avoiding stack growth.
///
/// Instead of:
///   coro_A -> call resume(coro_B) -> returns to coro_A -> coro_A suspends
///
/// We get:
///   coro_A -> tail call resume(coro_B) directly
#[derive(Debug, Clone)]
pub struct X86CoroSymmetricTransfer {
    /// Whether symmetric transfer is enabled.
    pub enabled: bool,
    /// The register holding the target coroutine handle.
    pub target_handle_reg: Option<u16>,
    /// The register holding our own frame pointer.
    pub own_frame_reg: Option<u16>,
}

impl X86CoroSymmetricTransfer {
    /// Create a new symmetric transfer descriptor.
    pub fn new() -> Self {
        Self {
            enabled: false,
            target_handle_reg: None,
            own_frame_reg: None,
        }
    }

    /// Enable symmetric transfer.
    pub fn enable(&mut self) {
        self.enabled = true;
    }

    /// Generate the tail-call sequence for symmetric transfer.
    ///
    /// On X86-64:
    ///   mov rdi, target_handle  ; first arg for resume function
    ///   mov rax, [rdi]           ; load resume function pointer
    ///   ; restore our callee-saved regs, adjust rsp
    ///   jmp rax                  ; tail call to resume function
    pub fn generate_tail_call_sequence(
        &self,
        target_handle_reg: u16,
        layout: &X86CoroFrameLayout,
    ) -> Vec<u8> {
        let mut seq = Vec::new();

        // Load target resume function pointer: mov rax, [target_handle_reg]
        let rex: u8 = 0x48 | if target_handle_reg >= 8 { 0x01 } else { 0 };
        seq.push(rex);
        seq.push(0x8B); // MOV r64, r/m64
        seq.push((target_handle_reg & 0x07) as u8); // ModRM: [reg]
                                                    // jmp rax
        seq.push(0xFF);
        seq.push(0xE0);

        seq
    }

    /// Check whether a given coro.suspend is eligible for symmetric transfer.
    ///
    /// Conditions:
    /// - The suspend point has exactly one save.
    /// - The suspend point is followed by a resume of another coroutine.
    /// - The target coroutine is not the same as the current coroutine.
    pub fn is_eligible(&self, sp: &X86CoroSuspendPoint) -> bool {
        if !self.enabled {
            return false;
        }
        // Must have a valid target handle
        if self.target_handle_reg.is_none() {
            return false;
        }
        // Must not be a final suspend
        if sp.flags.is_final {
            return false;
        }
        true
    }
}

// ============================================================================
// Heap Elision Optimization
// ============================================================================

/// Heap elision: when the compiler can prove that the coroutine's lifetime
/// is bounded by the caller's frame, the coroutine frame can be allocated
/// on the caller's stack (via alloca) instead of the heap.
#[derive(Debug, Clone)]
pub struct X86CoroHeapElision {
    /// Whether heap elision is enabled.
    pub enabled: bool,
    /// Whether the coroutine was successfully elided.
    pub elided: bool,
    /// Maximum frame size for which elision is attempted.
    pub max_frame_size: u32,
    /// Reason why elision was not applied (if applicable).
    pub elision_failure_reason: Option<String>,
}

impl Default for X86CoroHeapElision {
    fn default() -> Self {
        Self {
            enabled: true,
            elided: false,
            max_frame_size: X86_CORO_HEAP_ELISION_MAX_SIZE,
            elision_failure_reason: None,
        }
    }
}

impl X86CoroHeapElision {
    /// Attempt to elide a heap allocation for the given frame.
    ///
    /// Heap elision is possible when:
    /// 1. The coroutine does not escape the caller's frame (does not
    ///    outlive the scope in which it was created).
    /// 2. The frame size is <= max_frame_size.
    /// 3. There are no recursive coroutines that could cause
    ///    unbounded stack growth.
    /// 4. The coroutine is not stored in a global or passed to
    ///    another thread.
    pub fn try_elide(
        &mut self,
        frame_size: u32,
        does_not_escape: bool,
        is_recursive: bool,
    ) -> bool {
        if !self.enabled {
            self.elision_failure_reason = Some("elision disabled".to_string());
            return false;
        }

        if !does_not_escape {
            self.elision_failure_reason =
                Some("coroutine handle escapes caller's scope".to_string());
            return false;
        }

        if frame_size > self.max_frame_size {
            self.elision_failure_reason = Some(format!(
                "frame size {} exceeds max {}",
                frame_size, self.max_frame_size
            ));
            return false;
        }

        if is_recursive {
            self.elision_failure_reason =
                Some("recursive coroutines may cause unbounded stack growth".to_string());
            return false;
        }

        self.elided = true;
        self.elision_failure_reason = None;
        true
    }

    /// Generate the alloca sequence for stack-allocated frames.
    /// Instead of calling `operator new`, use `sub rsp, frame_size`.
    pub fn generate_alloca_sequence(&self, frame_size: u32) -> Vec<u8> {
        // sub rsp, frame_size
        // mov frame_ptr, rsp
        let mut seq = Vec::new();
        seq.push(0x48);
        seq.push(0x81); // SUB r/m64, imm32
        seq.push(0xEC); // ModRM: mod=11, reg=101 (sub), r/m=100 (rsp)
        seq.extend_from_slice(&frame_size.to_le_bytes());
        // mov rax, rsp (return the frame pointer)
        seq.push(0x48);
        seq.push(0x89);
        seq.push(0xE0);
        seq
    }
}

// ============================================================================
// Coroutine-specific ABI for X86-64
// ============================================================================

/// X86-64 coroutine ABI definition.
///
/// The ABI specifies how:
/// - The coroutine handle is passed between functions.
/// - The promise object is accessed from the handle.
/// - Resume and destroy functions are invoked.
/// - Parameters are stored into the coroutine frame.
pub struct X86CoroABI {
    /// Register used to pass the coroutine handle (first argument: rdi).
    pub handle_reg: u16,
    /// Register used for the return value (rax).
    pub return_reg: u16,
    /// Register used as the frame pointer inside resume/destroy (callee-saved).
    pub frame_ptr_reg: u16,
    /// Register used as a scratch for loading function pointers.
    pub scratch_reg: u16,
    /// Callee-saved registers that coroutine functions must preserve.
    pub callee_saved_regs: Vec<u16>,
    /// Caller-saved registers that may be clobbered.
    pub caller_saved_regs: Vec<u16>,
}

impl Default for X86CoroABI {
    fn default() -> Self {
        Self {
            handle_reg: 7,                                        // rdi
            return_reg: 0,                                        // rax
            frame_ptr_reg: 3, // rbx (callee-saved, holds frame pointer)
            scratch_reg: 0,   // rax (used for indirect calls)
            callee_saved_regs: vec![3, 6, 12, 13, 14, 15], // rbx, rbp, r12-r15
            caller_saved_regs: vec![0, 2, 1, 4, 5, 8, 9, 10, 11], // rax,rcx,rdx,rsi,rdi,r8-r11
        }
    }
}

impl X86CoroABI {
    /// Generate code to load the resume function pointer and call it.
    pub fn generate_indirect_resume_call(&self, frame_ptr_reg: u16) -> Vec<u8> {
        let mut seq = Vec::new();
        // Load resume_fn from frame: mov rax, [frame_ptr + 0]
        let rex = 0x48u8;
        seq.push(rex);
        seq.push(0x8B); // MOV r64, r/m64
        seq.push((frame_ptr_reg & 0x07) as u8); // ModRM: [frame_ptr_reg]
                                                // call rax
        seq.push(0xFF);
        seq.push(0xD0);
        seq
    }

    /// Generate the standard prologue for resume/destroy functions.
    /// Saves frame pointer, sets up frame.
    pub fn generate_coro_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);
        // push rbx (we use rbx as frame_ptr)
        seq.push(0x53);
        // mov rbx, rdi (save handle in callee-saved register)
        seq.push(0x48);
        seq.push(0x89);
        seq.push(0xFB);
        seq
    }

    /// Generate the standard epilogue for resume/destroy functions.
    pub fn generate_coro_epilogue(&self) -> Vec<u8> {
        let mut seq = Vec::new();
        // pop rbx
        seq.push(0x5B);
        // pop rbp
        seq.push(0x5D);
        // ret
        seq.push(0xC3);
        seq
    }

    /// Generate code to access the promise object from the frame pointer.
    /// lea rax, [frame_ptr + promise_offset]
    pub fn generate_promise_access(&self, frame_ptr_reg: u16, promise_offset: u32) -> Vec<u8> {
        let mut seq = Vec::new();
        seq.push(0x48);
        seq.push(0x8D); // LEA r64, m
        let modrm = (0x80u16 | (frame_ptr_reg & 0x07)) as u8; // mod=10 (disp32), r/m=frame_ptr_reg
        seq.push(modrm);
        seq.extend_from_slice(&promise_offset.to_le_bytes());
        seq
    }
}

// ============================================================================
// X86CoroLowering — Main Lowering Pass
// ============================================================================

/// Configuration for the coroutine lowering pass.
#[derive(Debug, Clone)]
pub struct X86CoroLoweringConfig {
    /// Enable symmetric transfer optimization.
    pub symmetric_transfer: bool,
    /// Enable heap elision optimization.
    pub heap_elision: bool,
    /// Maximum frame size for heap elision.
    pub heap_elision_max_size: u32,
    /// Whether to split the coroutine into separate functions (resume,
    /// destroy, cleanup, ramp).
    pub split_coroutine: bool,
    /// Target triple (e.g., "x86_64-unknown-linux-gnu").
    pub target_triple: String,
    /// Whether to emit debug info for coroutine frames.
    pub emit_debug_info: bool,
}

impl Default for X86CoroLoweringConfig {
    fn default() -> Self {
        Self {
            symmetric_transfer: true,
            heap_elision: true,
            heap_elision_max_size: X86_CORO_HEAP_ELISION_MAX_SIZE,
            split_coroutine: true,
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            emit_debug_info: false,
        }
    }
}

/// The main X86 coroutine lowering pass.
///
/// Transforms coroutine intrinsics (coro.id, coro.begin, coro.suspend,
/// etc.) into the four coroutine functions (ramp, resume, destroy,
/// cleanup) and the coroutine frame.
pub struct X86CoroLowering {
    /// Configuration.
    pub config: X86CoroLoweringConfig,
    /// The coroutine frame layout.
    frame_layout: X86CoroFrameLayout,
    /// The ramp function.
    ramp_function: Option<X86CoroRampFunction>,
    /// The resume function.
    resume_function: Option<X86CoroResumeFunction>,
    /// The destroy function.
    destroy_function: Option<X86CoroDestroyFunction>,
    /// Symmetric transfer state.
    symmetric_transfer: X86CoroSymmetricTransfer,
    /// Heap elision state.
    heap_elision: X86CoroHeapElision,
    /// X86 coroutine ABI.
    abi: X86CoroABI,
    /// Current coroutine name.
    coroutine_name: Option<String>,
    /// Suspend points collected during lowering.
    suspend_points: Vec<X86CoroSuspendPoint>,
    /// Spill slots.
    spill_slots: Vec<X86CoroSpillSlot>,
    /// Parameters saved into the frame.
    parameters: Vec<X86CoroParameter>,
    /// Promise type info.
    promise_info: Option<X86CoroPromiseType>,
}

impl X86CoroLowering {
    /// Create a new X86 coroutine lowering pass.
    pub fn new(config: X86CoroLoweringConfig) -> Self {
        let mut st = X86CoroSymmetricTransfer::new();
        if config.symmetric_transfer {
            st.enable();
        }

        let mut he = X86CoroHeapElision::default();
        he.enabled = config.heap_elision;
        he.max_frame_size = config.heap_elision_max_size;

        Self {
            config,
            frame_layout: X86CoroFrameLayout::default(),
            ramp_function: None,
            resume_function: None,
            destroy_function: None,
            symmetric_transfer: st,
            heap_elision: he,
            abi: X86CoroABI::default(),
            coroutine_name: None,
            suspend_points: Vec::new(),
            spill_slots: Vec::new(),
            parameters: Vec::new(),
            promise_info: None,
        }
    }

    /// Begin lowering a coroutine.
    pub fn begin_coroutine(&mut self, name: &str) {
        self.coroutine_name = Some(name.to_string());
        self.suspend_points.clear();
        self.spill_slots.clear();
        self.parameters.clear();
    }

    /// Set the promise type.
    pub fn set_promise(&mut self, size: u32, alignment: u32, type_name: &str) {
        self.promise_info = Some(X86CoroPromiseType {
            size,
            alignment,
            type_name: type_name.to_string(),
            has_get_return_object: true,
            has_initial_suspend: true,
            has_final_suspend: true,
            has_unhandled_exception: true,
            has_return_value: true,
        });
    }

    /// Add a parameter to be saved in the frame.
    pub fn add_parameter(&mut self, name: &str, size: u32, by_value: bool, register: Option<u16>) {
        self.parameters.push(X86CoroParameter {
            name: name.to_string(),
            size,
            frame_offset: 0, // computed later
            by_value,
            register,
        });
    }

    /// Add a spill slot for a value that must survive across suspensions.
    pub fn add_spill(
        &mut self,
        size: u32,
        alignment: u32,
        owner_suspend_id: u32,
        is_gc_pointer: bool,
        dwarf_reg: Option<u16>,
    ) -> u32 {
        let id = self.spill_slots.len() as u32;
        self.spill_slots.push(X86CoroSpillSlot {
            id,
            frame_offset: 0, // computed later
            size,
            alignment,
            original_value: None,
            owner_suspend_id,
            is_gc_pointer,
            dwarf_reg,
        });
        id
    }

    /// Add a suspend point.
    pub fn add_suspend_point(
        &mut self,
        is_final: bool,
        may_unwind: bool,
        spills: Vec<u32>,
        reloads: Vec<u32>,
    ) -> u32 {
        let state_value = self.suspend_points.len() as u32 + X86_CORO_STATE_RESERVED;
        let id = self.suspend_points.len() as u32;

        let spill_slots: Vec<X86CoroSpillSlot> = spills
            .iter()
            .filter_map(|&sid| self.spill_slots.iter().find(|s| s.id == sid).cloned())
            .collect();

        let reload_slots: Vec<X86CoroSpillSlot> = reloads
            .iter()
            .filter_map(|&sid| self.spill_slots.iter().find(|s| s.id == sid).cloned())
            .collect();

        self.suspend_points.push(X86CoroSuspendPoint {
            id,
            state_value,
            resume_offset: 0, // computed later
            flags: X86CoroSuspendFlags {
                is_final,
                may_unwind,
                is_retcon: false,
                can_elide: false,
            },
            spills: spill_slots,
            reloads: reload_slots,
            passes_handle: false,
        });

        state_value
    }

    /// Compute the frame layout based on accumulated data.
    pub fn compute_frame_layout(&mut self) -> &X86CoroFrameLayout {
        let promise_size = self.promise_info.as_ref().map(|p| p.size).unwrap_or(0);
        let promise_align = self
            .promise_info
            .as_ref()
            .map(|p| p.alignment)
            .unwrap_or(X86_CORO_PROMISE_ALIGNMENT);

        let num_params = self.parameters.len() as u32;
        let params_total: u32 = self.parameters.iter().map(|p| p.size).sum();

        let num_spills = self.spill_slots.len() as u32;
        let spills_total: u32 = self.spill_slots.iter().map(|s| s.size).sum();

        self.frame_layout = X86CoroFrameLayout::compute(
            promise_size,
            promise_align,
            num_params,
            params_total,
            0, // locals handled separately
            0,
            num_spills,
            spills_total,
        );

        // Back-patch frame offsets for parameters
        let mut param_offset = self.frame_layout.params_offset;
        for param in &mut self.parameters {
            param.frame_offset = param_offset;
            param_offset += param.size;
        }

        // Back-patch frame offsets for spills
        let mut spill_offset = self.frame_layout.spills_offset;
        for spill in &mut self.spill_slots {
            spill.frame_offset = spill_offset;
            spill_offset += spill.size;
        }

        &self.frame_layout
    }

    /// Attempt heap elision.
    ///
    /// Returns true if the frame will be stack-allocated.
    pub fn try_heap_elision(&mut self, does_not_escape: bool, is_recursive: bool) -> bool {
        let frame_size = self.frame_layout.total_size;
        let result = self
            .heap_elision
            .try_elide(frame_size, does_not_escape, is_recursive);
        if result {
            self.frame_layout.is_heap = false;
        }
        result
    }

    /// Build the ramp function.
    pub fn build_ramp(&mut self) -> &X86CoroRampFunction {
        let name = format!("{}_ramp", self.coroutine_name.as_deref().unwrap_or("coro"));

        let mut ramp = X86CoroRampFunction::new(&name, self.frame_layout.clone());
        ramp.heap_elided = self.heap_elision.elided;
        ramp.parameters = self.parameters.clone();
        ramp.promise_type = self.promise_info.clone();
        ramp.prologue_size = ramp.generate_prologue().len() as u32;

        self.ramp_function = Some(ramp);
        self.ramp_function.as_ref().unwrap()
    }

    /// Build the resume function.
    pub fn build_resume(&mut self) -> &X86CoroResumeFunction {
        let name = format!(
            "{}_resume",
            self.coroutine_name.as_deref().unwrap_or("coro")
        );

        let mut resume = X86CoroResumeFunction::new(&name, self.frame_layout.clone());
        resume.symmetric_transfer = self.symmetric_transfer.enabled;
        for sp in &self.suspend_points {
            resume.add_suspend_point(sp.clone());
        }

        self.resume_function = Some(resume);
        self.resume_function.as_ref().unwrap()
    }

    /// Build the destroy function.
    pub fn build_destroy(&mut self) -> &X86CoroDestroyFunction {
        let name = format!(
            "{}_destroy",
            self.coroutine_name.as_deref().unwrap_or("coro")
        );

        let mut destroy = X86CoroDestroyFunction::new(&name, self.frame_layout.clone());
        destroy.needs_deallocation = self.frame_layout.is_heap;

        // Add destructors for each suspend point in reverse order
        for sp in self.suspend_points.iter().rev() {
            // Each suspend point may have objects constructed before it
            // that need destruction.
            destroy.add_destructor(X86CoroDestructor {
                state_threshold: sp.state_value,
                object_offset: 0, // would be computed from scope tracking
                destructor_fn: None,
                object_size: 0,
            });
        }

        self.destroy_function = Some(destroy);
        self.destroy_function.as_ref().unwrap()
    }

    /// Finalize the coroutine lowering: compute layout, build all functions.
    pub fn finalize(&mut self) -> X86CoroLoweringResult {
        self.compute_frame_layout();

        let ramp = self.build_ramp().clone();
        let resume = self.build_resume().clone();
        let destroy = self.build_destroy().clone();

        X86CoroLoweringResult {
            coroutine_name: self.coroutine_name.clone().unwrap_or_default(),
            frame_layout: self.frame_layout.clone(),
            ramp_function: ramp,
            resume_function: resume,
            destroy_function: destroy,
            heap_elided: self.heap_elision.elided,
            symmetric_transfer_enabled: self.symmetric_transfer.enabled,
            spill_slots: self.spill_slots.clone(),
            suspend_points: self.suspend_points.clone(),
        }
    }

    /// Get the X86 coroutine ABI.
    pub fn get_abi(&self) -> &X86CoroABI {
        &self.abi
    }
}

// ============================================================================
// Coroutine Lowering Result
// ============================================================================

/// The result of coroutine lowering: all generated functions and metadata.
#[derive(Debug, Clone)]
pub struct X86CoroLoweringResult {
    /// Name of the coroutine.
    pub coroutine_name: String,
    /// Coroutine frame layout.
    pub frame_layout: X86CoroFrameLayout,
    /// The ramp function (user-facing entry point).
    pub ramp_function: X86CoroRampFunction,
    /// The resume function.
    pub resume_function: X86CoroResumeFunction,
    /// The destroy function.
    pub destroy_function: X86CoroDestroyFunction,
    /// Whether heap elision was applied.
    pub heap_elided: bool,
    /// Whether symmetric transfer is enabled.
    pub symmetric_transfer_enabled: bool,
    /// All spill slots across suspend points.
    pub spill_slots: Vec<X86CoroSpillSlot>,
    /// All suspend points.
    pub suspend_points: Vec<X86CoroSuspendPoint>,
}

impl X86CoroLoweringResult {
    /// Get the total code size (prologue + body + epilogue) for all
    /// generated functions.
    pub fn total_code_size(&self) -> u32 {
        let ramp_prologue = self.ramp_function.generate_prologue().len() as u32;
        let ramp_epilogue = self.ramp_function.generate_epilogue().len() as u32;
        let resume_body = self.resume_function.generate_body().len() as u32;
        let destroy_body = self.destroy_function.generate_body().len() as u32;

        ramp_prologue + ramp_epilogue + resume_body + destroy_body
    }

    /// Get the frame size in bytes.
    pub fn frame_size(&self) -> u32 {
        self.frame_layout.aligned_size()
    }

    /// Check if the coroutine is valid (has all required functions).
    pub fn is_valid(&self) -> bool {
        !self.coroutine_name.is_empty() && self.frame_layout.total_size > 0
    }
}

// ============================================================================
// Coroutine Cleanup Function
// ============================================================================

/// The cleanup function is called when an exception propagates through
/// a suspended coroutine. It runs destructors for all objects whose
/// lifetimes have started but not ended, then deallocates the frame.
#[derive(Debug, Clone)]
pub struct X86CoroCleanupFunction {
    /// Name of the cleanup function.
    pub name: String,
    /// The frame layout.
    pub frame_layout: X86CoroFrameLayout,
    /// Destructors to run.
    pub destructors: Vec<X86CoroDestructor>,
}

impl X86CoroCleanupFunction {
    /// Create a new cleanup function descriptor.
    pub fn new(name: &str, frame_layout: X86CoroFrameLayout) -> Self {
        Self {
            name: name.to_string(),
            frame_layout,
            destructors: Vec::new(),
        }
    }

    /// Add a destructor.
    pub fn add_destructor(&mut self, dtor: X86CoroDestructor) {
        self.destructors.push(dtor);
    }

    /// Generate the cleanup function body.
    ///
    /// Structure:
    /// ```text
    /// cleanup_fn(frame_ptr):
    ///   save frame_ptr
    ///   for each destructor (reverse order):
    ///     if state_needs_destructor(dtor):
    ///       call dtor(object_in_frame)
    ///   if heap_allocated:
    ///     operator delete(frame_ptr)
    ///   return
    /// ```
    pub fn generate_body(&self) -> Vec<u8> {
        let mut seq = Vec::new();

        // Prologue
        seq.push(0x55); // push rbp
        seq.push(0x48);
        seq.push(0x89);
        seq.push(0xE5); // mov rbp, rsp
        seq.push(0x53); // push rbx

        // Save frame_ptr: mov rbx, rdi
        seq.push(0x48);
        seq.push(0x89);
        seq.push(0xFB);

        // Load state: mov eax, [rbx + index_offset]
        seq.push(0x8B);
        seq.push(0x43);
        seq.push(self.frame_layout.index_offset as u8);

        // Run destructors in reverse order
        for dtor in self.destructors.iter().rev() {
            // cmp eax, dtor.state_threshold
            if dtor.state_threshold < 128 {
                seq.push(0x83);
                seq.push(0xF8);
                seq.push(dtor.state_threshold as u8);
            } else {
                seq.push(0x3D);
                seq.extend_from_slice(&dtor.state_threshold.to_le_bytes());
            }
            seq.push(0x7C); // jl skip
            seq.push(0x0A);

            // lea rdi, [rbx + object_offset]
            seq.push(0x48);
            seq.push(0x8D);
            seq.push(0xBB);
            seq.extend_from_slice(&dtor.object_offset.to_le_bytes());

            // call destructor
            seq.push(0xE8);
            seq.extend_from_slice(&0u32.to_le_bytes());
        }

        // Epilogue
        seq.push(0x5B);
        seq.push(0x5D);
        seq.push(0xC3); // ret

        seq
    }
}

// ============================================================================
// Coroutine Splitting Pass
// ============================================================================

/// The coroutine splitting pass transforms a single coroutine function
/// into the ramp, resume, destroy, and cleanup functions.
///
/// Splitting works by:
/// 1. Identifying all coro.suspend intrinsics → suspend points.
/// 2. Building the frame layout from spilled values.
/// 3. Creating the resume function with a switch on the state index.
/// 4. Creating the destroy function that runs destructors.
/// 5. Creating the cleanup function for exception paths.
/// 6. Creating the ramp function that allocates and initializes.
/// 7. Replacing coro intrinsics with frame accesses.
#[derive(Debug, Clone)]
pub struct X86CoroSplittingPass {
    /// Configuration.
    pub config: X86CoroLoweringConfig,
    /// Collected suspend-point state.
    suspend_states: Vec<X86CoroSuspendState>,
}

/// Per-suspend-point state during splitting.
#[derive(Debug, Clone)]
pub struct X86CoroSuspendState {
    /// The suspend point.
    pub suspend: X86CoroSuspendPoint,
    /// Values live across this suspend.
    pub live_values: Vec<X86CoroSpillSlot>,
    /// Basic block before the suspend.
    pub before_block: Option<u64>,
    /// Basic block after the resume.
    pub after_block: Option<u64>,
    /// Whether this suspend must save all live registers.
    pub requires_full_save: bool,
}

impl X86CoroSplittingPass {
    /// Create a new splitting pass.
    pub fn new(config: X86CoroLoweringConfig) -> Self {
        Self {
            config,
            suspend_states: Vec::new(),
        }
    }

    /// Register a suspend point with its live values.
    pub fn register_suspend(
        &mut self,
        suspend: X86CoroSuspendPoint,
        live_values: Vec<X86CoroSpillSlot>,
        requires_full_save: bool,
    ) {
        self.suspend_states.push(X86CoroSuspendState {
            suspend,
            live_values,
            before_block: None,
            after_block: None,
            requires_full_save,
        });
    }

    /// Perform the split: generate all four functions.
    pub fn split(&self, coro_name: &str) -> X86CoroSplitResult {
        // In a full implementation, this would:
        // 1. Clone the coroutine body into each function.
        // 2. Replace suspend points with frame state writes.
        // 3. Generate switch dispatches in resume.
        // 4. Wire up the frame function pointers.

        let num_suspends = self.suspend_states.len();
        let num_full_saves = self
            .suspend_states
            .iter()
            .filter(|s| s.requires_full_save)
            .count();

        X86CoroSplitResult {
            coroutine_name: coro_name.to_string(),
            num_suspend_points: num_suspends,
            num_full_saves,
            requires_cleanup_fn: true,
            has_dynamic_allocation: true,
        }
    }
}

/// Result of the coroutine splitting pass.
#[derive(Debug, Clone)]
pub struct X86CoroSplitResult {
    /// Name of the coroutine.
    pub coroutine_name: String,
    /// Number of suspend points.
    pub num_suspend_points: usize,
    /// Number of suspend points requiring full register saves.
    pub num_full_saves: usize,
    /// Whether a separate cleanup function is needed.
    pub requires_cleanup_fn: bool,
    /// Whether the frame is heap-allocated (not elided).
    pub has_dynamic_allocation: bool,
}

// ============================================================================
// Coroutine Debug Info
// ============================================================================

/// Debug information for coroutine frames.
///
/// Allows debuggers to inspect coroutine state: local variables
/// are remapped from their original stack slots to their coroutine
/// frame offsets.
#[derive(Debug, Clone)]
pub struct X86CoroDebugInfo {
    /// DWARF expression for computing the frame base (typically rbx).
    pub frame_base_reg: u16,
    /// Mapping from original variable offset to frame offset.
    pub variable_remappings: Vec<X86CoroVarRemapping>,
    /// Source location of each suspend point.
    pub suspend_locations: Vec<X86CoroSuspendLocation>,
}

/// Remapping a variable from stack to coroutine frame.
#[derive(Debug, Clone)]
pub struct X86CoroVarRemapping {
    /// Original variable name.
    pub name: String,
    /// Original offset from RBP.
    pub original_offset: i32,
    /// New offset in the coroutine frame.
    pub frame_offset: u32,
    /// Size of the variable.
    pub size: u32,
}

/// Source location of a suspend point.
#[derive(Debug, Clone)]
pub struct X86CoroSuspendLocation {
    /// Suspend point ID.
    pub suspend_id: u32,
    /// Source file line.
    pub line: u32,
    /// Source file column.
    pub column: u32,
}

// ============================================================================
// Coroutine Elision Analysis
// ============================================================================

/// Analysis pass to determine whether a coroutine can be elided
/// (have its frame allocated on the stack).
///
/// Elision is possible when the compiler can prove the coroutine
/// does not outlive its creator.
pub struct X86CoroElisionAnalysis {
    /// Whether the coroutine handle is stored in a global.
    pub stored_in_global: bool,
    /// Whether the coroutine handle is passed to another thread.
    pub passed_to_thread: bool,
    /// Whether the coroutine handle is returned from a function
    /// other than the ramp function.
    pub returned_from_non_ramp: bool,
    /// Whether symmetric transfer preserves elision.
    pub symmetric_transfer_preserves_elision: bool,
}

impl Default for X86CoroElisionAnalysis {
    fn default() -> Self {
        Self {
            stored_in_global: false,
            passed_to_thread: false,
            returned_from_non_ramp: false,
            symmetric_transfer_preserves_elision: true,
        }
    }
}

impl X86CoroElisionAnalysis {
    /// Determine whether heap elision is possible.
    pub fn can_elide(&self) -> bool {
        !self.stored_in_global && !self.passed_to_thread && !self.returned_from_non_ramp
    }

    /// Mark the coroutine as stored in a global (disables elision).
    pub fn mark_escapes(&mut self) {
        self.stored_in_global = true;
    }

    /// Check if all conditions for elision are met.
    pub fn check_elision_conditions(&self, frame_size: u32, max_size: u32) -> Option<String> {
        if !self.can_elide() {
            return Some("coroutine escapes".to_string());
        }
        if frame_size > max_size {
            return Some(format!("frame too large: {} > {}", frame_size, max_size));
        }
        None
    }
}

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

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

    #[test]
    fn test_frame_layout_computation() {
        let layout = X86CoroFrameLayout::compute(
            32, // promise size
            8,  // promise alignment
            2,  // num params
            16, // params total size
            0,  // num locals
            0,  // locals size
            4,  // num spills
            32, // spills size
        );

        assert!(layout.total_size >= X86_CORO_MIN_FRAME_SIZE);
        assert_eq!(layout.alignment, 16);
        assert_eq!(layout.resume_fn_offset, 0);
        assert_eq!(layout.destroy_fn_offset, 8);
        assert_eq!(layout.index_offset, 16);
        assert!(layout.promise_offset >= 24);
        assert_eq!(layout.promise_size, 32);
        assert_eq!(layout.num_params, 2);
        assert_eq!(layout.num_spills, 4);
    }

    #[test]
    fn test_suspend_point_state_values() {
        let mut lowering = X86CoroLowering::new(X86CoroLoweringConfig::default());
        lowering.begin_coroutine("test_coro");

        let s0 = lowering.add_suspend_point(false, false, vec![], vec![]);
        let s1 = lowering.add_suspend_point(false, false, vec![], vec![]);
        let s2 = lowering.add_suspend_point(true, false, vec![], vec![]);

        assert_eq!(s0, X86_CORO_STATE_RESERVED); // 2
        assert_eq!(s1, X86_CORO_STATE_RESERVED + 1); // 3
        assert_eq!(s2, X86_CORO_STATE_RESERVED + 2); // 4
    }

    #[test]
    fn test_ramp_prologue_generation() {
        let mut lowering = X86CoroLowering::new(X86CoroLoweringConfig::default());
        lowering.begin_coroutine("test_coro");
        lowering.set_promise(16, 8, "promise_type");
        lowering.add_parameter("x", 8, true, Some(5)); // rdi

        lowering.compute_frame_layout();
        let ramp = lowering.build_ramp();

        let prologue = ramp.generate_prologue();
        assert!(prologue.len() > 10);
        // Should start with push rbp
        assert_eq!(prologue[0], 0x55);
        // Should end with store of initial state
    }

    #[test]
    fn test_ramp_epilogue_generation() {
        let layout = X86CoroFrameLayout::default();
        let ramp = X86CoroRampFunction::new("test", layout);

        let epilogue = ramp.generate_epilogue();
        // Should end with ret
        assert_eq!(epilogue.last(), Some(&0xC3));
    }

    #[test]
    fn test_resume_function_generation() {
        let layout = X86CoroFrameLayout::default();
        let mut resume = X86CoroResumeFunction::new("test_resume", layout);

        let sp = X86CoroSuspendPoint {
            id: 0,
            state_value: 2,
            resume_offset: 0,
            flags: X86CoroSuspendFlags::default(),
            spills: vec![],
            reloads: vec![],
            passes_handle: false,
        };
        resume.add_suspend_point(sp);

        let body = resume.generate_body();
        assert!(body.len() > 5);
        // Should start with push rbp
        assert_eq!(body[0], 0x55);
    }

    #[test]
    fn test_destroy_function_generation() {
        let layout = X86CoroFrameLayout::default();
        let mut destroy = X86CoroDestroyFunction::new("test_destroy", layout);

        destroy.add_destructor(X86CoroDestructor {
            state_threshold: 2,
            object_offset: 32,
            destructor_fn: Some(0x401000),
            object_size: 16,
        });

        let body = destroy.generate_body();
        assert!(body.len() > 5);
        // Should end with ret
        assert_eq!(body.last(), Some(&0xC3));
    }

    #[test]
    fn test_symmetric_transfer_eligibility() {
        let mut st = X86CoroSymmetricTransfer::new();
        assert!(!st.is_eligible(&X86CoroSuspendPoint {
            id: 0,
            state_value: 2,
            resume_offset: 0,
            flags: X86CoroSuspendFlags::default(),
            spills: vec![],
            reloads: vec![],
            passes_handle: false,
        })); // not enabled

        st.enable();
        st.target_handle_reg = Some(11); // r11

        let sp = X86CoroSuspendPoint {
            id: 1,
            state_value: 3,
            resume_offset: 0,
            flags: X86CoroSuspendFlags::default(),
            spills: vec![],
            reloads: vec![],
            passes_handle: false,
        };
        assert!(st.is_eligible(&sp));

        let final_sp = X86CoroSuspendPoint {
            id: 2,
            state_value: 4,
            resume_offset: 0,
            flags: X86CoroSuspendFlags {
                is_final: true,
                ..Default::default()
            },
            spills: vec![],
            reloads: vec![],
            passes_handle: false,
        };
        assert!(!st.is_eligible(&final_sp)); // final suspend not eligible
    }

    #[test]
    fn test_heap_elision_success() {
        let mut he = X86CoroHeapElision::default();
        let result = he.try_elide(256, true, false);
        assert!(result);
        assert!(he.elided);
        assert!(he.elision_failure_reason.is_none());
    }

    #[test]
    fn test_heap_elision_failure_escapes() {
        let mut he = X86CoroHeapElision::default();
        let result = he.try_elide(256, false, false);
        assert!(!result);
        assert!(he.elision_failure_reason.is_some());
    }

    #[test]
    fn test_heap_elision_failure_large() {
        let mut he = X86CoroHeapElision::default();
        let result = he.try_elide(8192, true, false);
        assert!(!result);
        assert!(he.elision_failure_reason.is_some());
    }

    #[test]
    fn test_heap_elision_failure_recursive() {
        let mut he = X86CoroHeapElision::default();
        let result = he.try_elide(256, true, true);
        assert!(!result);
    }

    #[test]
    fn test_coro_abi_prologue_epilogue() {
        let abi = X86CoroABI::default();
        let prologue = abi.generate_coro_prologue();
        let epilogue = abi.generate_coro_epilogue();

        // Prologue starts with push rbp
        assert_eq!(prologue[0], 0x55);
        // Epilogue ends with ret
        assert_eq!(epilogue.last(), Some(&0xC3));
    }

    #[test]
    fn test_full_lowering_pipeline() {
        let mut lowering = X86CoroLowering::new(X86CoroLoweringConfig::default());

        lowering.begin_coroutine("my_coro");
        lowering.set_promise(24, 8, "MyPromise");

        // Add parameters
        lowering.add_parameter("arg0", 8, true, Some(7)); // rdi
        lowering.add_parameter("arg1", 4, true, Some(6)); // rsi

        // Add spills
        let s0 = lowering.add_spill(8, 8, 0, false, Some(0)); // rax
        let s1 = lowering.add_spill(8, 8, 0, true, Some(3)); // rbx (GC pointer)

        // Add suspend points
        lowering.add_suspend_point(false, false, vec![s0], vec![s0]);
        lowering.add_suspend_point(true, false, vec![s0, s1], vec![s0, s1]);

        // Try heap elision
        let elided = lowering.try_heap_elision(true, false);

        // Finalize
        let result = lowering.finalize();

        assert_eq!(result.coroutine_name, "my_coro");
        assert!(result.frame_layout.total_size > 0);
        assert!(result.is_valid());
        assert_eq!(result.suspend_points.len(), 2);
        assert_eq!(result.spill_slots.len(), 2);

        // Check code size
        let code_size = result.total_code_size();
        assert!(code_size > 0);
    }

    #[test]
    fn test_handle_null() {
        let handle = X86CoroHandle::null();
        assert!(!handle.is_valid);
        assert_eq!(handle.frame_ptr, 0);
    }

    #[test]
    fn test_handle_valid() {
        let handle = X86CoroHandle::new(0x7FFF00001000);
        assert!(handle.is_valid);
        assert_eq!(handle.frame_ptr, 0x7FFF00001000);
    }

    #[test]
    fn test_intrinsic_display() {
        assert_eq!(X86CoroIntrinsicKind::CoroId.to_string(), "coro.id");
        assert_eq!(X86CoroIntrinsicKind::CoroBegin.to_string(), "coro.begin");
        assert_eq!(
            X86CoroIntrinsicKind::CoroSuspend.to_string(),
            "coro.suspend"
        );
        assert_eq!(X86CoroIntrinsicKind::CoroResume.to_string(), "coro.resume");
        assert_eq!(
            X86CoroIntrinsicKind::CoroDestroy.to_string(),
            "coro.destroy"
        );
    }

    #[test]
    fn test_frame_state_read_write() {
        let layout = X86CoroFrameLayout::default();

        // Generate write state = 3
        let write_seq = layout.generate_set_state(3, 3); // rbx
        assert!(write_seq.len() >= 7);

        // Generate read state
        let read_seq = layout.generate_read_state(3); // rbx
        assert!(read_seq.len() >= 3);
    }

    #[test]
    fn test_spill_slot_creation() {
        let mut lowering = X86CoroLowering::new(X86CoroLoweringConfig::default());
        lowering.begin_coroutine("spill_test");

        let id = lowering.add_spill(8, 8, 0, true, Some(0));
        assert_eq!(id, 0);

        let id2 = lowering.add_spill(16, 16, 0, false, Some(2));
        assert_eq!(id2, 1);

        lowering.compute_frame_layout();
        assert!(lowering.spill_slots[0].frame_offset > 0);
        assert!(lowering.spill_slots[1].frame_offset > lowering.spill_slots[0].frame_offset);
    }

    #[test]
    fn test_cleanup_function_generation() {
        let layout = X86CoroFrameLayout::default();
        let mut cleanup = X86CoroCleanupFunction::new("test_cleanup", layout);
        cleanup.add_destructor(X86CoroDestructor {
            state_threshold: 2,
            object_offset: 32,
            destructor_fn: Some(0x500000),
            object_size: 16,
        });
        let body = cleanup.generate_body();
        assert!(body.len() > 10);
        assert_eq!(body[0], 0x55);
        assert_eq!(body.last(), Some(&0xC3));
    }

    #[test]
    fn test_splitting_pass() {
        let config = X86CoroLoweringConfig::default();
        let mut pass = X86CoroSplittingPass::new(config);
        let sp1 = X86CoroSuspendPoint {
            id: 0,
            state_value: 2,
            resume_offset: 0,
            flags: X86CoroSuspendFlags::default(),
            spills: vec![],
            reloads: vec![],
            passes_handle: false,
        };
        pass.register_suspend(sp1, vec![], false);
        let result = pass.split("test_split");
        assert_eq!(result.num_suspend_points, 1);
        assert!(result.requires_cleanup_fn);
    }

    #[test]
    fn test_elision_analysis() {
        let analysis = X86CoroElisionAnalysis::default();
        assert!(analysis.can_elide());
        assert!(analysis.check_elision_conditions(256, 4096).is_none());
    }

    #[test]
    fn test_elision_analysis_escape() {
        let mut analysis = X86CoroElisionAnalysis::default();
        analysis.mark_escapes();
        assert!(!analysis.can_elide());
    }

    #[test]
    fn test_elision_too_large() {
        let analysis = X86CoroElisionAnalysis::default();
        let reason = analysis.check_elision_conditions(8192, 4096);
        assert!(reason.is_some());
        assert!(reason.unwrap().contains("too large"));
    }

    #[test]
    fn test_coro_result_validity() {
        let layout = X86CoroFrameLayout::default();
        let result = X86CoroLoweringResult {
            coroutine_name: "".to_string(),
            frame_layout: layout.clone(),
            ramp_function: X86CoroRampFunction::new("", layout.clone()),
            resume_function: X86CoroResumeFunction::new("", layout.clone()),
            destroy_function: X86CoroDestroyFunction::new("", layout.clone()),
            heap_elided: false,
            symmetric_transfer_enabled: false,
            spill_slots: vec![],
            suspend_points: vec![],
        };
        assert!(!result.is_valid());
    }

    #[test]
    fn test_abi_registers() {
        let abi = X86CoroABI::default();
        assert_eq!(abi.handle_reg, 7);
        assert_eq!(abi.return_reg, 0);
        assert_eq!(abi.frame_ptr_reg, 3);
        assert_eq!(abi.callee_saved_regs.len(), 6);
    }

    #[test]
    fn test_indirect_resume_call_gen() {
        let abi = X86CoroABI::default();
        let seq = abi.generate_indirect_resume_call(3);
        assert!(seq.len() >= 4);
        assert!(seq.contains(&0x8B));
        assert!(seq.contains(&0xFF));
    }

    #[test]
    fn test_tail_call_sequence() {
        let st = X86CoroSymmetricTransfer::new();
        let layout = X86CoroFrameLayout::default();
        let seq = st.generate_tail_call_sequence(DW_R11 as u16, &layout);
        assert!(seq.len() >= 4);
        assert_eq!(seq[seq.len() - 2], 0xFF);
        assert_eq!(seq[seq.len() - 1], 0xE0);
    }
}