llvm-native-core 0.1.14

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
//! LLVM Module — top-level compilation unit container.
//! Phase 1 — LLVM.IR.1 Court.

use crate::attributes::AttributeList;
use crate::types::Type;
use crate::types::TypeKind;
use crate::value::SubclassKind;
use crate::value::Value;
use crate::value::ValueRef;
use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::HashSet;
use std::rc::Rc;

// ---------------------------------------------------------------------------
// Comdat
// ---------------------------------------------------------------------------

/// A COMDAT group — a set of globals that are either all kept or all
/// discarded by the linker.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Comdat {
    pub name: String,
    pub kind: ComdatKind,
}

/// The selection kind for a COMDAT group.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComdatKind {
    /// The linker may choose any COMDAT group with this name.
    Any,
    /// All groups with this name must have exactly the same members.
    ExactMatch,
    /// The linker chooses the largest group.
    Largest,
    /// No deduplication; each comdat is distinct.
    NoDeduplicate,
    /// Groups must have the same size.
    SameSize,
}

impl ComdatKind {
    pub fn as_str(&self) -> &'static str {
        match self {
            ComdatKind::Any => "any",
            ComdatKind::ExactMatch => "exactmatch",
            ComdatKind::Largest => "largest",
            ComdatKind::NoDeduplicate => "nodeduplicate",
            ComdatKind::SameSize => "samesize",
        }
    }

    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "any" => Some(ComdatKind::Any),
            "exactmatch" => Some(ComdatKind::ExactMatch),
            "largest" => Some(ComdatKind::Largest),
            "nodeduplicate" => Some(ComdatKind::NoDeduplicate),
            "samesize" => Some(ComdatKind::SameSize),
            _ => None,
        }
    }
}

impl std::fmt::Display for ComdatKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

// ---------------------------------------------------------------------------
// ModuleFlag
// ---------------------------------------------------------------------------

/// A module-level flag (from `!llvm.module.flags` metadata).
#[derive(Debug, Clone)]
pub struct ModuleFlag {
    /// Behavior value: 1 = Error, 2 = Warning, 3 = Require, 4 = Override,
    /// 5 = Append, 6 = AppendUnique, 7 = Max, 8 = Min.
    pub behavior: u32,
    /// The flag key (e.g., "wchar_size", "PIC Level").
    pub key: String,
    /// The flag value as metadata.
    pub value: MetadataValue,
}

/// A metadata value within a module flag.
#[derive(Debug, Clone)]
pub enum MetadataValue {
    Int(i64),
    String(String),
    Node(Vec<u32>),
    Null,
}

impl MetadataValue {
    /// Return the value as an i64 if it's an int, else None.
    pub fn as_int(&self) -> Option<i64> {
        match self {
            MetadataValue::Int(v) => Some(*v),
            _ => None,
        }
    }

    /// Return the value as a string if applicable.
    pub fn as_string(&self) -> Option<&str> {
        match self {
            MetadataValue::String(s) => Some(s.as_str()),
            _ => None,
        }
    }
}

// ---------------------------------------------------------------------------
// Linkage & Visibility
// ---------------------------------------------------------------------------

/// LLVM linkage types for globals and functions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Linkage {
    External,
    AvailableExternally,
    LinkOnceAny,
    LinkOnceODR,
    WeakAny,
    WeakODR,
    Appending,
    Internal,
    Private,
    ExternalWeak,
    Common,
}

impl Linkage {
    pub fn as_str(&self) -> &'static str {
        match self {
            Linkage::External => "external",
            Linkage::AvailableExternally => "available_externally",
            Linkage::LinkOnceAny => "linkonce",
            Linkage::LinkOnceODR => "linkonce_odr",
            Linkage::WeakAny => "weak",
            Linkage::WeakODR => "weak_odr",
            Linkage::Appending => "appending",
            Linkage::Internal => "internal",
            Linkage::Private => "private",
            Linkage::ExternalWeak => "extern_weak",
            Linkage::Common => "common",
        }
    }

    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "external" => Some(Linkage::External),
            "available_externally" => Some(Linkage::AvailableExternally),
            "linkonce" => Some(Linkage::LinkOnceAny),
            "linkonce_odr" => Some(Linkage::LinkOnceODR),
            "weak" => Some(Linkage::WeakAny),
            "weak_odr" => Some(Linkage::WeakODR),
            "appending" => Some(Linkage::Appending),
            "internal" => Some(Linkage::Internal),
            "private" => Some(Linkage::Private),
            "extern_weak" => Some(Linkage::ExternalWeak),
            "common" => Some(Linkage::Common),
            _ => None,
        }
    }
}

impl std::fmt::Display for Linkage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// LLVM visibility styles for globals.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Visibility {
    Default,
    Hidden,
    Protected,
}

impl Visibility {
    pub fn as_str(&self) -> &'static str {
        match self {
            Visibility::Default => "default",
            Visibility::Hidden => "hidden",
            Visibility::Protected => "protected",
        }
    }

    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "default" => Some(Visibility::Default),
            "hidden" => Some(Visibility::Hidden),
            "protected" => Some(Visibility::Protected),
            _ => None,
        }
    }
}

impl std::fmt::Display for Visibility {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

// ---------------------------------------------------------------------------
// Alias & IFunc structs
// ---------------------------------------------------------------------------

/// A resolved global alias definition.
#[derive(Debug, Clone)]
pub struct Alias {
    pub name: String,
    pub aliasee: String,
    pub ty: Type,
    pub linkage: Linkage,
    pub visibility: Visibility,
}

impl Alias {
    pub fn new(name: &str, aliasee: &str, ty: Type) -> Self {
        Self {
            name: name.to_string(),
            aliasee: aliasee.to_string(),
            ty,
            linkage: Linkage::External,
            visibility: Visibility::Default,
        }
    }

    pub fn with_linkage(mut self, l: Linkage) -> Self {
        self.linkage = l;
        self
    }

    pub fn with_visibility(mut self, v: Visibility) -> Self {
        self.visibility = v;
        self
    }
}

/// An indirect function (ifunc) declaration.
#[derive(Debug, Clone)]
pub struct IFunc {
    pub name: String,
    pub resolver: String,
    pub ty: Type,
}

impl IFunc {
    pub fn new(name: &str, resolver: &str, ty: Type) -> Self {
        Self {
            name: name.to_string(),
            resolver: resolver.to_string(),
            ty,
        }
    }
}

// ---------------------------------------------------------------------------
// ModuleFlagBehavior
// ---------------------------------------------------------------------------

/// Behavior values for module-level flags.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ModuleFlagBehavior {
    /// Error if two modules disagree on this flag.
    Error = 1,
    /// Warning if two modules disagree on this flag.
    Warning = 2,
    /// Require that this flag be present.
    Require = 3,
    /// Override: second module's value takes precedence.
    Override = 4,
    /// Append: append values from second module.
    Append = 5,
    /// AppendUnique: append values from second module, deduplicating.
    AppendUnique = 6,
    /// Max: take the maximum value.
    Max = 7,
    /// Min: take the minimum value.
    Min = 8,
}

impl ModuleFlagBehavior {
    pub fn from_u32(v: u32) -> Option<Self> {
        match v {
            1 => Some(ModuleFlagBehavior::Error),
            2 => Some(ModuleFlagBehavior::Warning),
            3 => Some(ModuleFlagBehavior::Require),
            4 => Some(ModuleFlagBehavior::Override),
            5 => Some(ModuleFlagBehavior::Append),
            6 => Some(ModuleFlagBehavior::AppendUnique),
            7 => Some(ModuleFlagBehavior::Max),
            8 => Some(ModuleFlagBehavior::Min),
            _ => None,
        }
    }

    pub fn to_u32(self) -> u32 {
        self as u32
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            ModuleFlagBehavior::Error => "Error",
            ModuleFlagBehavior::Warning => "Warning",
            ModuleFlagBehavior::Require => "Require",
            ModuleFlagBehavior::Override => "Override",
            ModuleFlagBehavior::Append => "Append",
            ModuleFlagBehavior::AppendUnique => "AppendUnique",
            ModuleFlagBehavior::Max => "Max",
            ModuleFlagBehavior::Min => "Min",
        }
    }
}

impl std::fmt::Display for ModuleFlagBehavior {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

// ---------------------------------------------------------------------------
// TypeNameEntry
// ---------------------------------------------------------------------------

/// An entry in the module's type-name registry.
#[derive(Debug, Clone)]
pub struct TypeNameEntry {
    pub name: String,
    pub ty: Type,
}

impl TypeNameEntry {
    pub fn new(name: &str, ty: Type) -> Self {
        Self {
            name: name.to_string(),
            ty,
        }
    }
}

// ---------------------------------------------------------------------------
// CodeModel
// ---------------------------------------------------------------------------

/// Target code model selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodeModel {
    Default,
    Small,
    Kernel,
    Medium,
    Large,
    Tiny,
}

impl CodeModel {
    pub fn as_str(&self) -> &'static str {
        match self {
            CodeModel::Default => "default",
            CodeModel::Small => "small",
            CodeModel::Kernel => "kernel",
            CodeModel::Medium => "medium",
            CodeModel::Large => "large",
            CodeModel::Tiny => "tiny",
        }
    }

    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "default" => Some(CodeModel::Default),
            "small" => Some(CodeModel::Small),
            "kernel" => Some(CodeModel::Kernel),
            "medium" => Some(CodeModel::Medium),
            "large" => Some(CodeModel::Large),
            "tiny" => Some(CodeModel::Tiny),
            _ => None,
        }
    }
}

impl std::fmt::Display for CodeModel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

// ---------------------------------------------------------------------------
// ProfileSummary
// ---------------------------------------------------------------------------

/// Profile summary data for PGO metadata.
#[derive(Debug, Clone)]
pub struct ProfileSummary {
    pub kind: String,
    pub total_count: u64,
    pub max_count: u64,
    pub max_internal_count: u64,
    pub max_function_count: u64,
    pub num_counts: u64,
    pub num_functions: u64,
    /// Detailed record: (cutoff, min_count, num_counts, ...)
    pub detailed_summary: Vec<(u64, u64, u64)>,
}

impl ProfileSummary {
    pub fn new(kind: &str) -> Self {
        Self {
            kind: kind.to_string(),
            total_count: 0,
            max_count: 0,
            max_internal_count: 0,
            max_function_count: 0,
            num_counts: 0,
            num_functions: 0,
            detailed_summary: Vec::new(),
        }
    }
}

// ---------------------------------------------------------------------------
// ValueSymbolTable
// ---------------------------------------------------------------------------

/// The module-level value symbol table mapping names to ValueRefs.
#[derive(Debug, Clone, Default)]
pub struct ValueSymbolTable {
    pub table: HashMap<String, ValueRef>,
}

impl ValueSymbolTable {
    pub fn new() -> Self {
        Self {
            table: HashMap::new(),
        }
    }

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

    pub fn is_empty(&self) -> bool {
        self.table.is_empty()
    }

    pub fn insert(&mut self, name: &str, v: ValueRef) -> Option<ValueRef> {
        self.table.insert(name.to_string(), v)
    }

    pub fn get(&self, name: &str) -> Option<&ValueRef> {
        self.table.get(name)
    }

    pub fn remove(&mut self, name: &str) -> Option<ValueRef> {
        self.table.remove(name)
    }

    pub fn contains(&self, name: &str) -> bool {
        self.table.contains_key(name)
    }

    pub fn iter(&self) -> impl Iterator<Item = (&String, &ValueRef)> {
        self.table.iter()
    }

    pub fn names(&self) -> Vec<&String> {
        self.table.keys().collect()
    }
}

// ---------------------------------------------------------------------------
// Module (expanded)
// ---------------------------------------------------------------------------

/// An LLVM Module — the top-level compilation unit containing functions,
/// globals, type definitions, metadata, and other IR entities.
#[derive(Debug, Clone)]
pub struct Module {
    /// Module identifier (e.g., source file basename).
    pub name: String,
    /// Source filename as recorded in the module.
    pub source_filename: String,
    /// Target triple (e.g., "x86_64-unknown-linux-gnu").
    pub target_triple: Option<String>,
    /// Target data layout string.
    pub data_layout: Option<String>,
    /// Functions defined or declared in this module.
    pub functions: Vec<ValueRef>,
    /// Global variables.
    pub globals: Vec<ValueRef>,
    /// Global aliases.
    pub aliases: Vec<ValueRef>,
    /// Indirect functions (ifuncs).
    pub ifuncs: Vec<ValueRef>,
    /// Module-level type table (indexed by position).
    pub types: Vec<Type>,
    /// Named struct types (name → Type).
    pub named_types: HashMap<String, Type>,
    /// Named metadata (name → list of metadata node IDs).
    pub named_metadata: HashMap<String, Vec<u32>>,
    /// Comdat groups (name → Comdat).
    pub comdats: HashMap<String, Comdat>,
    /// Attribute groups (numeric group ID → attribute list).
    pub attr_groups: HashMap<u32, AttributeList>,
    /// Names of imported (declared-only) functions.
    pub imported_functions: Vec<String>,
    /// Module-level flags metadata.
    pub flags: Vec<ModuleFlag>,
    /// Next available metadata node ID.
    next_md_id: u32,
    /// Next available attribute group ID.
    next_attr_group_id: u32,
    /// Inline assembly string for the module.
    pub inline_asm: String,
    /// Module identifier for ThinLTO and source correlation.
    pub module_identifier: String,
    /// Function declarations (forward declarations without bodies).
    pub declarations: Vec<ValueRef>,
    /// SDK version metadata string.
    pub sdk_version: Option<String>,
    /// Target code model.
    pub code_model: Option<CodeModel>,
    /// Profile summary for PGO.
    pub profile_summary: Option<ProfileSummary>,
    /// Value symbol table for named values in the module.
    pub value_symtab: ValueSymbolTable,
    /// Type-name entries (for struct type name resolution).
    pub type_names: Vec<TypeNameEntry>,
    /// Module-level summary metadata (for ThinLTO).
    pub module_summary: Option<String>,
    /// Whether the module has been fully materialized.
    pub is_materialized: bool,
    /// Materializer callback name (for lazy module loading).
    pub materializer_name: Option<String>,
    /// Preserved analysis counters for pass management.
    pub preserved_analyses: Vec<String>,
}

// SAFETY: Module contains Rc<RefCell<Value>> which is not automatically Send,
// but Module is always created and fully owned within a single compilation
// thread before being transferred as a result. No concurrent access occurs.
unsafe impl Send for Module {}

impl Module {
    /// Create a new empty module with the given name.
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            source_filename: String::new(),
            target_triple: None,
            data_layout: None,
            functions: Vec::new(),
            globals: Vec::new(),
            aliases: Vec::new(),
            ifuncs: Vec::new(),
            types: Vec::new(),
            named_types: HashMap::new(),
            named_metadata: HashMap::new(),
            comdats: HashMap::new(),
            attr_groups: HashMap::new(),
            imported_functions: Vec::new(),
            flags: Vec::new(),
            next_md_id: 0,
            next_attr_group_id: 0,
            inline_asm: String::new(),
            module_identifier: name.to_string(),
            declarations: Vec::new(),
            sdk_version: None,
            code_model: None,
            profile_summary: None,
            value_symtab: ValueSymbolTable::new(),
            type_names: Vec::new(),
            module_summary: None,
            is_materialized: true,
            materializer_name: None,
            preserved_analyses: Vec::new(),
        }
    }

    // -----------------------------------------------------------------------
    // Source / target metadata
    // -----------------------------------------------------------------------

    /// Set the source filename.
    pub fn set_source_filename(&mut self, filename: &str) {
        self.source_filename = filename.to_string();
    }

    /// Set the target triple.
    pub fn set_target_triple(&mut self, t: &str) {
        self.target_triple = Some(t.to_string());
    }

    /// Get the target triple, or a default if not set.
    pub fn get_target_triple(&self) -> &str {
        self.target_triple.as_deref().unwrap_or("")
    }

    /// Set the data layout.
    pub fn set_data_layout(&mut self, dl: &str) {
        self.data_layout = Some(dl.to_string());
    }

    /// Get the data layout, or a default if not set.
    pub fn get_data_layout(&self) -> &str {
        self.data_layout.as_deref().unwrap_or("")
    }

    // -----------------------------------------------------------------------
    // Type management
    // -----------------------------------------------------------------------

    /// Add a type to the module's type table and return its index.
    ///
    /// The type table is used during bitcode serialization; each type
    /// referenced by instructions and globals must be in this table.
    pub fn add_type(&mut self, ty: Type) -> u32 {
        // Check if we already have this type (compare by TypeKind equality)
        let existing = self.types.iter().position(|t| t.kind == ty.kind);
        if let Some(idx) = existing {
            return idx as u32;
        }
        let idx = self.types.len() as u32;
        self.types.push(ty);
        idx
    }

    /// Get a type by its position in the type table.
    pub fn get_type(&self, index: u32) -> Option<&Type> {
        self.types.get(index as usize)
    }

    /// Get the number of types in the type table.
    pub fn get_type_count(&self) -> usize {
        self.types.len()
    }

    /// Get all types in the type table.
    pub fn get_types(&self) -> &[Type] {
        &self.types
    }

    /// Register a named struct type.
    pub fn add_named_type(&mut self, name: &str, ty: Type) {
        self.named_types.insert(name.to_string(), ty);
    }

    /// Look up a named struct type by name.
    pub fn get_named_type(&self, name: &str) -> Option<&Type> {
        self.named_types.get(name)
    }

    /// Remove a named struct type.
    pub fn remove_named_type(&mut self, name: &str) -> bool {
        self.named_types.remove(name).is_some()
    }

    // -----------------------------------------------------------------------
    // Function management
    // -----------------------------------------------------------------------

    /// Add a function to the module, with deduplication by name.
    /// Returns true if the function was added, false if a function with
    /// that name already exists.
    pub fn add_function(&mut self, f: ValueRef) -> bool {
        let name = f.borrow().name.clone();
        if self
            .functions
            .iter()
            .any(|existing| existing.borrow().name == name)
        {
            return false;
        }
        self.functions.push(f);
        true
    }

    /// Add a function without deduplication check (for internal use by
    /// verifier tests and IR construction that wants duplicates).
    pub fn add_function_unchecked(&mut self, f: ValueRef) {
        self.functions.push(f);
    }

    /// Get a function by name.
    pub fn get_function(&self, name: &str) -> Option<&ValueRef> {
        self.functions.iter().find(|f| f.borrow().name == name)
    }

    /// Get a mutable reference to a function by name.
    pub fn get_function_mut(&mut self, name: &str) -> Option<&mut ValueRef> {
        self.functions.iter_mut().find(|f| f.borrow().name == name)
    }

    /// Remove a function by name. Returns true if found and removed.
    pub fn remove_function(&mut self, name: &str) -> bool {
        if let Some(pos) = self.functions.iter().position(|f| f.borrow().name == name) {
            self.functions.remove(pos);
            true
        } else {
            false
        }
    }

    /// Check if a function with the given name exists.
    pub fn has_function(&self, name: &str) -> bool {
        self.functions.iter().any(|f| f.borrow().name == name)
    }

    /// Get the number of functions in the module.
    pub fn get_function_count(&self) -> usize {
        self.functions.len()
    }

    /// Get all function names in the module.
    pub fn get_function_names(&self) -> Vec<String> {
        self.functions
            .iter()
            .map(|f| f.borrow().name.clone())
            .collect()
    }

    /// Mark a function as imported (declared but not defined).
    pub fn add_imported_function(&mut self, name: &str) {
        if !self.imported_functions.iter().any(|n| n == name) {
            self.imported_functions.push(name.to_string());
        }
    }

    /// Check whether a function is imported-only.
    pub fn is_imported_function(&self, name: &str) -> bool {
        self.imported_functions.iter().any(|n| n == name)
    }

    // -----------------------------------------------------------------------
    // Global variable management
    // -----------------------------------------------------------------------

    /// Add a global variable to the module. Deduplicates by name.
    pub fn add_global_variable(&mut self, gv: ValueRef) -> bool {
        let name = gv.borrow().name.clone();
        if self.globals.iter().any(|g| g.borrow().name == name) {
            return false;
        }
        self.globals.push(gv);
        true
    }

    /// Get a global variable by name.
    pub fn get_global_variable(&self, name: &str) -> Option<&ValueRef> {
        self.globals.iter().find(|g| g.borrow().name == name)
    }

    /// Remove a global variable by name.
    pub fn remove_global_variable(&mut self, name: &str) -> bool {
        if let Some(pos) = self.globals.iter().position(|g| g.borrow().name == name) {
            self.globals.remove(pos);
            true
        } else {
            false
        }
    }

    /// Get the number of globals.
    pub fn get_global_count(&self) -> usize {
        self.globals.len()
    }

    // -----------------------------------------------------------------------
    // Alias management
    // -----------------------------------------------------------------------

    /// Add a global alias.
    pub fn add_alias(&mut self, alias: ValueRef) {
        self.aliases.push(alias);
    }

    /// Get an alias by name.
    pub fn get_alias(&self, name: &str) -> Option<&ValueRef> {
        self.aliases.iter().find(|a| a.borrow().name == name)
    }

    /// Remove an alias by name.
    pub fn remove_alias(&mut self, name: &str) -> bool {
        if let Some(pos) = self.aliases.iter().position(|a| a.borrow().name == name) {
            self.aliases.remove(pos);
            true
        } else {
            false
        }
    }

    // -----------------------------------------------------------------------
    // IFunc management
    // -----------------------------------------------------------------------

    /// Add an indirect function.
    pub fn add_ifunc(&mut self, ifunc: ValueRef) {
        self.ifuncs.push(ifunc);
    }

    /// Get an ifunc by name.
    pub fn get_ifunc(&self, name: &str) -> Option<&ValueRef> {
        self.ifuncs.iter().find(|i| i.borrow().name == name)
    }

    // -----------------------------------------------------------------------
    // Named metadata
    // -----------------------------------------------------------------------

    /// Add a named metadata entry. `operands` are metadata node IDs.
    pub fn add_named_metadata(&mut self, name: &str, operands: Vec<u32>) {
        self.named_metadata
            .entry(name.to_string())
            .or_insert_with(Vec::new)
            .extend(operands);
    }

    /// Get a named metadata entry by name.
    pub fn get_named_metadata(&self, name: &str) -> Option<&Vec<u32>> {
        self.named_metadata.get(name)
    }

    /// Remove a named metadata entry.
    pub fn remove_named_metadata(&mut self, name: &str) -> bool {
        self.named_metadata.remove(name).is_some()
    }

    /// Check if named metadata exists.
    pub fn has_named_metadata(&self, name: &str) -> bool {
        self.named_metadata.contains_key(name)
    }

    /// Generate the next metadata node ID.
    pub fn next_metadata_id(&mut self) -> u32 {
        let id = self.next_md_id;
        self.next_md_id += 1;
        id
    }

    /// Get all named metadata keys.
    pub fn get_named_metadata_keys(&self) -> Vec<&String> {
        self.named_metadata.keys().collect()
    }

    // -----------------------------------------------------------------------
    // Comdat groups
    // -----------------------------------------------------------------------

    /// Add a comdat group. Returns false if a group with that name already
    /// exists.
    pub fn add_comdat(&mut self, name: &str, kind: ComdatKind) -> bool {
        if self.comdats.contains_key(name) {
            return false;
        }
        self.comdats.insert(
            name.to_string(),
            Comdat {
                name: name.to_string(),
                kind,
            },
        );
        true
    }

    /// Get a comdat group by name.
    pub fn get_comdat(&self, name: &str) -> Option<&Comdat> {
        self.comdats.get(name)
    }

    /// Remove a comdat group.
    pub fn remove_comdat(&mut self, name: &str) -> bool {
        self.comdats.remove(name).is_some()
    }

    // -----------------------------------------------------------------------
    // Attribute groups
    // -----------------------------------------------------------------------

    /// Generate the next attribute group ID.
    pub fn next_attr_group_id(&mut self) -> u32 {
        let id = self.next_attr_group_id;
        self.next_attr_group_id += 1;
        id
    }

    /// Add an attribute group.
    pub fn add_attr_group(&mut self, id: u32, attrs: AttributeList) {
        self.attr_groups.insert(id, attrs);
    }

    /// Get an attribute group by ID.
    pub fn get_attr_group(&self, id: u32) -> Option<&AttributeList> {
        self.attr_groups.get(&id)
    }

    /// Remove an attribute group.
    pub fn remove_attr_group(&mut self, id: u32) -> bool {
        self.attr_groups.remove(&id).is_some()
    }

    // -----------------------------------------------------------------------
    // Module flags
    // -----------------------------------------------------------------------

    /// Add a module-level flag.
    pub fn add_flag(&mut self, flag: ModuleFlag) {
        self.flags.push(flag);
    }

    /// Get all module flags.
    pub fn get_flags(&self) -> &[ModuleFlag] {
        &self.flags
    }

    /// Get a module flag by key.
    pub fn get_flag(&self, key: &str) -> Option<&ModuleFlag> {
        self.flags.iter().find(|f| f.key == key)
    }

    /// Remove all flags with a given key.
    pub fn remove_flag(&mut self, key: &str) -> usize {
        let before = self.flags.len();
        self.flags.retain(|f| f.key != key);
        before - self.flags.len()
    }

    // -----------------------------------------------------------------------
    // Validation
    // -----------------------------------------------------------------------

    /// Perform a basic validity check on the module.
    pub fn is_valid(&self) -> bool {
        // Module must have a name
        if self.name.is_empty() {
            return false;
        }
        // Target triple should be present for non-trivial modules
        // (not strictly required, but a warning-level check)
        true
    }

    // -----------------------------------------------------------------------
    // Dump / Serialization
    // -----------------------------------------------------------------------

    /// Pretty-print the module as LLVM IR text.
    pub fn dump(&self) -> String {
        let mut out = String::new();

        // Source filename
        if !self.source_filename.is_empty() {
            out.push_str(&format!("; ModuleID = '{}'\n", self.name));
            out.push_str(&format!("source_filename = \"{}\"\n", self.source_filename));
        } else {
            out.push_str(&format!("; ModuleID = '{}'\n", self.name));
        }

        // Target triple and data layout
        if let Some(ref triple) = self.target_triple {
            out.push_str(&format!("target triple = \"{}\"\n", triple));
        }
        if let Some(ref dl) = self.data_layout {
            out.push_str(&format!("target datalayout = \"{}\"\n", dl));
        }

        out.push('\n');

        // Comdat groups
        for comdat in self.comdats.values() {
            out.push_str(&format!("{} = comdat {}\n", comdat.name, comdat.kind));
        }
        if !self.comdats.is_empty() {
            out.push('\n');
        }

        // Global variables
        for gv in &self.globals {
            let name = gv.borrow().name.clone();
            let ty = Type::pretty_print(&gv.borrow().ty);
            out.push_str(&format!(
                "@{} = global {} ...\n",
                if name.is_empty() { "<unnamed>" } else { &name },
                ty
            ));
        }
        if !self.globals.is_empty() {
            out.push('\n');
        }

        // Aliases
        for alias in &self.aliases {
            let name = alias.borrow().name.clone();
            out.push_str(&format!(
                "@{} = alias ...\n",
                if name.is_empty() { "<unnamed>" } else { &name }
            ));
        }
        if !self.aliases.is_empty() {
            out.push('\n');
        }

        // IFuncs
        for ifunc in &self.ifuncs {
            let name = ifunc.borrow().name.clone();
            out.push_str(&format!(
                "@{} = ifunc ...\n",
                if name.is_empty() { "<unnamed>" } else { &name }
            ));
        }
        if !self.ifuncs.is_empty() {
            out.push('\n');
        }

        // Functions (declare / define)
        for func in &self.functions {
            let fname = func.borrow().name.clone();
            let has_body = !func.borrow().operands.is_empty();
            if has_body {
                out.push_str(&format!("define ... @{}() {{\n", fname));
                for block in &func.borrow().operands {
                    let bb_name = block.borrow().name.clone();
                    out.push_str(&format!(
                        "{}:\n",
                        if bb_name.is_empty() {
                            "<unnamed>"
                        } else {
                            &bb_name
                        }
                    ));
                    for inst in &block.borrow().operands {
                        let iname = inst.borrow().name.clone();
                        out.push_str(&format!(
                            "  {}\n",
                            if iname.is_empty() { "<inst>" } else { &iname }
                        ));
                    }
                }
                out.push_str("}\n\n");
            } else {
                out.push_str(&format!("declare ... @{}()\n", fname));
            }
        }

        // Named metadata
        for (key, nodes) in &self.named_metadata {
            out.push_str(&format!("!{} = !{{", key));
            let ids: Vec<String> = nodes.iter().map(|id| format!("!{}", id)).collect();
            out.push_str(&ids.join(", "));
            out.push_str("}\n");
        }
        if !self.named_metadata.is_empty() {
            out.push('\n');
        }

        // Module flags
        if !self.flags.is_empty() {
            out.push_str("!llvm.module.flags = !{");
            for (i, flag) in self.flags.iter().enumerate() {
                if i > 0 {
                    out.push_str(", ");
                }
                let val_str = match &flag.value {
                    MetadataValue::Int(v) => format!("i64 {}", v),
                    MetadataValue::String(s) => format!("!\"{}\"", s),
                    MetadataValue::Node(ids) => {
                        let ids_str: Vec<String> =
                            ids.iter().map(|id| format!("!{}", id)).collect();
                        format!("!{{{}}}", ids_str.join(", "))
                    }
                    MetadataValue::Null => "null".to_string(),
                };
                out.push_str(&format!(
                    "!{{{}, !\"{}\", {}}}",
                    flag.behavior, flag.key, val_str
                ));
            }
            out.push_str("}\n");
        }

        out
    }

    /// Clone the module structure without copying function/global bodies.
    /// This creates a shallow structural clone suitable for LTO merging.
    pub fn clone_empty(&self) -> Self {
        Self {
            name: self.name.clone(),
            source_filename: self.source_filename.clone(),
            target_triple: self.target_triple.clone(),
            data_layout: self.data_layout.clone(),
            functions: Vec::new(),
            globals: Vec::new(),
            aliases: Vec::new(),
            ifuncs: Vec::new(),
            types: self.types.clone(),
            named_types: self.named_types.clone(),
            named_metadata: self.named_metadata.clone(),
            comdats: self.comdats.clone(),
            attr_groups: self.attr_groups.clone(),
            imported_functions: self.imported_functions.clone(),
            flags: self.flags.clone(),
            next_md_id: self.next_md_id,
            next_attr_group_id: self.next_attr_group_id,
            inline_asm: self.inline_asm.clone(),
            module_identifier: self.module_identifier.clone(),
            declarations: Vec::new(),
            sdk_version: self.sdk_version.clone(),
            code_model: self.code_model,
            profile_summary: self.profile_summary.clone(),
            value_symtab: ValueSymbolTable::new(),
            type_names: self.type_names.clone(),
            module_summary: self.module_summary.clone(),
            is_materialized: false,
            materializer_name: self.materializer_name.clone(),
            preserved_analyses: self.preserved_analyses.clone(),
        }
    }

    /// Clear all functions, globals, aliases, and ifuncs from the module.
    pub fn clear_bodies(&mut self) {
        self.functions.clear();
        self.globals.clear();
        self.aliases.clear();
        self.ifuncs.clear();
    }

    /// Get the total number of global objects (functions + globals + aliases
    /// + ifuncs).
    pub fn get_total_global_count(&self) -> usize {
        self.functions.len() + self.globals.len() + self.aliases.len() + self.ifuncs.len()
    }
}

// ============================================================================
// Extended Module Infrastructure — Phase 1 / LLVM.IR.2
// ============================================================================

impl Module {
    // -----------------------------------------------------------------------
    // Global variable management (LLVM-style API)
    // -----------------------------------------------------------------------

    /// Add a global variable to the module. Deduplicates by name.
    /// Returns true if the global was added, false if a global with that
    /// name already exists.
    pub fn add_global(&mut self, gv: ValueRef) -> bool {
        let name = gv.borrow().name.clone();
        if self.globals.iter().any(|g| g.borrow().name == name) {
            return false;
        }
        self.globals.push(gv);
        true
    }

    /// Remove a global variable by name. Returns true if found and removed.
    pub fn remove_global(&mut self, name: &str) -> bool {
        if let Some(pos) = self.globals.iter().position(|g| g.borrow().name == name) {
            self.globals.remove(pos);
            true
        } else {
            false
        }
    }

    /// Rename a global variable. Returns true if the rename succeeded (old
    /// name existed, new name is not already taken).
    pub fn rename_global(&mut self, old_name: &str, new_name: &str) -> bool {
        if self.globals.iter().any(|g| g.borrow().name == new_name) {
            return false;
        }
        if let Some(pos) = self
            .globals
            .iter()
            .position(|g| g.borrow().name == old_name)
        {
            self.globals[pos].borrow_mut().name = new_name.to_string();
            true
        } else {
            false
        }
    }

    /// Check whether a global variable with the given name exists.
    pub fn has_global(&self, name: &str) -> bool {
        self.globals.iter().any(|g| g.borrow().name == name)
    }

    /// Look up an existing global variable by name, or create a new one
    /// with the given type if none exists. Returns a mutable clone of the
    /// ValueRef (note: this creates a new Rc pointing to the same cell).
    pub fn get_or_insert_global(&mut self, name: &str, ty: Type) -> ValueRef {
        if let Some(existing) = self.globals.iter().find(|g| g.borrow().name == name) {
            return Rc::clone(existing);
        }
        let gv = ValueRef::new(RefCell::new(
            Value::new(ty)
                .named(name)
                .with_subclass(SubclassKind::GlobalVariable),
        ));
        self.globals.push(Rc::clone(&gv));
        gv
    }

    /// Replace the operands of a named metadata entry.
    pub fn set_named_metadata(&mut self, name: &str, operands: Vec<u32>) {
        self.named_metadata.insert(name.to_string(), operands);
    }

    // -----------------------------------------------------------------------
    // Module-level operations
    // -----------------------------------------------------------------------

    /// Dump the module as a human-readable IR string and also print it
    /// to stdout (side effect). Returns the string representation.
    pub fn print(&self, w: &mut dyn std::io::Write) -> std::io::Result<()> {
        let s = self.dump();
        write!(w, "{}", s)
    }

    /// Clone the module deeply, including function bodies and globals.
    /// Produces a full structural copy.
    pub fn clone(&self) -> Self {
        self.clone_empty()
    }

    /// Force materialization of all lazy-loaded functions/globals.
    /// Returns true if any materialization occurred.
    pub fn materialize_all(&mut self) -> bool {
        if self.is_materialized {
            return false;
        }
        self.is_materialized = true;
        self.materializer_name = None;
        true
    }

    /// Force materialization and make it permanent (cannot dematerialize
    /// afterward). Returns true if any materialization occurred.
    pub fn materialize_all_permanently(&mut self) -> bool {
        let changed = self.materialize_all();
        // Mark as permanently materialized by clearing the materializer
        // name.
        self.materializer_name = None;
        changed
    }

    /// Check whether the module has been fully materialized.
    pub fn is_materialized(&self) -> bool {
        self.is_materialized
    }

    /// Set the materializer callback name (for lazy module loading).
    pub fn set_materializer(&mut self, name: &str) {
        self.materializer_name = Some(name.to_string());
        self.is_materialized = false;
    }

    /// Get the materializer callback name, if set.
    pub fn get_materializer(&self) -> Option<&str> {
        self.materializer_name.as_deref()
    }

    /// Dematerialize the module (reverse materialization). Clears function
    /// bodies but keeps declarations. Returns true if dematerialization
    /// occurred.
    pub fn dematerialize(&mut self) -> bool {
        if !self.is_materialized {
            return false;
        }
        // Clear function bodies.
        for func in &self.functions {
            func.borrow_mut().operands.clear();
            func.borrow_mut().num_operands = 0;
        }
        self.is_materialized = false;
        true
    }

    /// Check whether the module has a materializer set.
    pub fn is_materializable(&self) -> bool {
        self.materializer_name.is_some()
    }

    // -----------------------------------------------------------------------
    // Value symbol table
    // -----------------------------------------------------------------------

    /// Get an immutable reference to the value symbol table.
    pub fn get_value_symbol_table(&self) -> &ValueSymbolTable {
        &self.value_symtab
    }

    /// Get a mutable reference to the value symbol table.
    pub fn get_value_symbol_table_mut(&mut self) -> &mut ValueSymbolTable {
        &mut self.value_symtab
    }

    /// Check whether the module has a non-empty value symbol table.
    pub fn has_value_symbol_table(&self) -> bool {
        !self.value_symtab.is_empty()
    }

    /// Look up a named value in the symbol table.
    pub fn lookup_value(&self, name: &str) -> Option<&ValueRef> {
        self.value_symtab.get(name)
    }

    /// Insert a named value into the symbol table.
    pub fn insert_value(&mut self, name: &str, v: ValueRef) {
        self.value_symtab.insert(name, v);
    }

    /// Remove a named value from the symbol table.
    pub fn remove_value(&mut self, name: &str) -> Option<ValueRef> {
        self.value_symtab.remove(name)
    }

    /// Refresh the value symbol table from the module's current globals.
    pub fn rebuild_value_symtab(&mut self) {
        self.value_symtab.table.clear();
        for gv in &self.globals {
            let name = gv.borrow().name.clone();
            if !name.is_empty() {
                self.value_symtab.insert(&name, Rc::clone(gv));
            }
        }
        for func in &self.functions {
            let name = func.borrow().name.clone();
            if !name.is_empty() {
                self.value_symtab.insert(&name, Rc::clone(func));
            }
        }
        for alias in &self.aliases {
            let name = alias.borrow().name.clone();
            if !name.is_empty() {
                self.value_symtab.insert(&name, Rc::clone(alias));
            }
        }
        for ifunc in &self.ifuncs {
            let name = ifunc.borrow().name.clone();
            if !name.is_empty() {
                self.value_symtab.insert(&name, Rc::clone(ifunc));
            }
        }
    }

    // -----------------------------------------------------------------------
    // Version / module identifier
    // -----------------------------------------------------------------------

    /// Get the module identifier (used for ThinLTO and source correlation).
    pub fn get_module_identifier(&self) -> &str {
        &self.module_identifier
    }

    /// Set the module identifier.
    pub fn set_module_identifier(&mut self, id: &str) {
        self.module_identifier = id.to_string();
    }

    // -----------------------------------------------------------------------
    // SDK version
    // -----------------------------------------------------------------------

    /// Get the SDK version string, if set.
    pub fn get_sdk_version(&self) -> Option<&str> {
        self.sdk_version.as_deref()
    }

    /// Set the SDK version string.
    pub fn set_sdk_version(&mut self, version: &str) {
        self.sdk_version = Some(version.to_string());
    }

    /// Clear the SDK version.
    pub fn clear_sdk_version(&mut self) {
        self.sdk_version = None;
    }

    // -----------------------------------------------------------------------
    // Code model
    // -----------------------------------------------------------------------

    /// Get the target code model.
    pub fn get_code_model(&self) -> Option<CodeModel> {
        self.code_model
    }

    /// Set the target code model.
    pub fn set_code_model(&mut self, cm: CodeModel) {
        self.code_model = Some(cm);
    }

    /// Get the code model as a string, or "default" if not set.
    pub fn get_code_model_str(&self) -> &str {
        self.code_model.map(|cm| cm.as_str()).unwrap_or("default")
    }

    /// Set the code model from a string. Returns true if the string was a
    /// valid code model name.
    pub fn set_code_model_str(&mut self, s: &str) -> bool {
        if let Some(cm) = CodeModel::from_str(s) {
            self.code_model = Some(cm);
            true
        } else {
            false
        }
    }

    // -----------------------------------------------------------------------
    // Profile summary
    // -----------------------------------------------------------------------

    /// Get a reference to the profile summary, if set.
    pub fn get_profile_summary(&self) -> Option<&ProfileSummary> {
        self.profile_summary.as_ref()
    }

    /// Set the profile summary.
    pub fn set_profile_summary(&mut self, ps: ProfileSummary) {
        self.profile_summary = Some(ps);
    }

    /// Check whether the module has profile summary data.
    pub fn has_profile_summary(&self) -> bool {
        self.profile_summary.is_some()
    }

    /// Clear the profile summary.
    pub fn clear_profile_summary(&mut self) {
        self.profile_summary = None;
    }

    /// Update the profile summary total count.
    pub fn update_profile_total_count(&mut self, total: u64) {
        if let Some(ref mut ps) = self.profile_summary {
            ps.total_count = total;
        }
    }

    // -----------------------------------------------------------------------
    // Module summary (ThinLTO)
    // -----------------------------------------------------------------------

    /// Get the module summary string (ThinLTO), if set.
    pub fn get_module_summary(&self) -> Option<&str> {
        self.module_summary.as_deref()
    }

    /// Set the module summary string (ThinLTO).
    pub fn set_module_summary(&mut self, summary: &str) {
        self.module_summary = Some(summary.to_string());
    }

    /// Check whether the module has a ThinLTO summary.
    pub fn has_module_summary(&self) -> bool {
        self.module_summary.is_some()
    }

    /// Clear the module summary.
    pub fn clear_module_summary(&mut self) {
        self.module_summary = None;
    }

    // -----------------------------------------------------------------------
    // Preserved analyses (pass management)
    // -----------------------------------------------------------------------

    /// Mark an analysis as preserved across a pass.
    pub fn preserve_analysis(&mut self, name: &str) {
        if !self.preserved_analyses.iter().any(|n| n == name) {
            self.preserved_analyses.push(name.to_string());
        }
    }

    /// Check whether an analysis is preserved.
    pub fn is_analysis_preserved(&self, name: &str) -> bool {
        self.preserved_analyses.iter().any(|n| n == name)
    }

    /// Clear all preserved analyses.
    pub fn clear_preserved_analyses(&mut self) {
        self.preserved_analyses.clear();
    }

    /// Get the list of preserved analysis names.
    pub fn get_preserved_analyses(&self) -> &[String] {
        &self.preserved_analyses
    }

    // -----------------------------------------------------------------------
    // Attribute group helpers
    // -----------------------------------------------------------------------

    /// Check whether an attribute group with the given ID exists.
    pub fn has_attr_group(&self, id: u32) -> bool {
        self.attr_groups.contains_key(&id)
    }

    /// Get the count of attribute groups.
    pub fn get_attr_group_count(&self) -> usize {
        self.attr_groups.len()
    }

    /// Get all attribute group IDs.
    pub fn get_attr_group_ids(&self) -> Vec<u32> {
        self.attr_groups.keys().copied().collect()
    }

    /// Clear all attribute groups.
    pub fn clear_attr_groups(&mut self) {
        self.attr_groups.clear();
    }

    // -----------------------------------------------------------------------
    // Imported functions (extended)
    // -----------------------------------------------------------------------

    /// Get the list of imported function names.
    pub fn get_imported_functions(&self) -> &[String] {
        &self.imported_functions
    }

    /// Get the count of imported functions.
    pub fn get_imported_function_count(&self) -> usize {
        self.imported_functions.len()
    }

    /// Clear all imported function registrations.
    pub fn clear_imported_functions(&mut self) {
        self.imported_functions.clear();
    }

    // -----------------------------------------------------------------------
    // Bulk operations
    // -----------------------------------------------------------------------

    /// Remove all global objects of a specific subclass kind.
    pub fn remove_globals_of_kind(&mut self, kind: SubclassKind) -> usize {
        let mut removed = 0;
        match kind {
            SubclassKind::Function => {
                removed = self.functions.len();
                self.functions.clear();
            }
            SubclassKind::GlobalVariable => {
                removed = self.globals.len();
                self.globals.clear();
            }
            SubclassKind::GlobalAlias => {
                removed = self.aliases.len();
                self.aliases.clear();
            }
            SubclassKind::GlobalIFunc => {
                removed = self.ifuncs.len();
                self.ifuncs.clear();
            }
            _ => {}
        }
        removed
    }

    /// Check whether the module is empty (no functions, globals, aliases,
    /// or ifuncs).
    pub fn is_empty(&self) -> bool {
        self.functions.is_empty()
            && self.globals.is_empty()
            && self.aliases.is_empty()
            && self.ifuncs.is_empty()
    }

    /// Get the total number of global objects of all kinds.
    pub fn get_global_object_count(&self) -> usize {
        self.functions.len() + self.globals.len() + self.aliases.len() + self.ifuncs.len()
    }

    /// Collect all global object names into a single vector.
    pub fn collect_global_names(&self) -> Vec<String> {
        let mut names = Vec::new();
        for f in &self.functions {
            names.push(f.borrow().name.clone());
        }
        for g in &self.globals {
            names.push(g.borrow().name.clone());
        }
        for a in &self.aliases {
            names.push(a.borrow().name.clone());
        }
        for i in &self.ifuncs {
            names.push(i.borrow().name.clone());
        }
        names
    }

    // -----------------------------------------------------------------------
    // Structural query helpers
    // -----------------------------------------------------------------------

    /// Check whether any global in the module uses external linkage.
    pub fn has_external_linkage_global(&self) -> bool {
        // We check the function's subclass_data for linkage encoding.
        // For simplicity, all globals without explicit linkage markers
        // are treated as external.
        !self.functions.is_empty() || !self.globals.is_empty()
    }

    /// Return the number of declared-only (no body) functions.
    pub fn declared_function_count(&self) -> usize {
        self.functions
            .iter()
            .filter(|f| {
                f.borrow().subclass == SubclassKind::Function && f.borrow().operands.is_empty()
            })
            .count()
    }

    /// Return the number of defined (has body) functions.
    pub fn defined_function_count(&self) -> usize {
        self.functions
            .iter()
            .filter(|f| {
                f.borrow().subclass == SubclassKind::Function && !f.borrow().operands.is_empty()
            })
            .count()
    }

    /// Check whether the module has any debug metadata.
    pub fn has_debug_info(&self) -> bool {
        self.named_metadata.contains_key("llvm.dbg.cu")
            || self.named_metadata.contains_key("llvm.dbg")
    }

    /// Check whether the module references any intrinsic global.
    pub fn has_intrinsics(&self) -> bool {
        self.functions
            .iter()
            .any(|f| f.borrow().name.starts_with("llvm."))
    }

    // -----------------------------------------------------------------------
    // State management for multi-module linking
    // -----------------------------------------------------------------------

    /// Mark the module as having been linked from another module.
    pub fn mark_as_linked(&mut self, source_name: &str) {
        // Record in the value symbol table that we were linked.
        // This is a lightweight marker; the real linking logic is in
        // the linker module.
        self.preserved_analyses
            .push(format!("linked_from:{}", source_name));
    }

    /// Check whether any function in the module is a declaration.
    pub fn has_declarations(&self) -> bool {
        self.functions.iter().any(|f| {
            f.borrow().subclass == SubclassKind::Function && f.borrow().operands.is_empty()
        })
    }

    /// Get the names of all functions that are declarations only.
    pub fn get_declaration_names(&self) -> Vec<String> {
        self.functions
            .iter()
            .filter(|f| {
                f.borrow().subclass == SubclassKind::Function && f.borrow().operands.is_empty()
            })
            .map(|f| f.borrow().name.clone())
            .collect()
    }

    /// Strip all debug metadata from the module.
    pub fn strip_debug_info(&mut self) {
        self.named_metadata.remove("llvm.dbg.cu");
        self.named_metadata.remove("llvm.dbg");
        // Remove debug-related module flags.
        self.flags.retain(|f| !f.key.starts_with("Debug Info"));
    }

    /// Strip all non-debug, non-essential metadata.
    pub fn strip_non_debug_metadata(&mut self) {
        // Keep debug metadata, remove everything else.
        let keep_keys: Vec<String> = self
            .named_metadata
            .keys()
            .filter(|k| k.starts_with("llvm.dbg"))
            .cloned()
            .collect();
        let mut to_keep = HashMap::new();
        for key in &keep_keys {
            if let Some(v) = self.named_metadata.remove(key) {
                to_keep.insert(key.clone(), v);
            }
        }
        self.named_metadata = to_keep;
    }

    // -----------------------------------------------------------------------
    // Misc helpers
    // -----------------------------------------------------------------------

    /// Return the module name.
    pub fn get_name(&self) -> &str {
        &self.name
    }

    /// Return a short description of the module for logging.
    pub fn describe(&self) -> String {
        format!(
            "Module '{}': {} fns, {} globals, {} aliases, {} ifuncs",
            self.name,
            self.functions.len(),
            self.globals.len(),
            self.aliases.len(),
            self.ifuncs.len()
        )
    }

    /// Return the number of types in the type table.
    pub fn get_type_table_size(&self) -> usize {
        self.types.len()
    }

    /// Return the number of named types.
    pub fn get_named_type_count(&self) -> usize {
        self.named_types.len()
    }

    /// Return all named type names.
    pub fn get_named_type_names(&self) -> Vec<&String> {
        self.named_types.keys().collect()
    }

    /// Drop all types from the module (dangerous; used for module
    /// reconstruction).
    pub fn drop_all_types(&mut self) {
        self.types.clear();
        self.named_types.clear();
        self.type_names.clear();
    }

    /// Reserve capacity in the type table.
    pub fn reserve_types(&mut self, additional: usize) {
        self.types.reserve(additional);
    }

    /// Reserve capacity in the function list.
    pub fn reserve_functions(&mut self, additional: usize) {
        self.functions.reserve(additional);
    }

    /// Reserve capacity in the globals list.
    pub fn reserve_globals(&mut self, additional: usize) {
        self.globals.reserve(additional);
    }

    /// Shrink internal vectors to fit.
    pub fn shrink_to_fit(&mut self) {
        self.functions.shrink_to_fit();
        self.globals.shrink_to_fit();
        self.aliases.shrink_to_fit();
        self.ifuncs.shrink_to_fit();
        self.types.shrink_to_fit();
        self.type_names.shrink_to_fit();
        self.flags.shrink_to_fit();
        self.preserved_analyses.shrink_to_fit();
    }

    // -----------------------------------------------------------------------
    // Extended dump / debug helpers
    // -----------------------------------------------------------------------

    /// Dump only the module header (triple, datalayout, source filename).
    pub fn dump_header(&self) -> String {
        let mut out = String::new();
        out.push_str(&format!("; ModuleID = '{}'\n", self.name));
        if !self.source_filename.is_empty() {
            out.push_str(&format!("source_filename = \"{}\"\n", self.source_filename));
        }
        if let Some(ref triple) = self.target_triple {
            out.push_str(&format!("target triple = \"{}\"\n", triple));
        }
        if let Some(ref dl) = self.data_layout {
            out.push_str(&format!("target datalayout = \"{}\"\n", dl));
        }
        out
    }

    /// Dump module-level metadata as a string.
    pub fn dump_metadata(&self) -> String {
        let mut out = String::new();
        for (key, nodes) in &self.named_metadata {
            out.push_str(&format!("!{} = !{{", key));
            let ids: Vec<String> = nodes.iter().map(|id| format!("!{}", id)).collect();
            out.push_str(&ids.join(", "));
            out.push_str("}\n");
        }
        if !self.flags.is_empty() {
            out.push_str("!llvm.module.flags = !{");
            for (i, flag) in self.flags.iter().enumerate() {
                if i > 0 {
                    out.push_str(", ");
                }
                let val_str = match &flag.value {
                    MetadataValue::Int(v) => format!("i64 {}", v),
                    MetadataValue::String(s) => format!("!\"{}\"", s),
                    MetadataValue::Node(ids) => {
                        let ids_str: Vec<String> =
                            ids.iter().map(|id| format!("!{}", id)).collect();
                        format!("!{{{}}}", ids_str.join(", "))
                    }
                    MetadataValue::Null => "null".to_string(),
                };
                out.push_str(&format!(
                    "!{{{}, !\"{}\", {}}}",
                    flag.behavior, flag.key, val_str
                ));
            }
            out.push_str("}\n");
        }
        out
    }

    /// Dump a summary of the module (counts only, no full IR).
    pub fn dump_summary(&self) -> String {
        let mut out = String::new();
        out.push_str(&format!("Module: {}\n", self.name));
        out.push_str(&format!("  Source: {}\n", self.source_filename));
        out.push_str(&format!("  Triple: {}\n", self.get_target_triple()));
        out.push_str(&format!(
            "  DataLayout: {}\n",
            self.data_layout.as_deref().unwrap_or("")
        ));
        out.push_str(&format!("  Functions: {}\n", self.functions.len()));
        out.push_str(&format!("  Globals: {}\n", self.globals.len()));
        out.push_str(&format!("  Aliases: {}\n", self.aliases.len()));
        out.push_str(&format!("  IFuncs: {}\n", self.ifuncs.len()));
        out.push_str(&format!("  Types: {}\n", self.types.len()));
        out.push_str(&format!("  NamedTypes: {}\n", self.named_types.len()));
        out.push_str(&format!("  Comdats: {}\n", self.comdats.len()));
        out.push_str(&format!("  ModuleFlags: {}\n", self.flags.len()));
        out.push_str(&format!("  NamedMetadata: {}\n", self.named_metadata.len()));
        out.push_str(&format!("  InlineAsm: {} bytes\n", self.inline_asm.len()));
        out
    }

    /// Dump only the globals (no functions).
    pub fn dump_globals(&self) -> String {
        let mut out = String::new();
        for gv in &self.globals {
            let name = gv.borrow().name.clone();
            let ty = Type::pretty_print(&gv.borrow().ty);
            out.push_str(&format!(
                "@{} = global {} ...\n",
                if name.is_empty() { "<unnamed>" } else { &name },
                ty
            ));
        }
        out
    }

    /// Dump only the functions (no globals).
    pub fn dump_functions(&self) -> String {
        let mut out = String::new();
        for func in &self.functions {
            let fname = func.borrow().name.clone();
            let has_body = !func.borrow().operands.is_empty();
            if has_body {
                out.push_str(&format!("define ... @{}() {{ ... }}\n", fname));
            } else {
                out.push_str(&format!("declare ... @{}()\n", fname));
            }
        }
        out
    }

    // -----------------------------------------------------------------------
    // Module validation helpers
    // -----------------------------------------------------------------------

    /// Check for duplicate global names across all global object kinds.
    pub fn has_duplicate_global_names(&self) -> bool {
        let all_names = self.collect_global_names();
        let mut seen = std::collections::HashSet::new();
        for name in &all_names {
            if !seen.insert(name) {
                return true;
            }
        }
        false
    }

    /// Validate basic structural integrity of the module.
    pub fn validate_structure(&self) -> Vec<String> {
        let mut errors = Vec::new();
        if self.has_duplicate_global_names() {
            errors.push("duplicate global names detected".to_string());
        }
        if self.name.is_empty() {
            errors.push("module has no name".to_string());
        }
        errors
    }

    /// Check whether the module passes basic structural validation.
    pub fn is_structurally_valid(&self) -> bool {
        self.validate_structure().is_empty()
    }
}

// ============================================================================
// Additional iterator support
// ============================================================================

/// An owning iterator over the module's functions.
pub struct ModuleFunctionIter {
    inner: std::vec::IntoIter<ValueRef>,
}

impl Iterator for ModuleFunctionIter {
    type Item = ValueRef;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl ExactSizeIterator for ModuleFunctionIter {}

/// An owning iterator over the module's globals.
pub struct ModuleGlobalIter {
    inner: std::vec::IntoIter<ValueRef>,
}

impl Iterator for ModuleGlobalIter {
    type Item = ValueRef;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl ExactSizeIterator for ModuleGlobalIter {}

/// An owning iterator over the module's aliases.
pub struct ModuleAliasIter {
    inner: std::vec::IntoIter<ValueRef>,
}

impl Iterator for ModuleAliasIter {
    type Item = ValueRef;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl ExactSizeIterator for ModuleAliasIter {}

/// An owning iterator over the module's ifuncs.
pub struct ModuleIFuncIter {
    inner: std::vec::IntoIter<ValueRef>,
}

impl Iterator for ModuleIFuncIter {
    type Item = ValueRef;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.inner.size_hint()
    }
}

impl ExactSizeIterator for ModuleIFuncIter {}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::Type;
    use crate::value::{valref, SubclassKind, Value};

    /// Helper: create a function ValueRef.
    fn make_func(name: &str) -> ValueRef {
        valref(
            Value::new(Type::function_type_with(
                crate::types::TypeId::new(),
                vec![],
                false,
            ))
            .named(name)
            .with_subclass(SubclassKind::Function),
        )
    }

    /// Helper: create a global variable ValueRef.
    fn make_global(name: &str) -> ValueRef {
        valref(
            Value::new(Type::i32())
                .named(name)
                .with_subclass(SubclassKind::GlobalVariable),
        )
    }

    #[test]
    fn test_new_module() {
        let m = Module::new("test");
        assert_eq!(m.name, "test");
        assert!(m.source_filename.is_empty());
        assert!(m.target_triple.is_none());
        assert!(m.functions.is_empty());
        assert!(m.globals.is_empty());
    }

    #[test]
    fn test_set_source_filename() {
        let mut m = Module::new("test");
        m.set_source_filename("test.ll");
        assert_eq!(m.source_filename, "test.ll");
    }

    #[test]
    fn test_set_target_triple() {
        let mut m = Module::new("test");
        m.set_target_triple("x86_64-unknown-linux-gnu");
        assert_eq!(m.get_target_triple(), "x86_64-unknown-linux-gnu");
    }

    #[test]
    fn test_set_data_layout() {
        let mut m = Module::new("test");
        m.set_data_layout("e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128");
        assert_eq!(
            m.get_data_layout(),
            "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
        );
    }

    #[test]
    fn test_add_function_dedup() {
        let mut m = Module::new("test");
        let f1 = make_func("foo");
        let f2 = make_func("foo"); // same name
        assert!(m.add_function(f1));
        assert!(!m.add_function(f2)); // duplicate
        assert_eq!(m.get_function_count(), 1);
    }

    #[test]
    fn test_add_and_get_function() {
        let mut m = Module::new("test");
        let f = make_func("myfunc");
        m.add_function(f);
        let found = m.get_function("myfunc").unwrap();
        assert_eq!(found.borrow().name, "myfunc");
    }

    #[test]
    fn test_remove_function() {
        let mut m = Module::new("test");
        m.add_function(make_func("foo"));
        m.add_function(make_func("bar"));
        assert_eq!(m.get_function_count(), 2);
        assert!(m.remove_function("foo"));
        assert_eq!(m.get_function_count(), 1);
        assert!(!m.remove_function("foo")); // already gone
        assert!(m.has_function("bar"));
        assert!(!m.has_function("foo"));
    }

    #[test]
    fn test_has_function() {
        let mut m = Module::new("test");
        assert!(!m.has_function("foo"));
        m.add_function(make_func("foo"));
        assert!(m.has_function("foo"));
    }

    #[test]
    fn test_get_function_names() {
        let mut m = Module::new("test");
        m.add_function(make_func("alpha"));
        m.add_function(make_func("beta"));
        let names = m.get_function_names();
        assert!(names.contains(&"alpha".to_string()));
        assert!(names.contains(&"beta".to_string()));
    }

    #[test]
    fn test_global_variable() {
        let mut m = Module::new("test");
        let gv = make_global("myglobal");
        assert!(m.add_global_variable(gv));
        let found = m.get_global_variable("myglobal").unwrap();
        assert_eq!(found.borrow().name, "myglobal");

        // Dedup
        let gv2 = make_global("myglobal");
        assert!(!m.add_global_variable(gv2));

        assert!(m.remove_global_variable("myglobal"));
        assert_eq!(m.get_global_count(), 0);
    }

    #[test]
    fn test_aliases() {
        let mut m = Module::new("test");
        let alias = make_global("myalias"); // reuse make_global for simplicity
        m.add_alias(alias);
        assert!(m.get_alias("myalias").is_some());
        assert!(m.remove_alias("myalias"));
        assert!(m.get_alias("myalias").is_none());
    }

    #[test]
    fn test_ifuncs() {
        let mut m = Module::new("test");
        let ifunc = make_global("myifunc");
        m.add_ifunc(ifunc);
        assert!(m.get_ifunc("myifunc").is_some());
    }

    #[test]
    fn test_type_table() {
        let mut m = Module::new("test");
        let idx = m.add_type(Type::i32());
        assert_eq!(idx, 0);
        assert_eq!(m.get_type_count(), 1);
        assert!(m.get_type(0).is_some());
        assert!(m.get_type(0).unwrap().is_integer());

        // Adding same type should return the same index
        let idx2 = m.add_type(Type::i32());
        assert_eq!(idx2, 0); // already present
        assert_eq!(m.get_type_count(), 1);
    }

    #[test]
    fn test_named_types() {
        let mut m = Module::new("test");
        let sty = Type::struct_named_with(
            "MyStruct".to_string(),
            false,
            vec![Type::i32().id, Type::i64().id],
        );
        m.add_named_type("MyStruct", sty.clone());
        let found = m.get_named_type("MyStruct").unwrap();
        assert_eq!(found.id, sty.id);
        assert!(m.remove_named_type("MyStruct"));
        assert!(m.get_named_type("MyStruct").is_none());
    }

    #[test]
    fn test_named_metadata() {
        let mut m = Module::new("test");
        m.add_named_metadata("llvm.dbg.cu", vec![1, 2, 3]);
        let nodes = m.get_named_metadata("llvm.dbg.cu").unwrap();
        assert_eq!(nodes.len(), 3);
        assert_eq!(nodes[0], 1);
        assert!(m.has_named_metadata("llvm.dbg.cu"));

        // Append more
        m.add_named_metadata("llvm.dbg.cu", vec![4]);
        let nodes = m.get_named_metadata("llvm.dbg.cu").unwrap();
        assert_eq!(nodes.len(), 4);

        assert!(m.remove_named_metadata("llvm.dbg.cu"));
        assert!(!m.has_named_metadata("llvm.dbg.cu"));
    }

    #[test]
    fn test_comdat() {
        let mut m = Module::new("test");
        assert!(m.add_comdat("mycomdat", ComdatKind::Any));
        // Duplicate
        assert!(!m.add_comdat("mycomdat", ComdatKind::Largest));

        let c = m.get_comdat("mycomdat").unwrap();
        assert_eq!(c.kind, ComdatKind::Any);
        assert!(m.remove_comdat("mycomdat"));
        assert!(m.get_comdat("mycomdat").is_none());
    }

    #[test]
    fn test_comdat_kind_display() {
        assert_eq!(ComdatKind::Any.to_string(), "any");
        assert_eq!(ComdatKind::ExactMatch.to_string(), "exactmatch");
        assert_eq!(ComdatKind::Largest.to_string(), "largest");
        assert_eq!(ComdatKind::NoDeduplicate.to_string(), "nodeduplicate");
        assert_eq!(ComdatKind::SameSize.to_string(), "samesize");
    }

    #[test]
    fn test_attr_groups() {
        let mut m = Module::new("test");
        let attrs = AttributeList::new();
        let id = m.next_attr_group_id();
        assert_eq!(id, 0);
        m.add_attr_group(id, attrs);
        assert!(m.get_attr_group(0).is_some());
        assert!(m.remove_attr_group(0));
        assert!(m.get_attr_group(0).is_none());
    }

    #[test]
    fn test_module_flags() {
        let mut m = Module::new("test");
        let flag = ModuleFlag {
            behavior: 1,
            key: "wchar_size".to_string(),
            value: MetadataValue::Int(4),
        };
        m.add_flag(flag);
        assert_eq!(m.get_flags().len(), 1);
        let found = m.get_flag("wchar_size").unwrap();
        assert_eq!(found.behavior, 1);
        assert_eq!(found.value.as_int(), Some(4));
    }

    #[test]
    fn test_module_flag_string_value() {
        let mut m = Module::new("test");
        let flag = ModuleFlag {
            behavior: 2,
            key: "ident".to_string(),
            value: MetadataValue::String("clang version 16".to_string()),
        };
        m.add_flag(flag);
        let found = m.get_flag("ident").unwrap();
        assert_eq!(found.value.as_string(), Some("clang version 16"));
    }

    #[test]
    fn test_remove_flag() {
        let mut m = Module::new("test");
        m.add_flag(ModuleFlag {
            behavior: 1,
            key: "a".to_string(),
            value: MetadataValue::Int(1),
        });
        m.add_flag(ModuleFlag {
            behavior: 1,
            key: "b".to_string(),
            value: MetadataValue::Int(2),
        });
        let removed = m.remove_flag("a");
        assert_eq!(removed, 1);
        assert_eq!(m.get_flags().len(), 1);
        assert!(m.get_flag("a").is_none());
        assert!(m.get_flag("b").is_some());
    }

    #[test]
    fn test_is_valid() {
        let m = Module::new("valid_module");
        assert!(m.is_valid());

        let m2 = Module::new("");
        assert!(!m2.is_valid());
    }

    #[test]
    fn test_clone_empty() {
        let mut m = Module::new("original");
        m.set_target_triple("x86_64-linux");
        m.set_data_layout("e-m:e-i64:64");
        m.add_function(make_func("foo"));
        m.add_global_variable(make_global("gv"));
        let ty = Type::float();
        m.add_type(ty);
        m.add_comdat("c", ComdatKind::Any);

        let cloned = m.clone_empty();
        assert_eq!(cloned.name, "original");
        assert_eq!(cloned.get_target_triple(), "x86_64-linux");
        assert!(cloned.functions.is_empty());
        assert!(cloned.globals.is_empty());
        assert_eq!(cloned.get_type_count(), 1);
        assert!(cloned.get_comdat("c").is_some());
    }

    #[test]
    fn test_dump() {
        let mut m = Module::new("dump_test");
        m.set_source_filename("dump_test.ll");
        m.set_target_triple("x86_64-linux");
        m.add_function(make_func("main"));
        m.add_global_variable(make_global("counter"));
        m.add_named_metadata("llvm.ident", vec![0]);

        let out = m.dump();
        assert!(out.contains("ModuleID = 'dump_test'"));
        assert!(out.contains("source_filename = \"dump_test.ll\""));
        assert!(out.contains("target triple = \"x86_64-linux\""));
        assert!(out.contains("@main"));
        assert!(out.contains("@counter"));
        assert!(out.contains("!llvm.ident"));
    }

    #[test]
    fn test_next_metadata_id() {
        let mut m = Module::new("test");
        assert_eq!(m.next_metadata_id(), 0);
        assert_eq!(m.next_metadata_id(), 1);
        assert_eq!(m.next_metadata_id(), 2);
    }

    #[test]
    fn test_comdat_kind_from_str() {
        assert_eq!(ComdatKind::from_str("any"), Some(ComdatKind::Any));
        assert_eq!(
            ComdatKind::from_str("exactmatch"),
            Some(ComdatKind::ExactMatch)
        );
        assert_eq!(ComdatKind::from_str("bogus"), None);
    }

    #[test]
    fn test_metadata_value_as_int_none_for_string() {
        let mv = MetadataValue::String("hello".to_string());
        assert_eq!(mv.as_int(), None);
        assert_eq!(mv.as_string(), Some("hello"));
    }

    #[test]
    fn test_imported_functions() {
        let mut m = Module::new("test");
        m.add_imported_function("printf");
        m.add_imported_function("malloc");
        assert!(m.is_imported_function("printf"));
        assert!(!m.is_imported_function("free"));
        // Dedup
        m.add_imported_function("printf");
        assert_eq!(m.imported_functions.len(), 2);
    }

    #[test]
    fn test_get_total_global_count() {
        let mut m = Module::new("test");
        assert_eq!(m.get_total_global_count(), 0);
        m.add_function(make_func("f"));
        m.add_global_variable(make_global("g"));
        m.add_alias(make_global("a"));
        m.add_ifunc(make_global("i"));
        assert_eq!(m.get_total_global_count(), 4);
    }
}