llvm-native-core 0.1.2

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
//! X86 Calling Conventions — complete implementation of all major X86 ABIs.
//!
//! Covers:
//! - System V AMD64 ABI (Linux, macOS, FreeBSD, Solaris)
//! - Microsoft x64 ABI (Windows)
//! - 32-bit cdecl, stdcall, fastcall, thiscall, vectorcall
//! - GCC/ICC extensions: regcall, preserve_all, preserve_most
//! - GHC (Glasgow Haskell Compiler) calling convention
//! - AnyReg (any register for return value)
//!
//! Classification follows the AMD64 ABI §3.2.3 algorithm for aggregate
//! types (structs, unions, arrays) with eightbyte-by-eightbyte analysis
//! and post-merger cleanup per the published specification.
//!
//! Clean-room reconstruction from:
//! - System V Application Binary Interface: AMD64 Architecture Processor
//!   Supplement (with LP64 and ILP32 programming models)
//! - Microsoft x64 Software Conventions
//! - Intel® 64 and IA-32 Architectures Software Developer's Manual
//! - cdecl/stdcall/fastcall/thiscall/vectorcall conventions
//!
//! Zero LLVM source code consultation.

use crate::types::{Type, TypeKind};
use crate::x86::x86_register_info::*;
use std::collections::HashMap;

// ============================================================================
// X86ArgClass — AMD64 ABI eightbyte classification categories
// ============================================================================

/// Classification category for each eightbyte of an argument type,
/// per System V AMD64 ABI §3.2.3.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum X86ArgClass {
    /// No class at all (zero-sized or empty).
    NoClass,
    /// Integer types: _Bool, char, short, int, long, long long, pointers,
    /// and enums. Fit in a general-purpose register.
    Integer,
    /// SSE types: float, double, _Decimal32, _Decimal64, __m64,
    /// and vectors of these. Fit in an XMM register.
    SSE,
    /// SSEUp: upper 8 bytes of a type that uses two eightbytes
    /// where the first is SSE. Goes in the next XMM register.
    SSEUp,
    /// X87: 80-bit extended precision (long double). Uses the x87 stack.
    X87,
    /// X87Up: upper 8 bytes of a complex type whose first eightbyte is X87.
    X87Up,
    /// ComplexX87: complex long double — split across x87 and memory.
    ComplexX87,
    /// Memory: passed on the stack (too large, or contains holes).
    Memory,
}

impl X86ArgClass {
    /// Returns true if this class indicates a register-passed eightbyte.
    pub fn is_register_class(&self) -> bool {
        matches!(
            self,
            X86ArgClass::Integer | X86ArgClass::SSE | X86ArgClass::SSEUp | X86ArgClass::X87
        )
    }

    /// Returns true if the class needs an XMM register.
    pub fn needs_xmm(&self) -> bool {
        matches!(self, X86ArgClass::SSE | X86ArgClass::SSEUp)
    }
}

// ============================================================================
// X86CallingConvention — the set of all supported X86 calling conventions
// ============================================================================

/// All X86 calling conventions supported by this backend.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum X86CallingConvention {
    /// C calling convention (cdecl) — default for C on 32-bit.
    /// All arguments on stack, caller cleans up.
    C,

    /// Fastcall — first 2 integer args in ECX, EDX; rest on stack (32-bit).
    /// On 64-bit Windows, fastcall is the default (first 4 in RCX,RDX,R8,R9).
    Fast,

    /// Stdcall — Windows 32-bit convention; callee cleans stack.
    StdCall,

    /// Thiscall — C++ member functions on 32-bit Windows; `this` in ECX.
    ThisCall,

    /// Vectorcall — up to 6 SIMD args in XMM0-XMM5; integers in registers.
    /// Used for SIMD-heavy functions.
    VectorCall,

    /// System V AMD64 ABI — standard on Linux, macOS, FreeBSD, Solaris.
    /// First 6 integer args in RDI,RSI,RDX,RCX,R8,R9; first 8 SSE in XMM0-XMM7.
    #[allow(non_camel_case_types)]
    X86_64_SysV,

    /// Microsoft x64 ABI — Windows 64-bit.
    /// First 4 in RCX,RDX,R8,R9 (or XMM0-XMM3 for floats); 32-byte shadow space.
    Win64,

    /// Regcall — ICC/GCC extension passing many args in registers.
    #[allow(non_camel_case_types)]
    X86_RegCall,

    /// PreserveAll — callee saves and restores all registers.
    PreserveAll,

    /// PreserveMost — callee saves most registers (used for runtime calls).
    PreserveMost,

    /// GHC — Glasgow Haskell Compiler calling convention.
    GHC,

    /// AnyReg — any register may be used for the return value.
    AnyReg,
}

impl Default for X86CallingConvention {
    fn default() -> Self {
        X86CallingConvention::X86_64_SysV
    }
}

impl X86CallingConvention {
    /// Create a calling convention from a `CallConv` (from frame lowering).
    pub fn new(cc: crate::x86::x86_frame_lowering::CallConv) -> Self {
        use crate::x86::x86_frame_lowering::CallConv;
        match cc {
            CallConv::SystemV => X86CallingConvention::X86_64_SysV,
            CallConv::Win64 => X86CallingConvention::Win64,
            CallConv::CDecl32 => X86CallingConvention::C,
            CallConv::StdCall32 => X86CallingConvention::StdCall,
            CallConv::FastCall32 => X86CallingConvention::Fast,
        }
    }

    /// Human-readable name of the calling convention.
    pub fn name(&self) -> &'static str {
        match self {
            X86CallingConvention::C => "cdecl",
            X86CallingConvention::Fast => "fastcall",
            X86CallingConvention::StdCall => "stdcall",
            X86CallingConvention::ThisCall => "thiscall",
            X86CallingConvention::VectorCall => "vectorcall",
            X86CallingConvention::X86_64_SysV => "System V AMD64",
            X86CallingConvention::Win64 => "Microsoft x64",
            X86CallingConvention::X86_RegCall => "regcall",
            X86CallingConvention::PreserveAll => "preserve_all",
            X86CallingConvention::PreserveMost => "preserve_most",
            X86CallingConvention::GHC => "GHC",
            X86CallingConvention::AnyReg => "anyreg",
        }
    }

    /// Whether this convention is a 64-bit convention.
    pub fn is_64bit(&self) -> bool {
        matches!(
            self,
            X86CallingConvention::X86_64_SysV
                | X86CallingConvention::Win64
                | X86CallingConvention::X86_RegCall
        )
    }

    /// Whether the callee cleans the stack (true) or caller (false).
    pub fn callee_cleans_stack(&self) -> bool {
        matches!(
            self,
            X86CallingConvention::StdCall
                | X86CallingConvention::ThisCall
                | X86CallingConvention::Fast
        )
    }

    /// Whether this convention uses register parameters at all.
    pub fn uses_register_params(&self) -> bool {
        match self {
            X86CallingConvention::C => false,
            X86CallingConvention::Fast => true,
            X86CallingConvention::StdCall => false,
            X86CallingConvention::ThisCall => true,
            X86CallingConvention::VectorCall => true,
            X86CallingConvention::X86_64_SysV => true,
            X86CallingConvention::Win64 => true,
            X86CallingConvention::X86_RegCall => true,
            X86CallingConvention::PreserveAll => false,
            X86CallingConvention::PreserveMost => false,
            X86CallingConvention::GHC => true,
            X86CallingConvention::AnyReg => true,
        }
    }

    /// Number of integer parameter registers available.
    pub fn get_num_int_param_regs(&self) -> usize {
        match self {
            X86CallingConvention::C | X86CallingConvention::StdCall => 0,
            X86CallingConvention::Fast => 2,
            X86CallingConvention::ThisCall => 1,
            X86CallingConvention::VectorCall => 2,
            X86CallingConvention::X86_64_SysV => 6,
            X86CallingConvention::Win64 => 4,
            X86CallingConvention::X86_RegCall => 5, // EAX,ECX,EDX,EDI,ESI
            X86CallingConvention::PreserveAll | X86CallingConvention::PreserveMost => 0,
            X86CallingConvention::GHC => 0,
            X86CallingConvention::AnyReg => 1,
        }
    }

    /// Number of SSE (XMM) parameter registers available.
    pub fn get_num_sse_param_regs(&self) -> usize {
        match self {
            X86CallingConvention::VectorCall => 6,
            X86CallingConvention::X86_64_SysV => 8,
            X86CallingConvention::Win64 => 4,
            _ => 0,
        }
    }

    /// Integer parameter registers (by register ID).
    pub fn get_int_param_regs(&self) -> Vec<u16> {
        match self {
            X86CallingConvention::Fast => vec![ECX, EDX],
            X86CallingConvention::ThisCall => vec![ECX],
            X86CallingConvention::X86_64_SysV => vec![RDI, RSI, RDX, RCX, R8, R9],
            X86CallingConvention::Win64 => vec![RCX, RDX, R8, R9],
            X86CallingConvention::X86_RegCall => vec![EAX, ECX, EDX, EDI, ESI],
            _ => vec![],
        }
    }

    /// SSE (XMM) parameter registers (by register ID).
    pub fn get_sse_param_regs(&self) -> Vec<u16> {
        match self {
            X86CallingConvention::VectorCall => vec![XMM0, XMM1, XMM2, XMM3, XMM4, XMM5],
            X86CallingConvention::X86_64_SysV => {
                vec![XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6, XMM7]
            }
            X86CallingConvention::Win64 => vec![XMM0, XMM1, XMM2, XMM3],
            _ => vec![],
        }
    }

    /// Stack alignment at the function call boundary.
    pub fn get_stack_alignment(&self) -> u32 {
        match self {
            X86CallingConvention::X86_64_SysV
            | X86CallingConvention::Win64
            | X86CallingConvention::X86_RegCall
            | X86CallingConvention::PreserveAll
            | X86CallingConvention::PreserveMost
            | X86CallingConvention::GHC
            | X86CallingConvention::AnyReg => 16,
            // 32-bit ABIs often use 16-byte alignment with SSE, but default to 4
            _ => 4,
        }
    }

    /// Shadow store size (for Win64, this is always 32 bytes).
    pub fn get_shadow_store_size(&self) -> i64 {
        match self {
            X86CallingConvention::Win64 => 32,
            _ => 0,
        }
    }

    /// Whether a struct-return type needs a hidden sret pointer (first arg).
    /// Per AMD64 ABI: aggregates > 16 bytes, or with MEMORY class, use sret.
    /// Win64: aggregates > 8 bytes use hidden pointer.
    pub fn needs_hidden_sret(&self, ty: &Type, type_map: &HashMap<TypeId, Type>) -> bool {
        if !ty.is_struct() {
            return false;
        }
        let size = type_size(ty, type_map);
        match self {
            X86CallingConvention::X86_64_SysV => {
                let classes = classify_aggregate_type(ty, type_map);
                // If MEMORY class appears, or size > 16 bytes (two eightbytes)
                size > 16 || classes.iter().any(|c| *c == X86ArgClass::Memory)
            }
            X86CallingConvention::Win64 => size > 8,
            _ => false,
        }
    }

    /// Determine which registers hold the return value for a given type.
    /// Returns a vector of register IDs.
    pub fn get_return_regs(&self, ty: &Type, type_map: &HashMap<TypeId, Type>) -> Vec<u16> {
        match self {
            X86CallingConvention::X86_64_SysV => {
                let classes = classify_arg_type(ty, 0, type_map);
                sysv_return_regs_from_classes(&classes)
            }
            X86CallingConvention::Win64 => {
                let size = type_size(ty, type_map);
                win64_return_regs(ty, size)
            }
            X86CallingConvention::C
            | X86CallingConvention::StdCall
            | X86CallingConvention::Fast
            | X86CallingConvention::ThisCall
            | X86CallingConvention::VectorCall => {
                // 32-bit: return in EAX (or EDX:EAX for i64), ST0 for x87 float
                cdecl_return_regs(ty, type_map)
            }
            _ => vec![RAX],
        }
    }

    /// Full argument assignment: classify each arg, assign registers/stack slots.
    /// Returns the per-argument info and the overall call frame layout.
    pub fn assign_args(
        &self,
        args: &[Type],
        type_map: &HashMap<TypeId, Type>,
    ) -> (Vec<X86ArgInfo>, X86CallFrame) {
        match self {
            X86CallingConvention::X86_64_SysV => assign_sysv_args(args, type_map),
            X86CallingConvention::Win64 => assign_win64_args(args, type_map),
            X86CallingConvention::C => assign_cdecl_args(args, type_map),
            X86CallingConvention::StdCall => assign_stdcall_args(args, type_map),
            X86CallingConvention::Fast => assign_fastcall_args(args, type_map),
            X86CallingConvention::ThisCall => assign_thiscall_args(args, type_map),
            X86CallingConvention::VectorCall => assign_vectorcall_args(args, type_map),
            _ => assign_stack_only_args(args, type_map),
        }
    }

    /// Classify a single argument type into a vector of X86ArgClass (one per
    /// eightbyte). Works only for the System V AMD64 classification.
    pub fn classify_arg(
        &self,
        ty: &Type,
        offset: i64,
        type_map: &HashMap<TypeId, Type>,
    ) -> Vec<X86ArgClass> {
        classify_arg_type(ty, offset, type_map)
    }
}

// Re-export TypeId for convenience since it's used in type_map parameters.
use crate::types::TypeId;

// ============================================================================
// X86ArgInfo — per-argument assignment information
// ============================================================================

/// Describes how a single function argument is passed.
#[derive(Debug, Clone)]
pub struct X86ArgInfo {
    /// True if this argument is passed in a register.
    pub in_reg: bool,

    /// Register IDs assigned to this argument (may be empty if all-stack).
    pub regs: Vec<u16>,

    /// Offset from RSP (or base pointer) where this argument lives on
    /// the stack. Negative for caller's frame, positive for callee's.
    pub stack_offset: i64,

    /// Size of the argument in bytes.
    pub size: u32,

    /// Alignment requirement of the argument.
    pub alignment: u32,

    /// True if passed by value on the stack (struct byval).
    pub is_byval: bool,

    /// True if this argument is the hidden struct-return pointer (sret).
    pub is_sret: bool,

    /// Padding bytes needed before this argument for alignment.
    pub padding: u32,
}

impl Default for X86ArgInfo {
    fn default() -> Self {
        X86ArgInfo {
            in_reg: false,
            regs: Vec::new(),
            stack_offset: 0,
            size: 0,
            alignment: 1,
            is_byval: false,
            is_sret: false,
            padding: 0,
        }
    }
}

// ============================================================================
// X86CallFrame — overall stack frame layout for a call
// ============================================================================

/// Describes the stack frame layout for a function call.
#[derive(Debug, Clone)]
pub struct X86CallFrame {
    /// Total stack space needed for arguments (not including shadow store
    /// or alignment padding beyond what's implicit).
    pub stack_size: i64,

    /// Stack offset for each argument (index in the same order as args).
    pub arg_offsets: Vec<i64>,

    /// Offset of the struct-return save area, if sret is used.
    pub return_save_area: Option<i64>,

    /// Shadow store size (Win64: 32 bytes for RCX,RDX,R8,R9 spill).
    pub shadow_store_size: i64,

    /// Extra padding added to achieve the required stack alignment.
    pub alignment_padding: i64,
}

impl Default for X86CallFrame {
    fn default() -> Self {
        X86CallFrame {
            stack_size: 0,
            arg_offsets: Vec::new(),
            return_save_area: None,
            shadow_store_size: 0,
            alignment_padding: 0,
        }
    }
}

// ============================================================================
// Type size and alignment helpers
// ============================================================================

/// Compute the size in bytes of an LLVM type.
/// For compound types, uses `type_map` to resolve TypeIds.
pub fn type_size(ty: &Type, type_map: &HashMap<TypeId, Type>) -> u64 {
    match &ty.kind {
        TypeKind::Void => 0,
        TypeKind::Half => 2,
        TypeKind::BFloat => 2,
        TypeKind::Float => 4,
        TypeKind::Double => 8,
        TypeKind::FP128 => 16,
        TypeKind::X86FP80 => 16, // Stored as 16 bytes (10 bytes used + 6 padding)
        TypeKind::PPCFP128 => 16,
        TypeKind::Label => 0,
        TypeKind::Metadata => 0,
        TypeKind::X86AMX => 0, // Variable-sized tile
        TypeKind::X86MMX => 8,
        TypeKind::Token => 0,
        TypeKind::Integer { bits } => ((*bits + 7) / 8) as u64,
        TypeKind::Pointer { .. } => 8, // Assume 64-bit pointers
        TypeKind::Array {
            len,
            element_type_id,
        } => {
            let elem_size = type_size_from_id(*element_type_id, type_map);
            (*len) * elem_size
        }
        TypeKind::Struct {
            is_packed,
            element_type_ids,
            ..
        } => {
            if element_type_ids.is_empty() {
                return 0;
            }
            let mut total = 0u64;
            let mut max_align = 1u64;
            for tid in element_type_ids {
                let elem = type_size_from_id(*tid, type_map);
                let align = type_alignment_from_id(*tid, type_map);
                if align > max_align {
                    max_align = align;
                }
                if !(*is_packed) {
                    // Align current offset to element alignment
                    total = align_to(total, align);
                }
                total += elem;
            }
            if !(*is_packed) && max_align > 0 {
                total = align_to(total, max_align);
            }
            total
        }
        TypeKind::FixedVector {
            len,
            element_type_id,
        } => {
            let elem_size = type_size_from_id(*element_type_id, type_map);
            (*len as u64) * elem_size
        }
        TypeKind::ScalableVector {
            min_elems,
            element_type_id,
        } => {
            let elem_size = type_size_from_id(*element_type_id, type_map);
            (*min_elems as u64) * elem_size
        }
        TypeKind::Function { .. } => 8, // Function pointer
    }
}

/// Compute the alignment of an LLVM type.
pub fn type_alignment(ty: &Type, type_map: &HashMap<TypeId, Type>) -> u64 {
    match &ty.kind {
        TypeKind::Void | TypeKind::Label | TypeKind::Metadata | TypeKind::Token => 1,
        TypeKind::Half | TypeKind::BFloat => 2,
        TypeKind::Float => 4,
        TypeKind::Double => 8,
        TypeKind::FP128 | TypeKind::PPCFP128 => 16,
        TypeKind::X86FP80 => 16,
        TypeKind::X86AMX => 64,
        TypeKind::X86MMX => 8,
        TypeKind::Integer { bits } => {
            let bytes = (*bits + 7) / 8;
            if bytes >= 16 {
                16
            } else if bytes >= 8 {
                8
            } else if bytes >= 4 {
                4
            } else if bytes >= 2 {
                2
            } else {
                1
            }
        }
        TypeKind::Pointer { .. } => 8,
        TypeKind::Array {
            element_type_id, ..
        } => type_alignment_from_id(*element_type_id, type_map),
        TypeKind::Struct {
            is_packed,
            element_type_ids,
            ..
        } => {
            if *is_packed {
                1
            } else {
                let mut max_align = 1u64;
                for tid in element_type_ids {
                    let a = type_alignment_from_id(*tid, type_map);
                    if a > max_align {
                        max_align = a;
                    }
                }
                max_align
            }
        }
        TypeKind::FixedVector {
            len,
            element_type_id,
        } => {
            let total = (*len as u64) * type_size_from_id(*element_type_id, type_map);
            vector_alignment(total)
        }
        TypeKind::ScalableVector {
            min_elems,
            element_type_id,
        } => {
            let total = (*min_elems as u64) * type_size_from_id(*element_type_id, type_map);
            vector_alignment(total)
        }
        TypeKind::Function { .. } => 8,
    }
}

/// Vector alignment rules: vectors align to their total size up to 64 bytes.
fn vector_alignment(total_bytes: u64) -> u64 {
    if total_bytes >= 64 {
        64
    } else if total_bytes >= 32 {
        32
    } else if total_bytes >= 16 {
        16
    } else if total_bytes >= 8 {
        8
    } else if total_bytes >= 4 {
        4
    } else if total_bytes >= 2 {
        2
    } else {
        1
    }
}

/// Resolve a TypeId to a Type via the type map. Panics if not found.
fn resolve_type(tid: TypeId, type_map: &HashMap<TypeId, Type>) -> Type {
    type_map
        .get(&tid)
        .cloned()
        .unwrap_or_else(|| panic!("TypeId {} not found in type map", tid.as_u64()))
}

/// Compute the size from a TypeId, using the map.
fn type_size_from_id(tid: TypeId, type_map: &HashMap<TypeId, Type>) -> u64 {
    let ty = resolve_type(tid, type_map);
    type_size(&ty, type_map)
}

/// Compute the alignment from a TypeId, using the map.
fn type_alignment_from_id(tid: TypeId, type_map: &HashMap<TypeId, Type>) -> u64 {
    let ty = resolve_type(tid, type_map);
    type_alignment(&ty, type_map)
}

/// Align `value` up to `alignment`.
fn align_to(value: u64, alignment: u64) -> u64 {
    if alignment == 0 {
        return value;
    }
    ((value + alignment - 1) / alignment) * alignment
}

/// Check if a type is a floating-point type that maps to SSE class.
#[allow(dead_code)]
fn is_sse_type(ty: &Type) -> bool {
    matches!(
        ty.kind,
        TypeKind::Float | TypeKind::Double | TypeKind::Half | TypeKind::BFloat
    )
}

/// Check if a type is an x87 type (80-bit extended precision).
#[allow(dead_code)]
fn is_x87_type(ty: &Type) -> bool {
    matches!(ty.kind, TypeKind::X86FP80)
}

/// Check if a type is an integer-like type (integers and pointers).
#[allow(dead_code)]
fn is_integer_like(ty: &Type) -> bool {
    matches!(ty.kind, TypeKind::Integer { .. } | TypeKind::Pointer { .. })
}

// ============================================================================
// System V AMD64 ABI Classification Algorithm (§3.2.3)
// ============================================================================

/// Classify a type by eightbytes for the System V AMD64 ABI.
///
/// The algorithm walks the type in 8-byte chunks ("eightbytes"), determining
/// the class of each chunk based on the fields that span it. After initial
/// classification, a post-merger cleanup pass enforces the ABI rules.
pub fn classify_arg_type(
    ty: &Type,
    offset: i64,
    type_map: &HashMap<TypeId, Type>,
) -> Vec<X86ArgClass> {
    let size = type_size(ty, type_map);

    match &ty.kind {
        // Primitives → classify directly
        TypeKind::Integer { bits } => {
            let bytes = (*bits + 7) / 8;
            let num_eightbytes = ((bytes as i64 + 7) / 8).max(1);
            let classes = vec![X86ArgClass::Integer; num_eightbytes as usize];
            classes
        }
        TypeKind::Pointer { .. } => {
            vec![X86ArgClass::Integer]
        }
        TypeKind::Half | TypeKind::BFloat | TypeKind::Float | TypeKind::Double => {
            vec![X86ArgClass::SSE]
        }
        TypeKind::FP128 | TypeKind::PPCFP128 => {
            // 128-bit floats: SSE + SSEUp
            vec![X86ArgClass::SSE, X86ArgClass::SSEUp]
        }
        TypeKind::X86FP80 => {
            // 80-bit extended precision → X87 class
            if offset % 16 == 0 {
                vec![X86ArgClass::X87]
            } else {
                vec![X86ArgClass::Memory]
            }
        }
        TypeKind::X86MMX => {
            vec![X86ArgClass::SSE]
        }
        TypeKind::Void
        | TypeKind::Label
        | TypeKind::Metadata
        | TypeKind::Token
        | TypeKind::X86AMX => {
            vec![]
        }
        // Compound types → use the full aggregate classification
        TypeKind::Array { .. }
        | TypeKind::Struct { .. }
        | TypeKind::FixedVector { .. }
        | TypeKind::ScalableVector { .. }
        | TypeKind::Function { .. } => {
            let mut classes = Vec::new();
            classify_aggregate_impl(ty, 0, offset, type_map, &mut classes);
            post_merger_cleanup(&mut classes, size);
            classes
        }
    }
}

/// Classify an aggregate type (struct, array, vector) using the full
/// eightbyte-by-eightbyte algorithm from AMD64 ABI §3.2.3.
pub fn classify_aggregate_type(ty: &Type, type_map: &HashMap<TypeId, Type>) -> Vec<X86ArgClass> {
    let size = type_size(ty, type_map);
    let mut classes = Vec::new();
    classify_aggregate_impl(ty, 0, 0, type_map, &mut classes);
    post_merger_cleanup(&mut classes, size);
    classes
}

/// Recursive implementation of the eightbyte classification algorithm.
///
/// Each field of the aggregate is classified into the eightbyte(s) it occupies.
/// The `start_offset` is relative to the aggregate start; `base_offset` is
/// the absolute offset from the beginning of the argument list.
fn classify_aggregate_impl(
    ty: &Type,
    start_offset: i64,
    base_offset: i64,
    type_map: &HashMap<TypeId, Type>,
    classes: &mut Vec<X86ArgClass>,
) {
    // Determine how many eightbytes we need
    let size = type_size(ty, type_map) as i64;
    let num_eightbytes = ((size + 7) / 8).max(1) as usize;

    // Ensure classes vector is large enough
    while classes.len() < num_eightbytes {
        classes.push(X86ArgClass::NoClass);
    }

    match &ty.kind {
        TypeKind::Struct {
            is_packed,
            element_type_ids,
            ..
        } => {
            let mut field_offset = 0i64;
            for tid in element_type_ids {
                let field_ty = resolve_type(*tid, type_map);
                let field_size = type_size(&field_ty, type_map) as i64;
                let field_align = type_alignment(&field_ty, type_map) as i64;

                if !(*is_packed) && field_align > 1 {
                    field_offset = align_to_i64(field_offset, field_align);
                }

                let abs_offset = base_offset + start_offset + field_offset;
                // Recursively classify this field
                classify_field_in_eightbytes(
                    &field_ty,
                    field_offset,
                    abs_offset,
                    type_map,
                    classes,
                );

                field_offset += field_size;
            }
        }
        TypeKind::Array {
            len,
            element_type_id,
        } => {
            let elem_ty = resolve_type(*element_type_id, type_map);
            let elem_size = type_size(&elem_ty, type_map) as i64;
            for i in 0..(*len as i64) {
                let field_offset = i * elem_size;
                let abs_offset = base_offset + start_offset + field_offset;
                classify_field_in_eightbytes(&elem_ty, field_offset, abs_offset, type_map, classes);
            }
        }
        TypeKind::FixedVector {
            len,
            element_type_id,
        } => {
            let elem_ty = resolve_type(*element_type_id, type_map);
            let elem_size = type_size(&elem_ty, type_map) as i64;
            // Vectors: each element classified independently within the eightbytes
            for i in 0..(*len as i64) {
                let field_offset = i * elem_size;
                let abs_offset = base_offset + start_offset + field_offset;
                let elem_classes = classify_arg_type(&elem_ty, abs_offset, type_map);
                merge_classes_into(classes, &elem_classes, start_offset + field_offset);
            }
        }
        TypeKind::ScalableVector { .. } => {
            // Scalable vectors always go to memory
            for c in classes.iter_mut() {
                *c = X86ArgClass::Memory;
            }
        }
        _ => {
            // Single non-aggregate type: classify it
            let sub_classes = classify_arg_type(ty, base_offset + start_offset, type_map);
            for (i, cls) in sub_classes.iter().enumerate() {
                let idx = i + (start_offset as usize / 8);
                if idx < classes.len() {
                    classes[idx] = merge_classes(classes[idx], *cls);
                }
            }
        }
    }
}

/// Classify a field that falls within certain eightbytes.
fn classify_field_in_eightbytes(
    field_ty: &Type,
    field_offset: i64, // Offset within the parent aggregate
    abs_offset: i64,   // Absolute offset from arg list start
    type_map: &HashMap<TypeId, Type>,
    classes: &mut Vec<X86ArgClass>,
) {
    let _field_size = type_size(field_ty, type_map) as i64;
    let field_classes = classify_arg_type(field_ty, abs_offset, type_map);
    merge_classes_into(classes, &field_classes, field_offset);
}

/// Merge a list of classes into the `classes` buffer at the given offset.
fn merge_classes_into(
    classes: &mut Vec<X86ArgClass>,
    field_classes: &[X86ArgClass],
    field_offset: i64,
) {
    let start_eightbyte = (field_offset / 8) as usize;
    for (i, cls) in field_classes.iter().enumerate() {
        let idx = start_eightbyte + i;
        if idx < classes.len() {
            classes[idx] = merge_classes(classes[idx], *cls);
        }
    }
}

/// Merge two classes per the AMD64 ABI rules.
/// The more "severe" class takes precedence.
fn merge_classes(a: X86ArgClass, b: X86ArgClass) -> X86ArgClass {
    use X86ArgClass::*;
    match (a, b) {
        // If either is Memory, the result is Memory
        (Memory, _) | (_, Memory) => Memory,
        // If either is NoClass, use the other
        (NoClass, other) | (other, NoClass) => other,
        // Integer + Integer = Integer
        (Integer, Integer) => Integer,
        // SSE + SSE = SSE; SSE + SSEUp = SSE; SSEUp + SSEUp = SSE
        (SSE, SSE) | (SSE, SSEUp) | (SSEUp, SSE) | (SSEUp, SSEUp) => SSE,
        // Integer + SSE = SSE (SSE wins when mixed)
        (Integer, SSE) | (SSE, Integer) => SSE,
        // SSEUp + Integer = SSE
        (SSEUp, Integer) | (Integer, SSEUp) => SSE,
        // X87 combinations
        (X87, X87) => X87,
        (X87, X87Up) | (X87Up, X87) => X87,
        (X87, Integer) | (Integer, X87) => Memory,
        (X87, SSE) | (SSE, X87) => Memory,
        (X87Up, X87Up) => X87Up,
        (X87Up, Integer) | (Integer, X87Up) => Memory,
        (X87Up, SSE) | (SSE, X87Up) => Memory,
        // SSEUp + X87 family -> Memory (mixed)
        (SSEUp, X87) | (X87, SSEUp) => Memory,
        (SSEUp, X87Up) | (X87Up, SSEUp) => Memory,
        // X87 + SSEUp already covered above
        // ComplexX87 pairs
        (ComplexX87, _) | (_, ComplexX87) => ComplexX87,
    }
}

/// Post-merger cleanup per AMD64 ABI §3.2.3 paragraph 5.
///
/// (a) If the size of the aggregate exceeds two eightbytes and the first
///     eightbyte is not SSE or any other eightbyte is not SSEUp, the whole
///     thing is passed in memory.
/// (b) If the size is exactly two eightbytes, enforce SSE + SSEUp pattern:
///     SSEUp only valid as the second eightbyte after SSE in the first.
fn post_merger_cleanup(classes: &mut Vec<X86ArgClass>, _total_size: u64) {
    if classes.is_empty() {
        return;
    }

    let num_eightbytes = classes.len();

    // Rule (a): if > 2 eightbytes and not all SSE/SSEUp → Memory
    if num_eightbytes > 2 {
        let all_sse = classes.iter().all(|c| {
            matches!(
                c,
                X86ArgClass::SSE | X86ArgClass::SSEUp | X86ArgClass::NoClass
            )
        });
        let first_is_sse = matches!(classes[0], X86ArgClass::SSE);
        if !(all_sse && first_is_sse) {
            for c in classes.iter_mut() {
                *c = X86ArgClass::Memory;
            }
            return;
        }
    }

    // Rule (b): SSEUp is only valid as second eightbyte after SSE
    for i in 0..num_eightbytes {
        if classes[i] == X86ArgClass::SSEUp {
            if i == 0 || classes[i - 1] != X86ArgClass::SSE {
                classes[i] = X86ArgClass::SSE;
            }
        }
    }

    // Rule (c): Only the first two eightbytes can be in registers;
    // everything beyond goes to memory (already handled by rule (a) for > 2).
    // For exactly 2 eightbytes, validate the pairing.
    if num_eightbytes == 2 {
        if classes[0] == X86ArgClass::SSE && classes[1] == X86ArgClass::SSEUp {
            // Valid pair: SSE in XMMn, SSEUp in XMM(n+1)
        } else if classes[0] == X86ArgClass::Integer && classes[1] == X86ArgClass::Integer {
            // Valid pair: both in GPRs
        } else if classes[0] == X86ArgClass::NoClass && classes[1] == X86ArgClass::Integer {
            // First eightbyte is empty → second goes in a GPR
        } else if classes[0] == X86ArgClass::Integer && classes[1] == X86ArgClass::NoClass {
            // Only first eightbyte used
        } else if classes[0] == X86ArgClass::SSE && classes[1] == X86ArgClass::NoClass {
            // Only first eightbyte SSE
        } else {
            // Mixed: pass in memory
            for c in classes.iter_mut() {
                *c = X86ArgClass::Memory;
            }
        }
    }
}

// ============================================================================
// System V AMD64 ABI argument assignment
// ============================================================================

/// Assign arguments per System V AMD64 ABI.
pub fn assign_sysv_args(
    args: &[Type],
    type_map: &HashMap<TypeId, Type>,
) -> (Vec<X86ArgInfo>, X86CallFrame) {
    let int_regs = vec![RDI, RSI, RDX, RCX, R8, R9];
    let sse_regs = vec![XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6, XMM7];

    let mut arg_infos = Vec::new();
    let mut int_used = 0usize;
    let mut sse_used = 0usize;
    let mut stack_offset = 8i64; // First stack arg is above the return address
    let mut arg_offsets = Vec::new();

    for ty in args {
        let size = type_size(ty, type_map);
        let align = type_alignment(ty, type_map);
        let classes = classify_arg_type(ty, 0, type_map);

        let mut info = X86ArgInfo {
            size: size as u32,
            alignment: align as u32,
            ..Default::default()
        };

        if classes.iter().any(|c| *c == X86ArgClass::Memory) {
            // Pass on stack
            let padding = if stack_offset % (align as i64) != 0 {
                (align as i64) - (stack_offset % (align as i64))
            } else {
                0
            };
            stack_offset += padding;
            info.stack_offset = stack_offset;
            info.padding = padding as u32;
            info.is_byval = ty.is_struct();
            stack_offset += size as i64;
            arg_offsets.push(info.stack_offset);
        } else {
            // Try to assign to registers
            let int_needed = classes
                .iter()
                .filter(|c| **c == X86ArgClass::Integer)
                .count();
            let sse_needed = classes
                .iter()
                .filter(|c| matches!(c, X86ArgClass::SSE | X86ArgClass::SSEUp))
                .count();

            if int_used + int_needed <= int_regs.len() && sse_used + sse_needed <= sse_regs.len() {
                info.in_reg = true;
                let mut ridx = int_used;
                for cls in &classes {
                    match cls {
                        X86ArgClass::Integer => {
                            if ridx < int_regs.len() {
                                info.regs.push(int_regs[ridx]);
                                ridx += 1;
                            }
                        }
                        X86ArgClass::SSE | X86ArgClass::SSEUp => {
                            if sse_used < sse_regs.len() {
                                info.regs.push(sse_regs[sse_used]);
                                sse_used += 1;
                            }
                        }
                        X86ArgClass::NoClass => {}
                        _ => {}
                    }
                }
                int_used += int_needed;
                // sse_used already incremented in the loop
                info.stack_offset = 0; // Not on stack
                arg_offsets.push(-1); // Sentinel
            } else {
                // Not enough registers → pass on stack
                let padding = if stack_offset % (align as i64) != 0 {
                    (align as i64) - (stack_offset % (align as i64))
                } else {
                    0
                };
                stack_offset += padding;
                info.stack_offset = stack_offset;
                info.padding = padding as u32;
                info.is_byval = ty.is_struct();
                stack_offset += size as i64;
                arg_offsets.push(info.stack_offset);
            }
        }

        arg_infos.push(info);
    }

    // Align stack to 16 bytes
    let alignment = 16i64;
    let padding = if stack_offset % alignment != 0 {
        alignment - (stack_offset % alignment)
    } else {
        0
    };

    let frame = X86CallFrame {
        stack_size: stack_offset + padding,
        arg_offsets,
        return_save_area: None,
        shadow_store_size: 0,
        alignment_padding: padding,
    };

    (arg_infos, frame)
}

/// Determine return registers for System V from the classified classes.
fn sysv_return_regs_from_classes(classes: &[X86ArgClass]) -> Vec<u16> {
    let mut regs = Vec::new();

    for cls in classes {
        match cls {
            X86ArgClass::Integer => {
                if regs.is_empty() {
                    regs.push(RAX);
                } else if regs.len() == 1 {
                    regs.push(RDX);
                }
            }
            X86ArgClass::SSE | X86ArgClass::SSEUp => {
                if regs.is_empty() {
                    regs.push(XMM0);
                } else if regs.len() == 1 {
                    regs.push(XMM1);
                }
            }
            X86ArgClass::X87 => {
                regs.push(ST0);
            }
            X86ArgClass::Memory => {
                // Hidden pointer in RAX
                regs.push(RAX);
            }
            _ => {}
        }
    }

    if regs.is_empty() {
        regs.push(RAX); // Default for single integers
    }

    regs
}

// ============================================================================
// Microsoft x64 ABI argument assignment
// ============================================================================

/// Assign arguments per Microsoft x64 calling convention.
///
/// Integer and floating-point arguments share the same slot counter:
/// - Slot 0 → RCX (int) / XMM0 (float)
/// - Slot 1 → RDX (int) / XMM1 (float)
/// - Slot 2 → R8  (int) / XMM2 (float)
/// - Slot 3 → R9  (int) / XMM3 (float)
fn assign_win64_args(
    args: &[Type],
    type_map: &HashMap<TypeId, Type>,
) -> (Vec<X86ArgInfo>, X86CallFrame) {
    let int_regs = vec![RCX, RDX, R8, R9];
    let sse_regs = vec![XMM0, XMM1, XMM2, XMM3];
    let shadow_size: i64 = 32;

    let mut arg_infos = Vec::new();
    let mut slot = 0usize; // Shared argument slot (0-3 for registers)
    let mut stack_offset = shadow_size + 8; // After shadow store + return address
    let mut arg_offsets = Vec::new();

    for ty in args {
        let size = type_size(ty, type_map);
        let align = type_alignment(ty, type_map).max(8);

        let mut info = X86ArgInfo {
            size: size as u32,
            alignment: align as u32,
            ..Default::default()
        };

        if ty.is_floating_point() && size <= 8 {
            // Float/double in XMM at the current slot
            if slot < sse_regs.len() {
                info.in_reg = true;
                info.regs.push(sse_regs[slot]);
                slot += 1;
            } else {
                // Stack spill
                stack_offset = align_to_i64(stack_offset, align as i64);
                info.stack_offset = stack_offset;
                stack_offset += 8;
                arg_offsets.push(info.stack_offset);
                arg_infos.push(info);
                continue;
            }
        } else if size <= 8 {
            // Integer or pointer
            if slot < int_regs.len() {
                info.in_reg = true;
                info.regs.push(int_regs[slot]);
                slot += 1;
            } else {
                stack_offset = align_to_i64(stack_offset, align as i64);
                info.stack_offset = stack_offset;
                stack_offset += 8;
            }
        } else if size <= 16 && (ty.is_struct() || ty.is_vector()) {
            // __m128 or small struct — try registers
            if slot < int_regs.len() {
                info.in_reg = true;
                info.regs.push(int_regs[slot]);
                slot += 1;
                // May need second register
                if size > 8 && slot < int_regs.len() {
                    info.regs.push(int_regs[slot]);
                    slot += 1;
                }
            } else {
                stack_offset = align_to_i64(stack_offset, align as i64);
                info.stack_offset = stack_offset;
                info.is_byval = true;
                stack_offset += size as i64;
            }
        } else {
            // Large aggregate: pass by pointer (hidden copy)
            if slot < int_regs.len() {
                info.in_reg = true;
                info.regs.push(int_regs[slot]);
                info.is_byval = true;
                slot += 1;
            } else {
                stack_offset = align_to_i64(stack_offset, 8);
                info.stack_offset = stack_offset;
                info.is_byval = true;
                stack_offset += 8;
            }
        }

        if !info.in_reg {
            arg_offsets.push(info.stack_offset);
        } else {
            arg_offsets.push(-1);
        }

        arg_infos.push(info);
    }

    // Stack must be 16-byte aligned
    let alignment = 16i64;
    let padding = if stack_offset % alignment != 0 {
        alignment - (stack_offset % alignment)
    } else {
        0
    };

    let frame = X86CallFrame {
        stack_size: stack_offset + padding,
        arg_offsets,
        return_save_area: None,
        shadow_store_size: shadow_size,
        alignment_padding: padding,
    };

    (arg_infos, frame)
}

/// Win64 return value register assignment.
fn win64_return_regs(ty: &Type, size: u64) -> Vec<u16> {
    if ty.is_floating_point() && size <= 8 {
        vec![XMM0]
    } else if size <= 8 {
        vec![RAX]
    } else if size <= 16 && (ty.is_struct() || ty.is_vector()) {
        vec![RAX, RDX]
    } else {
        // Hidden pointer returned in RAX
        vec![RAX]
    }
}

// ============================================================================
// 32-bit calling convention argument assignment
// ============================================================================

/// Assign arguments for cdecl (all on stack, caller cleans).
fn assign_cdecl_args(
    args: &[Type],
    type_map: &HashMap<TypeId, Type>,
) -> (Vec<X86ArgInfo>, X86CallFrame) {
    assign_stack_only_args(args, type_map)
}

/// Assign arguments for stdcall (all on stack, callee cleans).
fn assign_stdcall_args(
    args: &[Type],
    type_map: &HashMap<TypeId, Type>,
) -> (Vec<X86ArgInfo>, X86CallFrame) {
    assign_stack_only_args(args, type_map)
}

/// Assign arguments for 32-bit fastcall (ECX, EDX then stack).
fn assign_fastcall_args(
    args: &[Type],
    type_map: &HashMap<TypeId, Type>,
) -> (Vec<X86ArgInfo>, X86CallFrame) {
    let int_regs = vec![ECX, EDX];
    let mut arg_infos = Vec::new();
    let mut int_used = 0usize;
    let mut stack_offset = 4i64; // Above return address (32-bit)
    let mut arg_offsets = Vec::new();

    for ty in args {
        let size = type_size(ty, type_map);
        let align = type_alignment(ty, type_map).max(4);

        let mut info = X86ArgInfo {
            size: size as u32,
            alignment: align as u32,
            ..Default::default()
        };

        if size <= 4 && int_used < int_regs.len() {
            info.in_reg = true;
            info.regs.push(int_regs[int_used]);
            int_used += 1;
            arg_offsets.push(-1);
        } else {
            let padding = if stack_offset % (align as i64) != 0 {
                (align as i64) - (stack_offset % (align as i64))
            } else {
                0
            };
            stack_offset += padding;
            info.stack_offset = stack_offset;
            info.padding = padding as u32;
            stack_offset += size as i64;
            arg_offsets.push(info.stack_offset);
        }

        arg_infos.push(info);
    }

    let frame = X86CallFrame {
        stack_size: stack_offset,
        arg_offsets,
        return_save_area: None,
        shadow_store_size: 0,
        alignment_padding: 0,
    };

    (arg_infos, frame)
}

/// Assign arguments for 32-bit thiscall (ECX = this, rest on stack).
fn assign_thiscall_args(
    args: &[Type],
    type_map: &HashMap<TypeId, Type>,
) -> (Vec<X86ArgInfo>, X86CallFrame) {
    let mut arg_infos = Vec::new();
    let mut this_assigned = false;
    let mut stack_offset = 4i64;
    let mut arg_offsets = Vec::new();

    for ty in args {
        let size = type_size(ty, type_map);
        let align = type_alignment(ty, type_map).max(4);

        let mut info = X86ArgInfo {
            size: size as u32,
            alignment: align as u32,
            ..Default::default()
        };

        if !this_assigned {
            info.in_reg = true;
            info.regs.push(ECX);
            this_assigned = true;
            arg_offsets.push(-1);
        } else {
            let padding = if stack_offset % (align as i64) != 0 {
                (align as i64) - (stack_offset % (align as i64))
            } else {
                0
            };
            stack_offset += padding;
            info.stack_offset = stack_offset;
            info.padding = padding as u32;
            stack_offset += size as i64;
            arg_offsets.push(info.stack_offset);
        }

        arg_infos.push(info);
    }

    let frame = X86CallFrame {
        stack_size: stack_offset,
        arg_offsets,
        return_save_area: None,
        shadow_store_size: 0,
        alignment_padding: 0,
    };

    (arg_infos, frame)
}

/// Assign arguments for 32-bit vectorcall (XMM0-5 for SIMD, ECX/EDX for int).
fn assign_vectorcall_args(
    args: &[Type],
    type_map: &HashMap<TypeId, Type>,
) -> (Vec<X86ArgInfo>, X86CallFrame) {
    let int_regs = vec![ECX, EDX];
    let xmm_regs = vec![XMM0, XMM1, XMM2, XMM3, XMM4, XMM5];
    let mut arg_infos = Vec::new();
    let mut int_used = 0usize;
    let mut xmm_used = 0usize;
    let mut stack_offset = 4i64;
    let mut arg_offsets = Vec::new();

    for ty in args {
        let size = type_size(ty, type_map);
        let align = type_alignment(ty, type_map).max(4);

        let mut info = X86ArgInfo {
            size: size as u32,
            alignment: align as u32,
            ..Default::default()
        };

        if ty.is_vector() && xmm_used < xmm_regs.len() {
            info.in_reg = true;
            info.regs.push(xmm_regs[xmm_used]);
            xmm_used += 1;
            arg_offsets.push(-1);
        } else if size <= 4 && int_used < int_regs.len() {
            info.in_reg = true;
            info.regs.push(int_regs[int_used]);
            int_used += 1;
            arg_offsets.push(-1);
        } else {
            let padding = if stack_offset % (align as i64) != 0 {
                (align as i64) - (stack_offset % (align as i64))
            } else {
                0
            };
            stack_offset += padding;
            info.stack_offset = stack_offset;
            info.padding = padding as u32;
            stack_offset += size as i64;
            arg_offsets.push(info.stack_offset);
        }

        arg_infos.push(info);
    }

    let frame = X86CallFrame {
        stack_size: stack_offset,
        arg_offsets,
        return_save_area: None,
        shadow_store_size: 0,
        alignment_padding: 0,
    };

    (arg_infos, frame)
}

/// Assign all arguments on the stack (used for cdecl, stdcall, and fallback).
fn assign_stack_only_args(
    args: &[Type],
    type_map: &HashMap<TypeId, Type>,
) -> (Vec<X86ArgInfo>, X86CallFrame) {
    let mut arg_infos = Vec::new();
    let mut stack_offset = 4i64; // Above return address (32-bit) or 8 (64-bit)
    let mut arg_offsets = Vec::new();

    // Detect 64-bit by checking pointer size in type_map
    let ptr_size: i64 = 8; // Default to 64-bit

    for ty in args {
        let size = type_size(ty, type_map);
        let align = type_alignment(ty, type_map);

        let padding = if stack_offset % (align as i64) != 0 {
            (align as i64) - (stack_offset % (align as i64))
        } else {
            0
        };
        stack_offset += padding;

        let info = X86ArgInfo {
            in_reg: false,
            stack_offset,
            size: size as u32,
            alignment: align as u32,
            is_byval: ty.is_struct() && size > ptr_size as u64,
            is_sret: false,
            padding: padding as u32,
            ..Default::default()
        };

        stack_offset += size as i64;
        arg_offsets.push(info.stack_offset);
        arg_infos.push(info);
    }

    let frame = X86CallFrame {
        stack_size: stack_offset,
        arg_offsets,
        return_save_area: None,
        shadow_store_size: 0,
        alignment_padding: 0,
    };

    (arg_infos, frame)
}

/// 32-bit return value registers: EAX for int/ptr, EDX:EAX for i64, ST0 for x87.
fn cdecl_return_regs(ty: &Type, type_map: &HashMap<TypeId, Type>) -> Vec<u16> {
    match &ty.kind {
        TypeKind::Void => vec![],
        TypeKind::X86FP80 => vec![ST0],
        TypeKind::Float | TypeKind::Double => {
            // Return in ST0 (x87) for 32-bit; in SSE for modern targets
            // Use XMM0 for SSE-enabled 32-bit
            vec![XMM0]
        }
        TypeKind::Integer { bits } if *bits <= 32 => vec![EAX],
        TypeKind::Integer { bits } if *bits <= 64 => vec![EDX, EAX],
        TypeKind::Pointer { .. } => vec![EAX],
        _ => {
            let size = type_size(ty, type_map);
            if size <= 4 {
                vec![EAX]
            } else if size <= 8 {
                vec![EDX, EAX]
            } else {
                // Hidden pointer in EAX
                vec![EAX]
            }
        }
    }
}

/// i64 align_to for signed values.
fn align_to_i64(value: i64, alignment: i64) -> i64 {
    if alignment == 0 {
        return value;
    }
    ((value + alignment - 1) / alignment) * alignment
}

// ============================================================================
// x86-64 System V: Full Eightbyte Classification
// ============================================================================

/// The x86-64 System V ABI classifies each eightbyte of an aggregate type
/// into one of these classes, which determines how it is passed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EightByteClass {
    /// No class (padding or uninitialized).
    NO_CLASS,
    /// Pass in a general-purpose register (or on stack if registers exhausted).
    INTEGER,
    /// Pass in an SSE register (XMM).
    SSE,
    /// Pass in an SSEUP register (the upper half of an XMM pair).
    SSEUP,
    /// Pass in an X87 floating-point register (87-class).
    X87,
    /// Pass in an X87UP register.
    X87UP,
    /// Pass in a pair of registers (COMPLEX_X87).
    COMPLEX_X87,
    /// Pass in memory (on the stack).
    MEMORY,
}

impl EightByteClass {
    /// Check if this class is a register-passing class.
    pub fn is_register_class(&self) -> bool {
        matches!(
            self,
            Self::INTEGER | Self::SSE | Self::SSEUP | Self::X87 | Self::X87UP
        )
    }

    /// Check if two classes can be merged (per ABI post-merging rules).
    pub fn can_merge_with(&self, other: &Self) -> bool {
        match (self, other) {
            // INTEGER + SSE = MEMORY
            (Self::INTEGER, Self::SSE) | (Self::SSE, Self::INTEGER) => false,
            // INTEGER + INTEGER = INTEGER
            (Self::INTEGER, Self::INTEGER) => true,
            // SSE + SSEUP = SSE
            (Self::SSE, Self::SSEUP) | (Self::SSEUP, Self::SSE) => true,
            // X87 + X87UP = X87
            (Self::X87, Self::X87UP) | (Self::X87UP, Self::X87) => true,
            // Two SSE = SSE
            (Self::SSE, Self::SSE) => true,
            // Two INTEGER (both INTEGER or INTEGER + NO_CLASS) = INTEGER
            (Self::INTEGER, Self::NO_CLASS) | (Self::NO_CLASS, Self::INTEGER) => true,
            (Self::SSE, Self::NO_CLASS) | (Self::NO_CLASS, Self::SSE) => true,
            // Same classes
            (a, b) if a == b => true,
            _ => false,
        }
    }

    /// Post-merging cleanup: simplify class pairs to canonical form.
    pub fn post_merge(a: Self, b: Self) -> (Self, Self) {
        match (a, b) {
            (Self::MEMORY, _) | (_, Self::MEMORY) => (Self::MEMORY, Self::MEMORY),
            (Self::INTEGER, Self::SSE) | (Self::SSE, Self::INTEGER) => (Self::MEMORY, Self::MEMORY),
            (Self::SSEUP, Self::SSE) => (Self::SSE, Self::SSEUP),
            (Self::X87UP, Self::X87) => (Self::X87, Self::X87UP),
            // Two SSEUP → SSE + SSEUP
            (Self::SSEUP, Self::SSEUP) => (Self::SSE, Self::SSEUP),
            // Two X87UP → X87 + X87UP
            (Self::X87UP, Self::X87UP) => (Self::X87, Self::X87UP),
            other => other,
        }
    }
}

/// A complete eightbyte classification result for a struct/union.
#[derive(Debug, Clone)]
pub struct EightByteClassification {
    /// Classification for each eightbyte (0-3 eightbytes for up to 32-byte types).
    pub classes: [EightByteClass; 4],
    /// Number of valid eightbytes.
    pub num_eightbytes: u8,
    /// Whether this type must be passed in memory (indirect).
    pub is_indirect: bool,
    /// Whether this is a homogeneous floating-point aggregate (HFA).
    pub is_hfa: bool,
    /// For HFAs: the number of homogeneous elements.
    pub hfa_count: u8,
}

impl EightByteClassification {
    pub fn new() -> Self {
        Self {
            classes: [EightByteClass::NO_CLASS; 4],
            num_eightbytes: 0,
            is_indirect: false,
            is_hfa: false,
            hfa_count: 0,
        }
    }

    /// Classify as memory (indirect).
    pub fn memory() -> Self {
        Self {
            classes: [EightByteClass::MEMORY; 4],
            num_eightbytes: 0,
            is_indirect: true,
            is_hfa: false,
            hfa_count: 0,
        }
    }

    /// Check if this classification requires sret (hidden struct return).
    pub fn needs_sret(&self) -> bool {
        self.is_indirect || self.classes[0] == EightByteClass::MEMORY
    }

    /// Get the GPR count needed (number of INTEGER eightbytes).
    pub fn gpr_count(&self) -> u8 {
        self.classes
            .iter()
            .take(self.num_eightbytes as usize)
            .filter(|c| **c == EightByteClass::INTEGER)
            .count() as u8
    }

    /// Get the SSE register count needed.
    pub fn sse_count(&self) -> u8 {
        self.classes
            .iter()
            .take(self.num_eightbytes as usize)
            .filter(|c| matches!(c, EightByteClass::SSE | EightByteClass::SSEUP))
            .count() as u8
    }
}

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

// ============================================================================
// HFA (Homogeneous Floating-point Aggregate) Detection
// ============================================================================

/// Detects whether a struct/union is an HFA or HVA (Homogeneous Vector Aggregate).
/// HFAs are structs composed entirely of the same floating-point type and
/// are passed in SIMD/FP registers instead of on the stack.
#[derive(Debug, Clone)]
pub struct HFADetector;

impl HFADetector {
    /// Check if a type is an HFA.
    /// Returns (base_type, count) if it is, None otherwise.
    pub fn detect_hfa(fields: &[HfaFieldInfo]) -> Option<(HfaBaseType, u8)> {
        if fields.is_empty() {
            return None;
        }

        if fields.len() > 4 {
            return None; // Max 4 members for HFA on x86-64
        }

        let base = fields[0].base_type;
        if base == HfaBaseType::None {
            return None;
        }

        // All fields must have the same base type
        for field in fields.iter().skip(1) {
            if field.base_type != base {
                return None;
            }
        }

        let count = fields.len() as u8;
        Some((base, count))
    }
}

/// Base types for HFA detection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HfaBaseType {
    None,
    Float,
    Double,
    Float128,
    Float16,
    BFloat16,
    Vector64,
    Vector128,
}

/// Information about a struct field for HFA detection.
#[derive(Debug, Clone, Copy)]
pub struct HfaFieldInfo {
    pub base_type: HfaBaseType,
    pub offset: u32,
    pub size: u32,
}

// ============================================================================
// Microsoft x64 Calling Convention
// ============================================================================

/// Microsoft x64 calling convention parameters.
#[derive(Debug, Clone)]
pub struct MicrosoftX64CC {
    /// Shadow space (home space) size: 32 bytes (4 QWORDs) for the first 4 args.
    pub shadow_space: u32,
    /// Whether this is __vectorcall (uses XMM registers for SIMD args).
    pub is_vectorcall: bool,
    /// Whether this is __fastcall (first 2 args in RCX, RDX).
    pub is_fastcall: bool,
    /// Required stack alignment.
    pub stack_alignment: u32,
}

impl MicrosoftX64CC {
    pub fn standard() -> Self {
        Self {
            shadow_space: 32,
            is_vectorcall: false,
            is_fastcall: false,
            stack_alignment: 16,
        }
    }

    pub fn vectorcall() -> Self {
        Self {
            shadow_space: 32,
            is_vectorcall: true,
            is_fastcall: false,
            stack_alignment: 16,
        }
    }

    pub fn fastcall() -> Self {
        Self {
            shadow_space: 32,
            is_vectorcall: false,
            is_fastcall: true,
            stack_alignment: 16,
        }
    }

    /// Get the integer parameter registers for MS x64.
    pub fn int_arg_regs(&self) -> &[u16] {
        if self.is_fastcall {
            &[RCX, RDX]
        } else {
            &[RCX, RDX, R8, R9]
        }
    }

    /// Get the XMM parameter registers for vectorcall.
    pub fn xmm_arg_regs(&self) -> &[u16] {
        if self.is_vectorcall {
            &[XMM0, XMM1, XMM2, XMM3, XMM4, XMM5]
        } else {
            &[XMM0, XMM1, XMM2, XMM3]
        }
    }

    /// Get the caller-saved (volatile) registers for MS x64.
    pub fn caller_saved_regs(&self) -> Vec<u16> {
        vec![RAX, RCX, RDX, R8, R9, R10, R11]
    }

    /// Get the callee-saved (non-volatile) registers for MS x64.
    pub fn callee_saved_regs(&self) -> Vec<u16> {
        vec![RBX, RBP, RDI, RSI, R12, R13, R14, R15]
    }

    /// Get the required shadow space size.
    pub fn shadow_space_size(&self) -> u32 {
        self.shadow_space
    }

    /// Check if a type is passed indirectly (by pointer) in MS x64.
    pub fn is_indirect(&self, size: u32) -> bool {
        // MS x64 passes types larger than 8 bytes indirectly,
        // unless they are powers of 2 (1,2,4,8) and not aggregates.
        size > 8 && !size.is_power_of_two()
    }
}

// ============================================================================
// X86-32 Calling Conventions: cdecl, stdcall, fastcall, thiscall, vectorcall
// ============================================================================

/// X86-32 calling convention enumeration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86_32CallingConvention {
    /// cdecl: caller cleans stack, all args on stack.
    CDecl,
    /// stdcall: callee cleans stack, all args on stack.
    StdCall,
    /// fastcall: first 2 args in ECX, EDX; rest on stack.
    FastCall,
    /// thiscall: 'this' pointer in ECX; rest on stack (MSVC).
    ThisCallMSVC,
    /// thiscall: 'this' pointer in ECX; rest on stack (GNU).
    ThisCallGNU,
    /// vectorcall: first 6 args in ECX,EDX + XMM0-XMM3; rest on stack.
    VectorCall,
    /// regcall: all args in registers if possible.
    RegCall,
    /// Pascal: left-to-right evaluation, callee cleans.
    Pascal,
}

impl X86_32CallingConvention {
    /// Get the name of this convention.
    pub fn name(&self) -> &'static str {
        match self {
            Self::CDecl => "cdecl",
            Self::StdCall => "stdcall",
            Self::FastCall => "fastcall",
            Self::ThisCallMSVC => "thiscall (MSVC)",
            Self::ThisCallGNU => "thiscall (GNU)",
            Self::VectorCall => "vectorcall",
            Self::RegCall => "regcall",
            Self::Pascal => "pascal",
        }
    }

    /// Whether the callee cleans the stack.
    pub fn callee_cleans_stack(&self) -> bool {
        matches!(
            self,
            Self::StdCall | Self::FastCall | Self::ThisCallMSVC | Self::Pascal
        )
    }

    /// Get the integer argument registers for this convention.
    pub fn int_arg_regs(&self) -> &[u16] {
        match self {
            Self::FastCall | Self::ThisCallMSVC => &[ECX, EDX],
            Self::ThisCallGNU => &[ECX],
            Self::VectorCall => &[ECX, EDX],
            Self::RegCall => &[EAX, ECX, EDX, EDI, ESI],
            _ => &[],
        }
    }

    /// Get the XMM argument registers (vectorcall only).
    pub fn xmm_arg_regs(&self) -> &[u16] {
        match self {
            Self::VectorCall => &[XMM0, XMM1, XMM2, XMM3],
            _ => &[],
        }
    }

    /// Minimum stack argument alignment.
    pub fn stack_alignment(&self) -> u32 {
        match self {
            Self::VectorCall => 16,
            _ => 4,
        }
    }

    /// Check if this convention passes 'this' pointer in ECX.
    pub fn has_this_in_ecx(&self) -> bool {
        matches!(self, Self::ThisCallMSVC | Self::ThisCallGNU)
    }
}

// ============================================================================
// RegCall: __regcall with register parameter assignment
// ============================================================================

/// __regcall convention: attempts to pass arguments in registers.
/// Uses up to 5 GPRs and 8 XMM registers before spilling to stack.
#[derive(Debug, Clone)]
pub struct RegCallConvention {
    /// Integer argument registers (in order): EAX, ECX, EDX, EDI, ESI
    pub int_regs: Vec<u16>,
    /// XMM argument registers: XMM0-XMM7
    pub xmm_regs: Vec<u16>,
    /// Return register: EAX (or EDX:EAX for 64-bit returns)
    pub ret_regs: Vec<u16>,
}

impl RegCallConvention {
    pub fn new_32() -> Self {
        Self {
            int_regs: vec![EAX, ECX, EDX, EDI, ESI],
            xmm_regs: vec![XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6, XMM7],
            ret_regs: vec![EAX, EDX],
        }
    }

    /// Assign a parameter to the next available register.
    pub fn assign_param(
        &self,
        used_int: &mut usize,
        used_xmm: &mut usize,
        is_fp: bool,
    ) -> Option<u16> {
        if is_fp && *used_xmm < self.xmm_regs.len() {
            let reg = self.xmm_regs[*used_xmm];
            *used_xmm += 1;
            Some(reg)
        } else if !is_fp && *used_int < self.int_regs.len() {
            let reg = self.int_regs[*used_int];
            *used_int += 1;
            Some(reg)
        } else {
            None
        }
    }

    /// How many integer registers remain.
    pub fn remaining_int(&self, used: usize) -> usize {
        self.int_regs.len().saturating_sub(used)
    }

    /// How many XMM registers remain.
    pub fn remaining_xmm(&self, used: usize) -> usize {
        self.xmm_regs.len().saturating_sub(used)
    }
}

// ============================================================================
// X32 ABI (ILP32 on x86-64)
// ============================================================================

/// X32 ABI: ILP32 programming model on x86-64.
/// Uses 32-bit pointers but allows access to 64-bit registers and instructions.
#[derive(Debug, Clone)]
pub struct X32ABI {
    /// Pointer size in bytes (4 for ILP32).
    pub pointer_size: u8,
    /// Size of long type.
    pub long_size: u8,
    /// Size of size_t.
    pub size_t_size: u8,
    /// Stack alignment.
    pub stack_alignment: u32,
}

impl X32ABI {
    pub fn new() -> Self {
        Self {
            pointer_size: 4,
            long_size: 4,
            size_t_size: 4,
            stack_alignment: 16,
        }
    }

    /// Check if this target uses the X32 ABI.
    pub fn is_x32(&self) -> bool {
        self.pointer_size == 4 && self.size_t_size == 4
    }

    /// Get the register class for a pointer (32-bit GPR in X32).
    pub fn pointer_register_class(&self) -> &'static str {
        "r32"
    }

    /// For X32, arguments are zero-extended to 32 bits when passed in registers.
    pub fn zero_extend_args(&self) -> bool {
        true
    }

    /// X32 still uses the full 64-bit register file, just with 32-bit values.
    pub fn available_gprs(&self) -> u8 {
        16 // full set of 64-bit GPRs available
    }
}

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

// ============================================================================
// Return Value Lowering: sret, multiple registers, varargs
// ============================================================================

/// Describes how a function return value is lowered to machine registers/memory.
#[derive(Debug, Clone)]
pub struct ReturnValueLowering {
    /// If Some, the value is returned via a hidden sret pointer.
    pub sret_pointer: Option<u16>,
    /// Register(s) used for the return value.
    pub ret_regs: Vec<ReturnRegister>,
    /// Whether the return value spans multiple registers.
    pub is_multi_reg: bool,
    /// Total size of the return value in bytes.
    pub size: u32,
}

/// A single register used in a return value.
#[derive(Debug, Clone, Copy)]
pub struct ReturnRegister {
    /// The physical register number.
    pub reg: u16,
    /// The byte offset into the return value.
    pub offset: u32,
    /// The size of this portion.
    pub size: u8,
    /// Whether this is a GPR or XMM register.
    pub is_xmm: bool,
}

impl ReturnValueLowering {
    pub fn new() -> Self {
        Self {
            sret_pointer: None,
            ret_regs: Vec::new(),
            is_multi_reg: false,
            size: 0,
        }
    }

    /// Set up sret (indirect) return.
    pub fn sret() -> Self {
        Self {
            sret_pointer: Some(RDI), // sret pointer passed in RDI on SysV
            ret_regs: Vec::new(),
            is_multi_reg: false,
            size: 0,
        }
    }

    /// Single integer return value in RAX.
    pub fn int_ret_rax(size: u8) -> Self {
        Self {
            sret_pointer: None,
            ret_regs: vec![ReturnRegister {
                reg: RAX,
                offset: 0,
                size,
                is_xmm: false,
            }],
            is_multi_reg: false,
            size: size as u32,
        }
    }

    /// Double-width return in RAX:RDX.
    pub fn pair_ret_rax_rdx(size: u32) -> Self {
        let half = (size / 2) as u8;
        Self {
            sret_pointer: None,
            ret_regs: vec![
                ReturnRegister {
                    reg: RAX,
                    offset: 0,
                    size: half,
                    is_xmm: false,
                },
                ReturnRegister {
                    reg: RDX,
                    offset: half as u32,
                    size: half,
                    is_xmm: false,
                },
            ],
            is_multi_reg: true,
            size,
        }
    }

    /// Floating-point return in XMM0.
    pub fn fp_ret_xmm0() -> Self {
        Self {
            sret_pointer: None,
            ret_regs: vec![ReturnRegister {
                reg: XMM0,
                offset: 0,
                size: 8,
                is_xmm: true,
            }],
            is_multi_reg: false,
            size: 8,
        }
    }

    /// HFA return: multiple XMM registers.
    pub fn hfa_ret(count: u8) -> Self {
        let xmm_regs = [XMM0, XMM1, XMM2, XMM3];
        let mut ret_regs = Vec::new();
        for i in 0..count.min(4) {
            ret_regs.push(ReturnRegister {
                reg: xmm_regs[i as usize],
                offset: (i as u32) * 8,
                size: 8,
                is_xmm: true,
            });
        }
        Self {
            sret_pointer: None,
            ret_regs,
            is_multi_reg: count > 1,
            size: count as u32 * 8,
        }
    }
}

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

// ============================================================================
// Varargs Handling: va_list, register save area, overflow_arg_area
// ============================================================================

/// Varargs frame setup for x86-64 System V ABI.
/// Describes the va_list structure layout and argument access.
#[derive(Debug, Clone)]
pub struct VarArgsInfo {
    /// Offset of gp_offset field in va_list.
    pub gp_offset_offset: u32,
    /// Offset of fp_offset field in va_list.
    pub fp_offset_offset: u32,
    /// Offset of overflow_arg_area pointer in va_list.
    pub overflow_arg_area_offset: u32,
    /// Offset of reg_save_area pointer in va_list.
    pub reg_save_area_offset: u32,
    /// Total size of the va_list structure.
    pub va_list_size: u32,
    /// Number of GPRs used for register save area.
    pub num_gpr_save: u8,
    /// Number of XMM registers used for register save area.
    pub num_xmm_save: u8,
    /// Size of the register save area.
    pub reg_save_area_size: u32,
}

impl VarArgsInfo {
    /// Create varargs info for x86-64 System V.
    pub fn sysv_64() -> Self {
        Self {
            gp_offset_offset: 0,
            fp_offset_offset: 4,
            overflow_arg_area_offset: 8,
            reg_save_area_offset: 16,
            va_list_size: 24,
            num_gpr_save: 6,
            num_xmm_save: 8,
            reg_save_area_size: 6 * 8 + 8 * 16, // 6 GPRs * 8 bytes + 8 XMMs * 16 bytes
        }
    }

    /// Create varargs info for Microsoft x64.
    pub fn ms_64() -> Self {
        Self {
            gp_offset_offset: 0,
            fp_offset_offset: 4,
            overflow_arg_area_offset: 8,
            reg_save_area_offset: 16,
            va_list_size: 24,
            num_gpr_save: 4,
            num_xmm_save: 4,
            reg_save_area_size: 4 * 8 + 4 * 16,
        }
    }

    /// Create varargs info for x86-32 (cdecl).
    pub fn x86_32() -> Self {
        Self {
            gp_offset_offset: 0,
            fp_offset_offset: 0,
            overflow_arg_area_offset: 4,
            reg_save_area_offset: 0,
            va_list_size: 8,
            num_gpr_save: 0,
            num_xmm_save: 0,
            reg_save_area_size: 0,
        }
    }

    /// Compute the register save area layout.
    pub fn compute_reg_save_area(&self) -> Vec<(u16, u32, u32)> {
        // Returns (register, offset, size) for each saved register
        let mut area = Vec::new();
        let mut offset: u32 = 0;

        // GPR save area
        let gprs = [RDI, RSI, RDX, RCX, R8, R9];
        for i in 0..self.num_gpr_save.min(6) {
            area.push((gprs[i as usize], offset, 8));
            offset += 8;
        }

        // XMM save area
        let xmms = [XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6, XMM7];
        for i in 0..self.num_xmm_save.min(8) {
            area.push((xmms[i as usize], offset, 16));
            offset += 16;
        }

        area
    }
}

// ============================================================================
// Calling Convention: Full Stack Frame Layout
// ============================================================================

/// Describes the full stack frame layout for a function call.
#[derive(Debug, Clone)]
pub struct StackFrameLayout {
    /// Total frame size.
    pub frame_size: u32,
    /// Offset of return address from RSP on entry.
    pub return_address_offset: i32,
    /// Saved frame pointer offset (from RBP or frame base).
    pub saved_rbp_offset: i32,
    /// Offset where callee-saved registers begin.
    pub callee_saved_start: i32,
    /// Size of the callee-saved register area.
    pub callee_saved_size: u32,
    /// Offset of local variables area.
    pub locals_offset: i32,
    /// Size of local variables area.
    pub locals_size: u32,
    /// Offset of outgoing argument area (for calls made by this function).
    pub outgoing_args_offset: i32,
    /// Size of outgoing argument area.
    pub outgoing_args_size: u32,
    /// Whether this function has a red zone (128 bytes for SysV x86-64).
    pub has_red_zone: bool,
    /// Red zone size.
    pub red_zone_size: u32,
    /// Required stack alignment.
    pub stack_alignment: u32,
}

impl StackFrameLayout {
    pub fn new() -> Self {
        Self {
            frame_size: 0,
            return_address_offset: 8,
            saved_rbp_offset: 0,
            callee_saved_start: 0,
            callee_saved_size: 0,
            locals_offset: 0,
            locals_size: 0,
            outgoing_args_offset: 0,
            outgoing_args_size: 0,
            has_red_zone: true,
            red_zone_size: 128,
            stack_alignment: 16,
        }
    }

    /// Compute the final frame size with alignment.
    pub fn compute_frame_size(&mut self) {
        let mut size = self.callee_saved_size + self.locals_size + self.outgoing_args_size;
        // Align to required boundary
        if size % self.stack_alignment != 0 {
            size = (size + self.stack_alignment - 1) / self.stack_alignment * self.stack_alignment;
        }
        self.frame_size = size;
    }

    /// Calculate the offset of a stack-allocated local from RBP.
    pub fn local_offset_from_rbp(&self, index: usize, size: u32) -> i32 {
        let base = -((index + 1) as i32) * size as i32;
        base - self.callee_saved_size as i32
    }

    /// Get the offset from RSP to the given stack argument.
    pub fn arg_offset_from_rsp(&self, arg_index: usize) -> i32 {
        // Arguments beyond the register-passed ones are at positive offsets from RSP
        // after the return address and saved registers
        8 + self.callee_saved_size as i32 + (arg_index * 8) as i32
    }

    /// Check if a leaf function can avoid setting up a frame pointer.
    pub fn can_omit_frame_pointer(&self) -> bool {
        self.locals_size == 0 && self.callee_saved_size == 0 && self.outgoing_args_size == 0
    }

    /// Disable red zone (for kernel code or when frame is large).
    pub fn disable_red_zone(&mut self) {
        self.has_red_zone = false;
        self.red_zone_size = 0;
    }
}

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

// ============================================================================
// Calling Convention: Parameter Assignment Helpers
// ============================================================================

/// Helper to split a large aggregate parameter into register-sized chunks.
#[derive(Debug, Clone)]
pub struct ParameterSplitter {
    /// Chunks of the parameter, each with register class and offset.
    pub chunks: Vec<ParamChunk>,
    /// Total parameter size in bytes.
    pub total_size: u32,
}

/// A single chunk of a split parameter.
#[derive(Debug, Clone, Copy)]
pub struct ParamChunk {
    /// The register class for this chunk.
    pub reg_class: ParamRegClass,
    /// Offset within the parameter (in bytes).
    pub offset: u32,
    /// Size of this chunk (usually 8).
    pub size: u8,
}

/// Register class for parameter chunks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParamRegClass {
    /// General-purpose register (INTEGER class).
    GPR,
    /// SSE register.
    SSE,
    /// Memory (not passed in register).
    Memory,
}

impl ParameterSplitter {
    pub fn new() -> Self {
        Self {
            chunks: Vec::new(),
            total_size: 0,
        }
    }

    /// Split a parameter into eightbyte chunks per SysV ABI classification.
    pub fn split_into_eightbytes(size: u32, classification: &EightByteClassification) -> Self {
        let mut splitter = Self::new();
        splitter.total_size = size;

        let num_eightbytes = (size + 7) / 8;
        for i in 0..num_eightbytes {
            let class = if (i as usize) < classification.classes.len() {
                classification.classes[i as usize]
            } else {
                EightByteClass::NO_CLASS
            };

            let reg_class = match class {
                EightByteClass::INTEGER => ParamRegClass::GPR,
                EightByteClass::SSE | EightByteClass::SSEUP => ParamRegClass::SSE,
                EightByteClass::MEMORY => ParamRegClass::Memory,
                _ => ParamRegClass::Memory,
            };

            let chunk_size = if i == num_eightbytes - 1 && size % 8 != 0 {
                (size % 8) as u8
            } else {
                8
            };

            splitter.chunks.push(ParamChunk {
                reg_class,
                offset: i * 8,
                size: chunk_size,
            });
        }

        splitter
    }

    /// Get the number of GPRs needed for this parameter.
    pub fn gpr_needed(&self) -> u8 {
        self.chunks
            .iter()
            .filter(|c| c.reg_class == ParamRegClass::GPR)
            .count() as u8
    }

    /// Get the number of SSE registers needed.
    pub fn sse_needed(&self) -> u8 {
        self.chunks
            .iter()
            .filter(|c| c.reg_class == ParamRegClass::SSE)
            .count() as u8
    }

    /// Whether this parameter must go in memory (too many chunks).
    pub fn must_use_memory(&self, available_gprs: u8, available_sse: u8) -> bool {
        self.gpr_needed() > available_gprs || self.sse_needed() > available_sse
    }
}

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

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{Type, TypeId, TypeKind, TypeStore};

    /// Helper to create a type map with primitive types for testing.
    fn make_type_map() -> HashMap<TypeId, Type> {
        let mut store = TypeStore::new();
        let mut map = HashMap::new();

        // Insert all the types via the store and populate the map
        let types: Vec<Type> = vec![
            Type::void(),
            Type::i1(),
            Type::i8(),
            Type::i16(),
            Type::i32(),
            Type::i64(),
            Type::i128(),
            Type::float(),
            Type::double(),
            Type::half(),
            Type::bfloat(),
            Type::fp128(),
            Type::x86_fp80(),
            Type::ppc_fp128(),
            Type::x86_mmx(),
            Type::pointer(0),
        ];

        for ty in types {
            let uniqued = store.insert_or_get(ty.clone());
            map.insert(uniqued.id, uniqued);
        }

        map
    }

    /// Register a compound type (struct, array, vector) and return its TypeId.
    fn register_type(ty: Type, store: &mut TypeStore, map: &mut HashMap<TypeId, Type>) -> TypeId {
        let uniqued = store.insert_or_get(ty);
        let id = uniqued.id;
        map.insert(id, uniqued);
        id
    }

    // ==========================================================================
    // X86ArgClass tests
    // ==========================================================================

    #[test]
    fn test_arg_class_is_register_class() {
        assert!(X86ArgClass::Integer.is_register_class());
        assert!(X86ArgClass::SSE.is_register_class());
        assert!(X86ArgClass::SSEUp.is_register_class());
        assert!(X86ArgClass::X87.is_register_class());
        assert!(!X86ArgClass::NoClass.is_register_class());
        assert!(!X86ArgClass::Memory.is_register_class());
        assert!(!X86ArgClass::X87Up.is_register_class());
        assert!(!X86ArgClass::ComplexX87.is_register_class());
    }

    #[test]
    fn test_arg_class_needs_xmm() {
        assert!(X86ArgClass::SSE.needs_xmm());
        assert!(X86ArgClass::SSEUp.needs_xmm());
        assert!(!X86ArgClass::Integer.needs_xmm());
        assert!(!X86ArgClass::NoClass.needs_xmm());
    }

    // ==========================================================================
    // X86CallingConvention method tests
    // ==========================================================================

    #[test]
    fn test_cc_name() {
        assert_eq!(X86CallingConvention::C.name(), "cdecl");
        assert_eq!(X86CallingConvention::Fast.name(), "fastcall");
        assert_eq!(X86CallingConvention::StdCall.name(), "stdcall");
        assert_eq!(X86CallingConvention::ThisCall.name(), "thiscall");
        assert_eq!(X86CallingConvention::VectorCall.name(), "vectorcall");
        assert_eq!(X86CallingConvention::X86_64_SysV.name(), "System V AMD64");
        assert_eq!(X86CallingConvention::Win64.name(), "Microsoft x64");
        assert_eq!(X86CallingConvention::X86_RegCall.name(), "regcall");
        assert_eq!(X86CallingConvention::PreserveAll.name(), "preserve_all");
        assert_eq!(X86CallingConvention::PreserveMost.name(), "preserve_most");
        assert_eq!(X86CallingConvention::GHC.name(), "GHC");
        assert_eq!(X86CallingConvention::AnyReg.name(), "anyreg");
    }

    #[test]
    fn test_cc_is_64bit() {
        assert!(X86CallingConvention::X86_64_SysV.is_64bit());
        assert!(X86CallingConvention::Win64.is_64bit());
        assert!(X86CallingConvention::X86_RegCall.is_64bit());
        assert!(!X86CallingConvention::C.is_64bit());
        assert!(!X86CallingConvention::Fast.is_64bit());
        assert!(!X86CallingConvention::StdCall.is_64bit());
        assert!(!X86CallingConvention::ThisCall.is_64bit());
    }

    #[test]
    fn test_cc_callee_cleans_stack() {
        assert!(!X86CallingConvention::C.callee_cleans_stack());
        assert!(X86CallingConvention::StdCall.callee_cleans_stack());
        assert!(X86CallingConvention::ThisCall.callee_cleans_stack());
        assert!(X86CallingConvention::Fast.callee_cleans_stack());
        assert!(!X86CallingConvention::X86_64_SysV.callee_cleans_stack());
    }

    #[test]
    fn test_cc_num_int_param_regs() {
        assert_eq!(X86CallingConvention::C.get_num_int_param_regs(), 0);
        assert_eq!(X86CallingConvention::Fast.get_num_int_param_regs(), 2);
        assert_eq!(X86CallingConvention::ThisCall.get_num_int_param_regs(), 1);
        assert_eq!(
            X86CallingConvention::X86_64_SysV.get_num_int_param_regs(),
            6
        );
        assert_eq!(X86CallingConvention::Win64.get_num_int_param_regs(), 4);
        assert_eq!(
            X86CallingConvention::X86_RegCall.get_num_int_param_regs(),
            5
        );
    }

    #[test]
    fn test_cc_num_sse_param_regs() {
        assert_eq!(X86CallingConvention::C.get_num_sse_param_regs(), 0);
        assert_eq!(X86CallingConvention::VectorCall.get_num_sse_param_regs(), 6);
        assert_eq!(
            X86CallingConvention::X86_64_SysV.get_num_sse_param_regs(),
            8
        );
        assert_eq!(X86CallingConvention::Win64.get_num_sse_param_regs(), 4);
    }

    #[test]
    fn test_cc_get_int_param_regs_sysv() {
        let regs = X86CallingConvention::X86_64_SysV.get_int_param_regs();
        assert_eq!(regs, vec![RDI, RSI, RDX, RCX, R8, R9]);
    }

    #[test]
    fn test_cc_get_int_param_regs_win64() {
        let regs = X86CallingConvention::Win64.get_int_param_regs();
        assert_eq!(regs, vec![RCX, RDX, R8, R9]);
    }

    #[test]
    fn test_cc_get_sse_param_regs_sysv() {
        let regs = X86CallingConvention::X86_64_SysV.get_sse_param_regs();
        assert_eq!(regs, vec![XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6, XMM7]);
    }

    #[test]
    fn test_cc_get_stack_alignment() {
        assert_eq!(X86CallingConvention::X86_64_SysV.get_stack_alignment(), 16);
        assert_eq!(X86CallingConvention::Win64.get_stack_alignment(), 16);
        assert_eq!(X86CallingConvention::C.get_stack_alignment(), 4);
    }

    #[test]
    fn test_cc_get_shadow_store_size() {
        assert_eq!(X86CallingConvention::Win64.get_shadow_store_size(), 32);
        assert_eq!(X86CallingConvention::X86_64_SysV.get_shadow_store_size(), 0);
        assert_eq!(X86CallingConvention::C.get_shadow_store_size(), 0);
    }

    #[test]
    fn test_cc_uses_register_params() {
        assert!(!X86CallingConvention::C.uses_register_params());
        assert!(X86CallingConvention::Fast.uses_register_params());
        assert!(!X86CallingConvention::StdCall.uses_register_params());
        assert!(X86CallingConvention::ThisCall.uses_register_params());
        assert!(X86CallingConvention::X86_64_SysV.uses_register_params());
        assert!(X86CallingConvention::Win64.uses_register_params());
    }

    // ==========================================================================
    // Type size/alignment computation tests
    // ==========================================================================

    #[test]
    fn test_type_size_primitives() {
        let map = make_type_map();

        assert_eq!(type_size(&Type::void(), &map), 0);
        assert_eq!(type_size(&Type::i1(), &map), 1);
        assert_eq!(type_size(&Type::i8(), &map), 1);
        assert_eq!(type_size(&Type::i16(), &map), 2);
        assert_eq!(type_size(&Type::i32(), &map), 4);
        assert_eq!(type_size(&Type::i64(), &map), 8);
        assert_eq!(type_size(&Type::i128(), &map), 16);
        assert_eq!(type_size(&Type::float(), &map), 4);
        assert_eq!(type_size(&Type::double(), &map), 8);
        assert_eq!(type_size(&Type::half(), &map), 2);
        assert_eq!(type_size(&Type::fp128(), &map), 16);
        assert_eq!(type_size(&Type::x86_fp80(), &map), 16);
        assert_eq!(type_size(&Type::pointer(0), &map), 8);
        assert_eq!(type_size(&Type::x86_mmx(), &map), 8);
    }

    #[test]
    fn test_type_alignment_primitives() {
        let map = make_type_map();

        assert_eq!(type_alignment(&Type::i8(), &map), 1);
        assert_eq!(type_alignment(&Type::i16(), &map), 2);
        assert_eq!(type_alignment(&Type::i32(), &map), 4);
        assert_eq!(type_alignment(&Type::i64(), &map), 8);
        assert_eq!(type_alignment(&Type::i128(), &map), 16);
        assert_eq!(type_alignment(&Type::float(), &map), 4);
        assert_eq!(type_alignment(&Type::double(), &map), 8);
        assert_eq!(type_alignment(&Type::fp128(), &map), 16);
        assert_eq!(type_alignment(&Type::pointer(0), &map), 8);
    }

    #[test]
    fn test_type_size_array() {
        let mut store = TypeStore::new();
        let mut map = make_type_map();

        let i32_id = map
            .iter()
            .find(|(_, ty)| matches!(ty.kind, TypeKind::Integer { bits: 32 }))
            .map(|(id, _)| *id)
            .unwrap();

        let arr_ty = Type::array_with(10, i32_id);
        let arr_id = register_type(arr_ty, &mut store, &mut map);

        let arr = resolve_type(arr_id, &map);
        assert_eq!(type_size(&arr, &map), 40);
    }

    #[test]
    fn test_type_size_struct() {
        let mut store = TypeStore::new();
        let mut map = make_type_map();

        let i32_id = map
            .iter()
            .find(|(_, ty)| matches!(ty.kind, TypeKind::Integer { bits: 32 }))
            .map(|(id, _)| *id)
            .unwrap();
        let i64_id = map
            .iter()
            .find(|(_, ty)| matches!(ty.kind, TypeKind::Integer { bits: 64 }))
            .map(|(id, _)| *id)
            .unwrap();

        // struct { i32, i64 } — i32 at offset 0, i64 at offset 8 (aligned), total 16
        let struct_ty = Type::struct_literal_with(false, vec![i32_id, i64_id]);
        let struct_id = register_type(struct_ty, &mut store, &mut map);
        let s = resolve_type(struct_id, &map);
        assert_eq!(type_size(&s, &map), 16);

        // Packed struct { i32, i64 } — total 12
        let packed_ty = Type::struct_literal_with(true, vec![i32_id, i64_id]);
        let packed_id = register_type(packed_ty, &mut store, &mut map);
        let ps = resolve_type(packed_id, &map);
        assert_eq!(type_size(&ps, &map), 12);
    }

    #[test]
    fn test_type_size_vector() {
        let mut store = TypeStore::new();
        let mut map = make_type_map();

        let f32_id = map
            .iter()
            .find(|(_, ty)| matches!(ty.kind, TypeKind::Float))
            .map(|(id, _)| *id)
            .unwrap();

        // <4 x float> = 16 bytes
        let vec_ty = Type::fixed_vector_with(4, f32_id);
        let vec_id = register_type(vec_ty, &mut store, &mut map);
        let v = resolve_type(vec_id, &map);
        assert_eq!(type_size(&v, &map), 16);
        assert_eq!(type_alignment(&v, &map), 16);
    }

    // ==========================================================================
    // System V AMD64 ABI classification tests
    // ==========================================================================

    #[test]
    fn test_sysv_classify_integer_primitives() {
        let map = make_type_map();

        let classes = classify_arg_type(&Type::i32(), 0, &map);
        assert_eq!(classes, vec![X86ArgClass::Integer]);

        let classes = classify_arg_type(&Type::i64(), 0, &map);
        assert_eq!(classes, vec![X86ArgClass::Integer]);

        let classes = classify_arg_type(&Type::i128(), 0, &map);
        assert_eq!(classes.len(), 2);
        assert_eq!(classes[0], X86ArgClass::Integer);
        assert_eq!(classes[1], X86ArgClass::Integer);
    }

    #[test]
    fn test_sysv_classify_pointer() {
        let map = make_type_map();
        let classes = classify_arg_type(&Type::pointer(0), 0, &map);
        assert_eq!(classes, vec![X86ArgClass::Integer]);
    }

    #[test]
    fn test_sysv_classify_sse_primitives() {
        let map = make_type_map();

        assert_eq!(
            classify_arg_type(&Type::float(), 0, &map),
            vec![X86ArgClass::SSE]
        );
        assert_eq!(
            classify_arg_type(&Type::double(), 0, &map),
            vec![X86ArgClass::SSE]
        );
    }

    #[test]
    fn test_sysv_classify_fp128() {
        let map = make_type_map();
        let classes = classify_arg_type(&Type::fp128(), 0, &map);
        assert_eq!(classes, vec![X86ArgClass::SSE, X86ArgClass::SSEUp]);
    }

    #[test]
    fn test_sysv_classify_x86_fp80() {
        let map = make_type_map();
        // Aligned to 0 mod 16 → X87
        let classes = classify_arg_type(&Type::x86_fp80(), 0, &map);
        assert_eq!(classes, vec![X86ArgClass::X87]);

        // Not aligned to 0 mod 16 → Memory
        let classes = classify_arg_type(&Type::x86_fp80(), 8, &map);
        assert_eq!(classes, vec![X86ArgClass::Memory]);
    }

    #[test]
    fn test_sysv_classify_simple_struct() {
        let mut store = TypeStore::new();
        let mut map = make_type_map();

        let i32_id = map
            .iter()
            .find(|(_, ty)| matches!(ty.kind, TypeKind::Integer { bits: 32 }))
            .map(|(id, _)| *id)
            .unwrap();
        let i32_id_2 = i32_id; // Same type, reused

        // struct { i32, i32 } — 8 bytes, two ints → one eightbyte, INTEGER
        let struct_ty = Type::struct_literal_with(false, vec![i32_id, i32_id_2]);
        let struct_id = register_type(struct_ty, &mut store, &mut map);
        let s = resolve_type(struct_id, &map);
        let classes = classify_aggregate_type(&s, &map);
        assert_eq!(classes.len(), 1);
        assert_eq!(classes[0], X86ArgClass::Integer);
    }

    #[test]
    fn test_sysv_classify_struct_with_float() {
        let mut store = TypeStore::new();
        let mut map = make_type_map();

        let f32_id = map
            .iter()
            .find(|(_, ty)| matches!(ty.kind, TypeKind::Float))
            .map(|(id, _)| *id)
            .unwrap();

        // struct { float, float } — 8 bytes → one eightbyte SSE
        let struct_ty = Type::struct_literal_with(false, vec![f32_id, f32_id]);
        let struct_id = register_type(struct_ty, &mut store, &mut map);
        let s = resolve_type(struct_id, &map);
        let classes = classify_aggregate_type(&s, &map);
        assert_eq!(classes.len(), 1);
        assert_eq!(classes[0], X86ArgClass::SSE);
    }

    #[test]
    fn test_sysv_classify_large_struct() {
        let mut store = TypeStore::new();
        let mut map = make_type_map();

        let i64_id = map
            .iter()
            .find(|(_, ty)| matches!(ty.kind, TypeKind::Integer { bits: 64 }))
            .map(|(id, _)| *id)
            .unwrap();

        // struct { i64, i64, i64, i64 } — 32 bytes, > 2 eightbytes → MEMORY
        let struct_ty = Type::struct_literal_with(false, vec![i64_id, i64_id, i64_id, i64_id]);
        let struct_id = register_type(struct_ty, &mut store, &mut map);
        let s = resolve_type(struct_id, &map);
        let classes = classify_aggregate_type(&s, &map);
        // > 2 eightbytes, not all SSE → Memory
        assert!(classes.iter().all(|c| *c == X86ArgClass::Memory));
    }

    #[test]
    fn test_sysv_classify_mixed_struct_sse_int() {
        let mut store = TypeStore::new();
        let mut map = make_type_map();

        let f64_id = map
            .iter()
            .find(|(_, ty)| matches!(ty.kind, TypeKind::Double))
            .map(|(id, _)| *id)
            .unwrap();
        let i64_id = map
            .iter()
            .find(|(_, ty)| matches!(ty.kind, TypeKind::Integer { bits: 64 }))
            .map(|(id, _)| *id)
            .unwrap();

        // struct { double, i64 } — 16 bytes, SSE + Integer → mixed → Memory
        let struct_ty = Type::struct_literal_with(false, vec![f64_id, i64_id]);
        let struct_id = register_type(struct_ty, &mut store, &mut map);
        let s = resolve_type(struct_id, &map);
        let classes = classify_aggregate_type(&s, &map);
        // SSE + Integer = SSE (SSE wins), but Integer in second → check cleanup
        // Post-merger: SSE in first, Integer in second → not SSE+SSEUp → Memory
        assert!(classes.iter().any(|c| *c == X86ArgClass::Memory));
    }

    // ==========================================================================
    // System V AMD64 argument assignment tests
    // ==========================================================================

    #[test]
    fn test_sysv_assign_reg_args() {
        let map = make_type_map();
        let args = vec![Type::i32(), Type::i64(), Type::float(), Type::double()];
        let (infos, _frame) = X86CallingConvention::X86_64_SysV.assign_args(&args, &map);

        // i32 → RDI
        assert!(infos[0].in_reg);
        assert_eq!(infos[0].regs, vec![RDI]);

        // i64 → RSI
        assert!(infos[1].in_reg);
        assert_eq!(infos[1].regs, vec![RSI]);

        // float → XMM0
        assert!(infos[2].in_reg);
        assert_eq!(infos[2].regs, vec![XMM0]);

        // double → XMM1
        assert!(infos[3].in_reg);
        assert_eq!(infos[3].regs, vec![XMM1]);
    }

    #[test]
    fn test_sysv_assign_stack_args_when_regs_exhausted() {
        let map = make_type_map();
        // 8 integer args: should exhaust RDI,RSI,RDX,RCX,R8,R9; 7th and 8th on stack
        let args = vec![
            Type::i64(),
            Type::i64(),
            Type::i64(),
            Type::i64(),
            Type::i64(),
            Type::i64(),
            Type::i64(),
            Type::i64(),
        ];
        let (infos, _frame) = X86CallingConvention::X86_64_SysV.assign_args(&args, &map);

        // First 6 in registers
        for i in 0..6 {
            assert!(infos[i].in_reg, "arg {} should be in reg", i);
        }
        // Last 2 on stack
        assert!(!infos[6].in_reg);
        assert!(!infos[7].in_reg);
        assert!(infos[6].stack_offset > 0);
        assert!(infos[7].stack_offset > infos[6].stack_offset);
    }

    #[test]
    fn test_sysv_return_regs_integer() {
        let map = make_type_map();
        let regs = X86CallingConvention::X86_64_SysV.get_return_regs(&Type::i64(), &map);
        assert_eq!(regs, vec![RAX]);

        let regs = X86CallingConvention::X86_64_SysV.get_return_regs(&Type::i128(), &map);
        assert_eq!(regs, vec![RAX, RDX]);
    }

    #[test]
    fn test_sysv_return_regs_sse() {
        let map = make_type_map();
        let regs = X86CallingConvention::X86_64_SysV.get_return_regs(&Type::float(), &map);
        assert_eq!(regs, vec![XMM0]);

        let regs = X86CallingConvention::X86_64_SysV.get_return_regs(&Type::double(), &map);
        assert_eq!(regs, vec![XMM0]);
    }

    #[test]
    fn test_sysv_return_regs_fp128() {
        let map = make_type_map();
        let regs = X86CallingConvention::X86_64_SysV.get_return_regs(&Type::fp128(), &map);
        assert_eq!(regs, vec![XMM0, XMM1]);
    }

    // ==========================================================================
    // Microsoft x64 ABI tests
    // ==========================================================================

    #[test]
    fn test_win64_assign_reg_args() {
        let map = make_type_map();
        let args = vec![Type::i32(), Type::i64(), Type::float(), Type::double()];
        let (infos, frame) = X86CallingConvention::Win64.assign_args(&args, &map);

        // i32 → RCX
        assert!(infos[0].in_reg);
        assert_eq!(infos[0].regs, vec![RCX]);

        // i64 → RDX
        assert!(infos[1].in_reg);
        assert_eq!(infos[1].regs, vec![RDX]);

        // float → XMM2 (integer slot 2 already used)
        assert!(infos[2].in_reg);
        assert_eq!(infos[2].regs, vec![XMM2]);

        // double → XMM3
        assert!(infos[3].in_reg);
        assert_eq!(infos[3].regs, vec![XMM3]);

        // Win64 has shadow space
        assert_eq!(frame.shadow_store_size, 32);
    }

    #[test]
    fn test_win64_shadow_store() {
        let map = make_type_map();
        let args = vec![Type::i32()];
        let (_infos, frame) = X86CallingConvention::Win64.assign_args(&args, &map);
        assert_eq!(frame.shadow_store_size, 32);
        assert!(frame.stack_size >= 32 + 8); // Shadow + return address + args
    }

    #[test]
    fn test_win64_return_regs() {
        let map = make_type_map();

        let regs = X86CallingConvention::Win64.get_return_regs(&Type::i64(), &map);
        assert_eq!(regs, vec![RAX]);

        let regs = X86CallingConvention::Win64.get_return_regs(&Type::float(), &map);
        assert_eq!(regs, vec![XMM0]);

        let regs = X86CallingConvention::Win64.get_return_regs(&Type::double(), &map);
        assert_eq!(regs, vec![XMM0]);
    }

    // ==========================================================================
    // 32-bit calling convention tests
    // ==========================================================================

    #[test]
    fn test_cdecl_all_stack() {
        let map = make_type_map();
        let args = vec![Type::i32(), Type::i32(), Type::i32()];
        let (infos, _frame) = X86CallingConvention::C.assign_args(&args, &map);

        for info in &infos {
            assert!(!info.in_reg);
            assert!(info.stack_offset > 0);
        }
    }

    #[test]
    fn test_fastcall_reg_args() {
        let map = make_type_map();
        let args = vec![Type::i32(), Type::i32(), Type::i32(), Type::i32()];
        let (infos, _frame) = X86CallingConvention::Fast.assign_args(&args, &map);

        // First two in ECX, EDX
        assert!(infos[0].in_reg);
        assert_eq!(infos[0].regs, vec![ECX]);
        assert!(infos[1].in_reg);
        assert_eq!(infos[1].regs, vec![EDX]);

        // Rest on stack
        assert!(!infos[2].in_reg);
        assert!(!infos[3].in_reg);
    }

    #[test]
    fn test_thiscall_ecx_first() {
        let map = make_type_map();
        let args = vec![Type::pointer(0), Type::i32()];
        let (infos, _frame) = X86CallingConvention::ThisCall.assign_args(&args, &map);

        // First arg (this) in ECX
        assert!(infos[0].in_reg);
        assert_eq!(infos[0].regs, vec![ECX]);

        // Second arg on stack
        assert!(!infos[1].in_reg);
    }

    #[test]
    fn test_vectorcall_simd_regs() {
        let mut store = TypeStore::new();
        let mut map = make_type_map();

        let f32_id = map
            .iter()
            .find(|(_, ty)| matches!(ty.kind, TypeKind::Float))
            .map(|(id, _)| *id)
            .unwrap();

        let vec_ty = Type::fixed_vector_with(4, f32_id);
        let vec_id = register_type(vec_ty, &mut store, &mut map);
        let vec = resolve_type(vec_id, &map);

        let args = vec![vec.clone(), vec.clone(), vec.clone()];
        let (infos, _frame) = X86CallingConvention::VectorCall.assign_args(&args, &map);

        // First three vectors in XMM0, XMM1, XMM2
        assert!(infos[0].in_reg);
        assert_eq!(infos[0].regs, vec![XMM0]);
        assert!(infos[1].in_reg);
        assert_eq!(infos[1].regs, vec![XMM1]);
        assert!(infos[2].in_reg);
        assert_eq!(infos[2].regs, vec![XMM2]);
    }

    #[test]
    fn test_32bit_return_regs() {
        let map = make_type_map();

        let regs = cdecl_return_regs(&Type::i32(), &map);
        assert_eq!(regs, vec![EAX]);

        let regs = cdecl_return_regs(&Type::i64(), &map);
        assert_eq!(regs, vec![EDX, EAX]);

        let regs = cdecl_return_regs(&Type::float(), &map);
        assert_eq!(regs, vec![XMM0]);

        let regs = cdecl_return_regs(&Type::x86_fp80(), &map);
        assert_eq!(regs, vec![ST0]);
    }

    // ==========================================================================
    // X86ArgInfo and X86CallFrame tests
    // ==========================================================================

    #[test]
    fn test_arg_info_default() {
        let info = X86ArgInfo::default();
        assert!(!info.in_reg);
        assert!(info.regs.is_empty());
        assert_eq!(info.stack_offset, 0);
        assert_eq!(info.size, 0);
        assert_eq!(info.alignment, 1);
        assert!(!info.is_byval);
        assert!(!info.is_sret);
        assert_eq!(info.padding, 0);
    }

    #[test]
    fn test_call_frame_default() {
        let frame = X86CallFrame::default();
        assert_eq!(frame.stack_size, 0);
        assert!(frame.arg_offsets.is_empty());
        assert!(frame.return_save_area.is_none());
        assert_eq!(frame.shadow_store_size, 0);
        assert_eq!(frame.alignment_padding, 0);
    }

    // ==========================================================================
    // Merge classes ​tests
    // ==========================================================================

    #[test]
    fn test_merge_classes_basic() {
        use X86ArgClass::*;

        // NoClass + anything = anything
        assert_eq!(merge_classes(NoClass, Integer), Integer);
        assert_eq!(merge_classes(Integer, NoClass), Integer);

        // Integer + Integer = Integer
        assert_eq!(merge_classes(Integer, Integer), Integer);

        // SSE + SSE = SSE
        assert_eq!(merge_classes(SSE, SSE), SSE);

        // SSE + SSEUp = SSE
        assert_eq!(merge_classes(SSE, SSEUp), SSE);
        assert_eq!(merge_classes(SSEUp, SSE), SSE);

        // Integer + SSE = SSE (SSE wins)
        assert_eq!(merge_classes(Integer, SSE), SSE);
        assert_eq!(merge_classes(SSE, Integer), SSE);

        // Anything + Memory = Memory
        assert_eq!(merge_classes(Integer, Memory), Memory);
        assert_eq!(merge_classes(SSE, Memory), Memory);
        assert_eq!(merge_classes(Memory, NoClass), Memory);
    }

    // ==========================================================================
    // Post-merger cleanup tests
    // ==========================================================================

    #[test]
    fn test_post_merger_cleanup_two_eightbytes_valid_sse() {
        let mut classes = vec![X86ArgClass::SSE, X86ArgClass::SSEUp];
        post_merger_cleanup(&mut classes, 16);
        assert_eq!(classes, vec![X86ArgClass::SSE, X86ArgClass::SSEUp]);
    }

    #[test]
    fn test_post_merger_cleanup_two_eightbytes_mixed() {
        // SSE + Integer → Memory (not valid SSE pair)
        let mut classes = vec![X86ArgClass::SSE, X86ArgClass::Integer];
        post_merger_cleanup(&mut classes, 16);
        assert!(classes.iter().all(|c| *c == X86ArgClass::Memory));
    }

    #[test]
    fn test_post_merger_cleanup_more_than_two_not_all_sse() {
        let mut classes = vec![
            X86ArgClass::Integer,
            X86ArgClass::Integer,
            X86ArgClass::Integer,
        ];
        post_merger_cleanup(&mut classes, 24);
        assert!(classes.iter().all(|c| *c == X86ArgClass::Memory));
    }

    #[test]
    fn test_post_merger_cleanup_empty() {
        let mut classes: Vec<X86ArgClass> = vec![];
        post_merger_cleanup(&mut classes, 0);
        assert!(classes.is_empty());
    }

    // ==========================================================================
    // Needs hidden sret tests
    // ==========================================================================

    #[test]
    fn test_sysv_needs_hidden_sret() {
        let mut store = TypeStore::new();
        let mut map = make_type_map();

        let i64_id = map
            .iter()
            .find(|(_, ty)| matches!(ty.kind, TypeKind::Integer { bits: 64 }))
            .map(|(id, _)| *id)
            .unwrap();

        // struct { i64 } — 8 bytes, single INTEGER eightbyte → no sret
        let small_struct = Type::struct_literal_with(false, vec![i64_id]);
        let small_id = register_type(small_struct, &mut store, &mut map);
        let small = resolve_type(small_id, &map);
        assert!(!X86CallingConvention::X86_64_SysV.needs_hidden_sret(&small, &map));

        // struct { i64, i64, i64 } — 24 bytes → sret
        let large_struct = Type::struct_literal_with(false, vec![i64_id, i64_id, i64_id]);
        let large_id = register_type(large_struct, &mut store, &mut map);
        let large = resolve_type(large_id, &map);
        assert!(X86CallingConvention::X86_64_SysV.needs_hidden_sret(&large, &map));
    }

    #[test]
    fn test_win64_needs_hidden_sret() {
        let mut store = TypeStore::new();
        let mut map = make_type_map();

        let i64_id = map
            .iter()
            .find(|(_, ty)| matches!(ty.kind, TypeKind::Integer { bits: 64 }))
            .map(|(id, _)| *id)
            .unwrap();

        // struct { i64 } — 8 bytes → fits in RAX, no sret
        let small_struct = Type::struct_literal_with(false, vec![i64_id]);
        let small_id = register_type(small_struct, &mut store, &mut map);
        let small = resolve_type(small_id, &map);
        assert!(!X86CallingConvention::Win64.needs_hidden_sret(&small, &map));

        // struct { i64, i64 } — 16 bytes → > 8 → sret
        let medium_struct = Type::struct_literal_with(false, vec![i64_id, i64_id]);
        let medium_id = register_type(medium_struct, &mut store, &mut map);
        let medium = resolve_type(medium_id, &map);
        assert!(X86CallingConvention::Win64.needs_hidden_sret(&medium, &map));
    }

    // ==========================================================================
    // Assign_args integration tests for all conventions
    // ==========================================================================

    #[test]
    fn test_stdcall_assign_all_stack() {
        let map = make_type_map();
        let args = vec![Type::i32(), Type::i32(), Type::i32()];
        let (infos, _frame) = X86CallingConvention::StdCall.assign_args(&args, &map);

        // Stdcall: all on stack (same as cdecl for arg placement)
        for info in &infos {
            assert!(!info.in_reg);
            assert!(info.stack_offset > 0);
        }
    }

    #[test]
    fn test_preserve_all_assign() {
        let map = make_type_map();
        let args = vec![Type::i32(), Type::i64()];
        let (_infos, _frame) = X86CallingConvention::PreserveAll.assign_args(&args, &map);
        // Should complete without panicking
    }
}