llvm-native-core-ext 0.1.0

Extended modules for llvm-native-core: analysis passes, transforms, codegen extras, bitcode, linker, JIT, utilities. Part of the llvm-native workspace (https://crates.io/crates/llvm-native).
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
//! LLVM LTO — Link-Time Optimization framework.
//! Phase 7 — LLVM.LTO.1 Court.
//!
//! Clean-room behavioral reconstruction from the LLVM LTO design
//! documentation, ThinLTO RFC, and observable linker behavior. Zero
//! LLVM source code consultation.
//!
//! LTO enables inter-procedural optimization across translation units
//! at link time. Two modes are supported:
//!
//! - **Full LTO**: all modules are merged into one, then optimized
//!   monolithically. Best optimization quality, highest compile time.
//!
//! - **ThinLTO**: each module is optimized independently but with
//!   cross-module summary information. Scalable, parallel compilation.
//!
//! Key components:
//! - `LTOModule` — wraps an LLVM Module for LTO processing
//! - `ModuleSummaryIndex` — records per-module symbol summaries
//! - `CombinedLTOModule` — merged module for full LTO
//! - `ThinLTOImportDecider` — decides what to import from other modules
//! - `LTOCodeGenerator` — orchestrates the LTO pipeline

use llvm_native_core::linker;
use llvm_native_core::module::Module;
use llvm_native_core::passes;
use llvm_native_core::value::{SubclassKind, ValueRef};
use std::collections::{HashMap, HashSet};

// ============================================================================
// Symbol Resolution
// ============================================================================

/// Visibility level for a global symbol.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymbolVisibility {
    Default,
    Hidden,
    Protected,
}

/// Linkage type for global values.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlobalLinkage {
    External,
    AvailableExternally,
    LinkOnceAny,
    LinkOnceODR,
    WeakAny,
    WeakODR,
    Appending,
    Internal,
    Private,
    ExternalWeak,
    Common,
}

/// Resolution result for a symbol during LTO linking.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SymbolResolution {
    /// Symbol is defined in this module (prevailing definition)
    Prevailing,
    /// Symbol is defined in another module (non-prevailing)
    NonPrevailing,
    /// Symbol is unresolved (undefined reference)
    Undefined,
    /// Symbol is internal/private to this module
    Internal,
}

/// Information about a global symbol for LTO decisions.
#[derive(Debug, Clone)]
pub struct GlobalSummary {
    /// The symbol's name
    pub name: String,
    /// Which module index this symbol belongs to
    pub module_index: usize,
    /// Whether this is a function or a global variable
    pub is_function: bool,
    /// Estimated instruction count (for inlining decisions)
    pub instruction_count: u64,
    /// Whether this symbol is eligible for importing (ThinLTO)
    pub can_import: bool,
    /// Referenced global symbols
    pub refs: Vec<String>,
    /// Functions called by this function
    pub calls: Vec<String>,
    /// Read-only globals referenced
    pub readonly_refs: Vec<String>,
    /// Resolution status
    pub resolution: SymbolResolution,
}

// ============================================================================
// Module Summary Index (ThinLTO)
// ============================================================================

/// The Module Summary Index records per-module symbol summaries
/// used for ThinLTO cross-module optimization decisions.
#[derive(Debug, Clone)]
pub struct ModuleSummaryIndex {
    /// Map from module index to its symbol summaries
    pub module_summaries: Vec<Vec<GlobalSummary>>,
    /// Global map: symbol name → (module_index, summary_index)
    pub global_map: HashMap<String, (usize, usize)>,
    /// Symbols that have been resolved to a prevailing definition
    pub prevailing: HashSet<String>,
}

impl ModuleSummaryIndex {
    pub fn new() -> Self {
        Self {
            module_summaries: Vec::new(),
            global_map: HashMap::new(),
            prevailing: HashSet::new(),
        }
    }

    /// Add a module's symbol summaries to the index.
    pub fn add_module(&mut self, summaries: Vec<GlobalSummary>) -> usize {
        let module_idx = self.module_summaries.len();

        for (i, summary) in summaries.iter().enumerate() {
            self.global_map
                .insert(summary.name.clone(), (module_idx, i));
        }

        self.module_summaries.push(summaries);
        module_idx
    }

    /// Resolve symbol conflicts: for each symbol appearing in multiple
    /// modules, designate one as prevailing.
    pub fn resolve(&mut self, preserved_symbols: &HashSet<String>) {
        // Track which symbols have been seen and in which module
        let mut seen: HashMap<String, usize> = HashMap::new();

        for (mod_idx, summaries) in self.module_summaries.iter().enumerate() {
            for summary in summaries {
                let name = &summary.name;
                if let Some(&first_mod) = seen.get(name) {
                    // Symbol appears in multiple modules
                    // The first definition prevails (linker order)
                    if first_mod == mod_idx {
                        // This is the first definition — mark as prevailing
                        self.prevailing.insert(name.clone());
                    }
                    // Non-prevailing definitions can be internalized
                } else {
                    seen.insert(name.clone(), mod_idx);
                    // First occurrence — if it's preserved, mark prevailing
                    if preserved_symbols.contains(name) || mod_idx == 0 {
                        self.prevailing.insert(name.clone());
                    }
                }
            }
        }
    }

    /// Get the prevailing definition for a symbol.
    pub fn get_prevailing(&self, name: &str) -> Option<(usize, usize)> {
        if self.prevailing.contains(name) {
            self.global_map.get(name).copied()
        } else {
            None
        }
    }

    /// Check if a symbol can be imported from another module (ThinLTO).
    pub fn can_import(&self, name: &str, from_module: usize) -> bool {
        if let Some(&(mod_idx, sum_idx)) = self.global_map.get(name) {
            if mod_idx != from_module {
                let summary = &self.module_summaries[mod_idx][sum_idx];
                return summary.can_import;
            }
        }
        false
    }

    /// Get the estimated inline cost (instruction count) for a symbol.
    pub fn get_instruction_count(&self, name: &str) -> Option<u64> {
        if let Some(&(mod_idx, sum_idx)) = self.global_map.get(name) {
            Some(self.module_summaries[mod_idx][sum_idx].instruction_count)
        } else {
            None
        }
    }
}

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

// ============================================================================
// LTO Module
// ============================================================================

/// An LTO Module wraps an LLVM Module with LTO-specific metadata.
pub struct LTOModule {
    /// The underlying LLVM module
    pub module: Module,
    /// Module identifier
    pub id: String,
    /// Symbol summaries for this module
    pub summaries: Vec<GlobalSummary>,
    /// Symbols that must be preserved (not internalized)
    pub preserved_symbols: HashSet<String>,
    /// Whether this module has been optimized
    pub optimized: bool,
}

impl LTOModule {
    pub fn new(module: Module, id: &str) -> Self {
        let summaries = Self::compute_summaries(&module, 0);
        let preserved = Self::compute_preserved(&module);

        Self {
            module,
            id: id.to_string(),
            summaries,
            preserved_symbols: preserved,
            optimized: false,
        }
    }

    /// Compute per-function/global summaries from the module.
    fn compute_summaries(module: &Module, _mod_index: usize) -> Vec<GlobalSummary> {
        let mut summaries = Vec::new();

        for func in &module.functions {
            let f = func.borrow();
            let mut summary = GlobalSummary {
                name: f.name.clone(),
                module_index: 0,
                is_function: true,
                instruction_count: 0,
                can_import: true,
                refs: Vec::new(),
                calls: Vec::new(),
                readonly_refs: Vec::new(),
                resolution: SymbolResolution::Prevailing,
            };

            // Count instructions and record calls
            for op in &f.operands {
                let bb = op.borrow();
                if bb.is_basic_block() {
                    for inst in &bb.operands {
                        let i = inst.borrow();
                        if i.is_instruction() {
                            summary.instruction_count += 1;
                        }
                    }
                }
            }

            // Can't import functions with 0 instructions (declarations)
            if summary.instruction_count == 0 {
                summary.can_import = false;
            }

            summaries.push(summary);
        }

        // Also summarize globals
        for g in &module.globals {
            let gv = g.borrow();
            summaries.push(GlobalSummary {
                name: gv.name.clone(),
                module_index: 0,
                is_function: false,
                instruction_count: 0,
                can_import: false,
                refs: Vec::new(),
                calls: Vec::new(),
                readonly_refs: Vec::new(),
                resolution: SymbolResolution::Prevailing,
            });
        }

        summaries
    }

    /// Compute the set of symbols that must be preserved (exported).
    fn compute_preserved(module: &Module) -> HashSet<String> {
        let mut preserved = HashSet::new();

        for func in &module.functions {
            let f = func.borrow();
            // External or externally-visible functions are preserved
            preserved.insert(f.name.clone());
        }

        for g in &module.globals {
            let gv = g.borrow();
            preserved.insert(gv.name.clone());
        }

        preserved
    }

    /// Run intra-module optimizations (inlining, DCE, etc.).
    pub fn optimize(&mut self) -> usize {
        let mut total_removed = 0usize;

        for func in &self.module.functions {
            let removed = passes::eliminate_dead_code(func);
            total_removed += removed;

            let combined = passes::inst_combine(func);
            total_removed += combined;
        }

        // Promote memory to registers where possible
        for func in &self.module.functions {
            let promoted = passes::promote_memory_to_register(func);
            total_removed += promoted;
        }

        self.optimized = true;
        total_removed
    }

    /// Strip debug info and non-essential metadata.
    pub fn strip_debug_info(&mut self) {
        // Placeholder: in full LTO, debug info is often stripped
        // for the combined module and regenerated later
    }
}

// ============================================================================
// Combined LTO Module (Full LTO)
// ============================================================================

/// A Combined LTO Module merges multiple LTO modules into one
/// for monolithic full-LTO optimization.
pub struct CombinedLTOModule {
    /// The merged module
    pub module: Module,
    /// Original module IDs that were merged
    pub sources: Vec<String>,
    /// Total entities optimized
    pub entities_optimized: usize,
}

impl CombinedLTOModule {
    /// Create a combined module from multiple LTO modules.
    pub fn new(modules: &[LTOModule]) -> Self {
        let mut combined = Module::new("lto_combined");
        let mut sources = Vec::new();
        let mut entities = 0usize;

        for lto_mod in modules {
            sources.push(lto_mod.id.clone());

            // Link each source module into the combined module
            let linked = linker::link_modules(&mut combined, &lto_mod.module);
            entities += linked;
        }

        Self {
            module: combined,
            sources,
            entities_optimized: entities,
        }
    }

    /// Run full LTO optimization passes on the combined module.
    pub fn run_full_lto(&mut self) -> usize {
        let mut total_changes = 0usize;

        for func in &self.module.functions {
            // Dead code elimination
            total_changes += passes::eliminate_dead_code(func);

            // Memory to register promotion
            total_changes += passes::promote_memory_to_register(func);

            // CFG simplification
            total_changes += passes::simplify_cfg(func);

            // Instruction combining
            total_changes += passes::inst_combine(func);
        }

        self.entities_optimized = total_changes;
        total_changes
    }

    /// Internalize non-preserved symbols.
    pub fn internalize(&mut self, preserved: &HashSet<String>) -> usize {
        let mut internalized = 0usize;

        // Mark non-preserved functions
        self.module.functions.retain(|func| {
            let f = func.borrow();
            if preserved.contains(&f.name) || f.name.contains("llvm.") {
                true // keep
            } else {
                internalized += 1;
                true // keep for now, but mark as internal (placeholder)
            }
        });

        internalized
    }
}

// ============================================================================
// ThinLTO Import/Export
// ============================================================================

/// ThinLTO import decision: which symbols to import from other modules.
#[derive(Debug, Clone)]
pub struct ThinLTOImport {
    /// Symbol name to import
    pub symbol: String,
    /// Source module index
    pub from_module: usize,
    /// Reason for import (inline, devirtualization, etc.)
    pub reason: ImportReason,
}

/// Reasons for ThinLTO imports.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImportReason {
    /// Small function, good inlining candidate
    InlineCandidate,
    /// Virtual function for devirtualization
    Devirtualization,
    /// Referenced global with known constant value
    ConstantReference,
    /// Hot function called frequently
    HotCall,
}

/// ThinLTO import decider: determines which symbols to import
/// from other modules based on summary information.
pub struct ThinLTOImportDecider {
    /// Maximum instruction count for auto-import (inlining threshold)
    pub inline_threshold: u64,
    /// Maximum number of imports per module
    pub max_imports: usize,
}

impl ThinLTOImportDecider {
    pub fn new() -> Self {
        Self {
            inline_threshold: 100,
            max_imports: 256,
        }
    }

    /// Decide which symbols to import from other modules.
    pub fn decide_imports(
        &self,
        current_module: usize,
        index: &ModuleSummaryIndex,
        hot_symbols: &HashSet<String>,
    ) -> Vec<ThinLTOImport> {
        let mut imports = Vec::new();

        // Only consider modules other than the current one
        for (mod_idx, summaries) in index.module_summaries.iter().enumerate() {
            if mod_idx == current_module {
                continue;
            }

            for summary in summaries {
                if !summary.can_import {
                    continue;
                }

                // Small functions are good inlining candidates
                if summary.is_function && summary.instruction_count <= self.inline_threshold {
                    imports.push(ThinLTOImport {
                        symbol: summary.name.clone(),
                        from_module: mod_idx,
                        reason: ImportReason::InlineCandidate,
                    });
                    continue;
                }

                // Hot symbols should always be imported
                if hot_symbols.contains(&summary.name) {
                    imports.push(ThinLTOImport {
                        symbol: summary.name.clone(),
                        from_module: mod_idx,
                        reason: ImportReason::HotCall,
                    });
                }
            }
        }

        // Cap at max_imports
        if imports.len() > self.max_imports {
            imports.truncate(self.max_imports);
        }

        imports
    }

    /// Estimate the benefit of importing a given symbol.
    pub fn estimate_import_benefit(&self, summary: &GlobalSummary) -> u64 {
        if !summary.is_function {
            return 0;
        }

        // More instructions = more benefit from inlining (up to a point)
        // Fewer instructions = cheaper to import
        if summary.instruction_count == 0 {
            return 0;
        }

        // Simple heuristic: benefit is proportional to inst count
        // (more code inlined = more optimization opportunities)
        // but inversely proportional to import cost
        let benefit = summary.instruction_count.min(self.inline_threshold);
        let cost = summary.instruction_count;

        if cost == 0 {
            return 0;
        }

        benefit * 100 / cost
    }
}

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

// ============================================================================
// LTO Code Generator
// ============================================================================

/// The LTO Code Generator orchestrates the LTO compilation pipeline.
pub struct LTOCodeGenerator {
    /// All LTO modules being processed
    pub modules: Vec<LTOModule>,
    /// The module summary index (for ThinLTO)
    pub summary_index: ModuleSummaryIndex,
    /// Combined module (for full LTO)
    pub combined: Option<CombinedLTOModule>,
    /// LTO mode
    pub mode: LTOMode,
    /// Total optimizations applied
    pub total_optimizations: usize,
}

/// LTO compilation mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LTOMode {
    /// Full LTO: merge all modules, optimize monolithically
    Full,
    /// ThinLTO: optimize each module independently with cross-module summaries
    Thin,
}

impl LTOCodeGenerator {
    pub fn new(mode: LTOMode) -> Self {
        Self {
            modules: Vec::new(),
            summary_index: ModuleSummaryIndex::new(),
            combined: None,
            mode,
            total_optimizations: 0,
        }
    }

    /// Add a module to the LTO pipeline.
    pub fn add_module(&mut self, lto_module: LTOModule) {
        // Add summaries to the index
        let summaries = lto_module.summaries.clone();
        self.summary_index.add_module(summaries);

        self.modules.push(lto_module);
    }

    /// Run the LTO compilation pipeline.
    pub fn run(&mut self, preserved_symbols: &HashSet<String>) -> Result<usize, String> {
        // Resolve symbol conflicts
        self.summary_index.resolve(preserved_symbols);

        match self.mode {
            LTOMode::Full => self.run_full_lto(preserved_symbols),
            LTOMode::Thin => self.run_thin_lto(preserved_symbols),
        }
    }

    /// Full LTO: merge all modules and optimize.
    fn run_full_lto(&mut self, preserved_symbols: &HashSet<String>) -> Result<usize, String> {
        if self.modules.is_empty() {
            return Err("No modules for LTO".to_string());
        }

        // 1. Create combined module
        let mut combined = CombinedLTOModule::new(&self.modules);

        // 2. Internalize non-preserved symbols
        combined.internalize(preserved_symbols);

        // 3. Run full LTO optimization passes
        let changes = combined.run_full_lto();

        self.combined = Some(combined);
        self.total_optimizations = changes;

        Ok(changes)
    }

    /// ThinLTO: optimize each module independently with cross-module imports.
    fn run_thin_lto(&mut self, preserved_symbols: &HashSet<String>) -> Result<usize, String> {
        let mut total_changes = 0usize;
        let decider = ThinLTOImportDecider::new();

        // For each module, decide what to import and optimize locally
        for (mod_idx, lto_mod) in self.modules.iter_mut().enumerate() {
            // 1. Decide imports
            let imports = decider.decide_imports(mod_idx, &self.summary_index, preserved_symbols);

            // 2. Perform imports (placeholder: in real ThinLTO, this would
            //    copy function bodies from other modules)
            let mut _imported = 0usize;
            for imp in &imports {
                if self.summary_index.can_import(&imp.symbol, mod_idx) {
                    _imported += 1;
                }
            }

            // 3. Run intra-module optimizations
            let changes = lto_mod.optimize();
            total_changes += changes;
        }

        self.total_optimizations = total_changes;
        Ok(total_changes)
    }

    /// Get the output module(s) after LTO.
    pub fn output_modules(&self) -> Vec<&Module> {
        match self.mode {
            LTOMode::Full => {
                if let Some(ref combined) = self.combined {
                    vec![&combined.module]
                } else {
                    vec![]
                }
            }
            LTOMode::Thin => self.modules.iter().map(|m| &m.module).collect(),
        }
    }

    /// Get optimization statistics.
    pub fn stats(&self) -> LTOStats {
        LTOStats {
            mode: self.mode,
            num_modules: self.modules.len(),
            num_functions: self.modules.iter().map(|m| m.module.functions.len()).sum(),
            total_optimizations: self.total_optimizations,
            combined_size: self
                .combined
                .as_ref()
                .map(|c| c.module.functions.len())
                .unwrap_or(0),
            modules_processed: self.modules.len(),
            functions_internalized: 0,
            functions_imported: 0,
            globals_eliminated: 0,
            functions_merged: 0,
            total_instructions_before: 0,
            total_instructions_after: 0,
        }
    }
}

/// LTO compilation statistics.
#[derive(Debug, Clone)]
pub struct LTOStats {
    pub mode: LTOMode,
    pub num_modules: usize,
    pub num_functions: usize,
    pub total_optimizations: usize,
    pub combined_size: usize,
    /// Number of modules processed in this LTO run
    pub modules_processed: usize,
    /// Number of functions internalized (made non-exported)
    pub functions_internalized: usize,
    /// Number of functions imported from other modules (ThinLTO)
    pub functions_imported: usize,
    /// Number of dead globals eliminated
    pub globals_eliminated: usize,
    /// Number of functions merged/deduplicated
    pub functions_merged: usize,
    /// Total instruction count before optimization
    pub total_instructions_before: u64,
    /// Total instruction count after optimization
    pub total_instructions_after: u64,
}

// ============================================================================
// LTO Pipeline — comprehensive LTO compilation framework
// ============================================================================

/// LTO configuration options.
#[derive(Debug, Clone)]
pub struct LTOConfig {
    /// Enable ThinLTO (index-based) vs FullLTO (merged)
    pub use_thin_lto: bool,
    /// Number of parallel ThinLTO backend threads
    pub thin_lto_threads: u32,
    /// Enable internalization of non-exported symbols
    pub internalize: bool,
    /// Maximum instruction count for cross-module importing
    pub import_instr_limit: u32,
    /// Dead global elimination threshold
    pub dge_threshold: u32,
    /// Code generation optimization level
    pub cg_opt_level: u32,
    /// Save temporary files during compilation
    pub save_temps: bool,
}

impl Default for LTOConfig {
    fn default() -> Self {
        Self {
            use_thin_lto: false,
            thin_lto_threads: 4,
            internalize: true,
            import_instr_limit: 100,
            dge_threshold: 1,
            cg_opt_level: 2,
            save_temps: false,
        }
    }
}

/// Per-module summary for ThinLTO.
#[derive(Debug, Clone)]
pub struct ModuleSummary {
    /// Module name / identifier
    pub module_name: String,
    /// Hash of the module contents (for cache invalidation)
    pub module_hash: String,
    /// Function names defined in this module
    pub function_names: Vec<String>,
    /// Global variable names defined in this module
    pub global_names: Vec<String>,
}

/// Summary for one global value (function or variable).
#[derive(Debug, Clone)]
pub struct GlobalValueSummary {
    /// Symbol name
    pub name: String,
    /// Linkage type
    pub linkage: GlobalLinkage,
    /// Whether this is a function (true) or global variable (false)
    pub is_function: bool,
    /// Global Unique ID — hash of the mangled name
    pub guid: u64,
    /// Functions called by this function (callees)
    pub callees: Vec<String>,
    /// Is this function eligible for cross-module importing?
    pub is_import_eligible: bool,
    /// Number of instructions (for import cost model)
    pub instruction_count: u32,
    /// Entry count from profile data (for hot/cold decisions)
    pub entry_count: u64,
}

/// Summary for type identifiers (used for CFI and devirtualization).
#[derive(Debug, Clone)]
pub struct TypeIdSummary {
    /// Type identifier string
    pub type_id: String,
    /// Virtual table definitions associated with this type
    pub vtable_defs: Vec<String>,
}

/// Combined summary index used by the LTO pipeline.
#[derive(Debug, Clone)]
pub struct LTOSummary {
    /// Per-module summaries
    pub module_summaries: Vec<ModuleSummary>,
    /// Global value summary index (by name)
    pub global_summaries: HashMap<String, GlobalValueSummary>,
    /// Combined call graph: function name → callee names
    pub call_graph: HashMap<String, Vec<String>>,
    /// Type identifier summaries
    pub type_id_summaries: HashMap<String, TypeIdSummary>,
}

impl LTOSummary {
    pub fn new() -> Self {
        Self {
            module_summaries: Vec::new(),
            global_summaries: HashMap::new(),
            call_graph: HashMap::new(),
            type_id_summaries: HashMap::new(),
        }
    }

    /// Get a global value summary by name.
    pub fn get_global(&self, name: &str) -> Option<&GlobalValueSummary> {
        self.global_summaries.get(name)
    }

    /// Check if a function can be imported from another module.
    pub fn can_import(&self, name: &str) -> bool {
        self.global_summaries
            .get(name)
            .map(|s| s.is_import_eligible)
            .unwrap_or(false)
    }

    /// Get the instruction count for a function.
    pub fn get_instruction_count(&self, name: &str) -> Option<u32> {
        self.global_summaries.get(name).map(|s| s.instruction_count)
    }

    /// Get callees for a function.
    pub fn get_callees(&self, name: &str) -> Option<&Vec<String>> {
        self.call_graph.get(name)
    }
}

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

// ============================================================================
// LTO Pipeline Implementation
// ============================================================================

/// The main LTO compilation pipeline.
///
/// Orchestrates:
/// 1. Reading all input modules
/// 2. Building summary index
/// 3. Internalizing non-exported symbols
/// 4. Dead global elimination
/// 5. Cross-module function importing
/// 6. Running optimization passes on merged module
/// 7. Emitting optimized output
pub struct LTO {
    /// Input modules
    pub modules: Vec<Module>,
    /// Summary index for cross-module decisions
    pub summary: LTOSummary,
    /// Configuration
    pub config: LTOConfig,
    /// Optimization level
    pub opt_level: OptimizationLevel,
    /// Statistics
    pub stats: LTOStats,
}

/// Optimization level for the LTO pipeline.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OptimizationLevel {
    O0,
    O1,
    O2,
    O3,
    Os,
    Oz,
}

impl LTO {
    /// Create a new LTO pipeline with the given configuration.
    pub fn new(config: LTOConfig, opt_level: OptimizationLevel) -> Self {
        let use_thin = config.use_thin_lto;
        Self {
            modules: Vec::new(),
            summary: LTOSummary::new(),
            config,
            opt_level,
            stats: LTOStats {
                mode: if use_thin {
                    LTOMode::Thin
                } else {
                    LTOMode::Full
                },
                num_modules: 0,
                num_functions: 0,
                total_optimizations: 0,
                combined_size: 0,
                modules_processed: 0,
                functions_internalized: 0,
                functions_imported: 0,
                globals_eliminated: 0,
                functions_merged: 0,
                total_instructions_before: 0,
                total_instructions_after: 0,
            },
        }
    }

    /// Add an input module to the LTO pipeline.
    pub fn add_module(&mut self, module: Module) {
        self.stats.num_modules += 1;
        self.stats.num_functions += module.functions.len();
        self.modules.push(module);
    }

    /// Run the full LTO pipeline.
    /// Returns the optimized merged module (FullLTO) or nothing for ThinLTO.
    pub fn run(&mut self) -> Result<Module, String> {
        if self.modules.is_empty() {
            return Err("No modules for LTO".to_string());
        }

        // Phase 1: Build summaries
        self.build_summaries();

        // Count instructions before optimization
        self.stats.total_instructions_before = self.count_all_instructions();

        if self.config.use_thin_lto {
            // ThinLTO path
            self.run_thin_lto_pipeline()
        } else {
            // FullLTO path
            self.run_full_lto_pipeline()
        }
    }

    /// Run the Full LTO pipeline (monolithic optimization).
    fn run_full_lto_pipeline(&mut self) -> Result<Module, String> {
        // Phase 2: Internalize non-exported symbols
        let exported = self.find_exported_symbols();
        if self.config.internalize {
            self.internalize(&exported);
        }

        // Phase 3: Eliminate dead globals
        self.eliminate_dead_globals();

        // Phase 4: Merge all modules into one
        let mut merged = self.merge_modules()?;

        // Phase 5: Run optimization passes
        self.run_optimization_passes(&mut merged);

        // Count instructions after optimization
        self.stats.total_instructions_after = self.count_module_instructions(&merged);
        self.stats.combined_size = merged.functions.len();
        self.stats.modules_processed = self.modules.len();

        Ok(merged)
    }

    /// Run the ThinLTO pipeline (parallel, index-based).
    fn run_thin_lto_pipeline(&mut self) -> Result<Module, String> {
        // Phase 2: Build per-module summaries
        let module_summaries: Vec<ModuleSummary> = self
            .modules
            .iter()
            .map(|m| self.summarize_module(m))
            .collect();
        self.summary.module_summaries = module_summaries;

        // Phase 3: Compute import decisions
        let import_decisions = self.compute_import_decisions();

        // Phase 4: Import functions into each module
        self.apply_imported_functions(&import_decisions);

        // Phase 5: Internalize non-exported symbols
        let exported = self.find_exported_symbols();
        if self.config.internalize {
            self.internalize(&exported);
        }

        // Phase 6: Run per-module optimization backends
        // (In real ThinLTO, each backend runs in parallel)
        let mut optimized_modules: Vec<Module> = Vec::new();
        for (i, _summary) in self.summary.module_summaries.iter().enumerate() {
            if i < self.modules.len() {
                let mut mod_copy = self.modules[i].clone();
                self.run_thin_lto_backend(&mut mod_copy);
                optimized_modules.push(mod_copy);
            }
        }

        // Phase 7: Merge optimized modules (for final output)
        let merged = if optimized_modules.is_empty() {
            Module::new("lto_thin_combined")
        } else {
            let mut linker = llvm_native_core::linker::IRLinker::new(optimized_modules.remove(0));
            for m in optimized_modules {
                linker.add_source(m);
            }
            linker.link().module
        };

        self.stats.total_instructions_after = self.count_module_instructions(&merged);
        self.stats.combined_size = merged.functions.len();
        self.stats.modules_processed = self.modules.len();

        Ok(merged)
    }

    // ------------------------------------------------------------------
    // Summary Building
    // ------------------------------------------------------------------

    /// Build module and global summaries from all input modules.
    pub fn build_summaries(&mut self) {
        self.summary = LTOSummary::new();

        for module in &self.modules {
            let mod_summary = self.summarize_module(module);

            // Build global value summaries for each function
            for func in &module.functions {
                let f = func.borrow();
                let gv_summary = self.summarize_function(func);
                self.summary
                    .global_summaries
                    .insert(f.name.clone(), gv_summary);
            }

            // Build global value summaries for each global variable
            for g in &module.globals {
                let gv = g.borrow();
                let gv_summary = self.summarize_global(g);
                self.summary
                    .global_summaries
                    .insert(gv.name.clone(), gv_summary);
            }

            self.summary.module_summaries.push(mod_summary);
        }

        // Build the combined call graph
        self.summary.call_graph = self.build_call_graph();
    }

    /// Create a per-module summary.
    pub fn summarize_module(&self, module: &Module) -> ModuleSummary {
        let function_names: Vec<String> = module
            .functions
            .iter()
            .map(|f| f.borrow().name.clone())
            .collect();

        let global_names: Vec<String> = module
            .globals
            .iter()
            .map(|g| g.borrow().name.clone())
            .collect();

        // Simple hash: concatenation of function names
        let hash_input: String = function_names.iter().cloned().collect::<Vec<_>>().join(",");
        let module_hash = format!("{:016x}", Self::compute_guid(&hash_input));

        ModuleSummary {
            module_name: module.name.clone(),
            module_hash,
            function_names,
            global_names,
        }
    }

    /// Create a summary for a global variable.
    pub fn summarize_global(&self, value: &ValueRef) -> GlobalValueSummary {
        let gv = value.borrow();
        GlobalValueSummary {
            name: gv.name.clone(),
            linkage: self.infer_global_linkage(&gv),
            is_function: false,
            guid: Self::compute_guid(&gv.name),
            callees: Vec::new(),
            is_import_eligible: false, // globals are not imported by default
            instruction_count: 0,
            entry_count: 0,
        }
    }

    /// Create a summary for a function.
    pub fn summarize_function(&self, func: &ValueRef) -> GlobalValueSummary {
        let f = func.borrow();
        let inst_count = self.count_function_instructions(&f);
        let callees = self.compute_call_graph_for_func(&f);
        let is_eligible = inst_count > 0
            && inst_count <= self.config.import_instr_limit
            && self.infer_global_linkage(&f) != GlobalLinkage::Internal
            && self.infer_global_linkage(&f) != GlobalLinkage::Private;

        GlobalValueSummary {
            name: f.name.clone(),
            linkage: self.infer_global_linkage(&f),
            is_function: true,
            guid: Self::compute_guid(&f.name),
            callees,
            is_import_eligible: is_eligible,
            instruction_count: inst_count,
            entry_count: 0, // would come from profile data
        }
    }

    /// Compute the call graph from all modules.
    pub fn build_call_graph(&self) -> HashMap<String, Vec<String>> {
        let mut cg: HashMap<String, Vec<String>> = HashMap::new();

        for module in &self.modules {
            for func in &module.functions {
                let f = func.borrow();
                let callees = self.compute_call_graph_for_func(&f);
                cg.insert(f.name.clone(), callees);
            }
        }

        cg
    }

    /// Compute the set of callees for a single function.
    pub fn compute_call_graph_for_func(&self, func: &llvm_native_core::value::Value) -> Vec<String> {
        let mut callees = Vec::new();
        // Walk basic blocks and look for call instructions
        for op in &func.operands {
            let bb = op.borrow();
            if bb.subclass == SubclassKind::BasicBlock {
                for inst_ref in &bb.operands {
                    let inst = inst_ref.borrow();
                    // Check if this is a call instruction
                    if let Some(opcode) = inst.opcode {
                        if format!("{:?}", opcode).contains("Call") {
                            for operand in &inst.operands {
                                let op_val = operand.borrow();
                                if op_val.subclass == SubclassKind::Function {
                                    callees.push(op_val.name.clone());
                                }
                            }
                        }
                    }
                }
            }
        }
        callees
    }

    /// Compute a Global Unique ID (GUID) from a symbol name.
    /// Uses a simple FNV-like hash for the GUID.
    pub fn compute_guid(name: &str) -> u64 {
        let mut hash: u64 = 0xcbf29ce484222325;
        for byte in name.bytes() {
            hash ^= byte as u64;
            hash = hash.wrapping_mul(0x100000001b3);
        }
        hash
    }

    // ------------------------------------------------------------------
    // Internalization
    // ------------------------------------------------------------------

    /// Internalize non-exported symbols across all modules.
    pub fn internalize(&mut self, exported: &HashSet<String>) {
        let mut total_count = 0usize;
        let module_count = self.modules.len();

        for i in 0..module_count {
            let count = run_internalization_on_module(&mut self.modules[i], exported);
            total_count += count;
        }

        self.stats.functions_internalized += total_count;
    }
}

/// Free function: infer GlobalLinkage from a Value.
fn infer_linkage_from_value(v: &llvm_native_core::value::Value) -> GlobalLinkage {
    if v.name.starts_with("llvm.") {
        return GlobalLinkage::Internal;
    }
    if v.name.starts_with(".L") {
        return GlobalLinkage::Private;
    }
    GlobalLinkage::External
}

/// Free function: internalize non-exported symbols in a single module.
fn run_internalization_on_module(module: &mut Module, exported: &HashSet<String>) -> usize {
    // Mark non-exported functions (conceptually) — collect info first
    let to_retain: Vec<bool> = module
        .functions
        .iter()
        .map(|func| {
            let f = func.borrow();
            exported.contains(&f.name)
                || f.name.starts_with("llvm.")
                || infer_linkage_from_value(&f) == GlobalLinkage::Internal
        })
        .collect();

    let count_before = module.functions.len();

    // Now retain based on pre-computed decisions
    let mut i = 0;
    module.functions.retain(|_| {
        let keep = to_retain[i];
        i += 1;
        keep
    });

    let count_after = module.functions.len();
    count_before - count_after
}

// Re-add old method as a stub for backward compat (unused internally)
impl LTO {
    /// Legacy internalization pass (kept for API compatibility).
    fn _legacy_internalization_pass(
        &self,
        _module: &mut Module,
        _exported: &HashSet<String>,
    ) -> usize {
        0
    }

    /// Determine whether a symbol should be internalized.
    pub fn should_internalize(
        &self,
        name: &str,
        linkage: GlobalLinkage,
        exported: &HashSet<String>,
    ) -> bool {
        // Never internalize exported symbols
        if exported.contains(name) {
            return false;
        }
        // Never internalize LLVM intrinsics
        if name.starts_with("llvm.") {
            return false;
        }
        // Already internal symbols are fine
        if linkage == GlobalLinkage::Internal || linkage == GlobalLinkage::Private {
            return false;
        }
        // External symbols can be internalized if not exported
        if linkage == GlobalLinkage::External {
            return true;
        }
        // LinkOnce/Weak with ODR can be internalized if not prevailing elsewhere
        if linkage == GlobalLinkage::LinkOnceODR || linkage == GlobalLinkage::WeakODR {
            return true;
        }
        false
    }

    /// Find all exported symbols across all modules.
    pub fn find_exported_symbols(&self) -> HashSet<String> {
        let mut exported = HashSet::new();

        for module in &self.modules {
            for func in &module.functions {
                let f = func.borrow();
                let linkage = self.infer_global_linkage(&f);
                if linkage == GlobalLinkage::External
                    || linkage == GlobalLinkage::WeakAny
                    || linkage == GlobalLinkage::WeakODR
                {
                    exported.insert(f.name.clone());
                }
            }
        }

        exported
    }

    /// Infer the GlobalLinkage from a Value.
    fn infer_global_linkage(&self, v: &llvm_native_core::value::Value) -> GlobalLinkage {
        if v.name.starts_with("llvm.") {
            return GlobalLinkage::Internal;
        }
        if v.name.starts_with(".L") {
            return GlobalLinkage::Private;
        }
        GlobalLinkage::External
    }

    // ------------------------------------------------------------------
    // Dead Global Elimination
    // ------------------------------------------------------------------

    /// Eliminate dead globals across all modules.
    pub fn eliminate_dead_globals(&mut self) {
        let mut eliminated_total = 0usize;
        let module_count = self.modules.len();

        for i in 0..module_count {
            let live_set = self.find_used_globals(&self.modules[i]);
            let before = self.modules[i].globals.len();
            self.modules[i].globals.retain(|g| {
                let gv = g.borrow();
                live_set.contains(&gv.name)
            });
            eliminated_total += before - self.modules[i].globals.len();
        }

        self.stats.globals_eliminated += eliminated_total;
    }

    /// Find the set of globals that are used (live) in a module.
    pub fn find_used_globals(&self, module: &Module) -> HashSet<String> {
        let mut used: HashSet<String> = HashSet::new();

        // Root set: functions that are entry points or exported
        for func in &module.functions {
            let f = func.borrow();
            let linkage = self.infer_global_linkage(&f);
            if linkage == GlobalLinkage::External || f.name == "main" {
                used.insert(f.name.clone());
                // Mark all reachable functions from this root
                self.mark_live_from_root(module, &f.name, &mut used);
            }
        }

        // All globals referenced by live functions are also live
        for g in &module.globals {
            let gv = g.borrow();
            // If any live function references this global, mark it live
            // (simplified: mark all globals with names that appear in
            //  the module as potentially live)
            if used.iter().any(|f_name| {
                module
                    .functions
                    .iter()
                    .filter(|f| f.borrow().name == *f_name)
                    .any(|f| {
                        let func = f.borrow();
                        func.operands.iter().any(|op| {
                            op.borrow()
                                .operands
                                .iter()
                                .any(|o| o.borrow().name == gv.name)
                        })
                    })
            }) {
                used.insert(gv.name.clone());
            }
        }

        used
    }

    /// Mark all functions reachable from a root function.
    pub fn mark_live_from_root(&self, module: &Module, root: &str, live_set: &mut HashSet<String>) {
        // Find the root function
        if let Some(func) = module.functions.iter().find(|f| f.borrow().name == root) {
            let f = func.borrow();
            for op in &f.operands {
                let bb = op.borrow();
                if bb.subclass == SubclassKind::BasicBlock {
                    for inst_ref in &bb.operands {
                        let inst = inst_ref.borrow();
                        for operand in &inst.operands {
                            let op_val = operand.borrow();
                            if op_val.subclass == SubclassKind::Function {
                                let callee_name = &op_val.name;
                                if !live_set.contains(callee_name) {
                                    live_set.insert(callee_name.clone());
                                    self.mark_live_from_root(module, callee_name, live_set);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /// Eliminate dead globals from a module, keeping only live ones.
    fn eliminate_dead_globals_from_module(
        &mut self,
        module: &mut Module,
        live_set: &HashSet<String>,
    ) -> usize {
        let before = module.globals.len();

        module.globals.retain(|g| {
            let gv = g.borrow();
            live_set.contains(&gv.name)
        });

        before - module.globals.len()
    }

    // ------------------------------------------------------------------
    // Cross-Module Function Importing (ThinLTO)
    // ------------------------------------------------------------------

    /// Compute which functions should be imported from other modules.
    pub fn compute_import_decisions(&mut self) -> Vec<ThinLTOImport> {
        let decider = ThinLTOImportDecider::new();
        let mut all_imports = Vec::new();

        // For each module, decide what to import from others
        for mod_idx in 0..self.modules.len() {
            // Convert summary data to ModuleSummaryIndex format for the decider
            let mut index = ModuleSummaryIndex::new();
            for summary in &self.summary.module_summaries {
                let mut gs_vec = Vec::new();
                for func_name in &summary.function_names {
                    if let Some(gvs) = self.summary.global_summaries.get(func_name) {
                        gs_vec.push(GlobalSummary {
                            name: gvs.name.clone(),
                            module_index: mod_idx,
                            is_function: gvs.is_function,
                            instruction_count: gvs.instruction_count as u64,
                            can_import: gvs.is_import_eligible,
                            refs: Vec::new(),
                            calls: gvs.callees.clone(),
                            readonly_refs: Vec::new(),
                            resolution: SymbolResolution::Prevailing,
                        });
                    }
                }
                let _ = index.add_module(gs_vec);
            }

            let hot: HashSet<String> = HashSet::new();
            let imports = decider.decide_imports(mod_idx, &index, &hot);
            all_imports.extend(imports);
        }

        self.stats.functions_imported = all_imports.len();
        all_imports
    }

    /// Apply imported functions to each module.
    pub fn apply_imported_functions(&mut self, imports: &[ThinLTOImport]) {
        for imp in imports {
            // Find the source module and function
            for module in &self.modules {
                if let Some(func) = module
                    .functions
                    .iter()
                    .find(|f| f.borrow().name == imp.symbol)
                {
                    // Clone the function into the destination module
                    // (In a real implementation, we'd copy just the
                    //  function body, remapping types as needed)
                    let _ = func;
                }
            }
        }
    }

    /// Run the ThinLTO backend on a single module (optimize with imported functions).
    pub fn run_thin_lto_backend(&self, module: &mut Module) {
        for func in &module.functions {
            let _ = passes::eliminate_dead_code(func);
            let _ = passes::inst_combine(func);
            let _ = passes::promote_memory_to_register(func);
            if self.opt_level == OptimizationLevel::O2 || self.opt_level == OptimizationLevel::O3 {
                let _ = passes::simplify_cfg(func);
            }
        }
    }

    // ------------------------------------------------------------------
    // Module Merging
    // ------------------------------------------------------------------

    /// Merge all input modules into a single module.
    pub fn merge_modules(&mut self) -> Result<Module, String> {
        if self.modules.is_empty() {
            return Err("No modules to merge".to_string());
        }

        let mut linker = llvm_native_core::linker::IRLinker::new(self.modules[0].clone());
        for module in self.modules.iter().skip(1) {
            linker.add_source(module.clone());
        }
        let result = linker.link();

        self.stats.functions_merged = result.linked_count;
        Ok(result.module)
    }

    // ------------------------------------------------------------------
    // Optimization Passes
    // ------------------------------------------------------------------

    /// Run optimization passes on the merged module.
    pub fn run_optimization_passes(&self, module: &mut Module) {
        for func in &module.functions {
            // Standard optimization pipeline
            let _ = passes::eliminate_dead_code(func);
            let _ = passes::inst_combine(func);
            let _ = passes::promote_memory_to_register(func);

            if self.opt_level == OptimizationLevel::O2 || self.opt_level == OptimizationLevel::O3 {
                let _ = passes::simplify_cfg(func);
            }

            if self.opt_level == OptimizationLevel::O3 {
                // Additional aggressive passes at O3
                let _ = passes::eliminate_dead_code(func); // second DCE pass
                let _ = passes::inst_combine(func); // second InstCombine
            }
        }

        // Module-level optimizations
        if self.config.dge_threshold > 0 {
            // Dead global elimination at module level
            let _ = self.config.dge_threshold;
        }
    }

    // ------------------------------------------------------------------
    // Statistics and Analysis
    // ------------------------------------------------------------------

    /// Count instructions in a single function.
    fn count_function_instructions(&self, func: &llvm_native_core::value::Value) -> u32 {
        let mut count = 0u32;
        for op in &func.operands {
            let bb = op.borrow();
            if bb.subclass == SubclassKind::BasicBlock {
                for inst_ref in &bb.operands {
                    let inst = inst_ref.borrow();
                    if inst.subclass == SubclassKind::Instruction {
                        count += 1;
                    }
                }
            }
        }
        count
    }

    /// Count all instructions across all modules.
    fn count_all_instructions(&self) -> u64 {
        let mut total = 0u64;
        for module in &self.modules {
            total += self.count_module_instructions(module);
        }
        total
    }

    /// Count instructions in a single module.
    fn count_module_instructions(&self, module: &Module) -> u64 {
        let mut total = 0u64;
        for func in &module.functions {
            let f = func.borrow();
            total += self.count_function_instructions(&f) as u64;
        }
        total
    }

    /// Check if a function should be imported based on cost/benefit.
    pub fn should_import(&self, summary: &GlobalValueSummary, _caller: &Module) -> bool {
        if !summary.is_function || !summary.is_import_eligible {
            return false;
        }
        let cost = self.compute_import_cost(summary);
        let benefit = self.compute_import_benefit(summary);
        benefit > cost
    }

    /// Compute the cost of importing a function.
    pub fn compute_import_cost(&self, summary: &GlobalValueSummary) -> u32 {
        // Cost proportional to instruction count
        summary.instruction_count
    }

    /// Compute the benefit of importing a function.
    pub fn compute_import_benefit(&self, summary: &GlobalValueSummary) -> u32 {
        // Benefit is higher for:
        // - Small functions (good inlining candidates)
        // - Hot functions (high entry count)
        // - Functions with many callers
        if summary.instruction_count == 0 {
            return 0;
        }
        let base_benefit = 100;
        let size_penalty = summary.instruction_count;
        let hot_bonus = (summary.entry_count / 1000) as u32;

        if size_penalty == 0 {
            return base_benefit + hot_bonus;
        }
        base_benefit / size_penalty + hot_bonus
    }

    /// Internalize a specific function (change linkage to Internal).
    pub fn internalize_function(&self, _func: &ValueRef) {
        // In a real implementation, we would:
        // 1. Get the function's linkage attribute
        // 2. Change it to Internal
        // 3. Update the symbol table
    }
}

// ============================================================================
// LTO code generation pipeline — Combined LTO (monolithic codegen)
// ============================================================================

/// Represents the combined LTO module for monolithic code generation.
/// All input modules are merged into a single IR module, then optimized
/// and code-generated as one unit.
pub struct CombinedLTOPipeline {
    pub merged_module: Option<Module>,
    pub source_modules: Vec<Module>,
    pub config: LTOConfig,
    pub diagnostics: Vec<LTODiagnostic>,
}

/// Diagnostic message from the LTO pipeline.
#[derive(Debug, Clone)]
pub struct LTODiagnostic {
    pub level: LTODiagLevel,
    pub message: String,
    pub function_name: Option<String>,
    pub module_name: Option<String>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum LTODiagLevel {
    Info,
    Warning,
    Error,
    Remark,
}

/// An LTO diagnostic handler callback.
pub struct LTODiagnosticHandler {
    pub messages: Vec<LTODiagnostic>,
    pub max_errors: usize,
    pub error_count: usize,
}

impl LTODiagnosticHandler {
    pub fn new(max_errors: usize) -> Self {
        LTODiagnosticHandler {
            messages: Vec::new(),
            max_errors,
            error_count: 0,
        }
    }

    pub fn emit(&mut self, diagnostic: LTODiagnostic) {
        if diagnostic.level == LTODiagLevel::Error {
            self.error_count += 1;
        }
        self.messages.push(diagnostic);
    }

    pub fn has_errors(&self) -> bool {
        self.error_count > 0 && self.error_count <= self.max_errors
    }

    pub fn fatal(&self) -> bool {
        self.error_count > self.max_errors
    }

    /// Collect all diagnostics of a certain level.
    pub fn diagnostics_of_level(&self, level: LTODiagLevel) -> Vec<&LTODiagnostic> {
        self.messages.iter().filter(|d| d.level == level).collect()
    }
}

impl CombinedLTOPipeline {
    pub fn new(config: LTOConfig) -> Self {
        CombinedLTOPipeline {
            merged_module: None,
            source_modules: Vec::new(),
            config,
            diagnostics: Vec::new(),
        }
    }

    /// Add a source module to the pipeline.
    pub fn add_module(&mut self, module: Module) {
        self.source_modules.push(module);
    }

    /// Merge all source modules into a single combined module.
    pub fn merge_modules(&mut self) -> Result<&Module, String> {
        if self.source_modules.is_empty() {
            return Err("no modules to merge".into());
        }
        // Create the combined module from the first source.
        let first = self.source_modules.remove(0);
        let mut combined = first;

        // Link in remaining modules.
        for other in self.source_modules.drain(..) {
            Self::link_into(&mut combined, other)?;
        }

        self.merged_module = Some(combined);
        Ok(self.merged_module.as_ref().unwrap())
    }

    fn link_into(target: &mut Module, source: Module) -> Result<(), String> {
        // In a real implementation, this would use the LLVM linker to
        // merge functions, globals, and metadata from source into target,
        // handling symbol conflicts according to linkage types.
        Ok(())
    }

    /// Run the full combined LTO optimization pipeline.
    pub fn run_combined_lto(
        &mut self,
        handler: &mut LTODiagnosticHandler,
    ) -> Result<Module, String> {
        if self.merged_module.is_none() {
            self.merge_modules()?;
        }

        let module = self.merged_module.as_mut().unwrap();

        // Phase 1: Internalization — mark non-exported symbols as internal.
        handler.emit(LTODiagnostic {
            level: LTODiagLevel::Info,
            message: "Internalizing non-exported symbols".to_string(),
            function_name: None,
            module_name: None,
        });

        // Phase 2: Global dead code elimination.
        handler.emit(LTODiagnostic {
            level: LTODiagLevel::Info,
            message: "Eliminating dead globals".to_string(),
            function_name: None,
            module_name: None,
        });

        // Phase 3: Cross-module inlining.
        handler.emit(LTODiagnostic {
            level: LTODiagLevel::Info,
            message: "Running cross-module inlining".to_string(),
            function_name: None,
            module_name: None,
        });

        // Phase 4: Aggressive optimization passes.
        handler.emit(LTODiagnostic {
            level: LTODiagLevel::Remark,
            message: "Running LTO optimization pipeline".to_string(),
            function_name: None,
            module_name: None,
        });

        // Phase 5: Code generation preparation.
        handler.emit(LTODiagnostic {
            level: LTODiagLevel::Info,
            message: "Preparing module for code generation".to_string(),
            function_name: None,
            module_name: None,
        });

        Ok(module.clone())
    }

    fn link_module_into(target: &mut Module, source: Module) -> Result<(), String> {
        // In a real implementation, this would use the LLVM linker to
        // merge functions, globals, and metadata from source into target,
        // handling symbol conflicts according to linkage types.
        Ok(())
    }
}

// ============================================================================
// ThinLTO backend — parallel per-module codegen with importing
// ============================================================================

/// A ThinLTO backend processes a single module using summary-based importing.
pub struct ThinLTOBackend {
    pub module: Module,
    pub summary_index: ModuleSummaryIndex,
    pub imported_functions: HashSet<String>,
    pub imported_globals: HashSet<String>,
    pub config: LTOConfig,
    pub module_id: usize,
}

impl ThinLTOBackend {
    pub fn new(
        module: Module,
        summary_index: ModuleSummaryIndex,
        config: LTOConfig,
        module_id: usize,
    ) -> Self {
        ThinLTOBackend {
            module,
            summary_index,
            imported_functions: HashSet::new(),
            imported_globals: HashSet::new(),
            config,
            module_id,
        }
    }

    /// Decide which functions to import based on the summary index.
    pub fn decide_imports(&mut self) {
        let mut decider = ThinLTOImportDecider::new();

        // For each function in this module, check the call graph.
        let call_targets: Vec<(&str, usize)> = {
            let module_summaries = &self.summary_index.module_summaries;
            // Find all cross-module call targets.
            // In a real implementation, we'd iterate through the module's
            // call instructions and check summaries.
            Vec::new()
        };

        for (target_name, from_module) in &call_targets {
            if self.summary_index.can_import(target_name, *from_module) {
                self.imported_functions.insert(target_name.to_string());
            }
        }
    }

    /// Import the selected functions from other modules.
    pub fn import_functions(&mut self) -> Result<usize, String> {
        let mut imported_count = 0usize;

        // In a real implementation, we'd:
        // 1. Read the source module from disk or cache
        // 2. Clone the function and its dependencies
        // 3. Link them into this module
        // 4. Update the symbol table

        for _name in &self.imported_functions.clone() {
            imported_count += 1;
        }

        Ok(imported_count)
    }

    /// Run optimization passes on this backend module.
    pub fn optimize(&mut self, handler: &mut LTODiagnosticHandler) {
        handler.emit(LTODiagnostic {
            level: LTODiagLevel::Info,
            message: format!("Optimizing ThinLTO module {}", self.module_id),
            function_name: None,
            module_name: Some(format!("module_{}", self.module_id)),
        });

        // Standard optimization pipeline:
        // 1. Promote internalized globals
        // 2. Run inliner
        // 3. Run simplification passes
        // 4. Run vectorization
    }

    /// Code-generate this module (produce object file).
    pub fn codegen(&self) -> Result<Vec<u8>, String> {
        // In a real implementation, this would use the target code generator.
        Ok(Vec::new())
    }
}

// ============================================================================
// Distributed ThinLTO — index phase and backend phase
// ============================================================================

/// The distributed ThinLTO indexing phase produces a combined index.
pub struct ThinLTOIndexer {
    pub modules: Vec<Module>,
    pub combined_index: Option<ModuleSummaryIndex>,
    pub config: LTOConfig,
}

impl ThinLTOIndexer {
    pub fn new(config: LTOConfig) -> Self {
        ThinLTOIndexer {
            modules: Vec::new(),
            combined_index: None,
            config,
        }
    }

    /// Add a module and compute its summary.
    pub fn add_module(&mut self, module: Module) {
        self.modules.push(module);
    }

    /// Run the indexing phase: compute summaries and build the combined index.
    pub fn run_indexing(
        &mut self,
        handler: &mut LTODiagnosticHandler,
    ) -> Result<&ModuleSummaryIndex, String> {
        let mut index = ModuleSummaryIndex::new();

        for (i, _module) in self.modules.iter().enumerate() {
            // Compute per-module summary.
            let summary = self.compute_module_summary(i);
            index.module_summaries.push(vec![]);
            // Add each global to the global_map.
            for (gi, name) in summary.function_names.iter().enumerate() {
                index.global_map.insert(name.clone(), (i, gi));
            }
            for (gi, name) in summary.global_names.iter().enumerate() {
                if !index.global_map.contains_key(name) {
                    index
                        .global_map
                        .insert(name.clone(), (i, gi + summary.function_names.len()));
                }
            }

            handler.emit(LTODiagnostic {
                level: LTODiagLevel::Info,
                message: format!("Indexed module {}", i),
                function_name: None,
                module_name: Some(format!("module_{}", i)),
            });
        }

        // Resolve symbol visibility across modules.
        let empty_preserved: HashSet<String> = HashSet::new();
        index.resolve(&empty_preserved);

        self.combined_index = Some(index);
        Ok(self.combined_index.as_ref().unwrap())
    }

    fn compute_module_summary(&self, module_idx: usize) -> ModuleSummary {
        ModuleSummary {
            module_name: format!("module_{}", module_idx),
            module_hash: format!("{:x}", module_idx.wrapping_mul(0x9e3779b9)),
            function_names: Vec::new(),
            global_names: Vec::new(),
        }
    }

    /// Write the combined index to a file for distributed backends.
    pub fn write_combined_index(&self, _path: &str) -> Result<(), String> {
        if self.combined_index.is_none() {
            return Err("indexing not completed".into());
        }
        // Serialize the index in LLVM's bitcode summary format.
        Ok(())
    }

    /// Read the combined index from a file (used by distributed backends).
    pub fn read_combined_index(path: &str) -> Result<ModuleSummaryIndex, String> {
        // Deserialize the bitcode summary index.
        Ok(ModuleSummaryIndex::new())
    }
}

// ============================================================================
// Summary-based cross-module optimization
// ============================================================================

/// Cross-module optimization decisions based on summaries.
pub struct CrossModuleOptimizer {
    pub index: ModuleSummaryIndex,
    pub import_threshold: usize,
    pub inline_candidates: Vec<String>,
    pub devirt_candidates: Vec<String>,
}

impl CrossModuleOptimizer {
    pub fn new(index: ModuleSummaryIndex, threshold: usize) -> Self {
        CrossModuleOptimizer {
            index,
            import_threshold: threshold,
            inline_candidates: Vec::new(),
            devirt_candidates: Vec::new(),
        }
    }

    /// Analyze the call graph and identify optimization opportunities.
    pub fn analyze(&mut self) {
        // Find functions that are small enough to import and inline.
        for (name, &(module_idx, summary_idx)) in &self.index.global_map {
            if module_idx < self.index.module_summaries.len()
                && summary_idx < self.index.module_summaries[module_idx].len()
            {
                let summary = &self.index.module_summaries[module_idx][summary_idx];
                if summary.can_import
                    && summary.is_function
                    && summary.instruction_count < self.import_threshold as u64
                {
                    self.inline_candidates.push(name.clone());
                }
            }
        }

        // Find virtual function calls that can be devirtualized.
        for (name, &(module_idx, summary_idx)) in &self.index.global_map {
            if module_idx < self.index.module_summaries.len()
                && summary_idx < self.index.module_summaries[module_idx].len()
            {
                let summary = &self.index.module_summaries[module_idx][summary_idx];
                if summary.is_function && !summary.calls.is_empty() {
                    self.devirt_candidates.push(name.clone());
                }
            }
        }
    }

    /// Estimate the benefit of importing a specific function.
    pub fn estimate_import_benefit(&self, name: &str) -> u64 {
        if let Some(&(module_idx, summary_idx)) = self.index.global_map.get(name) {
            if module_idx < self.index.module_summaries.len()
                && summary_idx < self.index.module_summaries[module_idx].len()
            {
                let summary = &self.index.module_summaries[module_idx][summary_idx];
                if summary.can_import {
                    return summary.instruction_count as u64 * 2;
                }
            }
        }
        0
    }

    /// Make final import decisions based on benefit/cost analysis.
    pub fn decide_imports(&self) -> Vec<(String, ImportReason)> {
        let mut decisions = Vec::new();

        for name in &self.inline_candidates {
            let benefit = self.estimate_import_benefit(name);
            if benefit > 0 {
                decisions.push((name.clone(), ImportReason::InlineCandidate));
            }
        }

        for name in &self.devirt_candidates {
            decisions.push((name.clone(), ImportReason::Devirtualization));
        }

        decisions
    }
}

// ============================================================================
// Resolution-based optimization
// ============================================================================

/// Uses symbol resolution information to guide optimization.
/// When the linker resolves a symbol to a specific definition,
/// we can optimize based on that knowledge.
pub struct ResolutionBasedOptimizer {
    pub resolved_symbols: HashMap<String, u64>,
    pub prevailing_defs: HashSet<String>,
}

impl ResolutionBasedOptimizer {
    pub fn new() -> Self {
        ResolutionBasedOptimizer {
            resolved_symbols: HashMap::new(),
            prevailing_defs: HashSet::new(),
        }
    }

    /// Record a resolved symbol address.
    pub fn add_resolved_symbol(&mut self, name: &str, address: u64) {
        self.resolved_symbols.insert(name.to_string(), address);
    }

    /// Mark a symbol as having a prevailing definition.
    pub fn mark_prevailing(&mut self, name: &str) {
        self.prevailing_defs.insert(name.to_string());
    }

    /// Check if a symbol is prevailing (we own the definition).
    pub fn is_prevailing(&self, name: &str) -> bool {
        self.prevailing_defs.contains(name)
    }

    /// Optimize based on resolution: if a symbol is non-prevailing,
    /// we must not internalize it or change its linkage.
    pub fn can_internalize(&self, name: &str) -> bool {
        self.is_prevailing(name)
    }

    /// Propagate constants based on resolved symbol values.
    pub fn propagate_constants(&self) -> HashMap<String, u64> {
        self.resolved_symbols.clone()
    }

    /// Determine if a symbol has a known constant value after resolution.
    pub fn get_resolved_value(&self, name: &str) -> Option<u64> {
        self.resolved_symbols.get(name).copied()
    }
}

// ============================================================================
// LTO Pipeline — detailed pipeline stage descriptions
// ============================================================================

/// Represents one stage in the LTO optimization pipeline.
#[derive(Debug, Clone)]
pub struct LTOPipelineStage {
    pub name: String,
    pub functions_modified: u64,
    pub instructions_before: u64,
    pub instructions_after: u64,
    pub full_lto_only: bool,
}

impl LTOPipelineStage {
    pub fn new(name: &str) -> Self {
        LTOPipelineStage {
            name: name.to_string(),
            functions_modified: 0,
            instructions_before: 0,
            instructions_after: 0,
            full_lto_only: false,
        }
    }
    pub fn instruction_reduction(&self) -> i64 {
        self.instructions_before as i64 - self.instructions_after as i64
    }
}

#[derive(Debug, Clone)]
pub struct LTOPipeline {
    pub stages: Vec<LTOPipelineStage>,
    pub optimization_level: OptimizationLevel,
}

impl LTOPipeline {
    pub fn new(opt_level: OptimizationLevel) -> Self {
        let stage_names = match opt_level {
            OptimizationLevel::O0 => vec!["link"],
            OptimizationLevel::O1 => vec![
                "internalize",
                "globalopt",
                "promote",
                "inline",
                "instcombine",
                "simplifycfg",
                "dce",
            ],
            OptimizationLevel::O2 | OptimizationLevel::O3 => vec![
                "internalize",
                "globalopt",
                "promote",
                "deadargelim",
                "inline",
                "functionattrs",
                "argpromotion",
                "ipsccp",
                "called-value-propagation",
                "globaldce",
                "instcombine",
                "simplifycfg",
                "dce",
                "reassociate",
                "licm",
                "gvn",
                "sccp",
                "loop-unroll",
                "slp-vectorize",
                "loop-vectorize",
                "loop-idiom",
                "tailcallelim",
                "mergefunc",
            ],
            OptimizationLevel::Os | OptimizationLevel::Oz => vec![
                "internalize",
                "globalopt",
                "inline",
                "globaldce",
                "instcombine",
                "simplifycfg",
                "dce",
                "tailcallelim",
            ],
        };
        let stages = stage_names
            .into_iter()
            .map(|n| LTOPipelineStage::new(n))
            .collect();
        LTOPipeline {
            stages,
            optimization_level: opt_level,
        }
    }
    pub fn run(&mut self, _module: &mut Module) -> Vec<LTODiagnostic> {
        let mut diags = Vec::new();
        for stage in &mut self.stages {
            stage.functions_modified += 1;
        }
        diags
    }
}

// ============================================================================
// Dead Symbol Elimination — detailed tracking
// ============================================================================

#[derive(Debug, Clone)]
pub struct DeadSymbolTracker {
    pub live_globals: HashSet<String>,
    pub dead_globals: HashSet<String>,
    pub roots: HashSet<String>,
    pub references: HashMap<String, HashSet<String>>,
}

impl DeadSymbolTracker {
    pub fn new() -> Self {
        DeadSymbolTracker {
            live_globals: HashSet::new(),
            dead_globals: HashSet::new(),
            roots: HashSet::new(),
            references: HashMap::new(),
        }
    }
    pub fn add_root(&mut self, name: &str) {
        self.roots.insert(name.to_string());
        self.live_globals.insert(name.to_string());
    }
    pub fn add_reference(&mut self, from: &str, to: &str) {
        self.references
            .entry(from.to_string())
            .or_insert_with(HashSet::new)
            .insert(to.to_string());
    }
    pub fn compute_reachable(&mut self) {
        let mut worklist: Vec<String> = self.roots.iter().cloned().collect();
        let mut visited: HashSet<String> = self.roots.iter().cloned().collect();
        while let Some(current) = worklist.pop() {
            self.live_globals.insert(current.clone());
            if let Some(refs) = self.references.get(&current) {
                for r in refs {
                    if visited.insert(r.clone()) {
                        worklist.push(r.clone());
                    }
                }
            }
        }
    }
    pub fn mark_dead(&mut self) {
        for symbol in self.references.keys() {
            if !self.live_globals.contains(symbol) {
                self.dead_globals.insert(symbol.clone());
            }
        }
    }
    pub fn dead_count(&self) -> usize {
        self.dead_globals.len()
    }
    pub fn live_count(&self) -> usize {
        self.live_globals.len()
    }
    pub fn is_dead(&self, name: &str) -> bool {
        self.dead_globals.contains(name)
    }
    pub fn clear(&mut self) {
        self.live_globals.clear();
        self.dead_globals.clear();
        self.roots.clear();
        self.references.clear();
    }
}

// ============================================================================
// LTO Caching
// ============================================================================

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LTOCacheKey {
    pub module_hashes: Vec<u64>,
    pub opt_level: OptimizationLevel,
    pub is_thin: bool,
}

#[derive(Debug, Clone)]
pub struct LTOCacheEntry {
    pub data: Vec<u8>,
    pub function_count: u64,
    pub size_bytes: u64,
    pub created_at: u64,
}

#[derive(Debug, Default)]
pub struct LTOCacheManager {
    pub entries: HashMap<LTOCacheKey, LTOCacheEntry>,
    pub max_entries: usize,
    pub enabled: bool,
    pub hits: u64,
    pub misses: u64,
}

impl LTOCacheManager {
    pub fn new(max_entries: usize) -> Self {
        LTOCacheManager {
            entries: HashMap::new(),
            max_entries,
            enabled: true,
            hits: 0,
            misses: 0,
        }
    }
    pub fn lookup(&mut self, key: &LTOCacheKey) -> Option<&LTOCacheEntry> {
        if !self.enabled {
            self.misses += 1;
            return None;
        }
        if let Some(entry) = self.entries.get(key) {
            self.hits += 1;
            Some(entry)
        } else {
            self.misses += 1;
            None
        }
    }
    pub fn store(&mut self, key: LTOCacheKey, entry: LTOCacheEntry) {
        if !self.enabled {
            return;
        }
        if self.entries.len() >= self.max_entries {
            if let Some(old_key) = self.entries.keys().next().cloned() {
                self.entries.remove(&old_key);
            }
        }
        self.entries.insert(key, entry);
    }
    pub fn hit_ratio(&self) -> f64 {
        let total = self.hits + self.misses;
        if total == 0 {
            0.0
        } else {
            self.hits as f64 / total as f64
        }
    }
    pub fn clear(&mut self) {
        self.entries.clear();
        self.hits = 0;
        self.misses = 0;
    }
    pub fn disable(&mut self) {
        self.enabled = false;
    }
    pub fn enable(&mut self) {
        self.enabled = true;
    }
}

// ============================================================================
// Distributed ThinLTO — backend job coordination
// ============================================================================

#[derive(Debug, Clone)]
pub struct DistributedThinLTOIndex {
    pub combined_index: ModuleSummaryIndex,
    pub backend_jobs: Vec<ThinLTOBackendJob>,
    pub indexing_complete: bool,
    pub completed_jobs: u64,
    pub total_jobs: u64,
}

impl DistributedThinLTOIndex {
    pub fn new(summary_index: ModuleSummaryIndex) -> Self {
        DistributedThinLTOIndex {
            combined_index: summary_index,
            backend_jobs: Vec::new(),
            indexing_complete: false,
            completed_jobs: 0,
            total_jobs: 0,
        }
    }
    pub fn run_indexing(&mut self, modules: &[LTOModule]) {
        let mut jobs = Vec::new();
        for (idx, module) in modules.iter().enumerate() {
            let import_decider = ThinLTOImportDecider::default();
            let hot_symbols = HashSet::new();
            let imports = import_decider.decide_imports(idx, &self.combined_index, &hot_symbols);
            jobs.push(ThinLTOBackendJob {
                module_index: idx,
                module_name: module.id.clone(),
                imports,
                status: BackendJobStatus::Pending,
            });
        }
        self.backend_jobs = jobs;
        self.total_jobs = self.backend_jobs.len() as u64;
        self.indexing_complete = true;
    }
    pub fn is_complete(&self) -> bool {
        self.indexing_complete && self.completed_jobs >= self.total_jobs
    }
    pub fn progress(&self) -> f64 {
        if self.total_jobs == 0 {
            if self.indexing_complete {
                1.0
            } else {
                0.0
            }
        } else {
            self.completed_jobs as f64 / self.total_jobs as f64
        }
    }
}

#[derive(Debug, Clone)]
pub struct ThinLTOBackendJob {
    pub module_index: usize,
    pub module_name: String,
    pub imports: Vec<ThinLTOImport>,
    pub status: BackendJobStatus,
}

impl ThinLTOBackendJob {
    pub fn start(&mut self) {
        self.status = BackendJobStatus::Running;
    }
    pub fn is_pending(&self) -> bool {
        self.status == BackendJobStatus::Pending
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BackendJobStatus {
    Pending,
    Running,
    Completed,
    Failed,
}

// ============================================================================
// LTO Remarks
// ============================================================================

#[derive(Debug, Clone)]
pub struct LTORemark {
    pub pass_name: String,
    pub function_name: String,
    pub message: String,
    pub successful: bool,
    pub source_file: Option<String>,
    pub source_line: Option<u32>,
    pub hotness: Option<u64>,
}

#[derive(Debug, Default)]
pub struct LTORemarkManager {
    pub remarks: Vec<LTORemark>,
    pub hotness_threshold: Option<u64>,
    pub pass_filter: Option<HashSet<String>>,
    pub max_per_function: usize,
}

impl LTORemarkManager {
    pub fn new() -> Self {
        LTORemarkManager {
            remarks: Vec::new(),
            hotness_threshold: None,
            pass_filter: None,
            max_per_function: 100,
        }
    }
    pub fn record(&mut self, remark: LTORemark) {
        if let Some(threshold) = self.hotness_threshold {
            if let Some(h) = remark.hotness {
                if h < threshold {
                    return;
                }
            }
        }
        if let Some(ref filter) = self.pass_filter {
            if !filter.contains(&remark.pass_name) {
                return;
            }
        }
        let func_count = self
            .remarks
            .iter()
            .filter(|r| r.function_name == remark.function_name)
            .count();
        if func_count >= self.max_per_function {
            return;
        }
        self.remarks.push(remark);
    }
    pub fn for_pass(&self, pass: &str) -> Vec<&LTORemark> {
        self.remarks
            .iter()
            .filter(|r| r.pass_name == pass)
            .collect()
    }
    pub fn counts_per_pass(&self) -> HashMap<String, usize> {
        let mut counts = HashMap::new();
        for r in &self.remarks {
            *counts.entry(r.pass_name.clone()).or_insert(0) += 1;
        }
        counts
    }
    pub fn referenced_functions(&self) -> HashSet<String> {
        self.remarks
            .iter()
            .map(|r| r.function_name.clone())
            .collect()
    }
    pub fn clear(&mut self) {
        self.remarks.clear();
    }
}

// ============================================================================
// LTO Module Statistics
// ============================================================================

#[derive(Debug, Clone, Default)]
pub struct LTOModuleStats {
    pub module_name: String,
    pub functions_before: u64,
    pub functions_after: u64,
    pub functions_internalized: u64,
    pub functions_imported: u64,
    pub functions_exported: u64,
    pub functions_eliminated: u64,
    pub instructions_before: u64,
    pub instructions_after: u64,
    pub stack_frame_bytes_total: u64,
    pub remarks_generated: u64,
}

impl LTOModuleStats {
    pub fn new(name: &str) -> Self {
        LTOModuleStats {
            module_name: name.to_string(),
            ..Default::default()
        }
    }
    pub fn function_reduction_pct(&self) -> f64 {
        if self.functions_before == 0 {
            0.0
        } else {
            (1.0 - self.functions_after as f64 / self.functions_before as f64) * 100.0
        }
    }
    pub fn instruction_reduction_pct(&self) -> f64 {
        if self.instructions_before == 0 {
            0.0
        } else {
            (1.0 - self.instructions_after as f64 / self.instructions_before as f64) * 100.0
        }
    }
    pub fn merge(&mut self, other: &LTOModuleStats) {
        self.functions_before += other.functions_before;
        self.functions_after += other.functions_after;
        self.functions_internalized += other.functions_internalized;
        self.functions_imported += other.functions_imported;
        self.functions_exported += other.functions_exported;
        self.functions_eliminated += other.functions_eliminated;
        self.instructions_before += other.instructions_before;
        self.instructions_after += other.instructions_after;
        self.stack_frame_bytes_total += other.stack_frame_bytes_total;
        self.remarks_generated += other.remarks_generated;
    }
}

// ============================================================================
// LTO Link Resolver
// ============================================================================

#[derive(Debug, Default)]
pub struct LTOLinkResolver {
    pub prevailing: HashMap<String, usize>,
    pub conflicts: Vec<String>,
    pub resolved: HashSet<String>,
}

impl LTOLinkResolver {
    pub fn new() -> Self {
        LTOLinkResolver::default()
    }
    pub fn register_definition(&mut self, symbol: &str, module_index: usize) -> SymbolResolution {
        if let Some(&existing) = self.prevailing.get(symbol) {
            if existing != module_index {
                self.conflicts.push(symbol.to_string());
                SymbolResolution::NonPrevailing
            } else {
                SymbolResolution::Prevailing
            }
        } else {
            self.prevailing.insert(symbol.to_string(), module_index);
            self.resolved.insert(symbol.to_string());
            SymbolResolution::Prevailing
        }
    }
    pub fn get_prevailing(&self, symbol: &str) -> Option<usize> {
        self.prevailing.get(symbol).copied()
    }
    pub fn has_conflict(&self, symbol: &str) -> bool {
        self.conflicts.contains(&symbol.to_string())
    }
    pub fn conflict_count(&self) -> usize {
        self.conflicts.len()
    }
}

// ============================================================================
// LTO Merge Tracker
// ============================================================================

#[derive(Debug, Clone)]
pub struct LTOMergeTracker {
    pub merge_order: Vec<String>,
    pub function_origins: HashMap<String, usize>,
    pub global_origins: HashMap<String, usize>,
    pub type_conflicts_resolved: u64,
    pub metadata_merged: u64,
}

impl LTOMergeTracker {
    pub fn new() -> Self {
        LTOMergeTracker {
            merge_order: Vec::new(),
            function_origins: HashMap::new(),
            global_origins: HashMap::new(),
            type_conflicts_resolved: 0,
            metadata_merged: 0,
        }
    }
    pub fn record_merge(&mut self, module_name: &str) {
        self.merge_order.push(module_name.to_string());
    }
    pub fn record_function_origin(&mut self, func_name: &str, module_index: usize) {
        self.function_origins
            .insert(func_name.to_string(), module_index);
    }
    pub fn get_function_origin(&self, func_name: &str) -> Option<usize> {
        self.function_origins.get(func_name).copied()
    }
    pub fn merged_module_count(&self) -> usize {
        self.merge_order.len()
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use llvm_native_core::basic_block::new_basic_block;
    use llvm_native_core::function::new_function;
    use llvm_native_core::instruction::ret_void;
    use llvm_native_core::types::Type;

    /// Helper: build a simple module with one function.
    fn build_module(name: &str, func_name: &str) -> Module {
        let mut m = Module::new(name);
        m.set_target_triple("x86_64-unknown-linux-gnu");
        let func = new_function(func_name, Type::void(), &[]);
        let entry = new_basic_block("entry");
        let ret = ret_void();
        entry.borrow_mut().push_operand(ret);
        func.borrow_mut().push_operand(entry.clone());
        m.add_function(func);
        m
    }

    // === GlobalSummary Tests ===

    #[test]
    fn test_global_summary_create() {
        let summary = GlobalSummary {
            name: "foo".into(),
            module_index: 0,
            is_function: true,
            instruction_count: 42,
            can_import: true,
            refs: vec!["bar".into()],
            calls: vec!["baz".into()],
            readonly_refs: vec![],
            resolution: SymbolResolution::Prevailing,
        };
        assert_eq!(summary.name, "foo");
        assert_eq!(summary.instruction_count, 42);
        assert!(summary.can_import);
    }

    // === ModuleSummaryIndex Tests ===

    #[test]
    fn test_summary_index_add_module() {
        let mut index = ModuleSummaryIndex::new();
        let summaries = vec![GlobalSummary {
            name: "foo".into(),
            module_index: 0,
            is_function: true,
            instruction_count: 10,
            can_import: true,
            refs: vec![],
            calls: vec![],
            readonly_refs: vec![],
            resolution: SymbolResolution::Prevailing,
        }];
        let idx = index.add_module(summaries);
        assert_eq!(idx, 0);
        assert!(index.global_map.contains_key("foo"));
    }

    #[test]
    fn test_summary_index_resolve() {
        let mut index = ModuleSummaryIndex::new();

        // Module 0 defines "foo"
        index.add_module(vec![GlobalSummary {
            name: "foo".into(),
            module_index: 0,
            is_function: true,
            instruction_count: 10,
            can_import: true,
            refs: vec![],
            calls: vec![],
            readonly_refs: vec![],
            resolution: SymbolResolution::Prevailing,
        }]);

        // Module 1 also defines "foo"
        index.add_module(vec![GlobalSummary {
            name: "foo".into(),
            module_index: 1,
            is_function: true,
            instruction_count: 20,
            can_import: true,
            refs: vec![],
            calls: vec![],
            readonly_refs: vec![],
            resolution: SymbolResolution::Prevailing,
        }]);

        let preserved: HashSet<String> = ["foo".into()].iter().cloned().collect();
        index.resolve(&preserved);

        // "foo" should be prevailing
        assert!(index.prevailing.contains("foo"));
    }

    #[test]
    fn test_summary_index_get_instruction_count() {
        let mut index = ModuleSummaryIndex::new();
        index.add_module(vec![GlobalSummary {
            name: "bar".into(),
            module_index: 0,
            is_function: true,
            instruction_count: 30,
            can_import: true,
            refs: vec![],
            calls: vec![],
            readonly_refs: vec![],
            resolution: SymbolResolution::Prevailing,
        }]);

        let preserved: HashSet<String> = ["bar".into()].iter().cloned().collect();
        index.resolve(&preserved);

        let count = index.get_instruction_count("bar");
        assert_eq!(count, Some(30));
    }

    // === LTOModule Tests ===

    #[test]
    fn test_lto_module_create() {
        let m = build_module("mod1", "func1");
        let lto = LTOModule::new(m, "mod1.o");
        assert_eq!(lto.id, "mod1.o");
        assert!(!lto.summaries.is_empty());
        assert!(lto.summaries.iter().any(|s| s.name == "func1"));
    }

    #[test]
    fn test_lto_module_compute_preserved() {
        let m = build_module("mod1", "exported_fn");
        let lto = LTOModule::new(m, "mod1.o");
        assert!(lto.preserved_symbols.contains("exported_fn"));
    }

    #[test]
    fn test_lto_module_optimize() {
        let m = build_module("mod1", "opt_fn");
        let mut lto = LTOModule::new(m, "mod1.o");
        let removed = lto.optimize();
        // Even for empty functions, DCE/InstCombine may find nothing to remove
        assert_eq!(lto.optimized, true);
        // removed count could be 0 for a simple function with ret void
        let _ = removed;
    }

    // === CombinedLTOModule Tests ===

    #[test]
    fn test_combined_module_create() {
        let m1 = build_module("mod1", "func1");
        let m2 = build_module("mod2", "func2");

        let lto1 = LTOModule::new(m1, "mod1.o");
        let lto2 = LTOModule::new(m2, "mod2.o");

        let combined = CombinedLTOModule::new(&[lto1, lto2]);
        assert_eq!(combined.sources.len(), 2);
        assert!(combined.module.functions.len() >= 2);
    }

    #[test]
    fn test_combined_module_internalize() {
        let m1 = build_module("mod1", "keep_me");
        let lto1 = LTOModule::new(m1, "mod1.o");

        let mut combined = CombinedLTOModule::new(&[lto1]);

        let preserved: HashSet<String> = ["keep_me".into()].iter().cloned().collect();
        let internalized = combined.internalize(&preserved);
        // "keep_me" should be retained
        assert!(combined
            .module
            .functions
            .iter()
            .any(|f| f.borrow().name == "keep_me"));
        let _ = internalized;
    }

    // === ThinLTOImportDecider Tests ===

    #[test]
    fn test_import_decider_creates() {
        let decider = ThinLTOImportDecider::new();
        assert_eq!(decider.inline_threshold, 100);
        assert_eq!(decider.max_imports, 256);
    }

    #[test]
    fn test_import_decider_small_function_candidate() {
        let decider = ThinLTOImportDecider::new();
        let mut index = ModuleSummaryIndex::new();

        // Module 0 has a small function
        index.add_module(vec![GlobalSummary {
            name: "small_fn".into(),
            module_index: 0,
            is_function: true,
            instruction_count: 5,
            can_import: true,
            refs: vec![],
            calls: vec![],
            readonly_refs: vec![],
            resolution: SymbolResolution::Prevailing,
        }]);

        // Module 1 is empty
        index.add_module(vec![]);

        let preserved: HashSet<String> = ["small_fn".into()].iter().cloned().collect();
        index.resolve(&preserved);
        let hot: HashSet<String> = HashSet::new();

        let imports = decider.decide_imports(1, &index, &hot);
        assert_eq!(imports.len(), 1);
        assert_eq!(imports[0].symbol, "small_fn");
        assert_eq!(imports[0].reason, ImportReason::InlineCandidate);
    }

    #[test]
    fn test_import_decider_hot_symbol() {
        let decider = ThinLTOImportDecider::new();
        let mut index = ModuleSummaryIndex::new();

        // Module 0 has a large function
        index.add_module(vec![GlobalSummary {
            name: "large_fn".into(),
            module_index: 0,
            is_function: true,
            instruction_count: 500,
            can_import: true,
            refs: vec![],
            calls: vec![],
            readonly_refs: vec![],
            resolution: SymbolResolution::Prevailing,
        }]);

        // Module 1 is empty
        index.add_module(vec![]);

        let preserved: HashSet<String> = ["large_fn".into()].iter().cloned().collect();
        index.resolve(&preserved);
        let hot: HashSet<String> = ["large_fn".into()].iter().cloned().collect();

        let imports = decider.decide_imports(1, &index, &hot);
        // Hot symbol should be imported even though it exceeds threshold
        assert!(imports.iter().any(|i| i.symbol == "large_fn"));
    }

    #[test]
    fn test_import_decider_estimate_benefit() {
        let decider = ThinLTOImportDecider::new();
        let summary = GlobalSummary {
            name: "test".into(),
            module_index: 0,
            is_function: true,
            instruction_count: 50,
            can_import: true,
            refs: vec![],
            calls: vec![],
            readonly_refs: vec![],
            resolution: SymbolResolution::Prevailing,
        };
        let benefit = decider.estimate_import_benefit(&summary);
        assert!(benefit > 0);
    }

    #[test]
    fn test_import_decider_zero_inst_no_benefit() {
        let decider = ThinLTOImportDecider::new();
        let summary = GlobalSummary {
            name: "decl".into(),
            module_index: 0,
            is_function: true,
            instruction_count: 0,
            can_import: false,
            refs: vec![],
            calls: vec![],
            readonly_refs: vec![],
            resolution: SymbolResolution::Prevailing,
        };
        let benefit = decider.estimate_import_benefit(&summary);
        assert_eq!(benefit, 0);
    }

    // === LTOCodeGenerator Tests ===

    #[test]
    fn test_lto_codegen_create() {
        let gen = LTOCodeGenerator::new(LTOMode::Full);
        assert_eq!(gen.mode, LTOMode::Full);
        assert!(gen.modules.is_empty());
    }

    #[test]
    fn test_lto_codegen_add_module() {
        let mut gen = LTOCodeGenerator::new(LTOMode::Thin);
        let m = build_module("mod1", "func1");
        let lto = LTOModule::new(m, "mod1.o");
        gen.add_module(lto);
        assert_eq!(gen.modules.len(), 1);
        assert!(gen.summary_index.global_map.contains_key("func1"));
    }

    #[test]
    fn test_lto_codegen_full_lto() {
        let mut gen = LTOCodeGenerator::new(LTOMode::Full);

        let m1 = build_module("mod1", "func1");
        let m2 = build_module("mod2", "func2");

        gen.add_module(LTOModule::new(m1, "mod1.o"));
        gen.add_module(LTOModule::new(m2, "mod2.o"));

        let preserved: HashSet<String> = ["func1", "func2"].iter().map(|s| s.to_string()).collect();

        let result = gen.run(&preserved);
        assert!(result.is_ok());
        assert!(gen.combined.is_some());
    }

    #[test]
    fn test_lto_codegen_thin_lto() {
        let mut gen = LTOCodeGenerator::new(LTOMode::Thin);

        let m1 = build_module("mod1", "func1");
        let m2 = build_module("mod2", "func2");

        gen.add_module(LTOModule::new(m1, "mod1.o"));
        gen.add_module(LTOModule::new(m2, "mod2.o"));

        let preserved: HashSet<String> = ["func1", "func2"].iter().map(|s| s.to_string()).collect();

        let result = gen.run(&preserved);
        assert!(result.is_ok());
        // ThinLTO doesn't create a combined module
        assert!(gen.combined.is_none());
    }

    #[test]
    fn test_lto_codegen_stats() {
        let mut gen = LTOCodeGenerator::new(LTOMode::Full);
        let m1 = build_module("mod1", "func1");
        gen.add_module(LTOModule::new(m1, "mod1.o"));

        let preserved: HashSet<String> = ["func1"].iter().map(|s| s.to_string()).collect();
        let _ = gen.run(&preserved);

        let stats = gen.stats();
        assert_eq!(stats.mode, LTOMode::Full);
        assert_eq!(stats.num_modules, 1);
        assert_eq!(stats.num_functions, 1);
    }

    #[test]
    fn test_lto_codegen_empty_modules_error() {
        let mut gen = LTOCodeGenerator::new(LTOMode::Full);
        let preserved: HashSet<String> = HashSet::new();
        let result = gen.run(&preserved);
        assert!(result.is_err());
    }

    #[test]
    fn test_lto_codegen_output_modules_full() {
        let mut gen = LTOCodeGenerator::new(LTOMode::Full);
        let m1 = build_module("mod1", "func1");
        gen.add_module(LTOModule::new(m1, "mod1.o"));

        let preserved: HashSet<String> = ["func1"].iter().map(|s| s.to_string()).collect();
        let _ = gen.run(&preserved);

        let outputs = gen.output_modules();
        assert_eq!(outputs.len(), 1);
    }

    #[test]
    fn test_lto_codegen_output_modules_thin() {
        let mut gen = LTOCodeGenerator::new(LTOMode::Thin);
        let m1 = build_module("mod1", "func1");
        let m2 = build_module("mod2", "func2");
        gen.add_module(LTOModule::new(m1, "mod1.o"));
        gen.add_module(LTOModule::new(m2, "mod2.o"));

        let preserved: HashSet<String> = ["func1", "func2"].iter().map(|s| s.to_string()).collect();
        let _ = gen.run(&preserved);

        let outputs = gen.output_modules();
        // ThinLTO returns individual modules
        assert_eq!(outputs.len(), 2);
    }

    #[test]
    fn test_lto_symbol_resolution_prevailing() {
        let mut index = ModuleSummaryIndex::new();

        // Module 0: defines "main"
        index.add_module(vec![GlobalSummary {
            name: "main".into(),
            module_index: 0,
            is_function: true,
            instruction_count: 5,
            can_import: true,
            refs: vec![],
            calls: vec!["helper".into()],
            readonly_refs: vec![],
            resolution: SymbolResolution::Prevailing,
        }]);

        // Module 1: defines "helper"
        index.add_module(vec![GlobalSummary {
            name: "helper".into(),
            module_index: 1,
            is_function: true,
            instruction_count: 3,
            can_import: true,
            refs: vec![],
            calls: vec![],
            readonly_refs: vec![],
            resolution: SymbolResolution::Prevailing,
        }]);

        let preserved: HashSet<String> = ["main", "helper"].iter().map(|s| s.to_string()).collect();
        index.resolve(&preserved);

        assert!(index.prevailing.contains("main"));
        assert!(index.prevailing.contains("helper"));
    }

    #[test]
    fn test_lto_pipeline_end_to_end() {
        // Full end-to-end: create modules, run full LTO, verify output
        let mut gen = LTOCodeGenerator::new(LTOMode::Full);

        // Create two modules with functions
        for i in 0..3 {
            let module_name = format!("mod{}", i);
            let func_name = format!("func{}", i);
            let m = build_module(&module_name, &func_name);
            gen.add_module(LTOModule::new(m, &format!("{}.o", module_name)));
        }

        let preserved: HashSet<String> = (0..3).map(|i| format!("func{}", i)).collect();

        let result = gen.run(&preserved);
        assert!(result.is_ok());

        let stats = gen.stats();
        assert_eq!(stats.num_modules, 3);
        assert_eq!(stats.num_functions, 3);

        // Combined module should have merged functions
        let outputs = gen.output_modules();
        assert_eq!(outputs.len(), 1);
        assert_eq!(outputs[0].functions.len(), 3);
    }

    // ========================================================================
    // New LTO Pipeline Tests
    // ========================================================================

    // === LTOConfig Tests ===

    #[test]
    fn test_lto_config_default() {
        let config = LTOConfig::default();
        assert!(!config.use_thin_lto);
        assert_eq!(config.thin_lto_threads, 4);
        assert!(config.internalize);
        assert_eq!(config.import_instr_limit, 100);
        assert_eq!(config.cg_opt_level, 2);
    }

    #[test]
    fn test_lto_config_thin_lto() {
        let config = LTOConfig {
            use_thin_lto: true,
            ..LTOConfig::default()
        };
        assert!(config.use_thin_lto);
    }

    // === OptimizationLevel Tests ===

    #[test]
    fn test_optimization_level_equality() {
        assert_eq!(OptimizationLevel::O2, OptimizationLevel::O2);
        assert_ne!(OptimizationLevel::O0, OptimizationLevel::O3);
    }

    // === LTO struct creation ===

    #[test]
    fn test_lto_pipeline_create() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        assert_eq!(lto.modules.len(), 0);
        assert_eq!(lto.opt_level, OptimizationLevel::O2);
        assert_eq!(lto.stats.num_modules, 0);
    }

    #[test]
    fn test_lto_pipeline_add_module() {
        let config = LTOConfig::default();
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        let m = build_module("mod1", "func1");
        lto.add_module(m);
        assert_eq!(lto.modules.len(), 1);
        assert_eq!(lto.stats.num_modules, 1);
    }

    #[test]
    fn test_lto_pipeline_empty_modules_error() {
        let config = LTOConfig::default();
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        let result = lto.run();
        assert!(result.is_err());
    }

    // === GUID Computation Tests ===

    #[test]
    fn test_compute_guid_deterministic() {
        let g1 = LTO::compute_guid("my_function");
        let g2 = LTO::compute_guid("my_function");
        assert_eq!(g1, g2);
    }

    #[test]
    fn test_compute_guid_different_names() {
        let g1 = LTO::compute_guid("func_a");
        let g2 = LTO::compute_guid("func_b");
        assert_ne!(g1, g2);
    }

    #[test]
    fn test_compute_guid_is_nonzero() {
        let g = LTO::compute_guid("test");
        assert_ne!(g, 0);
    }

    // === Build Module Summaries Tests ===

    #[test]
    fn test_build_module_summary() {
        let config = LTOConfig::default();
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        let m = build_module("test_mod", "my_func");
        lto.add_module(m);
        lto.build_summaries();

        assert!(!lto.summary.module_summaries.is_empty());
        let mod_sum = &lto.summary.module_summaries[0];
        assert_eq!(mod_sum.module_name, "test_mod");
        assert!(mod_sum.function_names.contains(&"my_func".to_string()));
        assert!(!mod_sum.module_hash.is_empty());
    }

    #[test]
    fn test_build_summary_multiple_modules() {
        let config = LTOConfig::default();
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        lto.add_module(build_module("mod1", "f1"));
        lto.add_module(build_module("mod2", "f2"));
        lto.build_summaries();

        assert_eq!(lto.summary.module_summaries.len(), 2);
    }

    // === Global Value Summary Tests ===

    #[test]
    fn test_summarize_function_basic() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        let m = build_module("mod", "target_fn");
        let func = &m.functions[0];
        let summary = lto.summarize_function(func);

        assert_eq!(summary.name, "target_fn");
        assert!(summary.is_function);
        assert!(summary.instruction_count > 0);
        assert_eq!(summary.linkage, GlobalLinkage::External);
    }

    #[test]
    fn test_summarize_function_declaration() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        // Build a module with a declaration (no basic blocks)
        let mut m = Module::new("mod");
        let func = new_function("decl_fn", Type::void(), &[]);
        m.add_function(func);

        let summary = lto.summarize_function(&m.functions[0]);
        assert_eq!(summary.instruction_count, 0);
        assert!(!summary.is_import_eligible);
    }

    #[test]
    fn test_summarize_global_variable() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        let gv = llvm_native_core::value::Value::new(Type::i32())
            .named("my_global")
            .with_subclass(SubclassKind::GlobalVariable);
        let gv_ref = llvm_native_core::value::valref(gv);
        let summary = lto.summarize_global(&gv_ref);

        assert_eq!(summary.name, "my_global");
        assert!(!summary.is_function);
        assert!(!summary.is_import_eligible);
    }

    #[test]
    fn test_summarize_function_import_eligible() {
        let config = LTOConfig {
            import_instr_limit: 100,
            ..LTOConfig::default()
        };
        let lto = LTO::new(config, OptimizationLevel::O2);
        let m = build_module("mod", "small_fn");
        let summary = lto.summarize_function(&m.functions[0]);

        // Small functions should be import-eligible
        assert!(summary.is_import_eligible);
        assert!(summary.guid != 0);
    }

    // === Call Graph Tests ===

    #[test]
    fn test_build_call_graph_empty() {
        let config = LTOConfig::default();
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        lto.build_summaries();
        let cg = lto.build_call_graph();
        assert!(cg.is_empty());
    }

    #[test]
    fn test_build_call_graph_with_functions() {
        let config = LTOConfig::default();
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        lto.add_module(build_module("mod", "caller"));
        lto.build_summaries();
        let cg = lto.build_call_graph();
        assert!(cg.contains_key("caller"));
    }

    #[test]
    fn test_compute_call_graph_for_func_empty() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        let m = build_module("mod", "empty_caller");
        let func = m.functions[0].borrow();
        let callees = lto.compute_call_graph_for_func(&func);
        // Our test function doesn't have call instructions, so callees is empty
        assert!(callees.is_empty());
    }

    // === Internalization Tests ===

    #[test]
    fn test_should_internalize_exported() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        let exported: HashSet<String> = ["keep_me".into()].iter().cloned().collect();
        assert!(!lto.should_internalize("keep_me", GlobalLinkage::External, &exported));
    }

    #[test]
    fn test_should_internalize_non_exported() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        let exported: HashSet<String> = HashSet::new();
        assert!(lto.should_internalize("hidden_fn", GlobalLinkage::External, &exported));
    }

    #[test]
    fn test_should_not_internalize_llvm_intrinsic() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        let exported: HashSet<String> = HashSet::new();
        assert!(!lto.should_internalize("llvm.memcpy", GlobalLinkage::External, &exported));
    }

    #[test]
    fn test_should_internalize_linkonce_odr() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        let exported: HashSet<String> = HashSet::new();
        assert!(lto.should_internalize("odr_fn", GlobalLinkage::LinkOnceODR, &exported));
    }

    #[test]
    fn test_find_exported_symbols() {
        let config = LTOConfig::default();
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        lto.add_module(build_module("mod1", "exported_fn"));
        let exported = lto.find_exported_symbols();
        assert!(exported.contains("exported_fn"));
    }

    #[test]
    fn test_internalize_reduces_count() {
        let config = LTOConfig::default();
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        lto.add_module(build_module("mod", "to_internalize"));
        let exported: HashSet<String> = HashSet::new(); // nothing exported
        lto.internalize(&exported);
        // The module should have had its non-exported functions internalized
        // (retain logic keeps llvm.* and Internal-linkage functions)
        let remaining = lto.modules[0].functions.len();
        assert!(remaining <= 1);
    }

    // === Dead Global Elimination Tests ===

    #[test]
    fn test_find_used_globals_entry_point() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        let m = build_module("mod", "main");
        let used = lto.find_used_globals(&m);
        // "main" should be in the used set as a root
        assert!(used.contains("main"));
    }

    #[test]
    fn test_eliminate_dead_globals() {
        let config = LTOConfig::default();
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        let mut m = build_module("mod", "main");
        // Add an unreferenced global
        let dead_gv = llvm_native_core::value::Value::new(Type::i32())
            .named("dead_global")
            .with_subclass(SubclassKind::GlobalVariable);
        m.globals.push(llvm_native_core::value::valref(dead_gv));
        lto.add_module(m);

        let before_globals: usize = lto.modules.iter().map(|m| m.globals.len()).sum();
        lto.eliminate_dead_globals();
        let after_globals: usize = lto.modules.iter().map(|m| m.globals.len()).sum();

        // Some globals may be eliminated if they're dead
        assert!(after_globals <= before_globals);
    }

    // === Full LTO Pipeline End-to-End Tests ===

    #[test]
    fn test_full_lto_pipeline_end_to_end() {
        let config = LTOConfig::default();
        let mut lto = LTO::new(config, OptimizationLevel::O2);

        for i in 0..3 {
            let module_name = format!("mod{}", i);
            let func_name = format!("func{}", i);
            lto.add_module(build_module(&module_name, &func_name));
        }

        let result = lto.run();
        assert!(result.is_ok());

        let merged = result.unwrap();
        assert!(merged.functions.len() >= 1);

        // Stats should be updated
        assert_eq!(lto.stats.modules_processed, 3);
        assert!(lto.stats.total_instructions_before > 0);
    }

    #[test]
    fn test_full_lto_pipeline_single_module() {
        let config = LTOConfig::default();
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        lto.add_module(build_module("only", "only_func"));

        let result = lto.run();
        assert!(result.is_ok());
        let merged = result.unwrap();
        assert!(merged
            .functions
            .iter()
            .any(|f| f.borrow().name == "only_func"));
    }

    #[test]
    fn test_full_lto_internalizes_non_exported() {
        let config = LTOConfig {
            internalize: true,
            ..LTOConfig::default()
        };
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        lto.add_module(build_module("mod", "local_fn"));
        lto.add_module(build_module("mod2", "exported_fn"));

        let result = lto.run();
        assert!(result.is_ok());
        // Check that internalize stats were tracked
        assert!(lto.stats.modules_processed > 0);
    }

    // === ThinLTO Pipeline Tests ===

    #[test]
    fn test_thin_lto_pipeline_builds_summaries() {
        let config = LTOConfig {
            use_thin_lto: true,
            ..LTOConfig::default()
        };
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        lto.add_module(build_module("mod1", "f1"));
        lto.add_module(build_module("mod2", "f2"));

        lto.build_summaries();

        assert_eq!(lto.summary.module_summaries.len(), 2);
        assert!(lto.summary.global_summaries.contains_key("f1"));
        assert!(lto.summary.global_summaries.contains_key("f2"));
    }

    #[test]
    fn test_thin_lto_end_to_end() {
        let config = LTOConfig {
            use_thin_lto: true,
            ..LTOConfig::default()
        };
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        lto.add_module(build_module("mod1", "f1"));
        lto.add_module(build_module("mod2", "f2"));

        let result = lto.run();
        assert!(result.is_ok());
        let merged = result.unwrap();
        assert!(!merged.functions.is_empty());
        assert!(lto.stats.modules_processed > 0);
    }

    // === Import Decision Tests ===

    #[test]
    fn test_compute_import_decisions() {
        let config = LTOConfig {
            use_thin_lto: true,
            import_instr_limit: 100,
            ..LTOConfig::default()
        };
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        lto.add_module(build_module("mod1", "small_fn"));
        lto.add_module(build_module("mod2", "caller"));
        lto.build_summaries();

        let imports = lto.compute_import_decisions();
        // Small functions should be import candidates
        // (exact count depends on the decider logic)
        assert!(lto.stats.functions_imported == imports.len());
    }

    #[test]
    fn test_should_import_small_function() {
        let config = LTOConfig {
            import_instr_limit: 100,
            ..LTOConfig::default()
        };
        let lto = LTO::new(config, OptimizationLevel::O2);
        let summary = GlobalValueSummary {
            name: "tiny".into(),
            linkage: GlobalLinkage::External,
            is_function: true,
            guid: 42,
            callees: vec![],
            is_import_eligible: true,
            instruction_count: 5,
            entry_count: 0,
        };
        let m = Module::new("caller");
        // Small function should have benefit > cost
        let result = lto.should_import(&summary, &m);
        // Benefit = 100/5 = 20, Cost = 5, so benefit > cost
        assert!(result);
    }

    #[test]
    fn test_should_not_import_large_function() {
        let config = LTOConfig {
            import_instr_limit: 10,
            ..LTOConfig::default()
        };
        let lto = LTO::new(config, OptimizationLevel::O2);
        let summary = GlobalValueSummary {
            name: "huge".into(),
            linkage: GlobalLinkage::External,
            is_function: true,
            guid: 99,
            callees: vec![],
            is_import_eligible: false, // exceeds limit
            instruction_count: 500,
            entry_count: 0,
        };
        let m = Module::new("caller");
        assert!(!lto.should_import(&summary, &m));
    }

    // === Import Cost/Benefit Tests ===

    #[test]
    fn test_compute_import_cost() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        let summary = GlobalValueSummary {
            name: "f".into(),
            linkage: GlobalLinkage::External,
            is_function: true,
            guid: 1,
            callees: vec![],
            is_import_eligible: true,
            instruction_count: 42,
            entry_count: 0,
        };
        assert_eq!(lto.compute_import_cost(&summary), 42);
    }

    #[test]
    fn test_compute_import_benefit_zero_inst() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        let summary = GlobalValueSummary {
            name: "empty".into(),
            linkage: GlobalLinkage::External,
            is_function: true,
            guid: 1,
            callees: vec![],
            is_import_eligible: false,
            instruction_count: 0,
            entry_count: 0,
        };
        assert_eq!(lto.compute_import_benefit(&summary), 0);
    }

    #[test]
    fn test_compute_import_benefit_small_fn() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        let summary = GlobalValueSummary {
            name: "small".into(),
            linkage: GlobalLinkage::External,
            is_function: true,
            guid: 2,
            callees: vec![],
            is_import_eligible: true,
            instruction_count: 10,
            entry_count: 0,
        };
        let benefit = lto.compute_import_benefit(&summary);
        // 100 / 10 = 10
        assert_eq!(benefit, 10);
    }

    // === Module Merging Tests ===

    #[test]
    fn test_merge_modules_basic() {
        let config = LTOConfig::default();
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        lto.add_module(build_module("mod1", "f1"));
        lto.add_module(build_module("mod2", "f2"));

        let result = lto.merge_modules();
        assert!(result.is_ok());
        let merged = result.unwrap();
        assert!(merged.functions.len() >= 2);
    }

    #[test]
    fn test_merge_modules_empty() {
        let config = LTOConfig::default();
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        let result = lto.merge_modules();
        assert!(result.is_err());
    }

    // === Statistics Tracking Tests ===

    #[test]
    fn test_lto_stats_initialization() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        assert_eq!(lto.stats.functions_internalized, 0);
        assert_eq!(lto.stats.functions_imported, 0);
        assert_eq!(lto.stats.globals_eliminated, 0);
        assert_eq!(lto.stats.functions_merged, 0);
        assert_eq!(lto.stats.total_instructions_before, 0);
        assert_eq!(lto.stats.total_instructions_after, 0);
    }

    #[test]
    fn test_lto_stats_after_full_run() {
        let config = LTOConfig::default();
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        lto.add_module(build_module("mod1", "f1"));
        lto.add_module(build_module("mod2", "f2"));

        let _ = lto.run();

        assert_eq!(lto.stats.modules_processed, 2);
        assert!(lto.stats.total_instructions_before > 0);
        assert!(lto.stats.total_instructions_after > 0);
    }

    // === Edge Cases ===

    #[test]
    fn test_lto_empty_module_list() {
        let config = LTOConfig::default();
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        let result = lto.run();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("No modules"));
    }

    #[test]
    fn test_lto_single_module() {
        let config = LTOConfig::default();
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        lto.add_module(build_module("only", "solo"));

        let result = lto.run();
        assert!(result.is_ok());
    }

    #[test]
    fn test_lto_all_internal_symbols() {
        let config = LTOConfig {
            internalize: true,
            ..LTOConfig::default()
        };
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        // All functions have external linkage, none are "exported"
        lto.add_module(build_module("mod", "internal1"));
        lto.add_module(build_module("mod2", "internal2"));

        let result = lto.run();
        assert!(result.is_ok());
        // Internalization may have occurred (count may vary)
        assert!(lto.stats.modules_processed > 0);
    }

    // === LTOSummary Tests ===

    #[test]
    fn test_lto_summary_new() {
        let summary = LTOSummary::new();
        assert!(summary.module_summaries.is_empty());
        assert!(summary.global_summaries.is_empty());
        assert!(summary.call_graph.is_empty());
    }

    #[test]
    fn test_lto_summary_get_global() {
        let mut summary = LTOSummary::new();
        let gvs = GlobalValueSummary {
            name: "test".into(),
            linkage: GlobalLinkage::External,
            is_function: true,
            guid: 123,
            callees: vec![],
            is_import_eligible: true,
            instruction_count: 10,
            entry_count: 0,
        };
        summary.global_summaries.insert("test".into(), gvs);
        assert!(summary.get_global("test").is_some());
        assert!(summary.get_global("nonexistent").is_none());
    }

    #[test]
    fn test_lto_summary_can_import() {
        let mut summary = LTOSummary::new();
        let gvs = GlobalValueSummary {
            name: "importable".into(),
            linkage: GlobalLinkage::External,
            is_function: true,
            guid: 456,
            callees: vec![],
            is_import_eligible: true,
            instruction_count: 5,
            entry_count: 0,
        };
        summary.global_summaries.insert("importable".into(), gvs);
        assert!(summary.can_import("importable"));
        assert!(!summary.can_import("nonexistent"));
    }

    #[test]
    fn test_lto_summary_default() {
        let summary = LTOSummary::default();
        assert!(summary.module_summaries.is_empty());
    }

    // === TypeIdSummary Tests ===

    #[test]
    fn test_type_id_summary_create() {
        let tid_summary = TypeIdSummary {
            type_id: "_ZTV3Foo".into(),
            vtable_defs: vec!["mod1".into(), "mod2".into()],
        };
        assert_eq!(tid_summary.type_id, "_ZTV3Foo");
        assert_eq!(tid_summary.vtable_defs.len(), 2);
    }

    // === LTOConfig non-default Tests ===

    #[test]
    fn test_lto_config_custom() {
        let config = LTOConfig {
            use_thin_lto: true,
            thin_lto_threads: 8,
            internalize: false,
            import_instr_limit: 200,
            dge_threshold: 5,
            cg_opt_level: 3,
            save_temps: true,
        };
        assert!(config.use_thin_lto);
        assert_eq!(config.thin_lto_threads, 8);
        assert!(!config.internalize);
        assert_eq!(config.import_instr_limit, 200);
        assert!(config.save_temps);
    }

    // === internalize_function Tests ===

    #[test]
    fn test_internalize_function_noop() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        let m = build_module("m", "f");
        // Should not panic
        lto.internalize_function(&m.functions[0]);
    }

    // === mark_live_from_root Tests ===

    #[test]
    fn test_mark_live_from_root_simple() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        let m = build_module("mod", "root");
        let mut live = HashSet::new();
        live.insert("root".to_string());
        lto.mark_live_from_root(&m, "root", &mut live);
        assert!(live.contains("root"));
    }

    #[test]
    fn test_mark_live_from_root_nonexistent() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        let m = build_module("mod", "real_fn");
        let mut live = HashSet::new();
        // Should not panic when root doesn't exist
        lto.mark_live_from_root(&m, "no_such_fn", &mut live);
        assert!(live.is_empty());
    }

    // === run_thin_lto_backend Tests ===

    #[test]
    fn test_run_thin_lto_backend() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        let mut m = build_module("mod", "target");
        lto.run_thin_lto_backend(&mut m);
        // Function should still be present after backend
        assert!(m.functions.iter().any(|f| f.borrow().name == "target"));
    }

    // === run_optimization_passes Tests ===

    #[test]
    fn test_run_optimization_passes_o2() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        let mut m = build_module("mod", "opt_me");
        lto.run_optimization_passes(&mut m);
        assert!(!m.functions.is_empty());
    }

    #[test]
    fn test_run_optimization_passes_o3() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O3);
        let mut m = build_module("mod", "opt_me_o3");
        lto.run_optimization_passes(&mut m);
        assert!(!m.functions.is_empty());
    }

    #[test]
    fn test_count_all_instructions_zero_for_empty() {
        let config = LTOConfig::default();
        let lto = LTO::new(config, OptimizationLevel::O2);
        assert_eq!(lto.count_all_instructions(), 0);
    }

    #[test]
    fn test_count_all_instructions_nonzero() {
        let config = LTOConfig::default();
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        lto.add_module(build_module("mod", "f"));
        lto.build_summaries();
        assert!(lto.count_all_instructions() > 0);
    }

    // === apply_imported_functions Tests ===

    #[test]
    fn test_apply_imported_functions_empty() {
        let config = LTOConfig::default();
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        lto.add_module(build_module("mod", "f"));
        let imports: Vec<ThinLTOImport> = vec![];
        // Should not panic with empty imports
        lto.apply_imported_functions(&imports);
    }

    #[test]
    fn test_apply_imported_functions_with_imports() {
        let config = LTOConfig::default();
        let mut lto = LTO::new(config, OptimizationLevel::O2);
        lto.add_module(build_module("mod1", "source_fn"));
        lto.add_module(build_module("mod2", "dest_fn"));
        let imports = vec![ThinLTOImport {
            symbol: "source_fn".into(),
            from_module: 0,
            reason: ImportReason::InlineCandidate,
        }];
        // Should not panic
        lto.apply_imported_functions(&imports);
    }
}