llvm-native-core 0.1.6

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
//! LLVM Metadata — MDNode, NamedMDNode, DebugInfo, and metadata store.
//!
//! Clean-room behavioral reconstruction. Phase 2 — LLVM.IR.2 Court.
//!
//! @llvm_behavior: LLVM metadata is a hierarchical key-value system for
//! attaching non-code information to the IR. Metadata nodes form a DAG
//! (directed acyclic graph) of operands. Named metadata nodes (like
//! `!llvm.module.flags`) are module-level collections. Debug info
//! metadata (DICompileUnit, DIFile, DILocation, etc.) follows the
//! DWARF debug information model encoded as LLVM metadata.
//!
//! The metadata system supports:
//! - MetadataValue: a single metadata entry with a unique ID
//! - MetadataKind: the type of metadata (string, constant, node, etc.)
//! - MetadataStore: a central registry for all metadata in a module
//! - Debug info structs (DILocation, DIFile, etc.) for DWARF emission

use crate::types::Type;

use std::collections::HashMap;

/// A constant value usable in metadata operands.
///
/// @llvm_behavior: Constants in metadata are immutable value expressions.
/// This mirrors `llvm::Constant` for metadata purposes.
#[derive(Debug, Clone)]
pub struct ConstantValue {
    pub ty: Type,
    pub repr: ConstantRepr,
}

/// Representation of a constant value.
#[derive(Debug, Clone)]
pub enum ConstantRepr {
    Int(i64),
    Float(f64),
    Null,
    Undef,
    Poison,
    String(String),
    ZeroInitializer,
}

impl ConstantValue {
    pub fn new_int(ty: Type, val: i64) -> Self {
        Self {
            ty,
            repr: ConstantRepr::Int(val),
        }
    }

    pub fn new_float(ty: Type, val: f64) -> Self {
        Self {
            ty,
            repr: ConstantRepr::Float(val),
        }
    }

    pub fn null(ty: Type) -> Self {
        Self {
            ty,
            repr: ConstantRepr::Null,
        }
    }

    pub fn to_string(&self) -> String {
        match &self.repr {
            ConstantRepr::Int(v) => format!("i{} {}", self.ty.integer_bit_width(), v),
            ConstantRepr::Float(v) => format!("{} {}", self.ty, v),
            ConstantRepr::Null => "null".to_string(),
            ConstantRepr::Undef => "undef".to_string(),
            ConstantRepr::Poison => "poison".to_string(),
            ConstantRepr::String(s) => format!("\"{}\"", s),
            ConstantRepr::ZeroInitializer => "zeroinitializer".to_string(),
        }
    }
}

/// A single metadata value with a unique ID and kind.
///
/// @llvm_behavior: Each metadata entry in LLVM has a unique numeric ID
/// (e.g., `!42`) and a kind that determines its structure. This is the
/// core metadata value type.
#[derive(Debug, Clone)]
pub struct MetadataValue {
    /// Unique identifier for this metadata.
    pub id: u32,
    /// The kind/semantics of this metadata.
    pub kind: MetadataKind,
}

/// The kind of a metadata value.
///
/// @llvm_behavior: Metadata can be a simple string, a constant, a
/// reference to another value, or a composite node (MDNode, MDTuple).
/// Distinct nodes are guaranteed unique even if structurally identical.
#[derive(Debug, Clone)]
pub enum MetadataKind {
    /// A plain metadata string (e.g., `!"hello"`).
    MDString(String),
    /// A constant value embedded in metadata.
    Constant(ConstantValue),
    /// A reference to an IR value (by index).
    Value(usize),
    /// A metadata node: an ordered list of metadata operands.
    MDNode(Vec<MetadataOperand>),
    /// A distinct metadata node: structurally unique, never merged.
    DistinctMDNode(Vec<MetadataOperand>),
    /// A metadata tuple: lightweight ordered collection.
    MDTuple(Vec<MetadataOperand>),
    /// A named metadata node: module-level name with operand metadata IDs.
    NamedNode(String, Vec<u32>),
}

/// An operand within a metadata node.
///
/// @llvm_behavior: Metadata operands can refer to other metadata by ID,
/// reference IR values directly, embed strings, or embed constants.
/// This mirrors `llvm::MDOperand`.
#[derive(Debug, Clone)]
pub enum MetadataOperand {
    /// Reference to another metadata by its ID (e.g., `!42`).
    Metadata(u32),
    /// Direct reference to an IR value (by index in the value table).
    Value(usize),
    /// An inline metadata string.
    MDString(String),
    /// An inline constant value.
    Constant(ConstantValue),
    /// A null metadata operand.
    Null,
}

impl MetadataOperand {
    /// Returns true if this is a metadata reference.
    pub fn is_metadata_ref(&self) -> bool {
        matches!(self, MetadataOperand::Metadata(_))
    }

    /// Returns the metadata ID if this is a metadata reference.
    pub fn as_metadata_id(&self) -> Option<u32> {
        match self {
            MetadataOperand::Metadata(id) => Some(*id),
            _ => None,
        }
    }

    /// Returns a debug string for this operand.
    pub fn to_debug_string(&self) -> String {
        match self {
            MetadataOperand::Metadata(id) => format!("!{}", id),
            MetadataOperand::Value(v) => format!("value(%{})", v),
            MetadataOperand::MDString(s) => format!("!\"{}\"", s),
            MetadataOperand::Constant(c) => c.to_string(),
            MetadataOperand::Null => "null".to_string(),
        }
    }
}

// ============================================================================
// Debug Info Metadata (DINode hierarchy)
// ============================================================================

/// A debug location: line, column, scope, and inlined-at information.
///
/// @llvm_behavior: `DILocation` maps to `!DILocation(...)` in LLVM IR.
/// It describes a specific point in source code and can chain via
/// `inlined_at` to represent inlined call stacks.
#[derive(Debug, Clone)]
pub struct DILocation {
    /// Source line number (1-based).
    pub line: u32,
    /// Source column number (1-based).
    pub column: u32,
    /// Metadata ID of the parent scope (DISubprogram, DILexicalBlock, etc.).
    pub scope: u32,
    /// Optional metadata ID of the inlined-at location.
    pub inlined_at: Option<u32>,
}

impl DILocation {
    pub fn new(line: u32, column: u32, scope: u32) -> Self {
        Self {
            line,
            column,
            scope,
            inlined_at: None,
        }
    }

    pub fn with_inlined_at(mut self, inlined_at: u32) -> Self {
        self.inlined_at = Some(inlined_at);
        self
    }
}

/// A debug info file descriptor.
///
/// @llvm_behavior: `DIFile` maps to `!DIFile(...)` in LLVM IR, containing
/// the filename and directory path of a source file.
#[derive(Debug, Clone)]
pub struct DIFile {
    /// The source filename (e.g., `"main.c"`).
    pub filename: String,
    /// The directory path containing the file (e.g., `"/home/user/src"`).
    pub directory: String,
    /// Optional checksum information.
    pub checksum_kind: Option<String>,
    pub checksum_value: Option<String>,
    /// Optional source text (for embedded source).
    pub source: Option<String>,
}

impl DIFile {
    pub fn new(filename: String, directory: String) -> Self {
        Self {
            filename,
            directory,
            checksum_kind: None,
            checksum_value: None,
            source: None,
        }
    }

    /// Returns the full path by joining directory and filename.
    pub fn full_path(&self) -> String {
        if self.directory.is_empty() {
            self.filename.clone()
        } else {
            format!("{}/{}", self.directory, self.filename)
        }
    }
}

/// A debug info subprogram (function definition).
///
/// @llvm_behavior: `DISubprogram` maps to `!DISubprogram(...)` in LLVM IR.
/// It describes a function's debug information including name, file,
/// line number, and parent compilation unit.
#[derive(Debug, Clone)]
pub struct DISubprogram {
    /// The function name as it appears in source.
    pub name: String,
    /// Optional mangled/linkage name.
    pub linkage_name: Option<String>,
    /// Metadata ID of the DIFile where this function is defined.
    pub file: u32,
    /// Line number of the function definition.
    pub line: u32,
    /// Metadata ID of the parent DICompileUnit.
    pub unit: u32,
    /// Metadata ID of the subroutine type (signature).
    pub ty: Option<u32>,
    /// Metadata ID of the scope (parent scope).
    pub scope: Option<u32>,
    /// Whether this is a definition (vs. declaration).
    pub is_definition: bool,
    /// Whether this function is local to the compilation unit.
    pub is_local: bool,
    /// Whether this function is optimized.
    pub is_optimized: bool,
    /// Virtual index for virtual methods.
    pub virtual_index: Option<u32>,
    /// Flags (e.g., accessibility).
    pub flags: u32,
}

impl DISubprogram {
    pub fn new(name: String, file: u32, line: u32, unit: u32) -> Self {
        Self {
            name,
            linkage_name: None,
            file,
            line,
            unit,
            ty: None,
            scope: None,
            is_definition: true,
            is_local: false,
            is_optimized: false,
            virtual_index: None,
            flags: 0,
        }
    }
}

/// A debug info type descriptor.
///
/// @llvm_behavior: `DIType` maps to `!DIBasicType(...)` and `!DIDerivedType(...)`
/// in LLVM IR. It describes the size, alignment, offset, and encoding of a
/// source-level type.
#[derive(Debug, Clone)]
pub struct DIType {
    /// The type name (e.g., `"int"`, `"struct Foo"`).
    pub name: String,
    /// Size of the type in bits.
    pub size_in_bits: u64,
    /// Alignment of the type in bits.
    pub align_in_bits: u32,
    /// Offset in bits (for struct members, derived types).
    pub offset_in_bits: u64,
    /// DWARF encoding (e.g., DW_ATE_signed = 5).
    pub encoding: u32,
    /// Metadata ID of the base type (for derived types).
    pub base_type: Option<u32>,
    /// Metadata ID of the file where this type is defined.
    pub file: Option<u32>,
    /// Line number where this type is defined.
    pub line: Option<u32>,
    /// Tag identifying the type (e.g., DW_TAG_base_type = 36).
    pub tag: u32,
    /// Flags for the type.
    pub flags: u32,
}

impl DIType {
    pub fn new_basic(name: String, size_in_bits: u64, align_in_bits: u32, encoding: u32) -> Self {
        Self {
            name,
            size_in_bits,
            align_in_bits,
            offset_in_bits: 0,
            encoding,
            base_type: None,
            file: None,
            line: None,
            tag: 36, // DW_TAG_base_type
            flags: 0,
        }
    }

    /// Returns the size in bytes (rounded up).
    pub fn size_in_bytes(&self) -> u64 {
        (self.size_in_bits + 7) / 8
    }
}

/// A debug info local variable.
///
/// @llvm_behavior: `DILocalVariable` maps to `!DILocalVariable(...)` in
/// LLVM IR. It describes a local variable in a function scope, including
/// its name, type, and source location.
#[derive(Debug, Clone)]
pub struct DILocalVariable {
    /// The variable name.
    pub name: String,
    /// Metadata ID of the scope (DISubprogram or DILexicalBlock).
    pub scope: u32,
    /// Metadata ID of the file.
    pub file: u32,
    /// Line number of the variable declaration.
    pub line: u32,
    /// Metadata ID of the variable's type.
    pub var_type: u32,
    /// Argument number for function parameters (1-based).
    pub arg: Option<u32>,
    /// Flags for the variable.
    pub flags: u32,
    /// Alignment in bits.
    pub align_in_bits: u32,
}

impl DILocalVariable {
    pub fn new(name: String, scope: u32, file: u32, line: u32, var_type: u32) -> Self {
        Self {
            name,
            scope,
            file,
            line,
            var_type,
            arg: None,
            flags: 0,
            align_in_bits: 0,
        }
    }
}

/// A debug info global variable.
///
/// @llvm_behavior: `DIGlobalVariable` maps to `!DIGlobalVariable(...)` in
/// LLVM IR. It describes a global variable in a compilation unit.
#[derive(Debug, Clone)]
pub struct DIGlobalVariable {
    /// The variable name.
    pub name: String,
    /// Metadata ID of the scope (typically DICompileUnit).
    pub scope: u32,
    /// Metadata ID of the file where the variable is declared.
    pub file: u32,
    /// Line number of the declaration.
    pub line: u32,
    /// Metadata ID of the variable's type.
    pub var_type: u32,
    /// Whether the variable is local to the compilation unit.
    pub is_local_to_unit: bool,
    /// Whether this is a definition (vs. declaration).
    pub is_definition: bool,
    /// Metadata ID of the static member declaration.
    pub declaration: Option<u32>,
    /// Alignment in bits.
    pub align_in_bits: u32,
}

impl DIGlobalVariable {
    pub fn new(
        name: String,
        scope: u32,
        file: u32,
        line: u32,
        var_type: u32,
        is_local_to_unit: bool,
        is_definition: bool,
    ) -> Self {
        Self {
            name,
            scope,
            file,
            line,
            var_type,
            is_local_to_unit,
            is_definition,
            declaration: None,
            align_in_bits: 0,
        }
    }
}

/// A debug info compile unit (translation unit).
///
/// @llvm_behavior: `DICompileUnit` maps to `!DICompileUnit(...)` in LLVM
/// IR. It describes a compilation unit with language, producer, and
/// retained types.
#[derive(Debug, Clone)]
pub struct DICompileUnit {
    /// DWARF language identifier.
    pub language: u32,
    /// Metadata ID of the DIFile for this unit.
    pub file: u32,
    /// Producer string (e.g., `"clang version 18.0.0"`).
    pub producer: String,
    /// Whether the unit is optimized.
    pub is_optimized: bool,
    /// Compiler flags string.
    pub flags: String,
    /// Runtime version.
    pub runtime_version: u32,
    /// Split debug info filename.
    pub split_debug_filename: Option<String>,
    /// Emission kind (0 = FullDebug, 1 = LineTablesOnly, 2 = NoDebug).
    pub emission_kind: u32,
    /// List of metadata IDs for retained types.
    pub retained_types: Vec<u32>,
    /// List of metadata IDs for global variables.
    pub globals: Vec<u32>,
    /// List of metadata IDs for imported entities.
    pub imports: Vec<u32>,
}

impl DICompileUnit {
    pub fn new(language: u32, file: u32, producer: String) -> Self {
        Self {
            language,
            file,
            producer,
            is_optimized: false,
            flags: String::new(),
            runtime_version: 0,
            split_debug_filename: None,
            emission_kind: 0, // FullDebug
            retained_types: Vec::new(),
            globals: Vec::new(),
            imports: Vec::new(),
        }
    }
}

// ============================================================================
// Temporary MDNode state for deferred resolution
// ============================================================================

/// State tracking for a temporary metadata node.
///
/// @llvm_behavior: LLVM supports temporary MDNodes that can be created
/// before their operands are fully resolved, and later replaced with
/// resolved nodes via RAUW (Replace All Uses With).
#[derive(Debug, Clone)]
pub struct TemporaryNodeState {
    /// The operands of this temporary node.
    pub operands: Vec<MetadataOperand>,
    /// Whether this temporary node has been resolved.
    pub resolved: bool,
    /// The replacement metadata ID, if resolved.
    pub replacement: Option<u32>,
}

impl TemporaryNodeState {
    pub fn new(operands: Vec<MetadataOperand>) -> Self {
        Self {
            operands,
            resolved: false,
            replacement: None,
        }
    }
}

// ============================================================================
// MetadataStore — central metadata registry
// ============================================================================

/// The central metadata store for a module.
///
/// @llvm_behavior: LLVM maintains a metadata registry where all metadata
/// values are stored and referenced by ID. This `MetadataStore` provides
/// the same functionality with separate vectors for different debug info
/// types for efficient lookup.
#[derive(Debug, Clone)]
pub struct MetadataStore {
    /// All metadata values, indexed by ID.
    pub values: Vec<MetadataValue>,
    /// Named metadata nodes (module-level named collections).
    pub named_nodes: HashMap<String, Vec<u32>>,
    /// Debug locations, indexed by metadata ID (may be sparse).
    pub debug_loc: Vec<Option<DILocation>>,
    /// Debug files, indexed by metadata ID.
    pub debug_files: Vec<Option<DIFile>>,
    /// Debug subprograms, indexed by metadata ID.
    pub debug_subprograms: Vec<Option<DISubprogram>>,
    /// Debug types, indexed by metadata ID.
    pub debug_types: Vec<Option<DIType>>,
    /// Debug local variables, indexed by metadata ID.
    pub debug_local_vars: Vec<Option<DILocalVariable>>,
    /// Debug global variables, indexed by metadata ID.
    pub debug_global_vars: Vec<Option<DIGlobalVariable>>,
    /// Debug compile units, indexed by metadata ID.
    pub debug_compile_units: Vec<Option<DICompileUnit>>,
    /// Per-value metadata attachments: value_index -> [(kind_name, metadata_id)].
    pub metadata_attachments: HashMap<usize, Vec<(String, u32)>>,
    /// Temporary metadata nodes awaiting resolution.
    pub temporary_nodes: HashMap<u32, TemporaryNodeState>,
}

impl MetadataStore {
    /// Create a new, empty metadata store.
    pub fn new() -> Self {
        Self {
            values: Vec::new(),
            named_nodes: HashMap::new(),
            debug_loc: Vec::new(),
            debug_files: Vec::new(),
            debug_subprograms: Vec::new(),
            debug_types: Vec::new(),
            debug_local_vars: Vec::new(),
            debug_global_vars: Vec::new(),
            debug_compile_units: Vec::new(),
            metadata_attachments: HashMap::new(),
            temporary_nodes: HashMap::new(),
        }
    }

    /// Add a metadata value and return its assigned ID.
    ///
    /// IDs are assigned sequentially starting from 0. The metadata
    /// is appended to the internal values vector.
    pub fn add_metadata(&mut self, kind: MetadataKind) -> u32 {
        let id = self.values.len() as u32;
        self.values.push(MetadataValue { id, kind });
        id
    }

    /// Get a metadata value by ID.
    pub fn get_metadata(&self, id: u32) -> Option<&MetadataValue> {
        self.values.get(id as usize)
    }

    /// Get a mutable reference to a metadata value by ID.
    pub fn get_metadata_mut(&mut self, id: u32) -> Option<&mut MetadataValue> {
        self.values.get_mut(id as usize)
    }

    /// Add a named metadata node. The operands are metadata IDs.
    pub fn add_named_node(&mut self, name: &str, operands: Vec<u32>) {
        self.named_nodes.insert(name.to_string(), operands);
    }

    /// Get a named metadata node's operands by name.
    pub fn get_named_node(&self, name: &str) -> Option<&Vec<u32>> {
        self.named_nodes.get(name)
    }

    /// Remove a named metadata node.
    pub fn remove_named_node(&mut self, name: &str) {
        self.named_nodes.remove(name);
    }

    /// Check if a named node exists.
    pub fn has_named_node(&self, name: &str) -> bool {
        self.named_nodes.contains_key(name)
    }

    /// Returns the total number of metadata values.
    pub fn count(&self) -> usize {
        self.values.len()
    }

    /// Returns true if the store is empty.
    pub fn is_empty(&self) -> bool {
        self.values.is_empty() && self.named_nodes.is_empty()
    }

    // === Debug location operations ===

    /// Add a debug location and return its metadata ID.
    ///
    /// The ID is the index into the debug_loc vector.
    pub fn add_debug_location(&mut self, loc: DILocation) -> u32 {
        let id = self.debug_loc.len() as u32;
        self.debug_loc.push(Some(loc));
        id
    }

    /// Get a debug location by its metadata ID.
    pub fn get_debug_location(&self, id: u32) -> Option<&DILocation> {
        self.debug_loc.get(id as usize).and_then(|opt| opt.as_ref())
    }

    /// Update an existing debug location.
    pub fn set_debug_location(&mut self, id: u32, loc: DILocation) {
        let idx = id as usize;
        while self.debug_loc.len() <= idx {
            self.debug_loc.push(None);
        }
        self.debug_loc[idx] = Some(loc);
    }

    // === Debug file operations ===

    /// Add a debug file and return its metadata ID.
    pub fn add_debug_file(&mut self, file: DIFile) -> u32 {
        let id = self.debug_files.len() as u32;
        self.debug_files.push(Some(file));
        id
    }

    /// Get a debug file by its metadata ID.
    pub fn get_debug_file(&self, id: u32) -> Option<&DIFile> {
        self.debug_files
            .get(id as usize)
            .and_then(|opt| opt.as_ref())
    }

    /// Find a debug file by filename and directory.
    pub fn find_debug_file(&self, filename: &str, directory: &str) -> Option<u32> {
        self.debug_files
            .iter()
            .position(|opt| {
                opt.as_ref().map_or(false, |f| {
                    f.filename == filename && f.directory == directory
                })
            })
            .map(|idx| idx as u32)
    }

    // === Debug subprogram operations ===

    /// Add a debug subprogram and return its metadata ID.
    pub fn add_debug_subprogram(&mut self, sp: DISubprogram) -> u32 {
        let id = self.debug_subprograms.len() as u32;
        self.debug_subprograms.push(Some(sp));
        id
    }

    /// Get a debug subprogram by its metadata ID.
    pub fn get_debug_subprogram(&self, id: u32) -> Option<&DISubprogram> {
        self.debug_subprograms
            .get(id as usize)
            .and_then(|opt| opt.as_ref())
    }

    /// Find a debug subprogram by name.
    pub fn find_debug_subprogram(&self, name: &str) -> Option<u32> {
        self.debug_subprograms
            .iter()
            .position(|opt| opt.as_ref().map_or(false, |sp| sp.name == name))
            .map(|idx| idx as u32)
    }

    // === Debug type operations ===

    /// Add a debug type and return its metadata ID.
    pub fn add_debug_type(&mut self, ty: DIType) -> u32 {
        let id = self.debug_types.len() as u32;
        self.debug_types.push(Some(ty));
        id
    }

    /// Get a debug type by its metadata ID.
    pub fn get_debug_type(&self, id: u32) -> Option<&DIType> {
        self.debug_types
            .get(id as usize)
            .and_then(|opt| opt.as_ref())
    }

    /// Find a debug type by name.
    pub fn find_debug_type(&self, name: &str) -> Option<u32> {
        self.debug_types
            .iter()
            .position(|opt| opt.as_ref().map_or(false, |ty| ty.name == name))
            .map(|idx| idx as u32)
    }

    // === Debug local variable operations ===

    /// Add a debug local variable and return its metadata ID.
    pub fn add_debug_local_var(&mut self, var: DILocalVariable) -> u32 {
        let id = self.debug_local_vars.len() as u32;
        self.debug_local_vars.push(Some(var));
        id
    }

    /// Get a debug local variable by its metadata ID.
    pub fn get_debug_local_var(&self, id: u32) -> Option<&DILocalVariable> {
        self.debug_local_vars
            .get(id as usize)
            .and_then(|opt| opt.as_ref())
    }

    // === Debug global variable operations ===

    /// Add a debug global variable and return its metadata ID.
    pub fn add_debug_global_var(&mut self, var: DIGlobalVariable) -> u32 {
        let id = self.debug_global_vars.len() as u32;
        self.debug_global_vars.push(Some(var));
        id
    }

    /// Get a debug global variable by its metadata ID.
    pub fn get_debug_global_var(&self, id: u32) -> Option<&DIGlobalVariable> {
        self.debug_global_vars
            .get(id as usize)
            .and_then(|opt| opt.as_ref())
    }

    // === Debug compile unit operations ===

    /// Add a debug compile unit and return its metadata ID.
    pub fn add_debug_compile_unit(&mut self, cu: DICompileUnit) -> u32 {
        let id = self.debug_compile_units.len() as u32;
        self.debug_compile_units.push(Some(cu));
        id
    }

    /// Get a debug compile unit by its metadata ID.
    pub fn get_debug_compile_unit(&self, id: u32) -> Option<&DICompileUnit> {
        self.debug_compile_units
            .get(id as usize)
            .and_then(|opt| opt.as_ref())
    }

    // === Utility: creating metadata from an MDNode-style operand list ===

    /// Create an MDNode metadata value from a list of metadata operands.
    pub fn create_md_node(&mut self, operands: Vec<MetadataOperand>) -> u32 {
        self.add_metadata(MetadataKind::MDNode(operands))
    }

    /// Create a distinct MDNode metadata value from a list of operands.
    pub fn create_distinct_md_node(&mut self, operands: Vec<MetadataOperand>) -> u32 {
        self.add_metadata(MetadataKind::DistinctMDNode(operands))
    }

    /// Create an MDTuple metadata value from a list of operands.
    pub fn create_md_tuple(&mut self, operands: Vec<MetadataOperand>) -> u32 {
        self.add_metadata(MetadataKind::MDTuple(operands))
    }

    /// Create a metadata string value.
    pub fn create_md_string(&mut self, s: &str) -> u32 {
        self.add_metadata(MetadataKind::MDString(s.to_string()))
    }

    /// Helper: create a metadata operand that references another metadata by ID.
    pub fn md_ref(id: u32) -> MetadataOperand {
        MetadataOperand::Metadata(id)
    }

    /// Helper: create a metadata operand that is a string.
    pub fn md_string_op(s: &str) -> MetadataOperand {
        MetadataOperand::MDString(s.to_string())
    }

    /// Helper: create a null metadata operand.
    pub fn md_null() -> MetadataOperand {
        MetadataOperand::Null
    }

    /// Emit the LLVM IR assembly text for all metadata in this store.
    pub fn emit_assembly(&self) -> String {
        let mut lines = Vec::new();

        for mv in &self.values {
            let line = self.emit_metadata_value(mv);
            if !line.is_empty() {
                lines.push(line);
            }
        }

        for (name, operands) in &self.named_nodes {
            let ops_str = operands
                .iter()
                .map(|id| format!("!{}", id))
                .collect::<Vec<_>>()
                .join(", ");
            lines.push(format!("!{} = !{{{}}}", name, ops_str));
        }

        lines.join("\n")
    }

    fn emit_metadata_value(&self, mv: &MetadataValue) -> String {
        match &mv.kind {
            MetadataKind::MDString(s) => {
                format!("!{} = !\"{}\"", mv.id, s)
            }
            MetadataKind::Constant(c) => {
                format!("!{} = !{{{}}}", mv.id, c.to_string())
            }
            MetadataKind::Value(v) => {
                format!("!{} = !{{{}}}", mv.id, v)
            }
            MetadataKind::MDNode(operands)
            | MetadataKind::DistinctMDNode(operands)
            | MetadataKind::MDTuple(operands) => {
                let distinct = matches!(mv.kind, MetadataKind::DistinctMDNode(_));
                let prefix = if distinct { "distinct " } else { "" };
                let ops_str = operands
                    .iter()
                    .map(|op| op.to_debug_string())
                    .collect::<Vec<_>>()
                    .join(", ");
                format!("!{} = {}!{{{}}}", mv.id, prefix, ops_str)
            }
            MetadataKind::NamedNode(name, _) => {
                format!("; named node: {}", name)
            }
        }
    }
}

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

// ============================================================================
// Standard LLVM Metadata Kind Names
// ============================================================================

/// Well-known metadata kind names used by LLVM for attaching
/// metadata to instructions.
///
/// These constants mirror `llvm::LLVMContext::MD_kind` values.
pub mod md_kind {
    /// Debug info location metadata key.
    pub const DBG: &str = "dbg";
    /// Type-Based Alias Analysis metadata key.
    pub const TBAA: &str = "tbaa";
    /// TBAA struct-path metadata key.
    pub const TBAA_STRUCT: &str = "tbaa.struct";
    /// Alias scope metadata key.
    pub const ALIAS_SCOPE: &str = "alias.scope";
    /// No-alias metadata key.
    pub const NOALIAS: &str = "noalias";
    /// Value range metadata key.
    pub const RANGE: &str = "range";
    /// Floating-point math flags metadata key.
    pub const FPMATH: &str = "fpmath";
    /// Profile data metadata key.
    pub const PROF: &str = "prof";
    /// Loop metadata key.
    pub const LLVM_LOOP: &str = "llvm.loop";
    /// Make-implicit metadata key.
    pub const MAKE_IMPLICIT: &str = "make.implicit";
    /// Absolute symbol metadata key.
    pub const ABSOLUTE_SYMBOL: &str = "absolute_symbol";
    /// Inaccessible-memory-only metadata key.
    pub const INACCESSIBLEMEMONLY: &str = "inaccessiblememonly";
    /// Invariant load metadata key.
    pub const INVARIANT_LOAD: &str = "invariant.load";
    /// Invariant group metadata key.
    pub const INVARIANT_GROUP: &str = "invariant.group";
    /// Dereferenceable metadata key.
    pub const DEREFERENCEABLE: &str = "dereferenceable";
    /// Dereferenceable-or-null metadata key.
    pub const DEREFERENCEABLE_OR_NULL: &str = "dereferenceable_or_null";
    /// Nonnull metadata key.
    pub const NONNULL: &str = "nonnull";
    /// Alignment metadata key.
    pub const ALIGN: &str = "align";
    /// Type metadata key.
    pub const TYPE: &str = "type";
    /// Sanitizer metadata key.
    pub const SANITIZE: &str = "sanitize";
    /// Module flags (named metadata).
    pub const LLVM_MODULE_FLAGS: &str = "llvm.module.flags";
    /// Module identifier (named metadata).
    pub const LLVM_IDENT: &str = "llvm.ident";
    /// Debug compile unit list (named metadata).
    pub const LLVM_DBG_CU: &str = "llvm.dbg.cu";
    /// Used symbols list (named metadata).
    pub const LLVM_USED: &str = "llvm.used";
    /// Compiler-used symbols list (named metadata).
    pub const LLVM_COMPILER_USED: &str = "llvm.compiler.used";

    /// All well-known named metadata entries (for iteration).
    pub const NAMED: &[&str] = &[
        LLVM_MODULE_FLAGS,
        LLVM_IDENT,
        LLVM_DBG_CU,
        LLVM_USED,
        LLVM_COMPILER_USED,
    ];

    /// Returns true if the given kind name is a well-known named metadata.
    pub fn is_named(kind: &str) -> bool {
        NAMED.iter().any(|&n| n == kind)
    }
}

// ============================================================================
// DWARF Tag Constants
// ============================================================================

/// DWARF tag constants used by debug info metadata.
///
/// These are the standard `DW_TAG_*` values from the DWARF specification.
pub mod dwarf_tag {
    pub const ARRAY_TYPE: u32 = 1;
    pub const CLASS_TYPE: u32 = 2;
    pub const ENTRY_POINT: u32 = 3;
    pub const ENUMERATION_TYPE: u32 = 4;
    pub const FORMAL_PARAMETER: u32 = 5;
    pub const IMPORTED_DECLARATION: u32 = 8;
    pub const LABEL: u32 = 10;
    pub const LEXICAL_BLOCK: u32 = 11;
    pub const MEMBER: u32 = 13;
    pub const POINTER_TYPE: u32 = 15;
    pub const REFERENCE_TYPE: u32 = 16;
    pub const COMPILE_UNIT: u32 = 17;
    pub const STRUCTURE_TYPE: u32 = 19;
    pub const SUBROUTINE_TYPE: u32 = 21;
    pub const TYPEDEF: u32 = 22;
    pub const UNION_TYPE: u32 = 23;
    pub const INHERITANCE: u32 = 28;
    pub const PTR_TO_MEMBER_TYPE: u32 = 31;
    pub const ENUMERATOR: u32 = 40;
    pub const SUBRANGE_TYPE: u32 = 33;
    pub const CONST_TYPE: u32 = 38;
    pub const VOLATILE_TYPE: u32 = 53;
    pub const RESTRICT_TYPE: u32 = 55;
    pub const IMPORTED_MODULE: u32 = 58;
    pub const TEMPLATE_TYPE_PARAMETER: u32 = 47;
    pub const TEMPLATE_VALUE_PARAMETER: u32 = 48;
    pub const NAMESPACE: u32 = 57;
    pub const LEXICAL_BLOCK_FILE: u32 = 58;
    pub const GLOBAL_VARIABLE: u32 = 52;
    pub const LOCAL_VARIABLE: u32 = 33;
    pub const AUTO_VARIABLE: u32 = 256;
    pub const ARG_VARIABLE: u32 = 257;
    pub const RETURN_VARIABLE: u32 = 258;
    pub const STRING_TYPE: u32 = 67;
}

// ============================================================================
// DWARF Encoding Constants
// ============================================================================

/// DWARF attribute encoding constants used by DIBasicType.
///
/// These are the standard `DW_ATE_*` values from the DWARF specification.
pub mod dwarf_encoding {
    pub const ADDRESS: u32 = 1;
    pub const BOOLEAN: u32 = 2;
    pub const COMPLEX_FLOAT: u32 = 3;
    pub const FLOAT: u32 = 4;
    pub const SIGNED: u32 = 5;
    pub const SIGNED_CHAR: u32 = 6;
    pub const UNSIGNED: u32 = 7;
    pub const UNSIGNED_CHAR: u32 = 8;
    pub const IMAGINARY_FLOAT: u32 = 9;
    pub const PACKED_DECIMAL: u32 = 10;
    pub const NUMERIC_STRING: u32 = 11;
    pub const UTF: u32 = 16;
    pub const UCS: u32 = 17;
    pub const ASCII: u32 = 18;
}

// ============================================================================
// DWARF Language Constants
// ============================================================================

/// DWARF language constants used by DICompileUnit.
pub mod dwarf_lang {
    pub const C89: u32 = 1;
    pub const C: u32 = 2;
    pub const ADA83: u32 = 3;
    pub const C_PLUS_PLUS: u32 = 4;
    pub const COBOL74: u32 = 5;
    pub const COBOL85: u32 = 6;
    pub const FORTRAN77: u32 = 7;
    pub const FORTRAN90: u32 = 8;
    pub const PASCAL83: u32 = 9;
    pub const MODULA2: u32 = 10;
    pub const JAVA: u32 = 11;
    pub const C99: u32 = 12;
    pub const ADA95: u32 = 13;
    pub const FORTRAN95: u32 = 14;
    pub const PL1: u32 = 15;
    pub const OBJC: u32 = 16;
    pub const OBJC_PLUS_PLUS: u32 = 17;
    pub const D: u32 = 19;
    pub const PYTHON: u32 = 20;
    pub const RUST: u32 = 28;
    pub const C11: u32 = 29;
    pub const SWIFT: u32 = 31;
    pub const C_PLUS_PLUS_14: u32 = 33;
    pub const FORTRAN03: u32 = 34;
    pub const FORTRAN08: u32 = 35;
    pub const RENDERSCRIPT: u32 = 36;
    pub const C17: u32 = 38;
    pub const C_PLUS_PLUS_20: u32 = 41;
    pub const MOJO: u32 = 43;
}

// ============================================================================
// DWARF Expression Operation Constants (DW_OP_*)
// ============================================================================

/// DWARF expression operation codes used in DIExpression.
pub mod dwarf_op {
    pub const ADDR: u64 = 0x03;
    pub const DEREF: u64 = 0x06;
    pub const CONST1U: u64 = 0x08;
    pub const CONST1S: u64 = 0x09;
    pub const CONST2U: u64 = 0x0a;
    pub const CONST2S: u64 = 0x0b;
    pub const CONST4U: u64 = 0x0c;
    pub const CONST4S: u64 = 0x0d;
    pub const CONST8U: u64 = 0x0e;
    pub const CONST8S: u64 = 0x0f;
    pub const CONSTU: u64 = 0x10;
    pub const CONSTS: u64 = 0x11;
    pub const DUP: u64 = 0x12;
    pub const DROP: u64 = 0x13;
    pub const OVER: u64 = 0x14;
    pub const PICK: u64 = 0x15;
    pub const SWAP: u64 = 0x16;
    pub const ROT: u64 = 0x17;
    pub const XDEREF: u64 = 0x18;
    pub const ABS: u64 = 0x19;
    pub const AND: u64 = 0x1a;
    pub const DIV: u64 = 0x1b;
    pub const MINUS: u64 = 0x1c;
    pub const MOD: u64 = 0x1d;
    pub const MUL: u64 = 0x1e;
    pub const NEG: u64 = 0x1f;
    pub const NOT: u64 = 0x20;
    pub const OR: u64 = 0x21;
    pub const PLUS: u64 = 0x22;
    pub const PLUS_UCONST: u64 = 0x23;
    pub const SHL: u64 = 0x24;
    pub const SHR: u64 = 0x25;
    pub const SHRA: u64 = 0x26;
    pub const XOR: u64 = 0x27;
    pub const BRA: u64 = 0x28;
    pub const EQ: u64 = 0x29;
    pub const GE: u64 = 0x2a;
    pub const GT: u64 = 0x2b;
    pub const LE: u64 = 0x2c;
    pub const LT: u64 = 0x2d;
    pub const NE: u64 = 0x2e;
    pub const SKIP: u64 = 0x2f;
    pub const LIT0: u64 = 0x30;
    pub const LIT1: u64 = 0x31;
    pub const LIT2: u64 = 0x32;
    pub const LIT3: u64 = 0x33;
    pub const LIT4: u64 = 0x34;
    pub const LIT5: u64 = 0x35;
    pub const LIT6: u64 = 0x36;
    pub const LIT7: u64 = 0x37;
    pub const LIT8: u64 = 0x38;
    pub const LIT9: u64 = 0x39;
    pub const LIT10: u64 = 0x3a;
    pub const LIT11: u64 = 0x3b;
    pub const LIT12: u64 = 0x3c;
    pub const LIT13: u64 = 0x3d;
    pub const LIT14: u64 = 0x3e;
    pub const LIT15: u64 = 0x3f;
    pub const LIT16: u64 = 0x40;
    pub const LIT17: u64 = 0x41;
    pub const LIT18: u64 = 0x42;
    pub const LIT19: u64 = 0x43;
    pub const LIT20: u64 = 0x44;
    pub const LIT21: u64 = 0x45;
    pub const LIT22: u64 = 0x46;
    pub const LIT23: u64 = 0x47;
    pub const LIT24: u64 = 0x48;
    pub const LIT25: u64 = 0x49;
    pub const LIT26: u64 = 0x4a;
    pub const LIT27: u64 = 0x4b;
    pub const LIT28: u64 = 0x4c;
    pub const LIT29: u64 = 0x4d;
    pub const LIT30: u64 = 0x4e;
    pub const LIT31: u64 = 0x4f;
    pub const REG0: u64 = 0x50;
    pub const REG1: u64 = 0x51;
    pub const REG2: u64 = 0x52;
    pub const REG3: u64 = 0x53;
    pub const REG4: u64 = 0x54;
    pub const REG5: u64 = 0x55;
    pub const REG6: u64 = 0x56;
    pub const REG7: u64 = 0x57;
    pub const REG8: u64 = 0x58;
    pub const REG9: u64 = 0x59;
    pub const REG10: u64 = 0x5a;
    pub const REG11: u64 = 0x5b;
    pub const REG12: u64 = 0x5c;
    pub const REG13: u64 = 0x5d;
    pub const REG14: u64 = 0x5e;
    pub const REG15: u64 = 0x5f;
    pub const REG16: u64 = 0x60;
    pub const REG17: u64 = 0x61;
    pub const REG18: u64 = 0x62;
    pub const REG19: u64 = 0x63;
    pub const REG20: u64 = 0x64;
    pub const REG21: u64 = 0x65;
    pub const REG22: u64 = 0x66;
    pub const REG23: u64 = 0x67;
    pub const REG24: u64 = 0x68;
    pub const REG25: u64 = 0x69;
    pub const REG26: u64 = 0x6a;
    pub const REG27: u64 = 0x6b;
    pub const REG28: u64 = 0x6c;
    pub const REG29: u64 = 0x6d;
    pub const REG30: u64 = 0x6e;
    pub const REG31: u64 = 0x6f;
    pub const BREG0: u64 = 0x70;
    pub const BREG1: u64 = 0x71;
    pub const BREG2: u64 = 0x72;
    pub const BREG3: u64 = 0x73;
    pub const BREG4: u64 = 0x74;
    pub const BREG5: u64 = 0x75;
    pub const BREG6: u64 = 0x76;
    pub const BREG7: u64 = 0x77;
    pub const BREG8: u64 = 0x78;
    pub const BREG9: u64 = 0x79;
    pub const BREG10: u64 = 0x7a;
    pub const BREG11: u64 = 0x7b;
    pub const BREG12: u64 = 0x7c;
    pub const BREG13: u64 = 0x7d;
    pub const BREG14: u64 = 0x7e;
    pub const BREG15: u64 = 0x7f;
    pub const BREG16: u64 = 0x80;
    pub const BREG17: u64 = 0x81;
    pub const BREG18: u64 = 0x82;
    pub const BREG19: u64 = 0x83;
    pub const BREG20: u64 = 0x84;
    pub const BREG21: u64 = 0x85;
    pub const BREG22: u64 = 0x86;
    pub const BREG23: u64 = 0x87;
    pub const BREG24: u64 = 0x88;
    pub const BREG25: u64 = 0x89;
    pub const BREG26: u64 = 0x8a;
    pub const BREG27: u64 = 0x8b;
    pub const BREG28: u64 = 0x8c;
    pub const BREG29: u64 = 0x8d;
    pub const BREG30: u64 = 0x8e;
    pub const BREG31: u64 = 0x8f;
    pub const REGX: u64 = 0x90;
    pub const FBREG: u64 = 0x91;
    pub const BREGX: u64 = 0x92;
    pub const PIECE: u64 = 0x93;
    pub const DEREF_SIZE: u64 = 0x94;
    pub const XDEREF_SIZE: u64 = 0x95;
    pub const NOP: u64 = 0x96;
    pub const PUSH_OBJECT_ADDRESS: u64 = 0x97;
    pub const CALL2: u64 = 0x98;
    pub const CALL4: u64 = 0x99;
    pub const CALL_REF: u64 = 0x9a;
    pub const FORM_TLS_ADDRESS: u64 = 0x9b;
    pub const CALL_FRAME_CFA: u64 = 0x9c;
    pub const BIT_PIECE: u64 = 0x9d;
    pub const IMPLICIT_VALUE: u64 = 0x9e;
    pub const STACK_VALUE: u64 = 0x9f;
    pub const IMPLICIT_POINTER: u64 = 0xa0;
    pub const ADDR_OF: u64 = 0xa1;
    pub const ENTRY_VALUE: u64 = 0xa3;
    pub const CONST_TYPE: u64 = 0xa4;
    pub const REGVAL_TYPE: u64 = 0xa5;
    pub const DEREF_TYPE: u64 = 0xa6;
    pub const XDEREF_TYPE: u64 = 0xa7;
    pub const CONVERT: u64 = 0xa8;
    pub const REINTERPRET: u64 = 0xa9;
    /// LLVM-specific: marks a fragment (offset, size).
    pub const LLVM_FRAGMENT: u64 = 0x1000;
    /// LLVM-specific: marks an argument number.
    pub const LLVM_ARG: u64 = 0x1000 + 1;
    /// LLVM-specific: entry value expression.
    pub const LLVM_ENTRY_VALUE: u64 = 0x1000 + 3;
}

// ============================================================================
// DIScope trait — common interface for all debug info scopes
// ============================================================================

/// Trait implemented by all debug info scope types.
///
/// @llvm_behavior: In LLVM, `DIScope` is the base class for all debug info
/// nodes that can serve as a lexical scope (DISubprogram, DILexicalBlock,
/// DICompileUnit, DINamespace, DIType for composite types, etc.).
/// This trait provides the common interface for scope queries.
pub trait DIScope {
    /// Returns the display name of this scope.
    fn get_scope_name(&self) -> &str;

    /// Returns the metadata ID of the DIFile for this scope, if any.
    fn get_scope_file(&self) -> Option<u32>;

    /// Returns the line number where this scope begins, if any.
    fn get_scope_line(&self) -> Option<u32>;
}

// ============================================================================
// DIScope implementations for existing debug info types
// ============================================================================

impl DIScope for DISubprogram {
    fn get_scope_name(&self) -> &str {
        &self.name
    }

    fn get_scope_file(&self) -> Option<u32> {
        Some(self.file)
    }

    fn get_scope_line(&self) -> Option<u32> {
        Some(self.line)
    }
}

impl DIScope for DICompileUnit {
    fn get_scope_name(&self) -> &str {
        &self.producer
    }

    fn get_scope_file(&self) -> Option<u32> {
        Some(self.file)
    }

    fn get_scope_line(&self) -> Option<u32> {
        None
    }
}

// ============================================================================
// Full DIType Hierarchy (DWARF type descriptors)
// ============================================================================

/// DIBasicType — a basic/primitive type descriptor (int, float, char, etc.).
///
/// @llvm_behavior: `DIBasicType` maps to `!DIBasicType(...)` in LLVM IR.
/// It describes a primitive type with a name, size, alignment, encoding,
/// and optional flags.
#[derive(Debug, Clone)]
pub struct DIBasicType {
    /// The type name (e.g., "int", "float", "double").
    pub name: String,
    /// Size of the type in bits.
    pub size_in_bits: u64,
    /// Alignment of the type in bits.
    pub align_in_bits: u32,
    /// DWARF encoding (e.g., DW_ATE_signed = 5, DW_ATE_float = 4).
    pub encoding: u32,
    /// Optional flags (e.g., DIFlags for accessibility).
    pub flags: u32,
}

impl DIBasicType {
    /// Create a new DIBasicType.
    pub fn new(name: String, size_in_bits: u64, align_in_bits: u32, encoding: u32) -> Self {
        Self {
            name,
            size_in_bits,
            align_in_bits,
            encoding,
            flags: 0,
        }
    }

    /// Create a DIBasicType for a signed integer.
    pub fn signed_int(name: String, size_in_bits: u64, align_in_bits: u32) -> Self {
        Self::new(name, size_in_bits, align_in_bits, dwarf_encoding::SIGNED)
    }

    /// Create a DIBasicType for an unsigned integer.
    pub fn unsigned_int(name: String, size_in_bits: u64, align_in_bits: u32) -> Self {
        Self::new(name, size_in_bits, align_in_bits, dwarf_encoding::UNSIGNED)
    }

    /// Create a DIBasicType for a floating-point type.
    pub fn float_type(name: String, size_in_bits: u64, align_in_bits: u32) -> Self {
        Self::new(name, size_in_bits, align_in_bits, dwarf_encoding::FLOAT)
    }

    /// Create a DIBasicType for a boolean type.
    pub fn boolean(name: String, size_in_bits: u64, align_in_bits: u32) -> Self {
        Self::new(name, size_in_bits, align_in_bits, dwarf_encoding::BOOLEAN)
    }

    /// Create a DIBasicType for a character type.
    pub fn character(name: String, size_in_bits: u64, align_in_bits: u32, signed: bool) -> Self {
        let enc = if signed {
            dwarf_encoding::SIGNED_CHAR
        } else {
            dwarf_encoding::UNSIGNED_CHAR
        };
        Self::new(name, size_in_bits, align_in_bits, enc)
    }

    /// Returns the size in bytes (rounded up to the nearest byte).
    pub fn size_in_bytes(&self) -> u64 {
        (self.size_in_bits + 7) / 8
    }

    /// Returns true if this is a signed integer type.
    pub fn is_signed(&self) -> bool {
        self.encoding == dwarf_encoding::SIGNED || self.encoding == dwarf_encoding::SIGNED_CHAR
    }

    /// Returns true if this is an unsigned integer type.
    pub fn is_unsigned(&self) -> bool {
        self.encoding == dwarf_encoding::UNSIGNED || self.encoding == dwarf_encoding::UNSIGNED_CHAR
    }

    /// Returns true if this is a floating-point type.
    pub fn is_float(&self) -> bool {
        self.encoding == dwarf_encoding::FLOAT
            || self.encoding == dwarf_encoding::COMPLEX_FLOAT
            || self.encoding == dwarf_encoding::IMAGINARY_FLOAT
    }

    /// Returns true if this is a boolean type.
    pub fn is_boolean(&self) -> bool {
        self.encoding == dwarf_encoding::BOOLEAN
    }

    /// Set the flags for this type (builder pattern).
    pub fn with_flags(mut self, flags: u32) -> Self {
        self.flags = flags;
        self
    }
}

/// DIDerivedType — a derived type descriptor (pointer, reference, const,
/// volatile, typedef, member, inheritance, etc.).
///
/// @llvm_behavior: `DIDerivedType` maps to `!DIDerivedType(...)` in LLVM IR.
/// It describes a type derived from a base type, identified by its DWARF tag.
#[derive(Debug, Clone)]
pub struct DIDerivedType {
    /// DWARF tag (e.g., DW_TAG_pointer_type = 15, DW_TAG_typedef = 22).
    pub tag: u32,
    /// Metadata ID of the base type.
    pub base_type: u32,
    /// Optional name for the derived type (used for typedefs).
    pub name: Option<String>,
    /// Size of the derived type in bits.
    pub size: u64,
    /// Alignment of the derived type in bits.
    pub align: u32,
    /// Offset in bits (for struct/class members).
    pub offset: u64,
    /// Optional DWARF flags.
    pub dw_flags: u32,
    /// Optional metadata ID of the scope containing this type.
    pub scope: Option<u32>,
    /// Optional metadata ID of the file where this type is defined.
    pub file: Option<u32>,
    /// Optional line number where this type is defined.
    pub line: Option<u32>,
    /// Optional extra data metadata operand.
    pub extra_data: Option<u32>,
    /// Optional annotations.
    pub annotations: Option<u32>,
}

impl DIDerivedType {
    /// Create a new DIDerivedType.
    pub fn new(tag: u32, base_type: u32, size: u64, align: u32, offset: u64) -> Self {
        Self {
            tag,
            base_type,
            name: None,
            size,
            align,
            offset,
            dw_flags: 0,
            scope: None,
            file: None,
            line: None,
            extra_data: None,
            annotations: None,
        }
    }

    /// Create a pointer type (DW_TAG_pointer_type).
    pub fn pointer_type(base_type: u32, size: u64, align: u32) -> Self {
        Self::new(dwarf_tag::POINTER_TYPE, base_type, size, align, 0)
    }

    /// Create a reference type (DW_TAG_reference_type).
    pub fn reference_type(base_type: u32, size: u64, align: u32) -> Self {
        Self::new(dwarf_tag::REFERENCE_TYPE, base_type, size, align, 0)
    }

    /// Create a typedef (DW_TAG_typedef).
    pub fn typedef_type(name: String, base_type: u32, file: u32, line: u32) -> Self {
        let mut ty = Self::new(dwarf_tag::TYPEDEF, base_type, 0, 0, 0);
        ty.name = Some(name);
        ty.file = Some(file);
        ty.line = Some(line);
        ty
    }

    /// Create a const-qualified type (DW_TAG_const_type).
    pub fn const_type(base_type: u32) -> Self {
        Self::new(dwarf_tag::CONST_TYPE, base_type, 0, 0, 0)
    }

    /// Create a volatile-qualified type (DW_TAG_volatile_type).
    pub fn volatile_type(base_type: u32) -> Self {
        Self::new(dwarf_tag::VOLATILE_TYPE, base_type, 0, 0, 0)
    }

    /// Create a restrict-qualified type (DW_TAG_restrict_type).
    pub fn restrict_type(base_type: u32) -> Self {
        Self::new(dwarf_tag::RESTRICT_TYPE, base_type, 0, 0, 0)
    }

    /// Create a pointer-to-member type (DW_TAG_ptr_to_member_type).
    pub fn ptr_to_member_type(base_type: u32, class_type: u32, size: u64, align: u32) -> Self {
        let mut ty = Self::new(dwarf_tag::PTR_TO_MEMBER_TYPE, base_type, size, align, 0);
        ty.extra_data = Some(class_type);
        ty
    }

    /// Create a member type (struct/class field).
    pub fn member_type(
        name: String,
        base_type: u32,
        size: u64,
        align: u32,
        offset: u64,
        file: u32,
        line: u32,
    ) -> Self {
        let mut ty = Self::new(dwarf_tag::MEMBER, base_type, size, align, offset);
        ty.name = Some(name);
        ty.file = Some(file);
        ty.line = Some(line);
        ty
    }

    /// Create an inheritance descriptor.
    pub fn inheritance(base_type: u32, offset: u64, dw_flags: u32) -> Self {
        Self::new(dwarf_tag::INHERITANCE, base_type, 0, 0, offset).with_dw_flags(dw_flags)
    }

    /// Returns true if this is a pointer type.
    pub fn is_pointer(&self) -> bool {
        self.tag == dwarf_tag::POINTER_TYPE
    }

    /// Returns true if this is a reference type.
    pub fn is_reference(&self) -> bool {
        self.tag == dwarf_tag::REFERENCE_TYPE
    }

    /// Returns true if this is a typedef.
    pub fn is_typedef(&self) -> bool {
        self.tag == dwarf_tag::TYPEDEF
    }

    /// Returns true if this is a const-qualified type.
    pub fn is_const(&self) -> bool {
        self.tag == dwarf_tag::CONST_TYPE
    }

    /// Returns true if this is a volatile-qualified type.
    pub fn is_volatile(&self) -> bool {
        self.tag == dwarf_tag::VOLATILE_TYPE
    }

    /// Returns true if this is a restrict-qualified type.
    pub fn is_restrict(&self) -> bool {
        self.tag == dwarf_tag::RESTRICT_TYPE
    }

    /// Returns true if this is a member (struct field).
    pub fn is_member(&self) -> bool {
        self.tag == dwarf_tag::MEMBER
    }

    /// Returns true if this is an inheritance descriptor.
    pub fn is_inheritance(&self) -> bool {
        self.tag == dwarf_tag::INHERITANCE
    }

    /// Set the DWARF flags (builder pattern).
    pub fn with_dw_flags(mut self, flags: u32) -> Self {
        self.dw_flags = flags;
        self
    }

    /// Set the scope (builder pattern).
    pub fn with_scope(mut self, scope: u32) -> Self {
        self.scope = Some(scope);
        self
    }

    /// Set the name (builder pattern).
    pub fn with_name(mut self, name: String) -> Self {
        self.name = Some(name);
        self
    }

    /// Set the file and line (builder pattern).
    pub fn with_file_line(mut self, file: u32, line: u32) -> Self {
        self.file = Some(file);
        self.line = Some(line);
        self
    }
}

impl DIScope for DIDerivedType {
    fn get_scope_name(&self) -> &str {
        self.name.as_deref().unwrap_or("<derived>")
    }

    fn get_scope_file(&self) -> Option<u32> {
        self.file
    }

    fn get_scope_line(&self) -> Option<u32> {
        self.line
    }
}

/// DICompositeType — a composite type descriptor (struct, class, union,
/// array, enum, etc.).
///
/// @llvm_behavior: `DICompositeType` maps to `!DICompositeType(...)` in
/// LLVM IR. It describes aggregate types with their elements (members,
/// enumerators, subscripts), vtable holder, template parameters, and
/// optional ODR-unique identifier.
#[derive(Debug, Clone)]
pub struct DICompositeType {
    /// DWARF tag (e.g., DW_TAG_structure_type = 19, DW_TAG_array_type = 1).
    pub tag: u32,
    /// Optional type name.
    pub name: Option<String>,
    /// Metadata ID of the DIFile where this type is defined.
    pub file: Option<u32>,
    /// Line number where this type is defined.
    pub line: Option<u32>,
    /// Metadata ID of the parent scope.
    pub scope: Option<u32>,
    /// Metadata ID of the base type (for arrays: element type; for enums: underlying type).
    pub base_type: Option<u32>,
    /// Size of the type in bits.
    pub size: u64,
    /// Alignment of the type in bits.
    pub align: u32,
    /// Offset in bits (for nested types).
    pub offset: u64,
    /// Flags.
    pub flags: u32,
    /// Metadata IDs of element types (members for struct, elements for array,
    /// enumerators for enum).
    pub elements: Vec<u32>,
    /// Metadata ID of the vtable holder (for classes with virtual dispatch).
    pub vtable_holder: Option<u32>,
    /// Metadata IDs of template parameters.
    pub template_params: Vec<u32>,
    /// Optional unique identifier string (for ODR-uniqued types).
    pub identifier: Option<String>,
    /// Runtime language (e.g., Objective-C runtime version).
    pub runtime_lang: u32,
    /// Optional discriminator type (for variant parts).
    pub discriminator: Option<u32>,
    /// Optional data location expression.
    pub data_location: Option<u32>,
    /// Optional associated metadata.
    pub associated: Option<u32>,
    /// Optional allocated metadata.
    pub allocated: Option<u32>,
    /// Optional rank (for assumed-rank arrays).
    pub rank: Option<u32>,
}

impl DICompositeType {
    /// Create a new DICompositeType.
    pub fn new(tag: u32, name: Option<String>, size: u64, align: u32, offset: u64) -> Self {
        Self {
            tag,
            name,
            file: None,
            line: None,
            scope: None,
            base_type: None,
            size,
            align,
            offset,
            flags: 0,
            elements: Vec::new(),
            vtable_holder: None,
            template_params: Vec::new(),
            identifier: None,
            runtime_lang: 0,
            discriminator: None,
            data_location: None,
            associated: None,
            allocated: None,
            rank: None,
        }
    }

    /// Create a struct type.
    pub fn struct_type(name: String, size: u64, align: u32, file: u32, line: u32) -> Self {
        let mut ty = Self::new(dwarf_tag::STRUCTURE_TYPE, Some(name), size, align, 0);
        ty.file = Some(file);
        ty.line = Some(line);
        ty
    }

    /// Create a class type.
    pub fn class_type(name: String, size: u64, align: u32, file: u32, line: u32) -> Self {
        let mut ty = Self::new(dwarf_tag::CLASS_TYPE, Some(name), size, align, 0);
        ty.file = Some(file);
        ty.line = Some(line);
        ty
    }

    /// Create a union type.
    pub fn union_type(name: String, size: u64, align: u32, file: u32, line: u32) -> Self {
        let mut ty = Self::new(dwarf_tag::UNION_TYPE, Some(name), size, align, 0);
        ty.file = Some(file);
        ty.line = Some(line);
        ty
    }

    /// Create an array type.
    pub fn array_type(
        name: String,
        element_type: u32,
        size: u64,
        align: u32,
        subscripts: Vec<u32>,
    ) -> Self {
        let mut ty = Self::new(dwarf_tag::ARRAY_TYPE, Some(name), size, align, 0);
        ty.base_type = Some(element_type);
        ty.elements = subscripts;
        ty
    }

    /// Create an enumeration type.
    pub fn enum_type(
        name: String,
        underlying_type: u32,
        size: u64,
        align: u32,
        file: u32,
        line: u32,
        enumerators: Vec<u32>,
    ) -> Self {
        let mut ty = Self::new(dwarf_tag::ENUMERATION_TYPE, Some(name), size, align, 0);
        ty.base_type = Some(underlying_type);
        ty.file = Some(file);
        ty.line = Some(line);
        ty.elements = enumerators;
        ty
    }

    /// Returns true if this is a struct or class type.
    pub fn is_struct_or_class(&self) -> bool {
        self.tag == dwarf_tag::STRUCTURE_TYPE || self.tag == dwarf_tag::CLASS_TYPE
    }

    /// Returns true if this is a union type.
    pub fn is_union(&self) -> bool {
        self.tag == dwarf_tag::UNION_TYPE
    }

    /// Returns true if this is an array type.
    pub fn is_array(&self) -> bool {
        self.tag == dwarf_tag::ARRAY_TYPE
    }

    /// Returns true if this is an enumeration type.
    pub fn is_enum(&self) -> bool {
        self.tag == dwarf_tag::ENUMERATION_TYPE
    }

    /// Returns true if this is a forward declaration (no size, no elements).
    pub fn is_forward_declaration(&self) -> bool {
        self.size == 0 && self.elements.is_empty()
    }

    /// Returns true if this is a complete definition.
    pub fn is_complete_definition(&self) -> bool {
        !self.is_forward_declaration()
    }

    /// Add an element (member/enumerator/subscript) metadata ID.
    pub fn add_element(&mut self, element_id: u32) {
        self.elements.push(element_id);
    }

    /// Add a template parameter metadata ID.
    pub fn add_template_param(&mut self, param_id: u32) {
        self.template_params.push(param_id);
    }

    /// Set the ODR-unique identifier (builder pattern).
    pub fn with_identifier(mut self, identifier: String) -> Self {
        self.identifier = Some(identifier);
        self
    }

    /// Set the vtable holder (builder pattern).
    pub fn with_vtable_holder(mut self, vtable_holder: u32) -> Self {
        self.vtable_holder = Some(vtable_holder);
        self
    }

    /// Set the scope (builder pattern).
    pub fn with_scope(mut self, scope: u32) -> Self {
        self.scope = Some(scope);
        self
    }

    /// Set the flags (builder pattern).
    pub fn with_flags(mut self, flags: u32) -> Self {
        self.flags = flags;
        self
    }

    /// Set the discriminator for variant parts (builder pattern).
    pub fn with_discriminator(mut self, disc: u32) -> Self {
        self.discriminator = Some(disc);
        self
    }

    /// Set the data location expression (builder pattern).
    pub fn with_data_location(mut self, dl: u32) -> Self {
        self.data_location = Some(dl);
        self
    }

    /// Set the rank for assumed-rank arrays (builder pattern).
    pub fn with_rank(mut self, rank: u32) -> Self {
        self.rank = Some(rank);
        self
    }
}

impl DIScope for DICompositeType {
    fn get_scope_name(&self) -> &str {
        self.name.as_deref().unwrap_or("<unnamed>")
    }

    fn get_scope_file(&self) -> Option<u32> {
        self.file
    }

    fn get_scope_line(&self) -> Option<u32> {
        self.line
    }
}

/// DISubroutineType — a subroutine type descriptor (function signature).
///
/// @llvm_behavior: `DISubroutineType` maps to `!DISubroutineType(...)` in
/// LLVM IR. It describes the type signature of a function: the first element
/// in the `types` array is the return type; subsequent elements are the
/// parameter types in declaration order.
#[derive(Debug, Clone)]
pub struct DISubroutineType {
    /// Flags (e.g., calling convention info).
    pub flags: u32,
    /// Metadata IDs of type nodes. `types[0]` is the return type;
    /// `types[1..]` are the parameter types. May be empty for void-returning
    /// functions with no parameters.
    pub types: Vec<u32>,
    /// Optional calling convention.
    pub cc: Option<u32>,
}

impl DISubroutineType {
    /// Create a new DISubroutineType.
    pub fn new(flags: u32, types: Vec<u32>) -> Self {
        Self {
            flags,
            types,
            cc: None,
        }
    }

    /// Create a subroutine type with a return type and parameter types.
    pub fn with_signature(return_type: u32, param_types: Vec<u32>) -> Self {
        let mut types = vec![return_type];
        types.extend(param_types);
        Self::new(0, types)
    }

    /// Create a void-returning subroutine type.
    pub fn void_returning(param_types: Vec<u32>) -> Self {
        let mut types = Vec::with_capacity(param_types.len() + 1);
        types.push(0); // null = void in DWARF
        types.extend(param_types);
        Self::new(0, types)
    }

    /// Returns the return type metadata ID (first element of types).
    /// Returns None if the types list is empty.
    pub fn return_type(&self) -> Option<u32> {
        self.types.first().copied()
    }

    /// Returns the parameter type metadata IDs (everything after the return type).
    pub fn param_types(&self) -> &[u32] {
        if self.types.is_empty() {
            &[]
        } else {
            &self.types[1..]
        }
    }

    /// Returns the total number of types (return type + parameters).
    pub fn num_types(&self) -> usize {
        self.types.len()
    }

    /// Returns the number of parameters.
    pub fn num_params(&self) -> usize {
        if self.types.is_empty() {
            0
        } else {
            self.types.len() - 1
        }
    }

    /// Add a parameter type (appended to the end of the types list).
    pub fn add_param_type(&mut self, ty: u32) {
        self.types.push(ty);
    }

    /// Set the calling convention (builder pattern).
    pub fn with_cc(mut self, cc: u32) -> Self {
        self.cc = Some(cc);
        self
    }

    /// Set the flags (builder pattern).
    pub fn with_flags(mut self, flags: u32) -> Self {
        self.flags = flags;
        self
    }
}

impl DIScope for DISubroutineType {
    fn get_scope_name(&self) -> &str {
        "<subroutine>"
    }

    fn get_scope_file(&self) -> Option<u32> {
        None
    }

    fn get_scope_line(&self) -> Option<u32> {
        None
    }
}

/// DIEnumerator — an enumerator value descriptor.
///
/// @llvm_behavior: `DIEnumerator` maps to `!DIEnumerator(...)` in LLVM IR.
/// It describes a named constant value in an enumeration type.
#[derive(Debug, Clone)]
pub struct DIEnumerator {
    /// The enumerator name.
    pub name: String,
    /// The enumerator value (signed representation).
    pub value: i64,
    /// Whether the value should be interpreted as unsigned.
    pub is_unsigned: bool,
}

impl DIEnumerator {
    /// Create a new DIEnumerator.
    pub fn new(name: String, value: i64, is_unsigned: bool) -> Self {
        Self {
            name,
            value,
            is_unsigned,
        }
    }

    /// Create a signed enumerator.
    pub fn signed(name: String, value: i64) -> Self {
        Self::new(name, value, false)
    }

    /// Create an unsigned enumerator.
    pub fn unsigned(name: String, value: u64) -> Self {
        Self::new(name, value as i64, true)
    }

    /// Returns the value as u64 if unsigned. Panics if called on a signed
    /// enumerator with a negative value.
    pub fn value_as_u64(&self) -> u64 {
        if self.is_unsigned {
            self.value as u64
        } else {
            assert!(
                self.value >= 0,
                "Cannot convert negative signed enumerator value to u64"
            );
            self.value as u64
        }
    }

    /// Returns the value as i64.
    pub fn value_as_i64(&self) -> i64 {
        self.value
    }

    /// Returns a display representation of the value.
    pub fn value_display(&self) -> String {
        if self.is_unsigned {
            format!("{}", self.value as u64)
        } else {
            format!("{}", self.value)
        }
    }
}

/// DINamespace — a namespace descriptor.
///
/// @llvm_behavior: `DINamespace` maps to `!DINamespace(...)` in LLVM IR.
/// It describes a C++ namespace or module-level scope.
#[derive(Debug, Clone)]
pub struct DINamespace {
    /// The namespace name.
    pub name: String,
    /// Metadata ID of the parent scope (typically the enclosing namespace,
    /// compile unit, or another namespace).
    pub scope: u32,
    /// Whether this namespace exports its symbols (e.g., inline namespace).
    pub export_symbols: bool,
}

impl DINamespace {
    /// Create a new DINamespace.
    pub fn new(name: String, scope: u32, export_symbols: bool) -> Self {
        Self {
            name,
            scope,
            export_symbols,
        }
    }

    /// Create a regular (non-exporting) namespace.
    pub fn regular(name: String, scope: u32) -> Self {
        Self::new(name, scope, false)
    }

    /// Create an inline/exporting namespace.
    pub fn exporting(name: String, scope: u32) -> Self {
        Self::new(name, scope, true)
    }

    /// Returns true if this is an inline (exporting) namespace.
    pub fn is_inline(&self) -> bool {
        self.export_symbols
    }
}

impl DIScope for DINamespace {
    fn get_scope_name(&self) -> &str {
        &self.name
    }

    fn get_scope_file(&self) -> Option<u32> {
        None
    }

    fn get_scope_line(&self) -> Option<u32> {
        None
    }
}

/// DITemplateTypeParameter — a template type parameter descriptor.
///
/// @llvm_behavior: `DITemplateTypeParameter` maps to
/// `!DITemplateTypeParameter(...)` in LLVM IR. It describes a type template
/// parameter in a templated entity (e.g., `typename T`).
#[derive(Debug, Clone)]
pub struct DITemplateTypeParameter {
    /// The parameter name (e.g., "T").
    pub name: String,
    /// Metadata ID of the parameter's type.
    pub ty: u32,
    /// Whether this is a default template parameter.
    pub is_default: bool,
}

impl DITemplateTypeParameter {
    /// Create a new DITemplateTypeParameter.
    pub fn new(name: String, ty: u32) -> Self {
        Self {
            name,
            ty,
            is_default: false,
        }
    }

    /// Mark this parameter as a default (builder pattern).
    pub fn with_default(mut self) -> Self {
        self.is_default = true;
        self
    }
}

/// DITemplateValueParameter — a template value parameter descriptor (non-type
/// template parameter).
///
/// @llvm_behavior: `DITemplateValueParameter` maps to
/// `!DITemplateValueParameter(...)` in LLVM IR. It describes a non-type
/// template parameter (e.g., `int N` in `template<int N>`).
#[derive(Debug, Clone)]
pub struct DITemplateValueParameter {
    /// The parameter name.
    pub name: String,
    /// Metadata ID of the parameter's type.
    pub ty: u32,
    /// The constant value (as a metadata operand).
    pub value: MetadataOperand,
    /// Whether this is a default template parameter.
    pub is_default: bool,
}

impl DITemplateValueParameter {
    /// Create a new DITemplateValueParameter.
    pub fn new(name: String, ty: u32, value: MetadataOperand) -> Self {
        Self {
            name,
            ty,
            value,
            is_default: false,
        }
    }

    /// Create a value parameter with an integer value.
    pub fn integer(name: String, ty: u32, val: i64) -> Self {
        let cv = ConstantValue::new_int(Type::i32(), val);
        Self::new(name, ty, MetadataOperand::Constant(cv))
    }

    /// Mark this parameter as a default (builder pattern).
    pub fn with_default(mut self) -> Self {
        self.is_default = true;
        self
    }
}

/// DIObjCProperty — an Objective-C property descriptor.
///
/// @llvm_behavior: `DIObjCProperty` maps to `!DIObjCProperty(...)` in
/// LLVM IR. It describes a property declaration in an Objective-C class.
#[derive(Debug, Clone)]
pub struct DIObjCProperty {
    /// The property name.
    pub name: String,
    /// Metadata ID of the file where the property is declared.
    pub file: u32,
    /// Line number of the declaration.
    pub line: u32,
    /// Getter method name.
    pub getter_name: String,
    /// Setter method name.
    pub setter_name: String,
    /// Property attributes (bitmask of ObjCPropertyAttribute values).
    pub attributes: u32,
    /// Metadata ID of the property's type.
    pub ty: u32,
}

/// Objective-C property attribute flags.
pub mod objc_property_attribute {
    pub const READONLY: u32 = 1 << 0;
    pub const READWRITE: u32 = 1 << 1;
    pub const ASSIGN: u32 = 1 << 2;
    pub const COPY: u32 = 1 << 3;
    pub const RETAIN: u32 = 1 << 4;
    pub const NONATOMIC: u32 = 1 << 5;
    pub const ATOMIC: u32 = 1 << 6;
    pub const WEAK: u32 = 1 << 7;
    pub const STRONG: u32 = 1 << 8;
    pub const UNSAFE_UNRETAINED: u32 = 1 << 9;
    pub const NULLABILITY: u32 = 1 << 10;
    pub const NULL_RESETTABLE: u32 = 1 << 11;
    pub const CLASS: u32 = 1 << 12;
    pub const DIRECT: u32 = 1 << 13;
}

impl DIObjCProperty {
    /// Create a new DIObjCProperty.
    pub fn new(
        name: String,
        file: u32,
        line: u32,
        getter_name: String,
        setter_name: String,
        attributes: u32,
        ty: u32,
    ) -> Self {
        Self {
            name,
            file,
            line,
            getter_name,
            setter_name,
            attributes,
            ty,
        }
    }

    /// Returns true if the property is read-only.
    pub fn is_readonly(&self) -> bool {
        self.attributes & objc_property_attribute::READONLY != 0
    }

    /// Returns true if the property is read-write.
    pub fn is_readwrite(&self) -> bool {
        self.attributes & objc_property_attribute::READWRITE != 0
    }

    /// Returns true if the property uses retain semantics.
    pub fn is_retain(&self) -> bool {
        self.attributes & objc_property_attribute::RETAIN != 0
    }

    /// Returns true if the property uses copy semantics.
    pub fn is_copy(&self) -> bool {
        self.attributes & objc_property_attribute::COPY != 0
    }

    /// Returns true if the property is non-atomic.
    pub fn is_nonatomic(&self) -> bool {
        self.attributes & objc_property_attribute::NONATOMIC != 0
    }

    /// Returns true if the property is weak.
    pub fn is_weak(&self) -> bool {
        self.attributes & objc_property_attribute::WEAK != 0
    }

    /// Returns true if the property is strong.
    pub fn is_strong(&self) -> bool {
        self.attributes & objc_property_attribute::STRONG != 0
    }
}

/// DIImportedEntity — an imported entity descriptor (using declaration,
/// using directive, etc.).
///
/// @llvm_behavior: `DIImportedEntity` maps to `!DIImportedEntity(...)` in
/// LLVM IR. It describes an entity imported into a scope, such as a C++
/// `using` declaration, `using namespace` directive, or module import.
#[derive(Debug, Clone)]
pub struct DIImportedEntity {
    /// DWARF tag (e.g., DW_TAG_imported_module = 58,
    /// DW_TAG_imported_declaration = 8).
    pub tag: u32,
    /// Metadata ID of the scope into which the entity is imported.
    pub scope: u32,
    /// Metadata ID of the imported entity/declaration.
    pub entity: u32,
    /// Metadata ID of the file where the import occurs.
    pub file: Option<u32>,
    /// Line number where the import occurs.
    pub line: Option<u32>,
    /// Optional name (for imported declarations).
    pub name: Option<String>,
}

impl DIImportedEntity {
    /// Create a new DIImportedEntity.
    pub fn new(tag: u32, scope: u32, entity: u32) -> Self {
        Self {
            tag,
            scope,
            entity,
            file: None,
            line: None,
            name: None,
        }
    }

    /// Create an imported module (using namespace / import module).
    pub fn imported_module(scope: u32, entity: u32) -> Self {
        Self::new(dwarf_tag::IMPORTED_MODULE, scope, entity)
    }

    /// Create an imported declaration (using declaration).
    pub fn imported_declaration(
        scope: u32,
        entity: u32,
        name: String,
        file: u32,
        line: u32,
    ) -> Self {
        Self {
            tag: dwarf_tag::IMPORTED_DECLARATION,
            scope,
            entity,
            file: Some(file),
            line: Some(line),
            name: Some(name),
        }
    }

    /// Returns true if this is an imported module.
    pub fn is_imported_module(&self) -> bool {
        self.tag == dwarf_tag::IMPORTED_MODULE
    }

    /// Returns true if this is an imported declaration.
    pub fn is_imported_declaration(&self) -> bool {
        self.tag == dwarf_tag::IMPORTED_DECLARATION
    }

    /// Set the file and line (builder pattern).
    pub fn with_file_line(mut self, file: u32, line: u32) -> Self {
        self.file = Some(file);
        self.line = Some(line);
        self
    }

    /// Set the name (builder pattern).
    pub fn with_name(mut self, name: String) -> Self {
        self.name = Some(name);
        self
    }
}

impl DIScope for DIImportedEntity {
    fn get_scope_name(&self) -> &str {
        self.name.as_deref().unwrap_or("<imported>")
    }

    fn get_scope_file(&self) -> Option<u32> {
        self.file
    }

    fn get_scope_line(&self) -> Option<u32> {
        self.line
    }
}

// ============================================================================
// DIFile extensions — additional methods for the existing DIFile struct
// ============================================================================

impl DIFile {
    /// Sets the checksum kind (e.g., "CSK_MD5", "CSK_SHA1", "CSK_SHA256").
    pub fn set_checksum_kind(&mut self, kind: String) {
        self.checksum_kind = Some(kind);
    }

    /// Sets the checksum value (hex-encoded digest string).
    pub fn set_checksum_value(&mut self, value: String) {
        self.checksum_value = Some(value);
    }

    /// Sets the source text (for embedded source support).
    pub fn set_source(&mut self, source: String) {
        self.source = Some(source);
    }

    /// Returns the checksum kind, if set.
    pub fn get_checksum_kind(&self) -> Option<&str> {
        self.checksum_kind.as_deref()
    }

    /// Returns the checksum value, if set.
    pub fn get_checksum_value(&self) -> Option<&str> {
        self.checksum_value.as_deref()
    }

    /// Returns the embedded source text, if set.
    pub fn get_source(&self) -> Option<&str> {
        self.source.as_deref()
    }

    /// Returns true if checksum information is present.
    pub fn has_checksum(&self) -> bool {
        self.checksum_kind.is_some() && self.checksum_value.is_some()
    }

    /// Returns true if source text is embedded.
    pub fn has_source(&self) -> bool {
        self.source.is_some()
    }

    /// Creates a builder-style setter for the checksum kind.
    pub fn with_checksum_kind(mut self, kind: String) -> Self {
        self.checksum_kind = Some(kind);
        self
    }

    /// Creates a builder-style setter for the checksum value.
    pub fn with_checksum_value(mut self, value: String) -> Self {
        self.checksum_value = Some(value);
        self
    }

    /// Creates a builder-style setter for the source text.
    pub fn with_source(mut self, source: String) -> Self {
        self.source = Some(source);
        self
    }

    /// Creates a MD5 checksum entry (convenience).
    pub fn with_md5_checksum(mut self, value: String) -> Self {
        self.checksum_kind = Some("CSK_MD5".to_string());
        self.checksum_value = Some(value);
        self
    }

    /// Creates a SHA1 checksum entry (convenience).
    pub fn with_sha1_checksum(mut self, value: String) -> Self {
        self.checksum_kind = Some("CSK_SHA1".to_string());
        self.checksum_value = Some(value);
        self
    }
}

// ============================================================================
// DIExpression — debug info expression for variable locations
// ============================================================================

/// A debug info expression: a sequence of DW_OP_* operations describing
/// how to compute the value or address of a variable.
///
/// @llvm_behavior: `DIExpression` maps to `!DIExpression(...)` in LLVM IR.
/// It encodes a DWARF expression — a sequence of opcodes that the debugger
/// evaluates to find the location of a variable. Common operations include
/// `DW_OP_regN` (value is in register N), `DW_OP_fbreg` (value is at an
/// offset from the frame base), and `DW_OP_LLVM_fragment` (the value is a
/// subrange of bits within a larger location).
///
/// The expression can also carry fragment information (offset and size in
/// bits) to describe partial locations (e.g., a struct field within a
/// register).
#[derive(Debug, Clone, PartialEq)]
pub struct DIExpression {
    /// DWARF expression element sequence (raw u64 values encoding opcodes
    /// and their operands).
    elements: Vec<u64>,
    /// Optional fragment information: (offset_in_bits, size_in_bits).
    /// This is extracted from a trailing `DW_OP_LLVM_fragment` if present.
    fragment: Option<(u64, u64)>,
}

impl DIExpression {
    /// Create a new DIExpression from a vector of elements.
    /// Fragment information is automatically extracted if a trailing
    /// `DW_OP_LLVM_fragment` is present.
    pub fn new(elements: Vec<u64>) -> Self {
        let mut expr = Self {
            elements,
            fragment: None,
        };
        expr.extract_fragment();
        expr
    }

    /// Create an empty DIExpression (no operations).
    pub fn empty() -> Self {
        Self {
            elements: Vec::new(),
            fragment: None,
        }
    }

    /// Create a DIExpression that represents a fragment of a value.
    /// `offset_in_bits` is the bit offset from the start of the containing
    /// location; `size_in_bits` is the number of bits in the fragment.
    pub fn create_fragment_expression(offset_in_bits: u64, size_in_bits: u64) -> Self {
        Self {
            elements: vec![dwarf_op::LLVM_FRAGMENT, offset_in_bits, size_in_bits],
            fragment: Some((offset_in_bits, size_in_bits)),
        }
    }

    /// Extract fragment information from the last three elements, if they
    /// form a `DW_OP_LLVM_fragment` operation.
    fn extract_fragment(&mut self) {
        let len = self.elements.len();
        if len >= 3 && self.elements[len - 3] == dwarf_op::LLVM_FRAGMENT {
            self.fragment = Some((self.elements[len - 2], self.elements[len - 1]));
        }
    }

    /// Returns true if the expression is valid (not empty or has fragment info).
    pub fn is_valid(&self) -> bool {
        !self.elements.is_empty() || self.fragment.is_some()
    }

    /// Returns the fragment information as (offset_in_bits, size_in_bits),
    /// if a fragment is present.
    pub fn get_fragment_info(&self) -> Option<(u64, u64)> {
        self.fragment
    }

    /// Returns the element at the given index, or None if out of bounds.
    pub fn get_element(&self, index: usize) -> Option<u64> {
        self.elements.get(index).copied()
    }

    /// Returns the total number of elements in the expression.
    pub fn get_num_elements(&self) -> usize {
        self.elements.len()
    }

    /// Returns the raw elements slice.
    pub fn elements(&self) -> &[u64] {
        &self.elements
    }

    /// Returns true if the expression is complex (more than a simple
    /// register or frame-base reference). A complex expression involves
    /// arithmetic, dereferencing, or multiple operations.
    pub fn is_complex(&self) -> bool {
        // An expression is complex if it has more than one operation
        // besides fragment info, or contains arithmetic/computation ops.
        let non_fragment_len = if self.fragment.is_some() {
            self.elements.len().saturating_sub(3)
        } else {
            self.elements.len()
        };
        if non_fragment_len > 2 {
            return true;
        }
        if non_fragment_len == 1 {
            let op = self.elements[0];
            // Simple single-op: register, fbreg, or empty.
            let is_simple_register = (dwarf_op::REG0..=dwarf_op::REG31).contains(&op);
            let is_simple_fbreg = op == dwarf_op::FBREG;
            if is_simple_register || is_simple_fbreg {
                return false;
            }
        }
        non_fragment_len > 0
    }

    /// Returns true if the expression is an implicit location description
    /// (last element is `DW_OP_stack_value` = 0x9f).
    pub fn is_implicit(&self) -> bool {
        self.elements
            .last()
            .map_or(false, |&e| e == dwarf_op::STACK_VALUE)
    }

    /// Returns true if the expression represents a constant value
    /// (starts with `DW_OP_constu` or `DW_OP_consts`).
    pub fn is_constant(&self) -> bool {
        if self.elements.is_empty() {
            return false;
        }
        let first = self.elements[0];
        first == dwarf_op::CONSTU || first == dwarf_op::CONSTS
    }

    /// Append an element to the expression. If a fragment is present at the
    /// end, the new element is inserted before the fragment operation.
    pub fn append(&mut self, element: u64) {
        if let Some(_) = self.fragment {
            let insert_pos = self.elements.len() - 3;
            self.elements.insert(insert_pos, element);
        } else {
            self.elements.push(element);
        }
    }

    /// Prepend an element to the beginning of the expression.
    pub fn prepend(&mut self, element: u64) {
        self.elements.insert(0, element);
    }

    /// Get the operand value that follows an opcode at the given index.
    /// For example, `DW_OP_constu` is followed by a ULEB128-encoded constant.
    /// Returns the next element in the sequence, or None if at the end.
    pub fn get_expr_operand(&self, index: usize) -> Option<u64> {
        if index + 1 < self.elements.len() {
            Some(self.elements[index + 1])
        } else {
            None
        }
    }

    /// Create a simple register expression (`DW_OP_regN`).
    /// The register number must be 0-31 for `DW_OP_reg0..DW_OP_reg31`.
    /// For register numbers >= 32 use `reg_x` instead.
    pub fn reg(register: u64) -> Self {
        assert!(register < 32, "Use reg_x for register numbers >= 32");
        Self {
            elements: vec![dwarf_op::REG0 + register],
            fragment: None,
        }
    }

    /// Create an extended register expression (`DW_OP_regx reg`).
    /// This supports any register number.
    pub fn reg_x(register: u64) -> Self {
        Self {
            elements: vec![dwarf_op::REGX, register],
            fragment: None,
        }
    }

    /// Create a frame-base relative expression (`DW_OP_fbreg offset`).
    /// `offset` is a signed offset from the frame base pointer.
    pub fn fb_reg(offset: i64) -> Self {
        Self {
            elements: vec![dwarf_op::FBREG, offset as u64],
            fragment: None,
        }
    }

    /// Create a "dereference" expression (`DW_OP_deref`).
    pub fn deref() -> Self {
        Self {
            elements: vec![dwarf_op::DEREF],
            fragment: None,
        }
    }

    /// Create a "plus" expression (`DW_OP_plus`).
    /// Pops two values from the stack and pushes their sum.
    pub fn plus() -> Self {
        Self {
            elements: vec![dwarf_op::PLUS],
            fragment: None,
        }
    }

    /// Create a constant unsigned expression (`DW_OP_constu val`).
    pub fn const_u(val: u64) -> Self {
        Self {
            elements: vec![dwarf_op::CONSTU, val],
            fragment: None,
        }
    }

    /// Create a constant signed expression (`DW_OP_consts val`).
    pub fn const_s(val: i64) -> Self {
        Self {
            elements: vec![dwarf_op::CONSTS, val as u64],
            fragment: None,
        }
    }

    /// Create a stack-value marker expression (`DW_OP_stack_value`).
    /// This marks the top of the stack as the value (vs. address) of the variable.
    pub fn stack_value() -> Self {
        Self {
            elements: vec![dwarf_op::STACK_VALUE],
            fragment: None,
        }
    }

    /// Create an "and" expression (`DW_OP_and`).
    pub fn and() -> Self {
        Self {
            elements: vec![dwarf_op::AND],
            fragment: None,
        }
    }

    /// Create an "or" expression (`DW_OP_or`).
    pub fn or() -> Self {
        Self {
            elements: vec![dwarf_op::OR],
            fragment: None,
        }
    }

    /// Create an "xor" expression (`DW_OP_xor`).
    pub fn xor() -> Self {
        Self {
            elements: vec![dwarf_op::XOR],
            fragment: None,
        }
    }

    /// Create a "not" expression (`DW_OP_not`).
    pub fn not() -> Self {
        Self {
            elements: vec![dwarf_op::NOT],
            fragment: None,
        }
    }

    /// Create a "neg" expression (`DW_OP_neg`).
    pub fn neg() -> Self {
        Self {
            elements: vec![dwarf_op::NEG],
            fragment: None,
        }
    }

    /// Create an "address of" expression (`DW_OP_addr` followed by address value).
    pub fn addr(address: u64) -> Self {
        Self {
            elements: vec![dwarf_op::ADDR, address],
            fragment: None,
        }
    }

    /// Create an entry value expression (`DW_OP_LLVM_entry_value`).
    /// This describes the value of a variable at function entry.
    pub fn entry_value(expr: &DIExpression) -> Self {
        let mut elements = vec![dwarf_op::LLVM_ENTRY_VALUE];
        // Encode the nested expression length and elements.
        elements.push(expr.elements.len() as u64);
        elements.extend_from_slice(&expr.elements);
        Self {
            elements,
            fragment: None,
        }
    }

    /// Create a bit-piece expression (DW_OP_bit_piece size offset).
    pub fn bit_piece(size_in_bits: u64, offset_in_bits: u64) -> Self {
        Self {
            elements: vec![dwarf_op::BIT_PIECE, size_in_bits, offset_in_bits],
            fragment: None,
        }
    }

    /// Add fragment information to the expression. If a fragment already
    /// exists, it is replaced.
    pub fn with_fragment(mut self, offset_in_bits: u64, size_in_bits: u64) -> Self {
        // Remove existing fragment if present.
        if self.fragment.is_some() {
            let len = self.elements.len();
            if len >= 3 && self.elements[len - 3] == dwarf_op::LLVM_FRAGMENT {
                self.elements.truncate(len - 3);
            }
        }
        self.elements.push(dwarf_op::LLVM_FRAGMENT);
        self.elements.push(offset_in_bits);
        self.elements.push(size_in_bits);
        self.fragment = Some((offset_in_bits, size_in_bits));
        self
    }

    /// Create an implicit pointer expression (DW_OP_implicit_pointer).
    pub fn implicit_pointer(deref_id: u64, offset: i64) -> Self {
        Self {
            elements: vec![dwarf_op::IMPLICIT_POINTER, deref_id, offset as u64],
            fragment: None,
        }
    }

    /// Returns a human-readable debug string for the expression.
    pub fn to_debug_string(&self) -> String {
        if self.elements.is_empty() {
            return "<empty>".to_string();
        }
        let parts: Vec<String> = self.elements.iter().map(|e| format!("0x{:x}", e)).collect();
        parts.join(", ")
    }

    /// Returns true if the expression can be folded to a constant at
    /// compile time (contains only constants and stack_value).
    pub fn is_constant_expression(&self) -> bool {
        if self.elements.is_empty() {
            return false;
        }
        // A constant expression starts with a const operation and ends
        // with stack_value.
        let first = self.elements[0];
        let last = *self.elements.last().unwrap();
        matches!(first, dwarf_op::CONSTU | dwarf_op::CONSTS) && last == dwarf_op::STACK_VALUE
    }

    /// Combine two expressions by concatenating their elements (excluding
    /// fragments).
    pub fn combine(&self, other: &DIExpression) -> Self {
        let mut elements = Vec::with_capacity(
            self.non_fragment_elements().len() + other.non_fragment_elements().len(),
        );
        elements.extend_from_slice(self.non_fragment_elements());
        elements.extend_from_slice(other.non_fragment_elements());
        Self::new(elements)
    }

    /// Returns the elements excluding any trailing fragment operation.
    fn non_fragment_elements(&self) -> &[u64] {
        if self.fragment.is_some() && self.elements.len() >= 3 {
            &self.elements[..self.elements.len() - 3]
        } else {
            &self.elements
        }
    }
}

// ============================================================================
// Metadata Attachment — per-value metadata associations
// ============================================================================

/// Methods for attaching metadata to IR values (instructions, globals,
/// functions, etc.).
///
/// @llvm_behavior: LLVM allows metadata to be "attached" to instructions
/// and other values using a metadata kind string. For example, a load
/// instruction might have `!tbaa !5` and `!alias.scope !10` attached.
/// These methods manage those per-value, per-kind associations.
impl MetadataStore {
    /// Attach metadata of a given kind to a value.
    ///
    /// `value_index` identifies the IR value (instruction index, global index,
    /// etc.). `kind` is the metadata kind name (e.g., `"dbg"`, `"tbaa"`).
    /// `metadata_id` is the metadata node ID to attach.
    ///
    /// Multiple metadata of different kinds can be attached to the same value.
    pub fn attach_metadata(&mut self, value_index: usize, kind: &str, metadata_id: u32) {
        let attachments = self.metadata_attachments.entry(value_index).or_default();
        attachments.push((kind.to_string(), metadata_id));
    }

    /// Get the metadata attachment for a specific value and kind.
    ///
    /// Returns the metadata ID if found, or `None` if no attachment of that
    /// kind exists for the given value.
    pub fn get_metadata_attachment(&self, value_index: usize, kind: &str) -> Option<u32> {
        self.metadata_attachments
            .get(&value_index)
            .and_then(|attachments| {
                attachments
                    .iter()
                    .find(|(k, _)| k == kind)
                    .map(|(_, id)| *id)
            })
    }

    /// Erase (remove) a specific metadata attachment from a value.
    ///
    /// If no attachment of the given kind exists for the value, this is a no-op.
    pub fn erase_metadata_attachment(&mut self, value_index: usize, kind: &str) {
        if let Some(attachments) = self.metadata_attachments.get_mut(&value_index) {
            attachments.retain(|(k, _)| k != kind);
        }
    }

    /// Get all metadata attachments for a value.
    ///
    /// Returns a slice of `(kind, metadata_id)` pairs. The returned slice
    /// is empty if no attachments exist for the given value.
    pub fn get_all_metadata_attachments(&self, value_index: usize) -> &[(String, u32)] {
        match self.metadata_attachments.get(&value_index) {
            Some(attachments) => attachments.as_slice(),
            None => &[],
        }
    }

    /// Set (replace or add) a metadata attachment for a value.
    ///
    /// If an attachment of the same kind already exists for the given value,
    /// it is replaced with the new metadata ID. Otherwise, the attachment
    /// is added as a new entry.
    pub fn set_metadata_attachment(&mut self, value_index: usize, kind: &str, metadata_id: u32) {
        let attachments = self.metadata_attachments.entry(value_index).or_default();
        if let Some(existing) = attachments.iter_mut().find(|(k, _)| k == kind) {
            *existing = (kind.to_string(), metadata_id);
        } else {
            attachments.push((kind.to_string(), metadata_id));
        }
    }

    /// Returns true if the given value has any metadata attachments.
    pub fn has_metadata_attachments(&self, value_index: usize) -> bool {
        self.metadata_attachments
            .get(&value_index)
            .map_or(false, |v| !v.is_empty())
    }

    /// Remove all metadata attachments from a value.
    pub fn erase_all_metadata_attachments(&mut self, value_index: usize) {
        self.metadata_attachments.remove(&value_index);
    }

    /// Returns the number of metadata attachments for a value.
    pub fn num_metadata_attachments(&self, value_index: usize) -> usize {
        self.metadata_attachments
            .get(&value_index)
            .map_or(0, |v| v.len())
    }

    /// Iterate over all values that have metadata attachments.
    /// Returns an iterator yielding `(value_index, &[(kind, id)])` pairs.
    pub fn iter_metadata_attachments(&self) -> impl Iterator<Item = (usize, &[(String, u32)])> {
        self.metadata_attachments
            .iter()
            .map(|(&idx, attachments)| (idx, attachments.as_slice()))
    }

    /// Copy all metadata attachments from one value to another.
    pub fn copy_metadata_attachments(&mut self, from: usize, to: usize) {
        if let Some(attachments) = self.metadata_attachments.get(&from) {
            let cloned: Vec<(String, u32)> = attachments.clone();
            self.metadata_attachments.insert(to, cloned);
        }
    }
}

// ============================================================================
// Extended MetadataStore Methods — temporary nodes, uniquing, named metadata
// ============================================================================

impl MetadataStore {
    /// Get a metadata string value by ID. Returns the string if the metadata
    /// at the given ID is an MDString, or `None` otherwise.
    ///
    /// This complements the existing `create_md_string` with a getter.
    pub fn get_md_string(&self, id: u32) -> Option<&str> {
        self.get_metadata(id).and_then(|mv| match &mv.kind {
            MetadataKind::MDString(s) => Some(s.as_str()),
            _ => None,
        })
    }

    /// Create a temporary metadata node. Temporary nodes can be created
    /// before all their operands are known, and later resolved (replaced)
    /// with final metadata nodes.
    ///
    /// @llvm_behavior: LLVM's `MDNode::getTemporary()` creates a node that
    /// is not yet uniqued and can be replaced via RAUW.
    pub fn create_temporary_md_node(&mut self, operands: Vec<MetadataOperand>) -> u32 {
        let id = self.values.len() as u32;
        self.values.push(MetadataValue {
            id,
            kind: MetadataKind::MDNode(operands.clone()),
        });
        self.temporary_nodes
            .insert(id, TemporaryNodeState::new(operands));
        id
    }

    /// Replace a temporary MDNode with a resolved (permanent) node.
    ///
    /// Conceptually, all uses of the temporary node are updated to refer
    /// to the replacement. In this implementation, the temporary node's
    /// value is updated in-place and its state is marked as resolved.
    pub fn replace_temporary_md_node(&mut self, temp_id: u32, replacement_id: u32) {
        if let Some(temp) = self.temporary_nodes.get_mut(&temp_id) {
            temp.resolved = true;
            temp.replacement = Some(replacement_id);
        }
        // Update the stored metadata value to reference the replacement.
        if let Some(mv) = self.values.get_mut(temp_id as usize) {
            mv.kind = MetadataKind::MDNode(vec![MetadataOperand::Metadata(replacement_id)]);
        }
    }

    /// Resolve all temporary MDNodes by walking all metadata values and
    /// replacing references to resolved temporaries with their replacements.
    ///
    /// This processes named nodes and all MDNode/MDTuple operands.
    pub fn resolve_temporary_md_nodes(&mut self) {
        // Collect all resolved replacements.
        let replacements: Vec<(u32, u32)> = self
            .temporary_nodes
            .iter()
            .filter_map(|(&temp_id, state)| {
                if state.resolved {
                    state.replacement.map(|rep_id| (temp_id, rep_id))
                } else {
                    None
                }
            })
            .collect();

        if replacements.is_empty() {
            return;
        }

        // Walk all metadata values and replace references.
        for mv in &mut self.values {
            match &mut mv.kind {
                MetadataKind::MDNode(ops)
                | MetadataKind::DistinctMDNode(ops)
                | MetadataKind::MDTuple(ops) => {
                    for op in ops {
                        if let MetadataOperand::Metadata(id) = op {
                            for (temp_id, rep_id) in &replacements {
                                if *id == *temp_id {
                                    *id = *rep_id;
                                }
                            }
                        }
                    }
                }
                _ => {}
            }
        }

        // Update named metadata nodes.
        for (_name, operands) in &mut self.named_nodes {
            for op_id in operands {
                for (temp_id, rep_id) in &replacements {
                    if *op_id == *temp_id {
                        *op_id = *rep_id;
                    }
                }
            }
        }

        // Update metadata attachments.
        for (_value_idx, attachments) in &mut self.metadata_attachments {
            for (_kind, md_id) in attachments {
                for (temp_id, rep_id) in &replacements {
                    if *md_id == *temp_id {
                        *md_id = *rep_id;
                    }
                }
            }
        }
    }

    /// Returns true if the metadata at the given ID is marked as distinct.
    ///
    /// Distinct nodes are guaranteed to be unique even if structurally
    /// identical to another node. They are never merged or uniqued.
    pub fn is_distinct(&self, id: u32) -> bool {
        self.get_metadata(id).map_or(false, |mv| {
            matches!(mv.kind, MetadataKind::DistinctMDNode(_))
        })
    }

    /// Returns true if the metadata at the given ID is a temporary node.
    pub fn is_temporary(&self, id: u32) -> bool {
        self.temporary_nodes.contains_key(&id)
    }

    /// Returns true if the temporary node at the given ID has been resolved
    /// (replaced) with a permanent node.
    pub fn is_resolved(&self, id: u32) -> bool {
        self.temporary_nodes
            .get(&id)
            .map_or(false, |state| state.resolved)
    }

    /// Returns true if the metadata at the given ID is uniqued (not distinct
    /// and not temporary). Uniqued nodes with identical operands may be
    /// merged with existing nodes when created.
    pub fn is_uniqued(&self, id: u32) -> bool {
        self.get_metadata(id).map_or(false, |mv| {
            matches!(mv.kind, MetadataKind::MDNode(_) | MetadataKind::MDTuple(_))
                && !self.temporary_nodes.contains_key(&id)
        })
    }

    /// Create a uniqued MDNode. If an existing MDNode has identical operands
    /// (and is not temporary), its ID is returned instead of creating a new
    /// node. Otherwise, a new MDNode is created.
    pub fn create_uniqued_md_node(&mut self, operands: Vec<MetadataOperand>) -> u32 {
        // Search for an existing MDNode with identical operands.
        for mv in &self.values {
            if let MetadataKind::MDNode(existing_ops) = &mv.kind {
                // Skip temporary nodes — temporaries are never uniqued against.
                if self.temporary_nodes.contains_key(&mv.id) {
                    continue;
                }
                if operands_match(existing_ops, &operands) {
                    return mv.id;
                }
            }
        }
        // No match found; create a new one.
        self.create_md_node(operands)
    }

    /// Add a named metadata node. Alias for `add_named_node`.
    pub fn add_named_metadata(&mut self, name: &str, operands: Vec<u32>) {
        self.add_named_node(name, operands);
    }

    /// Get a named metadata node's operands by name. Alias for `get_named_node`.
    pub fn get_named_metadata(&self, name: &str) -> Option<&Vec<u32>> {
        self.get_named_node(name)
    }

    /// Get or create a named metadata node. If the named node does not exist,
    /// it is created with an empty operand list. Returns an immutable reference
    /// to the operand list.
    pub fn get_or_create_named_metadata(&mut self, name: &str) -> &Vec<u32> {
        if !self.named_nodes.contains_key(name) {
            self.named_nodes.insert(name.to_string(), Vec::new());
        }
        self.named_nodes.get(name).unwrap()
    }

    /// Get or create a named metadata node with mutable access to the operand
    /// list.
    pub fn get_or_create_named_metadata_mut(&mut self, name: &str) -> &mut Vec<u32> {
        self.named_nodes
            .entry(name.to_string())
            .or_insert_with(Vec::new)
    }

    /// Erase (remove) a named metadata node. Alias for `remove_named_node`.
    pub fn erase_named_metadata(&mut self, name: &str) {
        self.remove_named_node(name);
    }

    /// Returns true if the given metadata ID is a distinct node.
    /// This is the same as `is_distinct`, provided for API completeness.
    pub fn is_distinct_node(&self, id: u32) -> bool {
        self.is_distinct(id)
    }

    /// Returns true if the given metadata ID is a temporary node that has
    /// not yet been resolved.
    pub fn is_unresolved_temporary(&self, id: u32) -> bool {
        self.is_temporary(id) && !self.is_resolved(id)
    }

    /// Return the replacement ID for a resolved temporary node, if any.
    pub fn get_temporary_replacement(&self, id: u32) -> Option<u32> {
        self.temporary_nodes
            .get(&id)
            .and_then(|state| state.replacement)
    }

    /// Returns the number of temporary metadata nodes (both resolved and
    /// unresolved).
    pub fn num_temporaries(&self) -> usize {
        self.temporary_nodes.len()
    }

    /// Returns the number of unresolved temporary nodes.
    pub fn num_unresolved_temporaries(&self) -> usize {
        self.temporary_nodes
            .values()
            .filter(|state| !state.resolved)
            .count()
    }

    /// Add a DIBasicType to the store and return its metadata ID.
    /// The DIBasicType is converted to the common DIType format for
    /// storage compatibility.
    pub fn add_di_basic_type(&mut self, basic: DIBasicType) -> u32 {
        let id = self.debug_types.len() as u32;
        let ty = DIType {
            name: basic.name,
            size_in_bits: basic.size_in_bits,
            align_in_bits: basic.align_in_bits,
            offset_in_bits: 0,
            encoding: basic.encoding,
            base_type: None,
            file: None,
            line: None,
            tag: 36, // DW_TAG_base_type
            flags: basic.flags,
        };
        self.debug_types.push(Some(ty));
        id
    }

    /// Returns an iterator over all metadata values (excluding named nodes).
    pub fn iter_metadata(&self) -> impl Iterator<Item = &MetadataValue> {
        self.values.iter()
    }

    /// Returns an iterator over all named metadata entries.
    pub fn iter_named_metadata(&self) -> impl Iterator<Item = (&String, &Vec<u32>)> {
        self.named_nodes.iter()
    }

    /// Dump the entire metadata store to a human-readable string (for
    /// debugging).
    pub fn dump_debug(&self) -> String {
        let mut lines = Vec::new();
        lines.push(format!(
            "MetadataStore: {} values, {} named nodes",
            self.values.len(),
            self.named_nodes.len()
        ));
        for mv in &self.values {
            let kind_str = match &mv.kind {
                MetadataKind::MDString(s) => format!("MDString(\"{}\")", s),
                MetadataKind::Constant(c) => format!("Constant({})", c.to_string()),
                MetadataKind::Value(v) => format!("Value(%{})", v),
                MetadataKind::MDNode(ops) => {
                    format!("MDNode([{} ops])", ops.len())
                }
                MetadataKind::DistinctMDNode(ops) => {
                    format!("DistinctMDNode([{} ops])", ops.len())
                }
                MetadataKind::MDTuple(ops) => {
                    format!("MDTuple([{} ops])", ops.len())
                }
                MetadataKind::NamedNode(name, _) => format!("NamedNode({})", name),
            };
            lines.push(format!("  !{} = {}", mv.id, kind_str));
        }
        for (name, ops) in &self.named_nodes {
            lines.push(format!("  !{} -> [{} ops]", name, ops.len()));
        }
        lines.join("\n")
    }
}

/// Compare two metadata operand slices for structural equality.
///
/// Two operand slices match if they have the same length and each pair
/// of corresponding operands is equal. Constant equality is checked
/// by debug string representation (a simplification; full implementations
/// would compare constant values directly).
fn operands_match(a: &[MetadataOperand], b: &[MetadataOperand]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    a.iter().zip(b.iter()).all(|(a, b)| match (a, b) {
        (MetadataOperand::Metadata(id_a), MetadataOperand::Metadata(id_b)) => id_a == id_b,
        (MetadataOperand::MDString(s_a), MetadataOperand::MDString(s_b)) => s_a == s_b,
        (MetadataOperand::Null, MetadataOperand::Null) => true,
        (MetadataOperand::Value(v_a), MetadataOperand::Value(v_b)) => v_a == v_b,
        (MetadataOperand::Constant(c_a), MetadataOperand::Constant(c_b)) => {
            c_a.to_string() == c_b.to_string()
        }
        _ => false,
    })
}

// ============================================================================
// Checksum Kind Constants
// ============================================================================

/// Standard checksum kind strings for DIFile.
pub mod checksum_kind {
    pub const MD5: &str = "CSK_MD5";
    pub const SHA1: &str = "CSK_SHA1";
    pub const SHA256: &str = "CSK_SHA256";
}

// ============================================================================
// Emission Kind Constants
// ============================================================================

/// Emission kind values for DICompileUnit.
pub mod emission_kind {
    pub const FULL_DEBUG: u32 = 0;
    pub const LINE_TABLES_ONLY: u32 = 1;
    pub const NO_DEBUG: u32 = 2;
}

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

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

    // === MetadataOperand tests ===

    #[test]
    fn test_metadata_operand_is_metadata_ref() {
        let op_ref = MetadataOperand::Metadata(42);
        assert!(op_ref.is_metadata_ref());
        assert_eq!(op_ref.as_metadata_id(), Some(42));

        let op_str = MetadataOperand::MDString("hello".to_string());
        assert!(!op_str.is_metadata_ref());
        assert_eq!(op_str.as_metadata_id(), None);

        let op_null = MetadataOperand::Null;
        assert!(!op_null.is_metadata_ref());
        assert_eq!(op_null.as_metadata_id(), None);
    }

    #[test]
    fn test_metadata_operand_debug_string() {
        assert_eq!(MetadataOperand::Metadata(7).to_debug_string(), "!7");
        assert_eq!(
            MetadataOperand::MDString("test".to_string()).to_debug_string(),
            "!\"test\""
        );
        assert_eq!(MetadataOperand::Null.to_debug_string(), "null");
    }

    // === ConstantValue tests ===

    #[test]
    fn test_constant_value_to_string() {
        let ci = ConstantValue::new_int(crate::types::Type::i32(), 42);
        assert_eq!(ci.to_string(), "i32 42");

        let cf = ConstantValue::new_float(crate::types::Type::double(), 3.14);
        assert!(cf.to_string().contains("3.14"));

        let cn = ConstantValue::null(crate::types::Type::pointer(0));
        assert_eq!(cn.to_string(), "null");
    }

    // === MetadataStore basic tests ===

    #[test]
    fn test_metadata_store_new_empty() {
        let store = MetadataStore::new();
        assert!(store.is_empty());
        assert_eq!(store.count(), 0);
    }

    #[test]
    fn test_metadata_store_add_and_get() {
        let mut store = MetadataStore::new();

        let id1 = store.add_metadata(MetadataKind::MDString("hello".to_string()));
        let id2 = store.add_metadata(MetadataKind::MDString("world".to_string()));

        assert_eq!(id1, 0);
        assert_eq!(id2, 1);
        assert_eq!(store.count(), 2);

        let mv1 = store.get_metadata(0);
        assert!(mv1.is_some());
        if let MetadataKind::MDString(s) = &mv1.unwrap().kind {
            assert_eq!(s, "hello");
        } else {
            panic!("Expected MDString");
        }

        assert!(store.get_metadata(999).is_none());
    }

    #[test]
    fn test_metadata_store_mdnode() {
        let mut store = MetadataStore::new();

        let str_id = store.create_md_string("my_string");
        let node_id = store.create_md_node(vec![
            MetadataOperand::MDString("key".to_string()),
            MetadataOperand::Metadata(str_id),
            MetadataOperand::Null,
        ]);

        assert_eq!(str_id, 0);
        assert_eq!(node_id, 1);
        assert_eq!(store.count(), 2);

        let node = store.get_metadata(node_id).unwrap();
        match &node.kind {
            MetadataKind::MDNode(ops) => {
                assert_eq!(ops.len(), 3);
            }
            _ => panic!("Expected MDNode"),
        }
    }

    #[test]
    fn test_metadata_store_named_nodes() {
        let mut store = MetadataStore::new();

        let id0 = store.add_metadata(MetadataKind::MDString("flag1".to_string()));
        let id1 = store.add_metadata(MetadataKind::MDString("flag2".to_string()));

        store.add_named_node("llvm.module.flags", vec![id0, id1]);

        assert!(store.has_named_node("llvm.module.flags"));
        assert!(!store.has_named_node("nonexistent"));

        let ops = store.get_named_node("llvm.module.flags").unwrap();
        assert_eq!(ops.len(), 2);
        assert_eq!(ops[0], id0);
        assert_eq!(ops[1], id1);

        store.remove_named_node("llvm.module.flags");
        assert!(!store.has_named_node("llvm.module.flags"));
    }

    // === Debug info tests ===

    #[test]
    fn test_di_location() {
        let loc = DILocation::new(42, 10, 1);
        assert_eq!(loc.line, 42);
        assert_eq!(loc.column, 10);
        assert_eq!(loc.scope, 1);
        assert!(loc.inlined_at.is_none());

        let loc2 = DILocation::new(100, 5, 2).with_inlined_at(1);
        assert_eq!(loc2.inlined_at, Some(1));
    }

    #[test]
    fn test_di_file() {
        let file = DIFile::new("main.c".to_string(), "/home/user/src".to_string());
        assert_eq!(file.filename, "main.c");
        assert_eq!(file.full_path(), "/home/user/src/main.c");

        let file2 = DIFile::new("standalone.s".to_string(), String::new());
        assert_eq!(file2.full_path(), "standalone.s");
    }

    #[test]
    fn test_di_subprogram() {
        let sp = DISubprogram::new("my_func".to_string(), 0, 42, 1);
        assert_eq!(sp.name, "my_func");
        assert_eq!(sp.file, 0);
        assert_eq!(sp.line, 42);
        assert_eq!(sp.unit, 1);
        assert!(sp.is_definition);
        assert!(!sp.is_local);
    }

    #[test]
    fn test_di_type() {
        let ty = DIType::new_basic("int".to_string(), 32, 32, 5); // DW_ATE_signed = 5
        assert_eq!(ty.name, "int");
        assert_eq!(ty.size_in_bits, 32);
        assert_eq!(ty.align_in_bits, 32);
        assert_eq!(ty.size_in_bytes(), 4);
        assert_eq!(ty.encoding, 5);
    }

    #[test]
    fn test_di_local_variable() {
        let var = DILocalVariable::new("x".to_string(), 0, 1, 10, 2);
        assert_eq!(var.name, "x");
        assert_eq!(var.scope, 0);
        assert_eq!(var.line, 10);
        assert_eq!(var.var_type, 2);
        assert!(var.arg.is_none());
    }

    #[test]
    fn test_di_global_variable() {
        let var = DIGlobalVariable::new("g_counter".to_string(), 0, 1, 5, 2, false, true);
        assert_eq!(var.name, "g_counter");
        assert!(var.is_definition);
        assert!(!var.is_local_to_unit);
    }

    #[test]
    fn test_di_compile_unit() {
        let cu = DICompileUnit::new(12, 0, "clang 18.0".to_string()); // DW_LANG_C99 = 12
        assert_eq!(cu.language, 12);
        assert_eq!(cu.file, 0);
        assert_eq!(cu.producer, "clang 18.0");
        assert!(!cu.is_optimized);
        assert_eq!(cu.emission_kind, 0);
    }

    // === MetadataStore debug info operations ===

    #[test]
    fn test_metadata_store_debug_location() {
        let mut store = MetadataStore::new();
        let loc = DILocation::new(10, 5, 0);
        let id = store.add_debug_location(loc);

        let retrieved = store.get_debug_location(id);
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().line, 10);
        assert_eq!(retrieved.unwrap().column, 5);
    }

    #[test]
    fn test_metadata_store_debug_file() {
        let mut store = MetadataStore::new();
        let file = DIFile::new("test.rs".to_string(), "/src".to_string());
        let id = store.add_debug_file(file);

        let retrieved = store.get_debug_file(id);
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().filename, "test.rs");

        let found = store.find_debug_file("test.rs", "/src");
        assert_eq!(found, Some(id));

        let not_found = store.find_debug_file("nonexistent.rs", "/src");
        assert_eq!(not_found, None);
    }

    #[test]
    fn test_metadata_store_debug_subprogram() {
        let mut store = MetadataStore::new();
        let sp = DISubprogram::new("main".to_string(), 0, 1, 2);
        let id = store.add_debug_subprogram(sp);

        let retrieved = store.get_debug_subprogram(id);
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().name, "main");

        let found = store.find_debug_subprogram("main");
        assert_eq!(found, Some(id));
        assert_eq!(store.find_debug_subprogram("nonexistent"), None);
    }

    #[test]
    fn test_metadata_store_debug_type() {
        let mut store = MetadataStore::new();
        let ty = DIType::new_basic("i32".to_string(), 32, 32, 5);
        let id = store.add_debug_type(ty);

        let retrieved = store.get_debug_type(id);
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().name, "i32");
    }

    #[test]
    fn test_metadata_store_debug_var() {
        let mut store = MetadataStore::new();

        let local = DILocalVariable::new("x".to_string(), 0, 1, 5, 2);
        let local_id = store.add_debug_local_var(local);

        let global = DIGlobalVariable::new("g".to_string(), 0, 1, 3, 4, true, true);
        let global_id = store.add_debug_global_var(global);

        assert!(store.get_debug_local_var(local_id).is_some());
        assert!(store.get_debug_global_var(global_id).is_some());
        assert!(store.get_debug_local_var(999).is_none());
    }

    #[test]
    fn test_metadata_store_debug_compile_unit() {
        let mut store = MetadataStore::new();
        let cu = DICompileUnit::new(12, 0, "rustc".to_string());
        let id = store.add_debug_compile_unit(cu);

        let retrieved = store.get_debug_compile_unit(id);
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().producer, "rustc");
    }

    #[test]
    fn test_metadata_store_emit_assembly() {
        let mut store = MetadataStore::new();

        store.add_metadata(MetadataKind::MDString("test".to_string()));
        store.create_md_node(vec![MetadataOperand::Metadata(0)]);
        store.add_named_node("llvm.ident", vec![0]);

        let asm = store.emit_assembly();
        assert!(asm.contains("test"));
        assert!(asm.contains("llvm.ident"));
    }

    #[test]
    fn test_metadata_store_default() {
        let store = MetadataStore::default();
        assert!(store.is_empty());
        assert_eq!(store.count(), 0);
    }

    #[test]
    fn test_metadata_store_set_debug_location() {
        let mut store = MetadataStore::new();
        store.set_debug_location(5, DILocation::new(50, 5, 1));

        let loc = store.get_debug_location(5);
        assert!(loc.is_some());
        assert_eq!(loc.unwrap().line, 50);
    }

    #[test]
    fn test_constant_value_zeroinit() {
        let cv = ConstantValue {
            ty: crate::types::Type::i32(),
            repr: ConstantRepr::ZeroInitializer,
        };
        assert_eq!(cv.to_string(), "zeroinitializer");
    }

    #[test]
    fn test_metadata_value_id_consistency() {
        let mut store = MetadataStore::new();
        let ids: Vec<u32> = (0..10)
            .map(|i| store.add_metadata(MetadataKind::MDString(format!("v{}", i))))
            .collect();

        for (i, id) in ids.iter().enumerate() {
            assert_eq!(*id, i as u32);
            let mv = store.get_metadata(*id).unwrap();
            assert_eq!(mv.id, *id);
        }
    }

    #[test]
    fn test_metadata_store_mdref_helper() {
        let op = MetadataStore::md_ref(42);
        assert_eq!(op.as_metadata_id(), Some(42));

        let op_str = MetadataStore::md_string_op("hello");
        match op_str {
            MetadataOperand::MDString(s) => assert_eq!(s, "hello"),
            _ => panic!("Expected MDString"),
        }
    }

    #[test]
    fn test_dilocation_with_inlined_at() {
        let loc = DILocation::new(10, 1, 0).with_inlined_at(5);
        assert_eq!(loc.line, 10);
        assert_eq!(loc.column, 1);
        assert_eq!(loc.scope, 0);
        assert_eq!(loc.inlined_at, Some(5));
    }
}