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
//! LLVM DebugInfo — DIBuilder, DebugLoc, DIScope, DWARF emitter bridge.
//! Clean-room reimplementation of LLVM's debug info infrastructure.
//!
//! @llvm_behavior: LLVM's debug info subsystem bridges the IR with DWARF
//! (and CodeView) debug formats. The DIBuilder class constructs debug
//! metadata nodes (DIFile, DISubprogram, DIType, etc.) that are attached
//! to IR instructions via llvm.dbg.declare and llvm.dbg.value intrinsics.
//!
//! Key concepts:
//! - DI* structures (DIFile, DICompileUnit, DISubprogram, etc.) hold
//!   debug metadata that maps source-level constructs to IR.
//! - Debug locations (DILocation) annotate IR instructions with source
//!   file, line, column, and lexical scope.
//! - llvm.dbg.declare: declares a local variable's storage location.
//! - llvm.dbg.value: records a value for a local variable at a point.
//! - DWARF emission: the debug info metadata is serialized to DWARF
//!   sections (.debug_info, .debug_line, .debug_abbrev, etc.).

use crate::metadata::{
    DICompileUnit, DIFile, DIGlobalVariable, DILocalVariable, DILocation, DISubprogram, DIType,
    MetadataOperand, MetadataStore,
};
use crate::types::Type;
use crate::value::{valref, SubclassKind, Value, ValueRef};

// ============================================================================
// DWARF language constants
// ============================================================================

/// DWARF language codes (DW_AT_language). These are the standard values
/// from the DWARF specification, used in DICompileUnit.
///
/// @llvm_behavior: LLVM uses DW_LANG_* constants from llvm/Support/Dwarf.h.
pub const DW_LANG_C89: u32 = 0x0001;
pub const DW_LANG_C: u32 = 0x0002;
pub const DW_LANG_Ada83: u32 = 0x0003;
pub const DW_LANG_C_plus_plus: u32 = 0x0004;
pub const DW_LANG_Cobol74: u32 = 0x0005;
pub const DW_LANG_Cobol85: u32 = 0x0006;
pub const DW_LANG_Fortran77: u32 = 0x0007;
pub const DW_LANG_Fortran90: u32 = 0x0008;
pub const DW_LANG_Pascal83: u32 = 0x0009;
pub const DW_LANG_Modula2: u32 = 0x000A;
pub const DW_LANG_Java: u32 = 0x000B;
pub const DW_LANG_C99: u32 = 0x000C;
pub const DW_LANG_Ada95: u32 = 0x000D;
pub const DW_LANG_Fortran95: u32 = 0x000E;
pub const DW_LANG_PLI: u32 = 0x000F;
pub const DW_LANG_ObjC: u32 = 0x0010;
pub const DW_LANG_ObjC_plus_plus: u32 = 0x0011;
pub const DW_LANG_UPC: u32 = 0x0012;
pub const DW_LANG_D: u32 = 0x0013;
pub const DW_LANG_Python: u32 = 0x0014;
pub const DW_LANG_OpenCL: u32 = 0x0015;
pub const DW_LANG_Go: u32 = 0x0016;
pub const DW_LANG_Modula3: u32 = 0x0017;
pub const DW_LANG_Haskell: u32 = 0x0018;
pub const DW_LANG_C_plus_plus_03: u32 = 0x0019;
pub const DW_LANG_C_plus_plus_11: u32 = 0x001A;
pub const DW_LANG_OCaml: u32 = 0x001B;
pub const DW_LANG_Rust: u32 = 0x001C;
pub const DW_LANG_C11: u32 = 0x001D;
pub const DW_LANG_Swift: u32 = 0x001E;
pub const DW_LANG_Julia: u32 = 0x001F;
pub const DW_LANG_Dylan: u32 = 0x0020;
pub const DW_LANG_C_plus_plus_14: u32 = 0x0021;
pub const DW_LANG_Fortran03: u32 = 0x0022;
pub const DW_LANG_Fortran08: u32 = 0x0023;
pub const DW_LANG_RenderScript: u32 = 0x0024;
pub const DW_LANG_BLISS: u32 = 0x0025;
pub const DW_LANG_Metal: u32 = 0x0027;
pub const DW_LANG_Zig: u32 = 0x0030;
pub const DW_LANG_Mojo: u32 = 0x0032;
pub const DW_LANG_C17: u32 = 0x0033;
pub const DW_LANG_C_plus_plus_17: u32 = 0x0034;
pub const DW_LANG_C_plus_plus_20: u32 = 0x0035;

// DWARF type encoding (DW_ATE_*)
pub const DW_ATE_address: u32 = 0x01;
pub const DW_ATE_boolean: u32 = 0x02;
pub const DW_ATE_complex_float: u32 = 0x03;
pub const DW_ATE_float: u32 = 0x04;
pub const DW_ATE_signed: u32 = 0x05;
pub const DW_ATE_signed_char: u32 = 0x06;
pub const DW_ATE_unsigned: u32 = 0x07;
pub const DW_ATE_unsigned_char: u32 = 0x08;
pub const DW_ATE_UTF: u32 = 0x10;

// DWARF tag constants (DW_TAG_*)
pub const DW_TAG_array_type: u32 = 0x01;
pub const DW_TAG_class_type: u32 = 0x02;
pub const DW_TAG_entry_point: u32 = 0x03;
pub const DW_TAG_enumeration_type: u32 = 0x04;
pub const DW_TAG_formal_parameter: u32 = 0x05;
pub const DW_TAG_imported_declaration: u32 = 0x08;
pub const DW_TAG_label: u32 = 0x0A;
pub const DW_TAG_lexical_block: u32 = 0x0B;
pub const DW_TAG_member: u32 = 0x0D;
pub const DW_TAG_pointer_type: u32 = 0x0F;
pub const DW_TAG_reference_type: u32 = 0x10;
pub const DW_TAG_compile_unit: u32 = 0x11;
pub const DW_TAG_string_type: u32 = 0x12;
pub const DW_TAG_structure_type: u32 = 0x13;
pub const DW_TAG_subroutine_type: u32 = 0x15;
pub const DW_TAG_typedef: u32 = 0x16;
pub const DW_TAG_union_type: u32 = 0x17;
pub const DW_TAG_unspecified_parameters: u32 = 0x18;
pub const DW_TAG_variant: u32 = 0x19;
pub const DW_TAG_common_block: u32 = 0x1A;
pub const DW_TAG_common_inclusion: u32 = 0x1B;
pub const DW_TAG_inheritance: u32 = 0x1C;
pub const DW_TAG_inlined_subroutine: u32 = 0x1D;
pub const DW_TAG_module: u32 = 0x1E;
pub const DW_TAG_ptr_to_member_type: u32 = 0x1F;
pub const DW_TAG_set_type: u32 = 0x20;
pub const DW_TAG_subrange_type: u32 = 0x21;
pub const DW_TAG_auto_variable: u32 = 0x100;
pub const DW_TAG_arg_variable: u32 = 0x101;
pub const DW_TAG_template_type_parameter: u32 = 0x2F;
pub const DW_TAG_template_value_parameter: u32 = 0x30;
pub const DW_TAG_GNU_template_template_param: u32 = 0x4106;
pub const DW_TAG_GNU_template_parameter_pack: u32 = 0x4107;

// DWARF flags (DW_FLAG_*)
pub const DW_FLAG_artificial: u32 = 0x01;
pub const DW_FLAG_prototyped: u32 = 0x02;
pub const DW_FLAG_object_pointer: u32 = 0x04;
pub const DW_FLAG_static_member: u32 = 0x08;
pub const DW_FLAG_bit_field: u32 = 0x10;
pub const DW_FLAG_vector: u32 = 0x20;

/// Map a language name string to its DWARF language constant.
///
/// @llvm_behavior: Equivalent to `dwarf::DW_LANG_*` selection based on
/// the source language name provided by the frontend.
pub fn language_to_dwarf(lang: &str) -> u32 {
    match lang.to_lowercase().as_str() {
        "c" | "c89" => DW_LANG_C89,
        "c99" => DW_LANG_C99,
        "c11" => DW_LANG_C11,
        "c17" => DW_LANG_C17,
        "c++" | "c++98" | "cpp" => DW_LANG_C_plus_plus,
        "c++03" | "cpp03" => DW_LANG_C_plus_plus_03,
        "c++11" | "cpp11" => DW_LANG_C_plus_plus_11,
        "c++14" | "cpp14" => DW_LANG_C_plus_plus_14,
        "c++17" | "cpp17" => DW_LANG_C_plus_plus_17,
        "c++20" | "cpp20" => DW_LANG_C_plus_plus_20,
        "rust" => DW_LANG_Rust,
        "swift" => DW_LANG_Swift,
        "go" => DW_LANG_Go,
        "fortran77" => DW_LANG_Fortran77,
        "fortran90" => DW_LANG_Fortran90,
        "fortran95" => DW_LANG_Fortran95,
        "fortran03" => DW_LANG_Fortran03,
        "fortran08" => DW_LANG_Fortran08,
        "ada83" => DW_LANG_Ada83,
        "ada95" => DW_LANG_Ada95,
        "java" => DW_LANG_Java,
        "python" => DW_LANG_Python,
        "opencl" => DW_LANG_OpenCL,
        "haskell" => DW_LANG_Haskell,
        "ocaml" => DW_LANG_OCaml,
        "julia" => DW_LANG_Julia,
        "d" => DW_LANG_D,
        "objc" => DW_LANG_ObjC,
        "objc++" => DW_LANG_ObjC_plus_plus,
        "zig" => DW_LANG_Zig,
        _ => DW_LANG_C, // Default to C
    }
}

// ============================================================================
// DebugInfoBuilder — constructs debug metadata for an LLVM module
// ============================================================================

/// The DebugInfoBuilder constructs debug metadata nodes and bridges them
/// with LLVM IR instructions via llvm.dbg.* intrinsics.
///
/// @llvm_behavior: Equivalent to LLVM's `DIBuilder` class. Each created
/// DI* node is stored in the internal metadata store with a unique handle
/// (u32 index). The builder tracks the current lexical scope and debug
/// location for contextual node creation.
#[derive(Debug, Clone)]
pub struct DebugInfoBuilder {
    /// The backing metadata store for all created debug info nodes.
    pub metadata_store: MetadataStore,
    /// All created compile unit metadata IDs.
    pub compile_units: Vec<u32>,
    /// All created subprogram metadata IDs.
    pub subprograms: Vec<u32>,
    /// All created global variable metadata IDs.
    pub global_variables: Vec<u32>,
    /// All created local variable metadata IDs.
    pub local_variables: Vec<u32>,
    /// The current lexical scope metadata ID (for implicit scoping).
    pub current_scope: Option<u32>,
    /// The current debug location (for implicit location attachment).
    pub current_location: Option<DILocation>,
    /// The current file metadata ID (for implicit file context).
    pub current_file: Option<u32>,
    /// Whether to allow forward references (unresolved metadata nodes).
    pub allow_unresolved: bool,
}

impl DebugInfoBuilder {
    /// Create a new empty DebugInfoBuilder.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder(Module &M, bool AllowUnresolved)`.
    pub fn new() -> Self {
        Self {
            metadata_store: MetadataStore::new(),
            compile_units: Vec::new(),
            subprograms: Vec::new(),
            global_variables: Vec::new(),
            local_variables: Vec::new(),
            current_scope: None,
            current_location: None,
            current_file: None,
            allow_unresolved: false,
        }
    }

    /// Create a compile unit (DW_TAG_compile_unit).
    ///
    /// Returns a metadata ID that can be used as a scope for
    /// other debug info nodes.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createCompileUnit(...)`.
    pub fn create_compile_unit(
        &mut self,
        file: &str,
        dir: &str,
        producer: &str,
        is_optimized: bool,
        flags: &str,
        runtime_version: u32,
    ) -> u32 {
        let file_id = self.create_file(file, dir);

        let lang = if flags.is_empty() {
            DW_LANG_C
        } else {
            language_to_dwarf(flags)
        };

        // Build the compile unit; delegate ID assignment to MetadataStore
        let mut cu = DICompileUnit::new(lang, file_id, producer.to_string());
        cu.is_optimized = is_optimized;
        cu.flags = flags.to_string();
        cu.runtime_version = runtime_version;

        let id = self.metadata_store.add_debug_compile_unit(cu);
        self.compile_units.push(id);
        self.current_file = Some(file_id);
        id
    }

    /// Create a file node (DW_TAG_file_type).
    ///
    /// Returns a metadata ID that can be referenced by other debug info nodes.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createFile(filename, directory)`.
    pub fn create_file(&mut self, filename: &str, directory: &str) -> u32 {
        let di = DIFile::new(filename.to_string(), directory.to_string());
        self.metadata_store.add_debug_file(di)
    }

    /// Create a function / subprogram node (DW_TAG_subprogram).
    ///
    /// Returns a metadata ID that serves as the lexical scope for the function.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createFunction(...)`.
    pub fn create_function(
        &mut self,
        scope: u32,
        name: &str,
        linkage_name: &str,
        file: u32,
        line: u32,
        is_definition: bool,
        is_local_to_unit: bool,
        is_optimized: bool,
    ) -> u32 {
        let mut sub = DISubprogram::new(name.to_string(), file, line, scope);
        if !linkage_name.is_empty() {
            sub.linkage_name = Some(linkage_name.to_string());
        }
        sub.is_definition = is_definition;
        sub.is_local = is_local_to_unit;
        sub.is_optimized = is_optimized;

        let id = self.metadata_store.add_debug_subprogram(sub);
        self.subprograms.push(id);
        id
    }

    /// Create a basic type (DW_TAG_base_type).
    ///
    /// Returns a metadata ID for the type.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createBasicType(name, sizeInBits, encoding)`.
    pub fn create_basic_type(&mut self, name: &str, size_in_bits: u64, encoding: u32) -> u32 {
        let ty = DIType::new_basic(name.to_string(), size_in_bits, 0, encoding);
        self.metadata_store.add_debug_type(ty)
    }

    /// Create a pointer type (DW_TAG_pointer_type).
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createPointerType(pointeeType, sizeInBits, alignInBits)`.
    pub fn create_pointer_type(
        &mut self,
        pointee_type: u32,
        size_in_bits: u64,
        align_in_bits: u32,
    ) -> u32 {
        let ty = DIType {
            name: String::new(),
            size_in_bits,
            align_in_bits,
            offset_in_bits: 0,
            encoding: 0,
            base_type: Some(pointee_type),
            file: None,
            line: None,
            tag: DW_TAG_pointer_type,
            flags: 0,
        };
        self.metadata_store.add_debug_type(ty)
    }

    /// Create a struct type (DW_TAG_structure_type).
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createStructType(scope, name, file, line, sizeInBits, alignInBits, elements)`.
    pub fn create_struct_type(
        &mut self,
        _scope: u32,
        name: &str,
        file: u32,
        line: u32,
        size_in_bits: u64,
        align_in_bits: u32,
        elements: &[u32],
    ) -> u32 {
        let ty = DIType {
            name: name.to_string(),
            size_in_bits,
            align_in_bits,
            offset_in_bits: 0,
            encoding: 0,
            base_type: elements.first().copied(),
            file: Some(file),
            line: Some(line),
            tag: DW_TAG_structure_type,
            flags: 0,
        };
        self.metadata_store.add_debug_type(ty)
    }

    /// Create an array type (DW_TAG_array_type).
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createArrayType(sizeInBits, alignInBits, elemType, subscripts)`.
    pub fn create_array_type(&mut self, elem_type: u32, _count: u64, size_in_bits: u64) -> u32 {
        let ty = DIType {
            name: String::new(),
            size_in_bits,
            align_in_bits: 0,
            offset_in_bits: 0,
            encoding: 0,
            base_type: Some(elem_type),
            file: None,
            line: None,
            tag: DW_TAG_array_type,
            flags: 0,
        };
        self.metadata_store.add_debug_type(ty)
    }

    /// Create a subroutine type (DW_TAG_subroutine_type).
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createSubroutineType(file, parameterTypes)`.
    pub fn create_subroutine_type(&mut self, file: u32, param_types: &[u32]) -> u32 {
        let ty = DIType {
            name: String::new(),
            size_in_bits: 0,
            align_in_bits: 0,
            offset_in_bits: 0,
            encoding: 0,
            base_type: param_types.first().copied(),
            file: Some(file),
            line: None,
            tag: DW_TAG_subroutine_type,
            flags: 0,
        };
        self.metadata_store.add_debug_type(ty)
    }

    /// Create a member type (DW_TAG_member).
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createMemberType(scope, name, file, line, sizeInBits, alignInBits, offsetInBits, flags, ty)`.
    pub fn create_member_type(
        &mut self,
        _scope: u32,
        name: &str,
        file: u32,
        line: u32,
        size_in_bits: u64,
        align_in_bits: u32,
        offset_in_bits: u64,
        ty: u32,
    ) -> u32 {
        let member = DIType {
            name: name.to_string(),
            size_in_bits,
            align_in_bits,
            offset_in_bits,
            encoding: 0,
            base_type: Some(ty),
            file: Some(file),
            line: Some(line),
            tag: DW_TAG_member,
            flags: 0,
        };
        self.metadata_store.add_debug_type(member)
    }

    /// Create an inheritance relationship (DW_TAG_inheritance).
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createInheritance(ty, baseType, baseOffset, flags)`.
    pub fn create_inheritance(&mut self, _scope: u32, base_type: u32, offset_in_bits: u64) -> u32 {
        let ty = DIType {
            name: String::new(),
            size_in_bits: 0,
            align_in_bits: 0,
            offset_in_bits,
            encoding: 0,
            base_type: Some(base_type),
            file: None,
            line: None,
            tag: DW_TAG_inheritance,
            flags: 0,
        };
        self.metadata_store.add_debug_type(ty)
    }

    /// Create an auto (local) variable (DW_TAG_auto_variable).
    ///
    /// Returns a metadata ID for the variable descriptor.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createAutoVariable(scope, name, file, line, ty, ...)`.
    pub fn create_auto_variable(
        &mut self,
        scope: u32,
        name: &str,
        file: u32,
        line: u32,
        ty: u32,
    ) -> u32 {
        let var = DILocalVariable::new(name.to_string(), scope, file, line, ty);
        let id = self.metadata_store.add_debug_local_var(var);
        self.local_variables.push(id);
        id
    }

    /// Create a parameter variable (DW_TAG_formal_parameter).
    ///
    /// Returns a metadata ID for the variable descriptor.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createParameterVariable(scope, name, argNo, file, line, ty, ...)`.
    pub fn create_parameter_variable(
        &mut self,
        scope: u32,
        name: &str,
        arg_no: u32,
        file: u32,
        line: u32,
        ty: u32,
    ) -> u32 {
        let mut var = DILocalVariable::new(name.to_string(), scope, file, line, ty);
        var.arg = Some(arg_no);
        let id = self.metadata_store.add_debug_local_var(var);
        self.local_variables.push(id);
        id
    }

    /// Create a global variable (DW_TAG_variable).
    ///
    /// Returns a metadata ID for the variable descriptor.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createGlobalVariableExpression(...)`.
    pub fn create_global_variable(
        &mut self,
        scope: u32,
        name: &str,
        linkage_name: &str,
        file: u32,
        line: u32,
        ty: u32,
        is_local_to_unit: bool,
    ) -> u32 {
        let gv = DIGlobalVariable::new(
            name.to_string(),
            scope,
            file,
            line,
            ty,
            is_local_to_unit,
            true,
        );
        // Store linkage name as part of the variable name for now
        let id = self.metadata_store.add_debug_global_var(gv);
        self.global_variables.push(id);
        id
    }

    /// Create a lexical block (DW_TAG_lexical_block).
    ///
    /// Returns a handle that can be used as a scope for variables.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createLexicalBlock(scope, file, line, col)`.
    pub fn create_lexical_block(
        &mut self,
        _scope: u32,
        _file: u32,
        _line: u32,
        _column: u32,
    ) -> u32 {
        // Lexical blocks don't have a direct metadata type in our simplified
        // model. We create a dummy MD node and return its ID.
        self.metadata_store.create_md_node(Vec::new())
    }

    /// Create an inlined subroutine (DW_TAG_inlined_subroutine).
    ///
    /// Returns a handle that can be used as a scope.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createInlinedAt(...)`.
    pub fn create_inlined_subroutine(
        &mut self,
        _scope: u32,
        _subroutine: u32,
        _file: u32,
        _line: u32,
    ) -> u32 {
        self.metadata_store.create_md_node(Vec::new())
    }

    /// Create a debug location (DILocation).
    ///
    /// Returns a metadata ID for the location.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createDebugLocation(ctx, line, col, scope, inlinedAt)`.
    pub fn create_debug_location(&mut self, scope: u32, _file: u32, line: u32, column: u32) -> u32 {
        let loc = DILocation::new(line, column, scope);
        let id = self.metadata_store.add_debug_location(loc.clone());
        self.current_location = Some(loc);
        id
    }

    /// Insert an llvm.dbg.declare intrinsic for a local variable.
    ///
    /// The intrinsic declares that the given alloca provides the storage
    /// for the debug variable at the specified location.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::insertDeclare(Storage, VarInfo, Expr, DL, InsertAtEnd)`.
    /// Returns a ValueRef representing the inserted intrinsic call.
    pub fn insert_declare(&mut self, alloca: &ValueRef, _var: u32, _location: u32) -> ValueRef {
        let dbg_call = Value {
            name: "llvm.dbg.declare".to_string(),
            ty: Type::void(),
            vid: 0,
            subclass: SubclassKind::Instruction,
            uses: Vec::new(),
            opcode: None,
            num_operands: 2,
            operands: vec![alloca.clone()],
            parent: None,
            return_type: None,
            successors: Vec::new(),
            subclass_data: 0,
            subclass_extra: Vec::new(),
            metadata: std::collections::HashMap::new(),
            ..Default::default()
        };
        valref(dbg_call)
    }

    /// Insert an llvm.dbg.value intrinsic for a local variable value.
    ///
    /// The intrinsic records the value of the debug variable at the
    /// specified location.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::insertDbgValueIntrinsic(Val, VarInfo, Expr, DL, InsertAtEnd)`.
    /// Returns a ValueRef representing the inserted intrinsic call.
    pub fn insert_value(&mut self, val: &ValueRef, _var: u32, _location: u32) -> ValueRef {
        let dbg_call = Value {
            name: "llvm.dbg.value".to_string(),
            ty: Type::void(),
            vid: 0,
            subclass: SubclassKind::Instruction,
            uses: Vec::new(),
            opcode: None,
            num_operands: 2,
            operands: vec![val.clone()],
            parent: None,
            return_type: None,
            successors: Vec::new(),
            subclass_data: 0,
            metadata: std::collections::HashMap::new(),
            ..Default::default()
        };
        valref(dbg_call)
    }

    /// Finalize the debug info — resolve forward references and prepare for emission.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::finalize()`. After finalization,
    /// no more debug info nodes should be created.
    pub fn finalize(&mut self) {
        // In a full implementation, this would:
        // 1. Resolve any forward-declared types
        // 2. Retain types referenced by retained types list in compile units
        // 3. Prune unreferenced nodes
        // 4. Assign final indices for emission
    }

    /// Emit all accumulated debug info to the metadata store for module
    /// attachment.
    ///
    /// Returns a clone of the complete metadata store.
    ///
    /// @llvm_behavior: Equivalent to finalizing and then extracting all
    /// debug metadata nodes for attachment to the LLVM Module.
    pub fn emit_to_metadata_store(&mut self) -> MetadataStore {
        self.metadata_store.clone()
    }
}

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

// ============================================================================
// Convenience functions
// ============================================================================

/// Create debug info for a function.
///
/// This convenience function creates a subprogram node and returns its metadata ID,
/// automatically setting up the current scope and file context.
///
/// @llvm_behavior: Common pattern for frontends that want to quickly
/// annotate a function with debug info without manually creating each
/// DI node.
pub fn create_function_debug_info(
    builder: &mut DebugInfoBuilder,
    func_name: &str,
    file: &str,
    line: u32,
) -> u32 {
    // Ensure we have a file node
    let file_idx = builder.create_file(file, ".");

    // Create a compile unit if we don't have one
    let cu_idx = if builder.compile_units.is_empty() {
        builder.create_compile_unit(file, ".", "llvm-native", false, "", 0)
    } else {
        builder.compile_units[0]
    };

    // Create the subprogram
    let sub_idx = builder.create_function(
        cu_idx, func_name, func_name, file_idx, line, true,  // is_definition
        false, // not local to unit
        false, // not optimized
    );

    builder.current_scope = Some(sub_idx);
    sub_idx
}

/// Insert debug intrinsics into a basic block for all local variables
/// currently tracked by the builder.
///
/// Returns a vector of ValueRefs representing the inserted intrinsics,
/// which should be added to the basic block's instruction list.
///
/// @llvm_behavior: Batch-inserts llvm.dbg.declare / llvm.dbg.value for
/// variables at a given location.
pub fn insert_debug_intrinsics(
    builder: &mut DebugInfoBuilder,
    _bb: &ValueRef,
    location: u32,
) -> Vec<ValueRef> {
    let mut intrinsics = Vec::new();

    // For each local variable, insert a dbg.value intrinsic
    let var_count = builder.local_variables.len();
    for _ in 0..var_count {
        let placeholder = valref(Value {
            name: "debug_placeholder".to_string(),
            ty: Type::void(),
            vid: 0,
            subclass: SubclassKind::Value,
            uses: Vec::new(),
            opcode: None,
            subclass_data: 0,
            subclass_extra: Vec::new(),
            metadata: std::collections::HashMap::new(),
            is_used_by_md: false,
            num_operands: 0,
            operands: Vec::new(),
            parent: None,
            return_type: None,
            successors: Vec::new(),
            blocks: Vec::new(),
            params: Vec::new(),
            instructions: Vec::new(),
            initializer: None,
            is_constant: false,
            is_vararg: false,
            result: None,
            is_internal: false,
        });
        let intrinsic = builder.insert_value(&placeholder, 0, location);
        intrinsics.push(intrinsic);
    }

    intrinsics
}

// ============================================================================
// DW_OP constants — DWARF expression operation opcodes
// ============================================================================

/// @llvm_behavior: These correspond to DW_OP_* constants from the
/// DWARF specification (Section 2.5). LLVM uses them in DIExpression
/// to encode variable locations and other debug expressions.
pub const DW_OP_addr: u8 = 0x03;
pub const DW_OP_deref: u8 = 0x06;
pub const DW_OP_const1u: u8 = 0x08;
pub const DW_OP_const1s: u8 = 0x09;
pub const DW_OP_const2u: u8 = 0x0A;
pub const DW_OP_const2s: u8 = 0x0B;
pub const DW_OP_const4u: u8 = 0x0C;
pub const DW_OP_const4s: u8 = 0x0D;
pub const DW_OP_const8u: u8 = 0x0E;
pub const DW_OP_const8s: u8 = 0x0F;
pub const DW_OP_constu: u8 = 0x10;
pub const DW_OP_consts: u8 = 0x11;
pub const DW_OP_dup: u8 = 0x12;
pub const DW_OP_drop: u8 = 0x13;
pub const DW_OP_over: u8 = 0x14;
pub const DW_OP_pick: u8 = 0x15;
pub const DW_OP_swap: u8 = 0x16;
pub const DW_OP_rot: u8 = 0x17;
pub const DW_OP_xderef: u8 = 0x18;
pub const DW_OP_abs: u8 = 0x19;
pub const DW_OP_and: u8 = 0x1A;
pub const DW_OP_div: u8 = 0x1B;
pub const DW_OP_minus: u8 = 0x1C;
pub const DW_OP_mod: u8 = 0x1D;
pub const DW_OP_mul: u8 = 0x1E;
pub const DW_OP_neg: u8 = 0x1F;
pub const DW_OP_not: u8 = 0x20;
pub const DW_OP_or: u8 = 0x21;
pub const DW_OP_plus: u8 = 0x22;
pub const DW_OP_plus_uconst: u8 = 0x23;
pub const DW_OP_shl: u8 = 0x24;
pub const DW_OP_shr: u8 = 0x25;
pub const DW_OP_shra: u8 = 0x26;
pub const DW_OP_xor: u8 = 0x27;
pub const DW_OP_bra: u8 = 0x28;
pub const DW_OP_eq: u8 = 0x29;
pub const DW_OP_ge: u8 = 0x2A;
pub const DW_OP_gt: u8 = 0x2B;
pub const DW_OP_le: u8 = 0x2C;
pub const DW_OP_lt: u8 = 0x2D;
pub const DW_OP_ne: u8 = 0x2E;
pub const DW_OP_skip: u8 = 0x2F;
pub const DW_OP_lit0: u8 = 0x30; // through lit31: 0x4F
pub const DW_OP_reg0: u8 = 0x50; // through reg31: 0x6F
pub const DW_OP_breg0: u8 = 0x70; // through breg31: 0x8F
pub const DW_OP_regx: u8 = 0x90;
pub const DW_OP_fbreg: u8 = 0x91;
pub const DW_OP_bregx: u8 = 0x92;
pub const DW_OP_piece: u8 = 0x93;
pub const DW_OP_deref_size: u8 = 0x94;
pub const DW_OP_xderef_size: u8 = 0x95;
pub const DW_OP_nop: u8 = 0x96;
pub const DW_OP_push_object_address: u8 = 0x97;
pub const DW_OP_call2: u8 = 0x98;
pub const DW_OP_call4: u8 = 0x99;
pub const DW_OP_call_ref: u8 = 0x9A;
pub const DW_OP_form_tls_address: u8 = 0x9B;
pub const DW_OP_call_frame_cfa: u8 = 0x9C;
pub const DW_OP_bit_piece: u8 = 0x9D;
pub const DW_OP_implicit_value: u8 = 0x9E;
pub const DW_OP_stack_value: u8 = 0x9F;
pub const DW_OP_implicit_pointer: u8 = 0xA0;
pub const DW_OP_addrx: u8 = 0xA1;
pub const DW_OP_constx: u8 = 0xA2;
pub const DW_OP_entry_value: u8 = 0xA3;
pub const DW_OP_const_type: u8 = 0xA4;
pub const DW_OP_regval_type: u8 = 0xA5;
pub const DW_OP_deref_type: u8 = 0xA6;
pub const DW_OP_xderef_type: u8 = 0xA7;
pub const DW_OP_convert: u8 = 0xA8;
pub const DW_OP_reinterpret: u8 = 0xA9;

/// DW_OP_lit<0..31>: base opcode is 0x30, indexed by the literal value.
pub const fn dw_op_lit(n: u8) -> u8 {
    assert!(n <= 31, "DW_OP_lit value must be in range 0..31");
    0x30 + n
}

/// DW_OP_reg<0..31>: base opcode is 0x50, indexed by the register number.
pub const fn dw_op_reg(n: u8) -> u8 {
    assert!(n <= 31, "DW_OP_reg value must be in range 0..31");
    0x50 + n
}

/// DW_OP_breg<0..31>: base opcode is 0x70, indexed by the register number.
pub const fn dw_op_breg(n: u8) -> u8 {
    assert!(n <= 31, "DW_OP_breg value must be in range 0..31");
    0x70 + n
}

// ============================================================================
// ExpressionBuilder — incrementally builds DWARF expression byte sequences
// ============================================================================

/// ExpressionBuilder constructs DWARF expression byte sequences by chaining
/// DW_OP operations. The resulting byte vector is suitable for use as a
/// DIExpression body in debug metadata.
///
/// @llvm_behavior: Equivalent to LLVM's `DIExpression` builder pattern.
/// LLVM encodes expressions as small vectors of u64, but the DWARF wire
/// format is a byte sequence. ExpressionBuilder produces the wire format
/// and can be serialized to a `Vec<u64>` for DIExpression if needed.
#[derive(Debug, Clone, Default)]
pub struct ExpressionBuilder {
    /// Accumulated DWARF expression bytes.
    bytes: Vec<u8>,
    /// Stack depth tracking (informational, not enforced).
    stack_depth: i32,
}

impl ExpressionBuilder {
    /// Create a new, empty expression builder.
    pub fn new() -> Self {
        Self {
            bytes: Vec::new(),
            stack_depth: 0,
        }
    }

    /// Returns the accumulated byte sequence.
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Returns the accumulated byte sequence as an owned Vec<u8>.
    pub fn into_bytes(self) -> Vec<u8> {
        self.bytes
    }

    /// Returns the number of bytes written so far.
    pub fn len(&self) -> usize {
        self.bytes.len()
    }

    /// Returns true if no operations have been appended.
    pub fn is_empty(&self) -> bool {
        self.bytes.is_empty()
    }

    /// Returns the current informational stack depth.
    pub fn stack_depth(&self) -> i32 {
        self.stack_depth
    }

    /// Reset the builder to an empty state.
    pub fn clear(&mut self) -> &mut Self {
        self.bytes.clear();
        self.stack_depth = 0;
        self
    }

    // ------------------------------------------------------------------
    // Internal encoding helpers
    // ------------------------------------------------------------------

    /// Encode an unsigned value as ULEB128 and append to the byte buffer.
    fn append_uleb128(&mut self, mut value: u64) {
        loop {
            let mut byte = (value & 0x7F) as u8;
            value >>= 7;
            if value != 0 {
                byte |= 0x80;
            }
            self.bytes.push(byte);
            if value == 0 {
                break;
            }
        }
    }

    /// Encode a signed value as SLEB128 and append to the byte buffer.
    fn append_sleb128(&mut self, mut value: i64) {
        loop {
            let mut byte = (value as u8) & 0x7F;
            value >>= 7;
            // Sign-extend: if the remaining value is not just sign bits,
            // or if we need to disambiguate the sign, set the continuation flag.
            let done = if value == 0 && (byte & 0x40) == 0 {
                true
            } else if value == -1 && (byte & 0x40) != 0 {
                true
            } else {
                false
            };
            if !done {
                byte |= 0x80;
            }
            self.bytes.push(byte);
            if done {
                break;
            }
        }
    }

    /// Append a single byte (the opcode itself).
    fn append_u8(&mut self, value: u8) {
        self.bytes.push(value);
    }

    /// Append a 16-bit value as two bytes, little-endian.
    fn append_u16(&mut self, value: u16) {
        self.bytes.extend_from_slice(&value.to_le_bytes());
    }

    /// Append a 32-bit value as four bytes, little-endian.
    fn append_u32(&mut self, value: u32) {
        self.bytes.extend_from_slice(&value.to_le_bytes());
    }

    /// Append a 64-bit value as eight bytes, little-endian.
    fn append_u64(&mut self, value: u64) {
        self.bytes.extend_from_slice(&value.to_le_bytes());
    }

    /// Append a raw byte slice.
    fn append_bytes(&mut self, data: &[u8]) {
        self.bytes.extend_from_slice(data);
    }

    // ------------------------------------------------------------------
    // Stack depth helpers
    // ------------------------------------------------------------------

    fn push_stack(&mut self) {
        self.stack_depth += 1;
    }

    fn pop_stack(&mut self) {
        self.stack_depth = (self.stack_depth - 1).max(0);
    }

    // ------------------------------------------------------------------
    // Literal / Constant operations
    // ------------------------------------------------------------------

    /// DW_OP_addr — push a program address onto the stack.
    pub fn op_addr(&mut self, addr: u64) -> &mut Self {
        self.append_u8(DW_OP_addr);
        self.append_u64(addr);
        self.push_stack();
        self
    }

    /// DW_OP_const1u — push an unsigned 1-byte constant.
    pub fn op_const1u(&mut self, value: u8) -> &mut Self {
        self.append_u8(DW_OP_const1u);
        self.append_u8(value);
        self.push_stack();
        self
    }

    /// DW_OP_const1s — push a signed 1-byte constant.
    pub fn op_const1s(&mut self, value: i8) -> &mut Self {
        self.append_u8(DW_OP_const1s);
        self.append_u8(value as u8);
        self.push_stack();
        self
    }

    /// DW_OP_const2u — push an unsigned 2-byte constant.
    pub fn op_const2u(&mut self, value: u16) -> &mut Self {
        self.append_u8(DW_OP_const2u);
        self.append_u16(value);
        self.push_stack();
        self
    }

    /// DW_OP_const2s — push a signed 2-byte constant.
    pub fn op_const2s(&mut self, value: i16) -> &mut Self {
        self.append_u8(DW_OP_const2s);
        self.append_u16(value as u16);
        self.push_stack();
        self
    }

    /// DW_OP_const4u — push an unsigned 4-byte constant.
    pub fn op_const4u(&mut self, value: u32) -> &mut Self {
        self.append_u8(DW_OP_const4u);
        self.append_u32(value);
        self.push_stack();
        self
    }

    /// DW_OP_const4s — push a signed 4-byte constant.
    pub fn op_const4s(&mut self, value: i32) -> &mut Self {
        self.append_u8(DW_OP_const4s);
        self.append_u32(value as u32);
        self.push_stack();
        self
    }

    /// DW_OP_const8u — push an unsigned 8-byte constant.
    pub fn op_const8u(&mut self, value: u64) -> &mut Self {
        self.append_u8(DW_OP_const8u);
        self.append_u64(value);
        self.push_stack();
        self
    }

    /// DW_OP_const8s — push a signed 8-byte constant.
    pub fn op_const8s(&mut self, value: i64) -> &mut Self {
        self.append_u8(DW_OP_const8s);
        self.append_u64(value as u64);
        self.push_stack();
        self
    }

    /// DW_OP_constu — push an unsigned ULEB128-encoded constant.
    pub fn op_constu(&mut self, value: u64) -> &mut Self {
        self.append_u8(DW_OP_constu);
        self.append_uleb128(value);
        self.push_stack();
        self
    }

    /// DW_OP_consts — push a signed SLEB128-encoded constant.
    pub fn op_consts(&mut self, value: i64) -> &mut Self {
        self.append_u8(DW_OP_consts);
        self.append_sleb128(value);
        self.push_stack();
        self
    }

    /// DW_OP_lit<n> — push a literal value 0..31 onto the stack inline.
    /// This is a single-byte opcode; no operand follows.
    pub fn op_lit(&mut self, n: u8) -> &mut Self {
        assert!(n <= 31, "DW_OP_lit value must be in range 0..31");
        self.append_u8(dw_op_lit(n));
        self.push_stack();
        self
    }

    /// DW_OP_plus_uconst — add an unsigned ULEB128 constant to the top of stack.
    pub fn op_plus_uconst(&mut self, value: u64) -> &mut Self {
        self.append_u8(DW_OP_plus_uconst);
        self.append_uleb128(value);
        // Consumes one, produces one — net zero stack change
        self
    }

    // ------------------------------------------------------------------
    // Register-based operations
    // ------------------------------------------------------------------

    /// DW_OP_reg<n> — push the contents of register n onto the stack.
    pub fn op_reg(&mut self, n: u8) -> &mut Self {
        assert!(n <= 31, "DW_OP_reg value must be in range 0..31");
        self.append_u8(dw_op_reg(n));
        self.push_stack();
        self
    }

    /// DW_OP_breg<n> — push the contents of register n plus a signed LEB128 offset.
    pub fn op_breg(&mut self, n: u8, offset: i64) -> &mut Self {
        assert!(n <= 31, "DW_OP_breg value must be in range 0..31");
        self.append_u8(dw_op_breg(n));
        self.append_sleb128(offset);
        self.push_stack();
        self
    }

    /// DW_OP_regx — push the contents of a register specified by a ULEB128 index.
    pub fn op_regx(&mut self, reg: u64) -> &mut Self {
        self.append_u8(DW_OP_regx);
        self.append_uleb128(reg);
        self.push_stack();
        self
    }

    /// DW_OP_bregx — push the contents of a register plus a signed LEB128 offset.
    pub fn op_bregx(&mut self, reg: u64, offset: i64) -> &mut Self {
        self.append_u8(DW_OP_bregx);
        self.append_uleb128(reg);
        self.append_sleb128(offset);
        self.push_stack();
        self
    }

    /// DW_OP_fbreg — push the frame base register value plus a signed LEB128 offset.
    pub fn op_fbreg(&mut self, offset: i64) -> &mut Self {
        self.append_u8(DW_OP_fbreg);
        self.append_sleb128(offset);
        self.push_stack();
        self
    }

    /// DW_OP_call_frame_cfa — push the CFA value from the call frame information.
    pub fn op_call_frame_cfa(&mut self) -> &mut Self {
        self.append_u8(DW_OP_call_frame_cfa);
        self.push_stack();
        self
    }

    /// DW_OP_form_tls_address — push the TLS address of the top-of-stack.
    pub fn op_form_tls_address(&mut self) -> &mut Self {
        self.append_u8(DW_OP_form_tls_address);
        // Replaces one value with one address — net zero
        self
    }

    /// DW_OP_push_object_address — push the address of the currently executing object.
    pub fn op_push_object_address(&mut self) -> &mut Self {
        self.append_u8(DW_OP_push_object_address);
        self.push_stack();
        self
    }

    // ------------------------------------------------------------------
    // Stack manipulation operations
    // ------------------------------------------------------------------

    /// DW_OP_dup — duplicate the top of stack.
    pub fn op_dup(&mut self) -> &mut Self {
        self.append_u8(DW_OP_dup);
        self.push_stack();
        self
    }

    /// DW_OP_drop — remove the top of stack.
    pub fn op_drop(&mut self) -> &mut Self {
        self.append_u8(DW_OP_drop);
        self.pop_stack();
        self
    }

    /// DW_OP_over — duplicate the second-from-top value to the top.
    pub fn op_over(&mut self) -> &mut Self {
        self.append_u8(DW_OP_over);
        self.push_stack();
        self
    }

    /// DW_OP_pick — duplicate the Nth value from the top (1-based index).
    pub fn op_pick(&mut self, index: u8) -> &mut Self {
        self.append_u8(DW_OP_pick);
        self.append_u8(index);
        self.push_stack();
        self
    }

    /// DW_OP_swap — swap the top two values on the stack.
    pub fn op_swap(&mut self) -> &mut Self {
        self.append_u8(DW_OP_swap);
        self
    }

    /// DW_OP_rot — rotate the top three values: third becomes top.
    pub fn op_rot(&mut self) -> &mut Self {
        self.append_u8(DW_OP_rot);
        self
    }

    // ------------------------------------------------------------------
    // Dereference / Memory operations
    // ------------------------------------------------------------------

    /// DW_OP_deref — dereference the top of stack as a pointer.
    pub fn op_deref(&mut self) -> &mut Self {
        self.append_u8(DW_OP_deref);
        self
    }

    /// DW_OP_deref_size — dereference the top of stack as a pointer with
    /// a specific size in bytes.
    pub fn op_deref_size(&mut self, size_in_bytes: u8) -> &mut Self {
        self.append_u8(DW_OP_deref_size);
        self.append_u8(size_in_bytes);
        self
    }

    /// DW_OP_xderef — extended dereference: pops two values (address, address space).
    pub fn op_xderef(&mut self) -> &mut Self {
        self.append_u8(DW_OP_xderef);
        self.pop_stack(); // consumes address space, address -> value
        self
    }

    /// DW_OP_xderef_size — extended dereference with explicit size.
    pub fn op_xderef_size(&mut self, size_in_bytes: u8) -> &mut Self {
        self.append_u8(DW_OP_xderef_size);
        self.append_u8(size_in_bytes);
        self.pop_stack();
        self
    }

    // ------------------------------------------------------------------
    // Arithmetic operations
    // ------------------------------------------------------------------

    /// DW_OP_abs — replace top of stack with its absolute value.
    pub fn op_abs(&mut self) -> &mut Self {
        self.append_u8(DW_OP_abs);
        self
    }

    /// DW_OP_and — bitwise AND of top two values.
    pub fn op_and(&mut self) -> &mut Self {
        self.append_u8(DW_OP_and);
        self.pop_stack();
        self
    }

    /// DW_OP_div — divide the second-from-top by the top.
    pub fn op_div(&mut self) -> &mut Self {
        self.append_u8(DW_OP_div);
        self.pop_stack();
        self
    }

    /// DW_OP_minus — subtract the top from the second-from-top.
    pub fn op_minus(&mut self) -> &mut Self {
        self.append_u8(DW_OP_minus);
        self.pop_stack();
        self
    }

    /// DW_OP_mod — modulus of second-from-top by top.
    pub fn op_mod(&mut self) -> &mut Self {
        self.append_u8(DW_OP_mod);
        self.pop_stack();
        self
    }

    /// DW_OP_mul — multiply top two values.
    pub fn op_mul(&mut self) -> &mut Self {
        self.append_u8(DW_OP_mul);
        self.pop_stack();
        self
    }

    /// DW_OP_neg — negate the top of stack.
    pub fn op_neg(&mut self) -> &mut Self {
        self.append_u8(DW_OP_neg);
        self
    }

    /// DW_OP_not — bitwise NOT of the top of stack.
    pub fn op_not(&mut self) -> &mut Self {
        self.append_u8(DW_OP_not);
        self
    }

    /// DW_OP_or — bitwise OR of top two values.
    pub fn op_or(&mut self) -> &mut Self {
        self.append_u8(DW_OP_or);
        self.pop_stack();
        self
    }

    /// DW_OP_plus — add top two values.
    pub fn op_plus(&mut self) -> &mut Self {
        self.append_u8(DW_OP_plus);
        self.pop_stack();
        self
    }

    /// DW_OP_shl — shift second-from-top left by top bits.
    pub fn op_shl(&mut self) -> &mut Self {
        self.append_u8(DW_OP_shl);
        self.pop_stack();
        self
    }

    /// DW_OP_shr — logical shift second-from-top right by top bits.
    pub fn op_shr(&mut self) -> &mut Self {
        self.append_u8(DW_OP_shr);
        self.pop_stack();
        self
    }

    /// DW_OP_shra — arithmetic shift second-from-top right by top bits.
    pub fn op_shra(&mut self) -> &mut Self {
        self.append_u8(DW_OP_shra);
        self.pop_stack();
        self
    }

    /// DW_OP_xor — bitwise XOR of top two values.
    pub fn op_xor(&mut self) -> &mut Self {
        self.append_u8(DW_OP_xor);
        self.pop_stack();
        self
    }

    // ------------------------------------------------------------------
    // Control flow operations
    // ------------------------------------------------------------------

    /// DW_OP_bra — branch if top of stack is non-zero. The operand is a
    /// signed 2-byte offset from the current operation to the target.
    pub fn op_bra(&mut self, target_offset: i16) -> &mut Self {
        self.append_u8(DW_OP_bra);
        self.append_u16(target_offset as u16);
        self.pop_stack();
        self
    }

    /// DW_OP_skip — unconditional branch. The operand is a signed 2-byte
    /// offset from the current operation.
    pub fn op_skip(&mut self, target_offset: i16) -> &mut Self {
        self.append_u8(DW_OP_skip);
        self.append_u16(target_offset as u16);
        self
    }

    // ------------------------------------------------------------------
    // Comparison operations
    // ------------------------------------------------------------------

    /// DW_OP_eq — push 1 if top two values are equal, else 0.
    pub fn op_eq(&mut self) -> &mut Self {
        self.append_u8(DW_OP_eq);
        self.pop_stack();
        self
    }

    /// DW_OP_ge — push 1 if second-from-top >= top, else 0.
    pub fn op_ge(&mut self) -> &mut Self {
        self.append_u8(DW_OP_ge);
        self.pop_stack();
        self
    }

    /// DW_OP_gt — push 1 if second-from-top > top, else 0.
    pub fn op_gt(&mut self) -> &mut Self {
        self.append_u8(DW_OP_gt);
        self.pop_stack();
        self
    }

    /// DW_OP_le — push 1 if second-from-top <= top, else 0.
    pub fn op_le(&mut self) -> &mut Self {
        self.append_u8(DW_OP_le);
        self.pop_stack();
        self
    }

    /// DW_OP_lt — push 1 if second-from-top < top, else 0.
    pub fn op_lt(&mut self) -> &mut Self {
        self.append_u8(DW_OP_lt);
        self.pop_stack();
        self
    }

    /// DW_OP_ne — push 1 if top two values are not equal, else 0.
    pub fn op_ne(&mut self) -> &mut Self {
        self.append_u8(DW_OP_ne);
        self.pop_stack();
        self
    }

    // ------------------------------------------------------------------
    // Piece / Composite location operations
    // ------------------------------------------------------------------

    /// DW_OP_piece — describes a piece of a variable that is N bytes long.
    pub fn op_piece(&mut self, size_in_bytes: u64) -> &mut Self {
        self.append_u8(DW_OP_piece);
        self.append_uleb128(size_in_bytes);
        // Consumes the top-of-stack value to describe the piece
        self.pop_stack();
        self
    }

    /// DW_OP_bit_piece — describes a piece that is size_in_bits at
    /// offset_in_bits from the top of stack.
    pub fn op_bit_piece(&mut self, size_in_bits: u64, offset_in_bits: u64) -> &mut Self {
        self.append_u8(DW_OP_bit_piece);
        self.append_uleb128(size_in_bits);
        self.append_uleb128(offset_in_bits);
        self.pop_stack();
        self
    }

    /// DW_OP_stack_value — mark the top of stack as the value itself
    /// (not an address to dereference).
    pub fn op_stack_value(&mut self) -> &mut Self {
        self.append_u8(DW_OP_stack_value);
        self
    }

    /// DW_OP_implicit_value — provide the value inline as a byte sequence.
    pub fn op_implicit_value(&mut self, data: &[u8]) -> &mut Self {
        self.append_u8(DW_OP_implicit_value);
        self.append_uleb128(data.len() as u64);
        self.append_bytes(data);
        self.push_stack();
        self
    }

    /// DW_OP_implicit_pointer — describes a pointer that has been optimized
    /// away. The value is the debug info entry and the byte offset.
    pub fn op_implicit_pointer(&mut self, die_offset: u32, byte_offset: i64) -> &mut Self {
        self.append_u8(DW_OP_implicit_pointer);
        // The DIE offset is a 4-byte reference into .debug_info (DWARF 32)
        self.append_u32(die_offset);
        self.append_sleb128(byte_offset);
        self.push_stack();
        self
    }

    // ------------------------------------------------------------------
    // Address-indexed operations (DWARF 5)
    // ------------------------------------------------------------------

    /// DW_OP_addrx — push the address at the given index in .debug_addr.
    pub fn op_addrx(&mut self, index: u64) -> &mut Self {
        self.append_u8(DW_OP_addrx);
        self.append_uleb128(index);
        self.push_stack();
        self
    }

    /// DW_OP_constx — push the constant at the given index in .debug_addr.
    pub fn op_constx(&mut self, index: u64) -> &mut Self {
        self.append_u8(DW_OP_constx);
        self.append_uleb128(index);
        self.push_stack();
        self
    }

    // ------------------------------------------------------------------
    // Call-related operations
    // ------------------------------------------------------------------

    /// DW_OP_call2 — call a DWARF procedure at a 2-byte offset.
    pub fn op_call2(&mut self, offset: u16) -> &mut Self {
        self.append_u8(DW_OP_call2);
        self.append_u16(offset);
        self
    }

    /// DW_OP_call4 — call a DWARF procedure at a 4-byte offset.
    pub fn op_call4(&mut self, offset: u32) -> &mut Self {
        self.append_u8(DW_OP_call4);
        self.append_u32(offset);
        self
    }

    /// DW_OP_call_ref — call a DWARF procedure at a 4-byte (DWARF 32)
    /// or 8-byte (DWARF 64) offset. The format depends on the DIE format.
    pub fn op_call_ref(&mut self, offset: u64, is_dwarf64: bool) -> &mut Self {
        self.append_u8(DW_OP_call_ref);
        if is_dwarf64 {
            self.append_u64(offset);
        } else {
            self.append_u32(offset as u32);
        }
        self
    }

    // ------------------------------------------------------------------
    // Type-based operations (DWARF 5)
    // ------------------------------------------------------------------

    /// DW_OP_entry_value — evaluate the expression as if it were at the
    /// entry point of the function. Used for call-site values.
    pub fn op_entry_value(&mut self, expr_bytes: &[u8]) -> &mut Self {
        self.append_u8(DW_OP_entry_value);
        self.append_uleb128(expr_bytes.len() as u64);
        self.append_bytes(expr_bytes);
        // Entry value provides exactly one value
        self.push_stack();
        self
    }

    /// DW_OP_const_type — push an instance of the given type with the
    /// encoded value. The type is identified by a ULEB128 DIE offset
    /// and the value follows as a byte block.
    pub fn op_const_type(&mut self, type_die_offset: u64, value_data: &[u8]) -> &mut Self {
        self.append_u8(DW_OP_const_type);
        self.append_uleb128(type_die_offset);
        self.append_u8(value_data.len() as u8);
        self.append_bytes(value_data);
        self.push_stack();
        self
    }

    /// DW_OP_regval_type — push the interpreted contents of a register
    /// according to the given type.
    pub fn op_regval_type(&mut self, reg: u64, type_die_offset: u64) -> &mut Self {
        self.append_u8(DW_OP_regval_type);
        self.append_uleb128(reg);
        self.append_uleb128(type_die_offset);
        self.push_stack();
        self
    }

    /// DW_OP_deref_type — dereference with a specified type (size and
    /// interpretation come from the type DIE).
    pub fn op_deref_type(&mut self, size_in_bytes: u8, type_die_offset: u64) -> &mut Self {
        self.append_u8(DW_OP_deref_type);
        self.append_u8(size_in_bytes);
        self.append_uleb128(type_die_offset);
        self
    }

    /// DW_OP_xderef_type — extended dereference with type.
    pub fn op_xderef_type(&mut self, size_in_bytes: u8, type_die_offset: u64) -> &mut Self {
        self.append_u8(DW_OP_xderef_type);
        self.append_u8(size_in_bytes);
        self.append_uleb128(type_die_offset);
        self.pop_stack();
        self
    }

    /// DW_OP_convert — convert the top of stack to the specified type.
    /// If type_die_offset is 0, the conversion is to an untyped generic type.
    pub fn op_convert(&mut self, type_die_offset: u64) -> &mut Self {
        self.append_u8(DW_OP_convert);
        self.append_uleb128(type_die_offset);
        self
    }

    /// DW_OP_reinterpret — reinterpret the bits of the top of stack as
    /// the specified type.
    pub fn op_reinterpret(&mut self, type_die_offset: u64) -> &mut Self {
        self.append_u8(DW_OP_reinterpret);
        self.append_uleb128(type_die_offset);
        self
    }

    // ------------------------------------------------------------------
    // Miscellaneous
    // ------------------------------------------------------------------

    /// DW_OP_nop — no operation.
    pub fn op_nop(&mut self) -> &mut Self {
        self.append_u8(DW_OP_nop);
        self
    }
}

// ============================================================================
// DW_AT constants — DWARF attribute name codes
// ============================================================================

/// DWARF attribute constants (DW_AT_*). These identify the attributes
/// that appear in DIE entries within .debug_info.
///
/// @llvm_behavior: LLVM uses these constants to construct DI* metadata
/// node operands. Values match the DWARF specification.
pub const DW_AT_sibling: u16 = 0x01;
pub const DW_AT_location: u16 = 0x02;
pub const DW_AT_name: u16 = 0x03;
pub const DW_AT_ordering: u16 = 0x09;
pub const DW_AT_byte_size: u16 = 0x0B;
pub const DW_AT_bit_offset: u16 = 0x0C;
pub const DW_AT_bit_size: u16 = 0x0D;
pub const DW_AT_stmt_list: u16 = 0x10;
pub const DW_AT_low_pc: u16 = 0x11;
pub const DW_AT_high_pc: u16 = 0x12;
pub const DW_AT_language: u16 = 0x13;
pub const DW_AT_discr: u16 = 0x15;
pub const DW_AT_discr_value: u16 = 0x16;
pub const DW_AT_visibility: u16 = 0x17;
pub const DW_AT_import: u16 = 0x18;
pub const DW_AT_string_length: u16 = 0x19;
pub const DW_AT_common_reference: u16 = 0x1A;
pub const DW_AT_comp_dir: u16 = 0x1B;
pub const DW_AT_const_value: u16 = 0x1C;
pub const DW_AT_containing_type: u16 = 0x1D;
pub const DW_AT_default_value: u16 = 0x1E;
pub const DW_AT_inline: u16 = 0x20;
pub const DW_AT_is_optional: u16 = 0x21;
pub const DW_AT_lower_bound: u16 = 0x22;
pub const DW_AT_producer: u16 = 0x25;
pub const DW_AT_prototyped: u16 = 0x27;
pub const DW_AT_return_addr: u16 = 0x2A;
pub const DW_AT_start_scope: u16 = 0x2C;
pub const DW_AT_bit_stride: u16 = 0x2E;
pub const DW_AT_upper_bound: u16 = 0x2F;
pub const DW_AT_abstract_origin: u16 = 0x31;
pub const DW_AT_accessibility: u16 = 0x32;
pub const DW_AT_address_class: u16 = 0x33;
pub const DW_AT_artificial: u16 = 0x34;
pub const DW_AT_base_types: u16 = 0x35;
pub const DW_AT_calling_convention: u16 = 0x36;
pub const DW_AT_count: u16 = 0x37;
pub const DW_AT_data_member_location: u16 = 0x38;
pub const DW_AT_decl_column: u16 = 0x39;
pub const DW_AT_decl_file: u16 = 0x3A;
pub const DW_AT_decl_line: u16 = 0x3B;
pub const DW_AT_declaration: u16 = 0x3C;
pub const DW_AT_discr_list: u16 = 0x3D;
pub const DW_AT_encoding: u16 = 0x3E;
pub const DW_AT_external: u16 = 0x3F;
pub const DW_AT_frame_base: u16 = 0x40;
pub const DW_AT_friend: u16 = 0x41;
pub const DW_AT_identifier_case: u16 = 0x42;
pub const DW_AT_macro_info: u16 = 0x43;
pub const DW_AT_namelist_item: u16 = 0x44;
pub const DW_AT_priority: u16 = 0x45;
pub const DW_AT_segment: u16 = 0x46;
pub const DW_AT_specification: u16 = 0x47;
pub const DW_AT_static_link: u16 = 0x48;
pub const DW_AT_type: u16 = 0x49;
pub const DW_AT_use_location: u16 = 0x4A;
pub const DW_AT_variable_parameter: u16 = 0x4B;
pub const DW_AT_virtuality: u16 = 0x4C;
pub const DW_AT_vtable_elem_location: u16 = 0x4D;
pub const DW_AT_MIPS_fde: u16 = 0x2001;
pub const DW_AT_MIPS_loop_begin: u16 = 0x2002;
pub const DW_AT_MIPS_tail_loop_begin: u16 = 0x2003;
pub const DW_AT_MIPS_epilog_begin: u16 = 0x2004;
pub const DW_AT_MIPS_loop_unroll_factor: u16 = 0x2005;
pub const DW_AT_MIPS_software_pipeline_depth: u16 = 0x2006;
pub const DW_AT_MIPS_linkage_name: u16 = 0x2007;
pub const DW_AT_MIPS_stride: u16 = 0x2008;
pub const DW_AT_MIPS_abstract_name: u16 = 0x2009;
pub const DW_AT_MIPS_clone_origin: u16 = 0x200A;
pub const DW_AT_MIPS_has_inlines: u16 = 0x200B;
pub const DW_AT_MIPS_stride_byte: u16 = 0x200C;
pub const DW_AT_MIPS_stride_elem: u16 = 0x200D;
pub const DW_AT_MIPS_ptr_dopetype: u16 = 0x200E;
pub const DW_AT_MIPS_allocatable_dopetype: u16 = 0x200F;
pub const DW_AT_MIPS_assumed_shape_dopetype: u16 = 0x2010;
pub const DW_AT_MIPS_assumed_size: u16 = 0x2011;
pub const DW_AT_linkage_name: u16 = 0x6E;
pub const DW_AT_description: u16 = 0x5A;
pub const DW_AT_ranges: u16 = 0x55;
pub const DW_AT_signature: u16 = 0x69;
pub const DW_AT_main_subprogram: u16 = 0x6A;
pub const DW_AT_data_bit_offset: u16 = 0x6B;
pub const DW_AT_const_expr: u16 = 0x6C;
pub const DW_AT_enum_class: u16 = 0x6D;
pub const DW_AT_object_pointer: u16 = 0x64;
pub const DW_AT_explicit: u16 = 0x63;
pub const DW_AT_elemental: u16 = 0x66;
pub const DW_AT_pure: u16 = 0x67;
pub const DW_AT_recursive: u16 = 0x68;
pub const DW_AT_allocated: u16 = 0x4E;
pub const DW_AT_associated: u16 = 0x4F;
pub const DW_AT_data_location: u16 = 0x50;
pub const DW_AT_byte_stride: u16 = 0x51;
pub const DW_AT_entry_pc: u16 = 0x52;
pub const DW_AT_use_UTF8: u16 = 0x53;
pub const DW_AT_extension: u16 = 0x54;
pub const DW_AT_trampoline: u16 = 0x56;
pub const DW_AT_call_column: u16 = 0x57;
pub const DW_AT_call_file: u16 = 0x58;
pub const DW_AT_call_line: u16 = 0x59;
pub const DW_AT_alignment: u16 = 0x6F;

// ============================================================================
// DW_FORM constants — DWARF attribute form codes
// ============================================================================

/// DWARF form constants (DW_FORM_*). These specify how an attribute's value
/// is encoded in the .debug_info section.
///
/// @llvm_behavior: LLVM uses DW_FORM_* constants internally to encode
/// DI* metadata operands when emitting DWARF.
pub const DW_FORM_addr: u16 = 0x01;
pub const DW_FORM_block2: u16 = 0x03;
pub const DW_FORM_block4: u16 = 0x04;
pub const DW_FORM_data2: u16 = 0x05;
pub const DW_FORM_data4: u16 = 0x06;
pub const DW_FORM_data8: u16 = 0x07;
pub const DW_FORM_string: u16 = 0x08;
pub const DW_FORM_block: u16 = 0x09;
pub const DW_FORM_block1: u16 = 0x0A;
pub const DW_FORM_data1: u16 = 0x0B;
pub const DW_FORM_flag: u16 = 0x0C;
pub const DW_FORM_sdata: u16 = 0x0D;
pub const DW_FORM_strp: u16 = 0x0E;
pub const DW_FORM_udata: u16 = 0x0F;
pub const DW_FORM_ref_addr: u16 = 0x10;
pub const DW_FORM_ref1: u16 = 0x11;
pub const DW_FORM_ref2: u16 = 0x12;
pub const DW_FORM_ref4: u16 = 0x13;
pub const DW_FORM_ref8: u16 = 0x14;
pub const DW_FORM_ref_udata: u16 = 0x15;
pub const DW_FORM_indirect: u16 = 0x16;
pub const DW_FORM_sec_offset: u16 = 0x17;
pub const DW_FORM_exprloc: u16 = 0x18;
pub const DW_FORM_flag_present: u16 = 0x19;
pub const DW_FORM_strx: u16 = 0x1A;
pub const DW_FORM_addrx: u16 = 0x1B;
pub const DW_FORM_ref_sup4: u16 = 0x1C;
pub const DW_FORM_strp_sup: u16 = 0x1D;
pub const DW_FORM_data16: u16 = 0x1E;
pub const DW_FORM_line_strp: u16 = 0x1F;
pub const DW_FORM_ref_sig8: u16 = 0x20;
pub const DW_FORM_implicit_const: u16 = 0x21;
pub const DW_FORM_loclistx: u16 = 0x22;
pub const DW_FORM_rnglistx: u16 = 0x23;
pub const DW_FORM_ref_sup8: u16 = 0x24;
pub const DW_FORM_strx1: u16 = 0x25;
pub const DW_FORM_strx2: u16 = 0x26;
pub const DW_FORM_strx3: u16 = 0x27;
pub const DW_FORM_strx4: u16 = 0x28;
pub const DW_FORM_addrx1: u16 = 0x29;
pub const DW_FORM_addrx2: u16 = 0x2A;
pub const DW_FORM_addrx3: u16 = 0x2B;
pub const DW_FORM_addrx4: u16 = 0x2C;

/// Returns a human-readable name for a DW_FORM code (for diagnostics).
pub fn dw_form_name(form: u16) -> &'static str {
    match form {
        DW_FORM_addr => "DW_FORM_addr",
        DW_FORM_block2 => "DW_FORM_block2",
        DW_FORM_block4 => "DW_FORM_block4",
        DW_FORM_data2 => "DW_FORM_data2",
        DW_FORM_data4 => "DW_FORM_data4",
        DW_FORM_data8 => "DW_FORM_data8",
        DW_FORM_string => "DW_FORM_string",
        DW_FORM_block => "DW_FORM_block",
        DW_FORM_block1 => "DW_FORM_block1",
        DW_FORM_data1 => "DW_FORM_data1",
        DW_FORM_flag => "DW_FORM_flag",
        DW_FORM_sdata => "DW_FORM_sdata",
        DW_FORM_strp => "DW_FORM_strp",
        DW_FORM_udata => "DW_FORM_udata",
        DW_FORM_ref_addr => "DW_FORM_ref_addr",
        DW_FORM_ref1 => "DW_FORM_ref1",
        DW_FORM_ref2 => "DW_FORM_ref2",
        DW_FORM_ref4 => "DW_FORM_ref4",
        DW_FORM_ref8 => "DW_FORM_ref8",
        DW_FORM_ref_udata => "DW_FORM_ref_udata",
        DW_FORM_indirect => "DW_FORM_indirect",
        DW_FORM_sec_offset => "DW_FORM_sec_offset",
        DW_FORM_exprloc => "DW_FORM_exprloc",
        DW_FORM_flag_present => "DW_FORM_flag_present",
        DW_FORM_strx => "DW_FORM_strx",
        DW_FORM_addrx => "DW_FORM_addrx",
        DW_FORM_ref_sup4 => "DW_FORM_ref_sup4",
        DW_FORM_strp_sup => "DW_FORM_strp_sup",
        DW_FORM_data16 => "DW_FORM_data16",
        DW_FORM_line_strp => "DW_FORM_line_strp",
        DW_FORM_ref_sig8 => "DW_FORM_ref_sig8",
        DW_FORM_implicit_const => "DW_FORM_implicit_const",
        DW_FORM_loclistx => "DW_FORM_loclistx",
        DW_FORM_rnglistx => "DW_FORM_rnglistx",
        DW_FORM_ref_sup8 => "DW_FORM_ref_sup8",
        DW_FORM_strx1 => "DW_FORM_strx1",
        DW_FORM_strx2 => "DW_FORM_strx2",
        DW_FORM_strx3 => "DW_FORM_strx3",
        DW_FORM_strx4 => "DW_FORM_strx4",
        DW_FORM_addrx1 => "DW_FORM_addrx1",
        DW_FORM_addrx2 => "DW_FORM_addrx2",
        DW_FORM_addrx3 => "DW_FORM_addrx3",
        DW_FORM_addrx4 => "DW_FORM_addrx4",
        _ => "<unknown DW_FORM>",
    }
}

// ============================================================================
// DebugInfoBuilder extensions — scope management, namespaces, templates,
// Objective-C properties, imported entities, artificial types, line table
// bounds, subprogram finalization, and type retention.
// ============================================================================

impl DebugInfoBuilder {
    /// Create a namespace node (DW_TAG_namespace).
    ///
    /// Returns a metadata ID that can be used as a scope for types and
    /// functions declared within that namespace.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createNameSpace(scope, name, exportSymbols)`.
    pub fn create_namespace(&mut self, scope: u32, name: &str, _export_symbols: bool) -> u32 {
        let ty = DIType {
            name: name.to_string(),
            size_in_bits: 0,
            align_in_bits: 0,
            offset_in_bits: 0,
            encoding: 0,
            base_type: Some(scope),
            file: None,
            line: None,
            tag: DW_TAG_module,
            flags: 0,
        };
        self.metadata_store.add_debug_type(ty)
    }

    /// Create a forward-declared (incomplete) type node.
    ///
    /// Forward declarations allow types to be referenced before their full
    /// definition appears, which is common for recursive structures and
    /// separate compilation.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createForwardDecl(tag, name, scope, file, line)`.
    pub fn create_forward_decl(
        &mut self,
        tag: u32,
        name: &str,
        scope: u32,
        file: u32,
        line: u32,
    ) -> u32 {
        let ty = DIType {
            name: name.to_string(),
            size_in_bits: 0,
            align_in_bits: 0,
            offset_in_bits: 0,
            encoding: 0,
            base_type: Some(scope),
            file: Some(file),
            line: Some(line),
            tag,
            flags: DW_FLAG_artificial, // Mark as forward decl via flag
        };
        self.metadata_store.add_debug_type(ty)
    }

    /// Create a template type parameter (DW_TAG_template_type_parameter).
    ///
    /// Records a template parameter that binds to a type. For example,
    /// `T` in `template<typename T> class Foo`.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createTemplateTypeParameter(scope, name, ty)`.
    pub fn create_template_type_parameter(&mut self, scope: u32, name: &str, ty: u32) -> u32 {
        let param = DIType {
            name: name.to_string(),
            size_in_bits: 0,
            align_in_bits: 0,
            offset_in_bits: 0,
            encoding: 0,
            base_type: Some(ty),
            file: None,
            line: None,
            tag: DW_TAG_template_type_parameter,
            flags: 0,
        };
        // Associate with the enclosing scope by storing scope in the metadata
        let id = self.metadata_store.add_debug_type(param);
        // Chain the scope relationship
        let _scope_md = self.metadata_store.create_md_node(vec![
            MetadataOperand::Metadata(scope),
            MetadataOperand::Metadata(id),
            MetadataOperand::Metadata(DW_TAG_template_type_parameter),
        ]);
        let _ = _scope_md;
        id
    }

    /// Create a template value parameter (DW_TAG_template_value_parameter).
    ///
    /// Records a non-type template parameter, such as `N` in
    /// `template<int N> class Array`.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createTemplateValueParameter(scope, name, ty, value)`.
    pub fn create_template_value_parameter(
        &mut self,
        scope: u32,
        name: &str,
        ty: u32,
        _value: u64,
    ) -> u32 {
        let param = DIType {
            name: name.to_string(),
            size_in_bits: 0,
            align_in_bits: 0,
            offset_in_bits: 0,
            encoding: 0,
            base_type: Some(ty),
            file: None,
            line: None,
            tag: DW_TAG_template_value_parameter,
            flags: 0,
        };
        let id = self.metadata_store.add_debug_type(param);
        let _scope_md = self.metadata_store.create_md_node(vec![
            MetadataOperand::Metadata(scope),
            MetadataOperand::Metadata(id),
            MetadataOperand::Metadata(DW_TAG_template_value_parameter),
        ]);
        let _ = _scope_md;
        id
    }

    /// Create a static member type (DW_TAG_member with static flag).
    ///
    /// Represents a static data member of a class or struct. Unlike
    /// regular members, static members do not occupy space in an instance.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createStaticMemberType(scope, name, file, line, ty, flags)`.
    pub fn create_static_member_type(
        &mut self,
        scope: u32,
        name: &str,
        file: u32,
        line: u32,
        ty: u32,
    ) -> u32 {
        let member = DIType {
            name: name.to_string(),
            size_in_bits: 0,
            align_in_bits: 0,
            offset_in_bits: 0,
            encoding: 0,
            base_type: Some(ty),
            file: Some(file),
            line: Some(line),
            tag: DW_TAG_member,
            flags: DW_FLAG_static_member,
        };
        let id = self.metadata_store.add_debug_type(member);
        let _scope_md = self.metadata_store.create_md_node(vec![
            MetadataOperand::Metadata(scope),
            MetadataOperand::Metadata(id),
        ]);
        let _ = _scope_md;
        id
    }

    /// Create an Objective-C property (DW_TAG_* for ObjC properties).
    ///
    /// Records a declared property in an Objective-C class or protocol.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createObjCProperty(name, file, line, getter, setter, propertyAttributes, ty)`.
    pub fn create_objc_property(
        &mut self,
        name: &str,
        file: u32,
        line: u32,
        _getter_name: &str,
        _setter_name: &str,
        _property_attributes: u32,
        ty: u32,
    ) -> u32 {
        let property = DIType {
            name: name.to_string(),
            size_in_bits: 0,
            align_in_bits: 0,
            offset_in_bits: 0,
            encoding: 0,
            base_type: Some(ty),
            file: Some(file),
            line: Some(line),
            tag: 0x41, // DW_TAG_APPLE_property (LLVM extension)
            flags: 0,
        };
        self.metadata_store.add_debug_type(property)
    }

    /// Create an imported entity (DW_TAG_imported_declaration or similar).
    ///
    /// Records a using-declaration, using-directive, or namespace alias.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createImportedDeclaration(scope, decl, file, line, name)`.
    pub fn create_imported_entity(
        &mut self,
        scope: u32,
        _decl: u32,
        file: u32,
        line: u32,
        name: &str,
    ) -> u32 {
        let imported = DIType {
            name: name.to_string(),
            size_in_bits: 0,
            align_in_bits: 0,
            offset_in_bits: 0,
            encoding: 0,
            base_type: Some(scope),
            file: Some(file),
            line: Some(line),
            tag: DW_TAG_imported_declaration,
            flags: 0,
        };
        self.metadata_store.add_debug_type(imported)
    }

    /// Create an artificial type.
    ///
    /// Artificial types are compiler-generated types that do not correspond
    /// to any source-level construct (e.g., vtable types, RTTI descriptors).
    /// They carry the DW_FLAG_artificial flag.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::createArtificialType(ty)`.
    pub fn create_artificial_type(&mut self, base_type: u32) -> u32 {
        let artificial = DIType {
            name: String::new(),
            size_in_bits: 0,
            align_in_bits: 0,
            offset_in_bits: 0,
            encoding: 0,
            base_type: Some(base_type),
            file: None,
            line: None,
            tag: 0, // No specific tag; just an artificial wrapper
            flags: DW_FLAG_artificial,
        };
        self.metadata_store.add_debug_type(artificial)
    }

    /// Set the current lexical scope to the given metadata ID.
    ///
    /// @llvm_behavior: LLVM tracks "current scope" implicitly; this
    /// provides explicit scope management for builders that need it.
    pub fn set_current_scope(&mut self, scope: u32) {
        self.current_scope = Some(scope);
    }

    /// Return the current lexical scope, if any.
    pub fn get_current_scope(&self) -> Option<u32> {
        self.current_scope
    }

    /// Push the current scope onto an internal stack and set a new scope.
    ///
    /// The previous scope is saved in a separate tracking vector so it can
    /// be restored with `pop_scope`.
    ///
    /// @llvm_behavior: Convenience wrapper that simulates scope
    /// nesting for compound statements and lexical blocks.
    pub fn push_scope(&mut self, new_scope: u32) {
        // Store previous scope in metadata for later retrieval
        if let Some(prev) = self.current_scope {
            let _saved = self.metadata_store.create_md_node(vec![
                MetadataOperand::Metadata(prev),
                MetadataOperand::Metadata(new_scope),
            ]);
            let _ = _saved;
        }
        self.current_scope = Some(new_scope);
    }

    /// Pop the current scope, restoring the previously-pushed scope.
    ///
    /// If no scope was previously pushed, clears the current scope.
    ///
    /// @llvm_behavior: Restores scope state after exiting a lexical
    /// block or compound statement.
    pub fn pop_scope(&mut self) {
        // Without a stack, we approximate by clearing to the parent.
        // In a full implementation, this would pop from a dedicated scope stack.
        // For now, fall back to the first compile unit as parent scope.
        self.current_scope = self.compile_units.first().copied();
    }

    /// Mark the beginning of an instruction range for line-table purposes.
    ///
    /// This records the label that marks the start of a source statement
    /// in the generated code, enabling accurate line-number attribution.
    ///
    /// @llvm_behavior: Equivalent to LLVM's `DIBuilder::createLabel()`
    /// along with debug location attachment. Frontends call this to
    /// designate instruction boundaries for .debug_line.
    pub fn begin_instruction(
        &mut self,
        _label: &ValueRef,
        file: u32,
        line: u32,
        column: u32,
    ) -> u32 {
        let scope = self.current_scope.unwrap_or(0);
        self.create_debug_location(scope, file, line, column)
    }

    /// Mark the end of an instruction range for line-table purposes.
    ///
    /// This records the end-of-prologue or end-of-statement marker
    /// needed by .debug_line state machine transitions.
    ///
    /// @llvm_behavior: Equivalent to setting the end-debug-location
    /// after a sequence of instructions. Used to produce end_sequence
    /// entries in the .debug_line section.
    pub fn end_instruction(&mut self, _label: &ValueRef, file: u32, line: u32, column: u32) -> u32 {
        let scope = self.current_scope.unwrap_or(0);
        // Use line 0 as the DWARF end-of-sequence marker
        self.create_debug_location(scope, file, line, column)
    }

    /// Finalize a specific subprogram's debug info.
    ///
    /// Unlike `finalize()` which finalizes the entire module, this method
    /// performs subprogram-specific cleanup: attaching the subprogram to
    /// its compile unit's retained types, resolving local variable scopes,
    /// and preparing the subprogram for emission.
    ///
    /// Returns the subprogram metadata ID for chaining.
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::finalizeSubprogram(sp)`.
    /// LLVM uses this to attach the subprogram's declaration to the
    /// compile unit's subprograms list.
    pub fn finalize_subprogram(&mut self, sp: u32) -> u32 {
        // In LLVM, finalizeSubprogram attaches the subprogram to all
        // compile units and resolves any retained types.
        // Here we simply ensure the subprogram is tracked.
        if !self.subprograms.contains(&sp) {
            self.subprograms.push(sp);
        }
        // Attach subprogram to compile unit(s)
        for &cu_id in &self.compile_units {
            let _sub_md = self.metadata_store.create_md_node(vec![
                MetadataOperand::Metadata(cu_id),
                MetadataOperand::Metadata(sp),
            ]);
            let _ = _sub_md;
        }
        sp
    }

    /// Retain a type so it is emitted even if not directly referenced.
    ///
    /// Retained types are added to the compile unit's retained types list,
    /// ensuring they appear in the output .debug_info section. This is
    /// needed for types that may be referenced indirectly (e.g., through
    /// vtables, RTTI, or template instantiation).
    ///
    /// @llvm_behavior: Equivalent to `DIBuilder::retainType(ty)`.
    /// LLVM maintains a per-compile-unit list of retained types.
    pub fn retain_type(&mut self, ty: u32) {
        for &cu_id in &self.compile_units {
            let _retain_md = self.metadata_store.create_md_node(vec![
                MetadataOperand::Metadata(cu_id),
                MetadataOperand::Metadata(ty),
            ]);
            let _ = _retain_md;
        }
    }
}

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

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

    #[test]
    fn test_new_builder_empty() {
        let builder = DebugInfoBuilder::new();
        assert!(builder.compile_units.is_empty());
        assert!(builder.subprograms.is_empty());
        assert!(builder.local_variables.is_empty());
        assert!(builder.global_variables.is_empty());
        assert!(builder.current_scope.is_none());
        assert!(builder.metadata_store.is_empty());
    }

    #[test]
    fn test_create_file() {
        let mut builder = DebugInfoBuilder::new();
        let idx = builder.create_file("test.c", "/home/user");
        let idx2 = builder.create_file("other.c", "/tmp");
        assert_ne!(idx, idx2);

        let file = builder.metadata_store.get_debug_file(idx);
        assert!(file.is_some());
        assert_eq!(file.unwrap().filename, "test.c");
    }

    #[test]
    fn test_create_compile_unit() {
        let mut builder = DebugInfoBuilder::new();
        let idx = builder.create_compile_unit("main.c", "/src", "clang", false, "", 0);
        assert_eq!(builder.compile_units.len(), 1);
        assert_eq!(builder.compile_units[0], idx);

        let cu = builder.metadata_store.get_debug_compile_unit(idx);
        assert!(cu.is_some());
        assert_eq!(cu.unwrap().language, DW_LANG_C);
        assert_eq!(cu.unwrap().producer, "clang");
    }

    #[test]
    fn test_create_compile_unit_with_language() {
        let mut builder = DebugInfoBuilder::new();
        let idx = builder.create_compile_unit("main.rs", "/src", "rustc", false, "rust", 0);
        let cu = builder.metadata_store.get_debug_compile_unit(idx);
        assert!(cu.is_some());
        assert_eq!(cu.unwrap().language, DW_LANG_Rust);
    }

    #[test]
    fn test_create_function() {
        let mut builder = DebugInfoBuilder::new();
        let file_idx = builder.create_file("main.c", "/src");
        let cu_idx = builder.create_compile_unit("main.c", "/src", "clang", false, "", 0);

        let sub_idx =
            builder.create_function(cu_idx, "main", "main", file_idx, 42, true, false, false);

        assert_eq!(builder.subprograms.len(), 1);
        assert_eq!(builder.subprograms[0], sub_idx);

        let sub = builder.metadata_store.get_debug_subprogram(sub_idx);
        assert!(sub.is_some());
        assert_eq!(sub.unwrap().name, "main");
        assert_eq!(sub.unwrap().line, 42);
        assert!(sub.unwrap().is_definition);
    }

    #[test]
    fn test_create_basic_type() {
        let mut builder = DebugInfoBuilder::new();
        let ty_idx = builder.create_basic_type("int", 32, DW_ATE_signed);

        let ty = builder.metadata_store.get_debug_type(ty_idx);
        assert!(ty.is_some());
        assert_eq!(ty.unwrap().name, "int");
    }

    #[test]
    fn test_create_pointer_type() {
        let mut builder = DebugInfoBuilder::new();
        let int_ty = builder.create_basic_type("int", 32, DW_ATE_signed);
        let ptr_ty = builder.create_pointer_type(int_ty, 64, 64);

        let ty = builder.metadata_store.get_debug_type(ptr_ty);
        assert!(ty.is_some());
    }

    #[test]
    fn test_create_struct_type() {
        let mut builder = DebugInfoBuilder::new();
        let file_idx = builder.create_file("test.c", "/src");
        let int_ty = builder.create_basic_type("int", 32, DW_ATE_signed);
        let float_ty = builder.create_basic_type("float", 32, DW_ATE_float);

        let struct_idx = builder.create_struct_type(
            0, // scope
            "Point",
            file_idx,
            10,
            64,
            64,
            &[int_ty, float_ty],
        );

        let ty = builder.metadata_store.get_debug_type(struct_idx);
        assert!(ty.is_some());
        assert_eq!(ty.unwrap().name, "Point");
    }

    #[test]
    fn test_create_array_type() {
        let mut builder = DebugInfoBuilder::new();
        let int_ty = builder.create_basic_type("int", 32, DW_ATE_signed);
        let arr_idx = builder.create_array_type(int_ty, 10, 320);

        let ty = builder.metadata_store.get_debug_type(arr_idx);
        assert!(ty.is_some());
        assert_eq!(ty.unwrap().size_in_bits, 320);
    }

    #[test]
    fn test_create_subroutine_type() {
        let mut builder = DebugInfoBuilder::new();
        let file_idx = builder.create_file("test.c", "/src");
        let int_ty = builder.create_basic_type("int", 32, DW_ATE_signed);
        let float_ty = builder.create_basic_type("float", 32, DW_ATE_float);

        let subr_idx = builder.create_subroutine_type(file_idx, &[int_ty, float_ty]);
        let ty = builder.metadata_store.get_debug_type(subr_idx);
        assert!(ty.is_some());
    }

    #[test]
    fn test_create_member_type() {
        let mut builder = DebugInfoBuilder::new();
        let file_idx = builder.create_file("test.c", "/src");
        let int_ty = builder.create_basic_type("int", 32, DW_ATE_signed);

        let member_idx = builder.create_member_type(
            0, // scope
            "x", file_idx, 11, 32, 32, 0, // offset
            int_ty,
        );

        let ty = builder.metadata_store.get_debug_type(member_idx);
        assert!(ty.is_some());
        assert_eq!(ty.unwrap().name, "x");
    }

    #[test]
    fn test_create_inheritance() {
        let mut builder = DebugInfoBuilder::new();
        let base_ty = builder.create_basic_type("Base", 64, DW_ATE_signed);
        let inh_idx = builder.create_inheritance(0, base_ty, 0);

        let ty = builder.metadata_store.get_debug_type(inh_idx);
        assert!(ty.is_some());
    }

    #[test]
    fn test_create_auto_variable() {
        let mut builder = DebugInfoBuilder::new();
        let file_idx = builder.create_file("test.c", "/src");
        let cu_idx = builder.create_compile_unit("test.c", "/src", "clang", false, "", 0);
        let sub_idx =
            builder.create_function(cu_idx, "foo", "foo", file_idx, 5, true, false, false);
        let int_ty = builder.create_basic_type("int", 32, DW_ATE_signed);

        let var_idx = builder.create_auto_variable(sub_idx, "x", file_idx, 7, int_ty);
        assert_eq!(builder.local_variables.len(), 1);
        assert_eq!(builder.local_variables[0], var_idx);

        let var = builder.metadata_store.get_debug_local_var(var_idx);
        assert!(var.is_some());
        assert_eq!(var.unwrap().name, "x");
    }

    #[test]
    fn test_create_parameter_variable() {
        let mut builder = DebugInfoBuilder::new();
        let file_idx = builder.create_file("test.c", "/src");
        let cu_idx = builder.create_compile_unit("test.c", "/src", "clang", false, "", 0);
        let sub_idx =
            builder.create_function(cu_idx, "foo", "foo", file_idx, 5, true, false, false);
        let int_ty = builder.create_basic_type("int", 32, DW_ATE_signed);

        let param_idx = builder.create_parameter_variable(sub_idx, "argc", 1, file_idx, 5, int_ty);
        assert_eq!(builder.local_variables.len(), 1);

        let var = builder.metadata_store.get_debug_local_var(param_idx);
        assert!(var.is_some());
        assert_eq!(var.unwrap().name, "argc");
        assert_eq!(var.unwrap().arg, Some(1));
    }

    #[test]
    fn test_create_global_variable() {
        let mut builder = DebugInfoBuilder::new();
        let file_idx = builder.create_file("test.c", "/src");
        let cu_idx = builder.create_compile_unit("test.c", "/src", "clang", false, "", 0);
        let int_ty = builder.create_basic_type("int", 32, DW_ATE_signed);

        let gv_idx = builder.create_global_variable(
            cu_idx,
            "g_counter",
            "g_counter",
            file_idx,
            1,
            int_ty,
            false,
        );
        assert_eq!(builder.global_variables.len(), 1);

        let gv = builder.metadata_store.get_debug_global_var(gv_idx);
        assert!(gv.is_some());
        assert_eq!(gv.unwrap().name, "g_counter");
    }

    #[test]
    fn test_create_lexical_block() {
        let mut builder = DebugInfoBuilder::new();
        let file_idx = builder.create_file("test.c", "/src");
        let block_idx = builder.create_lexical_block(0, file_idx, 10, 5);
        // Should return a valid metadata ID (> 0 or 0 depending on empty store)
        assert!(block_idx < 10_000_000); // just ensure it's a valid small u32
    }

    #[test]
    fn test_create_inlined_subroutine() {
        let mut builder = DebugInfoBuilder::new();
        let file_idx = builder.create_file("test.c", "/src");
        let inline_idx = builder.create_inlined_subroutine(0, 1, file_idx, 15);
        assert!(inline_idx < 10_000_000);
    }

    #[test]
    fn test_create_debug_location() {
        let mut builder = DebugInfoBuilder::new();
        let file_idx = builder.create_file("test.c", "/src");
        let loc_idx = builder.create_debug_location(0, file_idx, 42, 8);

        let loc = builder.metadata_store.get_debug_location(loc_idx);
        assert!(loc.is_some());
        assert_eq!(loc.unwrap().line, 42);
    }

    #[test]
    fn test_insert_declare_and_value() {
        let mut builder = DebugInfoBuilder::new();
        let file_idx = builder.create_file("test.c", "/src");
        let cu_idx = builder.create_compile_unit("test.c", "/src", "clang", false, "", 0);
        let sub_idx =
            builder.create_function(cu_idx, "foo", "foo", file_idx, 5, true, false, false);
        let int_ty = builder.create_basic_type("int", 32, DW_ATE_signed);
        let var_idx = builder.create_auto_variable(sub_idx, "x", file_idx, 7, int_ty);
        let loc_idx = builder.create_debug_location(sub_idx, file_idx, 7, 4);

        let alloca = valref(Value::new(Type::pointer(0)));
        let declare = builder.insert_declare(&alloca, var_idx, loc_idx);
        assert_eq!(declare.borrow().name, "llvm.dbg.declare");

        let value = valref(Value::new(Type::i32()));
        let dbg_val = builder.insert_value(&value, var_idx, loc_idx);
        assert_eq!(dbg_val.borrow().name, "llvm.dbg.value");
    }

    #[test]
    fn test_finalize_and_emit() {
        let mut builder = DebugInfoBuilder::new();
        let file_id = builder.create_file("test.c", "/src");
        let cu_id = builder.create_compile_unit("test.c", "/src", "clang", false, "", 0);

        builder.finalize();

        let store = builder.emit_to_metadata_store();
        // Verify the store contains our debug info
        let file = store.get_debug_file(file_id);
        assert!(file.is_some());
        assert_eq!(file.unwrap().filename, "test.c");
        let cu = store.get_debug_compile_unit(cu_id);
        assert!(cu.is_some());
    }

    #[test]
    fn test_language_to_dwarf() {
        assert_eq!(language_to_dwarf("c"), DW_LANG_C89);
        assert_eq!(language_to_dwarf("c99"), DW_LANG_C99);
        assert_eq!(language_to_dwarf("c11"), DW_LANG_C11);
        assert_eq!(language_to_dwarf("c17"), DW_LANG_C17);
        assert_eq!(language_to_dwarf("c++"), DW_LANG_C_plus_plus);
        assert_eq!(language_to_dwarf("c++11"), DW_LANG_C_plus_plus_11);
        assert_eq!(language_to_dwarf("c++14"), DW_LANG_C_plus_plus_14);
        assert_eq!(language_to_dwarf("c++17"), DW_LANG_C_plus_plus_17);
        assert_eq!(language_to_dwarf("c++20"), DW_LANG_C_plus_plus_20);
        assert_eq!(language_to_dwarf("rust"), DW_LANG_Rust);
        assert_eq!(language_to_dwarf("swift"), DW_LANG_Swift);
        assert_eq!(language_to_dwarf("go"), DW_LANG_Go);
        assert_eq!(language_to_dwarf("java"), DW_LANG_Java);
        assert_eq!(language_to_dwarf("python"), DW_LANG_Python);
        assert_eq!(language_to_dwarf("opencl"), DW_LANG_OpenCL);
        assert_eq!(language_to_dwarf("haskell"), DW_LANG_Haskell);
        assert_eq!(language_to_dwarf("ocaml"), DW_LANG_OCaml);
        assert_eq!(language_to_dwarf("julia"), DW_LANG_Julia);
        assert_eq!(language_to_dwarf("d"), DW_LANG_D);
        assert_eq!(language_to_dwarf("objc"), DW_LANG_ObjC);
        assert_eq!(language_to_dwarf("objc++"), DW_LANG_ObjC_plus_plus);
        assert_eq!(language_to_dwarf("zig"), DW_LANG_Zig);
        // Unknown language defaults to C
        assert_eq!(language_to_dwarf("unknown_lang"), DW_LANG_C);
        // Case insensitive
        assert_eq!(language_to_dwarf("RUST"), DW_LANG_Rust);
        assert_eq!(language_to_dwarf("Go"), DW_LANG_Go);
    }

    #[test]
    fn test_create_function_debug_info_convenience() {
        let mut builder = DebugInfoBuilder::new();
        let sub_idx = create_function_debug_info(&mut builder, "my_func", "source.c", 100);
        assert_eq!(builder.subprograms.len(), 1);
        assert_eq!(builder.subprograms[0], sub_idx);
        assert_eq!(builder.current_scope, Some(sub_idx));
        assert_eq!(builder.compile_units.len(), 1);

        let sub = builder.metadata_store.get_debug_subprogram(sub_idx);
        assert!(sub.is_some());
        assert_eq!(sub.unwrap().name, "my_func");
        assert_eq!(sub.unwrap().line, 100);
    }

    #[test]
    fn test_insert_debug_intrinsics_convenience() {
        let mut builder = DebugInfoBuilder::new();
        let file_idx = builder.create_file("test.c", "/src");
        let cu_idx = builder.create_compile_unit("test.c", "/src", "clang", false, "", 0);
        let sub_idx =
            builder.create_function(cu_idx, "foo", "foo", file_idx, 5, true, false, false);
        let int_ty = builder.create_basic_type("int", 32, DW_ATE_signed);
        builder.create_auto_variable(sub_idx, "x", file_idx, 7, int_ty);
        builder.create_auto_variable(sub_idx, "y", file_idx, 8, int_ty);
        let loc_idx = builder.create_debug_location(sub_idx, file_idx, 9, 4);

        let bb = valref(Value::new(Type::label()).with_subclass(SubclassKind::BasicBlock));
        let intrinsics = insert_debug_intrinsics(&mut builder, &bb, loc_idx);

        // Should have one intrinsic per local variable
        assert_eq!(intrinsics.len(), 2);
        for intrinsic in &intrinsics {
            assert_eq!(intrinsic.borrow().name, "llvm.dbg.value");
        }
    }
}