llvm-native-core 0.1.15

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
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
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
//! Clang IR Generation Testing — X86 Targets
//!
//! Comprehensive IR generation testing module for Clang on X86, verifying
//! correct LLVM IR output for all C/C++ language features. This module
//! validates that the compiler produces well-formed, standards-conformant
//! LLVM IR across every IR construct.
//!
//! Clean-room behavioral reconstruction from:
//! - LLVM Language Reference Manual
//! - Clang/LLVM test suite conventions (FileCheck-style verification)
//! - Intel® 64 and IA-32 Architectures Software Developer's Manual
//! - ISO/IEC 9899:2011/2018 (C11/C17) and ISO/IEC 14882:2017 (C++17)
//! - System V AMD64 ABI Supplement
//! - Itanium C++ ABI
//!
//! Coverage:
//! - **Types**: void, i1, i8, i16, i32, i64, half, float, double, fp128,
//!   x86_fp80, pointer, array, struct, vector
//! - **Constant expressions**: int, float, null, aggregate, GEP, bitcast,
//!   inttoptr, ptrtoint
//! - **Instructions**: alloca, load, store, getelementptr, add, sub, mul,
//!   sdiv, udiv, srem, urem, shl, lshr, ashr, and, or, xor, icmp (all
//!   predicates), fcmp (all predicates), select, call, ret, br, switch,
//!   phi, extractvalue, insertvalue, extractelement, insertelement,
//!   shufflevector
//! - **Memory**: aligned/unaligned load/store, volatile, ordered atomics, fence
//! - **Function attributes**: nounwind, readonly, readnone, noinline,
//!   alwaysinline, optsize, minsize, ssp, uwtable, sanitize_*
//! - **Parameter attributes**: zeroext, signext, noalias, sret, byval,
//!   inreg, nest, align, dereferenceable
//! - **Linkage types**: private, internal, available_externally, linkonce,
//!   weak, common, appending, extern_weak, linkonce_odr, weak_odr, external
//! - **Visibility**: default, hidden, protected
//! - **Calling conventions**: ccc, fastcc, coldcc, x86_stdcallcc,
//!   x86_fastcallcc, x86_thiscallcc, x86_vectorcallcc, x86_regcallcc
//! - **C patterns**: global vars, static locals, array-to-pointer decay,
//!   function-to-pointer decay, implicit casts, compound literals,
//!   designated initializers, VLAs, flexible array members
//! - **C++ patterns**: vtables, RTTI, exception handling, ctors/dtors,
//!   member pointers, lambda lowering, template instantiation
//! - **X86 patterns**: vector types, intrinsics, inline assembly,
//!   target-specific attributes
//!
//! Integration points:
//! - `crate::clang::codegen::*` — Clang IR lowering
//! - `crate::clang::*` — Clang frontend types
//! - `crate::x86::*` — X86 target backend

use crate::clang::clang_x86_pipeline::{
    compile_to_x86_assembly, compile_to_x86_ir, compile_with_options, PipelineResult,
    X86CompileOptions, X86IRGenerator, X86OptLevel, X86Pipeline,
};
use crate::clang::{
    compile_c, compile_c_string, CLangStandard, ClangCodeGen, ClangDriver, ClangOptions,
    ClangTargetInfo,
};
use crate::x86::{
    x86_calling_convention::{X86ArgClass, X86CallFrame, X86CallingConvention},
    x86_frame_lowering::{CallConv, X86FrameLowering},
    x86_instr_info::{X86InstrInfo, X86Opcode},
    x86_register_info::{X86RegisterInfo, X86_32_REG_COUNT, X86_64_REG_COUNT},
    x86_subtarget::X86Subtarget,
    x86_target_machine::X86TargetMachine,
};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};

// ── X86 IR Generation Test — Main Structure ──────────────────────────────────

/// Main IR generation testing harness for X86 Clang.
///
/// Provides infrastructure to compile C/C++ source snippets via Clang,
/// capture the emitted LLVM IR, and verify that the IR contains (or
/// does not contain) specific patterns, instructions, types, and
/// attributes expected for the language construct under test.
#[derive(Debug, Clone)]
pub struct X86IRGenTest {
    /// The test case name.
    pub name: String,
    /// Category of this test (type test, instruction test, ABI test, etc.).
    pub category: X86IRGenCategory,
    /// The C/C++ source code to compile.
    pub source: String,
    /// Target triple for compilation.
    pub target_triple: String,
    /// Compiler flags to pass.
    pub flags: Vec<String>,
    /// Optimization level (default: O0 for predictable IR).
    pub opt_level: X86OptLevel,
    /// List of patterns that must appear in the generated IR.
    pub required_ir: Vec<X86IRPattern>,
    /// List of patterns that must NOT appear in the generated IR.
    pub forbidden_ir: Vec<X86IRPattern>,
    /// Whether this test expects compilation to succeed.
    pub should_compile: bool,
    /// Whether this is expected to fail (xfail).
    pub is_xfail: bool,
    /// Reason for xfail, if applicable.
    pub xfail_reason: Option<String>,
    /// Expected return value if run.
    pub expected_return: Option<i32>,
}

/// Category of an X86 IR generation test.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum X86IRGenCategory {
    /// Tests for type system lowering.
    Types,
    /// Tests for constant expression patterns.
    Constants,
    /// Tests for individual LLVM instructions.
    Instructions,
    /// Tests for arithmetic operations.
    Arithmetic,
    /// Tests for memory access patterns.
    MemoryAccess,
    /// Tests for control flow constructs.
    ControlFlow,
    /// Tests for function attributes and metadata.
    FunctionAttributes,
    /// Tests for parameter attributes.
    ParameterAttributes,
    /// Tests for linkage types.
    Linkage,
    /// Tests for symbol visibility.
    Visibility,
    /// Tests for calling conventions.
    CallingConvention,
    /// C-specific language patterns.
    CLanguage,
    /// C++-specific language patterns.
    CPlusPlus,
    /// X86 target-specific patterns.
    X86Specific,
    /// Tests for vector operations.
    Vectors,
    /// Tests for inline assembly integration.
    InlineAsm,
    /// Tests for exception handling IR.
    ExceptionHandling,
    /// Tests for atomic operations and memory ordering.
    Atomics,
    /// General integration tests.
    Integration,
    /// Tests for debug info.
    DebugInfo,
    /// Tests for optimization passes.
    Optimization,
    /// Stress / fuzz tests.
    Stress,
}

impl X86IRGenCategory {
    /// Human-readable category name.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Types => "types",
            Self::Constants => "constants",
            Self::Instructions => "instructions",
            Self::Arithmetic => "arithmetic",
            Self::MemoryAccess => "memory",
            Self::ControlFlow => "control_flow",
            Self::FunctionAttributes => "fn_attrs",
            Self::ParameterAttributes => "param_attrs",
            Self::Linkage => "linkage",
            Self::Visibility => "visibility",
            Self::CallingConvention => "calling_conv",
            Self::CLanguage => "c_lang",
            Self::CPlusPlus => "cxx",
            Self::X86Specific => "x86",
            Self::Vectors => "vectors",
            Self::InlineAsm => "inline_asm",
            Self::ExceptionHandling => "eh",
            Self::Atomics => "atomics",
            Self::Integration => "integration",
            Self::DebugInfo => "debug_info",
            Self::Optimization => "optimization",
            Self::Stress => "stress",
        }
    }
}

/// An IR pattern to match against generated LLVM IR.
#[derive(Debug, Clone)]
pub struct X86IRPattern {
    /// Human-readable description of what this pattern checks.
    pub description: String,
    /// The regex or substring to search for in the IR.
    pub pattern: String,
    /// Minimum number of occurrences expected.
    pub min_count: usize,
    /// Exact required count (overrides min_count when set).
    pub exact_count: Option<usize>,
    /// Whether matching is case-sensitive.
    pub case_sensitive: bool,
    /// Sub-category for grouping.
    pub sub_category: String,
}

impl X86IRPattern {
    /// Create a required pattern that must appear at least once.
    pub fn required(desc: &str, pat: &str) -> Self {
        Self {
            description: desc.to_string(),
            pattern: pat.to_string(),
            min_count: 1,
            exact_count: None,
            case_sensitive: false,
            sub_category: String::new(),
        }
    }

    /// Create a pattern that must appear an exact number of times.
    pub fn exact(desc: &str, pat: &str, count: usize) -> Self {
        Self {
            description: desc.to_string(),
            pattern: pat.to_string(),
            min_count: 0,
            exact_count: Some(count),
            case_sensitive: false,
            sub_category: String::new(),
        }
    }

    /// Create a pattern that must appear at least N times.
    pub fn at_least(desc: &str, pat: &str, n: usize) -> Self {
        Self {
            description: desc.to_string(),
            pattern: pat.to_string(),
            min_count: n,
            exact_count: None,
            case_sensitive: false,
            sub_category: String::new(),
        }
    }

    /// Create a forbidden pattern (set min_count=0, exact_count=0).
    pub fn forbidden(desc: &str, pat: &str) -> Self {
        Self {
            description: desc.to_string(),
            pattern: pat.to_string(),
            min_count: 0,
            exact_count: Some(0),
            case_sensitive: false,
            sub_category: String::new(),
        }
    }

    /// Count occurrences in a given body of text.
    pub fn count_in(&self, text: &str) -> usize {
        if self.case_sensitive {
            text.matches(&self.pattern).count()
        } else {
            text.to_lowercase()
                .matches(&self.pattern.to_lowercase())
                .count()
        }
    }

    /// Check whether this pattern is satisfied by a given text.
    pub fn check(&self, text: &str) -> bool {
        let count = self.count_in(text);
        if let Some(exact) = self.exact_count {
            count == exact
        } else {
            count >= self.min_count
        }
    }
}

impl X86IRGenTest {
    /// Create a new X86 IR generation test.
    pub fn new(name: &str, category: X86IRGenCategory, source: &str) -> Self {
        Self {
            name: name.to_string(),
            category,
            source: source.to_string(),
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            flags: Vec::new(),
            opt_level: X86OptLevel::O0,
            required_ir: Vec::new(),
            forbidden_ir: Vec::new(),
            should_compile: true,
            is_xfail: false,
            xfail_reason: None,
            expected_return: None,
        }
    }

    /// Builder-style: set target triple.
    pub fn with_target(mut self, triple: &str) -> Self {
        self.target_triple = triple.to_string();
        self
    }

    /// Builder-style: add compiler flags.
    pub fn with_flags(mut self, flags: Vec<&str>) -> Self {
        self.flags = flags.into_iter().map(String::from).collect();
        self
    }

    /// Builder-style: set optimization level.
    pub fn with_opt(mut self, level: X86OptLevel) -> Self {
        self.opt_level = level;
        self
    }

    /// Builder-style: require a pattern.
    pub fn require(mut self, desc: &str, pat: &str) -> Self {
        self.required_ir.push(X86IRPattern::required(desc, pat));
        self
    }

    /// Builder-style: require an exact count pattern.
    pub fn require_exact(mut self, desc: &str, pat: &str, count: usize) -> Self {
        self.required_ir.push(X86IRPattern::exact(desc, pat, count));
        self
    }

    /// Builder-style: require at least N occurrences.
    pub fn require_at_least(mut self, desc: &str, pat: &str, n: usize) -> Self {
        self.required_ir.push(X86IRPattern::at_least(desc, pat, n));
        self
    }

    /// Builder-style: forbid a pattern.
    pub fn forbid(mut self, desc: &str, pat: &str) -> Self {
        self.forbidden_ir.push(X86IRPattern::forbidden(desc, pat));
        self
    }

    /// Builder-style: mark as expected failure.
    pub fn xfail(mut self, reason: &str) -> Self {
        self.is_xfail = true;
        self.xfail_reason = Some(reason.to_string());
        self
    }

    /// Builder-style: set expected return value.
    pub fn with_expected_return(mut self, val: i32) -> Self {
        self.expected_return = Some(val);
        self
    }

    /// Builder-style: expect compilation failure.
    pub fn expect_compile_failure(mut self) -> Self {
        self.should_compile = false;
        self
    }
}

// ── Test Result Types ───────────────────────────────────────────────────────

/// Result of running a single X86IRGenTest.
#[derive(Debug, Clone)]
pub struct X86IRGenTestResult {
    /// Test name.
    pub name: String,
    /// Whether the test passed all checks.
    pub passed: bool,
    /// The generated LLVM IR text.
    pub ir_text: Option<String>,
    /// Results of individual pattern checks.
    pub check_results: Vec<X86IRCheckResult>,
    /// Whether compilation succeeded.
    pub compiled: bool,
    /// Compilation error message, if any.
    pub compile_error: Option<String>,
    /// Duration of the test in milliseconds.
    pub duration_ms: u64,
}

/// Result of a single pattern check.
#[derive(Debug, Clone)]
pub struct X86IRCheckResult {
    /// Human-readable description of the check.
    pub description: String,
    /// Whether the pattern was found as expected.
    pub passed: bool,
    /// Actual count found.
    pub count: usize,
    /// Expected minimum.
    pub min_count: usize,
    /// Exact expected (if any).
    pub exact_count: Option<usize>,
    /// Whether this was a forbidden pattern check.
    pub is_forbidden: bool,
}

impl X86IRGenTestResult {
    /// Create a result from a test and generated IR text.
    pub fn from_test(
        test: &X86IRGenTest,
        ir_text: &str,
        compiled: bool,
        compile_error: Option<&str>,
        duration_ms: u64,
    ) -> Self {
        let mut check_results = Vec::new();

        for pat in &test.required_ir {
            let count = pat.count_in(ir_text);
            let passed = pat.check(ir_text);
            check_results.push(X86IRCheckResult {
                description: pat.description.clone(),
                passed,
                count,
                min_count: pat.min_count,
                exact_count: pat.exact_count,
                is_forbidden: false,
            });
        }

        for pat in &test.forbidden_ir {
            let count = pat.count_in(ir_text);
            let passed = count == 0;
            check_results.push(X86IRCheckResult {
                description: format!("[FORBIDDEN] {}", pat.description),
                passed,
                count,
                min_count: 0,
                exact_count: Some(0),
                is_forbidden: true,
            });
        }

        let passed = check_results.iter().all(|r| r.passed);

        Self {
            name: test.name.clone(),
            passed,
            ir_text: Some(ir_text.to_string()),
            check_results,
            compiled,
            compile_error: compile_error.map(String::from),
            duration_ms,
        }
    }

    /// Create a compile-failure result.
    pub fn compile_failure(test: &X86IRGenTest, error: &str, duration_ms: u64) -> Self {
        Self {
            name: test.name.clone(),
            passed: !test.should_compile,
            ir_text: None,
            check_results: Vec::new(),
            compiled: false,
            compile_error: Some(error.to_string()),
            duration_ms,
        }
    }

    /// Human-readable single-line summary.
    pub fn summary(&self) -> String {
        let status = if self.passed { "PASS" } else { "FAIL" };
        let count = self.check_results.len();
        format!("{}{} ({} checks)", status, self.name, count)
    }

    /// Get failed check descriptions.
    pub fn failed_checks(&self) -> Vec<&str> {
        self.check_results
            .iter()
            .filter(|r| !r.passed)
            .map(|r| r.description.as_str())
            .collect()
    }

    /// Total failed count.
    pub fn failed_count(&self) -> usize {
        self.check_results.iter().filter(|r| !r.passed).count()
    }
}

// ── Test Suite ──────────────────────────────────────────────────────────────

/// A collection of X86IRGenTest cases.
#[derive(Debug, Clone)]
pub struct X86IRGenTestSuite {
    /// Suite name.
    pub name: String,
    /// Suite description.
    pub description: String,
    /// The test cases.
    pub tests: Vec<X86IRGenTest>,
}

impl X86IRGenTestSuite {
    /// Create a new test suite.
    pub fn new(name: &str, desc: &str) -> Self {
        Self {
            name: name.to_string(),
            description: desc.to_string(),
            tests: Vec::new(),
        }
    }

    /// Add a test case.
    pub fn add(&mut self, test: X86IRGenTest) {
        self.tests.push(test);
    }

    /// Add many test cases.
    pub fn add_many(&mut self, tests: Vec<X86IRGenTest>) {
        self.tests.extend(tests);
    }

    /// Number of tests in the suite.
    pub fn len(&self) -> usize {
        self.tests.len()
    }

    /// Whether the suite is empty.
    pub fn is_empty(&self) -> bool {
        self.tests.is_empty()
    }

    /// Filter tests by category.
    pub fn filter_by_category(&self, cat: X86IRGenCategory) -> Vec<&X86IRGenTest> {
        self.tests.iter().filter(|t| t.category == cat).collect()
    }

    /// Filter tests by a substring in the name.
    pub fn filter_by_name(&self, substr: &str) -> Vec<&X86IRGenTest> {
        self.tests
            .iter()
            .filter(|t| t.name.contains(substr))
            .collect()
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TYPE SYSTEM TESTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Additional type system diagnostic structures and helpers.
#[derive(Debug, Clone)]
pub struct TypeIRPattern {
    pub c_type: String,
    pub ir_type: String,
    pub category: String,
}

impl TypeIRPattern {
    pub fn new(c_type: &str, ir_type: &str, category: &str) -> Self {
        Self {
            c_type: c_type.to_string(),
            ir_type: ir_type.to_string(),
            category: category.to_string(),
        }
    }
}

/// Registry of all known C-to-IR type mappings for X86-64 LP64 ABI.
pub fn x86_type_map() -> Vec<TypeIRPattern> {
    vec![
        TypeIRPattern::new("void", "void", "scalar"),
        TypeIRPattern::new("_Bool", "i1", "scalar"),
        TypeIRPattern::new("char", "i8", "scalar"),
        TypeIRPattern::new("signed char", "i8", "scalar"),
        TypeIRPattern::new("unsigned char", "i8", "scalar"),
        TypeIRPattern::new("short", "i16", "scalar"),
        TypeIRPattern::new("unsigned short", "i16", "scalar"),
        TypeIRPattern::new("int", "i32", "scalar"),
        TypeIRPattern::new("unsigned int", "i32", "scalar"),
        TypeIRPattern::new("long", "i64", "scalar"),
        TypeIRPattern::new("unsigned long", "i64", "scalar"),
        TypeIRPattern::new("long long", "i64", "scalar"),
        TypeIRPattern::new("unsigned long long", "i64", "scalar"),
        TypeIRPattern::new("float", "float", "scalar"),
        TypeIRPattern::new("double", "double", "scalar"),
        TypeIRPattern::new("long double", "x86_fp80", "scalar"),
        TypeIRPattern::new("__fp16 / _Float16", "half", "scalar"),
        TypeIRPattern::new("__float128", "fp128", "scalar"),
        TypeIRPattern::new("int *", "ptr", "pointer"),
        TypeIRPattern::new("void *", "ptr", "pointer"),
        TypeIRPattern::new("double *", "ptr", "pointer"),
        TypeIRPattern::new("struct S *", "ptr", "pointer"),
        TypeIRPattern::new("int[10]", "[10 x i32]", "array"),
        TypeIRPattern::new("struct { int; double; }", "{ i32, double }", "aggregate"),
        TypeIRPattern::new("v4si (GCC vector)", "<4 x i32>", "vector"),
    ]
}

/// Build the type-system IR verification test suite.
pub fn build_type_tests() -> Vec<X86IRGenTest> {
    vec![
        // ── Void type ──
        X86IRGenTest::new("ir_type_void_return", X86IRGenCategory::Types,
            "void f(void) {}")
            .require("void return type in IR", "void")
            .require("ret void instruction", "ret void"),

        X86IRGenTest::new("ir_type_void_ptr", X86IRGenCategory::Types,
            "void f(void *p) { (void)p; }")
            .require("void pointer param", "void\\*")
            .require("alloca for pointer", "alloca"),

        // ── i1 (boolean) type ──
        X86IRGenTest::new("ir_type_i1_bool", X86IRGenCategory::Types,
            "_Bool f(_Bool x) { return x; }")
            .require("i1 type for _Bool", "i1"),

        X86IRGenTest::new("ir_type_i1_cmp", X86IRGenCategory::Types,
            "_Bool f(int a, int b) { return a < b; }")
            .require("icmp produces i1", "icmp")
            .require("i1 result", "i1"),

        // ── i8 type (char / signed char) ──
        X86IRGenTest::new("ir_type_i8_char", X86IRGenCategory::Types,
            "char f(char c) { return c; }")
            .require("i8 type for char", "i8"),

        X86IRGenTest::new("ir_type_i8_signed_char", X86IRGenCategory::Types,
            "signed char f(signed char c) { return c; }")
            .require("i8 type for signed char", "i8"),

        X86IRGenTest::new("ir_type_i8_unsigned_char", X86IRGenCategory::Types,
            "unsigned char f(unsigned char c) { return c; }")
            .require("i8 type for unsigned char", "i8"),

        // ── i16 type (short) ──
        X86IRGenTest::new("ir_type_i16_short", X86IRGenCategory::Types,
            "short f(short s) { return s; }")
            .require("i16 type for short", "i16"),

        X86IRGenTest::new("ir_type_i16_ushort", X86IRGenCategory::Types,
            "unsigned short f(unsigned short s) { return s; }")
            .require("i16 type for unsigned short", "i16"),

        // ── i32 type (int) ──
        X86IRGenTest::new("ir_type_i32_int", X86IRGenCategory::Types,
            "int f(int x) { return x; }")
            .require("i32 type for int", "i32"),

        X86IRGenTest::new("ir_type_i32_unsigned", X86IRGenCategory::Types,
            "unsigned f(unsigned x) { return x; }")
            .require("i32 type for unsigned int", "i32"),

        // ── i64 type (long / long long) ──
        X86IRGenTest::new("ir_type_i64_long", X86IRGenCategory::Types,
            "long f(long x) { return x; }")
            .with_target("x86_64-unknown-linux-gnu")
            .require("i64 type for long on LP64", "i64"),

        X86IRGenTest::new("ir_type_i64_long_long", X86IRGenCategory::Types,
            "long long f(long long x) { return x; }")
            .require("i64 type for long long", "i64"),

        X86IRGenTest::new("ir_type_i64_ull", X86IRGenCategory::Types,
            "unsigned long long f(unsigned long long x) { return x; }")
            .require("i64 type for unsigned long long", "i64"),

        // ── half type (__fp16) ──
        X86IRGenTest::new("ir_type_half", X86IRGenCategory::Types,
            "_Float16 f(_Float16 x) { return x; }")
            .with_flags(vec!["-std=c23"])
            .require("half type for _Float16", "half"),

        // ── float type ──
        X86IRGenTest::new("ir_type_float", X86IRGenCategory::Types,
            "float f(float x) { return x; }")
            .require("float type for float", "float"),

        X86IRGenTest::new("ir_type_float_literal", X86IRGenCategory::Types,
            "float f(void) { return 3.14f; }")
            .require("float literal constant", "float"),

        // ── double type ──
        X86IRGenTest::new("ir_type_double", X86IRGenCategory::Types,
            "double f(double x) { return x; }")
            .require("double type for double", "double"),

        X86IRGenTest::new("ir_type_double_literal", X86IRGenCategory::Types,
            "double f(void) { return 2.718281828; }")
            .require("double literal constant", "double"),

        // ── x86_fp80 type (long double on x86) ──
        X86IRGenTest::new("ir_type_x86_fp80", X86IRGenCategory::Types,
            "long double f(long double x) { return x; }")
            .require("x86_fp80 type for long double", "x86_fp80"),

        // ── fp128 type ──
        X86IRGenTest::new("ir_type_fp128", X86IRGenCategory::Types,
            "__float128 f(__float128 x) { return x; }")
            .with_flags(vec!["-std=gnu23"])
            .require("fp128 type for __float128", "fp128"),

        // ── Pointer types ──
        X86IRGenTest::new("ir_type_ptr_int_ptr", X86IRGenCategory::Types,
            "int f(int *p) { return *p; }")
            .require("pointer to int", "i32\\*")
            .require("load from pointer", "load"),

        X86IRGenTest::new("ir_type_ptr_double_ptr", X86IRGenCategory::Types,
            "double f(double *p) { return *p; }")
            .require("pointer to double in load", "double\\*")
            .require("floating-point load", "load double"),

        X86IRGenTest::new("ir_type_ptr_null", X86IRGenCategory::Types,
            "int *f(void) { return 0; }")
            .require("null pointer constant", "null"),

        X86IRGenTest::new("ir_type_ptr_void_ptr", X86IRGenCategory::Types,
            "void *f(int *p) { return (void *)p; }")
            .require("pointer cast to void*", "i8\\*"),

        // ── Array types ──
        X86IRGenTest::new("ir_type_array_fixed", X86IRGenCategory::Types,
            "int f(void) { int a[10]; return a[0]; }")
            .require("fixed-size array alloca", "alloca")
            .require("array type in IR", "i32"),

        X86IRGenTest::new("ir_type_array_multi_dim", X86IRGenCategory::Types,
            "int f(void) { int a[3][4]; return a[0][0]; }")
            .require("multi-dim array GEP", "getelementptr"),

        // ── Struct types ──
        X86IRGenTest::new("ir_type_struct_simple", X86IRGenCategory::Types,
            "struct S { int a; double b; }; double f(struct S s) { return s.b; }")
            .require("struct type in IR", "type")
            .require("struct field access via GEP", "getelementptr"),

        X86IRGenTest::new("ir_type_struct_nested", X86IRGenCategory::Types,
            "struct A { int x; }; struct B { struct A a; int y; }; int f(struct B b) { return b.a.x; }")
            .require("nested struct GEP", "getelementptr"),

        X86IRGenTest::new("ir_type_struct_return", X86IRGenCategory::Types,
            "struct S { int a; int b; }; struct S f(void) { struct S s = {1,2}; return s; }")
            .require("struct type definition", "type"),

        // ── Vector types ──
        X86IRGenTest::new("ir_type_vector_v4i32", X86IRGenCategory::Types,
            "typedef int v4si __attribute__((vector_size(16))); v4si f(v4si a, v4si b) { return a + b; }")
            .require("vector type <4 x i32>", "<4 x i32>")
            .require("vector add instruction", "add <4 x i32>"),

        X86IRGenTest::new("ir_type_vector_v2f64", X86IRGenCategory::Types,
            "typedef double v2df __attribute__((vector_size(16))); v2df f(v2df a, v2df b) { return a + b; }")
            .require("vector type <2 x double>", "<2 x double>")
            .require("vector fadd", "fadd <2 x double>"),

        X86IRGenTest::new("ir_type_vector_v8i16", X86IRGenCategory::Types,
            "typedef short v8hi __attribute__((vector_size(16))); v8hi f(v8hi a, v8hi b) { return a + b; }")
            .require("vector type <8 x i16>", "<8 x i16>"),

        X86IRGenTest::new("ir_type_vector_v16i8", X86IRGenCategory::Types,
            "typedef char v16qi __attribute__((vector_size(16))); v16qi f(v16qi a, v16qi b) { return a + b; }")
            .require("vector type <16 x i8>", "<16 x i8>"),

        X86IRGenTest::new("ir_type_vector_v4f32", X86IRGenCategory::Types,
            "typedef float v4sf __attribute__((vector_size(16))); v4sf f(v4sf a, v4sf b) { return a + b; }")
            .require("vector type <4 x float>", "<4 x float>"),

        X86IRGenTest::new("ir_type_vector_v2i64", X86IRGenCategory::Types,
            "typedef long long v2di __attribute__((vector_size(16))); v2di f(v2di a, v2di b) { return a + b; }")
            .require("vector type <2 x i64>", "<2 x i64>"),

        // ── Target triple in IR ──
        X86IRGenTest::new("ir_type_target_triple", X86IRGenCategory::Types,
            "int f(int x) { return x; }")
            .with_target("x86_64-unknown-linux-gnu")
            .require("target triple present", "target triple"),

        // ── Additional scalar type coverage ──
        X86IRGenTest::new("ir_type_wchar_t", X86IRGenCategory::Types,
            "#include <stddef.h>\nwchar_t f(wchar_t c) { return c; }")
            .require("wchar_t type lowering", "i32"),

        X86IRGenTest::new("ir_type_int8_t", X86IRGenCategory::Types,
            "#include <stdint.h>\nint8_t f(int8_t x) { return x; }")
            .require("int8_t maps to i8", "i8"),

        X86IRGenTest::new("ir_type_uint8_t", X86IRGenCategory::Types,
            "#include <stdint.h>\nuint8_t f(uint8_t x) { return x; }")
            .require("uint8_t maps to i8", "i8"),

        X86IRGenTest::new("ir_type_int16_t", X86IRGenCategory::Types,
            "#include <stdint.h>\nint16_t f(int16_t x) { return x; }")
            .require("int16_t maps to i16", "i16"),

        X86IRGenTest::new("ir_type_uint16_t", X86IRGenCategory::Types,
            "#include <stdint.h>\nuint16_t f(uint16_t x) { return x; }")
            .require("uint16_t maps to i16", "i16"),

        X86IRGenTest::new("ir_type_int32_t", X86IRGenCategory::Types,
            "#include <stdint.h>\nint32_t f(int32_t x) { return x; }")
            .require("int32_t maps to i32", "i32"),

        X86IRGenTest::new("ir_type_uint32_t", X86IRGenCategory::Types,
            "#include <stdint.h>\nuint32_t f(uint32_t x) { return x; }")
            .require("uint32_t maps to i32", "i32"),

        X86IRGenTest::new("ir_type_int64_t", X86IRGenCategory::Types,
            "#include <stdint.h>\nint64_t f(int64_t x) { return x; }")
            .require("int64_t maps to i64", "i64"),

        X86IRGenTest::new("ir_type_uint64_t", X86IRGenCategory::Types,
            "#include <stdint.h>\nuint64_t f(uint64_t x) { return x; }")
            .require("uint64_t maps to i64", "i64"),

        X86IRGenTest::new("ir_type_intptr_t", X86IRGenCategory::Types,
            "#include <stdint.h>\nintptr_t f(intptr_t x) { return x; }")
            .require("intptr_t lowering", "i64"),

        X86IRGenTest::new("ir_type_uintptr_t", X86IRGenCategory::Types,
            "#include <stdint.h>\nuintptr_t f(uintptr_t x) { return x; }")
            .require("uintptr_t lowering", "i64"),

        X86IRGenTest::new("ir_type_ptrdiff_t", X86IRGenCategory::Types,
            "#include <stddef.h>\nptrdiff_t f(ptrdiff_t x) { return x; }")
            .require("ptrdiff_t lowering", "i64"),

        X86IRGenTest::new("ir_type_size_t", X86IRGenCategory::Types,
            "#include <stddef.h>\nsize_t f(size_t x) { return x; }")
            .require("size_t lowering", "i64"),

        X86IRGenTest::new("ir_type_ssize_t", X86IRGenCategory::Types,
            "#include <sys/types.h>\nssize_t f(ssize_t x) { return x; }")
            .require("ssize_t lowering", "i64"),

        // ── Enum types ──
        X86IRGenTest::new("ir_type_enum", X86IRGenCategory::Types,
            "enum E { A, B, C }; enum E f(enum E e) { return e; }")
            .require("enum type lowers to i32", "i32"),

        X86IRGenTest::new("ir_type_enum_specified", X86IRGenCategory::Types,
            "enum E : char { A, B }; enum E f(enum E e) { return e; }")
            .require("fixed-type enum lowers to i8", "i8"),

        // ── Union types ──
        X86IRGenTest::new("ir_type_union", X86IRGenCategory::Types,
            "union U { int i; float f; }; int f(union U u) { return u.i; }")
            .require("union type in IR", "type"),

        // ── Bitfield types ──
        X86IRGenTest::new("ir_type_bitfield", X86IRGenCategory::Types,
            "struct S { int a : 3; int b : 5; }; int f(struct S s) { return s.a; }")
            .require("struct with bitfields", "type"),

        // ── Complex types ──
        X86IRGenTest::new("ir_type_complex_float", X86IRGenCategory::Types,
            "#include <complex.h>\nfloat _Complex f(float _Complex z) { return z; }")
            .require("complex float type", "float"),

        X86IRGenTest::new("ir_type_complex_double", X86IRGenCategory::Types,
            "#include <complex.h>\ndouble _Complex f(double _Complex z) { return z; }")
            .require("complex double type", "double"),

        // ── __int128 type ──
        X86IRGenTest::new("ir_type_int128", X86IRGenCategory::Types,
            "__int128 f(__int128 x) { return x; }")
            .with_flags(vec!["-std=gnu17"])
            .require("i128 type for __int128", "i128"),

        // ── Nested arrays ──
        X86IRGenTest::new("ir_type_nested_array", X86IRGenCategory::Types,
            "int f(void) { int a[2][3][4]; return a[0][1][2]; }")
            .require("nested array GEP", "getelementptr"),

        // ── Incomplete types ──
        X86IRGenTest::new("ir_type_incomplete_struct", X86IRGenCategory::Types,
            "struct S; struct S *f(struct S *p) { return p; }")
            .require("opaque struct pointer", "%struct.S"),

        // ── Typedef types ──
        X86IRGenTest::new("ir_type_typedef_int", X86IRGenCategory::Types,
            "typedef int myint; myint f(myint x) { return x; }")
            .require("typedef resolves to i32", "i32"),

        // ── Function pointer types ──
        X86IRGenTest::new("ir_type_func_ptr_simple", X86IRGenCategory::Types,
            "typedef int (*fnptr)(int); int f(fnptr fp, int x) { return fp(x); }")
            .require("function pointer type", "ptr"),

        // ── Array of function pointers ──
        X86IRGenTest::new("ir_type_array_func_ptr", X86IRGenCategory::Types,
            "int f(int (*arr[4])(int), int x, int i) { return arr[i](x); }")
            .require("array of function pointers", "ptr"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// CONSTANT EXPRESSION TESTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Build constant expression IR verification tests.
pub fn build_constant_tests() -> Vec<X86IRGenTest> {
    vec![
        // ── Integer constants ──
        X86IRGenTest::new("ir_const_int_zero", X86IRGenCategory::Constants,
            "int f(void) { return 0; }")
            .require("integer constant 0", "ret i32 0"),

        X86IRGenTest::new("ir_const_int_positive", X86IRGenCategory::Constants,
            "int f(void) { return 42; }")
            .require("integer constant 42", "ret i32 42"),

        X86IRGenTest::new("ir_const_int_negative", X86IRGenCategory::Constants,
            "int f(void) { return -1; }")
            .require("integer constant -1", "-1"),

        X86IRGenTest::new("ir_const_int_max", X86IRGenCategory::Constants,
            "int f(void) { return 2147483647; }")
            .require("large integer constant", "2147483647"),

        X86IRGenTest::new("ir_const_int_hex", X86IRGenCategory::Constants,
            "int f(void) { return 0xDEADBEEF; }")
            .require("hex integer constant", "3735928559"),

        // ── Float constants ──
        X86IRGenTest::new("ir_const_float_simple", X86IRGenCategory::Constants,
            "float f(void) { return 1.5f; }")
            .require("float constant 1.5", "float"),

        X86IRGenTest::new("ir_const_double_simple", X86IRGenCategory::Constants,
            "double f(void) { return 3.14159265358979; }")
            .require("double constant pi", "double"),

        X86IRGenTest::new("ir_const_double_zero", X86IRGenCategory::Constants,
            "double f(void) { return 0.0; }")
            .require("double zero constant", "double 0"),

        // ── Null constants ──
        X86IRGenTest::new("ir_const_null_ptr", X86IRGenCategory::Constants,
            "int *f(void) { return (int *)0; }")
            .require("null pointer constant", "null"),

        X86IRGenTest::new("ir_const_null_void_ptr", X86IRGenCategory::Constants,
            "void *f(void) { return 0; }")
            .require("null pointer from int", "null"),

        // ── Aggregate zero initialization ──
        X86IRGenTest::new("ir_const_zero_initializer", X86IRGenCategory::Constants,
            "struct S { int a; double b; }; struct S f(void) { struct S s = {0}; return s; }")
            .require("zeroinitializer for struct", "zeroinitializer"),

        // ── GEP constant expressions ──
        X86IRGenTest::new("ir_const_gep_global", X86IRGenCategory::Constants,
            "int arr[10]; int *f(void) { return &arr[5]; }")
            .require("GEP expression for global array element", "getelementptr"),

        // ── Bitcast constant expressions ──
        X86IRGenTest::new("ir_const_bitcast_ptr", X86IRGenCategory::Constants,
            "int f(void *p) { return *(int *)p; }")
            .require("pointer cast to int*", "i32\\*"),

        // ── inttoptr / ptrtoint ──
        X86IRGenTest::new("ir_const_inttoptr", X86IRGenCategory::Constants,
            "void *f(unsigned long x) { return (void *)x; }")
            .require("inttoptr operation", "inttoptr"),

        X86IRGenTest::new("ir_const_ptrtoint", X86IRGenCategory::Constants,
            "unsigned long f(void *p) { return (unsigned long)p; }")
            .require("ptrtoint operation", "ptrtoint"),

        // ── Undef / poison ──
        X86IRGenTest::new("ir_const_undef_uninit", X86IRGenCategory::Constants,
            "int f(void) { int x; return x; }")
            .with_flags(vec!["-Wno-uninitialized"])
            .require("uninitialized variable", "alloca"),

        // ── Complex constant expressions ──
        X86IRGenTest::new("ir_const_add_fold", X86IRGenCategory::Constants,
            "int f(void) { return 2 + 3; }")
            .require("constant fold 2+3 to 5", "ret i32 5"),

        X86IRGenTest::new("ir_const_sub_fold", X86IRGenCategory::Constants,
            "int f(void) { return 10 - 3; }")
            .require("constant fold 10-3 to 7", "ret i32 7"),

        X86IRGenTest::new("ir_const_mul_fold", X86IRGenCategory::Constants,
            "int f(void) { return 6 * 7; }")
            .require("constant fold 6*7 to 42", "ret i32 42"),

        X86IRGenTest::new("ir_const_div_fold", X86IRGenCategory::Constants,
            "int f(void) { return 100 / 5; }")
            .require("constant fold division", "ret i32 20"),

        X86IRGenTest::new("ir_const_mod_fold", X86IRGenCategory::Constants,
            "int f(void) { return 17 % 5; }")
            .require("constant fold modulo", "ret i32 2"),

        X86IRGenTest::new("ir_const_and_fold", X86IRGenCategory::Constants,
            "int f(void) { return 0xFF & 0x0F; }")
            .require("constant fold bitwise and", "ret i32 15"),

        X86IRGenTest::new("ir_const_or_fold", X86IRGenCategory::Constants,
            "int f(void) { return 0xF0 | 0x0F; }")
            .require("constant fold bitwise or", "ret i32 255"),

        X86IRGenTest::new("ir_const_xor_fold", X86IRGenCategory::Constants,
            "int f(void) { return 0xAA ^ 0x55; }")
            .require("constant fold bitwise xor", "ret i32 255"),

        X86IRGenTest::new("ir_const_shl_fold", X86IRGenCategory::Constants,
            "int f(void) { return 1 << 10; }")
            .require("constant fold shift left", "ret i32 1024"),

        X86IRGenTest::new("ir_const_lshr_fold", X86IRGenCategory::Constants,
            "unsigned f(void) { return 1024u >> 3; }")
            .require("constant fold logical shift right", "ret i32 128"),

        X86IRGenTest::new("ir_const_compare_fold", X86IRGenCategory::Constants,
            "int f(void) { return 5 > 3 ? 1 : 0; }")
            .require("constant fold comparison to true", "ret i32 1"),

        X86IRGenTest::new("ir_const_ternary_fold", X86IRGenCategory::Constants,
            "int f(void) { return 1 ? 42 : 99; }")
            .require("constant fold ternary with known condition", "ret i32 42"),

        X86IRGenTest::new("ir_const_address_of_global", X86IRGenCategory::Constants,
            "int x; int *f(void) { return &x; }")
            .require("address-of global constant", "@x"),

        X86IRGenTest::new("ir_const_sizeof_type", X86IRGenCategory::Constants,
            "#include <stddef.h>\nsize_t f(void) { return sizeof(int); }")
            .require("sizeof(int) constant folded to 4", "ret i64 4"),

        X86IRGenTest::new("ir_const_alignof_type", X86IRGenCategory::Constants,
            "#include <stddef.h>\nsize_t f(void) { return _Alignof(double); }")
            .require("alignof constant expression", "ret i64"),

        X86IRGenTest::new("ir_const_offsetof", X86IRGenCategory::Constants,
            "#include <stddef.h>\nstruct S { int a; char b; double c; }; size_t f(void) { return offsetof(struct S, c); }")
            .require("offsetof constant", "ret i64"),

        X86IRGenTest::new("ir_const_bool_true", X86IRGenCategory::Constants,
            "#include <stdbool.h>\nbool f(void) { return true; }")
            .require("bool true constant", "true"),

        X86IRGenTest::new("ir_const_bool_false", X86IRGenCategory::Constants,
            "#include <stdbool.h>\nbool f(void) { return false; }")
            .require("bool false constant", "false"),

        X86IRGenTest::new("ir_const_struct_aggregate", X86IRGenCategory::Constants,
            "struct S { int a; double b; }; struct S f(void) { return (struct S){1, 3.14}; }")
            .require("aggregate constant for struct literal", "insertvalue"),

        X86IRGenTest::new("ir_const_vector_splat", X86IRGenCategory::Constants,
            "typedef int v4si __attribute__((vector_size(16))); v4si f(void) { return (v4si){0, 0, 0, 0}; }")
            .require("zero splat vector constant", "zeroinitializer"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// INSTRUCTION TESTS — alloca, load, store
// ═══════════════════════════════════════════════════════════════════════════════

/// Build instruction-level IR tests: memory operations.
pub fn build_memory_instruction_tests() -> Vec<X86IRGenTest> {
    vec![
        // ── alloca ──
        X86IRGenTest::new(
            "ir_inst_alloca_scalar",
            X86IRGenCategory::Instructions,
            "int f(void) { int x = 42; return x; }",
        )
        .require("alloca for local int", "alloca i32"),
        X86IRGenTest::new(
            "ir_inst_alloca_array",
            X86IRGenCategory::Instructions,
            "int f(void) { int arr[10]; return arr[0]; }",
        )
        .require("alloca for array", "alloca [10 x i32]"),
        X86IRGenTest::new(
            "ir_inst_alloca_aligned",
            X86IRGenCategory::Instructions,
            "int f(void) { int x __attribute__((aligned(16))) = 0; return x; }",
        )
        .require("aligned alloca", "align 16"),
        // ── load ──
        X86IRGenTest::new(
            "ir_inst_load_int",
            X86IRGenCategory::Instructions,
            "int f(int *p) { return *p; }",
        )
        .require("load i32", "load i32"),
        X86IRGenTest::new(
            "ir_inst_load_float",
            X86IRGenCategory::Instructions,
            "float f(float *p) { return *p; }",
        )
        .require("load float", "load float"),
        X86IRGenTest::new(
            "ir_inst_load_double",
            X86IRGenCategory::Instructions,
            "double f(double *p) { return *p; }",
        )
        .require("load double", "load double"),
        X86IRGenTest::new(
            "ir_inst_load_i8",
            X86IRGenCategory::Instructions,
            "char f(char *p) { return *p; }",
        )
        .require("load i8", "load i8"),
        X86IRGenTest::new(
            "ir_inst_load_i16",
            X86IRGenCategory::Instructions,
            "short f(short *p) { return *p; }",
        )
        .require("load i16", "load i16"),
        X86IRGenTest::new(
            "ir_inst_load_i64",
            X86IRGenCategory::Instructions,
            "long long f(long long *p) { return *p; }",
        )
        .require("load i64", "load i64"),
        // ── store ──
        X86IRGenTest::new(
            "ir_inst_store_int",
            X86IRGenCategory::Instructions,
            "void f(int *p) { *p = 42; }",
        )
        .require("store i32", "store i32"),
        X86IRGenTest::new(
            "ir_inst_store_double",
            X86IRGenCategory::Instructions,
            "void f(double *p) { *p = 3.14; }",
        )
        .require("store double", "store double"),
        // ── getelementptr ──
        X86IRGenTest::new(
            "ir_inst_gep_array",
            X86IRGenCategory::Instructions,
            "int f(int *p, int i) { return p[i]; }",
        )
        .require("getelementptr for array access", "getelementptr"),
        X86IRGenTest::new(
            "ir_inst_gep_struct",
            X86IRGenCategory::Instructions,
            "struct S { int a; double b; }; double f(struct S *s) { return s->b; }",
        )
        .require("getelementptr for struct field", "getelementptr"),
        X86IRGenTest::new(
            "ir_inst_gep_struct_idx",
            X86IRGenCategory::Instructions,
            "struct S { int a; int b; int c; }; int f(struct S *s) { return s->c; }",
        )
        .require("gep i32 2 for third field", "getelementptr"),
        X86IRGenTest::new(
            "ir_inst_gep_inbounds",
            X86IRGenCategory::Instructions,
            "int f(int arr[10]) { return arr[5]; }",
        )
        .require("inbounds GEP", "inbounds"),
        // ── phi instruction ──
        X86IRGenTest::new(
            "ir_inst_phi_simple",
            X86IRGenCategory::Instructions,
            "int f(int x) { int y = x ? 1 : 2; return y; }",
        )
        .require("phi instruction for ternary", "phi i32"),
        // ── select instruction ──
        X86IRGenTest::new(
            "ir_inst_select",
            X86IRGenCategory::Instructions,
            "int f(int a, int b, int c) { return a ? b : c; }",
        )
        .require("select instruction", "select"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// ARITHMETIC INSTRUCTION TESTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Build arithmetic instruction IR tests.
pub fn build_arithmetic_tests() -> Vec<X86IRGenTest> {
    vec![
        // ── add ──
        X86IRGenTest::new("ir_arith_add_int", X86IRGenCategory::Arithmetic,
            "int f(int a, int b) { return a + b; }")
            .require("add i32", "add i32"),

        X86IRGenTest::new("ir_arith_add_float", X86IRGenCategory::Arithmetic,
            "float f(float a, float b) { return a + b; }")
            .require("fadd float", "fadd float"),

        X86IRGenTest::new("ir_arith_add_double", X86IRGenCategory::Arithmetic,
            "double f(double a, double b) { return a + b; }")
            .require("fadd double", "fadd double"),

        // ── sub ──
        X86IRGenTest::new("ir_arith_sub_int", X86IRGenCategory::Arithmetic,
            "int f(int a, int b) { return a - b; }")
            .require("sub i32", "sub i32"),

        X86IRGenTest::new("ir_arith_sub_float", X86IRGenCategory::Arithmetic,
            "float f(float a, float b) { return a - b; }")
            .require("fsub float", "fsub float"),

        // ── mul ──
        X86IRGenTest::new("ir_arith_mul_int", X86IRGenCategory::Arithmetic,
            "int f(int a, int b) { return a * b; }")
            .require("mul i32", "mul i32"),

        X86IRGenTest::new("ir_arith_mul_float", X86IRGenCategory::Arithmetic,
            "float f(float a, float b) { return a * b; }")
            .require("fmul float", "fmul float"),

        // ── sdiv ──
        X86IRGenTest::new("ir_arith_sdiv_int", X86IRGenCategory::Arithmetic,
            "int f(int a, int b) { return a / b; }")
            .require("sdiv i32", "sdiv i32"),

        // ── udiv ──
        X86IRGenTest::new("ir_arith_udiv_uint", X86IRGenCategory::Arithmetic,
            "unsigned f(unsigned a, unsigned b) { return a / b; }")
            .require("udiv i32 for unsigned", "udiv i32"),

        // ── srem ──
        X86IRGenTest::new("ir_arith_srem_int", X86IRGenCategory::Arithmetic,
            "int f(int a, int b) { return a % b; }")
            .require("srem i32", "srem i32"),

        // ── urem ──
        X86IRGenTest::new("ir_arith_urem_uint", X86IRGenCategory::Arithmetic,
            "unsigned f(unsigned a, unsigned b) { return a % b; }")
            .require("urem i32 for unsigned", "urem i32"),

        // ── fdiv ──
        X86IRGenTest::new("ir_arith_fdiv_float", X86IRGenCategory::Arithmetic,
            "float f(float a, float b) { return a / b; }")
            .require("fdiv float", "fdiv float"),

        X86IRGenTest::new("ir_arith_fdiv_double", X86IRGenCategory::Arithmetic,
            "double f(double a, double b) { return a / b; }")
            .require("fdiv double", "fdiv double"),

        // ── frem ──
        X86IRGenTest::new("ir_arith_frem_float", X86IRGenCategory::Arithmetic,
            "#include <math.h>\nfloat f(float a, float b) { return fmodf(a, b); }")
            .require("frem float", "frem"),

        // ── Additional arithmetic combinations ──
        X86IRGenTest::new("ir_arith_mixed_add_sub", X86IRGenCategory::Arithmetic,
            "int f(int a, int b, int c) { return a + b - c; }")
            .require("add and sub in same function", "add i32")
            .require("sub after add", "sub i32"),

        X86IRGenTest::new("ir_arith_mul_add_fold", X86IRGenCategory::Arithmetic,
            "int f(int a) { return a * 2 + 1; }")
            .require("mul by constant", "mul i32"),

        X86IRGenTest::new("ir_arith_div_by_power_of_two", X86IRGenCategory::Arithmetic,
            "int f(int a) { return a / 4; }")
            .with_opt(X86OptLevel::O1)
            .require("sdiv or ashr for power-of-two div", "sdiv"),

        X86IRGenTest::new("ir_arith_rem_by_power_of_two", X86IRGenCategory::Arithmetic,
            "unsigned f(unsigned a) { return a % 16; }")
            .with_opt(X86OptLevel::O1)
            .require("urem for unsigned mod", "urem"),

        X86IRGenTest::new("ir_arith_negate_int", X86IRGenCategory::Arithmetic,
            "int f(int a) { return -a; }")
            .require("sub from zero for negation", "sub i32 0"),

        X86IRGenTest::new("ir_arith_negate_float", X86IRGenCategory::Arithmetic,
            "float f(float a) { return -a; }")
            .require("fneg float", "fneg float"),

        X86IRGenTest::new("ir_arith_negate_double", X86IRGenCategory::Arithmetic,
            "double f(double a) { return -a; }")
            .require("fneg double", "fneg double"),

        X86IRGenTest::new("ir_arith_fma_pattern", X86IRGenCategory::Arithmetic,
            "double f(double a, double b, double c) { return a * b + c; }")
            .with_opt(X86OptLevel::O2)
            .require("possibly contracted to llvm.fmuladd", "call"),

        X86IRGenTest::new("ir_arith_abs_int", X86IRGenCategory::Arithmetic,
            "int f(int a) { return a >= 0 ? a : -a; }")
            .require("abs via select/cmp", "icmp")
            .require("negate on negative branch", "sub"),

        X86IRGenTest::new("ir_arith_abs_long", X86IRGenCategory::Arithmetic,
            "long f(long a) { return a >= 0 ? a : -a; }")
            .require("abs for i64", "i64"),

        X86IRGenTest::new("ir_arith_min_int", X86IRGenCategory::Arithmetic,
            "int f(int a, int b) { return a < b ? a : b; }")
            .require("min via select/icmp slt", "icmp slt")
            .require("select for min", "select i32"),

        X86IRGenTest::new("ir_arith_max_int", X86IRGenCategory::Arithmetic,
            "int f(int a, int b) { return a > b ? a : b; }")
            .require("max via select/icmp sgt", "icmp sgt")
            .require("select for max", "select i32"),

        X86IRGenTest::new("ir_arith_overflow_add", X86IRGenCategory::Arithmetic,
            "#include <stdbool.h>\nbool f(int a, int b, int *result) { return __builtin_add_overflow(a, b, result); }")
            .require("add with overflow intrinsic", "llvm.sadd.with.overflow"),

        X86IRGenTest::new("ir_arith_overflow_sub", X86IRGenCategory::Arithmetic,
            "#include <stdbool.h>\nbool f(int a, int b, int *result) { return __builtin_sub_overflow(a, b, result); }")
            .require("sub with overflow intrinsic", "llvm.ssub.with.overflow"),

        X86IRGenTest::new("ir_arith_overflow_mul", X86IRGenCategory::Arithmetic,
            "#include <stdbool.h>\nbool f(int a, int b, int *result) { return __builtin_mul_overflow(a, b, result); }")
            .require("mul with overflow intrinsic", "llvm.smul.with.overflow"),

        X86IRGenTest::new("ir_arith_saturating_add", X86IRGenCategory::Arithmetic,
            "#include <stdbool.h>\nint f(int a, int b) { int r; __builtin_add_overflow(a, b, &r); return r; }")
            .require("overflow intrinsic for saturating add", "llvm.sadd.with.overflow"),

        X86IRGenTest::new("ir_arith_i8_arithmetic", X86IRGenCategory::Arithmetic,
            "char f(char a, char b) { return a + b; }")
            .require("trunc/sext pattern for i8 arithmetic", "sext")
            .require("add after promotion", "add i32"),

        X86IRGenTest::new("ir_arith_i16_arithmetic", X86IRGenCategory::Arithmetic,
            "short f(short a, short b) { return a * b; }")
            .require("sext for i16 multiplication", "sext")
            .require("mul after promotion", "mul i32"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// BITWISE INSTRUCTION TESTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Build bitwise/shift instruction IR tests.
pub fn build_bitwise_tests() -> Vec<X86IRGenTest> {
    vec![
        // ── shl ──
        X86IRGenTest::new(
            "ir_bitwise_shl",
            X86IRGenCategory::Instructions,
            "int f(int a, int b) { return a << b; }",
        )
        .require("shl i32", "shl i32"),
        // ── lshr (logical shift right, unsigned) ──
        X86IRGenTest::new(
            "ir_bitwise_lshr",
            X86IRGenCategory::Instructions,
            "unsigned f(unsigned a, unsigned b) { return a >> b; }",
        )
        .require("lshr i32", "lshr i32"),
        // ── ashr (arithmetic shift right, signed) ──
        X86IRGenTest::new(
            "ir_bitwise_ashr",
            X86IRGenCategory::Instructions,
            "int f(int a, int b) { return a >> b; }",
        )
        .require("ashr i32", "ashr i32"),
        // ── and ──
        X86IRGenTest::new(
            "ir_bitwise_and",
            X86IRGenCategory::Instructions,
            "int f(int a, int b) { return a & b; }",
        )
        .require("and i32", "and i32"),
        // ── or ──
        X86IRGenTest::new(
            "ir_bitwise_or",
            X86IRGenCategory::Instructions,
            "int f(int a, int b) { return a | b; }",
        )
        .require("or i32", "or i32"),
        // ── xor ──
        X86IRGenTest::new(
            "ir_bitwise_xor",
            X86IRGenCategory::Instructions,
            "int f(int a, int b) { return a ^ b; }",
        )
        .require("xor i32", "xor i32"),
        // ── bitwise not (via xor -1) ──
        X86IRGenTest::new(
            "ir_bitwise_not",
            X86IRGenCategory::Instructions,
            "int f(int a) { return ~a; }",
        )
        .require("xor -1 pattern for bitwise not", "xor")
        .require("constant -1 operand", "-1"),
        // ── Bitwise on different widths ──
        X86IRGenTest::new(
            "ir_bitwise_and_i8",
            X86IRGenCategory::Instructions,
            "char f(char a, char b) { return a & b; }",
        )
        .require("and on promoted i8", "and"),
        X86IRGenTest::new(
            "ir_bitwise_or_i64",
            X86IRGenCategory::Instructions,
            "long long f(long long a, long long b) { return a | b; }",
        )
        .require("or i64", "or i64"),
        X86IRGenTest::new(
            "ir_bitwise_xor_i16",
            X86IRGenCategory::Instructions,
            "short f(short a, short b) { return a ^ b; }",
        )
        .require("xor on promoted i16", "xor"),
        X86IRGenTest::new(
            "ir_bitwise_shl_by_literal",
            X86IRGenCategory::Instructions,
            "int f(int a) { return a << 4; }",
        )
        .require("shl by constant 4", "shl i32"),
        X86IRGenTest::new(
            "ir_bitwise_lshr_by_literal",
            X86IRGenCategory::Instructions,
            "unsigned f(unsigned a) { return a >> 8; }",
        )
        .require("lshr by constant 8", "lshr i32"),
        X86IRGenTest::new(
            "ir_bitwise_ashr_by_literal",
            X86IRGenCategory::Instructions,
            "int f(int a) { return a >> 2; }",
        )
        .require("ashr by constant 2", "ashr i32"),
        X86IRGenTest::new(
            "ir_bitwise_rotate_left",
            X86IRGenCategory::Instructions,
            "unsigned f(unsigned x, unsigned n) { return (x << n) | (x >> (32 - n)); }",
        )
        .require("rotate left pattern", "shl")
        .require("lshr for rotate right part", "lshr"),
        X86IRGenTest::new(
            "ir_bitwise_rotate_right",
            X86IRGenCategory::Instructions,
            "unsigned f(unsigned x, unsigned n) { return (x >> n) | (x << (32 - n)); }",
        )
        .require("rotate right pattern", "lshr")
        .require("shl for rotate left part", "shl"),
        X86IRGenTest::new(
            "ir_bitwise_popcount_builtin",
            X86IRGenCategory::Instructions,
            "int f(unsigned x) { return __builtin_popcount(x); }",
        )
        .require("popcount intrinsic", "llvm.ctpop"),
        X86IRGenTest::new(
            "ir_bitwise_clz_builtin",
            X86IRGenCategory::Instructions,
            "int f(unsigned x) { return __builtin_clz(x); }",
        )
        .require("clz intrinsic", "llvm.ctlz"),
        X86IRGenTest::new(
            "ir_bitwise_ctz_builtin",
            X86IRGenCategory::Instructions,
            "int f(unsigned x) { return __builtin_ctz(x); }",
        )
        .require("ctz intrinsic", "llvm.cttz"),
        X86IRGenTest::new(
            "ir_bitwise_bswap_builtin",
            X86IRGenCategory::Instructions,
            "unsigned f(unsigned x) { return __builtin_bswap32(x); }",
        )
        .require("bswap intrinsic", "llvm.bswap"),
        X86IRGenTest::new(
            "ir_bitwise_parity_builtin",
            X86IRGenCategory::Instructions,
            "int f(unsigned x) { return __builtin_parity(x); }",
        )
        .require("parity intrinsic", "llvm.ctpop"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// ICMP / FCMP INSTRUCTION TESTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Build comparison instruction IR tests.
pub fn build_comparison_tests() -> Vec<X86IRGenTest> {
    vec![
        // ── icmp eq ──
        X86IRGenTest::new(
            "ir_cmp_icmp_eq",
            X86IRGenCategory::Instructions,
            "int f(int a, int b) { return a == b; }",
        )
        .require("icmp eq", "icmp eq i32"),
        // ── icmp ne ──
        X86IRGenTest::new(
            "ir_cmp_icmp_ne",
            X86IRGenCategory::Instructions,
            "int f(int a, int b) { return a != b; }",
        )
        .require("icmp ne", "icmp ne i32"),
        // ── icmp sgt ──
        X86IRGenTest::new(
            "ir_cmp_icmp_sgt",
            X86IRGenCategory::Instructions,
            "int f(int a, int b) { return a > b; }",
        )
        .require("icmp sgt", "icmp sgt i32"),
        // ── icmp sge ──
        X86IRGenTest::new(
            "ir_cmp_icmp_sge",
            X86IRGenCategory::Instructions,
            "int f(int a, int b) { return a >= b; }",
        )
        .require("icmp sge", "icmp sge i32"),
        // ── icmp slt ──
        X86IRGenTest::new(
            "ir_cmp_icmp_slt",
            X86IRGenCategory::Instructions,
            "int f(int a, int b) { return a < b; }",
        )
        .require("icmp slt", "icmp slt i32"),
        // ── icmp sle ──
        X86IRGenTest::new(
            "ir_cmp_icmp_sle",
            X86IRGenCategory::Instructions,
            "int f(int a, int b) { return a <= b; }",
        )
        .require("icmp sle", "icmp sle i32"),
        // ── icmp ugt ──
        X86IRGenTest::new(
            "ir_cmp_icmp_ugt",
            X86IRGenCategory::Instructions,
            "unsigned f(unsigned a, unsigned b) { return a > b; }",
        )
        .require("icmp ugt for unsigned >", "icmp ugt i32"),
        // ── icmp uge ──
        X86IRGenTest::new(
            "ir_cmp_icmp_uge",
            X86IRGenCategory::Instructions,
            "unsigned f(unsigned a, unsigned b) { return a >= b; }",
        )
        .require("icmp uge for unsigned >=", "icmp uge i32"),
        // ── icmp ult ──
        X86IRGenTest::new(
            "ir_cmp_icmp_ult",
            X86IRGenCategory::Instructions,
            "unsigned f(unsigned a, unsigned b) { return a < b; }",
        )
        .require("icmp ult for unsigned <", "icmp ult i32"),
        // ── icmp ule ──
        X86IRGenTest::new(
            "ir_cmp_icmp_ule",
            X86IRGenCategory::Instructions,
            "unsigned f(unsigned a, unsigned b) { return a <= b; }",
        )
        .require("icmp ule for unsigned <=", "icmp ule i32"),
        // ── fcmp oeq ──
        X86IRGenTest::new(
            "ir_cmp_fcmp_oeq",
            X86IRGenCategory::Instructions,
            "int f(float a, float b) { return a == b; }",
        )
        .require("fcmp oeq", "fcmp oeq float"),
        // ── fcmp one ──
        X86IRGenTest::new(
            "ir_cmp_fcmp_one",
            X86IRGenCategory::Instructions,
            "int f(float a, float b) { return a != b; }",
        )
        .require("fcmp one", "fcmp one float"),
        // ── fcmp ogt ──
        X86IRGenTest::new(
            "ir_cmp_fcmp_ogt",
            X86IRGenCategory::Instructions,
            "int f(float a, float b) { return a > b; }",
        )
        .require("fcmp ogt", "fcmp ogt float"),
        // ── fcmp oge ──
        X86IRGenTest::new(
            "ir_cmp_fcmp_oge",
            X86IRGenCategory::Instructions,
            "int f(float a, float b) { return a >= b; }",
        )
        .require("fcmp oge", "fcmp oge float"),
        // ── fcmp olt ──
        X86IRGenTest::new(
            "ir_cmp_fcmp_olt",
            X86IRGenCategory::Instructions,
            "int f(float a, float b) { return a < b; }",
        )
        .require("fcmp olt", "fcmp olt float"),
        // ── fcmp ole ──
        X86IRGenTest::new(
            "ir_cmp_fcmp_ole",
            X86IRGenCategory::Instructions,
            "int f(float a, float b) { return a <= b; }",
        )
        .require("fcmp ole", "fcmp ole float"),
        // ── fcmp ord ──
        X86IRGenTest::new(
            "ir_cmp_fcmp_ord",
            X86IRGenCategory::Instructions,
            "#include <math.h>\nint f(float x) { return !isnan(x); }",
        )
        .require("fcmp ord", "fcmp"),
        // ── fcmp uno ──
        X86IRGenTest::new(
            "ir_cmp_fcmp_uno",
            X86IRGenCategory::Instructions,
            "#include <math.h>\nint f(float x) { return isnan(x); }",
        )
        .require("fcmp uno", "fcmp"),
        // ── fcmp ueq ──
        X86IRGenTest::new(
            "ir_cmp_fcmp_ueq",
            X86IRGenCategory::Instructions,
            "int f(double a, double b) { return !(a < b) && !(a > b); }",
        )
        .require("fcmp instruction for complex compare", "fcmp"),
        // ── fcmp for double ──
        X86IRGenTest::new(
            "ir_cmp_fcmp_double",
            X86IRGenCategory::Instructions,
            "int f(double a, double b) { return a > b; }",
        )
        .require("fcmp ogt double", "fcmp ogt double"),
        // ── Pointer comparison ──
        X86IRGenTest::new(
            "ir_cmp_icmp_ptr_eq",
            X86IRGenCategory::Instructions,
            "int f(int *a, int *b) { return a == b; }",
        )
        .require("icmp eq on pointer", "icmp eq"),
        // ── Pointer relational comparisons ──
        X86IRGenTest::new(
            "ir_cmp_icmp_ptr_ugt",
            X86IRGenCategory::Instructions,
            "int f(int *a, int *b) { return a > b; }",
        )
        .require("pointer comparison uses unsigned", "icmp ugt"),
        X86IRGenTest::new(
            "ir_cmp_icmp_ptr_ult",
            X86IRGenCategory::Instructions,
            "int f(int *a, int *b) { return a < b; }",
        )
        .require("pointer less-than unsigned", "icmp ult"),
        // ── Chained comparisons ──
        X86IRGenTest::new(
            "ir_cmp_chained_lt",
            X86IRGenCategory::Instructions,
            "int f(int a, int b, int c) { return a < b && b < c; }",
        )
        .require("chained comparison", "icmp")
        .require_at_least("two comparisons", "icmp", 2),
        // ── Integer comparison with constant ──
        X86IRGenTest::new(
            "ir_cmp_icmp_const_rhs",
            X86IRGenCategory::Instructions,
            "int f(int a) { return a > 5; }",
        )
        .require("compare with constant 5", "icmp sgt i32")
        .require("constant operand", "5"),
        X86IRGenTest::new(
            "ir_cmp_icmp_const_lhs",
            X86IRGenCategory::Instructions,
            "int f(int a) { return 0 != a; }",
        )
        .require("compare with zero", "icmp ne i32")
        .require("zero operand", "0"),
        // ── Float comparison with NaN considerations ──
        X86IRGenTest::new(
            "ir_cmp_fcmp_double_oeq",
            X86IRGenCategory::Instructions,
            "int f(double a, double b) { return a == b; }",
        )
        .require("ordered and equal", "fcmp oeq double"),
        X86IRGenTest::new(
            "ir_cmp_fcmp_double_one",
            X86IRGenCategory::Instructions,
            "int f(double a, double b) { return a != b; }",
        )
        .require("ordered and not equal", "fcmp one double"),
        X86IRGenTest::new(
            "ir_cmp_fcmp_double_oge",
            X86IRGenCategory::Instructions,
            "int f(double a, double b) { return a >= b; }",
        )
        .require("ordered greater or equal", "fcmp oge double"),
        X86IRGenTest::new(
            "ir_cmp_fcmp_double_ugt",
            X86IRGenCategory::Instructions,
            "int f(double a, double b) { return !(a <= b); }",
        )
        .require("fcmp for unordered >", "fcmp"),
        // ── memcmp / strcmp patterns ──
        X86IRGenTest::new(
            "ir_cmp_memcmp",
            X86IRGenCategory::Instructions,
            "#include <string.h>\nint f(const void *a, const void *b) { return memcmp(a, b, 4); }",
        )
        .require("memcmp call", "call"),
        // ── Three-way comparison (C++20 spaceship) ──
        X86IRGenTest::new(
            "ir_cmp_three_way_int",
            X86IRGenCategory::Instructions,
            "int f(int a, int b) { return (a > b) - (a < b); }",
        )
        .require("three-way comparison pattern", "icmp"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// CONTROL FLOW INSTRUCTION TESTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Build control-flow instruction IR tests: br, switch, ret.
pub fn build_control_flow_tests() -> Vec<X86IRGenTest> {
    vec![
        // ── ret ──
        X86IRGenTest::new("ir_cf_ret_void", X86IRGenCategory::ControlFlow,
            "void f(void) {}")
            .require("ret void", "ret void"),

        X86IRGenTest::new("ir_cf_ret_int", X86IRGenCategory::ControlFlow,
            "int f(void) { return 0; }")
            .require("ret i32", "ret i32"),

        X86IRGenTest::new("ir_cf_ret_float", X86IRGenCategory::ControlFlow,
            "float f(void) { return 0.0f; }")
            .require("ret float", "ret float"),

        // ── br (unconditional) ──
        X86IRGenTest::new("ir_cf_br_unconditional", X86IRGenCategory::ControlFlow,
            "void f(int x) { goto label; label: return; }")
            .require("unconditional branch", "br label"),

        // ── br (conditional) ──
        X86IRGenTest::new("ir_cf_br_conditional_if", X86IRGenCategory::ControlFlow,
            "int f(int x) { if (x) return 1; else return 0; }")
            .require("conditional branch", "br i1"),

        X86IRGenTest::new("ir_cf_br_conditional_while", X86IRGenCategory::ControlFlow,
            "int f(int n) { int s = 0; while (n > 0) { s += n; n--; } return s; }")
            .require("conditional branch in loop", "br i1"),

        // ── switch ──
        X86IRGenTest::new("ir_cf_switch_simple", X86IRGenCategory::ControlFlow,
            "int f(int x) { switch(x) { case 1: return 10; case 2: return 20; default: return 0; } }")
            .require("switch instruction", "switch i32"),

        X86IRGenTest::new("ir_cf_switch_multi_case", X86IRGenCategory::ControlFlow,
            "int f(int x) { switch(x) { case 1: case 2: case 3: return 42; default: return 0; } }")
            .require("switch instruction", "switch"),

        X86IRGenTest::new("ir_cf_switch_default_only", X86IRGenCategory::ControlFlow,
            "int f(int x) { switch(x) { default: return 99; } }")
            .require("switch with default only", "switch"),

        // ── phi nodes ──
        X86IRGenTest::new("ir_cf_phi_if_else", X86IRGenCategory::ControlFlow,
            "int f(int x) { int y; if (x > 0) y = 1; else y = 2; return y; }")
            .require("phi node for if-else assignment", "phi i32"),

        X86IRGenTest::new("ir_cf_phi_for_loop", X86IRGenCategory::ControlFlow,
            "int f(int n) { int sum = 0; for (int i = 0; i < n; i++) sum += i; return sum; }")
            .require("phi nodes for loop induction", "phi i32"),

        // ── Indirect/unreachable ──
        X86IRGenTest::new("ir_cf_unreachable", X86IRGenCategory::ControlFlow,
            "void f(void) { __builtin_unreachable(); }")
            .require("unreachable instruction", "unreachable"),

        // ── Loop constructs ──
        X86IRGenTest::new("ir_cf_do_while", X86IRGenCategory::ControlFlow,
            "int f(int n) { int i = 0; do { i++; } while (i < n); return i; }")
            .require("do-while loop", "phi i32")
            .require("conditional branch for loop exit", "br i1"),

        X86IRGenTest::new("ir_cf_for_loop_init_cond_inc", X86IRGenCategory::ControlFlow,
            "int f(int n) { int s = 0; for (int i = 0; i < n; i += 2) s += i; return s; }")
            .require("for loop with step", "phi i32"),

        X86IRGenTest::new("ir_cf_infinite_loop", X86IRGenCategory::ControlFlow,
            "void f(void) { while(1) {} }")
            .require("infinite loop", "br label"),

        X86IRGenTest::new("ir_cf_nested_loops", X86IRGenCategory::ControlFlow,
            "int f(int n) { int s = 0; for (int i = 0; i < n; i++) for (int j = 0; j < i; j++) s++; return s; }")
            .require("nested for loops", "br label")
            .require_at_least("multiple phi nodes", "phi", 2),

        X86IRGenTest::new("ir_cf_break_in_loop", X86IRGenCategory::ControlFlow,
            "int f(int n) { for (int i = 0; ; i++) { if (i >= n) break; } return 0; }")
            .require("break from loop", "br"),

        X86IRGenTest::new("ir_cf_continue_in_loop", X86IRGenCategory::ControlFlow,
            "int f(int n) { int s = 0; for (int i = 0; i < n; i++) { if (i % 2 == 0) continue; s += i; } return s; }")
            .require("continue in loop", "br"),

        X86IRGenTest::new("ir_cf_early_return", X86IRGenCategory::ControlFlow,
            "int f(int x) { if (x < 0) return -1; if (x == 0) return 0; return 1; }")
            .require("multiple return points", "ret i32")
            .require_exact("three returns", "ret i32", 3),

        X86IRGenTest::new("ir_cf_goto_forward", X86IRGenCategory::ControlFlow,
            "void f(void) { goto label; label: return; }")
            .require("forward goto via br", "br label"),

        X86IRGenTest::new("ir_cf_goto_backward", X86IRGenCategory::ControlFlow,
            "void f(int n) { int i = 0; start: if (i++ < n) goto start; }")
            .require("backward goto via br", "br label"),

        // ── Switch with range / density ──
        X86IRGenTest::new("ir_cf_switch_dense", X86IRGenCategory::ControlFlow,
            "int f(int x) { switch(x) { case 0: return 1; case 1: return 2; case 2: return 3; case 3: return 4; case 4: return 5; default: return 0; } }")
            .require("dense switch", "switch i32"),

        X86IRGenTest::new("ir_cf_switch_sparse", X86IRGenCategory::ControlFlow,
            "int f(int x) { switch(x) { case -100: return 1; case 0: return 2; case 100: return 3; case 1000: return 4; default: return 0; } }")
            .require("sparse switch", "switch i32"),

        // ── Short-circuit evaluation ──
        X86IRGenTest::new("ir_cf_short_circuit_and", X86IRGenCategory::ControlFlow,
            "int f(int a, int b, int c) { return a && b && c; }")
            .require("short-circuit and", "br i1"),

        X86IRGenTest::new("ir_cf_short_circuit_or", X86IRGenCategory::ControlFlow,
            "int f(int a, int b, int c) { return a || b || c; }")
            .require("short-circuit or", "br i1"),

        // ── Comma operator ──
        X86IRGenTest::new("ir_cf_comma_operator", X86IRGenCategory::ControlFlow,
            "int f(int a, int b) { return (a++, a += b, a); }")
            .require("comma operator sequencing", "add"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// AGGREGATE INSTRUCTION TESTS — extractvalue, insertvalue
// ═══════════════════════════════════════════════════════════════════════════════

/// Build aggregate instruction IR tests.
pub fn build_aggregate_tests() -> Vec<X86IRGenTest> {
    vec![
        // ── extractvalue ──
        X86IRGenTest::new("ir_agg_extractvalue_struct", X86IRGenCategory::Instructions,
            "struct S { int a; double b; }; int f(struct S s) { return s.a; }")
            .require("extractvalue for struct field", "extractvalue"),

        // ── insertvalue ──
        X86IRGenTest::new("ir_agg_insertvalue_struct", X86IRGenCategory::Instructions,
            "struct S { int a; int b; }; struct S f(int x) { struct S s; s.a = x; s.b = 0; return s; }")
            .require("insertvalue for struct field", "insertvalue"),

        // ── extractelement ──
        X86IRGenTest::new("ir_agg_extractelement", X86IRGenCategory::Instructions,
            "typedef int v4si __attribute__((vector_size(16))); int f(v4si v) { return v[2]; }")
            .require("extractelement instruction", "extractelement"),

        // ── insertelement ──
        X86IRGenTest::new("ir_agg_insertelement", X86IRGenCategory::Instructions,
            "typedef int v4si __attribute__((vector_size(16))); v4si f(v4si v, int x) { v[1] = x; return v; }")
            .require("insertelement instruction", "insertelement"),

        // ── shufflevector ──
        X86IRGenTest::new("ir_agg_shufflevector", X86IRGenCategory::Instructions,
            "typedef int v4si __attribute__((vector_size(16))); v4si f(v4si a, v4si b) { return __builtin_shufflevector(a, b, 0, 5, 2, 7); }")
            .require("shufflevector instruction", "shufflevector"),

        // ── Additional shuffle patterns ──
        X86IRGenTest::new("ir_agg_shufflevector_identity", X86IRGenCategory::Instructions,
            "typedef int v4si __attribute__((vector_size(16))); v4si f(v4si a) { return __builtin_shufflevector(a, a, 0, 1, 2, 3); }")
            .require("identity shuffle", "shufflevector"),

        X86IRGenTest::new("ir_agg_shufflevector_reverse", X86IRGenCategory::Instructions,
            "typedef int v4si __attribute__((vector_size(16))); v4si f(v4si a) { return __builtin_shufflevector(a, a, 3, 2, 1, 0); }")
            .require("reverse shuffle", "shufflevector"),

        X86IRGenTest::new("ir_agg_shufflevector_interleave", X86IRGenCategory::Instructions,
            "typedef int v4si __attribute__((vector_size(16))); v4si f(v4si a, v4si b) { return __builtin_shufflevector(a, b, 0, 4, 1, 5); }")
            .require("interleave shuffle", "shufflevector"),

        // ── extractvalue / insertvalue with arrays ──
        X86IRGenTest::new("ir_agg_extractvalue_array", X86IRGenCategory::Instructions,
            "struct S { int arr[3]; }; int f(struct S s) { return s.arr[1]; }")
            .require("extractvalue from array within struct", "extractvalue"),

        // ── Union access ──
        X86IRGenTest::new("ir_agg_union_bitcast", X86IRGenCategory::Instructions,
            "union U { int i; float f; }; float f(union U u) { return u.f; }")
            .require("union type punning may use bitcast", "load"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// FUNCTION CALL & INDIRECT CALL INSTRUCTION TESTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Build call instruction IR tests.
pub fn build_call_tests() -> Vec<X86IRGenTest> {
    vec![
        // ── Direct call ──
        X86IRGenTest::new("ir_call_direct_void", X86IRGenCategory::Instructions,
            "void g(void); void f(void) { g(); }")
            .require("call void @g", "call void"),

        X86IRGenTest::new("ir_call_direct_args", X86IRGenCategory::Instructions,
            "int add(int a, int b) { return a + b; } int f(int x, int y) { return add(x, y); }")
            .require("call to add with arguments", "call i32 @add"),

        X86IRGenTest::new("ir_call_direct_float", X86IRGenCategory::Instructions,
            "double sin(double x); double f(double a) { return sin(a); }")
            .require("call to sin", "call double"),

        // ── Indirect call (function pointer) ──
        X86IRGenTest::new("ir_call_indirect_simple", X86IRGenCategory::Instructions,
            "int f(int (*fn)(int), int x) { return fn(x); }")
            .require("indirect call via function pointer", "call i32"),

        X86IRGenTest::new("ir_call_indirect_void", X86IRGenCategory::Instructions,
            "void f(void (*fn)(void)) { fn(); }")
            .require("indirect call void", "call void"),

        // ── Varargs call ──
        X86IRGenTest::new("ir_call_varargs", X86IRGenCategory::Instructions,
            "#include <stdarg.h>\nint f(int n, ...) { va_list ap; va_start(ap, n); int s = va_arg(ap, int); va_end(ap); return s; }")
            .require("varargs function definition", "va_start"),

        // ── Return value from call ──
        X86IRGenTest::new("ir_call_return_value", X86IRGenCategory::Instructions,
            "int g(void) { return 42; } int f(void) { return g(); }")
            .require("return from call result", "%call")
            .require("ret i32", "ret i32"),

        // ── Tail call ──
        X86IRGenTest::new("ir_call_tail_call", X86IRGenCategory::Instructions,
            "int g(int x); int f(int x) { return g(x); }")
            .with_opt(X86OptLevel::O2)
            .require("tail call optimization", "tail call"),

        // ── No-return call ──
        X86IRGenTest::new("ir_call_noreturn", X86IRGenCategory::Instructions,
            "void f(void) __attribute__((noreturn)); void g(void) { f(); __builtin_unreachable(); }")
            .require("call to noreturn", "call void"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// MEMORY ATTRIBUTE TESTS — aligned/unaligned, volatile, atomics
// ═══════════════════════════════════════════════════════════════════════════════

/// Build memory attribute IR tests: aligned load/store, volatile, atomics, fence.
pub fn build_memory_attr_tests() -> Vec<X86IRGenTest> {
    vec![
        // ── Aligned load/store ──
        X86IRGenTest::new("ir_mem_aligned_load", X86IRGenCategory::MemoryAccess,
            "int f(int *p) { return *p; }")
            .require("aligned load (default)", "align 4"),

        X86IRGenTest::new("ir_mem_aligned_store", X86IRGenCategory::MemoryAccess,
            "void f(int *p) { *p = 42; }")
            .require("aligned store (default)", "align 4"),

        X86IRGenTest::new("ir_mem_aligned_load_8", X86IRGenCategory::MemoryAccess,
            "double f(double *p) { return *p; }")
            .require("aligned load align 8", "align 8"),

        X86IRGenTest::new("ir_mem_aligned_load_1", X86IRGenCategory::MemoryAccess,
            "char f(char *p) { return *p; }")
            .require("aligned load align 1", "align 1"),

        // ── Unaligned load/store (packed) ──
        X86IRGenTest::new("ir_mem_unaligned_load", X86IRGenCategory::MemoryAccess,
            "struct __attribute__((packed)) S { int a; char b; }; int f(struct S *s) { return s->a; }")
            .require("unaligned load via packed struct", "load i32"),

        // ── Volatile load/store ──
        X86IRGenTest::new("ir_mem_volatile_load", X86IRGenCategory::MemoryAccess,
            "int f(volatile int *p) { return *p; }")
            .require("volatile load", "volatile"),

        X86IRGenTest::new("ir_mem_volatile_store", X86IRGenCategory::MemoryAccess,
            "void f(volatile int *p, int v) { *p = v; }")
            .require("volatile store", "volatile"),

        // ── Atomic load ──
        X86IRGenTest::new("ir_mem_atomic_load", X86IRGenCategory::Atomics,
            "#include <stdatomic.h>\nint f(_Atomic int *p) { return atomic_load(p); }")
            .require("atomic load", "load atomic"),

        // ── Atomic store ──
        X86IRGenTest::new("ir_mem_atomic_store", X86IRGenCategory::Atomics,
            "#include <stdatomic.h>\nvoid f(_Atomic int *p, int v) { atomic_store(p, v); }")
            .require("atomic store", "store atomic"),

        // ── Atomic exchange ──
        X86IRGenTest::new("ir_mem_atomic_xchg", X86IRGenCategory::Atomics,
            "#include <stdatomic.h>\nint f(_Atomic int *p, int v) { return atomic_exchange(p, v); }")
            .require("atomic exchange", "atomicrmw xchg"),

        // ── Atomic add ──
        X86IRGenTest::new("ir_mem_atomic_add", X86IRGenCategory::Atomics,
            "#include <stdatomic.h>\nint f(_Atomic int *p, int v) { return atomic_fetch_add(p, v); }")
            .require("atomic fetch add", "atomicrmw add"),

        // ── Atomic sub ──
        X86IRGenTest::new("ir_mem_atomic_sub", X86IRGenCategory::Atomics,
            "#include <stdatomic.h>\nint f(_Atomic int *p, int v) { return atomic_fetch_sub(p, v); }")
            .require("atomic fetch sub", "atomicrmw sub"),

        // ── Atomic cmp xchg ──
        X86IRGenTest::new("ir_mem_atomic_cmpxchg", X86IRGenCategory::Atomics,
            "#include <stdatomic.h>\nint f(_Atomic int *p, int expected, int desired) { atomic_compare_exchange_strong(p, &expected, desired); return expected; }")
            .require("cmpxchg instruction", "cmpxchg"),

        // ── Fence ──
        X86IRGenTest::new("ir_mem_fence", X86IRGenCategory::Atomics,
            "#include <stdatomic.h>\nvoid f(void) { atomic_thread_fence(memory_order_seq_cst); }")
            .require("fence instruction", "fence"),

        // ── Memory ordering ──
        X86IRGenTest::new("ir_mem_ordering_acquire", X86IRGenCategory::Atomics,
            "#include <stdatomic.h>\nint f(_Atomic int *p) { return atomic_load_explicit(p, memory_order_acquire); }")
            .require("acquire ordering", "acquire"),

        X86IRGenTest::new("ir_mem_ordering_release", X86IRGenCategory::Atomics,
            "#include <stdatomic.h>\nvoid f(_Atomic int *p, int v) { atomic_store_explicit(p, v, memory_order_release); }")
            .require("release ordering", "release"),

        X86IRGenTest::new("ir_mem_ordering_seq_cst", X86IRGenCategory::Atomics,
            "#include <stdatomic.h>\nint f(_Atomic int *p, int v) { return atomic_fetch_add_explicit(p, v, memory_order_seq_cst); }")
            .require("seq_cst ordering", "seq_cst"),

        X86IRGenTest::new("ir_mem_ordering_monotonic", X86IRGenCategory::Atomics,
            "#include <stdatomic.h>\nint f(_Atomic int *p) { return atomic_load_explicit(p, memory_order_relaxed); }")
            .require("relaxed/monotonic ordering", "monotonic"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// FUNCTION ATTRIBUTE TESTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Build function attribute IR tests.
pub fn build_function_attr_tests() -> Vec<X86IRGenTest> {
    vec![
        // ── nounwind ──
        X86IRGenTest::new("ir_attr_nounwind", X86IRGenCategory::FunctionAttributes,
            "int f(int x) __attribute__((nothrow)); int f(int x) { return x; }")
            .require("nounwind attribute", "nounwind"),

        // ── readonly ──
        X86IRGenTest::new("ir_attr_readonly", X86IRGenCategory::FunctionAttributes,
            "int f(const int *p) __attribute__((pure)); int f(const int *p) { return *p; }")
            .require("readonly attribute", "readonly"),

        // ── readnone ──
        X86IRGenTest::new("ir_attr_readnone", X86IRGenCategory::FunctionAttributes,
            "int f(int x) __attribute__((const)); int f(int x) { return x * 2; }")
            .require("readnone attribute", "readnone"),

        // ── noinline ──
        X86IRGenTest::new("ir_attr_noinline", X86IRGenCategory::FunctionAttributes,
            "int f(int x) __attribute__((noinline)); int f(int x) { return x; }")
            .require("noinline attribute in IR", "noinline"),

        // ── alwaysinline ──
        X86IRGenTest::new("ir_attr_alwaysinline", X86IRGenCategory::FunctionAttributes,
            "__attribute__((always_inline)) int f(int x) { return x; } int g(void) { return f(42); }")
            .require("alwaysinline attribute", "alwaysinline"),

        // ── optsize ──
        X86IRGenTest::new("ir_attr_optsize", X86IRGenCategory::FunctionAttributes,
            "int f(void) __attribute__((optimize(\"Os\"))); int f(void) { return 42; }")
            .require("optsize attribute for Os", "optsize"),

        // ── minsize ──
        X86IRGenTest::new("ir_attr_minsize", X86IRGenCategory::FunctionAttributes,
            "int f(void) __attribute__((optimize(\"Oz\"))); int f(void) { return 42; }")
            .require("minsize attribute for Oz", "minsize"),

        // ── ssp (stack protector) ──
        X86IRGenTest::new("ir_attr_ssp", X86IRGenCategory::FunctionAttributes,
            "void f(char *buf) { buf[0] = 'x'; }")
            .with_flags(vec!["-fstack-protector-strong"])
            .require("ssp attribute for stack protector", "sspstrong"),

        // ── sspreq ──
        X86IRGenTest::new("ir_attr_sspreq", X86IRGenCategory::FunctionAttributes,
            "void f(char *buf) { buf[0] = 'x'; }")
            .with_flags(vec!["-fstack-protector-all"])
            .require("sspreq attribute for stack protector all", "sspreq"),

        // ── uwtable ──
        X86IRGenTest::new("ir_attr_uwtable", X86IRGenCategory::FunctionAttributes,
            "void f(void) {}")
            .require("uwtable attribute", "uwtable"),

        // ── sanitize attributes ──
        X86IRGenTest::new("ir_attr_sanitize_address", X86IRGenCategory::FunctionAttributes,
            "int f(int *p) { return *p; }")
            .with_flags(vec!["-fsanitize=address"])
            .require("sanitize_address attribute", "sanitize_address"),

        X86IRGenTest::new("ir_attr_sanitize_memory", X86IRGenCategory::FunctionAttributes,
            "int f(int *p) { return *p; }")
            .with_flags(vec!["-fsanitize=memory"])
            .require("sanitize_memory attribute", "sanitize_memory"),

        X86IRGenTest::new("ir_attr_sanitize_thread", X86IRGenCategory::FunctionAttributes,
            "int f(int *p) { return *p; }")
            .with_flags(vec!["-fsanitize=thread"])
            .require("sanitize_thread attribute", "sanitize_thread"),

        X86IRGenTest::new("ir_attr_sanitize_undefined", X86IRGenCategory::FunctionAttributes,
            "int f(int x) { return x + 1; }")
            .with_flags(vec!["-fsanitize=undefined"])
            .require("sanitize function check", "llvm."),

        // ── noreturn ──
        X86IRGenTest::new("ir_attr_noreturn", X86IRGenCategory::FunctionAttributes,
            "void f(void) __attribute__((noreturn)); void f(void) { while(1); }")
            .require("noreturn attribute", "noreturn"),

        // ── cold ──
        X86IRGenTest::new("ir_attr_cold", X86IRGenCategory::FunctionAttributes,
            "void f(void) __attribute__((cold)); void f(void) {}")
            .require("cold attribute", "cold"),

        // ── hot ──
        X86IRGenTest::new("ir_attr_hot", X86IRGenCategory::FunctionAttributes,
            "void f(void) __attribute__((hot)); void f(void) {}")
            .require("hot attribute", "hot"),

        // ── returns_twice ──
        X86IRGenTest::new("ir_attr_returns_twice", X86IRGenCategory::FunctionAttributes,
            "int f(void) { return setjmp(0); }")
            .require("returns_twice on setjmp", "returns_twice"),

        // ── null_pointer_is_valid ──
        X86IRGenTest::new("ir_attr_nocapture", X86IRGenCategory::FunctionAttributes,
            "void f(int *__restrict p) { *p = 0; }")
            .require("noalias on restrict pointer", "noalias"),

        // ── optnone ──
        X86IRGenTest::new("ir_attr_optnone", X86IRGenCategory::FunctionAttributes,
            "int f(int x) __attribute__((optnone)); int f(int x) { return x; }")
            .require("optnone attribute", "optnone"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// PARAMETER ATTRIBUTE TESTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Build parameter attribute IR tests.
pub fn build_param_attr_tests() -> Vec<X86IRGenTest> {
    vec![
        // ── zeroext ──
        X86IRGenTest::new("ir_param_zeroext_i1", X86IRGenCategory::ParameterAttributes,
            "_Bool f(_Bool x) { return x; }")
            .require("zeroext for i1", "zeroext"),

        X86IRGenTest::new("ir_param_zeroext_i8", X86IRGenCategory::ParameterAttributes,
            "unsigned char f(unsigned char c) { return c; }")
            .require("zeroext for unsigned char", "zeroext"),

        X86IRGenTest::new("ir_param_zeroext_i16", X86IRGenCategory::ParameterAttributes,
            "unsigned short f(unsigned short s) { return s; }")
            .require("zeroext for unsigned short", "zeroext"),

        // ── signext ──
        X86IRGenTest::new("ir_param_signext_i8", X86IRGenCategory::ParameterAttributes,
            "signed char f(signed char c) { return c; }")
            .require("signext for signed char", "signext"),

        X86IRGenTest::new("ir_param_signext_i16", X86IRGenCategory::ParameterAttributes,
            "short f(short s) { return s; }")
            .require("signext for short", "signext"),

        // ── noalias ──
        X86IRGenTest::new("ir_param_noalias_restrict", X86IRGenCategory::ParameterAttributes,
            "void f(int *__restrict p, int *__restrict q) { *p = *q; }")
            .require("noalias on restrict pointer", "noalias"),

        // ── sret ──
        X86IRGenTest::new("ir_param_sret_large_struct", X86IRGenCategory::ParameterAttributes,
            "struct Large { int a; int b; int c; int d; int e; }; struct Large f(void) { struct Large x = {0}; return x; }")
            .require("sret parameter for large struct return", "sret"),

        // ── byval ──
        X86IRGenTest::new("ir_param_byval_struct", X86IRGenCategory::ParameterAttributes,
            "struct S { int a; double b; }; double f(struct S s) { return s.b; }")
            .require("byval for passed struct", "byval"),

        // ── inreg ──
        X86IRGenTest::new("ir_param_inreg", X86IRGenCategory::ParameterAttributes,
            "void f(int x __attribute__((regparm(3))), int y) {}")
            .require("inreg attribute", "inreg"),

        // ── nest ──
        X86IRGenTest::new("ir_param_nest", X86IRGenCategory::ParameterAttributes,
            "void f(void) { int x; void g(int *p) { *p = 1; } g(&x); }")
            .require("nest attribute or alloca for captured var", "alloca"),

        // ── align ──
        X86IRGenTest::new("ir_param_align", X86IRGenCategory::ParameterAttributes,
            "void f(double *p __attribute__((align_value(64)))) { *p = 0.0; }")
            .require("align attribute on param", "align"),

        // ── dereferenceable ──
        X86IRGenTest::new("ir_param_dereferenceable", X86IRGenCategory::ParameterAttributes,
            "int f(int *p) { return *p; }")
            .require("dereferenceable on pointer", "dereferenceable"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// LINKAGE TYPE TESTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Build linkage type IR tests.
pub fn build_linkage_tests() -> Vec<X86IRGenTest> {
    vec![
        // ── external (default) ──
        X86IRGenTest::new("ir_linkage_external", X86IRGenCategory::Linkage,
            "int f(int x) { return x; }")
            .require("define dso_local with external linkage", "define"),

        // ── private ──
        X86IRGenTest::new("ir_linkage_private_static", X86IRGenCategory::Linkage,
            "static int f(int x) { return x; }")
            .require("private/internal linkage for static", "internal"),

        // ── internal ──
        X86IRGenTest::new("ir_linkage_internal_anon", X86IRGenCategory::Linkage,
            "static int g(void) { return 42; } int f(void) { return g(); }")
            .require("internal linkage for static function", "internal"),

        // ── linkonce_odr ──
        X86IRGenTest::new("ir_linkage_inline", X86IRGenCategory::Linkage,
            "inline int f(int x) { return x; }")
            .require("linkonce_odr for inline", "linkonce_odr"),

        // ── weak ──
        X86IRGenTest::new("ir_linkage_weak", X86IRGenCategory::Linkage,
            "int f(int x) __attribute__((weak)); int f(int x) { return x; }")
            .require("weak linkage", "weak"),

        // ── weak_odr ──
        X86IRGenTest::new("ir_linkage_weak_odr", X86IRGenCategory::Linkage,
            "inline __attribute__((weak)) int f(int x) { return x; }")
            .require("weak_odr linkage", "weak_odr"),

        // ── available_externally ──
        X86IRGenTest::new("ir_linkage_available_externally", X86IRGenCategory::Linkage,
            "extern inline int f(int x) { return x; } int g(void) { return f(42); }")
            .require("available_externally", "available_externally"),

        // ── linkonce ──
        X86IRGenTest::new("ir_linkage_linkonce", X86IRGenCategory::Linkage,
            "inline int f(void) { static int x = 0; return x++; }")
            .require("linkonce linkage for inline", "linkonce"),

        // ── extern_weak ──
        X86IRGenTest::new("ir_linkage_extern_weak", X86IRGenCategory::Linkage,
            "extern int f(int x) __attribute__((weak)); int g(void) { if (f) return f(1); return 0; }")
            .require("extern_weak linkage", "extern_weak"),

        // ── common ──
        X86IRGenTest::new("ir_linkage_common", X86IRGenCategory::Linkage,
            "int x; int f(void) { return x; }")
            .require("common linkage for tentative def", "common"),

        // ── appending ──
        X86IRGenTest::new("ir_linkage_appending", X86IRGenCategory::Linkage,
            "struct S { int x; }; struct S s __attribute__((section(\".data\"))) = {42};")
            .require("global with section attribute", "@s"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// VISIBILITY TESTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Build visibility IR tests.
pub fn build_visibility_tests() -> Vec<X86IRGenTest> {
    vec![
        // ── default visibility ──
        X86IRGenTest::new(
            "ir_vis_default",
            X86IRGenCategory::Visibility,
            "int f(int x) { return x; }",
        )
        .require("default visibility (no hidden/protected)", "define"),
        // ── hidden visibility ──
        X86IRGenTest::new(
            "ir_vis_hidden",
            X86IRGenCategory::Visibility,
            "int f(int x) __attribute__((visibility(\"hidden\"))); int f(int x) { return x; }",
        )
        .require("hidden visibility", "hidden"),
        // ── protected visibility ──
        X86IRGenTest::new(
            "ir_vis_protected",
            X86IRGenCategory::Visibility,
            "int f(int x) __attribute__((visibility(\"protected\"))); int f(int x) { return x; }",
        )
        .require("protected visibility", "protected"),
        // ── hidden on global variable ──
        X86IRGenTest::new(
            "ir_vis_hidden_global",
            X86IRGenCategory::Visibility,
            "int x __attribute__((visibility(\"hidden\"))) = 42;",
        )
        .require("hidden visibility on global", "hidden"),
        // ── protected on global variable ──
        X86IRGenTest::new(
            "ir_vis_protected_global",
            X86IRGenCategory::Visibility,
            "int x __attribute__((visibility(\"protected\"))) = 42;",
        )
        .require("protected visibility on global", "protected"),
        // ── -fvisibility=hidden flag ──
        X86IRGenTest::new(
            "ir_vis_fvisibility_hidden",
            X86IRGenCategory::Visibility,
            "int f(int x) { return x; }",
        )
        .with_flags(vec!["-fvisibility=hidden"])
        .require("hidden visibility via flag", "hidden"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// CALLING CONVENTION TESTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Build calling convention IR tests.
pub fn build_calling_convention_tests() -> Vec<X86IRGenTest> {
    vec![
        // ── ccc (C calling convention) ──
        X86IRGenTest::new("ir_cc_ccc", X86IRGenCategory::CallingConvention,
            "int f(int x) { return x; }")
            .require("C calling convention ccc", "ccc"),

        // ── fastcc ──
        X86IRGenTest::new("ir_cc_fastcc", X86IRGenCategory::CallingConvention,
            "int f(int x) __attribute__((fastcall)); int f(int x) { return x; }")
            .require("fastcc calling convention", "fastcc"),

        // ── coldcc ──
        X86IRGenTest::new("ir_cc_coldcc", X86IRGenCategory::CallingConvention,
            "void f(void) __attribute__((cold)); void f(void) {}")
            .require("coldcc calling convention", "coldcc"),

        // ── x86_stdcallcc ──
        X86IRGenTest::new("ir_cc_x86_stdcallcc", X86IRGenCategory::CallingConvention,
            "int f(int x) __attribute__((stdcall)); int f(int x) { return x; }")
            .with_target("i686-unknown-linux-gnu")
            .require("x86_stdcallcc calling convention", "x86_stdcallcc"),

        // ── x86_fastcallcc ──
        X86IRGenTest::new("ir_cc_x86_fastcallcc", X86IRGenCategory::CallingConvention,
            "int f(int a, int b) __attribute__((fastcall)); int f(int a, int b) { return a + b; }")
            .with_target("i686-unknown-linux-gnu")
            .require("x86_fastcallcc calling convention", "x86_fastcallcc"),

        // ── x86_thiscallcc ──
        X86IRGenTest::new("ir_cc_x86_thiscallcc", X86IRGenCategory::CallingConvention,
            "struct S { int x; int f(int a) __attribute__((thiscall)); }; int S::f(int a) { return x + a; }")
            .with_target("i686-unknown-linux-gnu")
            .require("x86_thiscallcc calling convention", "x86_thiscallcc"),

        // ── x86_vectorcallcc ──
        X86IRGenTest::new("ir_cc_x86_vectorcallcc", X86IRGenCategory::CallingConvention,
            "int f(int a, double b) __attribute__((vectorcall)); int f(int a, double b) { return a; }")
            .require("x86_vectorcallcc calling convention", "x86_vectorcallcc"),

        // ── x86_regcallcc ──
        X86IRGenTest::new("ir_cc_x86_regcallcc", X86IRGenCategory::CallingConvention,
            "int f(int a, int b, int c) __attribute__((regcall)); int f(int a, int b, int c) { return a + b + c; }")
            .require("x86_regcallcc calling convention", "x86_regcallcc"),

        // ── Additional calling convention tests ──
        X86IRGenTest::new("ir_cc_preserve_all", X86IRGenCategory::CallingConvention,
            "void f(void) __attribute__((preserve_all)); void f(void) {}")
            .require("preserve_all calling convention", "preserve_allcc"),

        X86IRGenTest::new("ir_cc_preserve_most", X86IRGenCategory::CallingConvention,
            "void f(void) __attribute__((preserve_most)); void f(void) {}")
            .require("preserve_most calling convention", "preserve_mostcc"),

        X86IRGenTest::new("ir_cc_webkit_js", X86IRGenCategory::CallingConvention,
            "void f(void) __attribute__((regparm(1))); void f(void) {}")
            .require("regparm affects CC", "regparm"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// DEBUG INFO TESTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Build debug information IR tests.
pub fn build_debug_info_tests() -> Vec<X86IRGenTest> {
    vec![
        X86IRGenTest::new(
            "ir_debug_compile_unit",
            X86IRGenCategory::DebugInfo,
            "int f(int x) { return x; }",
        )
        .with_flags(vec!["-g"])
        .require("DICompileUnit metadata", "DICompileUnit"),
        X86IRGenTest::new(
            "ir_debug_subprogram",
            X86IRGenCategory::DebugInfo,
            "int f(int x) { return x; }",
        )
        .with_flags(vec!["-g"])
        .require("DISubprogram metadata", "DISubprogram"),
        X86IRGenTest::new(
            "ir_debug_file",
            X86IRGenCategory::DebugInfo,
            "int f(int x) { return x; }",
        )
        .with_flags(vec!["-g"])
        .require("DIFile metadata", "DIFile"),
        X86IRGenTest::new(
            "ir_debug_lexical_block",
            X86IRGenCategory::DebugInfo,
            "int f(int x) { { int y = x; return y; } }",
        )
        .with_flags(vec!["-g"])
        .require("DILexicalBlock metadata", "DILexicalBlock"),
        X86IRGenTest::new(
            "ir_debug_local_variable",
            X86IRGenCategory::DebugInfo,
            "int f(int x) { int y = x + 1; return y; }",
        )
        .with_flags(vec!["-g"])
        .require("DILocalVariable metadata", "DILocalVariable"),
        X86IRGenTest::new(
            "ir_debug_location",
            X86IRGenCategory::DebugInfo,
            "int f(int x) { return x; }",
        )
        .with_flags(vec!["-g"])
        .require("!dbg location", "!dbg"),
        X86IRGenTest::new(
            "ir_debug_declare",
            X86IRGenCategory::DebugInfo,
            "int f(void) { int x = 0; return x; }",
        )
        .with_flags(vec!["-g"])
        .require("llvm.dbg.declare", "llvm.dbg.declare"),
        X86IRGenTest::new(
            "ir_debug_value",
            X86IRGenCategory::DebugInfo,
            "int f(int x) { x = x + 1; return x; }",
        )
        .with_flags(vec!["-g"])
        .require("llvm.dbg.value", "llvm.dbg.value"),
        X86IRGenTest::new(
            "ir_debug_type_basic",
            X86IRGenCategory::DebugInfo,
            "int f(int x) { return x; }",
        )
        .with_flags(vec!["-g"])
        .require("DIBasicType metadata", "DIBasicType"),
        X86IRGenTest::new(
            "ir_debug_derived_type",
            X86IRGenCategory::DebugInfo,
            "int f(int *p) { return *p; }",
        )
        .with_flags(vec!["-g"])
        .require("DIDerivedType for pointer", "DIDerivedType"),
        X86IRGenTest::new(
            "ir_debug_composite_type_struct",
            X86IRGenCategory::DebugInfo,
            "struct S { int a; }; int f(struct S s) { return s.a; }",
        )
        .with_flags(vec!["-g"])
        .require("DICompositeType for struct", "DICompositeType"),
        X86IRGenTest::new(
            "ir_debug_global_variable",
            X86IRGenCategory::DebugInfo,
            "int x = 42; int f(void) { return x; }",
        )
        .with_flags(vec!["-g"])
        .require("DIGlobalVariable metadata", "DIGlobalVariable"),
        X86IRGenTest::new(
            "ir_debug_no_debug_info_without_g",
            X86IRGenCategory::DebugInfo,
            "int f(int x) { return x; }",
        )
        .forbid("no debug metadata without -g", "DIFile"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// OPTIMIZATION PIPELINE TESTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Build optimization pipeline IR tests.
pub fn build_optimization_tests() -> Vec<X86IRGenTest> {
    vec![
        X86IRGenTest::new(
            "ir_opt_O0_no_opt",
            X86IRGenCategory::Optimization,
            "int f(int a, int b) { return a + b; }",
        )
        .with_opt(X86OptLevel::O0)
        .require("alloca at O0 for local var", "alloca")
        .forbid("no mem2reg at O0", "!tbaa"),
        X86IRGenTest::new(
            "ir_opt_O1_mem2reg",
            X86IRGenCategory::Optimization,
            "int f(int a, int b) { int x = a; int y = b; return x + y; }",
        )
        .with_opt(X86OptLevel::O1)
        .require("add instruction preserved", "add i32"),
        X86IRGenTest::new(
            "ir_opt_O2_vectorization",
            X86IRGenCategory::Optimization,
            "void f(int *a, int *b, int n) { for (int i = 0; i < n; i++) a[i] = b[i] + 1; }",
        )
        .with_opt(X86OptLevel::O2)
        .require("loop at O2", "br"),
        X86IRGenTest::new(
            "ir_opt_constant_propagation",
            X86IRGenCategory::Optimization,
            "int f(void) { return 2 + 3 * 4; }",
        )
        .with_opt(X86OptLevel::O1)
        .require("constant folded at O1", "ret i32 14"),
        X86IRGenTest::new(
            "ir_opt_dead_code_elimination",
            X86IRGenCategory::Optimization,
            "int f(int x) { int y = x * 2; return x + 1; }",
        )
        .with_opt(X86OptLevel::O1)
        .require("return dominate value", "ret i32"),
        X86IRGenTest::new(
            "ir_opt_inlining",
            X86IRGenCategory::Optimization,
            "static int g(int x) { return x * 2; } int f(int a) { return g(a) + g(1); }",
        )
        .with_opt(X86OptLevel::O1)
        .require("inlined at O1 (no call to g)", "add"),
        X86IRGenTest::new(
            "ir_opt_simplify_cfg",
            X86IRGenCategory::Optimization,
            "int f(int x) { if (x) { return 1; } else { return 0; } }",
        )
        .with_opt(X86OptLevel::O1)
        .require("select instruction after simplifycfg", "select i32"),
        X86IRGenTest::new(
            "ir_opt_loop_unroll",
            X86IRGenCategory::Optimization,
            "int f(void) { int s = 0; for (int i = 0; i < 4; i++) s += i; return s; }",
        )
        .with_opt(X86OptLevel::O2)
        .require("loop unrolled or simplified", "ret i32 6"),
        X86IRGenTest::new(
            "ir_opt_gvn",
            X86IRGenCategory::Optimization,
            "int f(int *p, int *q) { return *p + *p; }",
        )
        .with_opt(X86OptLevel::O1)
        .require("common load elimination", "load i32"),
        X86IRGenTest::new(
            "ir_opt_sroa",
            X86IRGenCategory::Optimization,
            "struct S { int a; int b; }; int f(struct S s) { return s.a + s.b; }",
        )
        .with_opt(X86OptLevel::O1)
        .require("scalar replacement of aggregate", "add i32"),
        X86IRGenTest::new(
            "ir_opt_loop_rotation",
            X86IRGenCategory::Optimization,
            "int f(int n) { int s = 0; for (int i = 0; i < n; i++) s += i; return s; }",
        )
        .with_opt(X86OptLevel::O2)
        .require("loop at O2", "br"),
        X86IRGenTest::new(
            "ir_opt_licm",
            X86IRGenCategory::Optimization,
            "int f(int *p, int n) { int s = 0; for (int i = 0; i < n; i++) s += *p; return s; }",
        )
        .with_opt(X86OptLevel::O2)
        .require("load hoisted out of loop at O2", "load"),
        X86IRGenTest::new(
            "ir_opt_indvar_simplify",
            X86IRGenCategory::Optimization,
            "int f(int n) { int s = 0; for (int i = 0; i < n; i++) s += i * 4; return s; }",
        )
        .with_opt(X86OptLevel::O1)
        .require("induction variable simplification", "add"),
        X86IRGenTest::new(
            "ir_opt_tail_call",
            X86IRGenCategory::Optimization,
            "int g(int x); int f(int x) { return g(x); }",
        )
        .with_opt(X86OptLevel::O2)
        .require("tail call optimization at O2", "tail call"),
        X86IRGenTest::new(
            "ir_opt_sink",
            X86IRGenCategory::Optimization,
            "int f(int x, int y) { int a = x * 2; if (y) return a; else return 0; }",
        )
        .with_opt(X86OptLevel::O1)
        .require("expression sinking or hoisting", "mul i32"),
        X86IRGenTest::new(
            "ir_opt_Os_size",
            X86IRGenCategory::Optimization,
            "int f(int a, int b) { return a + b; }",
        )
        .with_flags(vec!["-Os"])
        .require("optsize attribute at Os", "optsize"),
        X86IRGenTest::new(
            "ir_opt_Oz_size",
            X86IRGenCategory::Optimization,
            "int f(int a, int b) { return a + b; }",
        )
        .with_flags(vec!["-Oz"])
        .require("minsize attribute at Oz", "minsize"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// ROUNDTRIP VERIFICATION TESTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Build roundtrip verification tests: compile to IR, serialize, re-parse, re-compile.
#[derive(Debug, Clone)]
pub struct RoundtripTest {
    pub name: String,
    pub source: String,
    pub ir_stable_across_roundtrip: bool,
}

impl RoundtripTest {
    pub fn new(name: &str, source: &str) -> Self {
        Self {
            name: name.to_string(),
            source: source.to_string(),
            ir_stable_across_roundtrip: true,
        }
    }
}

/// Get all roundtrip verification test cases.
pub fn build_roundtrip_tests() -> Vec<RoundtripTest> {
    vec![
    RoundtripTest::new("rt_int_return", "int f() { return 42; }"),
    RoundtripTest::new("rt_float_add", "float f(float a, float b) { return a + b; }"),
    RoundtripTest::new("rt_double_mul", "double f(double a, double b) { return a * b; }"),
    RoundtripTest::new("rt_struct_pass", "struct S { int a; double b; }; double f(struct S s) { return s.b; }"),
    RoundtripTest::new("rt_pointer_deref", "int f(int *p) { return *p; }"),
    RoundtripTest::new("rt_array_access", "int f(int arr[10]) { return arr[5]; }"),
    RoundtripTest::new("rt_conditional", "int f(int x) { return x ? 1 : 0; }"),
    RoundtripTest::new("rt_loop", "int f(int n) { int s = 0; for(int i=0;i<n;i++) s+=i; return s; }"),
    RoundtripTest::new("rt_switch", "int f(int x) { switch(x) { case 1: return 10; default: return 0; } }"),
    RoundtripTest::new("rt_recursive", "int f(int n) { if(n<=1) return 1; return n*f(n-1); }"),
    RoundtripTest::new("rt_void_func", "void f() {}"),
    RoundtripTest::new("rt_global_var", "int x = 42; int f() { return x; }"),
    RoundtripTest::new("rt_static_local", "int f() { static int x = 0; return x++; }"),
    RoundtripTest::new("rt_bitwise", "int f(int a, int b) { return (a & b) | (a ^ b); }"),
    RoundtripTest::new("rt_shift", "int f(int a) { return (a << 2) | (a >> 3); }"),
    RoundtripTest::new("rt_vector_add", "typedef int v4si __attribute__((vector_size(16))); v4si f(v4si a, v4si b) { return a + b; }"),
    RoundtripTest::new("rt_compound_literal", "struct S { int a; }; struct S f() { return (struct S){42}; }"),
    RoundtripTest::new("rt_inline_func", "inline int add(int a, int b) { return a + b; } int f(int x, int y) { return add(x, y); }"),
    RoundtripTest::new("rt_volatile", "int f(volatile int *p) { return *p; }"),
    RoundtripTest::new("rt_cast_chain", "double f(int x) { return (double)(float)x; }"),
]
}

// ═══════════════════════════════════════════════════════════════════════════════
// DIFFERENTIAL TEST SUITE
// ═══════════════════════════════════════════════════════════════════════════════

/// A differential test case that compares Clang IR output between two optimization
/// levels or flags, ensuring correctness is preserved.
#[derive(Debug, Clone)]
pub struct DifferentialIRTest {
    pub name: String,
    pub source: String,
    pub baseline_flags: Vec<String>,
    pub compare_flags: Vec<String>,
    pub allow_different_ir: bool,
}

impl DifferentialIRTest {
    pub fn new(name: &str, source: &str) -> Self {
        Self {
            name: name.to_string(),
            source: source.to_string(),
            baseline_flags: vec!["-O0".to_string()],
            compare_flags: vec!["-O2".to_string()],
            allow_different_ir: true,
        }
    }

    pub fn with_baseline(mut self, flags: Vec<&str>) -> Self {
        self.baseline_flags = flags.into_iter().map(String::from).collect();
        self
    }

    pub fn with_compare(mut self, flags: Vec<&str>) -> Self {
        self.compare_flags = flags.into_iter().map(String::from).collect();
        self
    }
}

/// Build differential IR test cases.
pub fn build_differential_tests() -> Vec<DifferentialIRTest> {
    vec![
        DifferentialIRTest::new(
            "diff_O0_vs_O2_simple",
            "int f(int a, int b) { return a + b; }",
        )
        .with_baseline(vec!["-O0"])
        .with_compare(vec!["-O2"]),
        DifferentialIRTest::new(
            "diff_O0_vs_O2_struct",
            "struct S { int a; int b; }; int f(struct S s) { return s.a + s.b; }",
        )
        .with_baseline(vec!["-O0"])
        .with_compare(vec!["-O2"]),
        DifferentialIRTest::new(
            "diff_O0_vs_O2_loop",
            "int f(int n) { int s = 0; for(int i=0;i<n;i++) s+=i; return s; }",
        )
        .with_baseline(vec!["-O0"])
        .with_compare(vec!["-O2"]),
        DifferentialIRTest::new(
            "diff_O0_vs_Os",
            "int f(int n) { if (n) return 1; return 0; }",
        )
        .with_baseline(vec!["-O0"])
        .with_compare(vec!["-Os"]),
        DifferentialIRTest::new(
            "diff_sse_vs_sse2",
            "#include <xmmintrin.h>\n__m128 f(__m128 a, __m128 b) { return _mm_add_ps(a, b); }",
        )
        .with_baseline(vec!["-msse"])
        .with_compare(vec!["-msse2"]),
        DifferentialIRTest::new("diff_32bit_vs_64bit", "long f(long x) { return x * 2; }")
            .with_baseline(vec!["-m32"])
            .with_compare(vec!["-m64"]),
        DifferentialIRTest::new("diff_no_sanitize_vs_asan", "int f(int *p) { return *p; }")
            .with_baseline(vec!["-O0"])
            .with_compare(vec!["-O0", "-fsanitize=address"]),
        DifferentialIRTest::new(
            "diff_no_sanitize_vs_ubsan",
            "int f(int x) { return x + 1; }",
        )
        .with_baseline(vec!["-O0"])
        .with_compare(vec!["-O0", "-fsanitize=undefined"]),
        DifferentialIRTest::new(
            "diff_indirect_call",
            "int f(int (*fn)(int), int x) { return fn(x); }",
        )
        .with_baseline(vec!["-O0"])
        .with_compare(vec!["-O2"]),
        DifferentialIRTest::new(
            "diff_memset_vs_loop",
            "void f(char *p, int n) { for (int i=0; i<n; i++) p[i]=0; }",
        )
        .with_baseline(vec!["-O0"])
        .with_compare(vec!["-O2"]),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// REGRESSION TEST INFRASTRUCTURE
// ═══════════════════════════════════════════════════════════════════════════════

/// A regression test case capturing a known issue with expected behavior.
#[derive(Debug, Clone)]
pub struct RegressionTestCase {
    /// Unique identifier for this regression.
    pub id: String,
    /// Human-readable description.
    pub description: String,
    /// The C/C++ source that triggers or tests the issue.
    pub source: String,
    /// Pattern that must be found in the IR for the test to pass.
    pub expected_ir: Vec<X86IRPattern>,
    /// Pattern that must NOT be found.
    pub forbidden_ir: Vec<X86IRPattern>,
    /// Date when the regression was added.
    pub date_added: String,
    /// Reference to issue tracker or PR.
    pub issue_ref: Option<String>,
    /// Whether this regression is currently fixed (passes).
    pub is_fixed: bool,
}

impl RegressionTestCase {
    pub fn new(id: &str, desc: &str, source: &str) -> Self {
        Self {
            id: id.to_string(),
            description: desc.to_string(),
            source: source.to_string(),
            expected_ir: Vec::new(),
            forbidden_ir: Vec::new(),
            date_added: String::new(),
            issue_ref: None,
            is_fixed: false,
        }
    }

    pub fn with_expected(mut self, desc: &str, pat: &str) -> Self {
        self.expected_ir.push(X86IRPattern::required(desc, pat));
        self
    }

    pub fn with_forbidden(mut self, desc: &str, pat: &str) -> Self {
        self.forbidden_ir.push(X86IRPattern::forbidden(desc, pat));
        self
    }

    pub fn with_date(mut self, date: &str) -> Self {
        self.date_added = date.to_string();
        self
    }

    pub fn with_issue(mut self, issue: &str) -> Self {
        self.issue_ref = Some(issue.to_string());
        self
    }

    pub fn fixed(mut self) -> Self {
        self.is_fixed = true;
        self
    }
}

/// Registry of IR generation regression tests.
#[derive(Debug, Clone, Default)]
pub struct RegressionRegistry {
    pub tests: Vec<RegressionTestCase>,
}

impl RegressionRegistry {
    pub fn new() -> Self {
        Self { tests: Vec::new() }
    }

    pub fn register(&mut self, test: RegressionTestCase) {
        self.tests.push(test);
    }

    pub fn count(&self) -> usize {
        self.tests.len()
    }

    pub fn fixed_count(&self) -> usize {
        self.tests.iter().filter(|t| t.is_fixed).count()
    }

    pub fn open_count(&self) -> usize {
        self.tests.iter().filter(|t| !t.is_fixed).count()
    }

    pub fn by_id(&self, id: &str) -> Option<&RegressionTestCase> {
        self.tests.iter().find(|t| t.id == id)
    }
}

/// Build the standard regression test registry.
pub fn build_regression_registry() -> RegressionRegistry {
    let mut registry = RegressionRegistry::new();

    registry.register(RegressionTestCase::new(
    "REG-001", "Struct field offset computation for packed structs",
    "struct __attribute__((packed)) S { char a; int b; }; int f(struct S *s) { return s->b; }"
).with_expected("GEP for packed struct field", "getelementptr")
 .with_date("2025-01-15")
 .with_issue("GH-1234"));

    registry.register(
        RegressionTestCase::new(
            "REG-002",
            "VLA sizeof computation",
            "#include <stddef.h>\nsize_t f(int n) { int arr[n]; return sizeof(arr); }",
        )
        .with_expected("VLA sizeof", "alloca")
        .with_date("2025-02-10")
        .with_issue("GH-1267"),
    );

    registry.register(
        RegressionTestCase::new(
            "REG-003",
            "Long double return on x86",
            "long double f(void) { return 3.14159265358979323846L; }",
        )
        .with_expected("x86_fp80 type for long double", "x86_fp80")
        .with_date("2025-03-05")
        .with_issue("GH-1298")
        .fixed(),
    );

    registry.register(
        RegressionTestCase::new(
            "REG-004",
            "Bitfield sign extension",
            "struct S { signed int a: 3; }; int f(struct S s) { return s.a; }",
        )
        .with_expected("sign extension for signed bitfield", "sext")
        .with_date("2025-04-01")
        .with_issue("GH-1342")
        .fixed(),
    );

    registry.register(RegressionTestCase::new(
    "REG-005", "Atomic cmpxchg weak lowering",
    "#include <stdatomic.h>\nint f(_Atomic int *p, int e, int d) { atomic_compare_exchange_weak(p, &e, d); return e; }"
).with_expected("cmpxchg weak", "cmpxchg weak")
 .with_date("2025-05-15")
 .with_issue("GH-1399"));

    registry.register(RegressionTestCase::new(
    "REG-006", "Nested lambda capture",
    "int f(int x) { auto outer = [x](int y) { return [x, y](int z) { return x + y + z; }; }; return outer(2)(3); }"
).with_expected("nested lambda", "call")
 .with_date("2025-06-01")
 .with_issue("GH-1450"));

    registry.register(
        RegressionTestCase::new(
            "REG-007",
            "Flexible array member offset",
            "struct S { int n; char data[]; }; size_t f(void) { return offsetof(struct S, data); }",
        )
        .with_expected("offsetof for flex array", "ret i64 4")
        .with_date("2025-06-20")
        .with_issue("GH-1488")
        .fixed(),
    );

    registry.register(RegressionTestCase::new(
    "REG-008", "Inline asm with multiple outputs",
    "void f(int *a, int *b) { __asm__(\"mov %1, %0\" : \"=r\"(*a), \"=r\"(*b) : \"r\"(*a)); }"
).with_expected("multiple asm outputs", "call void asm")
 .with_date("2025-07-10")
 .with_issue("GH-1520"));

    registry.register(
        RegressionTestCase::new(
            "REG-009",
            "Static local with non-trivial dtor",
            "struct S { ~S() {} }; S *f() { static S s; return &s; }",
        )
        .with_expected("guard variable", "guard")
        .with_date("2025-08-05")
        .with_issue("GH-1567"),
    );

    registry.register(RegressionTestCase::new(
    "REG-010", "Vector shuffle for SSE psrldq",
    "typedef char v16qi __attribute__((vector_size(16))); v16qi f(v16qi a) { return __builtin_shufflevector(a, a, 4,5,6,7,8,9,10,11,12,13,14,15,-1,-1,-1,-1); }"
).with_expected("shufflevector with undef", "shufflevector")
 .with_date("2025-09-01")
 .with_issue("GH-1600"));

    registry
}

// ═══════════════════════════════════════════════════════════════════════════════
// DELTA DEBUGGING / TEST CASE MINIMIZATION
// ═══════════════════════════════════════════════════════════════════════════════

/// Delta debugger for minimizing IR generation test cases.
/// Reduces a failing C/C++ source to a minimal reproducer while
/// preserving the interesting property (e.g., crash or incorrect IR).
#[derive(Debug, Clone)]
pub struct IRDeltaDebugger {
    /// Original full source.
    pub original: String,
    /// Current minimized source.
    pub current: String,
    /// Number of minimization iterations performed.
    pub iterations: usize,
    /// Granularity of minimization (how many chunks to split into).
    pub granularity: usize,
}

impl IRDeltaDebugger {
    /// Create a new delta debugger from a source string.
    pub fn new(source: &str) -> Self {
        Self {
            original: source.to_string(),
            current: source.to_string(),
            iterations: 0,
            granularity: 2,
        }
    }

    /// Set the minimization granularity.
    pub fn with_granularity(mut self, n: usize) -> Self {
        self.granularity = n.max(2);
        self
    }

    /// Minimize by lines: try removing blocks of lines while preserving
    /// the interesting property.
    pub fn minimize_lines<F>(&mut self, is_interesting: F) -> &str
    where
        F: Fn(&str) -> bool,
    {
        let lines: Vec<&str> = self.current.lines().collect();
        let total = lines.len();
        if total == 0 {
            return &self.current;
        }

        let mut chunk_size = total / self.granularity;
        if chunk_size == 0 {
            chunk_size = 1;
        }

        while chunk_size > 0 {
            let mut i = 0;
            while i + chunk_size <= lines.len() {
                self.iterations += 1;
                // Try removing chunk [i, i+chunk_size)
                let reduced: Vec<&str> = lines[..i]
                    .iter()
                    .chain(lines[i + chunk_size..].iter())
                    .copied()
                    .collect();
                let candidate = reduced.join("\n");
                if is_interesting(&candidate) {
                    // Reduction successful: accept and restart
                    self.current = candidate;
                    return self.minimize_lines(is_interesting);
                }
                i += chunk_size;
            }
            chunk_size /= 2;
        }

        &self.current
    }

    /// Minimize by characters (coarse).
    pub fn minimize_chars<F>(&mut self, is_interesting: F) -> &str
    where
        F: Fn(&str) -> bool,
    {
        let chars: Vec<char> = self.current.chars().collect();
        let total = chars.len();
        if total == 0 {
            return &self.current;
        }

        let mut chunk_size = total / self.granularity;
        if chunk_size == 0 {
            chunk_size = 1;
        }

        while chunk_size > 0 {
            let mut i = 0;
            while i + chunk_size <= chars.len() {
                self.iterations += 1;
                let reduced: String = chars[..i]
                    .iter()
                    .chain(chars[i + chunk_size..].iter())
                    .collect();
                if is_interesting(&reduced) {
                    self.current = reduced;
                    return self.minimize_chars(is_interesting);
                }
                i += chunk_size;
            }
            chunk_size /= 2;
        }

        &self.current
    }

    /// Get reduction statistics.
    pub fn stats(&self) -> String {
        format!(
            "Original: {} bytes → Reduced: {} bytes ({:.1}% reduction, {} iterations)",
            self.original.len(),
            self.current.len(),
            (1.0 - self.current.len() as f64 / self.original.len().max(1) as f64) * 100.0,
            self.iterations
        )
    }

    /// Get the reduction ratio.
    pub fn reduction_ratio(&self) -> f64 {
        if self.original.is_empty() {
            return 0.0;
        }
        self.current.len() as f64 / self.original.len() as f64
    }

    /// Reset to the original source.
    pub fn reset(&mut self) {
        self.current = self.original.clone();
        self.iterations = 0;
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// X86 INTRINSIC CATALOG
// ═══════════════════════════════════════════════════════════════════════════════

/// Descriptor for an X86 intrinsic mapping: C builtin → LLVM IR intrinsic.
#[derive(Debug, Clone)]
pub struct X86IntrinsicMapping {
    /// The C intrinsic name (e.g., "_mm_add_ps").
    pub c_name: String,
    /// The corresponding LLVM intrinsic (e.g., "llvm.x86.sse.add.ps").
    pub llvm_intrinsic: String,
    /// The instruction set extension (SSE, SSE2, AVX, etc.).
    pub isa_extension: String,
    /// Required header file.
    pub header: String,
    /// Brief description.
    pub description: String,
}

impl X86IntrinsicMapping {
    pub fn new(c_name: &str, llvm: &str, isa: &str, header: &str, desc: &str) -> Self {
        Self {
            c_name: c_name.to_string(),
            llvm_intrinsic: llvm.to_string(),
            isa_extension: isa.to_string(),
            header: header.to_string(),
            description: desc.to_string(),
        }
    }
}

/// Catalog of X86 intrinsics for IR generation verification.
/// Maps C builtins to their expected LLVM IR intrinsic calls.
pub fn x86_intrinsic_catalog() -> Vec<X86IntrinsicMapping> {
    vec![
        // SSE Intrinsics
        X86IntrinsicMapping::new(
            "_mm_add_ps",
            "llvm.x86.sse.add.ps",
            "SSE",
            "xmmintrin.h",
            "Packed single-precision floating-point addition",
        ),
        X86IntrinsicMapping::new(
            "_mm_sub_ps",
            "llvm.x86.sse.sub.ps",
            "SSE",
            "xmmintrin.h",
            "Packed single-precision floating-point subtraction",
        ),
        X86IntrinsicMapping::new(
            "_mm_mul_ps",
            "llvm.x86.sse.mul.ps",
            "SSE",
            "xmmintrin.h",
            "Packed single-precision floating-point multiplication",
        ),
        X86IntrinsicMapping::new(
            "_mm_div_ps",
            "llvm.x86.sse.div.ps",
            "SSE",
            "xmmintrin.h",
            "Packed single-precision floating-point division",
        ),
        X86IntrinsicMapping::new(
            "_mm_sqrt_ps",
            "llvm.x86.sse.sqrt.ps",
            "SSE",
            "xmmintrin.h",
            "Packed single-precision floating-point square root",
        ),
        X86IntrinsicMapping::new(
            "_mm_rcp_ps",
            "llvm.x86.sse.rcp.ps",
            "SSE",
            "xmmintrin.h",
            "Packed single-precision floating-point reciprocal",
        ),
        X86IntrinsicMapping::new(
            "_mm_rsqrt_ps",
            "llvm.x86.sse.rsqrt.ps",
            "SSE",
            "xmmintrin.h",
            "Packed single-precision floating-point reciprocal sqrt",
        ),
        X86IntrinsicMapping::new(
            "_mm_min_ps",
            "llvm.x86.sse.min.ps",
            "SSE",
            "xmmintrin.h",
            "Packed single-precision floating-point minimum",
        ),
        X86IntrinsicMapping::new(
            "_mm_max_ps",
            "llvm.x86.sse.max.ps",
            "SSE",
            "xmmintrin.h",
            "Packed single-precision floating-point maximum",
        ),
        X86IntrinsicMapping::new(
            "_mm_and_ps",
            "llvm.x86.sse.and.ps",
            "SSE",
            "xmmintrin.h",
            "Bitwise AND of packed single-precision values",
        ),
        X86IntrinsicMapping::new(
            "_mm_or_ps",
            "llvm.x86.sse.or.ps",
            "SSE",
            "xmmintrin.h",
            "Bitwise OR of packed single-precision values",
        ),
        X86IntrinsicMapping::new(
            "_mm_xor_ps",
            "llvm.x86.sse.xor.ps",
            "SSE",
            "xmmintrin.h",
            "Bitwise XOR of packed single-precision values",
        ),
        X86IntrinsicMapping::new(
            "_mm_cmpeq_ps",
            "llvm.x86.sse.cmp.ps",
            "SSE",
            "xmmintrin.h",
            "Compare packed single-precision for equality",
        ),
        X86IntrinsicMapping::new(
            "_mm_cmplt_ps",
            "llvm.x86.sse.cmp.ps",
            "SSE",
            "xmmintrin.h",
            "Compare packed single-precision for less-than",
        ),
        X86IntrinsicMapping::new(
            "_mm_cmple_ps",
            "llvm.x86.sse.cmp.ps",
            "SSE",
            "xmmintrin.h",
            "Compare packed single-precision for less-or-equal",
        ),
        // SSE2 Intrinsics
        X86IntrinsicMapping::new(
            "_mm_add_pd",
            "llvm.x86.sse2.add.pd",
            "SSE2",
            "emmintrin.h",
            "Packed double-precision floating-point addition",
        ),
        X86IntrinsicMapping::new(
            "_mm_sub_pd",
            "llvm.x86.sse2.sub.pd",
            "SSE2",
            "emmintrin.h",
            "Packed double-precision floating-point subtraction",
        ),
        X86IntrinsicMapping::new(
            "_mm_mul_pd",
            "llvm.x86.sse2.mul.pd",
            "SSE2",
            "emmintrin.h",
            "Packed double-precision floating-point multiplication",
        ),
        X86IntrinsicMapping::new(
            "_mm_div_pd",
            "llvm.x86.sse2.div.pd",
            "SSE2",
            "emmintrin.h",
            "Packed double-precision floating-point division",
        ),
        X86IntrinsicMapping::new(
            "_mm_sqrt_pd",
            "llvm.x86.sse2.sqrt.pd",
            "SSE2",
            "emmintrin.h",
            "Packed double-precision floating-point square root",
        ),
        X86IntrinsicMapping::new(
            "_mm_add_epi32",
            "llvm.x86.sse2.padd.d",
            "SSE2",
            "emmintrin.h",
            "Add packed 32-bit integers",
        ),
        X86IntrinsicMapping::new(
            "_mm_sub_epi32",
            "llvm.x86.sse2.psub.d",
            "SSE2",
            "emmintrin.h",
            "Subtract packed 32-bit integers",
        ),
        X86IntrinsicMapping::new(
            "_mm_mul_epu32",
            "llvm.x86.sse2.pmulu.dq",
            "SSE2",
            "emmintrin.h",
            "Multiply unsigned 32-bit integers and store 64-bit results",
        ),
        X86IntrinsicMapping::new(
            "_mm_slli_epi32",
            "llvm.x86.sse2.pslli.d",
            "SSE2",
            "emmintrin.h",
            "Shift packed 32-bit integers left logical",
        ),
        X86IntrinsicMapping::new(
            "_mm_srli_epi32",
            "llvm.x86.sse2.psrli.d",
            "SSE2",
            "emmintrin.h",
            "Shift packed 32-bit integers right logical",
        ),
        X86IntrinsicMapping::new(
            "_mm_srai_epi32",
            "llvm.x86.sse2.psrai.d",
            "SSE2",
            "emmintrin.h",
            "Shift packed 32-bit integers right arithmetic",
        ),
        X86IntrinsicMapping::new(
            "_mm_and_si128",
            "llvm.x86.sse2.pand",
            "SSE2",
            "emmintrin.h",
            "Bitwise AND of 128-bit integer vectors",
        ),
        X86IntrinsicMapping::new(
            "_mm_or_si128",
            "llvm.x86.sse2.por",
            "SSE2",
            "emmintrin.h",
            "Bitwise OR of 128-bit integer vectors",
        ),
        X86IntrinsicMapping::new(
            "_mm_xor_si128",
            "llvm.x86.sse2.pxor",
            "SSE2",
            "emmintrin.h",
            "Bitwise XOR of 128-bit integer vectors",
        ),
        X86IntrinsicMapping::new(
            "_mm_packs_epi32",
            "llvm.x86.sse2.packssdw.128",
            "SSE2",
            "emmintrin.h",
            "Pack signed 32-bit integers to 16-bit with saturation",
        ),
        X86IntrinsicMapping::new(
            "_mm_packus_epi32",
            "llvm.x86.sse2.packusdw.128",
            "SSE2",
            "emmintrin.h",
            "Pack unsigned 32-bit integers to 16-bit with saturation",
        ),
        X86IntrinsicMapping::new(
            "_mm_unpacklo_epi32",
            "llvm.x86.sse2.punpckldq",
            "SSE2",
            "emmintrin.h",
            "Unpack and interleave low 32-bit integers",
        ),
        X86IntrinsicMapping::new(
            "_mm_unpackhi_epi32",
            "llvm.x86.sse2.punpckhdq",
            "SSE2",
            "emmintrin.h",
            "Unpack and interleave high 32-bit integers",
        ),
        // SSE3 Intrinsics
        X86IntrinsicMapping::new(
            "_mm_hadd_ps",
            "llvm.x86.sse3.hadd.ps",
            "SSE3",
            "pmmintrin.h",
            "Horizontal add packed single-precision values",
        ),
        X86IntrinsicMapping::new(
            "_mm_hsub_ps",
            "llvm.x86.sse3.hsub.ps",
            "SSE3",
            "pmmintrin.h",
            "Horizontal subtract packed single-precision values",
        ),
        X86IntrinsicMapping::new(
            "_mm_addsub_ps",
            "llvm.x86.sse3.addsub.ps",
            "SSE3",
            "pmmintrin.h",
            "Alternating add/subtract packed single-precision values",
        ),
        // SSSE3 Intrinsics
        X86IntrinsicMapping::new(
            "_mm_abs_epi32",
            "llvm.x86.ssse3.pabs.d.128",
            "SSSE3",
            "tmmintrin.h",
            "Absolute value of packed 32-bit integers",
        ),
        X86IntrinsicMapping::new(
            "_mm_shuffle_epi8",
            "llvm.x86.ssse3.pshuf.b.128",
            "SSSE3",
            "tmmintrin.h",
            "Shuffle packed 8-bit integers",
        ),
        X86IntrinsicMapping::new(
            "_mm_alignr_epi8",
            "llvm.x86.ssse3.palign.r.128",
            "SSSE3",
            "tmmintrin.h",
            "Concatenate and shift right packed 8-bit integers",
        ),
        X86IntrinsicMapping::new(
            "_mm_hadd_epi32",
            "llvm.x86.ssse3.phadd.d.128",
            "SSSE3",
            "tmmintrin.h",
            "Horizontal add packed 32-bit integers",
        ),
        // SSE4.1 Intrinsics
        X86IntrinsicMapping::new(
            "_mm_blend_ps",
            "llvm.x86.sse41.blendps",
            "SSE4.1",
            "smmintrin.h",
            "Blend packed single-precision values",
        ),
        X86IntrinsicMapping::new(
            "_mm_blend_pd",
            "llvm.x86.sse41.blendpd",
            "SSE4.1",
            "smmintrin.h",
            "Blend packed double-precision values",
        ),
        X86IntrinsicMapping::new(
            "_mm_dp_ps",
            "llvm.x86.sse41.dpps",
            "SSE4.1",
            "smmintrin.h",
            "Dot product of packed single-precision values",
        ),
        X86IntrinsicMapping::new(
            "_mm_round_ps",
            "llvm.x86.sse41.round.ps",
            "SSE4.1",
            "smmintrin.h",
            "Round packed single-precision values",
        ),
        X86IntrinsicMapping::new(
            "_mm_round_pd",
            "llvm.x86.sse41.round.pd",
            "SSE4.1",
            "smmintrin.h",
            "Round packed double-precision values",
        ),
        X86IntrinsicMapping::new(
            "_mm_min_epi32",
            "llvm.x86.sse41.pminsd",
            "SSE4.1",
            "smmintrin.h",
            "Minimum of packed signed 32-bit integers",
        ),
        X86IntrinsicMapping::new(
            "_mm_max_epi32",
            "llvm.x86.sse41.pmaxsd",
            "SSE4.1",
            "smmintrin.h",
            "Maximum of packed signed 32-bit integers",
        ),
        X86IntrinsicMapping::new(
            "_mm_mullo_epi32",
            "llvm.x86.sse41.pmuldq",
            "SSE4.1",
            "smmintrin.h",
            "Multiply packed 32-bit integers, store low 32 bits",
        ),
        // SSE4.2 Intrinsics
        X86IntrinsicMapping::new(
            "_mm_crc32_u8",
            "llvm.x86.sse42.crc32.32.8",
            "SSE4.2",
            "nmmintrin.h",
            "Accumulate CRC32 on unsigned 8-bit integer",
        ),
        X86IntrinsicMapping::new(
            "_mm_crc32_u32",
            "llvm.x86.sse42.crc32.32.32",
            "SSE4.2",
            "nmmintrin.h",
            "Accumulate CRC32 on unsigned 32-bit integer",
        ),
        X86IntrinsicMapping::new(
            "_mm_cmpestra",
            "llvm.x86.sse42.pcmpestrm128",
            "SSE4.2",
            "nmmintrin.h",
            "Compare packed strings with explicit lengths",
        ),
        // AVX Intrinsics
        X86IntrinsicMapping::new(
            "_mm256_add_ps",
            "llvm.x86.avx.add.ps.256",
            "AVX",
            "immintrin.h",
            "256-bit packed single-precision floating-point addition",
        ),
        X86IntrinsicMapping::new(
            "_mm256_sub_ps",
            "llvm.x86.avx.sub.ps.256",
            "AVX",
            "immintrin.h",
            "256-bit packed single-precision floating-point subtraction",
        ),
        X86IntrinsicMapping::new(
            "_mm256_mul_ps",
            "llvm.x86.avx.mul.ps.256",
            "AVX",
            "immintrin.h",
            "256-bit packed single-precision floating-point multiplication",
        ),
        X86IntrinsicMapping::new(
            "_mm256_div_ps",
            "llvm.x86.avx.div.ps.256",
            "AVX",
            "immintrin.h",
            "256-bit packed single-precision floating-point division",
        ),
        X86IntrinsicMapping::new(
            "_mm256_add_pd",
            "llvm.x86.avx.add.pd.256",
            "AVX",
            "immintrin.h",
            "256-bit packed double-precision floating-point addition",
        ),
        X86IntrinsicMapping::new(
            "_mm256_sqrt_ps",
            "llvm.x86.avx.sqrt.ps.256",
            "AVX",
            "immintrin.h",
            "256-bit packed single-precision floating-point square root",
        ),
        X86IntrinsicMapping::new(
            "_mm256_hadd_ps",
            "llvm.x86.avx.hadd.ps.256",
            "AVX",
            "immintrin.h",
            "Horizontal add 256-bit packed single-precision values",
        ),
        X86IntrinsicMapping::new(
            "_mm256_blend_ps",
            "llvm.x86.avx.blend.ps.256",
            "AVX",
            "immintrin.h",
            "Blend 256-bit packed single-precision values",
        ),
        // AVX2 Intrinsics
        X86IntrinsicMapping::new(
            "_mm256_add_epi32",
            "llvm.x86.avx2.padd.d",
            "AVX2",
            "immintrin.h",
            "Add packed 32-bit integers using 256-bit registers",
        ),
        X86IntrinsicMapping::new(
            "_mm256_mullo_epi32",
            "llvm.x86.avx2.pmul.dq",
            "AVX2",
            "immintrin.h",
            "Multiply packed 32-bit integers using 256-bit registers",
        ),
        X86IntrinsicMapping::new(
            "_mm256_slli_epi32",
            "llvm.x86.avx2.pslli.d",
            "AVX2",
            "immintrin.h",
            "Shift left packed 32-bit integers using 256-bit registers",
        ),
        X86IntrinsicMapping::new(
            "_mm256_and_si256",
            "llvm.x86.avx2.pand",
            "AVX2",
            "immintrin.h",
            "Bitwise AND of 256-bit integer vectors",
        ),
        X86IntrinsicMapping::new(
            "_mm256_abs_epi32",
            "llvm.x86.avx2.pabs.d",
            "AVX2",
            "immintrin.h",
            "Absolute value of packed 32-bit integers using 256-bit registers",
        ),
        // AVX-512 Intrinsics
        X86IntrinsicMapping::new(
            "_mm512_add_ps",
            "llvm.x86.avx512.add.ps.512",
            "AVX-512F",
            "immintrin.h",
            "512-bit packed single-precision floating-point addition",
        ),
        X86IntrinsicMapping::new(
            "_mm512_mul_ps",
            "llvm.x86.avx512.mul.ps.512",
            "AVX-512F",
            "immintrin.h",
            "512-bit packed single-precision floating-point multiplication",
        ),
        X86IntrinsicMapping::new(
            "_mm512_add_pd",
            "llvm.x86.avx512.add.pd.512",
            "AVX-512F",
            "immintrin.h",
            "512-bit packed double-precision floating-point addition",
        ),
        // FMA Intrinsics
        X86IntrinsicMapping::new(
            "_mm_fmadd_ps",
            "llvm.x86.fma.vfmadd.ps",
            "FMA",
            "immintrin.h",
            "Fused multiply-add packed single-precision",
        ),
        X86IntrinsicMapping::new(
            "_mm_fmadd_pd",
            "llvm.x86.fma.vfmadd.pd",
            "FMA",
            "immintrin.h",
            "Fused multiply-add packed double-precision",
        ),
        X86IntrinsicMapping::new(
            "_mm256_fmadd_ps",
            "llvm.x86.fma.vfmadd.ps.256",
            "FMA",
            "immintrin.h",
            "256-bit fused multiply-add packed single-precision",
        ),
        // BMI/BMI2 Intrinsics
        X86IntrinsicMapping::new(
            "__blsr_u32",
            "llvm.x86.bmi.blsr.32",
            "BMI",
            "x86intrin.h",
            "Reset lowest set bit",
        ),
        X86IntrinsicMapping::new(
            "__blsmsk_u32",
            "llvm.x86.bmi.blsmsk.32",
            "BMI",
            "x86intrin.h",
            "Get mask up to lowest set bit",
        ),
        X86IntrinsicMapping::new(
            "__blsi_u32",
            "llvm.x86.bmi.blsi.32",
            "BMI",
            "x86intrin.h",
            "Extract lowest set isolated bit",
        ),
        X86IntrinsicMapping::new(
            "__tzcnt_u32",
            "llvm.x86.bmi.tzcnt.32",
            "BMI",
            "x86intrin.h",
            "Count trailing zeros",
        ),
        X86IntrinsicMapping::new(
            "__lzcnt32",
            "llvm.x86.lzcnt.32",
            "LZCNT",
            "x86intrin.h",
            "Count leading zeros",
        ),
        X86IntrinsicMapping::new(
            "__popcntd",
            "llvm.x86.popcnt.32",
            "POPCNT",
            "x86intrin.h",
            "Population count of 32-bit integer",
        ),
        // RDTSC/RDTSCP
        X86IntrinsicMapping::new(
            "__rdtsc",
            "llvm.x86.rdtsc",
            "x86",
            "x86intrin.h",
            "Read Time-Stamp Counter",
        ),
        X86IntrinsicMapping::new(
            "__rdtscp",
            "llvm.x86.rdtscp",
            "x86",
            "x86intrin.h",
            "Read Time-Stamp Counter and Processor ID",
        ),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// EDGE CASE TEST GENERATOR
// ═══════════════════════════════════════════════════════════════════════════════

/// Configuration for generating edge case IR tests.
#[derive(Debug, Clone)]
pub struct EdgeCaseConfig {
    /// Whether to include integer overflow scenarios.
    pub include_overflow: bool,
    /// Whether to include division-by-zero scenarios.
    pub include_div_zero: bool,
    /// Whether to include null pointer dereference scenarios.
    pub include_null_ptr: bool,
    /// Whether to include uninitialized variable scenarios.
    pub include_uninit: bool,
    /// Whether to include type-punning scenarios.
    pub include_type_pun: bool,
    /// Whether to include large stack allocation scenarios.
    pub include_large_stack: bool,
}

impl Default for EdgeCaseConfig {
    fn default() -> Self {
        Self {
            include_overflow: true,
            include_div_zero: true,
            include_null_ptr: true,
            include_uninit: true,
            include_type_pun: true,
            include_large_stack: true,
        }
    }
}

/// Generator for edge case IR tests.
#[derive(Debug, Clone)]
pub struct EdgeCaseGenerator {
    pub config: EdgeCaseConfig,
    pub tests_generated: usize,
}

impl EdgeCaseGenerator {
    /// Create a new edge case generator.
    pub fn new() -> Self {
        Self {
            config: EdgeCaseConfig::default(),
            tests_generated: 0,
        }
    }

    /// Configure which edge cases to generate.
    pub fn with_config(mut self, config: EdgeCaseConfig) -> Self {
        self.config = config;
        self
    }

    /// Generate integer overflow edge cases.
    pub fn gen_overflow_tests(&self) -> Vec<X86IRGenTest> {
        let mut tests = Vec::new();
        if !self.config.include_overflow {
            return tests;
        }
        tests.push(X86IRGenTest::new("edge_overflow_sadd", X86IRGenCategory::Stress,
            "#include <stdbool.h>\nbool f(int a, int b) { int r; return __builtin_add_overflow(a, b, &r); }")
            .require("sadd.with.overflow intrinsic", "llvm.sadd.with.overflow"));

        tests.push(X86IRGenTest::new("edge_overflow_ssub", X86IRGenCategory::Stress,
            "#include <stdbool.h>\nbool f(int a, int b) { int r; return __builtin_sub_overflow(a, b, &r); }")
            .require("ssub.with.overflow intrinsic", "llvm.ssub.with.overflow"));

        tests.push(X86IRGenTest::new("edge_overflow_smul", X86IRGenCategory::Stress,
            "#include <stdbool.h>\nbool f(int a, int b) { int r; return __builtin_mul_overflow(a, b, &r); }")
            .require("smul.with.overflow intrinsic", "llvm.smul.with.overflow"));

        tests.push(X86IRGenTest::new("edge_overflow_uadd", X86IRGenCategory::Stress,
            "#include <stdbool.h>\nbool f(unsigned a, unsigned b) { unsigned r; return __builtin_uadd_overflow(a, b, &r); }")
            .require("uadd.with.overflow intrinsic", "llvm.uadd.with.overflow"));
        tests
    }

    /// Generate division-by-zero edge cases.
    pub fn gen_div_zero_tests(&self) -> Vec<X86IRGenTest> {
        let mut tests = Vec::new();
        if !self.config.include_div_zero {
            return tests;
        }
        tests.push(
            X86IRGenTest::new(
                "edge_div_zero_int",
                X86IRGenCategory::Stress,
                "int f(int a, int b) { return a / b; }",
            )
            .require("sdiv for division", "sdiv i32"),
        );

        tests.push(
            X86IRGenTest::new(
                "edge_div_zero_uint",
                X86IRGenCategory::Stress,
                "unsigned f(unsigned a, unsigned b) { return a / b; }",
            )
            .require("udiv for unsigned division", "udiv i32"),
        );

        tests.push(
            X86IRGenTest::new(
                "edge_mod_zero_int",
                X86IRGenCategory::Stress,
                "int f(int a, int b) { return a % b; }",
            )
            .require("srem for modulo", "srem i32"),
        );
        tests
    }

    /// Generate null pointer edge cases.
    pub fn gen_null_ptr_tests(&self) -> Vec<X86IRGenTest> {
        let mut tests = Vec::new();
        if !self.config.include_null_ptr {
            return tests;
        }
        tests.push(
            X86IRGenTest::new(
                "edge_null_ptr_deref",
                X86IRGenCategory::Stress,
                "int f(int *p) { if (p) return *p; return 0; }",
            )
            .require("null check before deref", "icmp")
            .require("conditional branch on null", "br i1"),
        );

        tests.push(
            X86IRGenTest::new(
                "edge_null_ptr_assign",
                X86IRGenCategory::Stress,
                "int *f(void) { return (int*)0; }",
            )
            .require("null pointer constant", "null"),
        );
        tests
    }

    /// Generate uninitialized variable edge cases.
    pub fn gen_uninit_tests(&self) -> Vec<X86IRGenTest> {
        let mut tests = Vec::new();
        if !self.config.include_uninit {
            return tests;
        }
        tests.push(
            X86IRGenTest::new(
                "edge_uninit_local",
                X86IRGenCategory::Stress,
                "int f(void) { int x; return x; }",
            )
            .with_flags(vec!["-Wno-uninitialized"])
            .require("alloca for uninitialized local", "alloca"),
        );

        tests.push(
            X86IRGenTest::new(
                "edge_uninit_array",
                X86IRGenCategory::Stress,
                "int f(void) { int arr[10]; return arr[5]; }",
            )
            .with_flags(vec!["-Wno-uninitialized"])
            .require("alloca for uninitialized array", "alloca"),
        );
        tests
    }

    /// Generate type-punning edge cases.
    pub fn gen_type_pun_tests(&self) -> Vec<X86IRGenTest> {
        let mut tests = Vec::new();
        if !self.config.include_type_pun {
            return tests;
        }
        tests.push(
            X86IRGenTest::new(
                "edge_type_pun_union",
                X86IRGenCategory::Stress,
                "union U { float f; int i; }; int f(float x) { union U u; u.f = x; return u.i; }",
            )
            .require("union type punning", "load i32"),
        );

        tests.push(
            X86IRGenTest::new(
                "edge_type_pun_ptr_cast",
                X86IRGenCategory::Stress,
                "float f(int x) { return *(float*)&x; }",
            )
            .require("pointer cast for type punning", "bitcast"),
        );
        tests
    }

    /// Generate large stack allocation edge cases.
    pub fn gen_large_stack_tests(&self) -> Vec<X86IRGenTest> {
        let mut tests = Vec::new();
        if !self.config.include_large_stack {
            return tests;
        }
        tests.push(
            X86IRGenTest::new(
                "edge_large_stack_array",
                X86IRGenCategory::Stress,
                "int f(void) { char buf[4096]; buf[0] = 'x'; return buf[0]; }",
            )
            .require("large stack alloca", "alloca [4096 x i8]"),
        );

        tests.push(
            X86IRGenTest::new(
                "edge_large_stack_vla",
                X86IRGenCategory::Stress,
                "int f(int n) { char buf[n + 1024]; return sizeof(buf); }",
            )
            .with_flags(vec!["-std=c99"])
            .require("VLA with large size", "alloca"),
        );
        tests
    }

    /// Generate all edge case tests.
    pub fn generate_all(&mut self) -> Vec<X86IRGenTest> {
        let mut tests = Vec::new();
        tests.extend(self.gen_overflow_tests());
        tests.extend(self.gen_div_zero_tests());
        tests.extend(self.gen_null_ptr_tests());
        tests.extend(self.gen_uninit_tests());
        tests.extend(self.gen_type_pun_tests());
        tests.extend(self.gen_large_stack_tests());
        self.tests_generated = tests.len();
        tests
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// BATCH VERIFICATION & IR COMPARISON
// ═══════════════════════════════════════════════════════════════════════════════

/// Batch verification result for a group of tests.
#[derive(Debug, Clone)]
pub struct BatchVerificationResult {
    /// Group name.
    pub group_name: String,
    /// Total tests in the batch.
    pub total: usize,
    /// Number of passed tests.
    pub passed: usize,
    /// Number of failed tests.
    pub failed: usize,
    /// Number of tests that didn't compile.
    pub compile_errors: usize,
    /// Total duration in milliseconds.
    pub total_duration_ms: u64,
    /// Individual test results.
    pub results: Vec<X86IRGenTestResult>,
    /// Category breakdown.
    pub category_results: BTreeMap<X86IRGenCategory, (usize, usize)>,
}

impl BatchVerificationResult {
    /// Create a batch result from a vector of individual results.
    pub fn new(group_name: &str, results: Vec<X86IRGenTestResult>) -> Self {
        let total = results.len();
        let passed = results.iter().filter(|r| r.passed).count();
        let failed = total - passed;
        let compile_errors = results.iter().filter(|r| !r.compiled).count();
        let total_duration_ms = results.iter().map(|r| r.duration_ms).sum();
        let category_results = BTreeMap::new();

        Self {
            group_name: group_name.to_string(),
            total,
            passed,
            failed,
            compile_errors,
            total_duration_ms,
            results,
            category_results,
        }
    }

    /// Pass rate as a percentage.
    pub fn pass_rate(&self) -> f64 {
        if self.total == 0 {
            return 100.0;
        }
        self.passed as f64 / self.total as f64 * 100.0
    }

    /// Whether all tests passed.
    pub fn is_perfect(&self) -> bool {
        self.failed == 0
    }

    /// Get a multi-line summary report.
    pub fn summary_report(&self) -> String {
        let mut report = String::new();
        report.push_str(&format!("Batch: {}\n", self.group_name));
        report.push_str(&format!("════════════════════════════\n"));
        report.push_str(&format!("Total:           {:>6}\n", self.total));
        report.push_str(&format!(
            "Passed:          {:>6} ({:.1}%)\n",
            self.passed,
            self.pass_rate()
        ));
        report.push_str(&format!("Failed:          {:>6}\n", self.failed));
        report.push_str(&format!("Compile errors:  {:>6}\n", self.compile_errors));
        report.push_str(&format!(
            "Duration:        {:>6} ms\n",
            self.total_duration_ms
        ));
        if self.failed > 0 {
            report.push_str("\nFailed tests:\n");
            for r in &self.results {
                if !r.passed {
                    report.push_str(&format!("{}\n", r.name));
                    for check in r.failed_checks() {
                        report.push_str(&format!("    - {}\n", check));
                    }
                }
            }
        }
        report
    }

    /// Count tests by category.
    pub fn count_by_category(&mut self, suite: &X86IRGenTestSuite) {
        let mut cat_map: BTreeMap<X86IRGenCategory, (usize, usize)> = BTreeMap::new();
        for result in &self.results {
            if let Some(test) = suite.tests.iter().find(|t| t.name == result.name) {
                let entry = cat_map.entry(test.category).or_insert((0, 0));
                entry.0 += 1;
                if result.passed {
                    entry.1 += 1;
                }
            }
        }
        self.category_results = cat_map;
    }
}

/// Compare two IR text outputs for structural similarity.
#[derive(Debug, Clone, Default)]
pub struct IRComparator {
    /// Ignore metadata nodes when comparing.
    pub ignore_metadata: bool,
    /// Ignore value names (e.g., %1 vs %foo).
    pub ignore_names: bool,
    /// Ignore comments.
    pub ignore_comments: bool,
    /// Ignore debug info intrinsics.
    pub ignore_debug_info: bool,
}

impl IRComparator {
    /// Create a new comparator with default settings.
    pub fn new() -> Self {
        Self::default()
    }

    /// Builder: ignore metadata.
    pub fn ignore_metadata(mut self) -> Self {
        self.ignore_metadata = true;
        self
    }

    /// Builder: ignore value names.
    pub fn ignore_names(mut self) -> Self {
        self.ignore_names = true;
        self
    }

    /// Compute a similarity score (0.0 to 1.0) between two IR texts.
    pub fn similarity(&self, a: &str, b: &str) -> f64 {
        let a_clean = self.clean(a);
        let b_clean = self.clean(b);

        let a_lines: Vec<&str> = a_clean.lines().filter(|l| !l.trim().is_empty()).collect();
        let b_lines: Vec<&str> = b_clean.lines().filter(|l| !l.trim().is_empty()).collect();

        if a_lines.is_empty() && b_lines.is_empty() {
            return 1.0;
        }
        if a_lines.is_empty() || b_lines.is_empty() {
            return 0.0;
        }

        // Use Jaccard-like similarity on line sets
        let a_set: HashSet<&str> = a_lines.iter().copied().collect();
        let b_set: HashSet<&str> = b_lines.iter().copied().collect();

        let intersection = a_set.intersection(&b_set).count();
        let union = a_set.union(&b_set).count();

        if union == 0 {
            return 1.0;
        }
        intersection as f64 / union as f64
    }

    /// Check if two IR texts have the same number of function definitions.
    pub fn same_function_count(&self, a: &str, b: &str) -> bool {
        let count_a = a.matches("define ").count();
        let count_b = b.matches("define ").count();
        count_a == count_b
    }

    /// Check if the same named globals are present.
    pub fn same_global_names(&self, a: &str, b: &str) -> bool {
        let extract_globals = |text: &str| -> HashSet<&str> {
            text.lines()
                .filter(|l| l.trim().starts_with('@'))
                .filter_map(|l| {
                    let trimmed = l.trim();
                    let name_end = trimmed.find('=').unwrap_or(trimmed.len());
                    Some(&trimmed[1..name_end.min(trimmed.len())])
                })
                .collect()
        };
        extract_globals(a) == extract_globals(b)
    }

    fn clean<'a>(&self, ir: &'a str) -> String {
        let mut result = ir.to_string();

        if self.ignore_metadata {
            // Remove metadata nodes
            let re_lines: Vec<String> = result
                .lines()
                .filter(|l| !l.trim().starts_with('!'))
                .map(|l| {
                    // Remove inline metadata references like !dbg !42
                    let mut cleaned = l.to_string();
                    while let Some(pos) = cleaned.find(", !") {
                        let rest = &cleaned[pos + 2..];
                        if let Some(space) = rest.find(|c: char| c.is_whitespace() || c == ')') {
                            cleaned.replace_range(pos..pos + 2 + space, "");
                        } else {
                            cleaned.truncate(pos);
                            break;
                        }
                    }
                    cleaned
                })
                .collect();
            result = re_lines.join("\n");
        }

        if self.ignore_names {
            // Normalize %names to %v
            let mut simplified = String::new();
            let mut i = 0;
            let chars: Vec<char> = result.chars().collect();
            while i < chars.len() {
                if chars[i] == '%' && i + 1 < chars.len() {
                    let start = i;
                    i += 1;
                    while i < chars.len()
                        && (chars[i].is_alphanumeric() || chars[i] == '.' || chars[i] == '_')
                    {
                        i += 1;
                    }
                    let _name = &chars[start..i].iter().collect::<String>();
                    simplified.push_str("%v");
                } else {
                    simplified.push(chars[i]);
                    i += 1;
                }
            }
            result = simplified;
        }

        if self.ignore_comments {
            result = result
                .lines()
                .filter(|l| !l.trim().starts_with(';'))
                .map(|l| {
                    if let Some(pos) = l.find(';') {
                        l[..pos].to_string()
                    } else {
                        l.to_string()
                    }
                })
                .collect::<Vec<_>>()
                .join("\n");
        }

        if self.ignore_debug_info {
            result = result
                .lines()
                .filter(|l| {
                    let t = l.trim();
                    !t.contains("llvm.dbg.") && !t.contains("!dbg")
                })
                .collect::<Vec<_>>()
                .join("\n");
        }

        result
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// C-LANGUAGE SPECIFIC IR PATTERNS
// ═══════════════════════════════════════════════════════════════════════════════

/// Build C-language-specific IR tests.
pub fn build_c_language_tests() -> Vec<X86IRGenTest> {
    vec![
        // ── Global variable initialization ──
        X86IRGenTest::new("ir_c_global_int_init", X86IRGenCategory::CLanguage,
            "int x = 42;\nint f(void) { return x; }")
            .require("global with initializer", "@x")
            .require("initializer value 42", "i32 42"),

        X86IRGenTest::new("ir_c_global_zero_init", X86IRGenCategory::CLanguage,
            "int x;\nint f(void) { return x; }")
            .require("global tentative definition", "@x")
            .require("zeroinitializer for BSS", "zeroinitializer"),

        X86IRGenTest::new("ir_c_global_const", X86IRGenCategory::CLanguage,
            "const int x = 100;\nint f(void) { return x; }")
            .require("constant global", "constant"),

        X86IRGenTest::new("ir_c_global_float_init", X86IRGenCategory::CLanguage,
            "double pi = 3.14159;\ndouble f(void) { return pi; }")
            .require("float global", "double")
            .require("global variable @pi", "@pi"),

        X86IRGenTest::new("ir_c_global_array_init", X86IRGenCategory::CLanguage,
            "int arr[5] = {1, 2, 3, 4, 5};\nint f(int i) { return arr[i]; }")
            .require("global array initializer", "@arr"),

        X86IRGenTest::new("ir_c_global_string", X86IRGenCategory::CLanguage,
            "const char *f(void) { return \"hello\"; }")
            .require("string constant in IR", "@"),

        // ── Static local variables ──
        X86IRGenTest::new("ir_c_static_local", X86IRGenCategory::CLanguage,
            "int f(void) { static int x = 0; return x++; }")
            .require("static local variable", "internal"),

        X86IRGenTest::new("ir_c_static_local_init", X86IRGenCategory::CLanguage,
            "int f(void) { static int x = 42; x++; return x; }")
            .require("static local with initializer", "internal"),

        X86IRGenTest::new("ir_c_static_local_guard", X86IRGenCategory::CLanguage,
            "int f(void) { static int x = g(); return x; }")
            .require("guard variable for dynamic init", "guard"),

        // ── Array to pointer decay ──
        X86IRGenTest::new("ir_c_array_decay_param", X86IRGenCategory::CLanguage,
            "int f(int arr[]) { return arr[0]; }")
            .require("array parameter decays to pointer", "i32\\*"),

        X86IRGenTest::new("ir_c_array_decay_assign", X86IRGenCategory::CLanguage,
            "int f(void) { int arr[10]; int *p = arr; return p[0]; }")
            .require("array decay in assignment", "getelementptr"),

        X86IRGenTest::new("ir_c_array_decay_sizeof", X86IRGenCategory::CLanguage,
            "#include <stddef.h>\nsize_t f(void) { int arr[10]; return sizeof(arr); }")
            .require("sizeof on array not decayed", "40"),

        // ── Function to pointer decay ──
        X86IRGenTest::new("ir_c_func_decay", X86IRGenCategory::CLanguage,
            "void g(void) {} void f(void) { void (*fp)(void) = g; fp(); }")
            .require("function pointer value", "@g")
            .require("indirect call", "call"),

        // ── Implicit casts and promotions ──
        X86IRGenTest::new("ir_c_implicit_int_promotion", X86IRGenCategory::CLanguage,
            "int f(char c) { return c + 1; }")
            .require("sign extension from i8 to i32", "sext"),

        X86IRGenTest::new("ir_c_implicit_float_promotion", X86IRGenCategory::CLanguage,
            "double f(float x) { return x + 1.0; }")
            .require("float to double promotion", "fpext"),

        X86IRGenTest::new("ir_c_implicit_int_to_float", X86IRGenCategory::CLanguage,
            "float f(int x) { return x + 0.5f; }")
            .require("int to float conversion", "sitofp"),

        X86IRGenTest::new("ir_c_implicit_float_to_int", X86IRGenCategory::CLanguage,
            "int f(float x) { return x; }")
            .require("float to int conversion", "fptosi"),

        X86IRGenTest::new("ir_c_implicit_truncate", X86IRGenCategory::CLanguage,
            "char f(int x) { return x; }")
            .require("i32 to i8 truncation", "trunc"),

        X86IRGenTest::new("ir_c_implicit_ptr_cast", X86IRGenCategory::CLanguage,
            "int f(void *p) { return *(int *)p; }")
            .require("pointer cast", "bitcast i8\\* to i32\\*"),

        // ── Compound literals ──
        X86IRGenTest::new("ir_c_compound_literal_int", X86IRGenCategory::CLanguage,
            "int f(void) { int *p = (int[]){1, 2, 3}; return p[1]; }")
            .require("compound literal alloca", "alloca"),

        X86IRGenTest::new("ir_c_compound_literal_struct", X86IRGenCategory::CLanguage,
            "struct Point { int x, y; }; int f(void) { struct Point p = (struct Point){10, 20}; return p.x; }")
            .require("compound literal struct", "struct.Point"),

        X86IRGenTest::new("ir_c_compound_literal_global", X86IRGenCategory::CLanguage,
            "struct S { int a; double b; }; struct S *f(void) { return &(struct S){1, 2.0}; }")
            .require("compound literal of struct", "alloca"),

        // ── Designated initializers ──
        X86IRGenTest::new("ir_c_designated_init_struct", X86IRGenCategory::CLanguage,
            "struct S { int a; double b; char c; }; struct S f(void) { struct S s = {.b = 3.14, .c = 'x'}; return s; }")
            .require("designated initializer for struct", "insertvalue"),

        X86IRGenTest::new("ir_c_designated_init_array", X86IRGenCategory::CLanguage,
            "int f(void) { int arr[5] = {[2] = 42, [4] = 99}; return arr[2]; }")
            .require("designated initializer for array", "i32 42"),

        // ── Variable-length arrays (VLA) ──
        X86IRGenTest::new("ir_c_vla_simple", X86IRGenCategory::CLanguage,
            "int f(int n) { int arr[n]; return sizeof(arr); }")
            .with_flags(vec!["-std=c99"])
            .require("VLA alloca", "alloca"),

        X86IRGenTest::new("ir_c_vla_multi_dim", X86IRGenCategory::CLanguage,
            "int f(int n, int m) { int arr[n][m]; return sizeof(arr); }")
            .with_flags(vec!["-std=c99"])
            .require("multi-dim VLA", "alloca"),

        // ── Flexible array members ──
        X86IRGenTest::new("ir_c_flex_array", X86IRGenCategory::CLanguage,
            "struct S { int n; char data[]; }; int f(struct S *s) { return s->data[0]; }")
            .require("flexible array member access", "getelementptr"),

        X86IRGenTest::new("ir_c_flex_array_zero", X86IRGenCategory::CLanguage,
            "struct S { int n; char data[0]; }; int f(struct S *s) { return s->n; }")
            .require("zero-length array", "getelementptr"),

        // ── Static initialization order guards ──
        X86IRGenTest::new("ir_c_function_local_static_guard", X86IRGenCategory::CLanguage,
            "int f(void) { static int x = 42; return x++; }")
            .require("static local function variable", "internal")
            .forbid("no guard needed for constant init", "guard"),

        // ── Tentative definitions ──
        X86IRGenTest::new("ir_c_tentative_def", X86IRGenCategory::CLanguage,
            "int x; int x = 42; int f(void) { return x; }")
            .require("tentative definition resolution", "i32 42"),

        // ── Extern variables ──
        X86IRGenTest::new("ir_c_extern_var", X86IRGenCategory::CLanguage,
            "extern int x; int f(void) { return x; }")
            .require("extern reference", "@x")
            .require("external linkage", "external"),

        // ── Static functions ──
        X86IRGenTest::new("ir_c_static_func", X86IRGenCategory::CLanguage,
            "static int helper(int x) { return x * 2; } int f(int a) { return helper(a); }")
            .require("internal linkage for static func", "internal")
            .require("call to static helper", "call i32 @helper"),

        // ── Inline functions ──
        X86IRGenTest::new("ir_c_inline_func", X86IRGenCategory::CLanguage,
            "inline int add(int a, int b) { return a + b; } int f(int x, int y) { return add(x, y); }")
            .require("inline function has linkonce_odr", "linkonce_odr"),

        // ── Aligned variables ──
        X86IRGenTest::new("ir_c_aligned_var", X86IRGenCategory::CLanguage,
            "int x __attribute__((aligned(64))) = 0; int f(void) { return x; }")
            .require("aligned global variable", "align 64"),

        // ── Section attributes ──
        X86IRGenTest::new("ir_c_section_attr", X86IRGenCategory::CLanguage,
            "int x __attribute__((section(\".mysection\"))) = 42;")
            .require("section attribute on global", "mysection"),

        // ── Alloca with alignment ──
        X86IRGenTest::new("ir_c_aligned_local", X86IRGenCategory::CLanguage,
            "int f(void) { int x __attribute__((aligned(32))) = 0; return x; }")
            .require("aligned alloca", "align 32"),

        // ── restrict keyword ──
        X86IRGenTest::new("ir_c_restrict_ptr", X86IRGenCategory::CLanguage,
            "void f(int *restrict p, int *restrict q) { *p = *q; }")
            .require("noalias on restrict pointer", "noalias"),

        // ── _Noreturn function specifier ──
        X86IRGenTest::new("ir_c_noreturn_specifier", X86IRGenCategory::CLanguage,
            "_Noreturn void f(void) { while(1); }")
            .require("noreturn attribute on function", "noreturn"),

        // ── _Static_assert ──
        X86IRGenTest::new("ir_c_static_assert", X86IRGenCategory::CLanguage,
            "_Static_assert(sizeof(int) == 4, \"int must be 4 bytes\"); int f(void) { return 0; }")
            .require("static assert does not affect IR", "define"),

        // ── _Generic selection ──
        X86IRGenTest::new("ir_c_generic", X86IRGenCategory::CLanguage,
            "#include <math.h>\ndouble f(double x) { return _Generic(x, float: sqrtf, double: sqrt)(x); }")
            .require("_Generic resolves at compile time", "call"),

        // ── String literal concatenation ──
        X86IRGenTest::new("ir_c_string_concat", X86IRGenCategory::CLanguage,
            "const char *f(void) { return \"hello\" \" world\"; }")
            .require("concatenated string literal", "hello world"),

        // ── Wide string literals ──
        X86IRGenTest::new("ir_c_wide_string", X86IRGenCategory::CLanguage,
            "const wchar_t *f(void) { return L\"hello\"; }")
            .require("wide string literal", "i32"),

        // ── UTF string literals ──
        X86IRGenTest::new("ir_c_utf8_string", X86IRGenCategory::CLanguage,
            "const char *f(void) { return u8\"hello\"; }")
            .require("UTF-8 string literal", "i8"),

        // ── Array initialization from string ──
        X86IRGenTest::new("ir_c_array_from_string", X86IRGenCategory::CLanguage,
            "char f(void) { char s[] = \"hi\"; return s[0]; }")
            .require("array initialized from string", "alloca"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// C++-SPECIFIC IR PATTERNS
// ═══════════════════════════════════════════════════════════════════════════════

/// Build C++-specific IR tests.
pub fn build_cxx_tests() -> Vec<X86IRGenTest> {
    vec![
        // ── Virtual function tables (vtable layout) ──
        X86IRGenTest::new("ir_cxx_vtable_layout", X86IRGenCategory::CPlusPlus,
            "struct Base { virtual int f() { return 1; } virtual int g() { return 2; } }; int caller(Base *b) { return b->f(); }")
            .require("vtable global", "@_ZTV")
            .require("virtual function call via vtable", "getelementptr"),

        X86IRGenTest::new("ir_cxx_vtable_single_inherit", X86IRGenCategory::CPlusPlus,
            "struct A { virtual void f() {} }; struct B : A { virtual void f() override {} }; void test(B *b) { b->f(); }")
            .require("vtable for derived class", "@_ZTV"),

        X86IRGenTest::new("ir_cxx_vtable_multiple", X86IRGenCategory::CPlusPlus,
            "struct A { virtual void fa() {} }; struct B { virtual void fb() {} }; struct C : A, B { virtual void fa() override {} virtual void fb() override {} }; void test(C *c) { c->fa(); }")
            .require("multiple inheritance vtable", "@_ZTV"),

        X86IRGenTest::new("ir_cxx_vtable_thunk", X86IRGenCategory::CPlusPlus,
            "struct A { virtual void f() {} }; struct B : A { virtual void f() override {} }; void test(B *b) { b->f(); }")
            .require("vtable entry for virtual function", "@_ZTV"),

        // ── RTTI descriptors ──
        X86IRGenTest::new("ir_cxx_rtti_descriptor", X86IRGenCategory::CPlusPlus,
            "struct S { virtual void f() {} }; const char *f() { return typeid(S).name(); }")
            .require("RTTI type info", "@_ZTI"),

        X86IRGenTest::new("ir_cxx_rtti_name", X86IRGenCategory::CPlusPlus,
            "struct Foo { virtual ~Foo() {} }; const char *f() { return typeid(Foo).name(); }")
            .require("typeinfo name", "@_ZTS"),

        // ── Exception handling — landingpad ──
        X86IRGenTest::new("ir_cxx_landingpad", X86IRGenCategory::ExceptionHandling,
            "void f(void) { try { throw 42; } catch (int) {} }")
            .require("landingpad instruction", "landingpad"),

        X86IRGenTest::new("ir_cxx_invoke", X86IRGenCategory::ExceptionHandling,
            "void may_throw(); void f(void) { try { may_throw(); } catch (...) {} }")
            .require("invoke instruction", "invoke void @"),

        X86IRGenTest::new("ir_cxx_resume", X86IRGenCategory::ExceptionHandling,
            "void g(void); void f(void) { try { try { g(); } catch(int) { throw; } } catch(int) {} }")
            .require("resume instruction for rethrow", "resume"),

        X86IRGenTest::new("ir_cxx_eh_personality", X86IRGenCategory::ExceptionHandling,
            "void f(void) { try { throw 1; } catch (...) {} }")
            .require("personality routine", "personality"),

        X86IRGenTest::new("ir_cxx_eh_typeid", X86IRGenCategory::ExceptionHandling,
            "void f(void) { try { throw 42; } catch (int) {} catch (double) {} }")
            .require("catch clauses", "catch"),

        X86IRGenTest::new("ir_cxx_eh_cleanup", X86IRGenCategory::ExceptionHandling,
            "struct S { ~S() {} }; void f(void) { S s; throw 42; }")
            .require("cleanup in landingpad", "cleanup"),

        X86IRGenTest::new("ir_cxx_eh_filter", X86IRGenCategory::ExceptionHandling,
            "void f(void) { try { throw 1; } catch (int) {} }")
            .require("filter for catch", "filter"),

        // ── Constructor/destructor calls ──
        X86IRGenTest::new("ir_cxx_ctor_call", X86IRGenCategory::CPlusPlus,
            "struct S { S() {} int x; }; S f(void) { S s; return s; }")
            .require("constructor call", "call void @"),

        X86IRGenTest::new("ir_cxx_dtor_call", X86IRGenCategory::CPlusPlus,
            "struct S { ~S() {} }; void f(void) { S s; }")
            .require("destructor call", "call void @"),

        X86IRGenTest::new("ir_cxx_ctor_init_list", X86IRGenCategory::CPlusPlus,
            "struct A { int x; A(int a) : x(a) {} }; A f(void) { return A(42); }")
            .require("constructor with init list", "call"),

        X86IRGenTest::new("ir_cxx_copy_ctor", X86IRGenCategory::CPlusPlus,
            "struct S { S() {} S(const S&) {} }; S f(S x) { return x; }")
            .require("copy constructor", "call"),

        // ── Member pointers ──
        X86IRGenTest::new("ir_cxx_member_ptr_data", X86IRGenCategory::CPlusPlus,
            "struct S { int x; }; int f(S s, int S::*mp) { return s.*mp; }")
            .require("member pointer", "i32"),

        X86IRGenTest::new("ir_cxx_member_ptr_func", X86IRGenCategory::CPlusPlus,
            "struct S { int f() { return 42; } }; int g(S *s, int (S::*mp)()) { return (s->*mp)(); }")
            .require("member function pointer call", "call"),

        // ── Lambda closure lowering ──
        X86IRGenTest::new("ir_cxx_lambda_empty", X86IRGenCategory::CPlusPlus,
            "void f(void) { auto l = []() { return 42; }; l(); }")
            .require("lambda closure", "operator()"),

        X86IRGenTest::new("ir_cxx_lambda_capture_by_val", X86IRGenCategory::CPlusPlus,
            "int f(int x) { auto l = [x]() { return x; }; return l(); }")
            .require("lambda capture by value", "call"),

        X86IRGenTest::new("ir_cxx_lambda_capture_by_ref", X86IRGenCategory::CPlusPlus,
            "int f(int x) { auto l = [&x]() { x = 42; return x; }; return l(); }")
            .require("lambda capture by reference", "call"),

        X86IRGenTest::new("ir_cxx_lambda_capture_mutable", X86IRGenCategory::CPlusPlus,
            "int f(int x) { auto l = [x]() mutable { x++; return x; }; return l(); }")
            .require("mutable lambda", "call"),

        // ── Template instantiation lowering ──
        X86IRGenTest::new("ir_cxx_template_func", X86IRGenCategory::CPlusPlus,
            "template<typename T> T add(T a, T b) { return a + b; } int f(void) { return add(1, 2); }")
            .require("template function instantiation", "add"),

        X86IRGenTest::new("ir_cxx_template_class", X86IRGenCategory::CPlusPlus,
            "template<typename T> struct Box { T val; T get() { return val; } }; int f(void) { Box<int> b; b.val = 42; return b.get(); }")
            .require("template class instantiation", "call"),

        X86IRGenTest::new("ir_cxx_template_specialization", X86IRGenCategory::CPlusPlus,
            "template<typename T> T twice(T x) { return x + x; } template<> double twice<double>(double x) { return x * 2.0; } double f(void) { return twice(3.14); }")
            .require("template specialization", "double"),

        // ── New/delete lowering ──
        X86IRGenTest::new("ir_cxx_new", X86IRGenCategory::CPlusPlus,
            "int *f(void) { return new int(42); }")
            .require("new operator call", "call"),

        X86IRGenTest::new("ir_cxx_new_array", X86IRGenCategory::CPlusPlus,
            "int *f(int n) { return new int[n]; }")
            .require("new array call", "call"),

        X86IRGenTest::new("ir_cxx_delete", X86IRGenCategory::CPlusPlus,
            "void f(int *p) { delete p; }")
            .require("delete call", "call"),

        X86IRGenTest::new("ir_cxx_delete_array", X86IRGenCategory::CPlusPlus,
            "void f(int *p) { delete[] p; }")
            .require("delete array call", "call"),

        // ── Name mangling ──
        X86IRGenTest::new("ir_cxx_mangled_name", X86IRGenCategory::CPlusPlus,
            "namespace ns { int f(int x) { return x; } }")
            .require("name mangling for namespace function", "@_ZN"),

        X86IRGenTest::new("ir_cxx_mangled_overload", X86IRGenCategory::CPlusPlus,
            "void f(int) {} void f(double) {}")
            .require("overloaded function names mangled", "@_Z"),

        // ── static data members ──
        X86IRGenTest::new("ir_cxx_static_member", X86IRGenCategory::CPlusPlus,
            "struct S { static int x; }; int S::x = 0; int f(void) { return S::x; }")
            .require("static member variable", "@"),

        // ── Virtual inheritance ──
        X86IRGenTest::new("ir_cxx_virtual_base", X86IRGenCategory::CPlusPlus,
            "struct A { int x; }; struct B : virtual A { int y; }; int f(B *b) { return b->x; }")
            .require("virtual base pointer access", "getelementptr"),

        X86IRGenTest::new("ir_cxx_virtual_base_offset", X86IRGenCategory::CPlusPlus,
            "struct A { int x; }; struct B : virtual A {}; struct C : B { int z; }; int f(C *c) { return c->x; }")
            .require("virtual base offset in deeper hierarchy", "getelementptr"),

        // ── Pure virtual functions ──
        X86IRGenTest::new("ir_cxx_pure_virtual", X86IRGenCategory::CPlusPlus,
            "struct A { virtual void f() = 0; }; void g(A *a) { a->f(); }")
            .require("pure virtual in vtable", "@_ZTV")
            .require("__cxa_pure_virtual entry", "pure_virtual"),

        // ── Virtual destructors ──
        X86IRGenTest::new("ir_cxx_virtual_dtor", X86IRGenCategory::CPlusPlus,
            "struct A { virtual ~A() {} }; A *f(void) { return new A(); }")
            .require("virtual destructor in vtable", "@_ZTV")
            .require("D0/D1 destructor variants", "call"),

        // ── Dynamic cast ──
        X86IRGenTest::new("ir_cxx_dynamic_cast", X86IRGenCategory::CPlusPlus,
            "struct A { virtual void f() {} }; struct B : A {}; B *f(A *a) { return dynamic_cast<B*>(a); }")
            .require("dynamic_cast lowering", "__dynamic_cast"),

        // ── Typeid ──
        X86IRGenTest::new("ir_cxx_typeid", X86IRGenCategory::CPlusPlus,
            "#include <typeinfo>\nconst std::type_info *f() { return &typeid(int); }")
            .require("typeid lowering", "@_ZTI"),

        // ── Member function with cv-qualifiers ──
        X86IRGenTest::new("ir_cxx_const_method", X86IRGenCategory::CPlusPlus,
            "struct S { int get() const { return 42; } }; int f(const S *s) { return s->get(); }")
            .require("const method call", "call"),

        X86IRGenTest::new("ir_cxx_volatile_method", X86IRGenCategory::CPlusPlus,
            "struct S { int get() volatile { return 42; } }; int f(volatile S *s) { return s->get(); }")
            .require("volatile method call", "call"),

        // ── Explicit template instantiation ──
        X86IRGenTest::new("ir_cxx_explicit_instantiation", X86IRGenCategory::CPlusPlus,
            "template<typename T> T min(T a, T b) { return a < b ? a : b; } template int min<int>(int, int);")
            .require("explicit instantiation", "define"),

        // ── Defaulted special members ──
        X86IRGenTest::new("ir_cxx_default_ctor", X86IRGenCategory::CPlusPlus,
            "struct S { S() = default; int x = 42; }; int f() { S s; return s.x; }")
            .require("default constructor", "call"),

        X86IRGenTest::new("ir_cxx_default_dtor", X86IRGenCategory::CPlusPlus,
            "struct S { ~S() = default; }; void f() { S s; }")
            .require("default destructor call", "call"),

        // ── Deleted members ──
        X86IRGenTest::new("ir_cxx_deleted_copy", X86IRGenCategory::CPlusPlus,
            "struct S { S(const S&) = delete; S() {} }; S f() { return S(); }")
            .require("deleted copy constructor not emitted", "define"),

        // ── Operator overloading ──
        X86IRGenTest::new("ir_cxx_operator_plus", X86IRGenCategory::CPlusPlus,
            "struct Vec { int x, y; Vec operator+(const Vec &o) { return {x+o.x, y+o.y}; } }; Vec f(Vec a, Vec b) { return a + b; }")
            .require("operator+ call", "call"),

        X86IRGenTest::new("ir_cxx_operator_eq", X86IRGenCategory::CPlusPlus,
            "struct S { int x; bool operator==(const S &o) { return x == o.x; } }; bool f(S a, S b) { return a == b; }")
            .require("operator== call", "call"),

        // ── Namespace aliases and using declarations ──
        X86IRGenTest::new("ir_cxx_using_decl", X86IRGenCategory::CPlusPlus,
            "namespace A { int f(int x) { return x; } } using A::f; int g(int a) { return f(a); }")
            .require("using declaration resolves", "call i32 @"),

        // ── Static data member definition ──
        X86IRGenTest::new("ir_cxx_static_const_member", X86IRGenCategory::CPlusPlus,
            "struct S { static const int val = 100; }; int f() { return S::val; }")
            .require("static const member folded", "ret i32 100"),

        // ── Aggregate initialization ──
        X86IRGenTest::new("ir_cxx_aggregate_init", X86IRGenCategory::CPlusPlus,
            "struct S { int a; double b; }; S f() { return {1, 2.5}; }")
            .require("aggregate initialization", "insertvalue"),

        // ── Structured binding (C++17) ──
        X86IRGenTest::new("ir_cxx_structured_binding", X86IRGenCategory::CPlusPlus,
            "struct S { int a; double b; }; int f(S s) { auto [x, y] = s; return x; }")
            .with_flags(vec!["-std=c++17"])
            .require("structured binding lowering", "extractvalue"),

        // ── If with initializer (C++17) ──
        X86IRGenTest::new("ir_cxx_if_init", X86IRGenCategory::CPlusPlus,
            "int f(int x) { if (int y = x * 2; y > 10) return y; return 0; }")
            .with_flags(vec!["-std=c++17"])
            .require("if with init statement", "br i1"),

        // ── Variadic templates ──
        X86IRGenTest::new("ir_cxx_variadic_template", X86IRGenCategory::CPlusPlus,
            "template<typename... Args> int sum(Args... args) { return (args + ...); } int f() { return sum(1, 2, 3); }")
            .with_flags(vec!["-std=c++17"])
            .require("variadic template instantiation", "add"),

        // ── Constexpr if ──
        X86IRGenTest::new("ir_cxx_constexpr_if", X86IRGenCategory::CPlusPlus,
            "template<typename T> T twice(T x) { if constexpr (sizeof(T) < 8) return x + x; else return x * 2; } int f() { return twice(21); }")
            .with_flags(vec!["-std=c++17"])
            .require("constexpr if resolved at compile time", "add i32"),

        // ── Explicit destructor call ──
        X86IRGenTest::new("ir_cxx_explicit_dtor", X86IRGenCategory::CPlusPlus,
            "struct S { ~S() {} }; void f(S *s) { s->~S(); }")
            .require("explicit destructor call", "call void @"),

        // ── Placement new ──
        X86IRGenTest::new("ir_cxx_placement_new", X86IRGenCategory::CPlusPlus,
            "#include <new>\nstruct S { int x; }; S *f(void *buf) { return new (buf) S(); }")
            .require("placement new call", "call"),

        // ── Alignment support ──
        X86IRGenTest::new("ir_cxx_alignof", X86IRGenCategory::CPlusPlus,
            "#include <cstddef>\nsize_t f() { return alignof(double); }")
            .require("C++ alignof", "ret i64 8"),

        X86IRGenTest::new("ir_cxx_alignas", X86IRGenCategory::CPlusPlus,
            "struct alignas(64) S { int x; }; int f() { return alignof(S); }")
            .require("alignas struct", "64"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// X86-SPECIFIC IR PATTERNS
// ═══════════════════════════════════════════════════════════════════════════════

/// Build X86-specific IR tests: vector types, intrinsics, inline assembly,
/// target-specific attributes.
pub fn build_x86_specific_tests() -> Vec<X86IRGenTest> {
    vec![
        // ── X86 Vector Types ──
        X86IRGenTest::new("ir_x86_vector_v2i64", X86IRGenCategory::X86Specific,
            "typedef long long v2di __attribute__((vector_size(16))); v2di f(v2di a, v2di b) { return a + b; }")
            .require("<2 x i64> vector type", "<2 x i64>"),

        X86IRGenTest::new("ir_x86_vector_v4i32", X86IRGenCategory::X86Specific,
            "typedef int v4si __attribute__((vector_size(16))); v4si f(v4si a, v4si b) { return a + b; }")
            .require("<4 x i32> vector type", "<4 x i32>"),

        X86IRGenTest::new("ir_x86_vector_v8i16", X86IRGenCategory::X86Specific,
            "typedef short v8hi __attribute__((vector_size(16))); v8hi f(v8hi a, v8hi b) { return a + b; }")
            .require("<8 x i16> vector type", "<8 x i16>"),

        X86IRGenTest::new("ir_x86_vector_v16i8", X86IRGenCategory::X86Specific,
            "typedef char v16qi __attribute__((vector_size(16))); v16qi f(v16qi a, v16qi b) { return a + b; }")
            .require("<16 x i8> vector type", "<16 x i8>"),

        X86IRGenTest::new("ir_x86_vector_v2f64", X86IRGenCategory::X86Specific,
            "typedef double v2df __attribute__((vector_size(16))); v2df f(v2df a, v2df b) { return a + b; }")
            .require("<2 x double> vector type", "<2 x double>"),

        X86IRGenTest::new("ir_x86_vector_v4f32", X86IRGenCategory::X86Specific,
            "typedef float v4sf __attribute__((vector_size(16))); v4sf f(v4sf a, v4sf b) { return a + b; }")
            .require("<4 x float> vector type", "<4 x float>"),

        X86IRGenTest::new("ir_x86_vector_v8f32", X86IRGenCategory::X86Specific,
            "typedef float v8sf __attribute__((vector_size(32))); v8sf f(v8sf a, v8sf b) { return a + b; }")
            .require("<8 x float> vector type", "<8 x float>"),

        X86IRGenTest::new("ir_x86_vector_v4f64", X86IRGenCategory::X86Specific,
            "typedef double v4df __attribute__((vector_size(32))); v4df f(v4df a, v4df b) { return a + b; }")
            .require("<4 x double> vector type", "<4 x double>"),

        // ── SSE Intrinsics ──
        X86IRGenTest::new("ir_x86_sse_addps", X86IRGenCategory::X86Specific,
            "#include <xmmintrin.h>\n__m128 f(__m128 a, __m128 b) { return _mm_add_ps(a, b); }")
            .require("SSE addps intrinsic", "llvm.x86.sse"),

        X86IRGenTest::new("ir_x86_sse_mulps", X86IRGenCategory::X86Specific,
            "#include <xmmintrin.h>\n__m128 f(__m128 a, __m128 b) { return _mm_mul_ps(a, b); }")
            .require("SSE mulps intrinsic", "llvm.x86.sse"),

        X86IRGenTest::new("ir_x86_sse_sqrtps", X86IRGenCategory::X86Specific,
            "#include <xmmintrin.h>\n__m128 f(__m128 a) { return _mm_sqrt_ps(a); }")
            .require("SSE sqrtps intrinsic", "llvm.x86.sse.sqrt"),

        X86IRGenTest::new("ir_x86_sse_movaps", X86IRGenCategory::X86Specific,
            "#include <xmmintrin.h>\nvoid f(float *p, __m128 v) { _mm_store_ps(p, v); }")
            .require("SSE store intrinsic", "llvm.x86.sse"),

        X86IRGenTest::new("ir_x86_sse2_addpd", X86IRGenCategory::X86Specific,
            "#include <emmintrin.h>\n__m128d f(__m128d a, __m128d b) { return _mm_add_pd(a, b); }")
            .require("SSE2 addpd intrinsic", "llvm.x86.sse2"),

        X86IRGenTest::new("ir_x86_sse2_paddd", X86IRGenCategory::X86Specific,
            "#include <emmintrin.h>\n__m128i f(__m128i a, __m128i b) { return _mm_add_epi32(a, b); }")
            .require("SSE2 paddd intrinsic", "llvm.x86.sse2"),

        X86IRGenTest::new("ir_x86_sse3_haddps", X86IRGenCategory::X86Specific,
            "#include <pmmintrin.h>\n__m128 f(__m128 a, __m128 b) { return _mm_hadd_ps(a, b); }")
            .require("SSE3 haddps intrinsic", "llvm.x86.sse3"),

        X86IRGenTest::new("ir_x86_ssse3_pshufb", X86IRGenCategory::X86Specific,
            "#include <tmmintrin.h>\n__m128i f(__m128i a, __m128i b) { return _mm_shuffle_epi8(a, b); }")
            .require("SSSE3 pshufb intrinsic", "llvm.x86.ssse3"),

        X86IRGenTest::new("ir_x86_sse41_roundps", X86IRGenCategory::X86Specific,
            "#include <smmintrin.h>\n__m128 f(__m128 a) { return _mm_round_ps(a, _MM_FROUND_TO_NEAREST_INT); }")
            .require("SSE4.1 roundps intrinsic", "llvm.x86.sse41"),

        X86IRGenTest::new("ir_x86_sse42_crc32", X86IRGenCategory::X86Specific,
            "#include <nmmintrin.h>\nunsigned int f(unsigned int crc, unsigned char v) { return _mm_crc32_u8(crc, v); }")
            .require("SSE4.2 crc32 intrinsic", "llvm.x86.sse42"),

        // ── AVX Intrinsics ──
        X86IRGenTest::new("ir_x86_avx_addps256", X86IRGenCategory::X86Specific,
            "#include <immintrin.h>\n__m256 f(__m256 a, __m256 b) { return _mm256_add_ps(a, b); }")
            .require("AVX addps 256 intrinsic", "llvm.x86.avx"),

        X86IRGenTest::new("ir_x86_avx_mulpd256", X86IRGenCategory::X86Specific,
            "#include <immintrin.h>\n__m256d f(__m256d a, __m256d b) { return _mm256_mul_pd(a, b); }")
            .require("AVX mulpd intrinsic", "llvm.x86.avx"),

        X86IRGenTest::new("ir_x86_avx_haddps256", X86IRGenCategory::X86Specific,
            "#include <immintrin.h>\n__m256 f(__m256 a, __m256 b) { return _mm256_hadd_ps(a, b); }")
            .require("AVX haddps intrinsic", "llvm.x86.avx"),

        X86IRGenTest::new("ir_x86_avx2_add_i32", X86IRGenCategory::X86Specific,
            "#include <immintrin.h>\n__m256i f(__m256i a, __m256i b) { return _mm256_add_epi32(a, b); }")
            .require("AVX2 integer add intrinsic", "llvm.x86.avx2"),

        // ── AVX-512 Intrinsics ──
        X86IRGenTest::new("ir_x86_avx512_addps512", X86IRGenCategory::X86Specific,
            "#include <immintrin.h>\n__m512 f(__m512 a, __m512 b) { return _mm512_add_ps(a, b); }")
            .with_flags(vec!["-mavx512f"])
            .require("AVX-512 addps intrinsic", "llvm.x86.avx512"),

        X86IRGenTest::new("ir_x86_avx512_mulpd512", X86IRGenCategory::X86Specific,
            "#include <immintrin.h>\n__m512d f(__m512d a, __m512d b) { return _mm512_mul_pd(a, b); }")
            .with_flags(vec!["-mavx512f"])
            .require("AVX-512 mulpd intrinsic", "llvm.x86.avx512"),

        X86IRGenTest::new("ir_x86_avx512_gather", X86IRGenCategory::X86Specific,
            "#include <immintrin.h>\n__m512 f(void *p, __m512i idx) { return _mm512_i32gather_ps(idx, p, 4); }")
            .with_flags(vec!["-mavx512f"])
            .require("AVX-512 gather intrinsic", "llvm.x86.avx512.gather"),

        // ── FMA Intrinsics ──
        X86IRGenTest::new("ir_x86_fma_fmadd", X86IRGenCategory::X86Specific,
            "#include <immintrin.h>\n__m256 f(__m256 a, __m256 b, __m256 c) { return _mm256_fmadd_ps(a, b, c); }")
            .with_flags(vec!["-mfma"])
            .require("FMA intrinsic", "llvm.fmuladd"),

        // ── Inline Assembly ──
        X86IRGenTest::new("ir_x86_inline_asm_basic", X86IRGenCategory::InlineAsm,
            "int f(void) { int x; __asm__(\"movl $42, %0\" : \"=r\"(x)); return x; }")
            .require("inline assembly", "call void asm"),

        X86IRGenTest::new("ir_x86_inline_asm_sideeffect", X86IRGenCategory::InlineAsm,
            "void f(void) { __asm__ volatile(\"nop\"); }")
            .require("volatile asm sideeffect", "sideeffect"),

        X86IRGenTest::new("ir_x86_inline_asm_input", X86IRGenCategory::InlineAsm,
            "int f(int a, int b) { int result; __asm__(\"addl %1, %0\" : \"=r\"(result) : \"r\"(a), \"0\"(b)); return result; }")
            .require("inline asm with inputs", "call void asm"),

        X86IRGenTest::new("ir_x86_inline_asm_clobber", X86IRGenCategory::InlineAsm,
            "void f(void) { __asm__ volatile(\"cpuid\" : : : \"eax\", \"ebx\", \"ecx\", \"edx\"); }")
            .require("inline asm with clobbers", "call void asm"),

        X86IRGenTest::new("ir_x86_inline_asm_alignstack", X86IRGenCategory::InlineAsm,
            "void f(void) { __asm__ volatile(\"nop\" : : : \"memory\"); }")
            .require("asm with memory clobber", "~{memory}"),

        // ── Target-specific attributes ──
        X86IRGenTest::new("ir_x86_target_cpu", X86IRGenCategory::X86Specific,
            "int f(void) { return 42; }")
            .with_flags(vec!["-march=skylake"])
            .require("target-cpu attribute", "target-cpu"),

        X86IRGenTest::new("ir_x86_target_features", X86IRGenCategory::X86Specific,
            "int f(void) { return 42; }")
            .with_flags(vec!["-mavx2"])
            .require("target-features attribute", "target-features"),

        X86IRGenTest::new("ir_x86_target_attr_func", X86IRGenCategory::X86Specific,
            "int f(void) __attribute__((target(\"sse4.2\"))); int f(void) { return 42; }")
            .require("function target attribute", "target-features"),

        // ── X86-specific data layout ──
        X86IRGenTest::new("ir_x86_data_layout", X86IRGenCategory::X86Specific,
            "int f(int x) { return x; }")
            .with_target("x86_64-unknown-linux-gnu")
            .require("data layout string", "target datalayout"),

        // ── X86 stack alignment ──
        X86IRGenTest::new("ir_x86_stack_alignment", X86IRGenCategory::X86Specific,
            "struct S { char buf[1024]; }; void f(struct S s) {}")
            .require("stack allocation", "alloca"),

        // ── X86 red zone ──
        X86IRGenTest::new("ir_x86_redzone", X86IRGenCategory::X86Specific,
            "int f(void) { int x = 0; return x; }")
            .with_target("x86_64-unknown-linux-gnu")
            .require("function definition with norecurse or similar", "define"),

        // ── Additional X86 intrinsics and instructions ──
        X86IRGenTest::new("ir_x86_bmi_blsr", X86IRGenCategory::X86Specific,
            "unsigned f(unsigned x) { return x & (x - 1); }")
            .with_flags(vec!["-mbmi"])
            .require("BLSR pattern", "llvm.x86.bmi"),

        X86IRGenTest::new("ir_x86_bmi_blsmsk", X86IRGenCategory::X86Specific,
            "unsigned f(unsigned x) { return x ^ (x - 1); }")
            .with_flags(vec!["-mbmi"])
            .require("BLSMSK pattern", "llvm.x86.bmi"),

        X86IRGenTest::new("ir_x86_lzcnt", X86IRGenCategory::X86Specific,
            "unsigned f(unsigned x) { return __builtin_clz(x); }")
            .with_flags(vec!["-mlzcnt"])
            .require("LZCNT intrinsic", "llvm.ctlz"),

        X86IRGenTest::new("ir_x86_tzcnt", X86IRGenCategory::X86Specific,
            "unsigned f(unsigned x) { return __builtin_ctz(x); }")
            .with_flags(vec!["-mbmi"])
            .require("TZCNT intrinsic", "llvm.cttz"),

        X86IRGenTest::new("ir_x86_popcnt", X86IRGenCategory::X86Specific,
            "int f(unsigned x) { return __builtin_popcount(x); }")
            .with_flags(vec!["-mpopcnt"])
            .require("POPCNT intrinsic", "llvm.ctpop"),

        X86IRGenTest::new("ir_x86_rdtsc", X86IRGenCategory::X86Specific,
            "#include <x86intrin.h>\nunsigned long long f() { return __rdtsc(); }")
            .require("RDTSC intrinsic", "llvm.x86.rdtsc"),

        X86IRGenTest::new("ir_x86_rdtscp", X86IRGenCategory::X86Specific,
            "#include <x86intrin.h>\nunsigned long long f(unsigned int *aux) { return __rdtscp(aux); }")
            .require("RDTSCP intrinsic", "llvm.x86.rdtscp"),

        X86IRGenTest::new("ir_x86_cpuid", X86IRGenCategory::X86Specific,
            "#include <cpuid.h>\nvoid f(unsigned int *eax, unsigned int *ebx, unsigned int *ecx, unsigned int *edx) { __cpuid(0, *eax, *ebx, *ecx, *edx); }")
            .require("CPUID inline asm", "cpuid"),

        X86IRGenTest::new("ir_x86_cmpxchg16b", X86IRGenCategory::X86Specific,
            "#include <stdatomic.h>\nbool f(_Atomic __int128 *p, __int128 *expected, __int128 desired) { return atomic_compare_exchange_strong(p, expected, desired); }")
            .with_flags(vec!["-mcx16"])
            .require("cmpxchg on i128", "cmpxchg i128"),

        X86IRGenTest::new("ir_x86_fxsave", X86IRGenCategory::X86Specific,
            "#include <x86intrin.h>\nvoid f(void *p) { _fxsave(p); }")
            .require("FXSAVE intrinsic", "llvm.x86.fxsave"),

        X86IRGenTest::new("ir_x86_mfence", X86IRGenCategory::X86Specific,
            "#include <x86intrin.h>\nvoid f(void) { _mm_mfence(); }")
            .require("MFENCE intrinsic", "llvm.x86.sse2.mfence"),

        X86IRGenTest::new("ir_x86_sfence", X86IRGenCategory::X86Specific,
            "#include <x86intrin.h>\nvoid f(void) { _mm_sfence(); }")
            .require("SFENCE intrinsic", "fence"),

        X86IRGenTest::new("ir_x86_lfence", X86IRGenCategory::X86Specific,
            "#include <x86intrin.h>\nvoid f(void) { _mm_lfence(); }")
            .require("LFENCE intrinsic", "fence"),

        X86IRGenTest::new("ir_x86_pause", X86IRGenCategory::X86Specific,
            "void f(void) { __asm__ volatile(\"pause\"); }")
            .require("pause instruction in inline asm", "pause"),

        X86IRGenTest::new("ir_x86_clflush", X86IRGenCategory::X86Specific,
            "#include <x86intrin.h>\nvoid f(void *p) { _mm_clflush(p); }")
            .require("CLFLUSH intrinsic", "llvm.x86.sse2.clflush"),

        // ── AVX-512 specific intrinsics ──
        X86IRGenTest::new("ir_x86_avx512_mask_add", X86IRGenCategory::X86Specific,
            "#include <immintrin.h>\n__m512 f(__m512 a, __m512 b, __mmask16 k) { return _mm512_mask_add_ps(a, k, b, a); }")
            .with_flags(vec!["-mavx512f"])
            .require("masked AVX-512 add", "llvm.x86.avx512"),

        X86IRGenTest::new("ir_x86_avx512_compress", X86IRGenCategory::X86Specific,
            "#include <immintrin.h>\n__m512 f(__m512 a, __mmask16 k, __m512 b) { return _mm512_mask_compress_ps(a, k, b); }")
            .with_flags(vec!["-mavx512f"])
            .require("AVX-512 compress intrinsic", "llvm.x86.avx512"),

        X86IRGenTest::new("ir_x86_avx512_expand", X86IRGenCategory::X86Specific,
            "#include <immintrin.h>\n__m512 f(__mmask16 k, __m512 a) { return _mm512_maskz_expand_ps(k, a); }")
            .with_flags(vec!["-mavx512f"])
            .require("AVX-512 expand intrinsic", "llvm.x86.avx512"),

        // ── X86 cmov instruction patterns ──
        X86IRGenTest::new("ir_x86_select_as_cmov", X86IRGenCategory::X86Specific,
            "int f(int a, int b, int cond) { return cond ? a : b; }")
            .require("select instruction for cmov", "select i32"),

        // ── X86 setcc patterns ──
        X86IRGenTest::new("ir_x86_setcc", X86IRGenCategory::X86Specific,
            "bool f(int a, int b) { return a < b; }")
            .require("setcc via icmp + zext", "icmp")
            .require("zext from i1 to i8", "zext"),

        // ── X86 _mm_prefetch ──
        X86IRGenTest::new("ir_x86_prefetch", X86IRGenCategory::X86Specific,
            "#include <xmmintrin.h>\nvoid f(void *p) { _mm_prefetch((const char*)p, _MM_HINT_T0); }")
            .require("prefetch intrinsic", "llvm.prefetch"),

        // ── X86 stack protector strong ──
        X86IRGenTest::new("ir_x86_stack_protector_strong", X86IRGenCategory::X86Specific,
            "void f(char *buf) { buf[0] = 'x'; }")
            .with_flags(vec!["-fstack-protector-strong"])
            .require("stack protector cookie", "__stack_chk_guard")
            .require("stack protector check", "__stack_chk_fail"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// STRESS / FUZZ-STYLE TESTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Build stress-test IR tests.
pub fn build_stress_tests() -> Vec<X86IRGenTest> {
    vec![
        // ── Deep nesting ──
        X86IRGenTest::new("ir_stress_deep_if_nesting", X86IRGenCategory::Stress,
            "int f(int a, int b, int c, int d, int e, int f, int g, int h) { \
             if (a) { if (b) { if (c) { if (d) { if (e) { if (f) { if (g) { if (h) { return 1; }}}}}} }} return 0; }")
            .require("deep if nesting branches", "br")
            .require_at_least("many conditional branches", "br i1", 3),

        // ── Large switch ──
        X86IRGenTest::new("ir_stress_large_switch", X86IRGenCategory::Stress,
            "int f(int x) { switch(x) { \
             case 0: case 1: case 2: case 3: case 4: \
             case 5: case 6: case 7: case 8: case 9: \
             case 10: case 11: case 12: case 13: case 14: case 15: \
             return 1; default: return 0; } }")
            .require("large switch", "switch"),

        // ── Many parameters ──
        X86IRGenTest::new("ir_stress_many_params", X86IRGenCategory::Stress,
            "int f(int a, int b, int c, int d, int e, int f_val, \
             int g, int h, int i, int j, int k, int l) { \
             return a + b + c + d + e + f_val + g + h + i + j + k + l; }")
            .require_at_least("function with many params", "i32", 12),

        // ── Large struct ──
        X86IRGenTest::new("ir_stress_large_struct", X86IRGenCategory::Stress,
            "struct Big { \
             int a0; int a1; int a2; int a3; int a4; \
             int a5; int a6; int a7; int a8; int a9; \
             int a10; int a11; int a12; int a13; int a14; int a15; }; \
             int f(struct Big b) { return b.a15; }")
            .require("large struct type in IR", "type"),

        // ── Many local variables ──
        X86IRGenTest::new("ir_stress_many_locals", X86IRGenCategory::Stress,
            "int f(void) { \
             int a = 1, b = 2, c = 3, d = 4, e = 5, \
             f_val = 6, g = 7, h = 8, i = 9, j = 10; \
             return a + b + c + d + e + f_val + g + h + i + j; }")
            .require_at_least("many alloca instructions", "alloca", 8),

        // ── Many function calls ──
        X86IRGenTest::new("ir_stress_many_calls", X86IRGenCategory::Stress,
            "int g(int x) { return x + 1; } \
             int h(int x) { return g(x) + g(x + 1) + g(x + 2); } \
             int f(int x) { return h(x) + h(x + 1) + h(x + 2); }")
            .require_at_least("multiple call instructions", "call", 5),

        // ── Complex expression tree ──
        X86IRGenTest::new("ir_stress_complex_expr", X86IRGenCategory::Stress,
            "int f(int a, int b, int c, int d) { \
             return (a + b) * (c - d) / ((a & b) | (c ^ d)) + \
             (a << 2) + (b >> 1) - ((~c) & d); }")
            .require_at_least("many arithmetic ops", "add", 2)
            .require_at_least("bitwise ops", "and", 1),

        // ── Pointer chains ──
        X86IRGenTest::new("ir_stress_ptr_chain", X86IRGenCategory::Stress,
            "int f(int ********p) { return ********p; }")
            .require("many pointer loads", "load"),

        // ── Additional stress tests ──
        X86IRGenTest::new("ir_stress_wide_struct", X86IRGenCategory::Stress,
            "struct Wide { long long a; double b; long long c; double d; long long e; double f; }; \
             double f(struct Wide w) { return w.a + w.b + w.c + w.d + w.e + w.f; }")
            .require("wide struct passing", "type"),

        X86IRGenTest::new("ir_stress_mixed_types", X86IRGenCategory::Stress,
            "int f(int a, float b, double c, char d, short e, long long f_val) { \
             return (int)(a + (int)b + (int)c + d + e + (int)f_val); }")
            .require_at_least("mixed type arithmetic", "sitofp", 1)
            .require_at_least("truncation for narrow types", "trunc", 1),

        X86IRGenTest::new("ir_stress_volatile_chain", X86IRGenCategory::Stress,
            "int f(volatile int *p) { \
             volatile int a = *p; volatile int b = a + 1; volatile int c = b * 2; \
             volatile int d = c - 3; return d; }")
            .require_at_least("volatile loads and stores", "volatile", 4),

        X86IRGenTest::new("ir_stress_nested_ternary", X86IRGenCategory::Stress,
            "int f(int a, int b, int c, int d) { \
             return a ? (b ? (c ? d : 0) : 1) : (b ? 2 : (c ? 3 : 4)); }")
            .require_at_least("nested select chains", "select", 3),

        X86IRGenTest::new("ir_stress_bitfield_extract", X86IRGenCategory::Stress,
            "struct S { unsigned a:1, b:2, c:3, d:4, e:5, f:6, g:7, h:4; }; \
             unsigned f(struct S s) { return s.a + s.b + s.c + s.d + s.e + s.f + s.g + s.h; }")
            .require("bitfield extraction operations", "and")
            .require("bitfield shifts", "shl"),

        X86IRGenTest::new("ir_stress_recursive_phi", X86IRGenCategory::Stress,
            "int f(int n) { if (n <= 0) return 0; return n + f(n-1); }")
            .require("recursive call", "call i32 @f"),

        X86IRGenTest::new("ir_stress_complex_gep", X86IRGenCategory::Stress,
            "struct A { int x; double y; }; struct B { struct A a[3]; int z; }; \
             double f(struct B *b, int i) { return b->a[i].y; }")
            .require("complex GEP chain", "getelementptr"),

        X86IRGenTest::new("ir_stress_switch_with_fallthrough", X86IRGenCategory::Stress,
            "int f(int x) { int r = 0; switch(x) { \
             case 1: r += 1; /* fallthrough */ \
             case 2: r += 2; break; \
             case 3: r += 4; /* fallthrough */ \
             default: r += 8; } return r; }")
            .require("switch with fallthrough", "switch"),

        X86IRGenTest::new("ir_stress_va_list", X86IRGenCategory::Stress,
            "#include <stdarg.h>\nint f(int n, ...) { va_list ap; va_start(ap, n); \
             int s = 0; for (int i = 0; i < n; i++) s += va_arg(ap, int); va_end(ap); return s; }")
            .require("va_start usage", "va_start"),

        X86IRGenTest::new("ir_stress_alloca_vla_nested", X86IRGenCategory::Stress,
            "#include <alloca.h>\nvoid f(int n, int m) { \
             int *a = alloca(n); int *b = alloca(m * 2); \
             a[0] = b[0]; }")
            .with_flags(vec!["-std=gnu99"])
            .require_at_least("multiple alloca calls", "alloca", 3),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// INTEGRATION TESTS
// ═══════════════════════════════════════════════════════════════════════════════

/// Build integration tests that verify multiple IR features at once.
pub fn build_integration_tests() -> Vec<X86IRGenTest> {
    vec![
        X86IRGenTest::new(
            "ir_integration_full_module",
            X86IRGenCategory::Integration,
            "int global = 42;\n\
                 static int hidden = 99;\n\
                 extern int external;\n\
                 struct Point { int x, y; };\n\
                 double compute(double a, double b, int op) {\n\
                   struct Point p = {1, 2};\n\
                   double result = a + b;\n\
                   if (op > 0) result = a * b;\n\
                   else if (op < 0) result = a / b;\n\
                   for (int i = 0; i < 10; i++) { result += i * 0.1; }\n\
                   return result + global + p.x;\n\
                 }",
        )
        .require("global variable", "@global")
        .require("internal linkage for static", "internal")
        .require("struct type", "type")
        .require("getelementptr for struct field", "getelementptr")
        .require("add instruction", "fadd double")
        .require("conditional branch", "br i1")
        .require("phi instruction (if-else merge)", "phi double")
        .require("loop branch", "br label"),
        X86IRGenTest::new(
            "ir_integration_recursive",
            X86IRGenCategory::Integration,
            "int factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1); }",
        )
        .require("recursive call", "call i32 @factorial")
        .require("conditional branch for base case", "br i1")
        .require("icmp sle for n <= 1", "icmp"),
        X86IRGenTest::new(
            "ir_integration_fibonacci",
            X86IRGenCategory::Integration,
            "int fib(int n) { if (n < 2) return n; return fib(n-1) + fib(n-2); }",
        )
        .require("recursive function with two calls", "call i32 @fib"),
        // ── Full pipeline: globals + functions + structs + control flow ──
        X86IRGenTest::new(
            "ir_integration_pipeline",
            X86IRGenCategory::Integration,
            "static int counter = 0; \
             struct Counter { int id; int (*inc)(struct Counter*); }; \
             static int inc_fn(struct Counter *c) { counter++; return ++c->id; } \
             int f(void) { \
               struct Counter c = {0, inc_fn}; \
               int a = c.inc(&c); \
               int b = c.inc(&c); \
               return a + b + counter; \
             }",
        )
        .require("function pointer in struct", "ptr")
        .require("indirect call", "call")
        .require("static global counter", "@counter")
        .require("internal function", "internal"),
        X86IRGenTest::new(
            "ir_integration_long_double_x86",
            X86IRGenCategory::Integration,
            "long double f(long double a, long double b, int op) { \
               if (op == 1) return a + b; \
               else if (op == 2) return a - b; \
               else if (op == 3) return a * b; \
               else return a / b; \
             }",
        )
        .require("x86_fp80 type", "x86_fp80")
        .require("long double arithmetic", "fadd x86_fp80")
        .require("conditional for op selection", "switch"),
        X86IRGenTest::new(
            "ir_integration_printf",
            X86IRGenCategory::Integration,
            "#include <stdio.h>\nint f(void) { printf(\"hello %d\\n\", 42); return 0; }",
        )
        .require("call to printf", "call")
        .require("string constant", "hello %d"),
    ]
}

// ═══════════════════════════════════════════════════════════════════════════════
// TEST SUITE BUILDER
// ═══════════════════════════════════════════════════════════════════════════════

/// Build the complete X86 IR generation test suite with all categories.
pub fn build_x86_ir_gen_suite() -> X86IRGenTestSuite {
    let mut suite = X86IRGenTestSuite::new(
        "x86_ir_gen",
        "Complete IR generation test suite for Clang on X86 — verifies correct \
         LLVM IR output for all C/C++ language features across types, constants, \
         instructions, memory operations, attributes, linkage, visibility, \
         calling conventions, C patterns, C++ patterns, and X86-specific patterns.",
    );

    suite.add_many(build_type_tests());
    suite.add_many(build_constant_tests());
    suite.add_many(build_memory_instruction_tests());
    suite.add_many(build_arithmetic_tests());
    suite.add_many(build_bitwise_tests());
    suite.add_many(build_comparison_tests());
    suite.add_many(build_control_flow_tests());
    suite.add_many(build_aggregate_tests());
    suite.add_many(build_call_tests());
    suite.add_many(build_memory_attr_tests());
    suite.add_many(build_function_attr_tests());
    suite.add_many(build_param_attr_tests());
    suite.add_many(build_linkage_tests());
    suite.add_many(build_visibility_tests());
    suite.add_many(build_calling_convention_tests());
    suite.add_many(build_debug_info_tests());
    suite.add_many(build_optimization_tests());
    suite.add_many(build_c_language_tests());
    suite.add_many(build_cxx_tests());
    suite.add_many(build_x86_specific_tests());
    suite.add_many(build_stress_tests());
    suite.add_many(build_integration_tests());

    suite
}

/// Get the total number of tests across all suites.
pub fn total_test_count() -> usize {
    let suite = build_x86_ir_gen_suite();
    suite.len()
}

/// Get a summary of test counts per category.
pub fn category_summary() -> BTreeMap<X86IRGenCategory, usize> {
    let suite = build_x86_ir_gen_suite();
    let mut map = BTreeMap::new();
    for cat in &[
        X86IRGenCategory::Types,
        X86IRGenCategory::Constants,
        X86IRGenCategory::Instructions,
        X86IRGenCategory::Arithmetic,
        X86IRGenCategory::MemoryAccess,
        X86IRGenCategory::ControlFlow,
        X86IRGenCategory::FunctionAttributes,
        X86IRGenCategory::ParameterAttributes,
        X86IRGenCategory::Linkage,
        X86IRGenCategory::Visibility,
        X86IRGenCategory::CallingConvention,
        X86IRGenCategory::CLanguage,
        X86IRGenCategory::CPlusPlus,
        X86IRGenCategory::X86Specific,
        X86IRGenCategory::Vectors,
        X86IRGenCategory::InlineAsm,
        X86IRGenCategory::ExceptionHandling,
        X86IRGenCategory::Atomics,
        X86IRGenCategory::Integration,
        X86IRGenCategory::DebugInfo,
        X86IRGenCategory::Optimization,
        X86IRGenCategory::Stress,
    ] {
        let count = suite.filter_by_category(*cat).len();
        if count > 0 {
            map.insert(*cat, count);
        }
    }
    map
}

// ═══════════════════════════════════════════════════════════════════════════════
// TEST RUNNER
// ═══════════════════════════════════════════════════════════════════════════════

/// Runner for executing X86IRGenTest cases and producing results.
#[derive(Debug, Clone)]
pub struct X86IRGenTestRunner {
    /// Options controlling compilation.
    pub options: X86CompileOptions,
    /// Verbose output flag.
    pub verbose: bool,
}

impl X86IRGenTestRunner {
    /// Create a new test runner with default options.
    pub fn new() -> Self {
        Self {
            options: X86CompileOptions {
                target: "x86_64-unknown-linux-gnu".to_string(),
                opt_level: X86OptLevel::O0,
                debug_info: false,
                flags: Vec::new(),
                ..Default::default()
            },
            verbose: false,
        }
    }

    /// Set verbose mode.
    pub fn verbose(mut self, v: bool) -> Self {
        self.verbose = v;
        self
    }

    /// Set target triple.
    pub fn with_target(mut self, target: &str) -> Self {
        self.options.target = target.to_string();
        self
    }

    /// Run a single test case and return the result.
    pub fn run_single(&self, test: &X86IRGenTest) -> X86IRGenTestResult {
        use std::time::Instant;
        let start = Instant::now();

        // Try to compile the source to IR
        let compile_result = compile_to_x86_ir(&test.source, &self.options);

        let duration_ms = start.elapsed().as_millis() as u64;

        match compile_result {
            Ok(ir_text) => {
                if !test.should_compile {
                    return X86IRGenTestResult {
                        name: test.name.clone(),
                        passed: false,
                        ir_text: Some(ir_text),
                        check_results: Vec::new(),
                        compiled: true,
                        compile_error: None,
                        duration_ms,
                    };
                }
                X86IRGenTestResult::from_test(test, &ir_text, true, None, duration_ms)
            }
            Err(err) => {
                if !test.should_compile {
                    return X86IRGenTestResult {
                        name: test.name.clone(),
                        passed: true,
                        ir_text: None,
                        check_results: Vec::new(),
                        compiled: false,
                        compile_error: Some(format!("{:?}", err)),
                        duration_ms,
                    };
                }
                X86IRGenTestResult::compile_failure(test, &format!("{:?}", err), duration_ms)
            }
        }
    }

    /// Run a full test suite and return results.
    pub fn run_suite(&self, suite: &X86IRGenTestSuite) -> Vec<X86IRGenTestResult> {
        let mut results = Vec::with_capacity(suite.len());
        for test in &suite.tests {
            let result = self.run_single(test);
            if self.verbose {
                println!("{}", result.summary());
            }
            results.push(result);
        }
        results
    }

    /// Run all tests and print a summary.
    pub fn run_all_and_summarize(&self) {
        let suite = build_x86_ir_gen_suite();
        let results = self.run_suite(&suite);
        let passed = results.iter().filter(|r| r.passed).count();
        let failed = results.len() - passed;

        println!("═══════════════════════════════════════════════════════════");
        println!("  X86 IR Generation Test Results");
        println!("═══════════════════════════════════════════════════════════");
        println!("  Total:  {}", results.len());
        println!("  Passed: {}", passed);
        println!("  Failed: {}", failed);
        println!("═══════════════════════════════════════════════════════════");

        if failed > 0 {
            println!("\n  Failed tests:");
            for r in &results {
                if !r.passed {
                    println!("{}", r.name);
                    for check in r.failed_checks() {
                        println!("      - {}", check);
                    }
                }
            }
        }

        // Category breakdown
        let cat_summary = category_summary();
        println!("\n  Category breakdown:");
        for (cat, count) in &cat_summary {
            let cat_results: Vec<_> = results
                .iter()
                .filter(|r| {
                    suite
                        .tests
                        .iter()
                        .any(|t| t.name == r.name && t.category == *cat)
                })
                .collect();
            let cat_passed = cat_results.iter().filter(|r| r.passed).count();
            println!(
                "    {:20} {:>4} tests, {:>4} passed",
                cat.as_str(),
                count,
                cat_passed
            );
        }
    }
}

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

impl Default for X86CompileOptions {
    fn default() -> Self {
        Self {
            target: "x86_64-unknown-linux-gnu".to_string(),
            opt_level: X86OptLevel::O0,
            debug_info: false,
            flags: Vec::new(),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// MODULE TESTS
// ═══════════════════════════════════════════════════════════════════════════════

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

    // ── Test Infrastructure Tests ──────────────────────────────────────

    #[test]
    fn test_pattern_required_found() {
        let pat = X86IRPattern::required("test", "hello");
        assert!(pat.check("hello world"));
    }

    #[test]
    fn test_pattern_required_not_found() {
        let pat = X86IRPattern::required("test", "zzz");
        assert!(!pat.check("hello world"));
    }

    #[test]
    fn test_pattern_exact_count_match() {
        let pat = X86IRPattern::exact("test", "a", 3);
        assert!(pat.check("a a a"));
        assert!(!pat.check("a a"));
        assert!(!pat.check("a a a a"));
    }

    #[test]
    fn test_pattern_at_least() {
        let pat = X86IRPattern::at_least("test", "x", 3);
        assert!(pat.check("x x x"));
        assert!(pat.check("x x x x"));
        assert!(!pat.check("x x"));
    }

    #[test]
    fn test_pattern_forbidden() {
        let pat = X86IRPattern::forbidden("test", "bad");
        assert!(pat.check("good stuff"));
    }

    #[test]
    fn test_pattern_forbidden_found() {
        let pat = X86IRPattern::forbidden("test", "bad");
        assert!(!pat.check("this is bad stuff"));
    }

    #[test]
    fn test_pattern_case_insensitive() {
        let pat = X86IRPattern::required("test", "ADD");
        assert!(pat.check("the add instruction"));
    }

    #[test]
    fn test_pattern_case_sensitive() {
        let mut pat = X86IRPattern::required("test", "ADD");
        pat.case_sensitive = true;
        assert!(!pat.check("the add instruction"));
        assert!(pat.check("the ADD instruction"));
    }

    // ── Test Builder Tests ────────────────────────────────────────────

    #[test]
    fn test_test_new() {
        let t = X86IRGenTest::new(
            "mytest",
            X86IRGenCategory::Types,
            "int f(void) { return 0; }",
        );
        assert_eq!(t.name, "mytest");
        assert_eq!(t.category, X86IRGenCategory::Types);
        assert!(!t.source.is_empty());
        assert!(t.should_compile);
        assert!(!t.is_xfail);
    }

    #[test]
    fn test_test_builder() {
        let t = X86IRGenTest::new(
            "test",
            X86IRGenCategory::Arithmetic,
            "int f(int a, int b) { return a + b; }",
        )
        .with_target("i686-unknown-linux-gnu")
        .with_flags(vec!["-O2", "-Wall"])
        .with_opt(X86OptLevel::O2)
        .require("add", "add")
        .require_exact("exact", "add", 1)
        .forbid("nofmul", "fmul")
        .with_expected_return(42);

        assert_eq!(t.target_triple, "i686-unknown-linux-gnu");
        assert_eq!(t.flags.len(), 2);
        assert_eq!(t.required_ir.len(), 2);
        assert_eq!(t.forbidden_ir.len(), 1);
        assert_eq!(t.expected_return, Some(42));
    }

    #[test]
    fn test_test_xfail() {
        let t = X86IRGenTest::new("fail", X86IRGenCategory::Types, "bad syntax")
            .xfail("Parser cannot handle this yet");
        assert!(t.is_xfail);
        assert_eq!(
            t.xfail_reason,
            Some("Parser cannot handle this yet".to_string())
        );
    }

    // ── Result Tests ──────────────────────────────────────────────────

    #[test]
    fn test_result_all_pass() {
        let test = X86IRGenTest::new("test", X86IRGenCategory::Types, "").require("found", "test");
        let result = X86IRGenTestResult::from_test(&test, "this is a test string", true, None, 10);
        assert!(result.passed);
        assert_eq!(result.check_results.len(), 1);
        assert!(result.check_results[0].passed);
    }

    #[test]
    fn test_result_some_fail() {
        let test = X86IRGenTest::new("test", X86IRGenCategory::Types, "")
            .require("found", "present")
            .require("not_found", "zzz_nope");
        let result =
            X86IRGenTestResult::from_test(&test, "this string has present in it", true, None, 5);
        assert!(!result.passed);
        assert_eq!(result.check_results.len(), 2);
        assert!(result.check_results[0].passed); // "present" found
        assert!(!result.check_results[1].passed); // "zzz_nope" not found
    }

    #[test]
    fn test_result_compile_failure() {
        let test =
            X86IRGenTest::new("cfail", X86IRGenCategory::Types, "bad").expect_compile_failure();
        let result = X86IRGenTestResult::compile_failure(&test, "parse error", 15);
        assert!(result.passed); // expected failure
        assert!(!result.compiled);
        assert!(result.ir_text.is_none());
    }

    #[test]
    fn test_result_compile_failure_when_expected_success() {
        let test = X86IRGenTest::new("cfail", X86IRGenCategory::Types, "bad");
        let result = X86IRGenTestResult::compile_failure(&test, "parse error", 15);
        assert!(!result.passed); // unexpected failure
    }

    #[test]
    fn test_result_summary_format() {
        let test = X86IRGenTest::new("mytest", X86IRGenCategory::Types, "");
        let result = X86IRGenTestResult::from_test(&test, "hello", true, None, 1);
        let summary = result.summary();
        assert!(summary.contains("mytest"));
        assert!(summary.contains("PASS") || summary.contains("FAIL"));
    }

    #[test]
    fn test_result_failed_checks() {
        let test = X86IRGenTest::new("f", X86IRGenCategory::Types, "")
            .require("a", "present")
            .require("b", "absent_in_text");
        let result = X86IRGenTestResult::from_test(&test, "present in text", true, None, 1);
        let failed = result.failed_checks();
        assert_eq!(failed.len(), 1);
        assert!(failed[0].contains("absent_in_text") || failed[0].contains("b"));
    }

    #[test]
    fn test_result_failed_count() {
        let test = X86IRGenTest::new("f", X86IRGenCategory::Types, "")
            .require("a", "x")
            .require("b", "y")
            .require("c", "z")
            .forbid("d", "x");

        let result = X86IRGenTestResult::from_test(&test, "just x here", true, None, 1);
        assert_eq!(result.failed_count(), 3); // y, z missing, x forbidden found
    }

    // ── Suite Tests ───────────────────────────────────────────────────

    #[test]
    fn test_suite_creation() {
        let suite = X86IRGenTestSuite::new("test", "A test suite");
        assert_eq!(suite.name, "test");
        assert_eq!(suite.description, "A test suite");
        assert!(suite.is_empty());
        assert_eq!(suite.len(), 0);
    }

    #[test]
    fn test_suite_add() {
        let mut suite = X86IRGenTestSuite::new("s", "d");
        suite.add(X86IRGenTest::new("t1", X86IRGenCategory::Types, ""));
        suite.add(X86IRGenTest::new("t2", X86IRGenCategory::Arithmetic, ""));
        assert_eq!(suite.len(), 2);
    }

    #[test]
    fn test_suite_add_many() {
        let mut suite = X86IRGenTestSuite::new("s", "d");
        let tests = vec![
            X86IRGenTest::new("t1", X86IRGenCategory::Types, ""),
            X86IRGenTest::new("t2", X86IRGenCategory::Arithmetic, ""),
            X86IRGenTest::new("t3", X86IRGenCategory::Types, ""),
        ];
        suite.add_many(tests);
        assert_eq!(suite.len(), 3);
    }

    #[test]
    fn test_suite_filter_by_category() {
        let mut suite = X86IRGenTestSuite::new("s", "d");
        suite.add(X86IRGenTest::new("t1", X86IRGenCategory::Types, ""));
        suite.add(X86IRGenTest::new("t2", X86IRGenCategory::Arithmetic, ""));
        suite.add(X86IRGenTest::new("t3", X86IRGenCategory::Types, ""));
        let types = suite.filter_by_category(X86IRGenCategory::Types);
        assert_eq!(types.len(), 2);
    }

    #[test]
    fn test_suite_filter_by_name() {
        let mut suite = X86IRGenTestSuite::new("s", "d");
        suite.add(X86IRGenTest::new("foo_bar", X86IRGenCategory::Types, ""));
        suite.add(X86IRGenTest::new("foo_baz", X86IRGenCategory::Types, ""));
        suite.add(X86IRGenTest::new("qux", X86IRGenCategory::Types, ""));
        let filtered = suite.filter_by_name("foo");
        assert_eq!(filtered.len(), 2);
    }

    // ── Suite Builder Tests ───────────────────────────────────────────

    #[test]
    fn test_type_tests_not_empty() {
        let tests = build_type_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_constant_tests_not_empty() {
        let tests = build_constant_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_memory_instruction_tests_not_empty() {
        let tests = build_memory_instruction_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_arithmetic_tests_not_empty() {
        let tests = build_arithmetic_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_bitwise_tests_not_empty() {
        let tests = build_bitwise_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_comparison_tests_not_empty() {
        let tests = build_comparison_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_control_flow_tests_not_empty() {
        let tests = build_control_flow_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_aggregate_tests_not_empty() {
        let tests = build_aggregate_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_call_tests_not_empty() {
        let tests = build_call_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_memory_attr_tests_not_empty() {
        let tests = build_memory_attr_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_function_attr_tests_not_empty() {
        let tests = build_function_attr_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_param_attr_tests_not_empty() {
        let tests = build_param_attr_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_linkage_tests_not_empty() {
        let tests = build_linkage_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_visibility_tests_not_empty() {
        let tests = build_visibility_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_calling_convention_tests_not_empty() {
        let tests = build_calling_convention_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_c_language_tests_not_empty() {
        let tests = build_c_language_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_cxx_tests_not_empty() {
        let tests = build_cxx_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_x86_specific_tests_not_empty() {
        let tests = build_x86_specific_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_stress_tests_not_empty() {
        let tests = build_stress_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_integration_tests_not_empty() {
        let tests = build_integration_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_full_suite_not_empty() {
        let suite = build_x86_ir_gen_suite();
        assert!(!suite.is_empty());
        assert!(suite.len() > 50);
    }

    #[test]
    fn test_total_test_count() {
        let count = total_test_count();
        assert!(count > 50, "Expected >50 tests, got {}", count);
    }

    #[test]
    fn test_category_summary_has_keys() {
        let summary = category_summary();
        assert!(!summary.is_empty());
        assert!(summary.contains_key(&X86IRGenCategory::Types));
        assert!(summary.contains_key(&X86IRGenCategory::Arithmetic));
        assert!(summary.contains_key(&X86IRGenCategory::ControlFlow));
    }

    #[test]
    fn test_category_summary_sums_to_total() {
        let summary = category_summary();
        let total_cat: usize = summary.values().sum();
        let total_all = total_test_count();
        assert_eq!(total_cat, total_all);
    }

    // ── Category Display Tests ────────────────────────────────────────

    #[test]
    fn test_category_as_str() {
        assert_eq!(X86IRGenCategory::Types.as_str(), "types");
        assert_eq!(X86IRGenCategory::Constants.as_str(), "constants");
        assert_eq!(X86IRGenCategory::Instructions.as_str(), "instructions");
        assert_eq!(X86IRGenCategory::Arithmetic.as_str(), "arithmetic");
        assert_eq!(X86IRGenCategory::MemoryAccess.as_str(), "memory");
        assert_eq!(X86IRGenCategory::ControlFlow.as_str(), "control_flow");
        assert_eq!(X86IRGenCategory::FunctionAttributes.as_str(), "fn_attrs");
        assert_eq!(
            X86IRGenCategory::ParameterAttributes.as_str(),
            "param_attrs"
        );
        assert_eq!(X86IRGenCategory::Linkage.as_str(), "linkage");
        assert_eq!(X86IRGenCategory::Visibility.as_str(), "visibility");
        assert_eq!(X86IRGenCategory::CallingConvention.as_str(), "calling_conv");
        assert_eq!(X86IRGenCategory::CLanguage.as_str(), "c_lang");
        assert_eq!(X86IRGenCategory::CPlusPlus.as_str(), "cxx");
        assert_eq!(X86IRGenCategory::X86Specific.as_str(), "x86");
        assert_eq!(X86IRGenCategory::Vectors.as_str(), "vectors");
        assert_eq!(X86IRGenCategory::InlineAsm.as_str(), "inline_asm");
        assert_eq!(X86IRGenCategory::ExceptionHandling.as_str(), "eh");
        assert_eq!(X86IRGenCategory::Atomics.as_str(), "atomics");
        assert_eq!(X86IRGenCategory::Integration.as_str(), "integration");
        assert_eq!(X86IRGenCategory::DebugInfo.as_str(), "debug_info");
        assert_eq!(X86IRGenCategory::Optimization.as_str(), "optimization");
        assert_eq!(X86IRGenCategory::Stress.as_str(), "stress");
    }

    // ── Content Verification Tests ────────────────────────────────────

    #[test]
    fn test_type_tests_cover_void() {
        let tests = build_type_tests();
        let void_tests: Vec<_> = tests.iter().filter(|t| t.name.contains("void")).collect();
        assert!(!void_tests.is_empty());
    }

    #[test]
    fn test_type_tests_cover_i32() {
        let tests = build_type_tests();
        let i32_tests: Vec<_> = tests.iter().filter(|t| t.name.contains("i32")).collect();
        assert!(!i32_tests.is_empty());
    }

    #[test]
    fn test_type_tests_cover_pointer() {
        let tests = build_type_tests();
        let ptr_tests: Vec<_> = tests.iter().filter(|t| t.name.contains("ptr")).collect();
        assert!(!ptr_tests.is_empty());
    }

    #[test]
    fn test_type_tests_cover_vector() {
        let tests = build_type_tests();
        let vec_tests: Vec<_> = tests.iter().filter(|t| t.name.contains("vector")).collect();
        assert!(!vec_tests.is_empty());
    }

    #[test]
    fn test_cmp_tests_cover_all_icmp_predicates() {
        let tests = build_comparison_tests();
        let predicates = [
            "eq", "ne", "sgt", "sge", "slt", "sle", "ugt", "uge", "ult", "ule",
        ];
        for pred in &predicates {
            let found = tests
                .iter()
                .any(|t| t.name.contains(&format!("icmp_{}", pred)));
            assert!(found, "Missing icmp predicate: {}", pred);
        }
    }

    #[test]
    fn test_cmp_tests_cover_fcmp_predicates() {
        let tests = build_comparison_tests();
        let predicates = ["oeq", "one", "ogt", "oge", "olt", "ole"];
        for pred in &predicates {
            let found = tests
                .iter()
                .any(|t| t.name.contains(&format!("fcmp_{}", pred)));
            assert!(found, "Missing fcmp predicate: {}", pred);
        }
    }

    #[test]
    fn test_memory_tests_cover_volatile() {
        let tests = build_memory_attr_tests();
        let vol_tests: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("volatile"))
            .collect();
        assert!(!vol_tests.is_empty());
    }

    #[test]
    fn test_memory_tests_cover_atomic() {
        let tests = build_memory_attr_tests();
        let atom_tests: Vec<_> = tests.iter().filter(|t| t.name.contains("atomic")).collect();
        assert!(!atom_tests.is_empty());
    }

    #[test]
    fn test_attribute_tests_cover_nounwind() {
        let tests = build_function_attr_tests();
        let nw_tests: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("nounwind"))
            .collect();
        assert!(!nw_tests.is_empty());
    }

    #[test]
    fn test_attribute_tests_cover_sanitizer() {
        let tests = build_function_attr_tests();
        let san_tests: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("sanitize"))
            .collect();
        assert!(!san_tests.is_empty());
    }

    #[test]
    fn test_linkage_tests_cover_weak() {
        let tests = build_linkage_tests();
        let weak_tests: Vec<_> = tests.iter().filter(|t| t.name.contains("weak")).collect();
        assert!(!weak_tests.is_empty());
    }

    #[test]
    fn test_linkage_tests_cover_internal() {
        let tests = build_linkage_tests();
        let int_tests: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("internal"))
            .collect();
        assert!(!int_tests.is_empty());
    }

    #[test]
    fn test_calling_conv_tests_cover_ccc() {
        let tests = build_calling_convention_tests();
        let ccc_tests: Vec<_> = tests.iter().filter(|t| t.name.contains("ccc")).collect();
        assert!(!ccc_tests.is_empty());
    }

    #[test]
    fn test_c_lang_tests_cover_compound_literal() {
        let tests = build_c_language_tests();
        let cl_tests: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("compound"))
            .collect();
        assert!(!cl_tests.is_empty());
    }

    #[test]
    fn test_c_lang_tests_cover_vla() {
        let tests = build_c_language_tests();
        let vla_tests: Vec<_> = tests.iter().filter(|t| t.name.contains("vla")).collect();
        assert!(!vla_tests.is_empty());
    }

    #[test]
    fn test_cxx_tests_cover_vtable() {
        let tests = build_cxx_tests();
        let vt_tests: Vec<_> = tests.iter().filter(|t| t.name.contains("vtable")).collect();
        assert!(!vt_tests.is_empty());
    }

    #[test]
    fn test_cxx_tests_cover_rtti() {
        let tests = build_cxx_tests();
        let rtti_tests: Vec<_> = tests.iter().filter(|t| t.name.contains("rtti")).collect();
        assert!(!rtti_tests.is_empty());
    }

    #[test]
    fn test_cxx_tests_cover_lambda() {
        let tests = build_cxx_tests();
        let lam_tests: Vec<_> = tests.iter().filter(|t| t.name.contains("lambda")).collect();
        assert!(!lam_tests.is_empty());
    }

    #[test]
    fn test_cxx_tests_cover_template() {
        let tests = build_cxx_tests();
        let tpl_tests: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("template"))
            .collect();
        assert!(!tpl_tests.is_empty());
    }

    #[test]
    fn test_cxx_tests_cover_eh_landingpad() {
        let tests = build_cxx_tests();
        let lp_tests: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("landingpad"))
            .collect();
        assert!(!lp_tests.is_empty());
    }

    #[test]
    fn test_x86_tests_cover_sse() {
        let tests = build_x86_specific_tests();
        let sse_tests: Vec<_> = tests.iter().filter(|t| t.name.contains("sse")).collect();
        assert!(!sse_tests.is_empty());
    }

    #[test]
    fn test_x86_tests_cover_avx() {
        let tests = build_x86_specific_tests();
        let avx_tests: Vec<_> = tests.iter().filter(|t| t.name.contains("avx")).collect();
        assert!(!avx_tests.is_empty());
    }

    #[test]
    fn test_x86_tests_cover_inline_asm() {
        let tests = build_x86_specific_tests();
        let asm_tests: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("inline_asm"))
            .collect();
        assert!(!asm_tests.is_empty());
    }

    #[test]
    fn test_stress_tests_cover_deep_nesting() {
        let tests = build_stress_tests();
        let deep_tests: Vec<_> = tests.iter().filter(|t| t.name.contains("deep")).collect();
        assert!(!deep_tests.is_empty());
    }

    // ── Pattern Sanity Tests ──────────────────────────────────────────

    #[test]
    fn test_all_required_patterns_are_well_formed() {
        let suite = build_x86_ir_gen_suite();
        for test in &suite.tests {
            for pat in &test.required_ir {
                assert!(
                    !pat.pattern.is_empty(),
                    "Empty pattern in test '{}': {}",
                    test.name,
                    pat.description
                );
                // Pattern should not be just whitespace
                assert!(
                    !pat.pattern.trim().is_empty(),
                    "Whitespace-only pattern in test '{}': {}",
                    test.name,
                    pat.description
                );
            }
            for pat in &test.forbidden_ir {
                assert!(
                    !pat.pattern.is_empty(),
                    "Empty forbidden pattern in test '{}': {}",
                    test.name,
                    pat.description
                );
            }
        }
    }

    #[test]
    fn test_all_tests_have_source() {
        let suite = build_x86_ir_gen_suite();
        for test in &suite.tests {
            assert!(
                !test.source.is_empty(),
                "Empty source in test '{}'",
                test.name
            );
        }
    }

    #[test]
    fn test_all_tests_have_unique_names() {
        let suite = build_x86_ir_gen_suite();
        let mut names = HashSet::new();
        for test in &suite.tests {
            if !names.insert(&test.name) {
                panic!("Duplicate test name: '{}'", test.name);
            }
        }
    }

    // ── Runner Tests ──────────────────────────────────────────────────

    #[test]
    fn test_runner_new() {
        let runner = X86IRGenTestRunner::new();
        assert!(!runner.verbose);
    }

    #[test]
    fn test_runner_verbose() {
        let runner = X86IRGenTestRunner::new().verbose(true);
        assert!(runner.verbose);
    }

    #[test]
    fn test_runner_with_target() {
        let runner = X86IRGenTestRunner::new().with_target("i686-unknown-linux-gnu");
        assert_eq!(runner.options.target, "i686-unknown-linux-gnu");
    }

    #[test]
    fn test_runner_default() {
        let runner: X86IRGenTestRunner = Default::default();
        assert!(!runner.verbose);
    }

    #[test]
    fn test_runner_run_single_trivial() {
        let runner = X86IRGenTestRunner::new();
        let test = X86IRGenTest::new("trivial", X86IRGenCategory::Types, "");
        // Empty source may fail compilation, but should not panic
        let result = runner.run_single(&test);
        assert_eq!(result.name, "trivial");
    }

    #[test]
    fn test_suite_builder_consistent() {
        // Building the suite twice should produce the same count
        let count1 = build_x86_ir_gen_suite().len();
        let count2 = build_x86_ir_gen_suite().len();
        assert_eq!(count1, count2);
    }

    #[test]
    fn test_no_panic_on_min_checks() {
        // All builder functions should return without panicking
        let _ = build_type_tests();
        let _ = build_constant_tests();
        let _ = build_memory_instruction_tests();
        let _ = build_arithmetic_tests();
        let _ = build_bitwise_tests();
        let _ = build_comparison_tests();
        let _ = build_control_flow_tests();
        let _ = build_aggregate_tests();
        let _ = build_call_tests();
        let _ = build_memory_attr_tests();
        let _ = build_function_attr_tests();
        let _ = build_param_attr_tests();
        let _ = build_linkage_tests();
        let _ = build_visibility_tests();
        let _ = build_calling_convention_tests();
        let _ = build_c_language_tests();
        let _ = build_cxx_tests();
        let _ = build_x86_specific_tests();
        let _ = build_stress_tests();
        let _ = build_integration_tests();
    }

    #[test]
    fn test_ir_gen_category_equality() {
        assert_eq!(X86IRGenCategory::Types, X86IRGenCategory::Types);
        assert_ne!(X86IRGenCategory::Types, X86IRGenCategory::Arithmetic);
    }

    #[test]
    fn test_ir_gen_category_hash() {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut h1 = DefaultHasher::new();
        let mut h2 = DefaultHasher::new();
        X86IRGenCategory::Types.hash(&mut h1);
        X86IRGenCategory::Types.hash(&mut h2);
        assert_eq!(h1.finish(), h2.finish());
    }

    #[test]
    fn test_pattern_count_basic() {
        let pat = X86IRPattern::required("test", "add");
        let text = "add sub add mul add";
        assert_eq!(pat.count_in(text), 3);
    }

    #[test]
    fn test_pattern_count_case_insensitive() {
        let pat = X86IRPattern::required("test", "ADD");
        let text = "add sub Add aDd";
        assert_eq!(pat.count_in(text), 3);
    }

    #[test]
    fn test_pattern_count_zero_for_nonexistent() {
        let pat = X86IRPattern::required("test", "nonexistent");
        assert_eq!(pat.count_in("some text"), 0);
    }

    #[test]
    fn test_result_ir_text_preserved() {
        let test = X86IRGenTest::new("t", X86IRGenCategory::Types, "");
        let result = X86IRGenTestResult::from_test(&test, "define i32 @f", true, None, 1);
        assert_eq!(result.ir_text, Some("define i32 @f".to_string()));
    }

    // ── Extended Pattern Tests ─────────────────────────────────────

    #[test]
    fn test_pattern_count_overlapping() {
        let pat = X86IRPattern::required("test", "aa");
        assert_eq!(pat.count_in("aaa"), 1); // non-overlapping
                                            // Note: Rust `matches` does NOT count overlapping matches
    }

    #[test]
    fn test_pattern_exact_zero() {
        let pat = X86IRPattern::exact("test", "x", 0);
        assert!(pat.check("no x here"));
        assert!(!pat.check("x here"));
    }

    #[test]
    fn test_pattern_check_edge_cases() {
        let pat = X86IRPattern::required("test", "");
        // Empty pattern matches between every character
        assert!(pat.check("anything"));
    }

    // ── Extended Result Tests ──────────────────────────────────────

    #[test]
    fn test_result_forbidden_check_passes_when_absent() {
        let test = X86IRGenTest::new("f", X86IRGenCategory::Types, "").forbid("no_mul", "mul");
        let result = X86IRGenTestResult::from_test(&test, "add sub div", true, None, 1);
        assert!(result.passed);
    }

    #[test]
    fn test_result_forbidden_check_fails_when_present() {
        let test = X86IRGenTest::new("f", X86IRGenCategory::Types, "").forbid("no_mul", "mul");
        let result = X86IRGenTestResult::from_test(&test, "add mul div", true, None, 1);
        assert!(!result.passed);
    }

    #[test]
    fn test_result_exact_count_passes() {
        let test = X86IRGenTest::new("e", X86IRGenCategory::Types, "").require_exact(
            "exactly two adds",
            "add",
            2,
        );
        let result = X86IRGenTestResult::from_test(&test, "add sub add", true, None, 5);
        assert!(result.passed);
    }

    #[test]
    fn test_result_exact_count_fails_under() {
        let test = X86IRGenTest::new("e", X86IRGenCategory::Types, "").require_exact(
            "exactly two adds",
            "add",
            2,
        );
        let result = X86IRGenTestResult::from_test(&test, "add sub", true, None, 5);
        assert!(!result.passed);
    }

    #[test]
    fn test_result_exact_count_fails_over() {
        let test = X86IRGenTest::new("e", X86IRGenCategory::Types, "").require_exact(
            "exactly two adds",
            "add",
            2,
        );
        let result = X86IRGenTestResult::from_test(&test, "add add add", true, None, 5);
        assert!(!result.passed);
    }

    #[test]
    fn test_result_at_least_passes_at_boundary() {
        let test =
            X86IRGenTest::new("a", X86IRGenCategory::Types, "").require_at_least("min 2", "add", 2);
        let result = X86IRGenTestResult::from_test(&test, "add add", true, None, 5);
        assert!(result.passed);
    }

    #[test]
    fn test_result_at_least_fails_below_boundary() {
        let test =
            X86IRGenTest::new("a", X86IRGenCategory::Types, "").require_at_least("min 2", "add", 2);
        let result = X86IRGenTestResult::from_test(&test, "add", true, None, 5);
        assert!(!result.passed);
    }

    #[test]
    fn test_result_names_match() {
        let test = X86IRGenTest::new("hello_test", X86IRGenCategory::Types, "");
        let result = X86IRGenTestResult::from_test(&test, "x", true, None, 0);
        assert_eq!(result.name, "hello_test");
    }

    // ── Category Hash Tests ────────────────────────────────────────

    #[test]
    fn test_category_hash_consistent() {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let categories = vec![
            X86IRGenCategory::Types,
            X86IRGenCategory::Constants,
            X86IRGenCategory::Instructions,
            X86IRGenCategory::Arithmetic,
            X86IRGenCategory::MemoryAccess,
            X86IRGenCategory::ControlFlow,
        ];

        for cat in &categories {
            let mut h1 = DefaultHasher::new();
            let mut h2 = DefaultHasher::new();
            cat.hash(&mut h1);
            cat.hash(&mut h2);
            assert_eq!(h1.finish(), h2.finish());
        }
    }

    // ── Suite Builder Extended Tests ──────────────────────────────

    #[test]
    fn test_suite_filter_empty() {
        let suite = X86IRGenTestSuite::new("empty", "");
        let filtered = suite.filter_by_category(X86IRGenCategory::Types);
        assert!(filtered.is_empty());
    }

    #[test]
    fn test_suite_filter_name_no_match() {
        let mut suite = X86IRGenTestSuite::new("s", "");
        suite.add(X86IRGenTest::new("abc", X86IRGenCategory::Types, ""));
        let filtered = suite.filter_by_name("xyz");
        assert!(filtered.is_empty());
    }

    #[test]
    fn test_suite_len_after_add_many() {
        let mut suite = X86IRGenTestSuite::new("s", "");
        suite.add_many(vec![
            X86IRGenTest::new("a", X86IRGenCategory::Types, ""),
            X86IRGenTest::new("b", X86IRGenCategory::Types, ""),
            X86IRGenTest::new("c", X86IRGenCategory::Types, ""),
            X86IRGenTest::new("d", X86IRGenCategory::Types, ""),
            X86IRGenTest::new("e", X86IRGenCategory::Types, ""),
        ]);
        assert_eq!(suite.len(), 5);
    }

    // ── X86 Specific Content Tests ─────────────────────────────────

    #[test]
    fn test_x86_tests_cover_avx512() {
        let tests = build_x86_specific_tests();
        let avx512: Vec<_> = tests.iter().filter(|t| t.name.contains("avx512")).collect();
        assert!(!avx512.is_empty());
    }

    #[test]
    fn test_x86_tests_cover_fma() {
        let tests = build_x86_specific_tests();
        let fma: Vec<_> = tests.iter().filter(|t| t.name.contains("fma")).collect();
        assert!(!fma.is_empty());
    }

    #[test]
    fn test_cxx_tests_cover_new_delete() {
        let tests = build_cxx_tests();
        let nd: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("new") || t.name.contains("delete"))
            .collect();
        assert!(!nd.is_empty());
    }

    #[test]
    fn test_cxx_tests_cover_ctor_dtor() {
        let tests = build_cxx_tests();
        let cd: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("ctor") || t.name.contains("dtor"))
            .collect();
        assert!(!cd.is_empty());
    }

    #[test]
    fn test_debug_info_tests_not_empty() {
        let tests = build_debug_info_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_optimization_tests_not_empty() {
        let tests = build_optimization_tests();
        assert!(!tests.is_empty());
    }

    // ── Cross-Category Coverage Tests ─────────────────────────────

    #[test]
    fn test_all_categories_have_tests() {
        let suite = build_x86_ir_gen_suite();
        let categories = [
            X86IRGenCategory::Types,
            X86IRGenCategory::Constants,
            X86IRGenCategory::Arithmetic,
            X86IRGenCategory::MemoryAccess,
            X86IRGenCategory::ControlFlow,
            X86IRGenCategory::FunctionAttributes,
            X86IRGenCategory::ParameterAttributes,
            X86IRGenCategory::Linkage,
            X86IRGenCategory::Visibility,
            X86IRGenCategory::CallingConvention,
            X86IRGenCategory::CLanguage,
            X86IRGenCategory::CPlusPlus,
            X86IRGenCategory::X86Specific,
        ];
        for cat in &categories {
            let count = suite.filter_by_category(*cat).len();
            assert!(count > 0, "Category {:?} has no tests", cat);
        }
    }

    // ── Pattern Validity Tests ─────────────────────────────────────

    #[test]
    fn test_all_patterns_nonempty_in_type_tests() {
        for test in &build_type_tests() {
            for pat in &test.required_ir {
                assert!(
                    !pat.pattern.is_empty(),
                    "Empty pattern in test '{}': '{}'",
                    test.name,
                    pat.description
                );
            }
            for pat in &test.forbidden_ir {
                assert!(
                    !pat.pattern.is_empty(),
                    "Empty forbidden pattern in test '{}' : '{}'",
                    test.name,
                    pat.description
                );
            }
        }
    }

    #[test]
    fn test_all_patterns_nonempty_in_constant_tests() {
        for test in &build_constant_tests() {
            for pat in &test.required_ir {
                assert!(!pat.pattern.is_empty());
            }
        }
    }

    #[test]
    fn test_all_patterns_nonempty_in_arithmetic_tests() {
        for test in &build_arithmetic_tests() {
            for pat in &test.required_ir {
                assert!(!pat.pattern.is_empty());
            }
        }
    }

    #[test]
    fn test_all_patterns_nonempty_in_comparison_tests() {
        for test in &build_comparison_tests() {
            for pat in &test.required_ir {
                assert!(!pat.pattern.is_empty());
            }
        }
    }

    #[test]
    fn test_all_patterns_nonempty_in_control_flow_tests() {
        for test in &build_control_flow_tests() {
            for pat in &test.required_ir {
                assert!(!pat.pattern.is_empty());
            }
        }
    }

    #[test]
    fn test_all_patterns_nonempty_in_linkage_tests() {
        for test in &build_linkage_tests() {
            for pat in &test.required_ir {
                assert!(!pat.pattern.is_empty());
            }
        }
    }

    #[test]
    fn test_all_patterns_nonempty_in_calling_convention_tests() {
        for test in &build_calling_convention_tests() {
            for pat in &test.required_ir {
                assert!(!pat.pattern.is_empty());
            }
        }
    }

    #[test]
    fn test_all_patterns_nonempty_in_c_tests() {
        for test in &build_c_language_tests() {
            for pat in &test.required_ir {
                assert!(!pat.pattern.is_empty());
            }
        }
    }

    #[test]
    fn test_all_patterns_nonempty_in_cxx_tests() {
        for test in &build_cxx_tests() {
            for pat in &test.required_ir {
                assert!(!pat.pattern.is_empty());
            }
        }
    }

    #[test]
    fn test_all_patterns_nonempty_in_x86_tests() {
        for test in &build_x86_specific_tests() {
            for pat in &test.required_ir {
                assert!(!pat.pattern.is_empty());
            }
        }
    }

    // ── Type Map Tests ─────────────────────────────────────────────

    #[test]
    fn test_type_map_not_empty() {
        let map = x86_type_map();
        assert!(!map.is_empty());
    }

    #[test]
    fn test_type_map_has_i32() {
        let map = x86_type_map();
        let has_i32 = map.iter().any(|t| t.ir_type == "i32");
        assert!(has_i32);
    }

    #[test]
    fn test_type_map_has_double() {
        let map = x86_type_map();
        let has_double = map.iter().any(|t| t.ir_type == "double");
        assert!(has_double);
    }

    #[test]
    fn test_type_map_has_pointer() {
        let map = x86_type_map();
        let has_ptr = map.iter().any(|t| t.ir_type == "ptr");
        assert!(has_ptr);
    }

    // ── Misc Infrastructure Tests ──────────────────────────────────

    #[test]
    fn test_ir_pattern_clone() {
        let p1 = X86IRPattern::required("hello", "world");
        let p2 = p1.clone();
        assert_eq!(p1.description, p2.description);
        assert_eq!(p1.pattern, p2.pattern);
    }

    #[test]
    fn test_ir_gen_test_clone() {
        let t1 = X86IRGenTest::new("test", X86IRGenCategory::Types, "src");
        let t2 = t1.clone();
        assert_eq!(t1.name, t2.name);
    }

    #[test]
    fn test_ir_gen_test_result_debug() {
        let test = X86IRGenTest::new("t", X86IRGenCategory::Types, "");
        let result = X86IRGenTestResult::from_test(&test, "x", true, None, 1);
        let _ = format!("{:?}", result);
    }

    #[test]
    fn test_suite_clone() {
        let suite = build_x86_ir_gen_suite();
        let _ = suite.clone();
    }

    #[test]
    fn test_runner_debug() {
        let runner = X86IRGenTestRunner::new();
        let _ = format!("{:?}", runner);
    }

    // ── Roundtrip Test Infrastructure Tests ────────────────────────

    #[test]
    fn test_roundtrip_tests_not_empty() {
        let tests = build_roundtrip_tests();
        assert!(!tests.is_empty());
        assert!(
            tests.len() >= 15,
            "Expected at least 15 roundtrip tests, got {}",
            tests.len()
        );
    }

    #[test]
    fn test_roundtrip_test_new() {
        let rt = RoundtripTest::new("test", "int f() { return 0; }");
        assert_eq!(rt.name, "test");
        assert!(rt.ir_stable_across_roundtrip);
    }

    #[test]
    fn test_roundtrip_test_clone() {
        let rt = RoundtripTest::new("t", "int f() { return 0; }");
        let rt2 = rt.clone();
        assert_eq!(rt.name, rt2.name);
    }

    #[test]
    fn test_all_roundtrip_tests_have_source() {
        for test in &build_roundtrip_tests() {
            assert!(!test.source.is_empty());
        }
    }

    #[test]
    fn test_all_roundtrip_tests_have_unique_names() {
        let tests = build_roundtrip_tests();
        let mut names = HashSet::new();
        for test in &tests {
            assert!(
                names.insert(&test.name),
                "Duplicate roundtrip test name: {}",
                test.name
            );
        }
    }

    // ── Differential Test Infrastructure Tests ─────────────────────

    #[test]
    fn test_differential_tests_not_empty() {
        let tests = build_differential_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_differential_test_new() {
        let dt = DifferentialIRTest::new("test", "int f() { return 0; }");
        assert_eq!(dt.name, "test");
        assert!(dt.baseline_flags.contains(&"-O0".to_string()));
    }

    #[test]
    fn test_differential_test_builder() {
        let dt = DifferentialIRTest::new("test", "int f() { return 0; }")
            .with_baseline(vec!["-O1"])
            .with_compare(vec!["-O3"]);
        assert!(dt.baseline_flags.contains(&"-O1".to_string()));
        assert!(dt.compare_flags.contains(&"-O3".to_string()));
    }

    #[test]
    fn test_all_differential_tests_have_source() {
        for test in &build_differential_tests() {
            assert!(!test.source.is_empty());
        }
    }

    #[test]
    fn test_differential_test_clone() {
        let dt = DifferentialIRTest::new("d", "int f() { return 0; }");
        let dt2 = dt.clone();
        assert_eq!(dt.name, dt2.name);
    }

    // ── Regression Test Infrastructure Tests ───────────────────────

    #[test]
    fn test_regression_registry_new() {
        let registry = RegressionRegistry::new();
        assert_eq!(registry.count(), 0);
    }

    #[test]
    fn test_regression_registry_register() {
        let mut registry = RegressionRegistry::new();
        registry.register(RegressionTestCase::new(
            "REG-TEST",
            "desc",
            "int f() { return 0; }",
        ));
        assert_eq!(registry.count(), 1);
    }

    #[test]
    fn test_regression_registry_fixed_count() {
        let mut registry = RegressionRegistry::new();
        registry.register(RegressionTestCase::new("A", "", "").fixed());
        registry.register(RegressionTestCase::new("B", "", ""));
        registry.register(RegressionTestCase::new("C", "", "").fixed());
        assert_eq!(registry.fixed_count(), 2);
        assert_eq!(registry.open_count(), 1);
    }

    #[test]
    fn test_regression_registry_by_id() {
        let mut registry = RegressionRegistry::new();
        registry.register(RegressionTestCase::new("FIND-ME", "target", ""));
        assert!(registry.by_id("FIND-ME").is_some());
        assert!(registry.by_id("NONEXISTENT").is_none());
    }

    #[test]
    fn test_build_regression_registry_not_empty() {
        let registry = build_regression_registry();
        assert!(registry.count() >= 5);
    }

    #[test]
    fn test_regression_test_case_builder() {
        let tc = RegressionTestCase::new("ID", "desc", "int f() { return 0; }")
            .with_expected("return 0", "ret i32 0")
            .with_forbidden("no mul", "mul")
            .with_date("2025-12-25")
            .with_issue("ISSUE-1")
            .fixed();
        assert_eq!(tc.expected_ir.len(), 1);
        assert_eq!(tc.forbidden_ir.len(), 1);
        assert_eq!(tc.date_added, "2025-12-25");
        assert_eq!(tc.issue_ref, Some("ISSUE-1".to_string()));
        assert!(tc.is_fixed);
    }

    #[test]
    fn test_regression_registry_default() {
        let registry: RegressionRegistry = Default::default();
        assert_eq!(registry.count(), 0);
    }

    // ── Delta Debugger Tests ───────────────────────────────────────

    #[test]
    fn test_delta_debugger_new() {
        let dd = IRDeltaDebugger::new("int main() { return 0; }");
        assert_eq!(dd.original, "int main() { return 0; }");
        assert_eq!(dd.iterations, 0);
        assert_eq!(dd.granularity, 2);
    }

    #[test]
    fn test_delta_debugger_with_granularity() {
        let dd = IRDeltaDebugger::new("x").with_granularity(8);
        assert_eq!(dd.granularity, 8);
    }

    #[test]
    fn test_delta_debugger_reset() {
        let mut dd = IRDeltaDebugger::new("hello");
        dd.current = "he".to_string();
        dd.iterations = 5;
        dd.reset();
        assert_eq!(dd.current, "hello");
        assert_eq!(dd.iterations, 0);
    }

    #[test]
    fn test_delta_debugger_reduction_ratio() {
        let mut dd = IRDeltaDebugger::new("abcdefgh");
        dd.current = "abcd".to_string();
        assert!((dd.reduction_ratio() - 0.5).abs() < 0.01);
    }

    #[test]
    fn test_delta_debugger_stats() {
        let mut dd = IRDeltaDebugger::new("hello world");
        dd.current = "hi".to_string();
        dd.iterations = 3;
        let stats = dd.stats();
        assert!(stats.contains("hello world"));
        assert!(stats.contains("hi"));
    }

    #[test]
    fn test_delta_debugger_empty_source() {
        let dd = IRDeltaDebugger::new("");
        assert_eq!(dd.reduction_ratio(), 0.0);
    }

    #[test]
    fn test_delta_debugger_minimize_lines_no_change() {
        let mut dd = IRDeltaDebugger::new("a\nb\nc");
        // Nothing is "interesting" on its own except the full text
        let result = dd.minimize_lines(|s| s == "a\nb\nc");
        assert_eq!(result, "a\nb\nc");
    }

    #[test]
    fn test_delta_debugger_minimize_chars_stable() {
        let mut dd = IRDeltaDebugger::new("xyz");
        let result = dd.minimize_chars(|s| s.len() >= 3);
        assert_eq!(result.len(), 3);
    }

    #[test]
    fn test_delta_debugger_clone() {
        let dd = IRDeltaDebugger::new("test");
        let dd2 = dd.clone();
        assert_eq!(dd.original, dd2.original);
    }

    #[test]
    fn test_regression_test_case_clone() {
        let tc = RegressionTestCase::new("ID", "desc", "src");
        let tc2 = tc.clone();
        assert_eq!(tc.id, tc2.id);
    }

    // ── Batch Verification Tests ───────────────────────────────────

    #[test]
    fn test_batch_result_new() {
        let test = X86IRGenTest::new("t", X86IRGenCategory::Types, "");
        let result = X86IRGenTestResult::from_test(&test, "x", true, None, 10);
        let batch = BatchVerificationResult::new("batch", vec![result.clone()]);
        assert_eq!(batch.total, 1);
        assert_eq!(batch.passed, 1);
        assert_eq!(batch.failed, 0);
        assert!(!batch.is_perfect() || batch.is_perfect());
    }

    #[test]
    fn test_batch_result_pass_rate() {
        let test1 = X86IRGenTest::new("t1", X86IRGenCategory::Types, "");
        let test2 =
            X86IRGenTest::new("t2", X86IRGenCategory::Types, "").require("not found", "zzz");
        let r1 = X86IRGenTestResult::from_test(&test1, "x", true, None, 1);
        let r2 = X86IRGenTestResult::from_test(&test2, "x", true, None, 1);
        let batch = BatchVerificationResult::new("b", vec![r1, r2]);
        assert!((batch.pass_rate() - 50.0).abs() < 0.01);
    }

    #[test]
    fn test_batch_result_summary_report() {
        let test = X86IRGenTest::new("t", X86IRGenCategory::Types, "");
        let result = X86IRGenTestResult::from_test(&test, "x", true, None, 5);
        let batch = BatchVerificationResult::new("mybatch", vec![result]);
        let report = batch.summary_report();
        assert!(report.contains("mybatch"));
        assert!(report.contains("Total:"));
        assert!(report.contains("Passed:"));
    }

    #[test]
    fn test_batch_result_empty() {
        let batch = BatchVerificationResult::new("empty", vec![]);
        assert_eq!(batch.total, 0);
        assert_eq!(batch.pass_rate(), 100.0);
        assert!(batch.is_perfect());
    }

    #[test]
    fn test_batch_result_clone() {
        let test = X86IRGenTest::new("t", X86IRGenCategory::Types, "");
        let result = X86IRGenTestResult::from_test(&test, "x", true, None, 1);
        let batch = BatchVerificationResult::new("b", vec![result]);
        let batch2 = batch.clone();
        assert_eq!(batch.total, batch2.total);
    }

    // ── IR Comparator Tests ────────────────────────────────────────

    #[test]
    fn test_ir_comparator_new() {
        let cmp = IRComparator::new();
        assert!(!cmp.ignore_metadata);
        assert!(!cmp.ignore_names);
    }

    #[test]
    fn test_ir_comparator_ignore_metadata() {
        let cmp = IRComparator::new().ignore_metadata();
        assert!(cmp.ignore_metadata);
    }

    #[test]
    fn test_ir_comparator_ignore_names() {
        let cmp = IRComparator::new().ignore_names();
        assert!(cmp.ignore_names);
    }

    #[test]
    fn test_ir_comparator_similarity_identical() {
        let cmp = IRComparator::new();
        let ir = "define i32 @f() {\n  ret i32 42\n}";
        let score = cmp.similarity(ir, ir);
        assert!((score - 1.0).abs() < 0.01);
    }

    #[test]
    fn test_ir_comparator_similarity_different() {
        let cmp = IRComparator::new();
        let a = "define i32 @f() { ret i32 42 }";
        let b = "define double @g() { ret double 3.14 }";
        let score = cmp.similarity(a, b);
        assert!(score < 0.5, "Expected low similarity, got {}", score);
    }

    #[test]
    fn test_ir_comparator_same_function_count() {
        let cmp = IRComparator::new();
        let a = "define void @f() { ret void }\ndefine i32 @g() { ret i32 1 }";
        let b = "define void @h() { ret void }\ndefine i32 @i() { ret i32 2 }";
        assert!(cmp.same_function_count(a, b));
    }

    #[test]
    fn test_ir_comparator_same_function_count_different() {
        let cmp = IRComparator::new();
        let a = "define void @f() { ret void }";
        let b = "define void @g() { ret void }\ndefine void @h() { ret void }";
        assert!(!cmp.same_function_count(a, b));
    }

    #[test]
    fn test_ir_comparator_same_global_names() {
        let cmp = IRComparator::new();
        let a = "@x = global i32 0\n@y = global i32 1";
        let b = "@y = global i32 1\n@x = global i32 0";
        assert!(cmp.same_global_names(a, b));
    }

    #[test]
    fn test_ir_comparator_same_global_names_different() {
        let cmp = IRComparator::new();
        let a = "@x = global i32 0";
        let b = "@y = global i32 0";
        assert!(!cmp.same_global_names(a, b));
    }

    #[test]
    fn test_ir_comparator_empty_strings() {
        let cmp = IRComparator::new();
        assert!((cmp.similarity("", "") - 1.0).abs() < 0.01);
        assert!((cmp.similarity("a", "") - 0.0).abs() < 0.01);
    }

    #[test]
    fn test_ir_comparator_default() {
        let cmp: IRComparator = Default::default();
        assert!(!cmp.ignore_metadata);
        assert!(!cmp.ignore_names);
        assert!(!cmp.ignore_comments);
        assert!(!cmp.ignore_debug_info);
    }

    // ── Additional Edge Case Content Tests ──────────────────────────

    #[test]
    fn test_type_tests_cover_signed_unsigned() {
        let tests = build_type_tests();
        let signed_tests: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("signed") || t.name.contains("unsigned"))
            .collect();
        assert!(signed_tests.len() >= 2);
    }

    #[test]
    fn test_constant_tests_cover_all_folds() {
        let tests = build_constant_tests();
        let fold_tests: Vec<_> = tests.iter().filter(|t| t.name.contains("fold")).collect();
        assert!(
            fold_tests.len() >= 5,
            "Expected >=5 fold tests, got {}",
            fold_tests.len()
        );
    }

    #[test]
    fn test_memory_tests_cover_all_load_sizes() {
        let tests = build_memory_instruction_tests();
        let load_tests: Vec<_> = tests
            .iter()
            .filter(|t| t.name.starts_with("ir_inst_load_"))
            .collect();
        // Should have load tests for i8, i16, i32, i64, float, double
        assert!(
            load_tests.len() >= 4,
            "Expected >=4 load tests, got {}",
            load_tests.len()
        );
    }

    #[test]
    fn test_control_flow_tests_cover_all_loop_types() {
        let tests = build_control_flow_tests();
        let loop_tests: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("loop") || t.name.contains("while"))
            .collect();
        assert!(!loop_tests.is_empty());
    }

    #[test]
    fn test_memory_attr_tests_cover_all_ordering() {
        let tests = build_memory_attr_tests();
        let ordering_tests: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("ordering"))
            .collect();
        assert!(ordering_tests.len() >= 3);
    }

    #[test]
    fn test_function_attr_tests_cover_sanitizers() {
        let tests = build_function_attr_tests();
        let san: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("sanitize"))
            .collect();
        assert!(
            san.len() >= 3,
            "Expected >=3 sanitizer attr tests, got {}",
            san.len()
        );
    }

    #[test]
    fn test_param_attr_tests_cover_zeroext_signext() {
        let tests = build_param_attr_tests();
        let zx: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("zeroext"))
            .collect();
        let sx: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("signext"))
            .collect();
        assert!(!zx.is_empty());
        assert!(!sx.is_empty());
    }

    #[test]
    fn test_visibility_tests_cover_hidden_protected() {
        let tests = build_visibility_tests();
        let hidden: Vec<_> = tests.iter().filter(|t| t.name.contains("hidden")).collect();
        let protected: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("protected"))
            .collect();
        assert!(!hidden.is_empty());
        assert!(!protected.is_empty());
    }

    #[test]
    fn test_c_lang_tests_cover_static_locals() {
        let tests = build_c_language_tests();
        let statics: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("static_local"))
            .collect();
        assert!(!statics.is_empty());
    }

    #[test]
    fn test_c_lang_tests_cover_implicit_conversions() {
        let tests = build_c_language_tests();
        let implicit: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("implicit"))
            .collect();
        assert!(!implicit.is_empty());
    }

    // ── Large scale structural tests ────────────────────────────────

    #[test]
    fn test_all_builders_return_vecs() {
        assert!(!build_type_tests().is_empty());
        assert!(!build_constant_tests().is_empty());
        assert!(!build_memory_instruction_tests().is_empty());
        assert!(!build_arithmetic_tests().is_empty());
        assert!(!build_bitwise_tests().is_empty());
        assert!(!build_comparison_tests().is_empty());
        assert!(!build_control_flow_tests().is_empty());
        assert!(!build_aggregate_tests().is_empty());
        assert!(!build_call_tests().is_empty());
        assert!(!build_memory_attr_tests().is_empty());
        assert!(!build_function_attr_tests().is_empty());
        assert!(!build_param_attr_tests().is_empty());
        assert!(!build_linkage_tests().is_empty());
        assert!(!build_visibility_tests().is_empty());
        assert!(!build_calling_convention_tests().is_empty());
        assert!(!build_debug_info_tests().is_empty());
        assert!(!build_optimization_tests().is_empty());
        assert!(!build_c_language_tests().is_empty());
        assert!(!build_cxx_tests().is_empty());
        assert!(!build_x86_specific_tests().is_empty());
        assert!(!build_stress_tests().is_empty());
        assert!(!build_integration_tests().is_empty());
    }

    #[test]
    fn test_minimum_test_counts() {
        assert!(build_type_tests().len() >= 15);
        assert!(build_constant_tests().len() >= 10);
        assert!(build_memory_instruction_tests().len() >= 10);
        assert!(build_arithmetic_tests().len() >= 10);
        assert!(build_comparison_tests().len() >= 15);
        assert!(build_control_flow_tests().len() >= 10);
        assert!(build_c_language_tests().len() >= 15);
        assert!(build_cxx_tests().len() >= 20);
        assert!(build_x86_specific_tests().len() >= 20);
        assert!(build_integration_tests().len() >= 3);
    }

    #[test]
    fn test_suite_total_count_meets_minimum() {
        let count = total_test_count();
        // We should have at least 150 tests total
        assert!(count >= 150, "Expected >=150 tests, got only {}", count);
    }

    // ── X86 Intrinsic Catalog Tests ────────────────────────────────

    #[test]
    fn test_intrinsic_catalog_not_empty() {
        let catalog = x86_intrinsic_catalog();
        assert!(!catalog.is_empty());
        assert!(
            catalog.len() >= 40,
            "Expected >=40 intrinsics, got {}",
            catalog.len()
        );
    }

    #[test]
    fn test_intrinsic_catalog_has_sse() {
        let catalog = x86_intrinsic_catalog();
        let sse_count = catalog.iter().filter(|i| i.isa_extension == "SSE").count();
        assert!(sse_count >= 10);
    }

    #[test]
    fn test_intrinsic_catalog_has_sse2() {
        let catalog = x86_intrinsic_catalog();
        let sse2_count = catalog.iter().filter(|i| i.isa_extension == "SSE2").count();
        assert!(sse2_count >= 10);
    }

    #[test]
    fn test_intrinsic_catalog_has_avx() {
        let catalog = x86_intrinsic_catalog();
        let avx_count = catalog.iter().filter(|i| i.isa_extension == "AVX").count();
        assert!(avx_count >= 5);
    }

    #[test]
    fn test_intrinsic_catalog_has_fma() {
        let catalog = x86_intrinsic_catalog();
        let fma_count = catalog.iter().filter(|i| i.isa_extension == "FMA").count();
        assert!(fma_count >= 2);
    }

    #[test]
    fn test_intrinsic_mapping_new() {
        let m = X86IntrinsicMapping::new("test", "llvm.test", "ISA", "hdr.h", "desc");
        assert_eq!(m.c_name, "test");
        assert_eq!(m.llvm_intrinsic, "llvm.test");
        assert_eq!(m.isa_extension, "ISA");
    }

    #[test]
    fn test_intrinsic_mapping_clone() {
        let m = X86IntrinsicMapping::new("a", "b", "c", "d", "e");
        let m2 = m.clone();
        assert_eq!(m.c_name, m2.c_name);
    }

    #[test]
    fn test_intrinsic_catalog_all_have_headers() {
        for m in &x86_intrinsic_catalog() {
            assert!(
                !m.header.is_empty(),
                "Intrinsic '{}' has empty header",
                m.c_name
            );
        }
    }

    #[test]
    fn test_intrinsic_catalog_unique_names() {
        let catalog = x86_intrinsic_catalog();
        let mut names = HashSet::new();
        for m in &catalog {
            assert!(
                names.insert(&m.c_name),
                "Duplicate intrinsic name: {}",
                m.c_name
            );
        }
    }

    // ── Additional Content Coverage Tests ───────────────────────────

    #[test]
    fn test_debug_info_tests_cover_dbg_declare() {
        let tests = build_debug_info_tests();
        let dbg: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("declare"))
            .collect();
        assert!(!dbg.is_empty());
    }

    #[test]
    fn test_debug_info_tests_forbid_no_g() {
        let tests = build_debug_info_tests();
        let no_g: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("without_g"))
            .collect();
        assert!(!no_g.is_empty());
    }

    #[test]
    fn test_opt_tests_cover_tail_call() {
        let tests = build_optimization_tests();
        let tc: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("tail_call"))
            .collect();
        assert!(!tc.is_empty());
    }

    #[test]
    fn test_opt_tests_cover_const_prop() {
        let tests = build_optimization_tests();
        let cp: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("constant_propagation"))
            .collect();
        assert!(!cp.is_empty());
    }

    #[test]
    fn test_opt_tests_cover_inlining() {
        let tests = build_optimization_tests();
        let il: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("inlining"))
            .collect();
        assert!(!il.is_empty());
    }

    #[test]
    fn test_opt_tests_cover_sroa() {
        let tests = build_optimization_tests();
        let sroa: Vec<_> = tests.iter().filter(|t| t.name.contains("sroa")).collect();
        assert!(!sroa.is_empty());
    }

    #[test]
    fn test_opt_tests_cover_all_O_levels() {
        let tests = build_optimization_tests();
        let o0: Vec<_> = tests.iter().filter(|t| t.name.contains("O0")).collect();
        let o1: Vec<_> = tests.iter().filter(|t| t.name.contains("O1")).collect();
        let o2: Vec<_> = tests.iter().filter(|t| t.name.contains("O2")).collect();
        assert!(!o0.is_empty() || !o1.is_empty());
        assert!(!o2.is_empty());
    }

    // ── X86-specific advanced content tests ─────────────────────────

    #[test]
    fn test_x86_tests_cover_stack_protector() {
        let tests = build_x86_specific_tests();
        let sp: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("stack") && t.name.contains("protect"))
            .collect();
        assert!(!sp.is_empty());
    }

    #[test]
    fn test_x86_tests_cover_fences() {
        let tests = build_x86_specific_tests();
        let fences: Vec<_> = tests
            .iter()
            .filter(|t| {
                t.name.contains("fence")
                    || t.name.contains("mfence")
                    || t.name.contains("lfence")
                    || t.name.contains("sfence")
            })
            .collect();
        assert!(!fences.is_empty());
    }

    #[test]
    fn test_x86_tests_cover_cache_ops() {
        let tests = build_x86_specific_tests();
        let cache: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("clflush") || t.name.contains("prefetch"))
            .collect();
        assert!(cache.len() >= 2);
    }

    #[test]
    fn test_cxx_tests_cover_eh_all_ops() {
        let tests = build_cxx_tests();
        assert!(tests.iter().any(|t| t.name.contains("landingpad")));
        assert!(tests.iter().any(|t| t.name.contains("invoke")));
        assert!(tests.iter().any(|t| t.name.contains("resume")));
    }

    #[test]
    fn test_cxx_tests_cover_member_pointers() {
        let tests = build_cxx_tests();
        let mp: Vec<_> = tests
            .iter()
            .filter(|t| t.name.contains("member_ptr"))
            .collect();
        assert!(mp.len() >= 2);
    }

    #[test]
    fn test_cxx_tests_cover_lambda_captures() {
        let tests = build_cxx_tests();
        let lambdas: Vec<_> = tests.iter().filter(|t| t.name.contains("lambda")).collect();
        assert!(
            lambdas.len() >= 3,
            "Expected >=3 lambda tests, got {}",
            lambdas.len()
        );
    }

    #[test]
    fn test_stress_tests_count() {
        let tests = build_stress_tests();
        assert!(
            tests.len() >= 10,
            "Expected >=10 stress tests, got {}",
            tests.len()
        );
    }

    #[test]
    fn test_all_tests_have_nonempty_source() {
        let suite = build_x86_ir_gen_suite();
        for test in &suite.tests {
            assert!(
                !test.source.is_empty(),
                "Test '{}' has empty source",
                test.name
            );
        }
    }

    #[test]
    fn test_all_tests_have_valid_category() {
        let suite = build_x86_ir_gen_suite();
        for test in &suite.tests {
            // Category should have a valid string representation
            let s = test.category.as_str();
            assert!(!s.is_empty());
        }
    }

    #[test]
    fn test_runner_single_result_has_name() {
        let runner = X86IRGenTestRunner::new();
        let test = X86IRGenTest::new("identity_test", X86IRGenCategory::Types, "");
        let result = runner.run_single(&test);
        assert_eq!(result.name, "identity_test");
    }

    #[test]
    fn test_runner_result_has_duration() {
        let runner = X86IRGenTestRunner::new();
        let test = X86IRGenTest::new("timed", X86IRGenCategory::Types, "");
        let result = runner.run_single(&test);
        // Duration should be >= 0
        assert!(result.duration_ms < 10000); // Shouldn't take more than 10s
    }

    // ── Edge Case Generator Tests ──────────────────────────────────

    #[test]
    fn test_edge_case_generator_new() {
        let gen = EdgeCaseGenerator::new();
        assert_eq!(gen.tests_generated, 0);
        assert!(gen.config.include_overflow);
    }

    #[test]
    fn test_edge_case_generator_overflow_tests() {
        let gen = EdgeCaseGenerator::new();
        let tests = gen.gen_overflow_tests();
        assert!(!tests.is_empty());
        assert!(tests.len() >= 3);
    }

    #[test]
    fn test_edge_case_generator_div_zero_tests() {
        let gen = EdgeCaseGenerator::new();
        let tests = gen.gen_div_zero_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_edge_case_generator_null_ptr_tests() {
        let gen = EdgeCaseGenerator::new();
        let tests = gen.gen_null_ptr_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_edge_case_generator_uninit_tests() {
        let gen = EdgeCaseGenerator::new();
        let tests = gen.gen_uninit_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_edge_case_generator_type_pun_tests() {
        let gen = EdgeCaseGenerator::new();
        let tests = gen.gen_type_pun_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_edge_case_generator_large_stack_tests() {
        let gen = EdgeCaseGenerator::new();
        let tests = gen.gen_large_stack_tests();
        assert!(!tests.is_empty());
    }

    #[test]
    fn test_edge_case_generator_generate_all() {
        let mut gen = EdgeCaseGenerator::new();
        let tests = gen.generate_all();
        assert!(!tests.is_empty());
        assert!(gen.tests_generated > 0);
        assert_eq!(gen.tests_generated, tests.len());
    }

    #[test]
    fn test_edge_case_generator_disabled_overflow() {
        let config = EdgeCaseConfig {
            include_overflow: false,
            ..Default::default()
        };
        let gen = EdgeCaseGenerator::new().with_config(config);
        let tests = gen.gen_overflow_tests();
        assert!(tests.is_empty());
    }

    #[test]
    fn test_edge_case_generator_disabled_div_zero() {
        let config = EdgeCaseConfig {
            include_div_zero: false,
            ..Default::default()
        };
        let gen = EdgeCaseGenerator::new().with_config(config);
        let tests = gen.gen_div_zero_tests();
        assert!(tests.is_empty());
    }

    #[test]
    fn test_edge_case_generator_disabled_all() {
        let config = EdgeCaseConfig {
            include_overflow: false,
            include_div_zero: false,
            include_null_ptr: false,
            include_uninit: false,
            include_type_pun: false,
            include_large_stack: false,
        };
        let mut gen = EdgeCaseGenerator::new().with_config(config);
        let tests = gen.generate_all();
        assert!(tests.is_empty());
    }

    #[test]
    fn test_edge_case_config_default() {
        let config = EdgeCaseConfig::default();
        assert!(config.include_overflow);
        assert!(config.include_div_zero);
        assert!(config.include_null_ptr);
        assert!(config.include_uninit);
        assert!(config.include_type_pun);
        assert!(config.include_large_stack);
    }

    #[test]
    fn test_edge_case_generator_default() {
        let gen: EdgeCaseGenerator = Default::default();
        assert_eq!(gen.tests_generated, 0);
    }

    #[test]
    fn test_edge_case_generator_clone() {
        let gen = EdgeCaseGenerator::new();
        let gen2 = gen.clone();
        assert_eq!(gen.config.include_overflow, gen2.config.include_overflow);
    }

    // ── IR Coverage Summary Tests ──────────────────────────────────

    #[test]
    fn test_ir_instruction_coverage_basic() {
        // Verify we have tests for all basic instruction types
        let suite = build_x86_ir_gen_suite();
        let all_names: HashSet<_> = suite.tests.iter().map(|t| &t.name).collect();

        // Alloca
        assert!(
            all_names.iter().any(|n| n.contains("alloca")),
            "Missing alloca test"
        );
        // Load
        assert!(
            all_names.iter().any(|n| n.contains("load")),
            "Missing load test"
        );
        // Store
        assert!(
            all_names.iter().any(|n| n.contains("store")),
            "Missing store test"
        );
        // GEP
        assert!(
            all_names.iter().any(|n| n.contains("gep")),
            "Missing GEP test"
        );
        // Branch
        assert!(
            all_names.iter().any(|n| n.contains("br")),
            "Missing branch test"
        );
        // Switch
        assert!(
            all_names.iter().any(|n| n.contains("switch")),
            "Missing switch test"
        );
        // Phi
        assert!(
            all_names.iter().any(|n| n.contains("phi")),
            "Missing phi test"
        );
        // Select
        assert!(
            all_names.iter().any(|n| n.contains("select")),
            "Missing select test"
        );
    }

    #[test]
    fn test_ir_arith_coverage() {
        let suite = build_x86_ir_gen_suite();
        let all_names: HashSet<_> = suite.tests.iter().map(|t| &t.name).collect();
        assert!(
            all_names.iter().any(|n| n.contains("add")),
            "Missing add test"
        );
        assert!(
            all_names.iter().any(|n| n.contains("sub")),
            "Missing sub test"
        );
        assert!(
            all_names.iter().any(|n| n.contains("mul")),
            "Missing mul test"
        );
        assert!(
            all_names.iter().any(|n| n.contains("sdiv")),
            "Missing sdiv test"
        );
        assert!(
            all_names.iter().any(|n| n.contains("udiv")),
            "Missing udiv test"
        );
    }

    #[test]
    fn test_ir_type_coverage_scalar() {
        let suite = build_x86_ir_gen_suite();
        let all_names: HashSet<_> = suite.tests.iter().map(|t| &t.name).collect();
        // Verify we have tests for the key scalar types
        let types = ["void", "i1", "i8", "i16", "i32", "i64", "float", "double"];
        for typ in &types {
            assert!(
                all_names.iter().any(|n| n.contains(typ)),
                "Missing type coverage for: {}",
                typ
            );
        }
    }

    #[test]
    fn test_ir_coverage_calling_conventions() {
        let suite = build_x86_ir_gen_suite();
        let all_names: HashSet<_> = suite.tests.iter().map(|t| &t.name).collect();
        let ccs = [
            "ccc",
            "fastcc",
            "coldcc",
            "x86_stdcallcc",
            "x86_fastcallcc",
            "x86_thiscallcc",
            "x86_vectorcallcc",
            "x86_regcallcc",
        ];
        for cc in &ccs {
            assert!(
                all_names.iter().any(|n| n.contains(cc)),
                "Missing calling convention coverage for: {}",
                cc
            );
        }
    }

    #[test]
    fn test_ir_coverage_linkage_types() {
        let suite = build_x86_ir_gen_suite();
        let all_names: HashSet<_> = suite.tests.iter().map(|t| &t.name).collect();
        let linkages = [
            "external",
            "internal",
            "private",
            "weak",
            "linkonce",
            "common",
            "extern_weak",
        ];
        for linkage in &linkages {
            assert!(
                all_names.iter().any(|n| n.contains(linkage)),
                "Missing linkage coverage for: {}",
                linkage
            );
        }
    }

    #[test]
    fn test_ir_coverage_visibility() {
        let suite = build_x86_ir_gen_suite();
        let all_names: HashSet<_> = suite.tests.iter().map(|t| &t.name).collect();
        assert!(
            all_names.iter().any(|n| n.contains("hidden")),
            "Missing hidden visibility test"
        );
        assert!(
            all_names.iter().any(|n| n.contains("protected")),
            "Missing protected visibility test"
        );
    }

    #[test]
    fn test_ir_coverage_x86_vector_sizes() {
        let features = build_x86_specific_tests();
        let names: Vec<_> = features.iter().map(|t| &t.name).collect();
        // Check for various vector sizes
        assert!(
            names
                .iter()
                .any(|n| n.contains("<2 x i64>") || n.contains("v2i64")),
            "Missing 2 x i64 vector test"
        );
        assert!(
            names
                .iter()
                .any(|n| n.contains("<4 x i32>") || n.contains("v4i32")),
            "Missing 4 x i32 vector test"
        );
        assert!(
            names
                .iter()
                .any(|n| n.contains("<8 x i16>") || n.contains("v8i16")),
            "Missing 8 x i16 vector test"
        );
        assert!(
            names
                .iter()
                .any(|n| n.contains("<16 x i8>") || n.contains("v16i8")),
            "Missing 16 x i8 vector test"
        );
    }

    // ── IR Compatibility / Well-formedness Tests ──────────────────

    #[test]
    fn test_all_tests_have_valid_target_triple() {
        let suite = build_x86_ir_gen_suite();
        for test in &suite.tests {
            assert!(
                !test.target_triple.is_empty(),
                "Test '{}' has empty target triple",
                test.name
            );
        }
    }

    #[test]
    fn test_all_required_patterns_are_checkable() {
        let suite = build_x86_ir_gen_suite();
        for test in &suite.tests {
            for pat in &test.required_ir {
                assert!(
                    pat.min_count <= 1000,
                    "Pattern '{}' in test '{}' has unreasonably high min_count: {}",
                    pat.description,
                    test.name,
                    pat.min_count
                );
            }
        }
    }

    #[test]
    fn test_suite_opt_levels_are_valid() {
        let suite = build_x86_ir_gen_suite();
        for test in &suite.tests {
            match test.opt_level {
                X86OptLevel::O0
                | X86OptLevel::O1
                | X86OptLevel::O2
                | X86OptLevel::O3
                | X86OptLevel::Os
                | X86OptLevel::Oz => {}
            }
        }
    }

    #[test]
    fn test_discover_categories_via_iteration() {
        let suite = build_x86_ir_gen_suite();
        let categories: HashSet<X86IRGenCategory> =
            suite.tests.iter().map(|t| t.category).collect();
        assert!(
            categories.len() >= 15,
            "Expected >=15 categories, got {}",
            categories.len()
        );
    }

    #[test]
    fn test_batch_result_count_by_category() {
        let suite = build_x86_ir_gen_suite();
        let test = X86IRGenTest::new("cat_test", X86IRGenCategory::Types, "");
        let result = X86IRGenTestResult::from_test(&test, "x", true, None, 1);
        let mut batch = BatchVerificationResult::new("cat_batch", vec![result]);
        batch.count_by_category(&suite);
    }

    #[test]
    fn test_ir_comparator_similarity_edge_cases() {
        let cmp = IRComparator::new();
        let a = "define void @f() { ret void }";
        let b = "define void @f() {\n  ret void\n}";
        let score = cmp.similarity(a, b);
        assert!(score > 0.0, "Expected non-zero similarity");
    }

    #[test]
    fn test_differential_tests_unique_names() {
        let tests = build_differential_tests();
        let mut names = HashSet::new();
        for t in &tests {
            assert!(
                names.insert(&t.name),
                "Duplicate differential test name: {}",
                t.name
            );
        }
    }

    #[test]
    fn test_regression_tests_unique_ids() {
        let registry = build_regression_registry();
        let mut ids = HashSet::new();
        for t in &registry.tests {
            assert!(ids.insert(&t.id), "Duplicate regression test ID: {}", t.id);
        }
    }

    #[test]
    fn test_delta_debugger_reduction_ratio_bound() {
        let dd = IRDeltaDebugger::new("test");
        let ratio = dd.reduction_ratio();
        assert!(
            ratio >= 0.0 && ratio <= 1.0,
            "Reduction ratio {} out of [0,1]",
            ratio
        );
    }

    // ── Stress and Robustness Tests ─────────────────────────────────

    #[test]
    fn test_suite_repeated_builds_consistent() {
        for _ in 0..10 {
            let count = build_x86_ir_gen_suite().len();
            assert!(count > 50);
        }
    }

    #[test]
    fn test_pattern_no_panic_on_empty_text() {
        let pat = X86IRPattern::required("test", "hello");
        let count = pat.count_in("");
        assert_eq!(count, 0);
        assert!(!pat.check(""));
    }

    #[test]
    fn test_pattern_no_panic_on_single_char() {
        let pat = X86IRPattern::required("test", "a");
        assert_eq!(pat.count_in("a"), 1);
        assert_eq!(pat.count_in("b"), 0);
    }

    #[test]
    fn test_pattern_no_panic_on_unicode() {
        let pat = X86IRPattern::required("test", "hello");
        let count = pat.count_in("héllo wörld");
        assert_eq!(count, 0);
    }

    #[test]
    fn test_runner_results_ordered() {
        let suite = build_x86_ir_gen_suite();
        let runner = X86IRGenTestRunner::new();
        let results = runner.run_suite(&suite);
        assert_eq!(results.len(), suite.len());
        for (i, result) in results.iter().enumerate() {
            assert_eq!(result.name, suite.tests[i].name);
        }
    }

    #[test]
    fn test_category_summary_every_category_counts() {
        let summary = category_summary();
        let total: usize = summary.values().sum();
        assert_eq!(total, total_test_count());
    }

    #[test]
    fn test_x86_intrinsic_catalog_llvm_prefix() {
        for m in &x86_intrinsic_catalog() {
            assert!(
                m.llvm_intrinsic.starts_with("llvm."),
                "Intrinsic '{}' does not start with llvm.",
                m.llvm_intrinsic
            );
        }
    }

    #[test]
    fn test_edge_case_generator_produces_valid_tests() {
        let mut gen = EdgeCaseGenerator::new();
        let tests = gen.generate_all();
        for test in &tests {
            assert!(!test.name.is_empty());
            assert!(!test.source.is_empty());
            assert!(test.should_compile);
        }
    }

    #[test]
    fn test_batch_verification_empty() {
        let batch = BatchVerificationResult::new("empty", vec![]);
        assert!(batch.is_perfect());
        assert!((batch.pass_rate() - 100.0).abs() < 0.01);
        let report = batch.summary_report();
        assert!(report.contains("empty"));
        assert!(report.contains("Total:"));
    }

    #[test]
    fn test_ir_comparator_full_config() {
        let cmp = IRComparator {
            ignore_metadata: true,
            ignore_names: true,
            ignore_comments: true,
            ignore_debug_info: true,
        };
        let a = "define void @f() {\n  ; comment\n  ret void\n}";
        let b = "define void @f() { ret void }";
        let score = cmp.similarity(a, b);
        assert!(score > 0.0, "Expected similarity with all ignore flags");
    }

    // ── Final Validation Tests ─────────────────────────────────────

    #[test]
    fn test_type_map_coverage_complete() {
        let map = x86_type_map();
        let types: HashSet<&str> = map.iter().map(|t| t.ir_type.as_str()).collect();
        assert!(types.contains("void"));
        assert!(types.contains("i1"));
        assert!(types.contains("i8"));
        assert!(types.contains("i16"));
        assert!(types.contains("i32"));
        assert!(types.contains("i64"));
        assert!(types.contains("float"));
        assert!(types.contains("double"));
        assert!(types.contains("x86_fp80"));
        assert!(types.contains("ptr"));
        assert!(types.contains("<4 x i32>"));
    }

    #[test]
    fn test_intrinsic_catalog_isa_extensions() {
        let catalog = x86_intrinsic_catalog();
        let mut isas = HashSet::new();
        for m in &catalog {
            isas.insert(m.isa_extension.as_str());
        }
        assert!(isas.contains("SSE"));
        assert!(isas.contains("SSE2"));
        assert!(isas.contains("SSE3"));
        assert!(isas.contains("SSSE3"));
        assert!(isas.contains("SSE4.1"));
        assert!(isas.contains("AVX"));
        assert!(isas.contains("AVX2"));
        assert!(isas.contains("FMA"));
    }

    #[test]
    fn test_full_suite_consistency() {
        let suite = build_x86_ir_gen_suite();
        let total = suite.len();
        let total2 = total_test_count();
        assert_eq!(total, total2, "Suite len and test count must match");
        let summary = category_summary();
        let cat_total: usize = summary.values().sum();
        assert_eq!(cat_total, total, "Category summary must sum to total");
    }

    #[test]
    fn test_edge_case_all_tests_should_compile() {
        let mut gen = EdgeCaseGenerator::new();
        let tests = gen.generate_all();
        for test in &tests {
            assert!(
                test.should_compile,
                "Edge test '{}' should compile by default",
                test.name
            );
        }
    }

    #[test]
    fn test_delta_debugger_minimize_lines_reduces_size() {
        let mut dd = IRDeltaDebugger::new("line1\nline2\nline3\nline4\nline5");
        // Only interesting if it contains "line1"
        let result = dd.minimize_lines(|s| s.contains("line1"));
        assert!(result.contains("line1"));
        assert!(result.len() <= dd.original.len());
    }

    #[test]
    fn test_verify_no_duplicate_pub_functions() {
        // This is a meta-test to ensure we haven't accidentally repeated public API
        // (runs as a compile-time / logic check)
        let suite1 = build_x86_ir_gen_suite();
        let suite2 = build_x86_ir_gen_suite();
        assert_eq!(suite1.len(), suite2.len());
        assert_eq!(total_test_count(), suite1.len());
    }

    // ── End of test module ───────────────────────────────────────────
    // Total test count across all categories exceeds 200 individual
    // IR verification checks covering every major LLVM IR construct
    // that Clang can emit for X86 targets.
}