llvm-native-core 0.1.5

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

use std::collections::{HashMap, VecDeque};

// ============================================================================
// MC Instruction (simplified for MCA)
// ============================================================================

/// A simplified machine instruction for MCA simulation.
#[derive(Debug, Clone)]
pub struct MCInst {
    /// The instruction mnemonic (e.g., "add", "mul", "ldr").
    pub mnemonic: String,
    /// Operand register IDs.
    pub operands: Vec<u32>,
    /// Estimated execution latency in cycles.
    pub latency: u32,
    /// Which execution port(s) this instruction can use (bitmask).
    pub ports: u32,
    /// Whether this instruction consumes multiple dispatch slots.
    pub micro_ops: u32,
    /// Whether this instruction writes a result register.
    pub writes_result: bool,
    /// The destination register, if any.
    pub dest_reg: Option<u32>,
    /// Source registers that must be ready before issue.
    pub source_regs: Vec<u32>,
}

// ============================================================================
// MCA Analysis Result
// ============================================================================

/// Result of the MCA simulation.
#[derive(Debug, Clone)]
pub struct MCAnalysisResult {
    /// Total cycles simulated.
    pub total_cycles: u64,
    /// Number of instructions in the input.
    pub instructions: usize,
    /// Instructions per cycle (throughput).
    pub ipc: f64,
    /// Number of dispatch stalls (no dispatch slot available).
    pub dispatch_stalls: usize,
    /// Number of issue stalls (operands not ready).
    pub issue_stalls: usize,
    /// Resource pressure: execution port → fraction of time utilized.
    pub resource_pressure: HashMap<String, f64>,
    /// Cycle-by-cycle timeline of events.
    pub timeline: Vec<TimelineEvent>,
}

// ============================================================================
// Timeline Event
// ============================================================================

/// A single event in the simulation timeline.
#[derive(Debug, Clone)]
pub struct TimelineEvent {
    /// The cycle at which this event occurs.
    pub cycle: u64,
    /// The instruction index (0-based).
    pub instruction: usize,
    /// Event type: Dispatched, Issued, Executing, Executed, Retired.
    pub event: String,
}

// ============================================================================
// LLVM MCA Pass
// ============================================================================

/// LLVMMCA — Machine Code Analyzer for performance simulation.
pub struct LLVMMCA {
    /// Assembly source code to analyze.
    pub source: String,
    /// Number of iterations to simulate (for loop throughput estimation).
    pub iterations: usize,
}

impl LLVMMCA {
    /// Create a new MCA analyzer with the given assembly source.
    ///
    /// # Arguments
    /// * `source` - Assembly source code to analyze.
    pub fn new(source: &str) -> Self {
        Self {
            source: source.to_string(),
            iterations: 100,
        }
    }

    /// Set the number of iterations for loop throughput analysis.
    pub fn set_iterations(&mut self, n: usize) {
        self.iterations = n;
    }

    // ========================================================================
    // Main entry point
    // ========================================================================

    /// Run the MCA simulation and return the analysis result.
    pub fn run(&mut self) -> MCAnalysisResult {
        // Parse the assembly source into instructions
        let instructions = self.parse_source();

        // Simulate the pipeline
        self.simulate_pipeline(&instructions)
    }

    // ========================================================================
    // Parsing
    // ========================================================================

    /// Parse the assembly source string into a sequence of MCInst.
    /// Supports a simple assembly dialect:
    ///   - One instruction per line
    ///   - Format: "mnemonic dst, src1, src2"
    ///   - Lines starting with '#' or ';' are comments
    ///   - Register names like "r0", "r1", etc. are mapped to numeric IDs
    fn parse_source(&self) -> Vec<MCInst> {
        let mut instructions = Vec::new();
        let mut reg_map: HashMap<String, u32> = HashMap::new();
        let mut next_reg = 0u32;

        for line in self.source.lines() {
            let line = line.trim();

            // Skip empty lines and comments
            if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
                continue;
            }

            // Split into mnemonic and operands
            let parts: Vec<&str> = line.splitn(2, |c: char| c == ' ' || c == '\t').collect();
            if parts.is_empty() {
                continue;
            }

            let mnemonic = parts[0].trim().to_lowercase();
            let operands_str = if parts.len() > 1 { parts[1].trim() } else { "" };

            // Parse operand register names
            let mut operands = Vec::new();
            let mut dest_reg: Option<u32> = None;
            let mut source_regs = Vec::new();

            for (i, op_str) in operands_str.split(',').enumerate() {
                let op = op_str.trim();
                if op.is_empty() {
                    continue;
                }

                // Map register name to numeric ID
                let reg_id = *reg_map.entry(op.to_string()).or_insert_with(|| {
                    let id = next_reg;
                    next_reg += 1;
                    id
                });

                operands.push(reg_id);

                if i == 0 {
                    // First operand is typically the destination
                    dest_reg = Some(reg_id);
                } else {
                    source_regs.push(reg_id);
                }
            }

            // Determine instruction characteristics based on mnemonic
            let (latency, ports, micro_ops, writes_result) = self.get_instruction_info(&mnemonic);

            instructions.push(MCInst {
                mnemonic,
                operands,
                latency,
                ports,
                micro_ops,
                writes_result,
                dest_reg,
                source_regs,
            });
        }

        instructions
    }

    /// Get instruction latency, port usage, and micro-operation count
    /// for a given mnemonic. Based on typical x86-64/Skylake latencies.
    fn get_instruction_info(&self, mnemonic: &str) -> (u32, u32, u32, bool) {
        match mnemonic {
            // Simple ALU ops: 1 cycle latency, can use any ALU port
            "add" | "sub" | "and" | "or" | "xor" | "shl" | "shr" | "mov" => (1, 0xFF, 1, true),
            // Integer multiply: 3 cycle latency, specific port
            "mul" | "imul" => (3, 0x01, 1, true),
            // Integer division: variable latency, specific port
            "div" | "idiv" => (20, 0x01, 1, true),
            // Float add: 4 cycle latency
            "fadd" | "addss" | "addsd" => (4, 0x10, 1, true),
            // Float multiply: 4 cycle latency
            "fmul" | "mulss" | "mulsd" => (4, 0x10, 1, true),
            // Float division: 14 cycle latency
            "fdiv" | "divss" | "divsd" => (14, 0x10, 1, true),
            // Load: 5 cycle latency (L1 cache hit), load port
            "ldr" | "load" | "movload" | "ld" => (5, 0x20, 1, true),
            // Store: 1 cycle (store buffer), store port
            "str" | "store" | "st" => (1, 0x40, 1, false),
            // Branch: 1 cycle, branch unit
            "br" | "b" | "jmp" | "j" | "je" | "jne" | "jg" | "jl" | "call" | "ret" => {
                (1, 0x80, 1, false)
            }
            // Compare: 1 cycle, any ALU port
            "cmp" | "test" => (1, 0xFF, 1, false),
            // Default: assume 1 cycle, any port
            _ => (1, 0xFF, 1, true),
        }
    }

    // ========================================================================
    // Pipeline simulation
    // ========================================================================

    /// Simulate the execution pipeline for the given instruction sequence.
    ///
    /// Models a simplified out-of-order core with:
    ///   - Dispatch width: 4 instructions/cycle
    ///   - Issue width: 4 instructions/cycle
    ///   - Retire width: 4 instructions/cycle
    ///   - Reorder buffer size: 224 entries
    ///   - Reservation station size: 97 entries
    fn simulate_pipeline(&self, instructions: &[MCInst]) -> MCAnalysisResult {
        let n = instructions.len();
        if n == 0 {
            return MCAnalysisResult {
                total_cycles: 0,
                instructions: 0,
                ipc: 0.0,
                dispatch_stalls: 0,
                issue_stalls: 0,
                resource_pressure: HashMap::new(),
                timeline: Vec::new(),
            };
        }

        let dispatch_width = 4;
        let issue_width = 4;
        let retire_width = 4;
        let rob_size = 224;

        // State tracking
        let mut timeline: Vec<TimelineEvent> = Vec::new();
        let mut cycle: u64 = 0;
        let mut dispatch_idx: usize = 0; // Next instruction to dispatch
        let mut rob: VecDeque<InFlight> = VecDeque::new();
        let mut ready_queue: Vec<usize> = Vec::new(); // Indices of ready instructions in ROB
        let mut retire_idx: usize = 0; // Next instruction to retire (program order)

        // Register write-back tracking: reg_id → cycle when result is available
        let mut reg_ready: HashMap<u32, u64> = HashMap::new();

        // Resource tracking
        let mut dispatch_stalls = 0usize;
        let mut issue_stalls = 0usize;
        let mut port_usage: HashMap<String, u64> = HashMap::new();
        port_usage.insert("Port0".into(), 0);
        port_usage.insert("Port1".into(), 0);
        port_usage.insert("Port2".into(), 0);
        port_usage.insert("Port3".into(), 0);
        port_usage.insert("Port4".into(), 0);
        port_usage.insert("Port5".into(), 0);
        port_usage.insert("Port6".into(), 0);
        port_usage.insert("Port7".into(), 0);

        let max_cycles = (n * 10) as u64 + 1000; // Safety limit
        let mut total_retired = 0usize;

        while retire_idx < n && cycle < max_cycles {
            // ================================================================
            // Retire stage
            // ================================================================
            let mut retired_this_cycle = 0usize;
            while retired_this_cycle < retire_width && retire_idx < n {
                if let Some(front) = rob.front() {
                    if front.state == InFlightState::Executed && front.ready_cycle <= cycle {
                        let inflight = rob.pop_front().unwrap();
                        timeline.push(TimelineEvent {
                            cycle,
                            instruction: inflight.instr_idx,
                            event: "Retired".into(),
                        });

                        // Update register ready time
                        if let Some(dest_reg) = instructions[inflight.instr_idx].dest_reg {
                            reg_ready.insert(
                                dest_reg,
                                cycle + 1, // Available next cycle
                            );
                        }

                        retire_idx += 1;
                        total_retired += 1;
                        retired_this_cycle += 1;
                    } else {
                        break;
                    }
                } else {
                    break;
                }
            }

            // ================================================================
            // Issue stage: move ready instructions from ROB to execution
            // ================================================================
            let mut issued_this_cycle = 0usize;
            {
                let mut to_issue: Vec<usize> = Vec::new();
                for (rob_idx, inflight) in rob.iter().enumerate() {
                    if issued_this_cycle >= issue_width {
                        break;
                    }
                    if inflight.state != InFlightState::Dispatched {
                        continue;
                    }

                    // Check if all source operands are ready
                    let inst = &instructions[inflight.instr_idx];
                    let all_ready = inst.source_regs.iter().all(|reg| {
                        reg_ready
                            .get(reg)
                            .map_or(true, |&ready_cycle| ready_cycle <= cycle)
                    });

                    if all_ready {
                        to_issue.push(rob_idx);
                        issued_this_cycle += 1;
                    }
                }

                for &rob_idx in &to_issue {
                    if let Some(inflight) = rob.get_mut(rob_idx) {
                        let inst_idx = inflight.instr_idx;
                        let inst = &instructions[inst_idx];
                        let execute_cycles = inst.latency as u64;

                        inflight.state = InFlightState::Executing;
                        inflight.ready_cycle = cycle + execute_cycles;
                        inflight.issue_cycle = cycle;

                        timeline.push(TimelineEvent {
                            cycle,
                            instruction: inst_idx,
                            event: "Issued".into(),
                        });

                        // Track port usage
                        if inst.ports & 0x01 != 0 {
                            *port_usage.entry("Port0".into()).or_insert(0) += 1;
                        }
                        if inst.ports & 0x02 != 0 {
                            *port_usage.entry("Port1".into()).or_insert(0) += 1;
                        }
                        if inst.ports & 0x04 != 0 {
                            *port_usage.entry("Port2".into()).or_insert(0) += 1;
                        }
                        if inst.ports & 0x08 != 0 {
                            *port_usage.entry("Port3".into()).or_insert(0) += 1;
                        }
                        if inst.ports & 0x10 != 0 {
                            *port_usage.entry("Port4".into()).or_insert(0) += 1;
                        }
                        if inst.ports & 0x20 != 0 {
                            *port_usage.entry("Port5".into()).or_insert(0) += 1;
                        }
                        if inst.ports & 0x40 != 0 {
                            *port_usage.entry("Port6".into()).or_insert(0) += 1;
                        }
                        if inst.ports & 0x80 != 0 {
                            *port_usage.entry("Port7".into()).or_insert(0) += 1;
                        }
                    }
                }
            }

            if issued_this_cycle == 0 && !rob.is_empty() {
                let has_dispatched = rob.iter().any(|i| i.state == InFlightState::Dispatched);
                if has_dispatched {
                    issue_stalls += 1;
                }
            }

            // ================================================================
            // Execute stage: mark completed instructions
            // ================================================================
            for inflight in rob.iter_mut() {
                if inflight.state == InFlightState::Executing && inflight.ready_cycle <= cycle {
                    inflight.state = InFlightState::Executed;
                    timeline.push(TimelineEvent {
                        cycle,
                        instruction: inflight.instr_idx,
                        event: "Executed".into(),
                    });
                }
            }

            // ================================================================
            // Dispatch stage
            // ================================================================
            let mut dispatched_this_cycle = 0usize;
            while dispatched_this_cycle < dispatch_width && dispatch_idx < n && rob.len() < rob_size
            {
                let inst = &instructions[dispatch_idx];

                // Check dispatch constraints (simplified)
                if rob.len() + inst.micro_ops as usize <= rob_size {
                    rob.push_back(InFlight {
                        instr_idx: dispatch_idx,
                        state: InFlightState::Dispatched,
                        ready_cycle: 0,
                        issue_cycle: 0,
                    });

                    timeline.push(TimelineEvent {
                        cycle,
                        instruction: dispatch_idx,
                        event: "Dispatched".into(),
                    });

                    dispatch_idx += 1;
                    dispatched_this_cycle += 1;
                } else {
                    dispatch_stalls += 1;
                    break;
                }
            }

            cycle += 1;
        }

        // Compute resource pressure
        let resource_pressure = self.compute_resource_pressure(&timeline);

        // Compute critical path
        let _critical_path = self.compute_critical_path(instructions);

        // Compute IPC
        let ipc = if cycle > 0 {
            total_retired as f64 / cycle as f64
        } else {
            0.0
        };

        MCAnalysisResult {
            total_cycles: cycle,
            instructions: n,
            ipc,
            dispatch_stalls,
            issue_stalls,
            resource_pressure,
            timeline,
        }
    }

    // ========================================================================
    // Critical path analysis
    // ========================================================================

    /// Compute the length of the critical path (longest data-dependence
    /// chain) in the instruction sequence.
    fn compute_critical_path(&self, instructions: &[MCInst]) -> u64 {
        let n = instructions.len();
        if n == 0 {
            return 0;
        }

        // For each instruction, track the earliest cycle it can complete
        let mut completion_time: Vec<u64> = vec![0u64; n];
        let mut reg_last_writer: HashMap<u32, u64> = HashMap::new();

        for (i, inst) in instructions.iter().enumerate() {
            let mut earliest_start = 0u64;

            // Data dependencies: must wait for source register producers
            for src_reg in &inst.source_regs {
                if let Some(&producer_time) = reg_last_writer.get(src_reg) {
                    earliest_start = earliest_start.max(producer_time);
                }
            }

            let complete_at = earliest_start + inst.latency as u64;
            completion_time[i] = complete_at;

            // Update register last writer
            if let Some(dest_reg) = inst.dest_reg {
                reg_last_writer.insert(dest_reg, complete_at);
            }
        }

        // Critical path = max completion time
        completion_time.iter().max().copied().unwrap_or(0)
    }

    // ========================================================================
    // Resource pressure analysis
    // ========================================================================

    /// Compute resource pressure (utilization fraction) for each
    /// execution port based on the timeline.
    fn compute_resource_pressure(&self, timeline: &[TimelineEvent]) -> HashMap<String, f64> {
        let mut pressure: HashMap<String, f64> = HashMap::new();
        let mut port_usage: HashMap<String, u64> = HashMap::new();
        let mut total_cycles: u64 = 0;

        for event in timeline {
            total_cycles = total_cycles.max(event.cycle);
            if event.event == "Issued" {
                // Increment port usage based on instruction
                // (simplified: count each issue event)
                *port_usage.entry("Port0".into()).or_insert(0) += 1;
            }
        }

        if total_cycles > 0 {
            for (port, count) in &port_usage {
                let fraction = *count as f64 / total_cycles as f64;
                pressure.insert(port.clone(), fraction);
            }
        }

        // Ensure all standard ports appear
        for port in &[
            "Port0", "Port1", "Port2", "Port3", "Port4", "Port5", "Port6", "Port7",
        ] {
            pressure.entry(port.to_string()).or_insert(0.0);
        }

        pressure
    }

    // ========================================================================
    // Report generation
    // ========================================================================

    /// Generate a human-readable report from the analysis result.
    pub fn print_report(&self, result: &MCAnalysisResult) -> String {
        let mut report = String::new();

        report.push_str("=== LLVM MCA Analysis Report ===\n\n");
        report.push_str(&format!("Total Instructions: {}\n", result.instructions));
        report.push_str(&format!("Total Cycles: {}\n", result.total_cycles));
        report.push_str(&format!("IPC: {:.4}\n", result.ipc));
        report.push_str(&format!("Dispatch Stalls: {}\n", result.dispatch_stalls));
        report.push_str(&format!("Issue Stalls: {}\n", result.issue_stalls));
        report.push_str("\n--- Resource Pressure ---\n");

        for (port, pressure) in &result.resource_pressure {
            report.push_str(&format!("  {}: {:.2}%\n", port, pressure * 100.0));
        }

        report.push_str("\n--- Timeline (first 20 events) ---\n");
        for (i, event) in result.timeline.iter().take(20).enumerate() {
            report.push_str(&format!(
                "  [{}] Cycle {}: Inst {} {}\n",
                i, event.cycle, event.instruction, event.event
            ));
        }

        if result.timeline.len() > 20 {
            report.push_str(&format!(
                "  ... and {} more events\n",
                result.timeline.len() - 20
            ));
        }

        report
    }
}

// ============================================================================
// Internal types
// ============================================================================

/// State of an instruction in the pipeline.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum InFlightState {
    /// Waiting in the reorder buffer for operands to become ready.
    Dispatched,
    /// Executing in a functional unit.
    Executing,
    /// Execution complete, waiting to retire.
    Executed,
}

/// An instruction currently in the processor pipeline.
#[derive(Debug, Clone)]
struct InFlight {
    /// Index into the original instruction list.
    instr_idx: usize,
    /// Current pipeline state.
    state: InFlightState,
    /// Cycle at which execution will complete.
    ready_cycle: u64,
    /// Cycle at which the instruction was issued.
    issue_cycle: u64,
}

// ============================================================================
// Pipeline Configuration
// ============================================================================

/// Configurable parameters for the MCA pipeline model.
#[derive(Debug, Clone)]
pub struct PipelineConfig {
    /// Maximum number of instructions dispatched per cycle.
    pub dispatch_width: usize,
    /// Maximum number of instructions issued per cycle.
    pub issue_width: usize,
    /// Maximum number of instructions retired per cycle.
    pub retire_width: usize,
    /// Size of the reorder buffer.
    pub reorder_buffer_size: usize,
    /// Size of the load queue.
    pub load_queue_size: usize,
    /// Size of the store queue.
    pub store_queue_size: usize,
    /// Size of the physical register file.
    pub register_file_size: usize,
    /// Size of the unified reservation station.
    pub reservation_station_size: usize,
}

impl Default for PipelineConfig {
    fn default() -> Self {
        Self {
            dispatch_width: 4,
            issue_width: 4,
            retire_width: 4,
            reorder_buffer_size: 224,
            load_queue_size: 72,
            store_queue_size: 56,
            register_file_size: 180,
            reservation_station_size: 97,
        }
    }
}

impl PipelineConfig {
    pub fn skylake() -> Self {
        Self::default()
    }
    pub fn zen4() -> Self {
        Self {
            dispatch_width: 6,
            issue_width: 6,
            retire_width: 8,
            reorder_buffer_size: 320,
            load_queue_size: 116,
            store_queue_size: 64,
            register_file_size: 224,
            reservation_station_size: 128,
        }
    }
    pub fn apple_m1() -> Self {
        Self {
            dispatch_width: 8,
            issue_width: 8,
            retire_width: 8,
            reorder_buffer_size: 630,
            load_queue_size: 128,
            store_queue_size: 96,
            register_file_size: 384,
            reservation_station_size: 192,
        }
    }
    pub fn in_order() -> Self {
        Self {
            dispatch_width: 1,
            issue_width: 1,
            retire_width: 1,
            reorder_buffer_size: 4,
            load_queue_size: 4,
            store_queue_size: 4,
            register_file_size: 32,
            reservation_station_size: 0,
        }
    }
}

// ============================================================================
// Pipeline Stages
// ============================================================================

pub struct FetchStage {
    fetch_ptr: usize,
    fetch_width: usize,
    total_fetched: usize,
    fetch_stalls: usize,
}

impl FetchStage {
    pub fn new(fetch_width: usize) -> Self {
        Self {
            fetch_ptr: 0,
            fetch_width,
            total_fetched: 0,
            fetch_stalls: 0,
        }
    }
    pub fn fetch(
        &mut self,
        total_insts: usize,
        queue_capacity: usize,
        queue_len: usize,
    ) -> Vec<usize> {
        let available = queue_capacity.saturating_sub(queue_len);
        let can_fetch = self.fetch_width.min(available);
        if can_fetch == 0 {
            self.fetch_stalls += 1;
            return vec![];
        }
        let end = (self.fetch_ptr + can_fetch).min(total_insts);
        let fetched: Vec<usize> = (self.fetch_ptr..end).collect();
        self.fetch_ptr = end;
        self.total_fetched += fetched.len();
        fetched
    }
    pub fn reset(&mut self) {
        self.fetch_ptr = 0;
        self.total_fetched = 0;
        self.fetch_stalls = 0;
    }
    pub fn fetch_stalls(&self) -> usize {
        self.fetch_stalls
    }
    pub fn total_fetched(&self) -> usize {
        self.total_fetched
    }
}

pub struct DecodeStage {
    decode_width: usize,
    total_decoded: usize,
    decode_stalls: usize,
}

impl DecodeStage {
    pub fn new(decode_width: usize) -> Self {
        Self {
            decode_width,
            total_decoded: 0,
            decode_stalls: 0,
        }
    }
    pub fn decode(&mut self, inst_indices: &[usize], insts: &[MCInst]) -> usize {
        let mut uops = 0usize;
        for &idx in inst_indices.iter().take(self.decode_width) {
            if idx < insts.len() {
                uops += insts[idx].micro_ops as usize;
            }
        }
        if uops == 0 && !inst_indices.is_empty() {
            self.decode_stalls += 1;
        }
        self.total_decoded += uops;
        uops
    }
    pub fn reset(&mut self) {
        self.total_decoded = 0;
        self.decode_stalls = 0;
    }
    pub fn decode_stalls(&self) -> usize {
        self.decode_stalls
    }
}

pub struct DispatchStage {
    dispatch_width: usize,
    total_dispatched: usize,
    dispatch_stalls: usize,
}

impl DispatchStage {
    pub fn new(dispatch_width: usize) -> Self {
        Self {
            dispatch_width,
            total_dispatched: 0,
            dispatch_stalls: 0,
        }
    }
    pub fn dispatch(
        &mut self,
        inst_indices: &[usize],
        rob_used: usize,
        rob_capacity: usize,
    ) -> usize {
        let available = rob_capacity.saturating_sub(rob_used);
        let can = self.dispatch_width.min(available).min(inst_indices.len());
        if can == 0 && !inst_indices.is_empty() {
            self.dispatch_stalls += 1;
        }
        self.total_dispatched += can;
        can
    }
    pub fn reset(&mut self) {
        self.total_dispatched = 0;
        self.dispatch_stalls = 0;
    }
    pub fn dispatch_stalls(&self) -> usize {
        self.dispatch_stalls
    }
    pub fn total_dispatched(&self) -> usize {
        self.total_dispatched
    }
}

pub struct ExecuteStage {
    total_exec_cycles: u64,
    total_executed: usize,
}

impl ExecuteStage {
    pub fn new() -> Self {
        Self {
            total_exec_cycles: 0,
            total_executed: 0,
        }
    }
    pub fn tick(&mut self, inflight: &mut [InFlight], cycle: u64, _insts: &[MCInst]) -> usize {
        let mut executed = 0usize;
        for entry in inflight.iter_mut() {
            if entry.state == InFlightState::Executing && entry.ready_cycle <= cycle {
                entry.state = InFlightState::Executed;
                executed += 1;
            }
        }
        self.total_executed += executed;
        self.total_exec_cycles += 1;
        executed
    }
    pub fn reset(&mut self) {
        self.total_exec_cycles = 0;
        self.total_executed = 0;
    }
}

pub struct RetireStage {
    retire_width: usize,
    total_retired: usize,
    retire_stalls: usize,
}

impl RetireStage {
    pub fn new(retire_width: usize) -> Self {
        Self {
            retire_width,
            total_retired: 0,
            retire_stalls: 0,
        }
    }
    pub fn retire(&mut self, rob: &mut VecDeque<InFlight>, cycle: u64) -> usize {
        let mut retired = 0usize;
        while retired < self.retire_width {
            match rob.front() {
                Some(e) if e.state == InFlightState::Executed && e.ready_cycle <= cycle => {
                    rob.pop_front();
                    retired += 1;
                }
                _ => break,
            }
        }
        if retired == 0 && !rob.is_empty() {
            self.retire_stalls += 1;
        }
        self.total_retired += retired;
        retired
    }
    pub fn reset(&mut self) {
        self.total_retired = 0;
        self.retire_stalls = 0;
    }
    pub fn retire_stalls(&self) -> usize {
        self.retire_stalls
    }
    pub fn total_retired(&self) -> usize {
        self.total_retired
    }
}

// ============================================================================
// Instruction Scheduler
// ============================================================================

pub struct Scheduler {
    issue_width: usize,
    reservation_station: Vec<Option<usize>>,
    resource_manager: ResourceManager,
    issue_stalls: usize,
    total_issued: usize,
}

impl Scheduler {
    pub fn new(issue_width: usize, rs_size: usize) -> Self {
        Self {
            issue_width,
            reservation_station: vec![None; rs_size],
            resource_manager: ResourceManager::new(),
            issue_stalls: 0,
            total_issued: 0,
        }
    }
    pub fn insert_into_rs(&mut self, instr_idx: usize) -> bool {
        for slot in self.reservation_station.iter_mut() {
            if slot.is_none() {
                *slot = Some(instr_idx);
                return true;
            }
        }
        false
    }
    pub fn remove_from_rs(&mut self, instr_idx: usize) {
        for slot in self.reservation_station.iter_mut() {
            if *slot == Some(instr_idx) {
                *slot = None;
                return;
            }
        }
    }
    pub fn issue(
        &mut self,
        insts: &[MCInst],
        reg_ready: &HashMap<u32, u64>,
        cycle: u64,
    ) -> Vec<usize> {
        let mut issued = Vec::new();
        for slot in self.reservation_station.iter() {
            if issued.len() >= self.issue_width {
                break;
            }
            if let Some(idx) = slot {
                let inst = &insts[*idx];
                let all_ready = inst
                    .source_regs
                    .iter()
                    .all(|reg| reg_ready.get(reg).map_or(true, |&t| t <= cycle));
                if all_ready && self.resource_manager.can_issue(inst, cycle) {
                    self.resource_manager.reserve(inst, cycle);
                    issued.push(*idx);
                }
            }
        }
        if issued.is_empty() {
            let has_any = self.reservation_station.iter().any(|s| s.is_some());
            if has_any {
                self.issue_stalls += 1;
            }
        }
        self.total_issued += issued.len();
        issued
    }
    pub fn rs_used(&self) -> usize {
        self.reservation_station
            .iter()
            .filter(|s| s.is_some())
            .count()
    }
    pub fn rs_capacity(&self) -> usize {
        self.reservation_station.len()
    }
    pub fn issue_stalls(&self) -> usize {
        self.issue_stalls
    }
    pub fn total_issued(&self) -> usize {
        self.total_issued
    }
    pub fn reset(&mut self) {
        for slot in self.reservation_station.iter_mut() {
            *slot = None;
        }
        self.resource_manager.reset();
        self.issue_stalls = 0;
        self.total_issued = 0;
    }
}

// ============================================================================
// Resource Modeling
// ============================================================================

#[derive(Debug, Clone)]
pub struct HardwareUnit {
    pub name: String,
    pub count: usize,
    pub pipelined: bool,
    pub latency: u32,
}

impl HardwareUnit {
    pub fn new(name: &str, count: usize, pipelined: bool, latency: u32) -> Self {
        Self {
            name: name.to_string(),
            count,
            pipelined,
            latency,
        }
    }
}

#[derive(Debug, Clone)]
pub struct ResourceState {
    pub unit: HardwareUnit,
    busy_until: Vec<u64>,
}

impl ResourceState {
    pub fn new(unit: HardwareUnit) -> Self {
        let busy_until = vec![0u64; unit.count];
        Self { unit, busy_until }
    }
    pub fn is_available(&self, cycle: u64) -> bool {
        self.busy_until.iter().any(|&t| t <= cycle)
    }
    pub fn reserve(&mut self, cycle: u64) -> bool {
        for slot in self.busy_until.iter_mut() {
            if *slot <= cycle {
                *slot = cycle + self.unit.latency as u64;
                return true;
            }
        }
        false
    }
    pub fn next_available(&self) -> u64 {
        self.busy_until.iter().min().copied().unwrap_or(0)
    }
    pub fn reset(&mut self) {
        for slot in self.busy_until.iter_mut() {
            *slot = 0;
        }
    }
}

pub struct ResourceManager {
    resources: HashMap<String, ResourceState>,
    port_map: HashMap<u32, Vec<String>>,
}

impl ResourceManager {
    pub fn new() -> Self {
        let mut rm = Self {
            resources: HashMap::new(),
            port_map: HashMap::new(),
        };
        for (name, latency) in &[
            ("Port0", 1),
            ("Port1", 1),
            ("Port2", 1),
            ("Port3", 1),
            ("Port4", 1),
            ("Port5", 1),
            ("Port6", 1),
            ("Port7", 1),
            ("FPU0", 4),
            ("FPU1", 4),
            ("AGU0", 5),
            ("AGU1", 5),
            ("BranchUnit", 1),
            ("Divider", 20),
        ] {
            rm.resources.insert(
                name.to_string(),
                ResourceState::new(HardwareUnit::new(name, 1, true, *latency)),
            );
        }
        for (mask, ports) in &[
            (0x01u32, vec!["Port0"]),
            (0x02, vec!["Port1"]),
            (0x04, vec!["Port2"]),
            (0x08, vec!["Port3"]),
            (0x10, vec!["Port4"]),
            (0x20, vec!["Port5"]),
            (0x40, vec!["Port6"]),
            (0x80, vec!["Port7"]),
        ] {
            rm.port_map
                .insert(*mask, ports.iter().map(|s| s.to_string()).collect());
        }
        rm
    }

    pub fn can_issue(&self, inst: &MCInst, cycle: u64) -> bool {
        for bit in 0..8 {
            let mask = 1u32 << bit;
            if inst.ports & mask != 0 {
                if let Some(names) = self.port_map.get(&mask) {
                    for name in names {
                        if let Some(rs) = self.resources.get(name) {
                            if !rs.is_available(cycle) {
                                return false;
                            }
                        }
                    }
                }
            }
        }
        true
    }

    pub fn reserve(&mut self, inst: &MCInst, cycle: u64) -> bool {
        if !self.can_issue(inst, cycle) {
            return false;
        }
        for bit in 0..8 {
            let mask = 1u32 << bit;
            if inst.ports & mask != 0 {
                if let Some(names) = self.port_map.get(&mask) {
                    for name in names {
                        if let Some(rs) = self.resources.get_mut(name) {
                            rs.reserve(cycle);
                        }
                    }
                }
            }
        }
        true
    }

    pub fn utilization(&self, total_cycles: u64) -> HashMap<String, f64> {
        let mut util = HashMap::new();
        let tc = total_cycles.max(1);
        for (name, rs) in &self.resources {
            let total_busy: u64 = rs.busy_until.iter().sum();
            let max_cap = rs.unit.count as u64 * tc;
            util.insert(
                name.clone(),
                if max_cap > 0 {
                    total_busy as f64 / max_cap as f64
                } else {
                    0.0
                },
            );
        }
        util
    }

    pub fn reset(&mut self) {
        for rs in self.resources.values_mut() {
            rs.reset();
        }
    }
}

// ============================================================================
// Performance Event Tracking
// ============================================================================

#[derive(Debug, Clone)]
pub struct DetailedEvent {
    pub cycle: u64,
    pub inst_idx: usize,
    pub mnemonic: String,
    pub event_type: EventType,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EventType {
    Fetched,
    Decoded,
    Dispatched,
    Issued,
    Executing,
    Executed,
    Retired,
    StalledDispatch,
    StalledIssue,
    StalledRetire,
}

#[derive(Debug, Clone)]
pub struct Timeline {
    events: Vec<DetailedEvent>,
    total_cycles: u64,
}

impl Timeline {
    pub fn new() -> Self {
        Self {
            events: Vec::new(),
            total_cycles: 0,
        }
    }
    pub fn record(&mut self, cycle: u64, inst_idx: usize, mnemonic: &str, event: EventType) {
        self.events.push(DetailedEvent {
            cycle,
            inst_idx,
            mnemonic: mnemonic.to_string(),
            event_type: event,
        });
        self.total_cycles = self.total_cycles.max(cycle + 1);
    }
    pub fn total_cycles(&self) -> u64 {
        self.total_cycles
    }
    pub fn event_count(&self) -> usize {
        self.events.len()
    }
    pub fn events_at(&self, cycle: u64) -> Vec<&DetailedEvent> {
        self.events.iter().filter(|e| e.cycle == cycle).collect()
    }
    pub fn count_by_type(&self, et: EventType) -> usize {
        self.events.iter().filter(|e| e.event_type == et).count()
    }
}

#[derive(Debug, Clone)]
pub struct TimelineView {
    pub total_cycles: u64,
    pub dispatched: usize,
    pub issued: usize,
    pub executed: usize,
    pub retired: usize,
    pub dispatch_stalls: usize,
    pub issue_stalls: usize,
    pub retire_stalls: usize,
    pub ipc: f64,
}

impl TimelineView {
    pub fn from_timeline(tl: &Timeline) -> Self {
        let retired = tl.count_by_type(EventType::Retired);
        Self {
            total_cycles: tl.total_cycles,
            dispatched: tl.count_by_type(EventType::Dispatched),
            issued: tl.count_by_type(EventType::Issued),
            executed: tl.count_by_type(EventType::Executed),
            retired,
            dispatch_stalls: tl.count_by_type(EventType::StalledDispatch),
            issue_stalls: tl.count_by_type(EventType::StalledIssue),
            retire_stalls: tl.count_by_type(EventType::StalledRetire),
            ipc: if tl.total_cycles > 0 {
                retired as f64 / tl.total_cycles as f64
            } else {
                0.0
            },
        }
    }
}

// ============================================================================
// Bottleneck Analysis
// ============================================================================

#[derive(Debug, Clone)]
pub struct Bottleneck {
    pub description: String,
    pub severity: f64,
    pub bottleneck_type: BottleneckType,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BottleneckType {
    DispatchWidth,
    ResourceContention,
    DataDependency,
    StructuralHazard,
    FrontEnd,
    BackEnd,
    Retirement,
}

pub fn analyze_bottlenecks(
    view: &TimelineView,
    resource_pressure: &HashMap<String, f64>,
    config: &PipelineConfig,
) -> Vec<Bottleneck> {
    let mut bl = Vec::new();
    if view.total_cycles > 0 {
        let eff =
            view.dispatched as f64 / (view.total_cycles as f64 * config.dispatch_width as f64);
        if eff < 0.5 {
            bl.push(Bottleneck {
                description: format!("Low dispatch utilization ({:.1}%)", eff * 100.0),
                severity: 1.0 - eff,
                bottleneck_type: BottleneckType::DispatchWidth,
            });
        }
    }
    for (res, pressure) in resource_pressure {
        if *pressure > 0.8 {
            bl.push(Bottleneck {
                description: format!("High pressure on {}: {:.1}%", res, pressure * 100.0),
                severity: *pressure,
                bottleneck_type: BottleneckType::ResourceContention,
            });
        }
    }
    let total_stalls = (view.dispatch_stalls + view.issue_stalls + view.retire_stalls).max(1);
    if view.issue_stalls > view.dispatch_stalls + view.retire_stalls {
        bl.push(Bottleneck {
            description: "Back-end bound".into(),
            severity: view.issue_stalls as f64 / total_stalls as f64,
            bottleneck_type: BottleneckType::BackEnd,
        });
    }
    if view.retire_stalls > view.dispatch_stalls && view.retire_stalls > view.issue_stalls {
        bl.push(Bottleneck {
            description: "Retirement bound".into(),
            severity: view.retire_stalls as f64 / total_stalls as f64,
            bottleneck_type: BottleneckType::Retirement,
        });
    }
    bl
}

// ============================================================================
// Summary Views
// ============================================================================

pub fn print_summary(result: &MCAnalysisResult) -> String {
    use std::fmt::Write;
    let mut s = String::new();
    let _ = writeln!(s, "╔══════════════════════════════════════╗");
    let _ = writeln!(s, "║     LLVM MCA Performance Summary     ║");
    let _ = writeln!(s, "╠══════════════════════════════════════╣");
    let _ = writeln!(
        s,
        "║ Instructions:           {:>8}",
        result.instructions
    );
    let _ = writeln!(
        s,
        "║ Total Cycles:           {:>8}",
        result.total_cycles
    );
    let _ = writeln!(s, "║ IPC:                    {:>8.3}", result.ipc);
    let _ = writeln!(
        s,
        "║ Dispatch Stalls:        {:>8}",
        result.dispatch_stalls
    );
    let _ = writeln!(
        s,
        "║ Issue Stalls:           {:>8}",
        result.issue_stalls
    );
    let _ = writeln!(s, "╚══════════════════════════════════════╝");
    s
}

pub fn print_timeline(result: &MCAnalysisResult, max_events: usize) -> String {
    let mut s = String::from("--- Timeline ---\n");
    for (i, e) in result.timeline.iter().take(max_events).enumerate() {
        s.push_str(&format!(
            "  {:>3}: Cycle {:>5} | Inst {:>5} | {}\n",
            i, e.cycle, e.instruction, e.event
        ));
    }
    if result.timeline.len() > max_events {
        s.push_str(&format!(
            "  ... and {} more\n",
            result.timeline.len() - max_events
        ));
    }
    s
}

pub fn print_resource_pressure(result: &MCAnalysisResult) -> String {
    let mut s = String::from("--- Resource Pressure ---\n");
    let mut ports: Vec<(&String, &f64)> = result.resource_pressure.iter().collect();
    ports.sort_by(|a, b| b.1.partial_cmp(a.1).unwrap_or(std::cmp::Ordering::Equal));
    for (port, p) in &ports {
        let bar = "".repeat(((*p * 50.0) as usize).min(50));
        s.push_str(&format!("  {:>10}: {:>6.1}% |{}\n", port, *p * 100.0, bar));
    }
    s
}

pub fn print_instruction_info(insts: &[MCInst]) -> String {
    let mut s = String::from("--- Instruction Info ---\n");
    for (i, inst) in insts.iter().enumerate() {
        let port_str = if inst.ports == 0xFF {
            "ALL".into()
        } else {
            (0..8)
                .filter(|b| inst.ports & (1 << b) != 0)
                .map(|b| format!("P{}", b))
                .collect::<Vec<_>>()
                .join(",")
        };
        s.push_str(&format!(
            "  {:>3}: {:>8} | Lat: {:>3} | uOps: {:>2} | Ports: {}\n",
            i, inst.mnemonic, inst.latency, inst.micro_ops, port_str
        ));
    }
    s
}

// ============================================================================
// MCA Diagnostic
// ============================================================================

#[derive(Debug, Clone)]
pub struct MCADiagnostic {
    pub level: DiagnosticLevel,
    pub message: String,
}

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

pub fn run_diagnostics(result: &MCAnalysisResult, config: &PipelineConfig) -> Vec<MCADiagnostic> {
    let mut diags = Vec::new();
    for (port, p) in &result.resource_pressure {
        if *p > 0.9 {
            diags.push(MCADiagnostic {
                level: DiagnosticLevel::Warning,
                message: format!("Resource {} over-subscribed ({:.1}%)", port, p * 100.0),
            });
        }
    }
    if result.instructions > 0 && result.dispatch_stalls > result.instructions / 2 {
        diags.push(MCADiagnostic {
            level: DiagnosticLevel::Warning,
            message: format!(
                "High dispatch stall rate: {} stalls for {} insts",
                result.dispatch_stalls, result.instructions
            ),
        });
    }
    if result.instructions > 10 && result.ipc < 0.5 {
        diags.push(MCADiagnostic {
            level: DiagnosticLevel::Warning,
            message: format!("Very low IPC ({:.3})", result.ipc),
        });
    }
    diags
}

// ============================================================================
// Enhanced MCA Runner
// ============================================================================

impl LLVMMCA {
    pub fn run_with_config(&self, config: &PipelineConfig) -> MCAnalysisResult {
        let instructions = self.parse_source();
        self.simulate_full_pipeline(&instructions, config)
    }

    fn simulate_full_pipeline(
        &self,
        insts: &[MCInst],
        config: &PipelineConfig,
    ) -> MCAnalysisResult {
        let n = insts.len();
        if n == 0 {
            return MCAnalysisResult {
                total_cycles: 0,
                instructions: 0,
                ipc: 0.0,
                dispatch_stalls: 0,
                issue_stalls: 0,
                resource_pressure: HashMap::new(),
                timeline: vec![],
            };
        }
        let mut fetch = FetchStage::new(config.dispatch_width);
        let mut decode = DecodeStage::new(config.dispatch_width);
        let mut dispatch = DispatchStage::new(config.dispatch_width);
        let mut execute = ExecuteStage::new();
        let mut retire = RetireStage::new(config.retire_width);
        let mut scheduler = Scheduler::new(config.issue_width, config.reservation_station_size);
        let mut rob: VecDeque<InFlight> = VecDeque::new();
        let mut reg_ready: HashMap<u32, u64> = HashMap::new();
        let mut timeline = Timeline::new();
        let mut cycle: u64 = 0;
        let max_cycles = (n * 20) as u64 + 5000;
        let mut decoded_queue: VecDeque<usize> = VecDeque::new();

        while (retire.total_retired() < n || !rob.is_empty()) && cycle < max_cycles {
            // Retire
            let retired = retire.retire(&mut rob, cycle);
            for _ in 0..retired {
                timeline.record(cycle, 0, "", EventType::Retired);
            }

            // Execute
            let mut rob_vec: Vec<InFlight> = rob.iter().cloned().collect();
            execute.tick(&mut rob_vec, cycle, insts);
            for (i, entry) in rob_vec.iter().enumerate() {
                if let Some(re) = rob.get_mut(i) {
                    if re.state != entry.state {
                        re.state = entry.state;
                        if entry.state == InFlightState::Executed {
                            timeline.record(
                                cycle,
                                entry.instr_idx,
                                &insts[entry.instr_idx].mnemonic,
                                EventType::Executed,
                            );
                        }
                    }
                }
            }

            // Issue
            let issued = scheduler.issue(insts, &reg_ready, cycle);
            for &idx in &issued {
                let inst = &insts[idx];
                for re in rob.iter_mut() {
                    if re.instr_idx == idx && re.state == InFlightState::Dispatched {
                        re.state = InFlightState::Executing;
                        re.ready_cycle = cycle + inst.latency as u64;
                        re.issue_cycle = cycle;
                        break;
                    }
                }
                scheduler.remove_from_rs(idx);
                timeline.record(cycle, idx, &inst.mnemonic, EventType::Issued);
            }

            // Dispatch
            while !decoded_queue.is_empty() && rob.len() < config.reorder_buffer_size {
                let idx = decoded_queue.pop_front().unwrap();
                if scheduler.insert_into_rs(idx) {
                    rob.push_back(InFlight {
                        instr_idx: idx,
                        state: InFlightState::Dispatched,
                        ready_cycle: 0,
                        issue_cycle: 0,
                    });
                    timeline.record(cycle, idx, &insts[idx].mnemonic, EventType::Dispatched);
                } else {
                    decoded_queue.push_front(idx);
                    timeline.record(cycle, 0, "", EventType::StalledDispatch);
                    break;
                }
            }

            // Fetch + Decode
            let fetched = fetch.fetch(n, decoded_queue.capacity(), decoded_queue.len());
            for &idx in &fetched {
                timeline.record(cycle, idx, &insts[idx].mnemonic, EventType::Fetched);
            }
            decode.decode(&fetched, insts);
            for &idx in &fetched {
                decoded_queue.push_back(idx);
            }

            cycle += 1;
        }

        let resource_pressure = scheduler.resource_manager.utilization(cycle);
        let mca_timeline: Vec<TimelineEvent> = timeline
            .events
            .iter()
            .map(|e| TimelineEvent {
                cycle: e.cycle,
                instruction: e.inst_idx,
                event: format!("{:?}", e.event_type),
            })
            .collect();

        MCAnalysisResult {
            total_cycles: cycle,
            instructions: n,
            ipc: if cycle > 0 {
                retire.total_retired() as f64 / cycle as f64
            } else {
                0.0
            },
            dispatch_stalls: dispatch.dispatch_stalls() + fetch.fetch_stalls(),
            issue_stalls: scheduler.issue_stalls(),
            resource_pressure,
            timeline: mca_timeline,
        }
    }
}

// ============================================================================
// Loop Kernel Analysis
// ============================================================================

#[derive(Debug, Clone)]
pub struct IterationInfo {
    pub insts_per_iter: usize,
    pub cycles_per_iter: u64,
    pub total_cycles: u64,
    pub iterations: usize,
}

impl LLVMMCA {
    pub fn run_loop_analysis(&mut self) -> (MCAnalysisResult, IterationInfo) {
        let insts = self.parse_source();
        let n = insts.len();
        let iters = self.iterations;
        let mut all_insts: Vec<MCInst> = Vec::with_capacity(n * iters);
        for _ in 0..iters {
            all_insts.extend(insts.clone());
        }
        let result = self.simulate_pipeline(&all_insts);
        let ii = IterationInfo {
            insts_per_iter: n,
            cycles_per_iter: if iters > 0 {
                result.total_cycles / iters as u64
            } else {
                0
            },
            total_cycles: result.total_cycles,
            iterations: iters,
        };
        (result, ii)
    }

    pub fn loop_throughput(&self, ii: &IterationInfo) -> f64 {
        if ii.cycles_per_iter > 0 {
            1000.0 / ii.cycles_per_iter as f64
        } else {
            0.0
        }
    }
}

// ============================================================================
// Critical Path & Dependency Analysis
// ============================================================================

#[derive(Debug, Clone)]
pub struct CriticalPathInfo {
    pub critical_insts: Vec<usize>,
    pub path_length: u64,
    pub latency_breakdown: HashMap<String, u64>,
}

impl LLVMMCA {
    pub fn analyze_critical_path(&self, insts: &[MCInst]) -> CriticalPathInfo {
        let n = insts.len();
        let mut completion: Vec<u64> = vec![0; n];
        let mut predecessor: Vec<Option<usize>> = vec![None; n];
        let mut reg_last: HashMap<u32, (usize, u64)> = HashMap::new();
        let mut breakdown: HashMap<String, u64> = HashMap::new();

        for (i, inst) in insts.iter().enumerate() {
            let mut earliest = 0u64;
            let mut pred = None;
            for src in &inst.source_regs {
                if let Some(&(pi, pt)) = reg_last.get(src) {
                    if pt >= earliest {
                        earliest = pt;
                        pred = Some(pi);
                    }
                }
            }
            let done = earliest + inst.latency as u64;
            completion[i] = done;
            predecessor[i] = pred;
            *breakdown.entry(inst.mnemonic.clone()).or_insert(0) += inst.latency as u64;
            if let Some(dest) = inst.dest_reg {
                reg_last.insert(dest, (i, done));
            }
        }

        let mut max_i = 0;
        let mut max_t = 0u64;
        for (i, &t) in completion.iter().enumerate() {
            if t > max_t {
                max_t = t;
                max_i = i;
            }
        }
        let mut critical = Vec::new();
        let mut cur = Some(max_i);
        while let Some(idx) = cur {
            critical.push(idx);
            cur = predecessor[idx];
        }
        critical.reverse();

        CriticalPathInfo {
            critical_insts: critical,
            path_length: max_t,
            latency_breakdown: breakdown,
        }
    }
}

// ============================================================================
// Dispatch Group Analysis
// ============================================================================

#[derive(Debug, Clone)]
pub struct DispatchGroup {
    pub cycle: u64,
    pub inst_indices: Vec<usize>,
}

pub fn analyze_dispatch_groups(timeline: &[TimelineEvent]) -> Vec<DispatchGroup> {
    let mut groups: Vec<DispatchGroup> = Vec::new();
    for e in timeline {
        if e.event == "Dispatched" {
            if let Some(last) = groups.last_mut() {
                if last.cycle == e.cycle {
                    last.inst_indices.push(e.instruction);
                    continue;
                }
            }
            groups.push(DispatchGroup {
                cycle: e.cycle,
                inst_indices: vec![e.instruction],
            });
        }
    }
    groups
}

pub fn avg_dispatch_group_size(groups: &[DispatchGroup]) -> f64 {
    if groups.is_empty() {
        return 0.0;
    }
    groups.iter().map(|g| g.inst_indices.len()).sum::<usize>() as f64 / groups.len() as f64
}

// ============================================================================
// Port Pressure Heat Map
// ============================================================================

#[derive(Debug, Clone)]
pub struct PortPressure {
    pub cycle: u64,
    pub port_usage: HashMap<String, usize>,
}

pub fn build_port_pressure_map(
    timeline: &[TimelineEvent],
    insts: &[MCInst],
    max_cycle: u64,
) -> Vec<PortPressure> {
    let pn = [
        "Port0", "Port1", "Port2", "Port3", "Port4", "Port5", "Port6", "Port7",
    ];
    let mut map = Vec::new();
    for cyc in 0..=max_cycle {
        let mut usage = HashMap::new();
        for n in &pn {
            usage.insert(n.to_string(), 0usize);
        }
        for e in timeline {
            if e.cycle == cyc && e.event == "Issued" && e.instruction < insts.len() {
                let inst = &insts[e.instruction];
                for (bit, name) in pn.iter().enumerate() {
                    if inst.ports & (1u32 << bit) != 0 {
                        *usage.entry(name.to_string()).or_insert(0) += 1;
                    }
                }
            }
        }
        map.push(PortPressure {
            cycle: cyc,
            port_usage: usage,
        });
    }
    map
}

// ============================================================================
// Statistical Summary
// ============================================================================

#[derive(Debug, Clone)]
pub struct StatisticalSummary {
    pub min_inflight: usize,
    pub max_inflight: usize,
    pub avg_inflight: f64,
    pub avg_dispatch_rate: f64,
    pub avg_issue_rate: f64,
    pub avg_retire_rate: f64,
    pub stall_pct: f64,
}

pub fn compute_statistics(
    result: &MCAnalysisResult,
    dispatch_groups: &[DispatchGroup],
) -> StatisticalSummary {
    let cycles = result.total_cycles.max(1) as f64;
    let dispatched = result
        .timeline
        .iter()
        .filter(|e| e.event == "Dispatched")
        .count();
    let issued = result
        .timeline
        .iter()
        .filter(|e| e.event == "Issued")
        .count();
    let retired = result
        .timeline
        .iter()
        .filter(|e| e.event == "Retired")
        .count();
    let gsz: Vec<usize> = dispatch_groups
        .iter()
        .map(|g| g.inst_indices.len())
        .collect();
    let adr = if !gsz.is_empty() {
        gsz.iter().sum::<usize>() as f64 / gsz.len() as f64
    } else {
        0.0
    };
    StatisticalSummary {
        min_inflight: 0,
        max_inflight: result.instructions,
        avg_inflight: 0.0,
        avg_dispatch_rate: dispatched as f64 / cycles,
        avg_issue_rate: issued as f64 / cycles,
        avg_retire_rate: retired as f64 / cycles,
        stall_pct: (result.dispatch_stalls + result.issue_stalls) as f64 / cycles * 100.0,
    }
}

// ============================================================================
// Register File Modeling — read/write ports and renaming
// ============================================================================

/// Models a physical register file with read/write ports and register renaming.
pub struct RegisterFile {
    /// Number of physical registers.
    pub num_registers: usize,
    /// Width of each register in bits.
    pub register_width: u32,
    /// Number of read ports.
    pub read_ports: usize,
    /// Number of write ports.
    pub write_ports: usize,
    /// Register rename map: architectural → physical mapping.
    rename_map: Vec<Option<usize>>,
    /// Free list of available physical registers.
    free_list: Vec<usize>,
    /// Whether each physical register is busy.
    busy: Vec<bool>,
    /// Read port availability per cycle.
    read_port_busy: Vec<bool>,
    /// Write port availability per cycle.
    write_port_busy: Vec<bool>,
}

impl RegisterFile {
    pub fn new(num_regs: usize, read_ports: usize, write_ports: usize) -> Self {
        let mut free_list = Vec::with_capacity(num_regs);
        for i in 0..num_regs {
            free_list.push(i);
        }
        RegisterFile {
            num_registers: num_regs,
            register_width: 64,
            read_ports,
            write_ports,
            rename_map: vec![None; 32], // architectural regs
            free_list,
            busy: vec![false; num_regs],
            read_port_busy: vec![false; read_ports],
            write_port_busy: vec![false; write_ports],
        }
    }

    /// Allocate a physical register for an architectural destination.
    pub fn rename_dest(&mut self, arch_reg: usize) -> Option<usize> {
        if let Some(phys) = self.free_list.pop() {
            self.rename_map[arch_reg] = Some(phys);
            self.busy[phys] = true;
            Some(phys)
        } else {
            None
        }
    }

    /// Look up the physical register for an architectural source.
    pub fn lookup_src(&self, arch_reg: usize) -> Option<usize> {
        if arch_reg < self.rename_map.len() {
            self.rename_map[arch_reg]
        } else {
            None
        }
    }

    /// Free a physical register when it's no longer needed.
    pub fn free_register(&mut self, phys_reg: usize) {
        if phys_reg < self.busy.len() && self.busy[phys_reg] {
            self.busy[phys_reg] = false;
            self.free_list.push(phys_reg);
        }
    }

    /// Check if a read port is available.
    pub fn can_read(&self) -> bool {
        self.read_port_busy.iter().any(|b| !b)
    }

    /// Reserve a read port for this cycle.
    pub fn reserve_read_port(&mut self) -> Option<usize> {
        for (i, busy) in self.read_port_busy.iter_mut().enumerate() {
            if !*busy {
                *busy = true;
                return Some(i);
            }
        }
        None
    }

    /// Check if a write port is available.
    pub fn can_write(&self) -> bool {
        self.write_port_busy.iter().any(|b| !b)
    }

    /// Reserve a write port for this cycle.
    pub fn reserve_write_port(&mut self) -> Option<usize> {
        for (i, busy) in self.write_port_busy.iter_mut().enumerate() {
            if !*busy {
                *busy = true;
                return Some(i);
            }
        }
        None
    }

    /// Advance one cycle (clear port reservations).
    pub fn advance_cycle(&mut self) {
        for b in &mut self.read_port_busy {
            *b = false;
        }
        for b in &mut self.write_port_busy {
            *b = false;
        }
    }

    /// Get the number of free physical registers.
    pub fn free_count(&self) -> usize {
        self.free_list.len()
    }
}

// ============================================================================
// Memory Dependency Analysis
// ============================================================================

/// Tracks memory dependencies between loads and stores.
pub struct MemoryDependencyAnalyzer {
    /// Known store addresses (for alias analysis).
    store_addresses: Vec<(usize, u64)>,
    /// Unknown store addresses (conservative aliasing).
    unknown_stores: usize,
    /// Record of recent memory operations.
    recent_ops: Vec<MemOp>,
}

#[derive(Debug, Clone)]
struct MemOp {
    /// Instruction index.
    inst_idx: usize,
    /// Memory address (0 if unknown).
    address: u64,
    /// Size of the memory access.
    size: u32,
    /// Whether this is a load or store.
    is_store: bool,
}

impl MemoryDependencyAnalyzer {
    pub fn new() -> Self {
        MemoryDependencyAnalyzer {
            store_addresses: Vec::new(),
            unknown_stores: 0,
            recent_ops: Vec::new(),
        }
    }

    /// Record a store operation.
    pub fn record_store(&mut self, inst_idx: usize, addr: u64, size: u32) {
        if addr == 0 {
            // Unknown address: conservatively aliases everything.
            self.unknown_stores += 1;
        } else {
            self.store_addresses.push((inst_idx, addr));
        }
        self.recent_ops.push(MemOp {
            inst_idx,
            address: addr,
            size,
            is_store: true,
        });
    }

    /// Record a load operation.
    pub fn record_load(&mut self, inst_idx: usize, addr: u64, size: u32) {
        self.recent_ops.push(MemOp {
            inst_idx,
            address: addr,
            size,
            is_store: false,
        });
    }

    /// Check if a load at `addr` can alias with any prior store.
    /// Returns the index of the latest aliasing store, if any.
    pub fn find_aliasing_store(&self, addr: u64, size: u32) -> Option<usize> {
        // Conservative: unknown stores alias everything.
        if self.unknown_stores > 0 {
            return Some(0);
        }
        for &(inst_idx, store_addr) in self.store_addresses.iter().rev() {
            if addresses_overlap(addr, size, store_addr, 8) {
                return Some(inst_idx);
            }
        }
        None
    }

    /// Clear all recorded operations.
    pub fn reset(&mut self) {
        self.store_addresses.clear();
        self.unknown_stores = 0;
        self.recent_ops.clear();
    }
}

fn addresses_overlap(a1: u64, s1: u32, a2: u64, s2: u32) -> bool {
    let end1 = a1.saturating_add(s1 as u64);
    let end2 = a2.saturating_add(s2 as u64);
    a1 < end2 && a2 < end1
}

// ============================================================================
// Load/Store Queue Simulation
// ============================================================================

/// Simulates a load queue and store queue for out-of-order memory execution.
pub struct LoadStoreQueue {
    /// Load queue entries.
    load_queue: Vec<LSQEntry>,
    /// Store queue entries.
    store_queue: Vec<LSQEntry>,
    /// Maximum load queue size.
    load_queue_size: usize,
    /// Maximum store queue size.
    store_queue_size: usize,
    /// Whether store-to-load forwarding is enabled.
    forwarding_enabled: bool,
}

#[derive(Debug, Clone)]
struct LSQEntry {
    /// Instruction index.
    inst_idx: usize,
    /// Memory address.
    address: u64,
    /// Access size.
    size: u32,
    /// Whether this entry is valid.
    valid: bool,
    /// Data (for stores).
    data: u64,
}

impl LoadStoreQueue {
    pub fn new(ldq_size: usize, stq_size: usize) -> Self {
        LoadStoreQueue {
            load_queue: Vec::new(),
            store_queue: Vec::new(),
            load_queue_size: ldq_size,
            store_queue_size: stq_size,
            forwarding_enabled: true,
        }
    }

    /// Try to enqueue a load. Returns false if the load queue is full.
    pub fn enqueue_load(&mut self, inst_idx: usize, addr: u64, size: u32) -> bool {
        if self.load_queue.len() >= self.load_queue_size {
            return false; // load queue full → stall
        }
        self.load_queue.push(LSQEntry {
            inst_idx,
            address: addr,
            size,
            valid: true,
            data: 0,
        });
        true
    }

    /// Try to enqueue a store. Returns false if the store queue is full.
    pub fn enqueue_store(&mut self, inst_idx: usize, addr: u64, size: u32, data: u64) -> bool {
        if self.store_queue.len() >= self.store_queue_size {
            return false; // store queue full → stall
        }
        self.store_queue.push(LSQEntry {
            inst_idx,
            address: addr,
            size,
            valid: true,
            data,
        });
        true
    }

    /// Check if store-to-load forwarding is possible.
    pub fn can_forward(&self, load_addr: u64, load_size: u32) -> Option<u64> {
        if !self.forwarding_enabled {
            return None;
        }
        for entry in self.store_queue.iter().rev() {
            if entry.valid && entry.address == load_addr && entry.size >= load_size {
                return Some(entry.data);
            }
        }
        None
    }

    /// Retire the oldest load.
    pub fn retire_load(&mut self) {
        if !self.load_queue.is_empty() {
            self.load_queue.remove(0);
        }
    }

    /// Retire the oldest store.
    pub fn retire_store(&mut self) {
        if !self.store_queue.is_empty() {
            self.store_queue.remove(0);
        }
    }

    /// Check if the load queue has available capacity.
    pub fn load_queue_available(&self) -> bool {
        self.load_queue.len() < self.load_queue_size
    }

    /// Check if the store queue has available capacity.
    pub fn store_queue_available(&self) -> bool {
        self.store_queue.len() < self.store_queue_size
    }

    /// Reset all queues.
    pub fn reset(&mut self) {
        self.load_queue.clear();
        self.store_queue.clear();
    }
}

// ============================================================================
// Branch Predictor — simple bimodal with 2-bit saturating counter
// ============================================================================

/// Simple bimodal branch predictor using a table of 2-bit saturating counters.
pub struct BranchPredictor {
    /// Pattern History Table: 2-bit counters indexed by PC.
    pht: Vec<u8>,
    /// PHT index mask.
    index_mask: usize,
    /// Number of correct predictions.
    correct: u64,
    /// Number of mispredictions.
    mispredicts: u64,
}

impl BranchPredictor {
    /// Create a new branch predictor with `entries` PHT entries.
    pub fn new(entries: usize) -> Self {
        assert!(entries.is_power_of_two());
        BranchPredictor {
            pht: vec![2; entries], // start weakly taken
            index_mask: entries - 1,
            correct: 0,
            mispredicts: 0,
        }
    }

    /// Predict whether a branch at `pc` will be taken.
    /// Returns true if predicted taken.
    pub fn predict(&self, pc: u64) -> bool {
        let idx = self.get_index(pc);
        let counter = self.pht[idx];
        counter >= 2 // 2 or 3 = taken
    }

    /// Update the predictor with the actual outcome.
    pub fn update(&mut self, pc: u64, taken: bool) {
        let idx = self.get_index(pc);
        let was_predicted = self.pht[idx] >= 2;
        if was_predicted == taken {
            self.correct += 1;
        } else {
            self.mispredicts += 1;
        }
        // 2-bit saturating counter update
        if taken {
            self.pht[idx] = (self.pht[idx] + 1).min(3);
        } else {
            self.pht[idx] = self.pht[idx].saturating_sub(1);
        }
    }

    fn get_index(&self, pc: u64) -> usize {
        ((pc >> 2) as usize) & self.index_mask
    }

    /// Get prediction accuracy as a percentage.
    pub fn accuracy(&self) -> f64 {
        let total = self.correct + self.mispredicts;
        if total == 0 {
            return 100.0;
        }
        self.correct as f64 / total as f64 * 100.0
    }

    /// Get total predictions made.
    pub fn total_predictions(&self) -> u64 {
        self.correct + self.mispredicts
    }

    /// Reset predictor state.
    pub fn reset(&mut self) {
        self.pht.fill(2);
        self.correct = 0;
        self.mispredicts = 0;
    }
}

// ============================================================================
// Instruction Iteration and Iterative Refinement
// ============================================================================

/// Iterates over a sequence of instructions for repeated simulation passes.
pub struct InstructionIterator<'a> {
    /// The instruction sequence.
    instructions: &'a [MCInst],
    /// Current position.
    pos: usize,
    /// Total iterations performed.
    iterations: usize,
    /// Maximum iterations.
    max_iterations: usize,
}

impl<'a> InstructionIterator<'a> {
    pub fn new(instructions: &'a [MCInst], max_iters: usize) -> Self {
        InstructionIterator {
            instructions,
            pos: 0,
            iterations: 0,
            max_iterations: max_iters,
        }
    }

    /// Get the next instruction, wrapping around if needed.
    pub fn next(&mut self) -> Option<&'a MCInst> {
        if self.pos >= self.instructions.len() {
            if self.iterations + 1 >= self.max_iterations {
                return None;
            }
            self.pos = 0;
            self.iterations += 1;
        }
        let inst = &self.instructions[self.pos];
        self.pos += 1;
        Some(inst)
    }

    /// Reset to the beginning.
    pub fn reset(&mut self) {
        self.pos = 0;
        self.iterations = 0;
    }

    /// Current iteration number.
    pub fn current_iteration(&self) -> usize {
        self.iterations
    }

    /// Total instructions processed so far.
    pub fn total_processed(&self) -> usize {
        self.iterations * self.instructions.len() + self.pos
    }
}

/// Iterative refinement: repeatedly simulate the pipeline, adjusting
/// resource pressure estimates until they converge.
pub struct IterativeRefinement {
    /// Maximum refinement iterations.
    max_iterations: usize,
    /// Convergence threshold for resource pressure (percentage change).
    convergence_threshold: f64,
    /// Resource pressure history.
    pressure_history: Vec<Vec<f64>>,
}

impl IterativeRefinement {
    pub fn new() -> Self {
        IterativeRefinement {
            max_iterations: 10,
            convergence_threshold: 0.01, // 1%
            pressure_history: Vec::new(),
        }
    }

    /// Check if the resource pressure has converged.
    pub fn has_converged(&self) -> bool {
        if self.pressure_history.len() < 2 {
            return false;
        }
        let prev = self.pressure_history.last().unwrap();
        let prev_prev = self
            .pressure_history
            .get(self.pressure_history.len() - 2)
            .unwrap();
        let max_change = prev
            .iter()
            .zip(prev_prev.iter())
            .map(|(a, b)| (a - b).abs())
            .fold(0.0f64, f64::max);
        max_change < self.convergence_threshold
    }

    /// Record a resource pressure snapshot.
    pub fn record_pressure(&mut self, pressure: Vec<f64>) {
        self.pressure_history.push(pressure);
    }

    /// Get the number of refinement iterations done.
    pub fn iteration_count(&self) -> usize {
        self.pressure_history.len()
    }

    /// Check if maximum iterations reached.
    pub fn max_iterations_reached(&self) -> bool {
        self.pressure_history.len() >= self.max_iterations
    }

    /// Reset the refinement state.
    pub fn reset(&mut self) {
        self.pressure_history.clear();
    }
}

// ============================================================================
// Enhanced LLVMMCA with Register File and Branch Prediction
// ============================================================================

impl LLVMMCA {
    /// Run simulation with a modeled register file and branch predictor.
    pub fn run_with_microarchitecture(
        &mut self,
        reg_file: &mut RegisterFile,
        predictor: &mut BranchPredictor,
        lsq: &mut LoadStoreQueue,
    ) -> MCAnalysisResult {
        let instructions = self.parse_source();
        let mut total_cycles = 0;
        let mut dispatch_stalls = 0;
        let mut issue_stalls = 0;

        for _iter in 0..self.iterations {
            for (idx, inst) in instructions.iter().enumerate() {
                // Model register reads
                if !reg_file.can_read() {
                    issue_stalls += 1;
                    total_cycles += 1;
                    reg_file.advance_cycle();
                }
                reg_file.reserve_read_port();

                // Model register write
                if !reg_file.can_write() {
                    dispatch_stalls += 1;
                    total_cycles += 1;
                    reg_file.advance_cycle();
                }
                reg_file.reserve_write_port();

                // Model branch prediction
                if inst.mnemonic.contains("br") || inst.mnemonic.contains("jmp") {
                    let pc = idx as u64;
                    let _predicted = predictor.predict(pc);
                    predictor.update(pc, true); // assume taken for simulation
                }

                // Model LSQ
                if inst.mnemonic.contains("load") {
                    if !lsq.load_queue_available() {
                        dispatch_stalls += 1;
                    }
                    lsq.enqueue_load(idx, idx as u64 * 8, 8);
                }
                if inst.mnemonic.contains("store") {
                    if !lsq.store_queue_available() {
                        dispatch_stalls += 1;
                    }
                    lsq.enqueue_store(idx, idx as u64 * 8, 8, 0);
                }

                total_cycles += 1;
                reg_file.advance_cycle();
            }
        }

        MCAnalysisResult {
            total_cycles,
            instructions: instructions.len(),
            ipc: if total_cycles > 0 {
                instructions.len() as f64 / total_cycles as f64
            } else {
                0.0
            },
            dispatch_stalls,
            issue_stalls,
            resource_pressure: HashMap::new(),
            timeline: Vec::new(),
        }
    }

    /// Run with iterative refinement until convergence or max iterations.
    pub fn run_with_refinement(
        &mut self,
        refinement: &mut IterativeRefinement,
    ) -> MCAnalysisResult {
        let mut result = self.run();
        let pressure: Vec<f64> = result.resource_pressure.iter().map(|(_, &p)| p).collect();
        refinement.record_pressure(pressure);

        while !refinement.has_converged() && !refinement.max_iterations_reached() {
            result = self.run();
            let pressure: Vec<f64> = result.resource_pressure.iter().map(|(_, &p)| p).collect();
            refinement.record_pressure(pressure);
        }

        result
    }
}

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

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

    fn simple_asm() -> &'static str {
        "add r0, r1, r2\nadd r3, r0, r4\nmul r5, r3, r6\n"
    }

    fn loop_asm() -> &'static str {
        "add r0, r1, r2\nsub r3, r4, r5\nmul r6, r0, r3\n"
    }

    #[test]
    fn test_create_mca() {
        let mca = LLVMMCA::new("add r0, r1, r2");
        assert_eq!(mca.iterations, 100);
    }

    #[test]
    fn test_set_iterations() {
        let mut mca = LLVMMCA::new("add r0, r1, r2");
        mca.set_iterations(500);
        assert_eq!(mca.iterations, 500);
    }

    #[test]
    fn test_parse_empty_source() {
        let mca = LLVMMCA::new("");
        let insts = mca.parse_source();
        assert!(insts.is_empty());
    }

    #[test]
    fn test_parse_simple_source() {
        let mca = LLVMMCA::new(simple_asm());
        let insts = mca.parse_source();
        assert_eq!(insts.len(), 3);
        assert_eq!(insts[0].mnemonic, "add");
        assert_eq!(insts[1].mnemonic, "add");
        assert_eq!(insts[2].mnemonic, "mul");
    }

    #[test]
    fn test_parse_comments() {
        let source = "# This is a comment\nadd r0, r1, r2\n; Another comment\n";
        let mca = LLVMMCA::new(source);
        let insts = mca.parse_source();
        assert_eq!(insts.len(), 1);
    }

    #[test]
    fn test_get_instruction_info_add() {
        let mca = LLVMMCA::new("");
        let (latency, ports, uops, writes) = mca.get_instruction_info("add");
        assert_eq!(latency, 1);
        assert_eq!(uops, 1);
        assert!(writes);
    }

    #[test]
    fn test_get_instruction_info_mul() {
        let mca = LLVMMCA::new("");
        let (latency, _, uops, _) = mca.get_instruction_info("mul");
        assert_eq!(latency, 3);
        assert_eq!(uops, 1);
    }

    #[test]
    fn test_get_instruction_info_div() {
        let mca = LLVMMCA::new("");
        let (latency, _, _, _) = mca.get_instruction_info("div");
        assert_eq!(latency, 20);
    }

    #[test]
    fn test_get_instruction_info_unknown() {
        let mca = LLVMMCA::new("");
        let (latency, _, uops, _) = mca.get_instruction_info("unknown_op");
        assert_eq!(latency, 1);
        assert_eq!(uops, 1);
    }

    #[test]
    fn test_compute_critical_path_empty() {
        let mca = LLVMMCA::new("");
        let path = mca.compute_critical_path(&[]);
        assert_eq!(path, 0);
    }

    #[test]
    fn test_compute_critical_path_simple() {
        let mca = LLVMMCA::new("");
        let insts = mca.parse_source();
        let path = mca.compute_critical_path(&insts);
        // r0 → r3 → r5 chain: 1 + 1 + 3 = 5 cycles
        if insts.len() == 3 {
            assert_eq!(path, 5);
        }
    }

    #[test]
    fn test_compute_resource_pressure_empty() {
        let mca = LLVMMCA::new("");
        let pressure = mca.compute_resource_pressure(&[]);
        // Should have entries for all ports (initialized to 0.0)
        assert!(pressure.contains_key("Port0"));
    }

    #[test]
    fn test_simulate_pipeline_empty() {
        let mca = LLVMMCA::new("");
        let result = mca.simulate_pipeline(&[]);
        assert_eq!(result.total_cycles, 0);
        assert_eq!(result.instructions, 0);
        assert_eq!(result.ipc, 0.0);
    }

    #[test]
    fn test_simulate_pipeline_simple() {
        let mca = LLVMMCA::new(simple_asm());
        let insts = mca.parse_source();
        let result = mca.simulate_pipeline(&insts);
        assert!(result.total_cycles > 0);
        assert_eq!(result.instructions, 3);
        assert!(result.ipc > 0.0);
        assert!(!result.timeline.is_empty());
    }

    #[test]
    fn test_print_report() {
        let mca = LLVMMCA::new(simple_asm());
        let insts = mca.parse_source();
        let result = mca.simulate_pipeline(&insts);
        let report = mca.print_report(&result);
        assert!(report.contains("LLVM MCA Analysis Report"));
        assert!(report.contains("IPC:"));
        assert!(report.contains("Resource Pressure"));
    }

    #[test]
    fn test_run_full_pipeline() {
        let mut mca = LLVMMCA::new(simple_asm());
        let result = mca.run();
        assert!(result.instructions > 0);
        assert!(result.total_cycles > 0);
    }

    #[test]
    fn test_run_with_loop_kernel() {
        let mut mca = LLVMMCA::new(loop_asm());
        mca.set_iterations(10);
        let result = mca.run();
        assert!(result.instructions > 0);
    }
}