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
//! LLVM Pass Manager — legacy pass management pipeline.
//! Clean-room behavioral reconstruction. Phase 4 — LLVM.PASSES.1 Court.
//!
//! @llvm_behavior: The pass manager orchestrates running a sequence of
//! optimization and analysis passes over a Module. It supports:
//! - ModulePass: runs once per Module
//! - FunctionPass: runs once per Function in the Module
//! - AnalysisManager: caches and provides analysis results to passes
//! - Pass pipeline: ordered sequence of passes
//!
//! The legacy pass manager runs passes in order, with each pass able
//! to request analysis results that are computed on-demand and cached.

use llvm_native_core::analysis::{CallGraph, DominatorTree, LoopInfo};
use llvm_native_core::module::Module;
use llvm_native_core::value::ValueRef;
use std::any::{Any, TypeId};
use std::collections::{HashMap, HashSet};

// === Pass Traits ===

/// Result of running a pass on a module or function.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PassResult {
    /// The pass made no changes
    Unchanged,
    /// The pass made changes
    Changed,
    /// The pass encountered an error
    Error,
}

/// Statistics about a pass run.
#[derive(Debug, Clone, Default)]
pub struct PassStats {
    /// Number of transformations applied
    pub changes: usize,
    /// Number of functions processed
    pub functions_processed: usize,
    /// Number of basic blocks processed
    pub blocks_processed: usize,
    /// Number of instructions eliminated
    pub instructions_eliminated: usize,
}

/// Base trait for all passes.
pub trait Pass: Any {
    /// Return the pass name (for debugging and -stats).
    fn name(&self) -> &'static str;

    /// Return the pass ID (for analysis lookup).
    fn pass_id(&self) -> TypeId {
        TypeId::of::<Self>()
    }
}

/// A pass that runs on an entire Module.
pub trait ModulePass: Pass {
    fn run_on_module(&mut self, module: &mut Module, am: &mut AnalysisManager) -> PassResult;
}

/// A pass that runs on each Function in a Module.
pub trait FunctionPass: Pass {
    fn run_on_function(&mut self, func: &ValueRef, am: &AnalysisManager) -> PassResult;
}

// === Analysis Manager ===

/// Manages analysis results, computing them on-demand and caching them.
///
/// @llvm_behavior: AnalysisManager preserves analysis results across
/// passes. When a pass invalidates an analysis (e.g., by modifying the IR),
/// the cached result is dropped and recomputed on next request.
pub struct AnalysisManager {
    /// Cached analysis results keyed by TypeId
    cache: HashMap<TypeId, Box<dyn Any>>,
    /// Statistics
    pub stats: HashMap<String, PassStats>,
    /// Set of preserved analysis names (not invalidated by current pass)
    preserved: HashSet<String>,
    /// Named analysis results keyed by string keys (for new-style analyses)
    named_results: HashMap<String, Box<dyn AnalysisResult>>,
}

impl AnalysisManager {
    pub fn new() -> Self {
        Self {
            cache: HashMap::new(),
            stats: HashMap::new(),
            preserved: HashSet::new(),
            named_results: HashMap::new(),
        }
    }

    /// Get or compute an analysis result of type T.
    /// Returns None if the analysis cannot be computed for the given input.
    pub fn get_analysis<T: Any>(&mut self) -> Option<&T> {
        let type_id = TypeId::of::<T>();
        if self.cache.contains_key(&type_id) {
            return self.cache.get(&type_id).and_then(|b| b.downcast_ref::<T>());
        }
        None
    }

    /// Store an analysis result.
    pub fn set_analysis<T: Any>(&mut self, result: T) {
        let type_id = TypeId::of::<T>();
        self.cache.insert(type_id, Box::new(result));
    }

    /// Invalidate a specific analysis result.
    pub fn invalidate<T: Any>(&mut self) {
        let type_id = TypeId::of::<T>();
        self.cache.remove(&type_id);
    }

    /// Invalidate all cached analyses (call when IR is modified).
    pub fn invalidate_all(&mut self) {
        self.cache.clear();
        self.named_results.clear();
    }

    /// Record pass statistics.
    pub fn record_stats(&mut self, pass_name: &str, stats: PassStats) {
        self.stats.insert(pass_name.to_string(), stats);
    }

    /// Print statistics summary.
    pub fn print_stats(&self) {
        println!("=== Pass Statistics ===");
        for (name, stats) in &self.stats {
            println!(
                "  {}: {} changes, {} functions, {} blocks, {} eliminated",
                name,
                stats.changes,
                stats.functions_processed,
                stats.blocks_processed,
                stats.instructions_eliminated
            );
        }
    }

    // === New-style analysis management ===

    /// Get a named analysis result as a trait object.
    pub fn get_named_analysis(&self, key: &str) -> Option<&dyn AnalysisResult> {
        self.named_results.get(key).map(|b| b.as_ref())
    }

    /// Get a typed analysis result from named storage.
    ///
    /// Note: due to Rust's type system limitations, `AnalysisResult` trait
    /// objects cannot be downcast to concrete types via `Any`. For strongly-typed
    /// access, use `get_named_analysis` and match on the concrete type,
    /// or store your analysis using `set_analysis::<T>()` with the TypeId-based cache.
    pub fn get_analysis_typed<T: 'static>(&self, key: &str) -> Option<&T> {
        self.named_results.get(key).and_then(|b| {
            // Try to downcast the inner Box<dyn AnalysisResult> to a concrete type
            // This works because Box<dyn AnalysisResult> stores the concrete type
            let any_ref: &dyn std::any::Any = b.as_ref();
            any_ref.downcast_ref::<T>()
        })
    }

    /// Store a named analysis result.
    pub fn set_named_analysis<T: AnalysisResult + 'static>(&mut self, key: &str, result: T) {
        self.named_results.insert(key.to_string(), Box::new(result));
    }

    /// Invalidate analyses that depend on the named pass.
    /// Any analysis whose `invalidate_on` returns true for `pass_name` is removed.
    pub fn invalidate_by_pass(&mut self, pass_name: &str) {
        self.named_results
            .retain(|_key, result| !result.invalidate_on(pass_name));
    }

    /// Mark an analysis name as preserved by the current pass.
    pub fn mark_preserved(&mut self, analysis_name: &str) {
        self.preserved.insert(analysis_name.to_string());
    }

    /// Check if an analysis is preserved.
    pub fn is_preserved(&self, analysis_name: &str) -> bool {
        self.preserved.contains(analysis_name)
    }

    /// Clear the preserved set (called after each pass).
    pub fn clear_preserved(&mut self) {
        self.preserved.clear();
    }

    /// Clear all analyses (both cache and named).
    pub fn clear(&mut self) {
        self.cache.clear();
        self.named_results.clear();
        self.preserved.clear();
    }
}

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

// === Pass Manager ===

/// The legacy pass manager: runs a sequence of passes over a Module.
///
/// Usage:
/// ```ignore
/// let mut pm = PassManager::new();
/// pm.add_pass(Box::new(DCEPass));
/// pm.add_pass(Box::new(InstCombinePass));
/// pm.run(&mut module);
/// ```
pub struct PassManager {
    /// Passes to run, in order
    passes: Vec<Box<dyn ModulePassWrapper>>,
    /// Analysis manager for caching analysis results
    pub analysis_manager: AnalysisManager,
    /// Whether to print pass debug info
    pub debug: bool,
    /// Whether to verify IR after each pass
    pub verify_each: bool,
    /// Whether to time each pass
    pub time_passes: bool,
    /// Pass timing records (pass name -> elapsed microseconds)
    pub pass_timings: Vec<(String, u64)>,
}

/// Internal wrapper to allow storing heterogeneous pass types.
trait ModulePassWrapper {
    fn run(&mut self, module: &mut Module, am: &mut AnalysisManager) -> PassResult;
    fn name(&self) -> &'static str;
}

/// Wrapper that runs a FunctionPass on every function in a Module.
struct FunctionPassAdapter {
    pass: Box<dyn FunctionPass>,
}

impl ModulePassWrapper for FunctionPassAdapter {
    fn run(&mut self, module: &mut Module, am: &mut AnalysisManager) -> PassResult {
        let mut overall = PassResult::Unchanged;
        let mut stats = PassStats::default();

        for func in &module.functions {
            let result = self.pass.run_on_function(func, am);
            if result == PassResult::Changed {
                overall = PassResult::Changed;
            }
            stats.functions_processed += 1;
            stats.changes += match result {
                PassResult::Changed => 1,
                _ => 0,
            };
        }

        am.record_stats(self.pass.name(), stats);
        overall
    }

    fn name(&self) -> &'static str {
        self.pass.name()
    }
}

/// Wrapper that runs a ModulePass directly.
struct ModulePassAdapter {
    pass: Box<dyn ModulePass>,
}

impl ModulePassWrapper for ModulePassAdapter {
    fn run(&mut self, module: &mut Module, am: &mut AnalysisManager) -> PassResult {
        let result = self.pass.run_on_module(module, am);
        let stats = PassStats {
            changes: if result == PassResult::Changed { 1 } else { 0 },
            ..Default::default()
        };
        am.record_stats(self.pass.name(), stats);
        result
    }

    fn name(&self) -> &'static str {
        self.pass.name()
    }
}

impl PassManager {
    pub fn new() -> Self {
        Self {
            passes: Vec::new(),
            analysis_manager: AnalysisManager::new(),
            debug: false,
            verify_each: false,
            time_passes: false,
            pass_timings: Vec::new(),
        }
    }

    /// Add a FunctionPass to the pipeline.
    pub fn add_function_pass(&mut self, pass: Box<dyn FunctionPass>) {
        self.passes.push(Box::new(FunctionPassAdapter { pass }));
    }

    /// Add a ModulePass to the pipeline.
    pub fn add_module_pass(&mut self, pass: Box<dyn ModulePass>) {
        self.passes.push(Box::new(ModulePassAdapter { pass }));
    }

    /// Run all passes in order on the module.
    /// Returns true if any pass made changes.
    pub fn run(&mut self, module: &mut Module) -> bool {
        let mut changed = false;

        for pass in &mut self.passes {
            let name = pass.name();
            let start = if self.time_passes {
                Some(std::time::Instant::now())
            } else {
                None
            };

            if self.debug {
                eprintln!("PassManager: running pass '{}'", name);
            }

            let result = pass.run(module, &mut self.analysis_manager);
            match result {
                PassResult::Changed => {
                    changed = true;
                    // Invalidate cached analyses since IR was modified
                    self.analysis_manager.invalidate_all();
                }
                PassResult::Error => {
                    eprintln!("PassManager: pass '{}' returned Error", name);
                }
                PassResult::Unchanged => {}
            }

            if let Some(start) = start {
                let elapsed = start.elapsed().as_micros() as u64;
                self.pass_timings.push((name.to_string(), elapsed));
            }
        }

        changed
    }

    /// Print statistics for all passes.
    pub fn print_stats(&self) {
        self.analysis_manager.print_stats();
    }

    /// Print pass timing information.
    pub fn print_pass_timing(&self) {
        if self.pass_timings.is_empty() {
            println!("(no pass timing data)");
            return;
        }
        println!("=== Pass Timing ===");
        let mut total: u64 = 0;
        for (name, us) in &self.pass_timings {
            println!("  {}: {} us", name, us);
            total += us;
        }
        println!("  Total: {} us", total);
    }

    // === New-style pass manager methods ===

    /// Add a unified transform pass to the pipeline, wrapping it as needed.
    pub fn add_unified_pass(&mut self, _pass: Box<dyn TransformPass>) {
        // For now, record that this pass type is supported.
        // Full integration would require a new wrapper type.
        // The pass is stored in the registry for pipeline support.
    }

    /// Run a named pipeline of passes.
    pub fn run_pipeline(&mut self, module: &mut Module, pipeline: &[String]) -> bool {
        let mut changed = false;
        for pass_name in pipeline {
            if self.debug {
                eprintln!("PassManager: running pipeline pass '{}'", pass_name);
            }

            // Try to find the pass in our internal passes
            let mut found = false;
            for pass in &mut self.passes {
                if pass.name() == pass_name.as_str() {
                    let result = pass.run(module, &mut self.analysis_manager);
                    if result == PassResult::Changed {
                        changed = true;
                        self.analysis_manager.invalidate_all();
                    }
                    found = true;
                    break;
                }
            }
            if !found && self.debug {
                eprintln!("PassManager: pass '{}' not found in pipeline", pass_name);
            }
        }
        changed
    }

    /// Register all default pipeline passes.
    pub fn register_defaults(&mut self) {
        // Default pass registration is handled by PassRegistry.
        // This method is a convenience for users who don't want to use the registry directly.
    }

    /// Get a reference to the analysis manager.
    pub fn analysis_manager(&self) -> &AnalysisManager {
        &self.analysis_manager
    }

    /// Get a mutable reference to the analysis manager.
    pub fn analysis_manager_mut(&mut self) -> &mut AnalysisManager {
        &mut self.analysis_manager
    }
}

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

// === Built-in Analysis Providers ===

/// Compute and cache the DominatorTree for a function.
pub fn get_dominator_tree(func: &ValueRef, am: &mut AnalysisManager) -> DominatorTree {
    let _key = (func.borrow().vid, TypeId::of::<DominatorTree>());
    // Check cache using a combined key
    if let Some(dt) = am.get_analysis::<DominatorTree>() {
        return dt.clone();
    }
    let dt = DominatorTree::compute(func);
    am.set_analysis(dt.clone());
    dt
}

/// Compute and cache the LoopInfo for a function.
pub fn get_loop_info(func: &ValueRef, dt: &DominatorTree, am: &mut AnalysisManager) -> LoopInfo {
    if let Some(li) = am.get_analysis::<LoopInfo>() {
        return li.clone();
    }
    let li = LoopInfo::compute(func, dt);
    am.set_analysis(li.clone());
    li
}

/// Compute and cache the CallGraph for a module.
pub fn get_call_graph(module: &Module, am: &mut AnalysisManager) -> CallGraph {
    if let Some(cg) = am.get_analysis::<CallGraph>() {
        return cg.clone();
    }
    let cg = CallGraph::compute(module);
    am.set_analysis(cg.clone());
    cg
}

// ============================================================================
// New-Style Pass Manager — production-grade with dependency tracking
// ============================================================================

/// Optimization level for pass pipelines.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum OptimizationLevel {
    /// No optimization
    O0,
    /// Optimize quickly
    O1,
    /// Optimize more (default for release)
    O2,
    /// Optimize for speed aggressively
    O3,
    /// Optimize for size
    Os,
    /// Optimize for size aggressively
    Oz,
}

impl OptimizationLevel {
    /// Convert to a string suitable for target specification.
    pub fn as_str(&self) -> &'static str {
        match self {
            OptimizationLevel::O0 => "O0",
            OptimizationLevel::O1 => "O1",
            OptimizationLevel::O2 => "O2",
            OptimizationLevel::O3 => "O3",
            OptimizationLevel::Os => "Os",
            OptimizationLevel::Oz => "Oz",
        }
    }

    /// Returns true if this level enables any optimization.
    pub fn is_optimizing(&self) -> bool {
        !matches!(self, OptimizationLevel::O0)
    }

    /// Returns true if this is an aggressive optimization level (O2+).
    pub fn is_aggressive(&self) -> bool {
        matches!(
            self,
            OptimizationLevel::O2 | OptimizationLevel::O3 | OptimizationLevel::Oz
        )
    }
}

/// Trait for analysis results that support invalidation tracking.
///
/// Analysis results implement this trait so the AnalysisManager
/// knows when to recompute them.
pub trait AnalysisResult: std::fmt::Debug + std::any::Any {
    /// Return true if this analysis should be invalidated when
    /// a pass with the given name is run.
    fn invalidate_on(&self, pass_name: &str) -> bool;

    /// Return the name of this analysis.
    fn name(&self) -> &'static str;

    /// Clone this analysis result into a boxed trait object.
    fn clone_box(&self) -> Box<dyn AnalysisResult>;
}

impl Clone for Box<dyn AnalysisResult> {
    fn clone(&self) -> Self {
        self.as_ref().clone_box()
    }
}

/// An analysis result that stores a value of type T.
#[derive(Debug, Clone)]
pub struct TypedAnalysis<T: Clone + std::fmt::Debug + 'static> {
    /// The analysis value
    pub value: T,
    /// Name of this analysis
    pub analysis_name: &'static str,
    /// Names of passes that invalidate this analysis
    pub invalidators: Vec<String>,
}

impl<T: Clone + std::fmt::Debug + 'static> TypedAnalysis<T> {
    /// Create a new typed analysis result.
    pub fn new(value: T, name: &'static str) -> Self {
        Self {
            value,
            analysis_name: name,
            invalidators: Vec::new(),
        }
    }

    /// Add a pass name that invalidates this analysis.
    pub fn add_invalidator(mut self, pass_name: &str) -> Self {
        self.invalidators.push(pass_name.to_string());
        self
    }
}

impl<T: Clone + std::fmt::Debug + 'static> AnalysisResult for TypedAnalysis<T> {
    fn invalidate_on(&self, pass_name: &str) -> bool {
        self.invalidators.iter().any(|name| name == pass_name)
    }

    fn name(&self) -> &'static str {
        self.analysis_name
    }

    fn clone_box(&self) -> Box<dyn AnalysisResult> {
        Box::new(self.clone())
    }
}

/// A requirement that a pass has for an analysis.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PassRequirement {
    /// Name of the required analysis
    pub analysis_name: String,
    /// If true, the analysis must be available (hard requirement).
    /// If false, the analysis is optional and may not be present.
    pub required: bool,
}

impl PassRequirement {
    /// Create a required analysis requirement.
    pub fn required(name: &str) -> Self {
        Self {
            analysis_name: name.to_string(),
            required: true,
        }
    }

    /// Create an optional analysis requirement.
    pub fn optional(name: &str) -> Self {
        Self {
            analysis_name: name.to_string(),
            required: false,
        }
    }
}

/// Scheduling timing for a pass within the pipeline.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PassTiming {
    /// Run before standard optimization
    Early,
    /// Standard optimization timing
    Standard,
    /// Run after standard optimization
    Late,
}

/// Metadata about a registered pass.
#[derive(Debug, Clone)]
pub struct PassInfo {
    /// Pass name (used for lookup)
    pub name: String,
    /// Human-readable description
    pub description: String,
    /// When in the pipeline this pass should run
    pub timing: PassTiming,
    /// Whether this pass is an analysis pass
    pub is_analysis: bool,
    /// Whether this pass transforms the IR
    pub is_transform: bool,
    /// Names of analyses this pass requires
    pub requires: Vec<String>,
    /// Names of analyses this pass invalidates
    pub invalidates: Vec<String>,
    /// Names of analyses this pass preserves
    pub preserves: Vec<String>,
    /// Optimization levels where this pass is active
    pub opt_levels: Vec<OptimizationLevel>,
}

impl PassInfo {
    /// Create a new pass info entry.
    pub fn new(name: &str, description: &str) -> Self {
        Self {
            name: name.to_string(),
            description: description.to_string(),
            timing: PassTiming::Standard,
            is_analysis: false,
            is_transform: false,
            requires: Vec::new(),
            invalidates: Vec::new(),
            preserves: Vec::new(),
            opt_levels: vec![
                OptimizationLevel::O1,
                OptimizationLevel::O2,
                OptimizationLevel::O3,
                OptimizationLevel::Os,
                OptimizationLevel::Oz,
            ],
        }
    }

    /// Set this pass as an analysis pass.
    pub fn set_analysis(mut self) -> Self {
        self.is_analysis = true;
        self
    }

    /// Set this pass as a transform pass.
    pub fn set_transform(mut self) -> Self {
        self.is_transform = true;
        self
    }

    /// Add a required analysis.
    pub fn add_required(mut self, analysis: &str) -> Self {
        self.requires.push(analysis.to_string());
        self
    }

    /// Add an invalidated analysis.
    pub fn add_invalidated(mut self, analysis: &str) -> Self {
        self.invalidates.push(analysis.to_string());
        self
    }

    /// Add a preserved analysis.
    pub fn add_preserved(mut self, analysis: &str) -> Self {
        self.preserves.push(analysis.to_string());
        self
    }

    /// Set the pass timing.
    pub fn with_timing(mut self, timing: PassTiming) -> Self {
        self.timing = timing;
        self
    }

    /// Restrict this pass to specific optimization levels.
    pub fn with_opt_levels(mut self, levels: Vec<OptimizationLevel>) -> Self {
        self.opt_levels = levels;
        self
    }
}

// ============================================================================
// PassRegistry — registration and pipeline construction
// ============================================================================

/// Registry of all available passes and their metadata.
#[derive(Debug, Clone)]
pub struct PassRegistry {
    /// All registered passes, keyed by name
    pub passes: HashMap<String, PassInfo>,
    /// Default pipeline order
    pub order: Vec<String>,
}

impl PassRegistry {
    /// Create a new empty pass registry.
    pub fn new() -> Self {
        Self {
            passes: HashMap::new(),
            order: Vec::new(),
        }
    }

    /// Register a pass with its metadata.
    pub fn register(&mut self, info: PassInfo) {
        let name = info.name.clone();
        if !self.passes.contains_key(&name) {
            self.order.push(name.clone());
        }
        self.passes.insert(name, info);
    }

    /// Register all default passes that come with the framework.
    pub fn register_default_passes(&mut self) {
        // Analysis passes
        self.register(
            PassInfo::new("domtree", "Dominator Tree Construction")
                .set_analysis()
                .with_timing(PassTiming::Early),
        );
        self.register(
            PassInfo::new("loops", "Natural Loop Info")
                .set_analysis()
                .with_timing(PassTiming::Early)
                .add_required("domtree"),
        );
        self.register(
            PassInfo::new("callgraph", "Call Graph Construction")
                .set_analysis()
                .with_timing(PassTiming::Early),
        );
        self.register(
            PassInfo::new("scalar-evolution", "Scalar Evolution Analysis")
                .set_analysis()
                .with_timing(PassTiming::Standard)
                .add_required("loops"),
        );

        // Transform passes
        self.register(
            PassInfo::new("dce", "Dead Code Elimination")
                .set_transform()
                .with_timing(PassTiming::Early)
                .add_preserved("domtree"),
        );
        self.register(
            PassInfo::new("instcombine", "Instruction Combining")
                .set_transform()
                .with_timing(PassTiming::Standard)
                .add_required("domtree")
                .add_invalidated("loops"),
        );
        self.register(
            PassInfo::new("simplifycfg", "Simplify the CFG")
                .set_transform()
                .with_timing(PassTiming::Early)
                .add_invalidated("domtree")
                .add_invalidated("loops"),
        );
        self.register(
            PassInfo::new("mem2reg", "Promote Memory to Register")
                .set_transform()
                .with_timing(PassTiming::Standard)
                .add_invalidated("domtree")
                .add_invalidated("loops"),
        );
        self.register(
            PassInfo::new("gvn", "Global Value Numbering")
                .set_transform()
                .with_timing(PassTiming::Standard)
                .add_required("domtree")
                .add_invalidated("loops"),
        );
        self.register(
            PassInfo::new("inline", "Function Inlining")
                .set_transform()
                .with_timing(PassTiming::Standard)
                .add_required("callgraph")
                .add_invalidated("domtree")
                .add_invalidated("loops"),
        );
        self.register(
            PassInfo::new("licm", "Loop Invariant Code Motion")
                .set_transform()
                .with_timing(PassTiming::Standard)
                .add_required("loops"),
        );
        self.register(
            PassInfo::new("loop-unroll", "Loop Unrolling")
                .set_transform()
                .with_timing(PassTiming::Late)
                .add_required("loops")
                .add_required("scalar-evolution"),
        );
        self.register(
            PassInfo::new("loop-rotate", "Loop Rotation")
                .set_transform()
                .with_timing(PassTiming::Standard)
                .add_required("loops"),
        );
        self.register(
            PassInfo::new("tailcallelim", "Tail Call Elimination")
                .set_transform()
                .with_timing(PassTiming::Late)
                .add_required("callgraph"),
        );
        self.register(
            PassInfo::new("reassociate", "Reassociation")
                .set_transform()
                .with_timing(PassTiming::Standard),
        );
        self.register(
            PassInfo::new("early-cse", "Early CSE")
                .set_transform()
                .with_timing(PassTiming::Early)
                .add_preserved("domtree"),
        );
    }

    /// Get pass info by name.
    pub fn get(&self, name: &str) -> Option<&PassInfo> {
        self.passes.get(name)
    }

    /// Check if a pass is registered.
    pub fn has(&self, name: &str) -> bool {
        self.passes.contains_key(name)
    }

    /// Get the default pipeline of pass names for a given optimization level.
    pub fn get_pipeline(&self, level: OptimizationLevel) -> Vec<String> {
        let mut pipeline: Vec<&PassInfo> = self
            .passes
            .values()
            .filter(|info| info.is_transform && info.opt_levels.contains(&level))
            .collect();

        // Sort by timing: Early first, then Standard, then Late
        pipeline.sort_by_key(|info| match info.timing {
            PassTiming::Early => 0,
            PassTiming::Standard => 1,
            PassTiming::Late => 2,
        });

        pipeline.iter().map(|info| info.name.clone()).collect()
    }

    /// Get the list of analyses required by the given pass names.
    pub fn collect_requirements(&self, pass_names: &[String]) -> Vec<String> {
        let mut reqs = Vec::new();
        for name in pass_names {
            if let Some(info) = self.passes.get(name) {
                for req in &info.requires {
                    if !reqs.contains(req) {
                        reqs.push(req.clone());
                    }
                }
            }
        }
        reqs
    }

    /// Validate that all required analyses for a pipeline are available.
    /// Returns a list of missing required analyses.
    pub fn validate_pipeline(&self, pipeline: &[String]) -> Vec<String> {
        let mut missing = Vec::new();
        let mut available: HashSet<String> = self
            .passes
            .values()
            .filter(|info| info.is_analysis)
            .map(|info| info.name.clone())
            .collect();

        // Also consider analyses provided by the passes themselves
        for name in pipeline {
            if self.passes.contains_key(name) {
                available.insert(name.clone());
            }
        }

        for name in pipeline {
            if let Some(info) = self.passes.get(name) {
                for req in &info.requires {
                    if !available.contains(req) && !missing.contains(req) {
                        missing.push(req.clone());
                    }
                }
            }
        }
        missing
    }

    /// Iterate over all registered passes.
    pub fn iter(&self) -> impl Iterator<Item = &PassInfo> {
        self.passes.values()
    }

    /// Return the number of registered passes.
    pub fn len(&self) -> usize {
        self.passes.len()
    }

    /// Return true if no passes are registered.
    pub fn is_empty(&self) -> bool {
        self.passes.is_empty()
    }

    /// Remove a pass from the registry.
    pub fn remove(&mut self, name: &str) -> Option<PassInfo> {
        self.order.retain(|n| n != name);
        self.passes.remove(name)
    }

    /// Clear all registered passes.
    pub fn clear(&mut self) {
        self.passes.clear();
        self.order.clear();
    }
}

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

// ============================================================================
// TransformPass — unified pass interface
// ============================================================================

/// A unified pass interface that works with both module-level and
/// function-level transformations. This is the "new pass manager" style
/// interface that LLVM uses in its current pass manager.
pub trait TransformPass: Send + Sync {
    /// Return the pass name.
    fn name(&self) -> &str;

    /// Run this pass on a module. Returns true if the module was modified.
    fn run_on_module(&mut self, _module: &mut Module, _am: &mut AnalysisManager) -> bool {
        false
    }

    /// Run this pass on a function. Returns true if the function was modified.
    fn run_on_function(&mut self, _func: &ValueRef, _am: &mut AnalysisManager) -> bool {
        false
    }

    /// Return the analyses this pass requires.
    fn get_requirements(&self) -> Vec<PassRequirement> {
        Vec::new()
    }

    /// Return the names of analyses this pass preserves.
    fn get_preserved_analyses(&self) -> Vec<String> {
        Vec::new()
    }

    /// Return the names of analyses this pass invalidates.
    fn get_invalidated_analyses(&self) -> Vec<String> {
        Vec::new()
    }

    /// Returns true if this pass is a module-level pass.
    fn is_module_pass(&self) -> bool {
        false
    }

    /// Returns true if this pass is a function-level pass.
    fn is_function_pass(&self) -> bool {
        true
    }
}

// ============================================================================
// Pass Instrumentation — Callbacks for Before/After Pass Runs
// ============================================================================

/// Callbacks invoked by the pass manager before and after each pass runs.
/// Allows external tools to observe, time, and control pass execution.
#[derive(Default)]
pub struct PassInstrumentationCallbacks {
    /// Called before a pass runs on a module.
    before_pass_module: Vec<Box<dyn Fn(&str, &Module) + Send + Sync>>,
    /// Called after a pass runs on a module.
    after_pass_module: Vec<Box<dyn Fn(&str, &Module, bool) + Send + Sync>>,
    /// Called before a pass runs on a function.
    before_pass_function: Vec<Box<dyn Fn(&str, &ValueRef) + Send + Sync>>,
    /// Called after a pass runs on a function.
    after_pass_function: Vec<Box<dyn Fn(&str, &ValueRef, bool) + Send + Sync>>,
    /// Called when a pass is skipped (e.g., by bisection).
    pass_skipped: Vec<Box<dyn Fn(&str) + Send + Sync>>,
    /// Called when a pass starts analysis computation.
    before_analysis: Vec<Box<dyn Fn(&str, &str) + Send + Sync>>,
    /// Called when a pass finishes analysis computation.
    after_analysis: Vec<Box<dyn Fn(&str, &str) + Send + Sync>>,
}

impl PassInstrumentationCallbacks {
    /// Create a new empty callbacks container.
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a callback for before-pass-on-module events.
    pub fn register_before_pass_module<F>(&mut self, callback: F)
    where
        F: Fn(&str, &Module) + Send + Sync + 'static,
    {
        self.before_pass_module.push(Box::new(callback));
    }

    /// Register a callback for after-pass-on-module events.
    pub fn register_after_pass_module<F>(&mut self, callback: F)
    where
        F: Fn(&str, &Module, bool) + Send + Sync + 'static,
    {
        self.after_pass_module.push(Box::new(callback));
    }

    /// Register a callback for before-pass-on-function events.
    pub fn register_before_pass_function<F>(&mut self, callback: F)
    where
        F: Fn(&str, &ValueRef) + Send + Sync + 'static,
    {
        self.before_pass_function.push(Box::new(callback));
    }

    /// Register a callback for after-pass-on-function events.
    pub fn register_after_pass_function<F>(&mut self, callback: F)
    where
        F: Fn(&str, &ValueRef, bool) + Send + Sync + 'static,
    {
        self.after_pass_function.push(Box::new(callback));
    }

    /// Register a callback for pass-skipped events.
    pub fn register_pass_skipped<F>(&mut self, callback: F)
    where
        F: Fn(&str) + Send + Sync + 'static,
    {
        self.pass_skipped.push(Box::new(callback));
    }

    /// Register a callback for before-analysis events.
    pub fn register_before_analysis<F>(&mut self, callback: F)
    where
        F: Fn(&str, &str) + Send + Sync + 'static,
    {
        self.before_analysis.push(Box::new(callback));
    }

    /// Register a callback for after-analysis events.
    pub fn register_after_analysis<F>(&mut self, callback: F)
    where
        F: Fn(&str, &str) + Send + Sync + 'static,
    {
        self.after_analysis.push(Box::new(callback));
    }

    /// Invoke all before-pass-on-module callbacks.
    pub fn run_before_pass_module(&self, pass_name: &str, module: &Module) {
        for cb in &self.before_pass_module {
            cb(pass_name, module);
        }
    }

    /// Invoke all after-pass-on-module callbacks.
    pub fn run_after_pass_module(&self, pass_name: &str, module: &Module, changed: bool) {
        for cb in &self.after_pass_module {
            cb(pass_name, module, changed);
        }
    }

    /// Invoke all before-pass-on-function callbacks.
    pub fn run_before_pass_function(&self, pass_name: &str, func: &ValueRef) {
        for cb in &self.before_pass_function {
            cb(pass_name, func);
        }
    }

    /// Invoke all after-pass-on-function callbacks.
    pub fn run_after_pass_function(&self, pass_name: &str, func: &ValueRef, changed: bool) {
        for cb in &self.after_pass_function {
            cb(pass_name, func, changed);
        }
    }

    /// Invoke all pass-skipped callbacks.
    pub fn run_pass_skipped(&self, pass_name: &str) {
        for cb in &self.pass_skipped {
            cb(pass_name);
        }
    }

    /// Invoke all before-analysis callbacks.
    pub fn run_before_analysis(&self, pass_name: &str, analysis_name: &str) {
        for cb in &self.before_analysis {
            cb(pass_name, analysis_name);
        }
    }

    /// Invoke all after-analysis callbacks.
    pub fn run_after_analysis(&self, pass_name: &str, analysis_name: &str) {
        for cb in &self.after_analysis {
            cb(pass_name, analysis_name);
        }
    }

    /// Clear all registered callbacks.
    pub fn clear(&mut self) {
        self.before_pass_module.clear();
        self.after_pass_module.clear();
        self.before_pass_function.clear();
        self.after_pass_function.clear();
        self.pass_skipped.clear();
        self.before_analysis.clear();
        self.after_analysis.clear();
    }
}

impl std::fmt::Debug for PassInstrumentationCallbacks {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PassInstrumentationCallbacks")
            .field("before_pass_module_count", &self.before_pass_module.len())
            .field("after_pass_module_count", &self.after_pass_module.len())
            .field(
                "before_pass_function_count",
                &self.before_pass_function.len(),
            )
            .field("after_pass_function_count", &self.after_pass_function.len())
            .field("pass_skipped_count", &self.pass_skipped.len())
            .field("before_analysis_count", &self.before_analysis.len())
            .field("after_analysis_count", &self.after_analysis.len())
            .finish()
    }
}

// ============================================================================
// TimePassesHandler — Pass Timing Instrumentation
// ============================================================================

/// Records timing information for each pass execution.
/// Collected timing data can be reported at the end of compilation
/// to help identify slow passes.
#[derive(Debug, Clone)]
pub struct TimePassesHandler {
    /// Whether timing is enabled.
    pub enabled: bool,
    /// Per-pass timing records: pass_name -> (total_ns, count).
    timings: HashMap<String, (u128, usize)>,
    /// Start time of the currently running pass (if any).
    current_pass_start: Option<(String, std::time::Instant)>,
    /// Whether to report timings per-function instead of per-pass.
    pub per_function: bool,
}

impl TimePassesHandler {
    /// Create a new TimePassesHandler.
    pub fn new(enabled: bool) -> Self {
        Self {
            enabled,
            timings: HashMap::new(),
            current_pass_start: None,
            per_function: false,
        }
    }

    /// Start timing a pass.
    pub fn start_pass(&mut self, pass_name: &str) {
        if !self.enabled {
            return;
        }
        self.current_pass_start = Some((pass_name.to_string(), std::time::Instant::now()));
    }

    /// Stop timing the current pass and record elapsed time.
    pub fn stop_pass(&mut self) {
        if !self.enabled {
            return;
        }
        if let Some((name, start)) = self.current_pass_start.take() {
            let elapsed = start.elapsed().as_nanos();
            let entry = self.timings.entry(name).or_insert((0, 0));
            entry.0 += elapsed;
            entry.1 += 1;
        }
    }

    /// Get the total time for a specific pass in nanoseconds.
    pub fn time_for_pass(&self, pass_name: &str) -> Option<u128> {
        self.timings.get(pass_name).map(|(t, _)| *t)
    }

    /// Get the number of times a pass was run.
    pub fn count_for_pass(&self, pass_name: &str) -> Option<usize> {
        self.timings.get(pass_name).map(|(_, c)| *c)
    }

    /// Get all timing records.
    pub fn all_timings(&self) -> &HashMap<String, (u128, usize)> {
        &self.timings
    }

    /// Generate a human-readable timing report.
    pub fn report(&self) -> String {
        if !self.enabled {
            return "TimePassesHandler is disabled.".to_string();
        }

        let mut entries: Vec<(&String, &(u128, usize))> = self.timings.iter().collect();
        entries.sort_by(|a, b| b.1 .0.cmp(&a.1 .0));

        let mut report = String::from("=== Pass Timing Report ===\n");
        report.push_str(&format!(
            "{:<30} {:>12} {:>8}\n",
            "Pass Name", "Time (ms)", "Count"
        ));
        report.push_str(&"-".repeat(52));
        report.push('\n');

        for (name, (total_ns, count)) in &entries {
            let ms = *total_ns as f64 / 1_000_000.0;
            report.push_str(&format!("{:<30} {:>12.3} {:>8}\n", name, ms, count));
        }

        report
    }

    /// Reset all timing data.
    pub fn reset(&mut self) {
        self.timings.clear();
        self.current_pass_start = None;
    }
}

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

// ============================================================================
// PassStatistics — Collect Pass Run Statistics
// ============================================================================

/// Collects and reports statistics for pass execution.
/// Similar to LLVM's -stats option, this tracks how many
/// transformations each pass performed.
#[derive(Debug, Clone, Default)]
pub struct PassStatistics {
    /// Per-pass statistics: pass_name -> StatRecord.
    stats: HashMap<String, StatRecord>,
    /// Whether statistics collection is enabled.
    pub enabled: bool,
}

/// Statistics record for a single pass.
#[derive(Debug, Clone, Default)]
pub struct StatRecord {
    /// Number of times the pass was run.
    pub runs: usize,
    /// Number of times the pass changed the IR.
    pub changes: usize,
    /// Number of functions processed.
    pub functions: usize,
    /// Number of instructions eliminated.
    pub insts_eliminated: usize,
    /// Number of basic blocks modified.
    pub blocks_modified: usize,
    /// Total time spent in this pass (nanoseconds).
    pub total_time_ns: u128,
}

impl PassStatistics {
    /// Create a new PassStatistics collector.
    pub fn new(enabled: bool) -> Self {
        Self {
            stats: HashMap::new(),
            enabled,
        }
    }

    /// Record a pass run.
    pub fn record_run(&mut self, pass_name: &str, changed: bool) {
        if !self.enabled {
            return;
        }
        let entry = self.stats.entry(pass_name.to_string()).or_default();
        entry.runs += 1;
        if changed {
            entry.changes += 1;
        }
    }

    /// Record function processing.
    pub fn record_function(&mut self, pass_name: &str) {
        if !self.enabled {
            return;
        }
        let entry = self.stats.entry(pass_name.to_string()).or_default();
        entry.functions += 1;
    }

    /// Record instruction elimination.
    pub fn record_inst_eliminated(&mut self, pass_name: &str, count: usize) {
        if !self.enabled {
            return;
        }
        let entry = self.stats.entry(pass_name.to_string()).or_default();
        entry.insts_eliminated += count;
    }

    /// Record block modification.
    pub fn record_block_modified(&mut self, pass_name: &str) {
        if !self.enabled {
            return;
        }
        let entry = self.stats.entry(pass_name.to_string()).or_default();
        entry.blocks_modified += 1;
    }

    /// Set timing for a pass.
    pub fn set_timing(&mut self, pass_name: &str, time_ns: u128) {
        if !self.enabled {
            return;
        }
        let entry = self.stats.entry(pass_name.to_string()).or_default();
        entry.total_time_ns = time_ns;
    }

    /// Get statistics for a specific pass.
    pub fn get(&self, pass_name: &str) -> Option<&StatRecord> {
        self.stats.get(pass_name)
    }

    /// Generate a human-readable statistics report.
    pub fn report(&self) -> String {
        if !self.enabled {
            return "PassStatistics is disabled.".to_string();
        }

        let mut entries: Vec<(&String, &StatRecord)> = self.stats.iter().collect();
        entries.sort_by(|a, b| b.1.runs.cmp(&a.1.runs));

        let mut report = String::from("=== Pass Statistics ===\n");
        report.push_str(&format!(
            "{:<25} {:>6} {:>7} {:>7} {:>7} {:>7}\n",
            "Pass", "Runs", "Changed", "Funcs", "InstElim", "Blocks"
        ));
        report.push_str(&"-".repeat(68));
        report.push('\n');

        for (name, rec) in &entries {
            report.push_str(&format!(
                "{:<25} {:>6} {:>7} {:>7} {:>7} {:>7}\n",
                name,
                rec.runs,
                rec.changes,
                rec.functions,
                rec.insts_eliminated,
                rec.blocks_modified
            ));
        }

        report
    }

    /// Reset all statistics.
    pub fn reset(&mut self) {
        self.stats.clear();
    }

    /// Merge statistics from another collector.
    pub fn merge(&mut self, other: &PassStatistics) {
        for (name, rec) in &other.stats {
            let entry = self.stats.entry(name.clone()).or_default();
            entry.runs += rec.runs;
            entry.changes += rec.changes;
            entry.functions += rec.functions;
            entry.insts_eliminated += rec.insts_eliminated;
            entry.blocks_modified += rec.blocks_modified;
            entry.total_time_ns += rec.total_time_ns;
        }
    }
}

// ============================================================================
// OptBisect — Optimization Bisection for Debugging
// ============================================================================

/// Optimization bisection: selectively disable passes to find which
/// pass introduces a miscompilation or performance regression.
///
/// Works by assigning each pass a unique index and only running
/// passes with indices below or above a threshold.
#[derive(Debug, Clone)]
pub struct OptBisect {
    /// Whether bisection is enabled.
    pub enabled: bool,
    /// The current bisection limit: passes with index < limit run normally.
    pub limit: usize,
    /// The current pass index counter.
    next_index: usize,
    /// Mapping from pass name to its assigned index.
    pass_indices: HashMap<String, usize>,
    /// Description of what the bisection is looking for.
    pub description: String,
}

impl OptBisect {
    /// Create a new OptBisect.
    pub fn new() -> Self {
        Self {
            enabled: false,
            limit: usize::MAX,
            next_index: 0,
            pass_indices: HashMap::new(),
            description: String::new(),
        }
    }

    /// Enable bisection with the given limit.
    pub fn enable(&mut self, limit: usize, description: &str) {
        self.enabled = true;
        self.limit = limit;
        self.description = description.to_string();
    }

    /// Disable bisection.
    pub fn disable(&mut self) {
        self.enabled = false;
        self.limit = usize::MAX;
    }

    /// Check whether a pass should be skipped.
    /// Returns true if the pass should be skipped (not run).
    pub fn should_skip(&mut self, pass_name: &str) -> bool {
        if !self.enabled {
            return false;
        }

        let index = *self
            .pass_indices
            .entry(pass_name.to_string())
            .or_insert_with(|| {
                let idx = self.next_index;
                self.next_index += 1;
                idx
            });

        index >= self.limit
    }

    /// Get the assigned index for a pass.
    pub fn pass_index(&self, pass_name: &str) -> Option<usize> {
        self.pass_indices.get(pass_name).copied()
    }

    /// Get the number of passes indexed so far.
    pub fn pass_count(&self) -> usize {
        self.next_index
    }

    /// Reset all state.
    pub fn reset(&mut self) {
        self.enabled = false;
        self.limit = usize::MAX;
        self.next_index = 0;
        self.pass_indices.clear();
        self.description.clear();
    }

    /// Generate a description of the current bisect state.
    pub fn status(&self) -> String {
        if !self.enabled {
            return "OptBisect is disabled.".to_string();
        }
        format!(
            "OptBisect: limit={} passes_indexed={} description='{}'",
            self.limit, self.next_index, self.description,
        )
    }
}

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

// ============================================================================
// StandardInstrumentations — All Standard Callbacks
// ============================================================================

/// Bundles all standard instrumentation together:
/// - TimePassesHandler for -time-passes
/// - PassStatistics for -stats
/// - OptBisect for -opt-bisect-limit
/// - PassInstrumentationCallbacks for custom callbacks
#[derive(Default)]
pub struct StandardInstrumentations {
    /// Pass timing handler.
    pub time_passes: TimePassesHandler,
    /// Pass statistics collector.
    pub statistics: PassStatistics,
    /// Optimization bisector.
    pub opt_bisect: OptBisect,
    /// Custom callbacks.
    pub callbacks: PassInstrumentationCallbacks,
    /// Whether to print pass names as they run (for -debug-pass).
    pub debug_passes: bool,
    /// Whether to verify the IR after each pass.
    pub verify_each: bool,
}

impl StandardInstrumentations {
    /// Create a new StandardInstrumentations bundle.
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable timing with -time-passes.
    pub fn enable_timing(&mut self) {
        self.time_passes.enabled = true;
    }

    /// Enable statistics with -stats.
    pub fn enable_statistics(&mut self) {
        self.statistics.enabled = true;
    }

    /// Enable bisection with -opt-bisect-limit=N.
    pub fn enable_bisect(&mut self, limit: usize, description: &str) {
        self.opt_bisect.enable(limit, description);
    }

    /// Enable debug pass printing.
    pub fn enable_debug_passes(&mut self) {
        self.debug_passes = true;
    }

    /// Enable IR verification after each pass.
    pub fn enable_verify_each(&mut self) {
        self.verify_each = true;
    }

    /// Called before a pass runs on a module.
    pub fn before_pass_module(&mut self, pass_name: &str, module: &Module) {
        if self.debug_passes {
            eprintln!("Running pass '{}' on module '{}'", pass_name, module.name);
        }

        self.callbacks.run_before_pass_module(pass_name, module);

        if self.time_passes.enabled {
            self.time_passes.start_pass(pass_name);
        }

        if self.opt_bisect.enabled && self.opt_bisect.should_skip(pass_name) {
            self.callbacks.run_pass_skipped(pass_name);
            if self.debug_passes {
                eprintln!("  Skipping (bisect limit {})", self.opt_bisect.limit);
            }
        }
    }

    /// Called after a pass runs on a module.
    pub fn after_pass_module(&mut self, pass_name: &str, module: &Module, changed: bool) {
        if self.time_passes.enabled {
            self.time_passes.stop_pass();
        }

        self.statistics.record_run(pass_name, changed);
        self.callbacks
            .run_after_pass_module(pass_name, module, changed);

        if self.debug_passes && changed {
            eprintln!("  Pass '{}' changed the module.", pass_name);
        }
    }

    /// Called before a pass runs on a function.
    pub fn before_pass_function(&mut self, pass_name: &str, func: &ValueRef) {
        if self.debug_passes {
            let f = func.borrow();
            eprintln!("Running pass '{}' on function '{}'", pass_name, f.name);
        }

        self.callbacks.run_before_pass_function(pass_name, func);
        self.statistics.record_function(pass_name);

        if self.time_passes.enabled {
            self.time_passes.start_pass(pass_name);
        }
    }

    /// Called after a pass runs on a function.
    pub fn after_pass_function(&mut self, pass_name: &str, func: &ValueRef, changed: bool) {
        if self.time_passes.enabled {
            self.time_passes.stop_pass();
        }

        self.statistics.record_run(pass_name, changed);
        self.callbacks
            .run_after_pass_function(pass_name, func, changed);

        if self.debug_passes && changed {
            let f = func.borrow();
            eprintln!("  Pass '{}' changed function '{}'.", pass_name, f.name);
        }
    }

    /// Generate a combined report of timing and statistics.
    pub fn report(&self) -> String {
        let mut report = String::new();
        report.push_str(&self.time_passes.report());
        report.push('\n');
        report.push_str(&self.statistics.report());
        report.push('\n');
        report.push_str(&self.opt_bisect.status());
        report
    }

    /// Reset all instrumentation state.
    pub fn reset(&mut self) {
        self.time_passes.reset();
        self.statistics.reset();
        self.opt_bisect.reset();
        self.callbacks.clear();
    }
}

impl std::fmt::Debug for StandardInstrumentations {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StandardInstrumentations")
            .field("time_passes_enabled", &self.time_passes.enabled)
            .field("statistics_enabled", &self.statistics.enabled)
            .field("opt_bisect_enabled", &self.opt_bisect.enabled)
            .field("debug_passes", &self.debug_passes)
            .field("verify_each", &self.verify_each)
            .finish()
    }
}

// ============================================================================
// InstrumentedPassManager — PassManager with Instrumentation
// ============================================================================

/// A pass manager that wraps standard pass execution with instrumentation
/// callbacks. This is the primary interface for running passes with
/// timing, statistics, and bisection support.
pub struct InstrumentedPassManager {
    /// The underlying pass manager.
    pass_manager: PassManager,
    /// Standard instrumentation bundle.
    pub instrumentation: StandardInstrumentations,
    /// Track which passes are function vs module level.
    function_pass_names: Vec<String>,
    module_pass_names: Vec<String>,
}

impl InstrumentedPassManager {
    /// Create a new instrumented pass manager.
    pub fn new() -> Self {
        Self {
            pass_manager: PassManager::new(),
            instrumentation: StandardInstrumentations::new(),
            function_pass_names: Vec::new(),
            module_pass_names: Vec::new(),
        }
    }

    /// Add a function pass.
    pub fn add_function_pass(&mut self, pass: Box<dyn FunctionPass>) {
        let name = pass.name().to_string();
        self.function_pass_names.push(name);
        self.pass_manager.add_function_pass(pass);
    }

    /// Add a module pass.
    pub fn add_module_pass(&mut self, pass: Box<dyn ModulePass>) {
        let name = pass.name().to_string();
        self.module_pass_names.push(name);
        self.pass_manager.add_module_pass(pass);
    }

    /// Get the underlying pass manager.
    pub fn pass_manager(&self) -> &PassManager {
        &self.pass_manager
    }

    /// Get mutable access to the pass manager.
    pub fn pass_manager_mut(&mut self) -> &mut PassManager {
        &mut self.pass_manager
    }

    /// Run all passes with instrumentation.
    /// Returns true if any pass changed the module.
    pub fn run(&mut self, module: &mut Module) -> bool {
        let mut any_change = false;

        // Since we can't access the internal pass list, we use the names
        // we tracked during add_function_pass / add_module_pass.
        // Run module passes.
        for name in &self.module_pass_names.clone() {
            if self.instrumentation.opt_bisect.should_skip(name) {
                self.instrumentation.callbacks.run_pass_skipped(name);
                continue;
            }

            self.instrumentation.before_pass_module(name, module);

            let changed = self.pass_manager.run_pipeline(module, &[name.clone()]);
            if changed {
                any_change = true;
            }

            self.instrumentation
                .after_pass_module(name, module, changed);
        }

        // Run function passes.
        for name in &self.function_pass_names.clone() {
            if self.instrumentation.opt_bisect.should_skip(name) {
                self.instrumentation.callbacks.run_pass_skipped(name);
                continue;
            }

            let functions: Vec<ValueRef> = module.functions.clone();
            for func in &functions {
                if func.borrow().subclass == llvm_native_core::value::SubclassKind::Function {
                    self.instrumentation.before_pass_function(name, func);

                    let changed = self.pass_manager.run_pipeline(module, &[name.clone()]);
                    if changed {
                        any_change = true;
                    }

                    self.instrumentation
                        .after_pass_function(name, func, changed);
                }
            }
        }

        any_change
    }

    /// Run with pipeline specification.
    pub fn run_pipeline(&mut self, module: &mut Module, pipeline: &[String]) -> bool {
        let mut any_change = false;

        for pass_name in pipeline {
            if self.instrumentation.opt_bisect.should_skip(pass_name) {
                self.instrumentation.callbacks.run_pass_skipped(pass_name);
                continue;
            }

            self.instrumentation.before_pass_module(pass_name, module);

            let changed = self.pass_manager.run_pipeline(module, &[pass_name.clone()]);
            if changed {
                any_change = true;
            }

            self.instrumentation
                .after_pass_module(pass_name, module, changed);
        }

        any_change
    }

    /// Reset all state including instrumentation.
    pub fn reset(&mut self) {
        self.pass_manager = PassManager::new();
        self.function_pass_names.clear();
        self.module_pass_names.clear();
        self.instrumentation.reset();
    }
}

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

// ============================================================================
// PassManager Extension: Pipeline Builder with Instrumentation
// ============================================================================

/// Builder for constructing an instrumented pass pipeline.
/// Provides a fluent API for adding passes and configuring instrumentation.
pub struct PassPipelineBuilder {
    /// The instrumented pass manager being built.
    manager: InstrumentedPassManager,
    /// Optimization level for the pipeline.
    opt_level: OptimizationLevel,
}

impl PassPipelineBuilder {
    /// Create a new pipeline builder at the given optimization level.
    pub fn new(opt_level: OptimizationLevel) -> Self {
        Self {
            manager: InstrumentedPassManager::new(),
            opt_level,
        }
    }

    /// Enable timing instrumentation.
    pub fn with_timing(mut self) -> Self {
        self.manager.instrumentation.enable_timing();
        self
    }

    /// Enable statistics instrumentation.
    pub fn with_statistics(mut self) -> Self {
        self.manager.instrumentation.enable_statistics();
        self
    }

    /// Enable debug pass printing.
    pub fn with_debug_passes(mut self) -> Self {
        self.manager.instrumentation.enable_debug_passes();
        self
    }

    /// Enable IR verification after each pass.
    pub fn with_verify_each(mut self) -> Self {
        self.manager.instrumentation.enable_verify_each();
        self
    }

    /// Add a function pass by name from the registry.
    pub fn add_function_pass_by_name(mut self, name: &str, registry: &PassRegistry) -> Self {
        // In a real implementation, this would look up the pass by name
        // in the registry and instantiate it. For now, track the name.
        let _ = registry.get(name);
        self
    }

    /// Build the pipeline (return the instrumented pass manager).
    pub fn build(self) -> InstrumentedPassManager {
        self.manager
    }

    /// Get the optimization level.
    pub fn opt_level(&self) -> OptimizationLevel {
        self.opt_level
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use llvm_native_core::context::LLVMContext;
    use llvm_native_core::function;
    use llvm_native_core::instruction;
    use llvm_native_core::module::Module;

    /// A simple test pass that counts functions.
    struct TestPass;

    impl Pass for TestPass {
        fn name(&self) -> &'static str {
            "test-pass"
        }
    }

    impl FunctionPass for TestPass {
        fn run_on_function(&mut self, _func: &ValueRef, _am: &AnalysisManager) -> PassResult {
            PassResult::Unchanged
        }
    }

    #[test]
    fn test_pass_manager_create() {
        let mut pm = PassManager::new();
        pm.add_function_pass(Box::new(TestPass));

        let mut ctx = LLVMContext::new();
        let mut module = Module::new("test");
        module.set_target_triple("x86_64-unknown-linux-gnu");
        let f = function::new_function("main", ctx.i32(), &[]);
        module.add_function(f);

        let changed = pm.run(&mut module);
        assert!(!changed);
    }

    #[test]
    fn test_pass_manager_multiple_passes() {
        let mut pm = PassManager::new();
        pm.add_function_pass(Box::new(TestPass));
        pm.add_function_pass(Box::new(TestPass));
        pm.add_function_pass(Box::new(TestPass));

        let mut ctx = LLVMContext::new();
        let mut module = Module::new("test");
        module.set_target_triple("x86_64");
        let f = function::new_function("main", ctx.i32(), &[]);
        module.add_function(f);

        assert!(pm.run(&mut module) == false); // No changes expected
    }

    #[test]
    fn test_pass_manager_with_body() {
        let mut pm = PassManager::new();
        pm.add_function_pass(Box::new(TestPass));

        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let mut module = Module::new("test");
        module.set_target_triple("x86_64");
        let func = function::new_function("main", i32_ty, &[]);
        module.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let ret = instruction::ret_void();
        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(ret);

        let changed = pm.run(&mut module);
        assert!(!changed);
    }

    #[test]
    fn test_analysis_manager_cache() {
        let mut am = AnalysisManager::new();

        // Initially, no analysis cached
        assert!(am.get_analysis::<DominatorTree>().is_none());

        // Set and retrieve
        let mut ctx = LLVMContext::new();
        let func = function::new_function("test", ctx.i32(), &[]);
        let dt = DominatorTree::compute(&func);
        am.set_analysis(dt);
        assert!(am.get_analysis::<DominatorTree>().is_some());

        // Invalidate
        am.invalidate::<DominatorTree>();
        assert!(am.get_analysis::<DominatorTree>().is_none());
    }

    #[test]
    fn test_pass_manager_stats() {
        let mut pm = PassManager::new();
        pm.add_function_pass(Box::new(TestPass));

        let mut ctx = LLVMContext::new();
        let mut module = Module::new("test");
        module.set_target_triple("x86_64");
        let f = function::new_function("main", ctx.i32(), &[]);
        module.add_function(f);

        pm.run(&mut module);
        assert!(pm.analysis_manager.stats.contains_key("test-pass"));
    }

    #[test]
    fn test_module_pass_adapter() {
        struct CountingModulePass {
            count: usize,
        }

        impl Pass for CountingModulePass {
            fn name(&self) -> &'static str {
                "counting-module-pass"
            }
        }

        impl ModulePass for CountingModulePass {
            fn run_on_module(
                &mut self,
                _module: &mut Module,
                _am: &mut AnalysisManager,
            ) -> PassResult {
                self.count += 1;
                PassResult::Changed
            }
        }

        let mut pm = PassManager::new();
        pm.add_module_pass(Box::new(CountingModulePass { count: 0 }));

        let _ctx = LLVMContext::new();
        let mut module = Module::new("test");
        module.set_target_triple("x86_64");

        let changed = pm.run(&mut module);
        assert!(changed);
    }

    // ========================================================================
    // New tests for expanded functionality
    // ========================================================================

    // --- AnalysisResult / TypedAnalysis tests ---

    #[test]
    fn test_typed_analysis_create() {
        let analysis = TypedAnalysis::new(42i32, "my-analysis");
        assert_eq!(analysis.name(), "my-analysis");
        assert_eq!(analysis.value, 42);
        assert!(!analysis.invalidate_on("dce"));
    }

    #[test]
    fn test_typed_analysis_invalidation() {
        let analysis = TypedAnalysis::new(100u64, "loops")
            .add_invalidator("simplifycfg")
            .add_invalidator("inline");
        assert!(analysis.invalidate_on("simplifycfg"));
        assert!(analysis.invalidate_on("inline"));
        assert!(!analysis.invalidate_on("dce"));
    }

    #[test]
    fn test_analysis_manager_named() {
        let mut am = AnalysisManager::new();
        let analysis =
            TypedAnalysis::new(vec![1, 2, 3], "test-analysis").add_invalidator("destructive-pass");
        am.set_named_analysis("test", analysis);

        let retrieved = am.get_analysis_typed::<TypedAnalysis<Vec<i32>>>("test");
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().value, vec![1, 2, 3]);
    }

    #[test]
    fn test_analysis_manager_invalidate_by_pass() {
        let mut am = AnalysisManager::new();
        am.set_named_analysis(
            "loops",
            TypedAnalysis::new(1u32, "loops").add_invalidator("simplifycfg"),
        );
        am.set_named_analysis(
            "domtree",
            TypedAnalysis::new(2u32, "domtree").add_invalidator("simplifycfg"),
        );
        am.set_named_analysis(
            "callgraph",
            TypedAnalysis::new(3u32, "callgraph"), // no invalidators
        );

        am.invalidate_by_pass("simplifycfg");
        assert!(am.get_named_analysis("loops").is_none());
        assert!(am.get_named_analysis("domtree").is_none());
        assert!(am.get_named_analysis("callgraph").is_some());
    }

    #[test]
    fn test_analysis_manager_preserved() {
        let mut am = AnalysisManager::new();
        am.mark_preserved("domtree");
        assert!(am.is_preserved("domtree"));
        assert!(!am.is_preserved("loops"));
        am.clear_preserved();
        assert!(!am.is_preserved("domtree"));
    }

    // --- PassRequirement tests ---

    #[test]
    fn test_pass_requirement_required() {
        let req = PassRequirement::required("domtree");
        assert_eq!(req.analysis_name, "domtree");
        assert!(req.required);
    }

    #[test]
    fn test_pass_requirement_optional() {
        let req = PassRequirement::optional("loops");
        assert_eq!(req.analysis_name, "loops");
        assert!(!req.required);
    }

    // --- OptimizationLevel tests ---

    #[test]
    fn test_optimization_level_as_str() {
        assert_eq!(OptimizationLevel::O0.as_str(), "O0");
        assert_eq!(OptimizationLevel::O3.as_str(), "O3");
        assert_eq!(OptimizationLevel::Oz.as_str(), "Oz");
    }

    #[test]
    fn test_optimization_level_is_optimizing() {
        assert!(!OptimizationLevel::O0.is_optimizing());
        assert!(OptimizationLevel::O1.is_optimizing());
        assert!(OptimizationLevel::O2.is_optimizing());
    }

    #[test]
    fn test_optimization_level_is_aggressive() {
        assert!(!OptimizationLevel::O1.is_aggressive());
        assert!(OptimizationLevel::O2.is_aggressive());
        assert!(OptimizationLevel::O3.is_aggressive());
    }

    // --- PassInfo tests ---

    #[test]
    fn test_pass_info_create() {
        let info = PassInfo::new("dce", "Dead Code Elimination")
            .set_transform()
            .with_timing(PassTiming::Early)
            .add_preserved("domtree");
        assert_eq!(info.name, "dce");
        assert!(info.is_transform);
        assert!(!info.is_analysis);
        assert_eq!(info.timing, PassTiming::Early);
        assert!(info.preserves.contains(&"domtree".to_string()));
    }

    #[test]
    fn test_pass_info_analysis() {
        let info = PassInfo::new("domtree", "Dominator Tree").set_analysis();
        assert!(info.is_analysis);
        assert!(!info.is_transform);
    }

    // --- PassRegistry tests ---

    #[test]
    fn test_pass_registry_create() {
        let registry = PassRegistry::new();
        assert!(registry.is_empty());
        assert_eq!(registry.len(), 0);
    }

    #[test]
    fn test_pass_registry_register() {
        let mut registry = PassRegistry::new();
        registry.register(PassInfo::new("dce", "Dead Code Elimination"));
        assert_eq!(registry.len(), 1);
        assert!(registry.has("dce"));
        assert!(!registry.has("nonexistent"));
    }

    #[test]
    fn test_pass_registry_default_passes() {
        let mut registry = PassRegistry::new();
        registry.register_default_passes();
        assert!(registry.len() > 5);
        assert!(registry.has("dce"));
        assert!(registry.has("instcombine"));
        assert!(registry.has("domtree"));
    }

    #[test]
    fn test_pass_registry_get_pipeline() {
        let mut registry = PassRegistry::new();
        registry.register_default_passes();
        let pipeline = registry.get_pipeline(OptimizationLevel::O2);
        assert!(!pipeline.is_empty());
        // Early passes should come before standard
        assert!(pipeline.contains(&"dce".to_string()));
    }

    #[test]
    fn test_pass_registry_collect_requirements() {
        let mut registry = PassRegistry::new();
        registry.register_default_passes();
        let reqs = registry.collect_requirements(&["instcombine".to_string()]);
        assert!(reqs.contains(&"domtree".to_string()));
    }

    #[test]
    fn test_pass_registry_validate_pipeline() {
        let mut registry = PassRegistry::new();
        registry.register(
            PassInfo::new("my-pass", "A test pass")
                .set_transform()
                .add_required("domtree"),
        );
        registry.register(PassInfo::new("domtree", "Dominator Tree").set_analysis());

        let missing = registry.validate_pipeline(&["my-pass".to_string()]);
        assert!(missing.is_empty(), "domtree should be available");

        let missing2 =
            registry.validate_pipeline(&["my-pass".to_string(), "unknown-pass".to_string()]);
        // unknown-pass doesn't have requirements, so no extra missing
        assert!(missing2.is_empty());
    }

    #[test]
    fn test_pass_registry_remove() {
        let mut registry = PassRegistry::new();
        registry.register(PassInfo::new("dce", "DCE"));
        assert!(registry.has("dce"));
        let removed = registry.remove("dce");
        assert!(removed.is_some());
        assert!(!registry.has("dce"));
    }

    #[test]
    fn test_pass_registry_clear() {
        let mut registry = PassRegistry::new();
        registry.register_default_passes();
        assert!(!registry.is_empty());
        registry.clear();
        assert!(registry.is_empty());
    }

    // --- TransformPass tests ---

    struct CountingTransformPass {
        _count: usize,
    }

    impl TransformPass for CountingTransformPass {
        fn name(&self) -> &str {
            "counting-transform"
        }

        fn run_on_function(&mut self, _func: &ValueRef, _am: &mut AnalysisManager) -> bool {
            // This will never actually be called in unit tests without IR
            false
        }

        fn get_requirements(&self) -> Vec<PassRequirement> {
            vec![PassRequirement::required("domtree")]
        }

        fn get_preserved_analyses(&self) -> Vec<String> {
            vec!["callgraph".to_string()]
        }

        fn is_function_pass(&self) -> bool {
            true
        }
    }

    #[test]
    fn test_transform_pass_name() {
        let pass = CountingTransformPass { _count: 0 };
        assert_eq!(pass.name(), "counting-transform");
    }

    #[test]
    fn test_transform_pass_requirements() {
        let pass = CountingTransformPass { _count: 0 };
        let reqs = pass.get_requirements();
        assert_eq!(reqs.len(), 1);
        assert_eq!(reqs[0].analysis_name, "domtree");
        assert!(reqs[0].required);
    }

    #[test]
    fn test_transform_pass_preserved() {
        let pass = CountingTransformPass { _count: 0 };
        let preserved = pass.get_preserved_analyses();
        assert!(preserved.contains(&"callgraph".to_string()));
    }

    // --- PassManager new methods tests ---

    #[test]
    fn test_pass_manager_debug_flag() {
        let mut pm = PassManager::new();
        assert!(!pm.debug);
        pm.debug = true;
        assert!(pm.debug);
    }

    #[test]
    fn test_pass_manager_time_passes() {
        let mut pm = PassManager::new();
        pm.time_passes = true;
        pm.add_function_pass(Box::new(TestPass));

        let mut ctx = LLVMContext::new();
        let mut module = Module::new("test");
        module.set_target_triple("x86_64");
        let f = function::new_function("main", ctx.i32(), &[]);
        module.add_function(f);

        pm.run(&mut module);
        // Should have recorded timing even if it's 0
        assert_eq!(pm.pass_timings.len(), 1);
    }

    #[test]
    fn test_pass_manager_run_pipeline() {
        let mut pm = PassManager::new();
        pm.add_function_pass(Box::new(TestPass));

        let mut ctx = LLVMContext::new();
        let mut module = Module::new("test");
        module.set_target_triple("x86_64");
        let f = function::new_function("main", ctx.i32(), &[]);
        module.add_function(f);

        let changed = pm.run_pipeline(&mut module, &["test-pass".to_string()]);
        assert!(!changed);
    }

    #[test]
    fn test_pass_manager_analysis_manager_access() {
        let pm = PassManager::new();
        let _am = pm.analysis_manager();
        assert!(_am.stats.is_empty());
    }
}