llvm-native-core 0.1.14

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

#![allow(non_upper_case_globals, non_camel_case_types, dead_code)]

use std::collections::HashMap;

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

/// DWARF language codes.
pub mod dwarf_lang {
    pub const DW_LANG_C89: u16 = 0x0001;
    pub const DW_LANG_C: u16 = 0x0002;
    pub const DW_LANG_C_plus_plus: u16 = 0x0004;
    pub const DW_LANG_C99: u16 = 0x000c;
    pub const DW_LANG_C11: u16 = 0x001d;
    pub const DW_LANG_C17: u16 = 0x002a;
    pub const DW_LANG_C23: u16 = 0x003c;
    pub const DW_LANG_C_plus_plus_03: u16 = 0x0013;
    pub const DW_LANG_C_plus_plus_11: u16 = 0x001a;
    pub const DW_LANG_C_plus_plus_14: u16 = 0x0021;
    pub const DW_LANG_C_plus_plus_17: u16 = 0x002e;
    pub const DW_LANG_C_plus_plus_20: u16 = 0x0037;
    pub const DW_LANG_Rust: u16 = 0x001c;
    pub const DW_LANG_Go: u16 = 0x0016;
    pub const DW_LANG_Swift: u16 = 0x001e;
    pub const DW_LANG_Fortran95: u16 = 0x000e;
    pub const DW_LANG_Ada95: u16 = 0x000d;
    pub const DW_LANG_PLI: u16 = 0x000f;
    pub const DW_LANG_ObjC: u16 = 0x0010;
    pub const DW_LANG_ObjC_plus_plus: u16 = 0x0011;
    pub const DW_LANG_D: u16 = 0x0013;
    pub const DW_LANG_Python: u16 = 0x0014;
    pub const DW_LANG_OpenCL: u16 = 0x0015;
    pub const DW_LANG_Haskell: u16 = 0x0018;
    pub const DW_LANG_Modula3: u16 = 0x0019;
    pub const DW_LANG_Julia: u16 = 0x0023;
    pub const DW_LANG_Dylan: u16 = 0x0024;
    pub const DW_LANG_Assembly: u16 = 0x8001;
}

/// DWARF tag values.
pub mod dwarf_tag {
    pub const DW_TAG_compile_unit: u16 = 0x11;
    pub const DW_TAG_subprogram: u16 = 0x2e;
    pub const DW_TAG_variable: u16 = 0x34;
    pub const DW_TAG_formal_parameter: u16 = 0x05;
    pub const DW_TAG_lexical_block: u16 = 0x0b;
    pub const DW_TAG_inlined_subroutine: u16 = 0x1d;
    pub const DW_TAG_base_type: u16 = 0x24;
    pub const DW_TAG_pointer_type: u16 = 0x0f;
    pub const DW_TAG_reference_type: u16 = 0x10;
    pub const DW_TAG_rvalue_reference_type: u16 = 0x42;
    pub const DW_TAG_const_type: u16 = 0x26;
    pub const DW_TAG_volatile_type: u16 = 0x35;
    pub const DW_TAG_restrict_type: u16 = 0x37;
    pub const DW_TAG_typedef: u16 = 0x16;
    pub const DW_TAG_structure_type: u16 = 0x13;
    pub const DW_TAG_union_type: u16 = 0x17;
    pub const DW_TAG_class_type: u16 = 0x02;
    pub const DW_TAG_enumeration_type: u16 = 0x04;
    pub const DW_TAG_enumerator: u16 = 0x28;
    pub const DW_TAG_array_type: u16 = 0x01;
    pub const DW_TAG_subrange_type: u16 = 0x21;
    pub const DW_TAG_subroutine_type: u16 = 0x15;
    pub const DW_TAG_member: u16 = 0x0d;
    pub const DW_TAG_inheritance: u16 = 0x1c;
    pub const DW_TAG_unspecified_type: u16 = 0x3b;
    pub const DW_TAG_unspecified_parameters: u16 = 0x21;
}

/// DWARF attribute values.
pub mod dwarf_attr {
    pub const DW_AT_name: u16 = 0x03;
    pub const DW_AT_producer: u16 = 0x25;
    pub const DW_AT_language: u16 = 0x13;
    pub const DW_AT_comp_dir: u16 = 0x1b;
    pub const DW_AT_low_pc: u16 = 0x11;
    pub const DW_AT_high_pc: u16 = 0x12;
    pub const DW_AT_location: u16 = 0x02;
    pub const DW_AT_type: u16 = 0x31;
    pub const DW_AT_decl_file: u16 = 0x3a;
    pub const DW_AT_decl_line: u16 = 0x3b;
    pub const DW_AT_decl_column: u16 = 0x39;
    pub const DW_AT_external: u16 = 0x3f;
    pub const DW_AT_artificial: u16 = 0x34;
    pub const DW_AT_inline: u16 = 0x20;
    pub const DW_AT_abstract_origin: u16 = 0x31;
    pub const DW_AT_specification: u16 = 0x47;
    pub const DW_AT_ranges: u16 = 0x55;
    pub const DW_AT_stmt_list: u16 = 0x10;
    pub const DW_AT_byte_size: u16 = 0x0b;
    pub const DW_AT_bit_size: u16 = 0x0d;
    pub const DW_AT_bit_offset: u16 = 0x0c;
    pub const DW_AT_data_member_location: u16 = 0x38;
    pub const DW_AT_accessibility: u16 = 0x32;
    pub const DW_AT_linkage_name: u16 = 0x6e;
    pub const DW_AT_frame_base: u16 = 0x40;
    pub const DW_AT_encoding: u16 = 0x3e;
    pub const DW_AT_const_value: u16 = 0x1c;
    pub const DW_AT_upper_bound: u16 = 0x2f;
    pub const DW_AT_lower_bound: u16 = 0x22;
    pub const DW_AT_count: u16 = 0x0b;
    pub const DW_AT_containing_type: u16 = 0x1d;
    pub const DW_AT_virtuality: u16 = 0x4c;
    pub const DW_AT_vtable_elem_location: u16 = 0x4d;
    pub const DW_AT_enum_class: u16 = 0x4e;
    pub const DW_AT_identifier_case: u16 = 0x42;
    pub const DW_AT_return_addr: u16 = 0x2a;
    pub const DW_AT_entry_pc: u16 = 0x52;
    pub const DW_AT_use_UTF8: u16 = 0x53;
    pub const DW_AT_call_file: u16 = 0x58;
    pub const DW_AT_call_line: u16 = 0x59;
    pub const DW_AT_call_column: u16 = 0x57;
    pub const DW_AT_description: u16 = 0x5a;
    pub const DW_AT_GNU_locviews: u16 = 0x2137;
}

/// DWARF form values.
pub mod dwarf_form {
    pub const DW_FORM_addr: u16 = 0x01;
    pub const DW_FORM_data1: u16 = 0x0b;
    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_block2: u16 = 0x03;
    pub const DW_FORM_block4: u16 = 0x04;
    pub const DW_FORM_flag: u16 = 0x0c;
    pub const DW_FORM_flag_present: u16 = 0x19;
    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_sec_offset: u16 = 0x17;
    pub const DW_FORM_exprloc: u16 = 0x18;
    pub const DW_FORM_strp: u16 = 0x0e;
    pub const DW_FORM_udata: u16 = 0x0f;
    pub const DW_FORM_sdata: u16 = 0x0d;
    pub const DW_FORM_strx: u16 = 0x1a;
    pub const DW_FORM_addrx: u16 = 0x1b;
    pub const DW_FORM_line_strp: u16 = 0x1f;
}

/// DWARF inline codes.
pub mod dwarf_inline {
    pub const DW_INL_not_inlined: u16 = 0;
    pub const DW_INL_inlined: u16 = 1;
    pub const DW_INL_declared_not_inlined: u16 = 2;
    pub const DW_INL_declared_inlined: u16 = 3;
}

/// DWARF operation codes for location expressions.
pub mod dwarf_op {
    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;
    pub const DW_OP_lit31: u8 = 0x4f;
    pub const DW_OP_reg0: u8 = 0x50;
    pub const DW_OP_reg31: u8 = 0x6f;
    pub const DW_OP_breg0: u8 = 0x70;
    pub const DW_OP_breg31: u8 = 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;
}

// ============================================================================
// X86 DWARF Register Mapping
// ============================================================================

/// X86-64 DWARF register numbers.
pub mod x86_64_dwarf_reg {
    pub const RAX: u16 = 0;
    pub const RDX: u16 = 1;
    pub const RCX: u16 = 2;
    pub const RBX: u16 = 3;
    pub const RSI: u16 = 4;
    pub const RDI: u16 = 5;
    pub const RBP: u16 = 6;
    pub const RSP: u16 = 7;
    pub const R8: u16 = 8;
    pub const R9: u16 = 9;
    pub const R10: u16 = 10;
    pub const R11: u16 = 11;
    pub const R12: u16 = 12;
    pub const R13: u16 = 13;
    pub const R14: u16 = 14;
    pub const R15: u16 = 15;
    pub const RIP: u16 = 16;
    pub const XMM0: u16 = 17;
    pub const XMM15: u16 = 32;
    pub const ST0: u16 = 33;
    pub const ST7: u16 = 40;
    pub const MM0: u16 = 41;
    pub const MM7: u16 = 48;
    pub const RFLAGS: u16 = 49;
    pub const ES: u16 = 50;
    pub const CS: u16 = 51;
    pub const SS: u16 = 52;
    pub const DS: u16 = 53;
    pub const FS: u16 = 54;
    pub const GS: u16 = 55;
    pub const FS_BASE: u16 = 58;
    pub const GS_BASE: u16 = 59;
    pub const TR: u16 = 62;
    pub const LDTR: u16 = 63;
    pub const MXCSR: u16 = 64;
    pub const FCW: u16 = 65;
    pub const FSW: u16 = 66;
}

/// X86-32 DWARF register numbers.
pub mod x86_32_dwarf_reg {
    pub const EAX: u16 = 0;
    pub const ECX: u16 = 1;
    pub const EDX: u16 = 2;
    pub const EBX: u16 = 3;
    pub const ESP: u16 = 4;
    pub const EBP: u16 = 5;
    pub const ESI: u16 = 6;
    pub const EDI: u16 = 7;
    pub const EIP: u16 = 8;
    pub const ST0: u16 = 11;
    pub const ST7: u16 = 18;
    pub const XMM0: u16 = 21;
    pub const XMM7: u16 = 28;
    pub const MM0: u16 = 29;
    pub const MM7: u16 = 36;
    pub const EFLAGS: u16 = 9;
}

/// Map an x86-64 register name to its DWARF register number.
pub fn x86_64_reg_to_dwarf(name: &str) -> Option<u16> {
    match name.to_lowercase().as_str() {
        "rax" => Some(x86_64_dwarf_reg::RAX),
        "rdx" => Some(x86_64_dwarf_reg::RDX),
        "rcx" => Some(x86_64_dwarf_reg::RCX),
        "rbx" => Some(x86_64_dwarf_reg::RBX),
        "rsi" => Some(x86_64_dwarf_reg::RSI),
        "rdi" => Some(x86_64_dwarf_reg::RDI),
        "rbp" => Some(x86_64_dwarf_reg::RBP),
        "rsp" => Some(x86_64_dwarf_reg::RSP),
        "r8" => Some(x86_64_dwarf_reg::R8),
        "r9" => Some(x86_64_dwarf_reg::R9),
        "r10" => Some(x86_64_dwarf_reg::R10),
        "r11" => Some(x86_64_dwarf_reg::R11),
        "r12" => Some(x86_64_dwarf_reg::R12),
        "r13" => Some(x86_64_dwarf_reg::R13),
        "r14" => Some(x86_64_dwarf_reg::R14),
        "r15" => Some(x86_64_dwarf_reg::R15),
        "rip" => Some(x86_64_dwarf_reg::RIP),
        "xmm0" => Some(x86_64_dwarf_reg::XMM0),
        "xmm1" => Some(18),
        "xmm14" => Some(31),
        "xmm15" => Some(x86_64_dwarf_reg::XMM15),
        "rflags" => Some(x86_64_dwarf_reg::RFLAGS),
        _ => None,
    }
}

/// Map an x86-32 register name to its DWARF register number.
pub fn x86_32_reg_to_dwarf(name: &str) -> Option<u16> {
    match name.to_lowercase().as_str() {
        "eax" => Some(x86_32_dwarf_reg::EAX),
        "ecx" => Some(x86_32_dwarf_reg::ECX),
        "edx" => Some(x86_32_dwarf_reg::EDX),
        "ebx" => Some(x86_32_dwarf_reg::EBX),
        "esp" => Some(x86_32_dwarf_reg::ESP),
        "ebp" => Some(x86_32_dwarf_reg::EBP),
        "esi" => Some(x86_32_dwarf_reg::ESI),
        "edi" => Some(x86_32_dwarf_reg::EDI),
        "eip" => Some(x86_32_dwarf_reg::EIP),
        _ => None,
    }
}

// ============================================================================
// DWARF Location Expression Builder
// ============================================================================

/// A DWARF location expression (list of operations).
#[derive(Debug, Clone)]
pub struct X86DebugLocationExpr {
    /// The raw byte sequence of the expression.
    pub bytes: Vec<u8>,
    /// Address size in bytes (4 or 8).
    pub address_size: u8,
    /// Whether this expression produces a location (versus a value).
    pub is_location: bool,
}

impl X86DebugLocationExpr {
    pub fn new(address_size: u8) -> Self {
        Self {
            bytes: Vec::new(),
            address_size,
            is_location: true,
        }
    }

    pub fn new_x86_64() -> Self {
        Self::new(8)
    }

    pub fn new_x86_32() -> Self {
        Self::new(4)
    }

    /// Get the expression as a byte slice.
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Length of the expression in bytes.
    pub fn len(&self) -> usize {
        self.bytes.len()
    }

    /// Whether the expression is empty.
    pub fn is_empty(&self) -> bool {
        self.bytes.is_empty()
    }

    /// Clear the expression.
    pub fn clear(&mut self) {
        self.bytes.clear();
    }

    /// Emit a single byte.
    fn emit_u8(&mut self, byte: u8) {
        self.bytes.push(byte);
    }

    /// Emit a 16-bit unsigned integer (little-endian).
    fn emit_u16(&mut self, val: u16) {
        self.bytes.extend_from_slice(&val.to_le_bytes());
    }

    /// Emit a 32-bit unsigned integer (little-endian).
    fn emit_u32(&mut self, val: u32) {
        self.bytes.extend_from_slice(&val.to_le_bytes());
    }

    /// Emit a 64-bit unsigned integer (little-endian).
    fn emit_u64(&mut self, val: u64) {
        self.bytes.extend_from_slice(&val.to_le_bytes());
    }

    /// Emit an address-sized value.
    fn emit_addr(&mut self, addr: u64) {
        match self.address_size {
            4 => self.emit_u32(addr as u32),
            8 => self.emit_u64(addr),
            _ => self.emit_u64(addr),
        }
    }

    /// Emit an unsigned LEB128 value.
    fn emit_uleb128(&mut self, mut val: u64) {
        loop {
            let mut byte = (val & 0x7f) as u8;
            val >>= 7;
            if val != 0 {
                byte |= 0x80;
            }
            self.bytes.push(byte);
            if val == 0 {
                break;
            }
        }
    }

    /// Emit a signed LEB128 value.
    fn emit_sleb128(&mut self, val: i64) {
        let mut more = true;
        let mut v = val;
        while more {
            let mut byte = (v & 0x7f) as u8;
            v >>= 7;
            if (v == 0 && byte & 0x40 == 0) || (v == -1 && byte & 0x40 != 0) {
                more = false;
            } else {
                byte |= 0x80;
            }
            self.bytes.push(byte);
        }
    }

    // ---- DW_OP Operations ----

    /// DW_OP_addr: push an absolute address.
    pub fn addr(&mut self, address: u64) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_addr);
        self.emit_addr(address);
        self
    }

    /// DW_OP_deref: dereference top of stack.
    pub fn deref(&mut self) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_deref);
        self
    }

    /// DW_OP_deref_size: dereference with explicit size.
    pub fn deref_size(&mut self, size: u8) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_deref_size);
        self.emit_u8(size);
        self
    }

    /// DW_OP_reg: variable is in a register.
    pub fn reg(&mut self, dwarf_reg: u16) -> &mut Self {
        if dwarf_reg < 32 {
            self.emit_u8(dwarf_op::DW_OP_reg0 + dwarf_reg as u8);
        } else {
            self.emit_u8(dwarf_op::DW_OP_regx);
            self.emit_uleb128(dwarf_reg as u64);
        }
        self
    }

    /// DW_OP_breg: variable is at register + offset.
    pub fn breg(&mut self, dwarf_reg: u16, offset: i64) -> &mut Self {
        if dwarf_reg < 32 {
            self.emit_u8(dwarf_op::DW_OP_breg0 + dwarf_reg as u8);
        } else {
            self.emit_u8(dwarf_op::DW_OP_bregx);
            self.emit_uleb128(dwarf_reg as u64);
        }
        self.emit_sleb128(offset);
        self
    }

    /// DW_OP_fbreg: variable is at frame_base + offset.
    pub fn fbreg(&mut self, offset: i64) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_fbreg);
        self.emit_sleb128(offset);
        self
    }

    /// Convenience: variable below RBP (x86-64).
    pub fn rbp_offset_64(&mut self, offset: i64) -> &mut Self {
        self.breg(x86_64_dwarf_reg::RBP, offset)
    }

    /// Convenience: variable below EBP (x86-32).
    pub fn ebp_offset_32(&mut self, offset: i64) -> &mut Self {
        self.breg(x86_32_dwarf_reg::EBP, offset)
    }

    /// Value is in RAX.
    pub fn in_rax(&mut self) -> &mut Self {
        self.reg(x86_64_dwarf_reg::RAX)
    }

    /// Value is in an XMM register.
    pub fn in_xmm(&mut self, index: u16) -> &mut Self {
        let dwarf_reg = x86_64_dwarf_reg::XMM0 + index;
        self.reg(dwarf_reg)
    }

    /// DW_OP_piece: take N bytes from stack as a piece.
    pub fn piece(&mut self, size_in_bytes: u64) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_piece);
        self.emit_uleb128(size_in_bytes);
        self
    }

    /// DW_OP_bit_piece: take N bits from stack as a piece.
    pub fn bit_piece(&mut self, size_in_bits: u64, offset_in_bits: u64) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_bit_piece);
        self.emit_uleb128(size_in_bits);
        self.emit_uleb128(offset_in_bits);
        self
    }

    /// DW_OP_stack_value: mark top of stack as a value (not location).
    pub fn stack_value(&mut self) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_stack_value);
        self.is_location = false;
        self
    }

    /// DW_OP_implicit_value: inline N bytes as value.
    pub fn implicit_value(&mut self, data: &[u8]) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_implicit_value);
        self.emit_uleb128(data.len() as u64);
        self.bytes.extend_from_slice(data);
        self.is_location = false;
        self
    }

    /// DW_OP_entry_value: evaluate expression as if at function entry.
    pub fn entry_value(&mut self, inner: &X86DebugLocationExpr) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_entry_value);
        self.emit_uleb128(inner.len() as u64);
        self.bytes.extend_from_slice(inner.as_bytes());
        self
    }

    /// DW_OP_plus: pop two values, push sum.
    pub fn plus(&mut self) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_plus);
        self
    }

    /// DW_OP_minus: pop two values, push (top - second).
    pub fn minus(&mut self) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_minus);
        self
    }

    /// DW_OP_mul: pop two values, push product.
    pub fn mul(&mut self) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_mul);
        self
    }

    /// DW_OP_div: pop two values, push quotient.
    pub fn div(&mut self) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_div);
        self
    }

    /// DW_OP_and: pop two values, push bitwise AND.
    pub fn and(&mut self) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_and);
        self
    }

    /// DW_OP_or: pop two values, push bitwise OR.
    pub fn or(&mut self) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_or);
        self
    }

    /// DW_OP_xor: pop two values, push bitwise XOR.
    pub fn xor(&mut self) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_xor);
        self
    }

    /// DW_OP_shl: pop two values, push (second << top).
    pub fn shl(&mut self) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_shl);
        self
    }

    /// DW_OP_shr: pop two values, push logical right shift.
    pub fn shr(&mut self) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_shr);
        self
    }

    /// DW_OP_plus_uconst: add unsigned constant.
    pub fn plus_uconst(&mut self, val: u64) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_plus_uconst);
        self.emit_uleb128(val);
        self
    }

    /// DW_OP_dup: duplicate top of stack.
    pub fn dup(&mut self) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_dup);
        self
    }

    /// DW_OP_drop: discard top of stack.
    pub fn drop(&mut self) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_drop);
        self
    }

    /// DW_OP_over: push copy of second-to-top element.
    pub fn over(&mut self) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_over);
        self
    }

    /// DW_OP_swap: swap top two stack elements.
    pub fn swap(&mut self) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_swap);
        self
    }

    /// DW_OP_rot: rotate top three elements.
    pub fn rot(&mut self) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_rot);
        self
    }

    /// DW_OP_pick: push copy of N-th element from top.
    pub fn pick(&mut self, index: u8) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_pick);
        self.emit_u8(index);
        self
    }

    /// DW_OP_form_tls_address: resolve TLS address.
    pub fn form_tls_address(&mut self) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_form_tls_address);
        self
    }

    /// DW_OP_call_frame_cfa: push CFA value.
    pub fn call_frame_cfa(&mut self) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_call_frame_cfa);
        self
    }

    /// DW_OP_nop: no operation.
    pub fn nop(&mut self) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_nop);
        self
    }

    /// Build a location description for a local variable below RBP.
    pub fn local_var_below_rbp(&mut self, offset: i64, is_64bit: bool) -> &mut Self {
        if is_64bit {
            self.rbpf(offset)
        } else {
            self.ebp_offset_32(offset)
        }
    }

    /// Build location for a parameter passed in a register.
    pub fn param_in_register(&mut self, reg_name: &str) -> &mut Self {
        if let Some(dwarf_reg) = x86_64_reg_to_dwarf(reg_name) {
            self.reg(dwarf_reg)
        } else {
            self
        }
    }

    /// Build location for a parameter passed on the stack.
    pub fn param_on_stack(&mut self, offset_from_cfa: i64) -> &mut Self {
        self.call_frame_cfa();
        self.plus_uconst(offset_from_cfa as u64);
        self
    }

    /// Build a composite location from multiple pieces.
    pub fn composite_location(&mut self, pieces: &[(u64, &X86DebugLocationExpr)]) -> &mut Self {
        for (size, expr) in pieces {
            self.bytes.extend_from_slice(expr.as_bytes());
            self.piece(*size);
        }
        self
    }

    /// Build a DW_OP_convert expression.
    pub fn convert(&mut self, type_die_offset: u64) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_convert);
        self.emit_uleb128(type_die_offset);
        self
    }

    /// Build a DW_OP_reinterpret expression.
    pub fn reinterpret(&mut self, type_die_offset: u64) -> &mut Self {
        self.emit_u8(dwarf_op::DW_OP_reinterpret);
        self.emit_uleb128(type_die_offset);
        self
    }

    // Helper: DW_OP_breg for RBP on x86-64.
    fn rbpf(&mut self, offset: i64) -> &mut Self {
        self.breg(x86_64_dwarf_reg::RBP, offset)
    }
}

impl Default for X86DebugLocationExpr {
    fn default() -> Self {
        Self::new_x86_64()
    }
}

// ============================================================================
// Line Table Generation
// ============================================================================

/// A file entry in the line table.
#[derive(Debug, Clone)]
pub struct X86DebugFileEntry {
    /// File name.
    pub name: String,
    /// Directory index (0 = compilation directory).
    pub directory_index: u32,
    /// Last modification timestamp.
    pub mod_time: u32,
    /// File length in bytes.
    pub length: u32,
}

impl X86DebugFileEntry {
    pub fn new(name: &str, dir_index: u32) -> Self {
        Self {
            name: name.to_string(),
            directory_index: dir_index,
            mod_time: 0,
            length: 0,
        }
    }
}

/// A source line entry.
#[derive(Debug, Clone)]
pub struct X86DebugLineEntry {
    /// Line number (1-based).
    pub line: u32,
    /// Column number (1-based, 0 = none).
    pub column: u32,
    /// File index (1-based).
    pub file: u32,
    /// Address of this line.
    pub address: u64,
    /// Is this a recommended breakpoint location.
    pub is_stmt: bool,
    /// Does this begin a basic block.
    pub basic_block: bool,
    /// Does this end the function prologue.
    pub prologue_end: bool,
    /// Does this start the function epilogue.
    pub epilogue_begin: bool,
    /// Instruction set architecture identifier.
    pub isa: u32,
    /// Discriminator for multiple basic blocks on the same line.
    pub discriminator: u32,
    /// Is this an end-of-sequence marker.
    pub end_sequence: bool,
}

impl Default for X86DebugLineEntry {
    fn default() -> Self {
        Self {
            line: 0,
            column: 0,
            file: 1,
            address: 0,
            is_stmt: true,
            basic_block: false,
            prologue_end: false,
            epilogue_begin: false,
            isa: 0,
            discriminator: 0,
            end_sequence: false,
        }
    }
}

/// A DWARF line table program.
#[derive(Debug, Clone)]
pub struct X86DebugLineTable {
    /// Compilation directory.
    pub comp_dir: String,
    /// Source files referenced.
    pub files: Vec<X86DebugFileEntry>,
    /// Include directories.
    pub directories: Vec<String>,
    /// Line entries.
    pub entries: Vec<X86DebugLineEntry>,
    /// DWARF version (4 or 5).
    pub version: u16,
    /// Address size in bytes.
    pub address_size: u8,
    /// Minimum instruction length (1 for x86).
    pub min_insn_length: u8,
    /// Maximum operations per instruction (1 for x86).
    pub max_ops_per_insn: u8,
    /// Default is_stmt.
    pub default_is_stmt: bool,
    /// Line base for special opcodes.
    pub line_base: i8,
    /// Line range for special opcodes.
    pub line_range: u8,
    /// Opcode base (one past the highest standard opcode).
    pub opcode_base: u8,
    /// Standard opcode lengths.
    pub standard_opcode_lengths: Vec<u8>,
}

impl X86DebugLineTable {
    /// Create a new line table for x86-64.
    pub fn new_x86_64() -> Self {
        Self {
            comp_dir: String::new(),
            files: Vec::new(),
            directories: Vec::new(),
            entries: Vec::new(),
            version: 4,
            address_size: 8,
            min_insn_length: 1,
            max_ops_per_insn: 1,
            default_is_stmt: true,
            line_base: -5,
            line_range: 14,
            opcode_base: 13,
            standard_opcode_lengths: vec![0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1],
        }
    }

    /// Create a new line table for x86-32.
    pub fn new_x86_32() -> Self {
        let mut tbl = Self::new_x86_64();
        tbl.address_size = 4;
        tbl
    }

    /// Set the compilation directory.
    pub fn set_comp_dir(&mut self, dir: &str) {
        self.comp_dir = dir.to_string();
    }

    /// Add a source file.
    pub fn add_file(&mut self, name: &str, dir_index: u32) -> u32 {
        self.files.push(X86DebugFileEntry::new(name, dir_index));
        self.files.len() as u32
    }

    /// Add an include directory.
    pub fn add_directory(&mut self, path: &str) -> u32 {
        self.directories.push(path.to_string());
        self.directories.len() as u32
    }

    /// Add a line entry.
    pub fn add_entry(&mut self, entry: X86DebugLineEntry) {
        self.entries.push(entry);
    }

    /// Convenience: add a line with address.
    pub fn add_line(&mut self, line: u32, column: u32, file: u32, address: u64) {
        self.add_entry(X86DebugLineEntry {
            line,
            column,
            file,
            address,
            is_stmt: true,
            ..Default::default()
        });
    }

    /// Add an end-of-sequence marker.
    pub fn add_end_sequence(&mut self, address: u64) {
        self.add_entry(X86DebugLineEntry {
            address,
            end_sequence: true,
            ..Default::default()
        });
    }

    /// Add a prologue-end marker.
    pub fn add_prologue_end(&mut self, line: u32, address: u64) {
        self.add_entry(X86DebugLineEntry {
            line,
            address,
            prologue_end: true,
            ..Default::default()
        });
    }

    /// Add an epilogue-begin marker.
    pub fn add_epilogue_begin(&mut self, line: u32, address: u64) {
        self.add_entry(X86DebugLineEntry {
            line,
            address,
            epilogue_begin: true,
            ..Default::default()
        });
    }

    /// Emit the line table as raw bytes.
    pub fn emit(&self) -> Vec<u8> {
        let mut data = Vec::new();

        // Unit length (placeholder, filled later)
        let length_offset = data.len();
        data.extend_from_slice(&[0u8; 4]);

        // Version
        data.extend_from_slice(&self.version.to_le_bytes());

        // Header length (placeholder)
        let header_length_offset = data.len();
        data.extend_from_slice(&[0u8; 4]);

        // Minimum instruction length
        data.push(self.min_insn_length);

        // DWARF 4: maximum operations per instruction
        if self.version >= 4 {
            data.push(self.max_ops_per_insn);
        }

        // Default is_stmt
        data.push(if self.default_is_stmt { 1 } else { 0 });

        // Line base
        data.push(self.line_base as u8);

        // Line range
        data.push(self.line_range);

        // Opcode base
        data.push(self.opcode_base);

        // Standard opcode lengths
        data.extend_from_slice(&self.standard_opcode_lengths);

        // Include directories
        for dir in &self.directories {
            data.extend_from_slice(dir.as_bytes());
            data.push(0);
        }
        data.push(0); // null terminator

        // File entries
        for file in &self.files {
            data.extend_from_slice(file.name.as_bytes());
            data.push(0);
            data.extend_from_slice(&file.directory_index.to_le_bytes());
            data.extend_from_slice(&file.mod_time.to_le_bytes());
            data.extend_from_slice(&file.length.to_le_bytes());
        }
        data.push(0); // null terminator

        // Line number program
        let program_start = data.len();

        // Emit line entries as DW_LNS statements
        let mut prev_address: u64 = 0;
        let mut prev_file: u32 = 1;
        let mut prev_line: u32 = 1;
        let mut prev_column: u32 = 0;

        for entry in &self.entries {
            if entry.end_sequence {
                // Set address
                data.push(0); // DW_LNE_set_address
                data.extend_from_slice(&entry.address.to_le_bytes());
                // End sequence
                data.push(0);
                data.push(1);
                data.push(1); // length of LNE
                              // Reset state machine
                prev_address = 0;
                prev_file = 1;
                prev_line = 1;
                prev_column = 0;
                continue;
            }

            // DW_LNS_set_file if changed
            if entry.file != prev_file {
                data.push(4); // DW_LNS_set_file
                data.extend_from_slice(&entry.file.to_le_bytes());
                prev_file = entry.file;
            }

            // DW_LNS_set_column if changed
            if entry.column != prev_column {
                data.push(5); // DW_LNS_set_column
                data.extend_from_slice(&entry.column.to_le_bytes());
                prev_column = entry.column;
            }

            // Advance PC
            if entry.address != prev_address {
                let delta = entry.address - prev_address;
                data.push(2); // DW_LNS_advance_pc
                              // Simple uleb128
                let mut val = delta;
                loop {
                    let mut byte = (val & 0x7f) as u8;
                    val >>= 7;
                    if val != 0 {
                        byte |= 0x80;
                    }
                    data.push(byte);
                    if val == 0 {
                        break;
                    }
                }
                prev_address = entry.address;
            }

            // Advance line
            if entry.line != prev_line {
                let delta = entry.line as i32 - prev_line as i32;
                data.push(3); // DW_LNS_advance_line
                              // Simple sleb128
                let mut val = delta as i64;
                loop {
                    let mut byte = (val & 0x7f) as u8;
                    val >>= 7;
                    if (val == 0 && byte & 0x40 == 0) || (val == -1 && byte & 0x40 != 0) {
                        data.push(byte);
                        break;
                    } else {
                        byte |= 0x80;
                    }
                    data.push(byte);
                }
                prev_line = entry.line;
            }

            // Emit DW_LNS_copy (opcode 1)
            data.push(1);
        }

        // Update header length
        let header_size = (program_start - header_length_offset - 4) as u32;
        let header_bytes = header_size.to_le_bytes();
        for (i, b) in header_bytes.iter().enumerate() {
            data[header_length_offset + i] = *b;
        }

        // Update unit length
        let unit_size = (data.len() - length_offset - 4) as u32;
        let unit_bytes = unit_size.to_le_bytes();
        for (i, b) in unit_bytes.iter().enumerate() {
            data[length_offset + i] = *b;
        }

        data
    }

    /// Number of source files.
    pub fn file_count(&self) -> usize {
        self.files.len()
    }

    /// Number of line entries.
    pub fn entry_count(&self) -> usize {
        self.entries.len()
    }

    /// Whether the table is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

impl Default for X86DebugLineTable {
    fn default() -> Self {
        Self::new_x86_64()
    }
}

// ============================================================================
// Debug Info Entities: Compile Units, Subprograms, Variables, Types
// ============================================================================

/// A DIE (Debugging Information Entry) attribute.
#[derive(Debug, Clone)]
pub struct X86DebugAttribute {
    pub name: u16,
    pub form: u16,
    pub value: X86DebugAttrValue,
}

/// The value of a DIE attribute.
#[derive(Debug, Clone)]
pub enum X86DebugAttrValue {
    String(String),
    Data1(u8),
    Data2(u16),
    Data4(u32),
    Data8(u64),
    Flag(bool),
    Ref(u32),         // reference to another DIE
    ExprLoc(Vec<u8>), // location expression
    Block(Vec<u8>),   // general block
    UData(u64),
    SData(i64),
    SecOffset(u32),
}

/// A DIE (Debugging Information Entry).
#[derive(Debug, Clone)]
pub struct X86DebugDIE {
    pub tag: u16,
    pub attributes: Vec<X86DebugAttribute>,
    pub children: Vec<X86DebugDIE>,
}

impl X86DebugDIE {
    pub fn new(tag: u16) -> Self {
        Self {
            tag,
            attributes: Vec::new(),
            children: Vec::new(),
        }
    }

    pub fn add_attr_string(&mut self, name: u16, value: &str) {
        self.attributes.push(X86DebugAttribute {
            name,
            form: dwarf_form::DW_FORM_string,
            value: X86DebugAttrValue::String(value.to_string()),
        });
    }

    pub fn add_attr_data4(&mut self, name: u16, value: u32) {
        self.attributes.push(X86DebugAttribute {
            name,
            form: dwarf_form::DW_FORM_data4,
            value: X86DebugAttrValue::Data4(value),
        });
    }

    pub fn add_attr_data8(&mut self, name: u16, value: u64) {
        self.attributes.push(X86DebugAttribute {
            name,
            form: dwarf_form::DW_FORM_data8,
            value: X86DebugAttrValue::Data8(value),
        });
    }

    pub fn add_attr_addr(&mut self, name: u16, value: u64) {
        self.attributes.push(X86DebugAttribute {
            name,
            form: dwarf_form::DW_FORM_addr,
            value: X86DebugAttrValue::Data8(value),
        });
    }

    pub fn add_attr_flag(&mut self, name: u16, value: bool) {
        self.attributes.push(X86DebugAttribute {
            name,
            form: dwarf_form::DW_FORM_flag,
            value: X86DebugAttrValue::Flag(value),
        });
    }

    pub fn add_attr_ref(&mut self, name: u16, die_offset: u32) {
        self.attributes.push(X86DebugAttribute {
            name,
            form: dwarf_form::DW_FORM_ref4,
            value: X86DebugAttrValue::Ref(die_offset),
        });
    }

    pub fn add_attr_exprloc(&mut self, name: u16, expr: &X86DebugLocationExpr) {
        self.attributes.push(X86DebugAttribute {
            name,
            form: dwarf_form::DW_FORM_exprloc,
            value: X86DebugAttrValue::ExprLoc(expr.bytes.clone()),
        });
    }

    pub fn add_attr_udata(&mut self, name: u16, value: u64) {
        self.attributes.push(X86DebugAttribute {
            name,
            form: dwarf_form::DW_FORM_udata,
            value: X86DebugAttrValue::UData(value),
        });
    }

    pub fn add_attr_sdata(&mut self, name: u16, value: i64) {
        self.attributes.push(X86DebugAttribute {
            name,
            form: dwarf_form::DW_FORM_sdata,
            value: X86DebugAttrValue::SData(value),
        });
    }

    pub fn add_attr_sec_offset(&mut self, name: u16, value: u32) {
        self.attributes.push(X86DebugAttribute {
            name,
            form: dwarf_form::DW_FORM_sec_offset,
            value: X86DebugAttrValue::SecOffset(value),
        });
    }

    pub fn add_child(&mut self, child: X86DebugDIE) {
        self.children.push(child);
    }
}

// ---- Compile Unit ----

/// A DWARF compile unit.
#[derive(Debug, Clone)]
pub struct X86DebugCompileUnit {
    /// Compilation directory.
    pub comp_dir: String,
    /// Source file name.
    pub file_name: String,
    /// Producer string (e.g., compiler name).
    pub producer: String,
    /// Source language.
    pub language: u16,
    /// Address size.
    pub address_size: u8,
    /// DWARF version.
    pub dwarf_version: u16,
    /// The line table for this unit.
    pub line_table: X86DebugLineTable,
    /// Subprograms defined in this unit.
    pub subprograms: Vec<X86DebugSubprogram>,
    /// Global variables.
    pub global_variables: Vec<X86DebugVariable>,
    /// Section offset of this unit within .debug_info.
    pub section_offset: u64,
    /// Low PC of this unit.
    pub low_pc: u64,
    /// High PC of this unit.
    pub high_pc: u64,
    /// Whether to use DWARF 5 line table format.
    pub use_dwarf5_line: bool,
}

impl X86DebugCompileUnit {
    pub fn new_x86_64(file: &str, comp_dir: &str, producer: &str) -> Self {
        Self {
            comp_dir: comp_dir.to_string(),
            file_name: file.to_string(),
            producer: producer.to_string(),
            language: dwarf_lang::DW_LANG_C_plus_plus_17,
            address_size: 8,
            dwarf_version: 4,
            line_table: X86DebugLineTable::new_x86_64(),
            subprograms: Vec::new(),
            global_variables: Vec::new(),
            section_offset: 0,
            low_pc: 0,
            high_pc: 0,
            use_dwarf5_line: false,
        }
    }

    pub fn new_x86_32(file: &str, comp_dir: &str, producer: &str) -> Self {
        let mut cu = Self::new_x86_64(file, comp_dir, producer);
        cu.address_size = 4;
        cu.line_table = X86DebugLineTable::new_x86_32();
        cu
    }

    /// Set the language.
    pub fn set_language(&mut self, lang: u16) {
        self.language = lang;
    }

    /// Add a subprogram.
    pub fn add_subprogram(&mut self, sp: X86DebugSubprogram) {
        self.subprograms.push(sp);
    }

    /// Add a global variable.
    pub fn add_global_variable(&mut self, var: X86DebugVariable) {
        self.global_variables.push(var);
    }

    /// Set PC bounds.
    pub fn set_pc_range(&mut self, low_pc: u64, high_pc: u64) {
        self.low_pc = low_pc;
        self.high_pc = high_pc;
    }

    /// Build the top-level compile unit DIE.
    pub fn build_die(&self) -> X86DebugDIE {
        let mut cu_die = X86DebugDIE::new(dwarf_tag::DW_TAG_compile_unit);
        cu_die.add_attr_string(dwarf_attr::DW_AT_name, &self.file_name);
        cu_die.add_attr_string(dwarf_attr::DW_AT_comp_dir, &self.comp_dir);
        cu_die.add_attr_string(dwarf_attr::DW_AT_producer, &self.producer);
        cu_die.add_attr_data4(dwarf_attr::DW_AT_language, self.language as u32);
        cu_die.add_attr_addr(dwarf_attr::DW_AT_low_pc, self.low_pc);
        // High PC as offset from low_pc in DWARF4
        cu_die.add_attr_data8(dwarf_attr::DW_AT_high_pc, self.high_pc - self.low_pc);
        cu_die.add_attr_sec_offset(dwarf_attr::DW_AT_stmt_list, 0); // placeholder
        cu_die
    }

    /// Number of subprograms.
    pub fn subprogram_count(&self) -> usize {
        self.subprograms.len()
    }

    /// Number of global variables.
    pub fn global_var_count(&self) -> usize {
        self.global_variables.len()
    }
}

// ---- Subprogram ----

/// A DWARF subprogram (function).
#[derive(Debug, Clone)]
pub struct X86DebugSubprogram {
    /// Function name.
    pub name: String,
    /// Mangled / linkage name.
    pub linkage_name: Option<String>,
    /// Low PC (start of function).
    pub low_pc: u64,
    /// High PC (end of function, exclusive).
    pub high_pc: u64,
    /// Frame base location expression.
    pub frame_base: Option<X86DebugLocationExpr>,
    /// Return type DIE offset.
    pub return_type: Option<u32>,
    /// Formal parameters.
    pub parameters: Vec<X86DebugVariable>,
    /// Local variables.
    pub variables: Vec<X86DebugVariable>,
    /// Lexical blocks.
    pub lexical_blocks: Vec<X86DebugLexicalBlock>,
    /// Inlined subroutines within this function.
    pub inlined_subroutines: Vec<X86DebugInlinedSubroutine>,
    /// Whether the function has external linkage.
    pub is_external: bool,
    /// Inline code.
    pub inline_code: u16,
    /// Declaration file index.
    pub decl_file: u32,
    /// Declaration line.
    pub decl_line: u32,
    /// Declaration column.
    pub decl_column: u32,
    /// Whether this is an artificial subprogram.
    pub is_artificial: bool,
    /// Whether this is a declaration only (not definition).
    pub is_declaration: bool,
    /// Abstract origin DIE offset (for inlined instances).
    pub abstract_origin: Option<u32>,
}

impl X86DebugSubprogram {
    pub fn new(name: &str, low_pc: u64, high_pc: u64) -> Self {
        Self {
            name: name.to_string(),
            linkage_name: None,
            low_pc,
            high_pc,
            frame_base: None,
            return_type: None,
            parameters: Vec::new(),
            variables: Vec::new(),
            lexical_blocks: Vec::new(),
            inlined_subroutines: Vec::new(),
            is_external: false,
            inline_code: dwarf_inline::DW_INL_not_inlined,
            decl_file: 1,
            decl_line: 1,
            decl_column: 0,
            is_artificial: false,
            is_declaration: false,
            abstract_origin: None,
        }
    }

    /// Set the frame base expression.
    pub fn set_frame_base(&mut self, expr: X86DebugLocationExpr) {
        self.frame_base = Some(expr);
    }

    /// Set return type DIE offset.
    pub fn set_return_type(&mut self, offset: u32) {
        self.return_type = Some(offset);
    }

    /// Set linkage name.
    pub fn set_linkage_name(&mut self, name: &str) {
        self.linkage_name = Some(name.to_string());
    }

    /// Add a formal parameter.
    pub fn add_parameter(&mut self, param: X86DebugVariable) {
        self.parameters.push(param);
    }

    /// Add a local variable.
    pub fn add_variable(&mut self, var: X86DebugVariable) {
        self.variables.push(var);
    }

    /// Add a lexical block.
    pub fn add_lexical_block(&mut self, block: X86DebugLexicalBlock) {
        self.lexical_blocks.push(block);
    }

    /// Add an inlined subroutine.
    pub fn add_inlined_subroutine(&mut self, inline: X86DebugInlinedSubroutine) {
        self.inlined_subroutines.push(inline);
    }

    /// Set as an inlined instance.
    pub fn set_inlined(&mut self, code: u16) {
        self.inline_code = code;
    }

    /// Set abstract origin.
    pub fn set_abstract_origin(&mut self, offset: u32) {
        self.abstract_origin = Some(offset);
    }

    /// Compute x86-64 default frame base (DW_OP_call_frame_cfa).
    pub fn compute_x86_64_frame_base(&mut self) {
        let mut fb = X86DebugLocationExpr::new_x86_64();
        fb.call_frame_cfa();
        self.frame_base = Some(fb);
    }

    /// Compute x86-32 default frame base.
    pub fn compute_x86_32_frame_base(&mut self) {
        let mut fb = X86DebugLocationExpr::new_x86_32();
        fb.call_frame_cfa();
        self.frame_base = Some(fb);
    }

    /// Build a DIE for this subprogram.
    pub fn build_die(&self) -> X86DebugDIE {
        let mut die = X86DebugDIE::new(dwarf_tag::DW_TAG_subprogram);
        die.add_attr_string(dwarf_attr::DW_AT_name, &self.name);
        die.add_attr_addr(dwarf_attr::DW_AT_low_pc, self.low_pc);
        die.add_attr_data8(dwarf_attr::DW_AT_high_pc, self.high_pc - self.low_pc);
        if let Some(ref ln) = self.linkage_name {
            die.add_attr_string(dwarf_attr::DW_AT_linkage_name, ln);
        }
        if self.is_external {
            die.add_attr_flag(dwarf_attr::DW_AT_external, true);
        }
        if let Some(ref fb) = self.frame_base {
            die.add_attr_exprloc(dwarf_attr::DW_AT_frame_base, fb);
        }
        if let Some(ret) = self.return_type {
            die.add_attr_ref(dwarf_attr::DW_AT_type, ret);
        }
        die
    }
}

// ---- Variable ----

/// A DWARF variable (local, parameter, or global).
#[derive(Debug, Clone)]
pub struct X86DebugVariable {
    /// Variable name.
    pub name: String,
    /// DIE tag (DW_TAG_variable or DW_TAG_formal_parameter).
    pub tag: u16,
    /// Type name (for reference).
    pub type_name: Option<String>,
    /// Type DIE offset.
    pub type_offset: Option<u32>,
    /// Location expression.
    pub location: Option<X86DebugLocationExpr>,
    /// Declaration file.
    pub decl_file: u32,
    /// Declaration line.
    pub decl_line: u32,
    /// Declaration column.
    pub decl_column: u32,
    /// Whether external linkage.
    pub is_external: bool,
    /// Whether artificial.
    pub is_artificial: bool,
}

impl X86DebugVariable {
    pub fn new(name: &str, tag: u16) -> Self {
        Self {
            name: name.to_string(),
            tag,
            type_name: None,
            type_offset: None,
            location: None,
            decl_file: 1,
            decl_line: 0,
            decl_column: 0,
            is_external: false,
            is_artificial: false,
        }
    }

    /// Create a new formal parameter.
    pub fn new_parameter(name: &str) -> Self {
        Self::new(name, dwarf_tag::DW_TAG_formal_parameter)
    }

    /// Create a new local variable.
    pub fn new_local(name: &str) -> Self {
        Self::new(name, dwarf_tag::DW_TAG_variable)
    }

    /// Set the type.
    pub fn set_type(&mut self, type_name: &str, type_offset: u32) {
        self.type_name = Some(type_name.to_string());
        self.type_offset = Some(type_offset);
    }

    /// Set the location expression.
    pub fn set_location(&mut self, loc: X86DebugLocationExpr) {
        self.location = Some(loc);
    }

    /// Build a DIE for this variable.
    pub fn build_die(&self) -> X86DebugDIE {
        let mut die = X86DebugDIE::new(self.tag);
        die.add_attr_string(dwarf_attr::DW_AT_name, &self.name);
        if let Some(off) = self.type_offset {
            die.add_attr_ref(dwarf_attr::DW_AT_type, off);
        }
        if let Some(ref loc) = self.location {
            die.add_attr_exprloc(dwarf_attr::DW_AT_location, loc);
        }
        if self.decl_file > 0 {
            die.add_attr_data4(dwarf_attr::DW_AT_decl_file, self.decl_file);
        }
        if self.decl_line > 0 {
            die.add_attr_data4(dwarf_attr::DW_AT_decl_line, self.decl_line);
        }
        if self.is_artificial {
            die.add_attr_flag(dwarf_attr::DW_AT_artificial, true);
        }
        die
    }
}

// ---- Lexical Block ----

/// A DWARF lexical block (scope).
#[derive(Debug, Clone)]
pub struct X86DebugLexicalBlock {
    /// Low PC of the block.
    pub low_pc: u64,
    /// High PC of the block (exclusive).
    pub high_pc: u64,
    /// Variables local to this block.
    pub variables: Vec<X86DebugVariable>,
    /// Nested lexical blocks.
    pub nested_blocks: Vec<X86DebugLexicalBlock>,
}

impl X86DebugLexicalBlock {
    pub fn new(low_pc: u64, high_pc: u64) -> Self {
        Self {
            low_pc,
            high_pc,
            variables: Vec::new(),
            nested_blocks: Vec::new(),
        }
    }

    /// Add a variable to this block.
    pub fn add_variable(&mut self, var: X86DebugVariable) {
        self.variables.push(var);
    }

    /// Build a DIE for this lexical block.
    pub fn build_die(&self) -> X86DebugDIE {
        let mut die = X86DebugDIE::new(dwarf_tag::DW_TAG_lexical_block);
        die.add_attr_addr(dwarf_attr::DW_AT_low_pc, self.low_pc);
        die.add_attr_data8(dwarf_attr::DW_AT_high_pc, self.high_pc - self.low_pc);
        for var in &self.variables {
            die.add_child(var.build_die());
        }
        die
    }
}

// ---- Inlined Subroutine ----

/// A DWARF inlined subroutine.
#[derive(Debug, Clone)]
pub struct X86DebugInlinedSubroutine {
    /// Abstract origin DIE offset (the concrete out-of-line subprogram).
    pub abstract_origin: u32,
    /// Low PC of the inlined instance.
    pub low_pc: u64,
    /// High PC of the inlined instance (exclusive).
    pub high_pc: u64,
    /// Call file.
    pub call_file: u32,
    /// Call line.
    pub call_line: u32,
    /// Call column.
    pub call_column: u32,
    /// Variables specific to this inlined instance.
    pub variables: Vec<X86DebugVariable>,
    /// Lexical blocks within the inlined instance.
    pub lexical_blocks: Vec<X86DebugLexicalBlock>,
}

impl X86DebugInlinedSubroutine {
    pub fn new(abstract_origin: u32, low_pc: u64, high_pc: u64) -> Self {
        Self {
            abstract_origin,
            low_pc,
            high_pc,
            call_file: 1,
            call_line: 0,
            call_column: 0,
            variables: Vec::new(),
            lexical_blocks: Vec::new(),
        }
    }

    /// Set the call site.
    pub fn set_call_site(&mut self, file: u32, line: u32, column: u32) {
        self.call_file = file;
        self.call_line = line;
        self.call_column = column;
    }

    /// Build a DIE for this inlined subroutine.
    pub fn build_die(&self) -> X86DebugDIE {
        let mut die = X86DebugDIE::new(dwarf_tag::DW_TAG_inlined_subroutine);
        die.add_attr_ref(dwarf_attr::DW_AT_abstract_origin, self.abstract_origin);
        die.add_attr_addr(dwarf_attr::DW_AT_low_pc, self.low_pc);
        die.add_attr_data8(dwarf_attr::DW_AT_high_pc, self.high_pc - self.low_pc);
        die.add_attr_data4(dwarf_attr::DW_AT_call_file, self.call_file);
        die.add_attr_data4(dwarf_attr::DW_AT_call_line, self.call_line);
        for var in &self.variables {
            die.add_child(var.build_die());
        }
        for block in &self.lexical_blocks {
            die.add_child(block.build_die());
        }
        die
    }
}

// ============================================================================
// Variable Location Tracking (DBG_VALUE)
// ============================================================================

/// A DBG_VALUE instruction recording where a variable lives.
#[derive(Debug, Clone)]
pub struct X86DbgValue {
    /// The variable being tracked.
    pub variable_name: String,
    /// The location expression.
    pub location: X86DebugLocationExpr,
    /// Instruction index this DBG_VALUE annotates.
    pub instruction_index: u32,
    /// Whether this DBG_VALUE is undefined (variable optimized away).
    pub is_undef: bool,
}

impl X86DbgValue {
    pub fn new(var_name: &str, location: X86DebugLocationExpr, inst_idx: u32) -> Self {
        Self {
            variable_name: var_name.to_string(),
            location,
            instruction_index: inst_idx,
            is_undef: false,
        }
    }

    /// Create an undefined DBG_VALUE (variable optimized away).
    pub fn undef(var_name: &str, inst_idx: u32) -> Self {
        Self {
            variable_name: var_name.to_string(),
            location: X86DebugLocationExpr::default(),
            instruction_index: inst_idx,
            is_undef: true,
        }
    }
}

/// A location range for a variable (start and end instruction indices).
#[derive(Debug, Clone)]
pub struct X86DebugLocRange {
    pub start_inst: u32,
    pub end_inst: u32,
    pub location: X86DebugLocationExpr,
}

/// Tracks variable locations across a function's instructions.
#[derive(Debug, Clone)]
pub struct X86DebugVarLocTracker {
    /// Name of the function being tracked.
    pub function_name: String,
    /// Per-variable location ranges.
    pub var_ranges: HashMap<String, Vec<X86DebugLocRange>>,
    /// DBG_VALUE instructions emitted.
    pub dbg_values: Vec<X86DbgValue>,
}

impl X86DebugVarLocTracker {
    pub fn new(func_name: &str) -> Self {
        Self {
            function_name: func_name.to_string(),
            var_ranges: HashMap::new(),
            dbg_values: Vec::new(),
        }
    }

    /// Record a DBG_VALUE for a variable at an instruction.
    pub fn record_dbg_value(&mut self, dbg: X86DbgValue) {
        self.dbg_values.push(dbg.clone());
        let ranges = self
            .var_ranges
            .entry(dbg.variable_name.clone())
            .or_insert_with(Vec::new);
        if let Some(last) = ranges.last_mut() {
            last.end_inst = dbg.instruction_index;
        }
        ranges.push(X86DebugLocRange {
            start_inst: dbg.instruction_index,
            end_inst: dbg.instruction_index + 1,
            location: dbg.location,
        });
    }

    /// Register a variable being in a register for an instruction range.
    pub fn register_in_reg(
        &mut self,
        var_name: &str,
        reg_name: &str,
        start_inst: u32,
        end_inst: u32,
        is_64bit: bool,
    ) {
        let mut loc = if is_64bit {
            X86DebugLocationExpr::new_x86_64()
        } else {
            X86DebugLocationExpr::new_x86_32()
        };
        loc.param_in_register(reg_name);
        let ranges = self
            .var_ranges
            .entry(var_name.to_string())
            .or_insert_with(Vec::new);
        ranges.push(X86DebugLocRange {
            start_inst,
            end_inst,
            location: loc,
        });
    }

    /// Register a variable being on the stack for an instruction range.
    pub fn register_on_stack(
        &mut self,
        var_name: &str,
        frame_offset: i32,
        start_inst: u32,
        end_inst: u32,
        is_64bit: bool,
    ) {
        let mut loc = if is_64bit {
            X86DebugLocationExpr::new_x86_64()
        } else {
            X86DebugLocationExpr::new_x86_32()
        };
        loc.local_var_below_rbp(frame_offset as i64, is_64bit);
        let ranges = self
            .var_ranges
            .entry(var_name.to_string())
            .or_insert_with(Vec::new);
        ranges.push(X86DebugLocRange {
            start_inst,
            end_inst,
            location: loc,
        });
    }

    /// Get all locations for a variable.
    pub fn get_locations(&self, var_name: &str) -> Option<&Vec<X86DebugLocRange>> {
        self.var_ranges.get(var_name)
    }

    /// Get all tracked variable names.
    pub fn tracked_variables(&self) -> Vec<String> {
        self.var_ranges.keys().cloned().collect()
    }

    /// Number of DBG_VALUEs emitted.
    pub fn dbg_value_count(&self) -> usize {
        self.dbg_values.len()
    }
}

impl Default for X86DebugVarLocTracker {
    fn default() -> Self {
        Self::new("unknown")
    }
}

// ============================================================================
// CodeView Debug Info (Windows)
// ============================================================================

/// A CodeView type record kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86CVLeafType {
    LF_POINTER = 0x1002,
    LF_MODIFIER = 0x1001,
    LF_PROCEDURE = 0x1008,
    LF_MFUNCTION = 0x1009,
    LF_ARGLIST = 0x1201,
    LF_FIELDLIST = 0x1203,
    LF_STRUCTURE = 0x1505,
    LF_UNION = 0x1506,
    LF_ENUM = 0x1507,
    LF_ARRAY = 0x1508,
    LF_CLASS = 0x1509,
    LF_MEMBER = 0x150d,
    LF_STMEMBER = 0x150e,
    LF_METHOD = 0x150f,
    LF_NESTTYPE = 0x1510,
    LF_ONEMETHOD = 0x1511,
    LF_ENUMERATE = 0x1502,
    LF_BITFIELD = 0x1205,
    LF_METHODLIST = 0x1206,
}

/// A CodeView type record.
#[derive(Debug, Clone)]
pub struct X86CVTypeRecord {
    pub leaf: u16,
    pub data: Vec<u8>,
}

/// A CodeView symbol record kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum X86CVSymbolKind {
    S_COMPILE3 = 0x113c,
    S_OBJNAME = 0x1101,
    S_GPROC32 = 0x1110,
    S_GPROC32_ID = 0x1146,
    S_LPROC32 = 0x110f,
    S_LPROC32_ID = 0x1147,
    S_END = 0x0006,
    S_BLOCK32 = 0x1103,
    S_LABEL32 = 0x1105,
    S_REGREL32 = 0x1111,
    S_CONSTANT = 0x1107,
    S_UDT = 0x1108,
    S_LDATA32 = 0x110c,
    S_GDATA32 = 0x110d,
    S_PUB32 = 0x110e,
    S_LTHREAD32 = 0x1112,
    S_GTHREAD32 = 0x1113,
    S_FRAMEPROC = 0x1012,
    S_FRAMECOOKIE = 0x1135,
    S_CALLSITEINFO = 0x1139,
    S_HEAPALLOCSITE = 0x1140,
    S_INLINESITE = 0x114d,
    S_INLINESITE_END = 0x114e,
    S_DEFRANGE_REGISTER = 0x1141,
    S_DEFRANGE_FRAMEPOINTER_REL = 0x1142,
}

/// A CodeView symbol record.
#[derive(Debug, Clone)]
pub struct X86CVSymbolRecord {
    pub kind: u16,
    pub data: Vec<u8>,
}

/// A CodeView line number entry.
#[derive(Debug, Clone)]
pub struct X86CVLineEntry {
    pub offset: u32,     // offset from function start
    pub line_start: u32, // line number
}

/// A CodeView line table for a section.
#[derive(Debug, Clone)]
pub struct X86CVLineTable {
    pub section_index: u32,
    pub entries: Vec<X86CVLineEntry>,
    pub file_checksums: Vec<(String, Vec<u8>)>,
    pub source_files: Vec<String>,
}

impl X86CVLineTable {
    pub fn new(section_index: u32) -> Self {
        Self {
            section_index,
            entries: Vec::new(),
            file_checksums: Vec::new(),
            source_files: Vec::new(),
        }
    }

    /// Add a line entry.
    pub fn add_line(&mut self, offset: u32, line: u32) {
        self.entries.push(X86CVLineEntry {
            offset,
            line_start: line,
        });
    }

    /// Add a source file.
    pub fn add_source_file(&mut self, path: &str) {
        if !self.source_files.iter().any(|f| f == path) {
            self.source_files.push(path.to_string());
        }
    }

    /// Number of line entries.
    pub fn entry_count(&self) -> usize {
        self.entries.len()
    }

    /// Whether the line table is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

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

// ============================================================================
// X86DebugCodeGen — Top-level Orchestrator
// ============================================================================

/// The top-level X86 debug info codegen orchestrator.
///
/// Manages DWARF debug info generation from IR: compile units,
/// subprograms, variables, types, lexical blocks, inlined subroutines,
/// location expressions, variable location tracking (DBG_VALUE),
/// line tables, and CodeView debug info for Windows.
#[derive(Debug, Clone)]
pub struct X86DebugCodeGen {
    /// All compile units being generated.
    pub compile_units: Vec<X86DebugCompileUnit>,
    /// Current compile unit index.
    pub current_cu: usize,
    /// Per-function variable location trackers.
    pub var_loc_trackers: HashMap<String, X86DebugVarLocTracker>,
    /// CodeView type records.
    pub cv_type_records: Vec<X86CVTypeRecord>,
    /// CodeView symbol records.
    pub cv_symbol_records: Vec<X86CVSymbolRecord>,
    /// CodeView line tables.
    pub cv_line_tables: Vec<X86CVLineTable>,
    /// Target triple.
    pub target_triple: String,
    /// Whether generating 64-bit code.
    pub is_64bit: bool,
    /// Whether generating CodeView (Windows) debug info.
    pub use_codeview: bool,
    /// Statistics.
    pub stats: X86DebugCodeGenStats,
}

/// Codegen statistics.
#[derive(Debug, Clone, Default)]
pub struct X86DebugCodeGenStats {
    pub compile_units: u64,
    pub subprograms: u64,
    pub variables: u64,
    pub line_entries: u64,
    pub dbg_values: u64,
    pub lexical_blocks: u64,
    pub inlined_subroutines: u64,
    pub cv_types: u64,
    pub cv_symbols: u64,
}

impl X86DebugCodeGen {
    /// Create a new debug codegen instance for x86-64.
    pub fn new_x86_64() -> Self {
        Self {
            compile_units: Vec::new(),
            current_cu: 0,
            var_loc_trackers: HashMap::new(),
            cv_type_records: Vec::new(),
            cv_symbol_records: Vec::new(),
            cv_line_tables: Vec::new(),
            target_triple: "x86_64-unknown-linux-gnu".to_string(),
            is_64bit: true,
            use_codeview: false,
            stats: X86DebugCodeGenStats::default(),
        }
    }

    /// Create a new debug codegen instance for x86-32.
    pub fn new_x86_32() -> Self {
        Self {
            target_triple: "i386-unknown-linux-gnu".to_string(),
            is_64bit: false,
            ..Self::new_x86_64()
        }
    }

    /// Configure for Windows/MSVC target (CodeView).
    pub fn as_windows(&mut self) {
        self.target_triple = "x86_64-pc-windows-msvc".to_string();
        self.use_codeview = true;
    }

    // ---- Compile Unit Management ----

    /// Create a new compile unit and make it current.
    pub fn create_compile_unit(
        &mut self,
        file: &str,
        comp_dir: &str,
        producer: &str,
    ) -> &mut X86DebugCompileUnit {
        let cu = if self.is_64bit {
            X86DebugCompileUnit::new_x86_64(file, comp_dir, producer)
        } else {
            X86DebugCompileUnit::new_x86_32(file, comp_dir, producer)
        };
        self.compile_units.push(cu);
        self.current_cu = self.compile_units.len() - 1;
        self.stats.compile_units += 1;
        &mut self.compile_units[self.current_cu]
    }

    /// Get the current compile unit.
    pub fn current_compile_unit(&self) -> Option<&X86DebugCompileUnit> {
        self.compile_units.get(self.current_cu)
    }

    /// Get a mutable reference to the current compile unit.
    pub fn current_compile_unit_mut(&mut self) -> Option<&mut X86DebugCompileUnit> {
        self.compile_units.get_mut(self.current_cu)
    }

    // ---- Subprogram Management ----

    /// Add a subprogram to the current compile unit.
    pub fn add_subprogram(&mut self, name: &str, low_pc: u64, high_pc: u64) {
        let mut sp = X86DebugSubprogram::new(name, low_pc, high_pc);
        if self.is_64bit {
            sp.compute_x86_64_frame_base();
        } else {
            sp.compute_x86_32_frame_base();
        }
        sp.is_external = true;
        if let Some(cu) = self.current_compile_unit_mut() {
            cu.add_subprogram(sp);
            self.stats.subprograms += 1;
        }
    }

    /// Add a local variable to the most recently added subprogram.
    pub fn add_local_variable(
        &mut self,
        var_name: &str,
        frame_offset: i32,
        type_name: &str,
        _type_offset: u32,
    ) {
        let mut var = X86DebugVariable::new_local(var_name);
        var.set_type(type_name, _type_offset);
        let mut loc = if self.is_64bit {
            X86DebugLocationExpr::new_x86_64()
        } else {
            X86DebugLocationExpr::new_x86_32()
        };
        loc.local_var_below_rbp(frame_offset as i64, self.is_64bit);
        var.set_location(loc);

        if let Some(cu) = self.current_compile_unit_mut() {
            if let Some(sp) = cu.subprograms.last_mut() {
                sp.add_variable(var);
                self.stats.variables += 1;
            }
        }
    }

    /// Add a parameter to the most recently added subprogram.
    pub fn add_parameter(
        &mut self,
        param_name: &str,
        reg_name: &str,
        type_name: &str,
        type_offset: u32,
    ) {
        let mut var = X86DebugVariable::new_parameter(param_name);
        var.set_type(type_name, type_offset);
        let mut loc = if self.is_64bit {
            X86DebugLocationExpr::new_x86_64()
        } else {
            X86DebugLocationExpr::new_x86_32()
        };
        loc.param_in_register(reg_name);
        var.set_location(loc);

        if let Some(cu) = self.current_compile_unit_mut() {
            if let Some(sp) = cu.subprograms.last_mut() {
                sp.add_parameter(var);
            }
        }
    }

    // ---- Variable Location Tracking ----

    /// Begin tracking variable locations for a function.
    pub fn begin_function(&mut self, func_name: &str) {
        self.var_loc_trackers
            .insert(func_name.to_string(), X86DebugVarLocTracker::new(func_name));
    }

    /// Record a DBG_VALUE for a variable.
    pub fn record_dbg_value(
        &mut self,
        func_name: &str,
        var_name: &str,
        location: X86DebugLocationExpr,
        inst_idx: u32,
    ) {
        if let Some(tracker) = self.var_loc_trackers.get_mut(func_name) {
            tracker.record_dbg_value(X86DbgValue::new(var_name, location, inst_idx));
            self.stats.dbg_values += 1;
        }
    }

    /// Record a variable being in a register.
    pub fn track_var_in_reg(
        &mut self,
        func_name: &str,
        var_name: &str,
        reg_name: &str,
        start_inst: u32,
        end_inst: u32,
    ) {
        if let Some(tracker) = self.var_loc_trackers.get_mut(func_name) {
            tracker.register_in_reg(var_name, reg_name, start_inst, end_inst, self.is_64bit);
        }
    }

    /// Record a variable being on the stack.
    pub fn track_var_on_stack(
        &mut self,
        func_name: &str,
        var_name: &str,
        frame_offset: i32,
        start_inst: u32,
        end_inst: u32,
    ) {
        if let Some(tracker) = self.var_loc_trackers.get_mut(func_name) {
            tracker.register_on_stack(var_name, frame_offset, start_inst, end_inst, self.is_64bit);
        }
    }

    /// Finish tracking for a function.
    pub fn end_function(&mut self, func_name: &str) -> Option<X86DebugVarLocTracker> {
        self.var_loc_trackers.remove(func_name)
    }

    // ---- Line Table ----

    /// Add a source line entry to the current compile unit's line table.
    pub fn add_line_entry(&mut self, line: u32, column: u32, file: u32, address: u64) {
        if let Some(cu) = self.current_compile_unit_mut() {
            cu.line_table.add_line(line, column, file, address);
            self.stats.line_entries += 1;
        }
    }

    /// Add a line table file to the current compile unit.
    pub fn add_line_file(&mut self, name: &str, dir_index: u32) -> u32 {
        if let Some(cu) = self.current_compile_unit_mut() {
            cu.line_table.add_file(name, dir_index)
        } else {
            0
        }
    }

    /// Add a line table directory to the current compile unit.
    pub fn add_line_directory(&mut self, path: &str) -> u32 {
        if let Some(cu) = self.current_compile_unit_mut() {
            cu.line_table.add_directory(path)
        } else {
            0
        }
    }

    // ---- Lexical Blocks ----

    /// Add a lexical block to the last subprogram.
    pub fn add_lexical_block(&mut self, low_pc: u64, high_pc: u64) {
        let block = X86DebugLexicalBlock::new(low_pc, high_pc);
        if let Some(cu) = self.current_compile_unit_mut() {
            if let Some(sp) = cu.subprograms.last_mut() {
                sp.add_lexical_block(block);
                self.stats.lexical_blocks += 1;
            }
        }
    }

    // ---- Inlined Subroutines ----

    /// Add an inlined subroutine to the last subprogram.
    pub fn add_inlined_subroutine(
        &mut self,
        abstract_origin: u32,
        low_pc: u64,
        high_pc: u64,
        call_file: u32,
        call_line: u32,
    ) {
        let mut inline = X86DebugInlinedSubroutine::new(abstract_origin, low_pc, high_pc);
        inline.set_call_site(call_file, call_line, 0);
        if let Some(cu) = self.current_compile_unit_mut() {
            if let Some(sp) = cu.subprograms.last_mut() {
                sp.add_inlined_subroutine(inline);
                self.stats.inlined_subroutines += 1;
            }
        }
    }

    // ---- CodeView ----

    /// Add a CodeView type record.
    pub fn cv_add_type_record(&mut self, leaf: u16, data: Vec<u8>) {
        self.cv_type_records.push(X86CVTypeRecord { leaf, data });
        self.stats.cv_types += 1;
    }

    /// Add a CodeView symbol record.
    pub fn cv_add_symbol_record(&mut self, kind: u16, data: Vec<u8>) {
        self.cv_symbol_records
            .push(X86CVSymbolRecord { kind, data });
        self.stats.cv_symbols += 1;
    }

    /// Create a new CodeView line table.
    pub fn cv_create_line_table(&mut self, section_index: u32) -> usize {
        self.cv_line_tables.push(X86CVLineTable::new(section_index));
        self.cv_line_tables.len() - 1
    }

    /// Add a CodeView line entry.
    pub fn cv_add_line_entry(&mut self, table_idx: usize, offset: u32, line: u32) {
        if let Some(table) = self.cv_line_tables.get_mut(table_idx) {
            table.add_line(offset, line);
            self.stats.line_entries += 1;
        }
    }

    // ---- Global Variables ----

    /// Add a global variable to the current compile unit.
    pub fn add_global_variable(
        &mut self,
        name: &str,
        address: u64,
        type_name: &str,
        type_offset: u32,
    ) {
        let mut var = X86DebugVariable::new(name, dwarf_tag::DW_TAG_variable);
        var.is_external = true;
        var.set_type(type_name, type_offset);
        let mut loc = if self.is_64bit {
            X86DebugLocationExpr::new_x86_64()
        } else {
            X86DebugLocationExpr::new_x86_32()
        };
        loc.addr(address);
        var.set_location(loc);

        if let Some(cu) = self.current_compile_unit_mut() {
            cu.add_global_variable(var);
        }
    }

    // ---- Statistics ----

    /// Get codegen statistics.
    pub fn get_stats(&self) -> &X86DebugCodeGenStats {
        &self.stats
    }

    /// Reset all state.
    pub fn reset(&mut self) {
        self.compile_units.clear();
        self.current_cu = 0;
        self.var_loc_trackers.clear();
        self.cv_type_records.clear();
        self.cv_symbol_records.clear();
        self.cv_line_tables.clear();
        self.stats = X86DebugCodeGenStats::default();
    }
}

impl Default for X86DebugCodeGen {
    fn default() -> Self {
        Self::new_x86_64()
    }
}

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

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

    // --- Location Expression Tests ---

    #[test]
    fn test_loc_expr_new_x86_64() {
        let expr = X86DebugLocationExpr::new_x86_64();
        assert_eq!(expr.address_size, 8);
        assert!(expr.is_empty());
    }

    #[test]
    fn test_loc_expr_new_x86_32() {
        let expr = X86DebugLocationExpr::new_x86_32();
        assert_eq!(expr.address_size, 4);
    }

    #[test]
    fn test_loc_expr_addr() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.addr(0x401000);
        assert!(!expr.is_empty());
        assert_eq!(expr.bytes[0], dwarf_op::DW_OP_addr);
    }

    #[test]
    fn test_loc_expr_deref() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.deref();
        assert_eq!(expr.bytes[0], dwarf_op::DW_OP_deref);
    }

    #[test]
    fn test_loc_expr_reg_compact() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.reg(5); // RDI
        assert_eq!(expr.bytes[0], dwarf_op::DW_OP_reg0 + 5);
    }

    #[test]
    fn test_loc_expr_reg_extended() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.reg(50); // needs regx
        assert_eq!(expr.bytes[0], dwarf_op::DW_OP_regx);
    }

    #[test]
    fn test_loc_expr_breg() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.breg(6, -8); // RBP-8
        assert_eq!(expr.bytes[0], dwarf_op::DW_OP_breg0 + 6);
    }

    #[test]
    fn test_loc_expr_fbreg() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.fbreg(-16);
        assert_eq!(expr.bytes[0], dwarf_op::DW_OP_fbreg);
    }

    #[test]
    fn test_loc_expr_piece() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.reg(0).piece(4);
        assert!(expr.as_bytes().contains(&dwarf_op::DW_OP_piece));
    }

    #[test]
    fn test_loc_expr_bit_piece() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.reg(0).bit_piece(32, 0);
        assert!(expr.as_bytes().contains(&dwarf_op::DW_OP_bit_piece));
    }

    #[test]
    fn test_loc_expr_stack_value() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.stack_value();
        assert!(!expr.is_location);
    }

    #[test]
    fn test_loc_expr_implicit_value() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.implicit_value(&[0x42, 0x43]);
        assert!(!expr.is_location);
        assert!(expr.as_bytes().contains(&0x42));
        assert!(expr.as_bytes().contains(&0x43));
    }

    #[test]
    fn test_loc_expr_arithmetic() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.plus();
        assert_eq!(expr.bytes[0], dwarf_op::DW_OP_plus);
        expr.minus();
        expr.mul();
        expr.div();
        expr.and();
        expr.or();
        expr.xor();
        expr.shl();
        expr.shr();
        assert!(!expr.is_empty());
    }

    #[test]
    fn test_loc_expr_comparisons() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.reg(0);
        // Just ensure all arithmetic ops can be appended without panic
        expr.plus_uconst(42);
        expr.dup();
        expr.drop();
        expr.over();
        expr.swap();
        expr.rot();
        expr.pick(2);
        expr.nop();
        assert!(!expr.is_empty());
    }

    #[test]
    fn test_loc_expr_clear() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.addr(0x1000);
        expr.clear();
        assert!(expr.is_empty());
    }

    #[test]
    fn test_loc_expr_rbp_offset() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.rbp_offset_64(-8);
        assert_eq!(expr.bytes[0], dwarf_op::DW_OP_breg0 + 6);
    }

    #[test]
    fn test_loc_expr_in_rax() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.in_rax();
        assert_eq!(expr.bytes[0], dwarf_op::DW_OP_reg0);
    }

    #[test]
    fn test_loc_expr_in_xmm() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.in_xmm(5);
        assert_eq!(expr.bytes[0], dwarf_op::DW_OP_reg0 + 22); // XMM0 = 17, +5 = 22
    }

    // --- Register Mapping Tests ---

    #[test]
    fn test_x86_64_reg_to_dwarf() {
        assert_eq!(x86_64_reg_to_dwarf("rax"), Some(0));
        assert_eq!(x86_64_reg_to_dwarf("rbp"), Some(6));
        assert_eq!(x86_64_reg_to_dwarf("rsp"), Some(7));
        assert_eq!(x86_64_reg_to_dwarf("r15"), Some(15));
        assert_eq!(x86_64_reg_to_dwarf("rip"), Some(16));
        assert_eq!(x86_64_reg_to_dwarf("nonexistent"), None);
    }

    #[test]
    fn test_x86_32_reg_to_dwarf() {
        assert_eq!(x86_32_reg_to_dwarf("eax"), Some(0));
        assert_eq!(x86_32_reg_to_dwarf("ebp"), Some(5));
        assert_eq!(x86_32_reg_to_dwarf("ebx"), Some(3));
        assert_eq!(x86_32_reg_to_dwarf("nonexistent"), None);
    }

    // --- Line Table Tests ---

    #[test]
    fn test_line_table_new_64() {
        let tbl = X86DebugLineTable::new_x86_64();
        assert_eq!(tbl.address_size, 8);
        assert_eq!(tbl.version, 4);
        assert!(tbl.is_empty());
    }

    #[test]
    fn test_line_table_new_32() {
        let tbl = X86DebugLineTable::new_x86_32();
        assert_eq!(tbl.address_size, 4);
    }

    #[test]
    fn test_line_table_add_file() {
        let mut tbl = X86DebugLineTable::new_x86_64();
        let idx = tbl.add_file("test.cpp", 0);
        assert_eq!(idx, 1);
        assert_eq!(tbl.file_count(), 1);
    }

    #[test]
    fn test_line_table_add_directory() {
        let mut tbl = X86DebugLineTable::new_x86_64();
        let idx = tbl.add_directory("/home/user/src");
        assert_eq!(idx, 1);
    }

    #[test]
    fn test_line_table_add_entry() {
        let mut tbl = X86DebugLineTable::new_x86_64();
        tbl.add_line(10, 5, 1, 0x401000);
        tbl.add_line(11, 5, 1, 0x401004);
        assert_eq!(tbl.entry_count(), 2);
    }

    #[test]
    fn test_line_table_add_end_sequence() {
        let mut tbl = X86DebugLineTable::new_x86_64();
        tbl.add_end_sequence(0x401008);
        assert_eq!(tbl.entry_count(), 1);
        assert!(tbl.entries[0].end_sequence);
    }

    #[test]
    fn test_line_table_emit_non_empty() {
        let mut tbl = X86DebugLineTable::new_x86_64();
        tbl.add_line(5, 0, 1, 0x1000);
        tbl.add_line(6, 0, 1, 0x1004);
        let data = tbl.emit();
        assert!(!data.is_empty());
        // Should start with unit length, version, etc.
        assert!(data.len() > 10);
    }

    #[test]
    fn test_line_table_emit_empty() {
        let tbl = X86DebugLineTable::new_x86_64();
        let data = tbl.emit();
        assert!(!data.is_empty());
    }

    // --- DIE Tests ---

    #[test]
    fn test_die_new() {
        let die = X86DebugDIE::new(dwarf_tag::DW_TAG_compile_unit);
        assert_eq!(die.tag, dwarf_tag::DW_TAG_compile_unit);
        assert!(die.attributes.is_empty());
        assert!(die.children.is_empty());
    }

    #[test]
    fn test_die_add_attributes() {
        let mut die = X86DebugDIE::new(dwarf_tag::DW_TAG_subprogram);
        die.add_attr_string(dwarf_attr::DW_AT_name, "main");
        die.add_attr_data4(dwarf_attr::DW_AT_decl_line, 42);
        die.add_attr_flag(dwarf_attr::DW_AT_external, true);
        assert_eq!(die.attributes.len(), 3);
    }

    #[test]
    fn test_die_add_child() {
        let mut parent = X86DebugDIE::new(dwarf_tag::DW_TAG_compile_unit);
        let child = X86DebugDIE::new(dwarf_tag::DW_TAG_subprogram);
        parent.add_child(child);
        assert_eq!(parent.children.len(), 1);
    }

    // --- Compile Unit Tests ---

    #[test]
    fn test_cu_new_x86_64() {
        let cu = X86DebugCompileUnit::new_x86_64("main.cpp", "/src", "mycc");
        assert_eq!(cu.file_name, "main.cpp");
        assert_eq!(cu.comp_dir, "/src");
        assert_eq!(cu.producer, "mycc");
        assert_eq!(cu.address_size, 8);
    }

    #[test]
    fn test_cu_new_x86_32() {
        let cu = X86DebugCompileUnit::new_x86_32("test.c", "/src", "gcc");
        assert_eq!(cu.address_size, 4);
    }

    #[test]
    fn test_cu_set_language() {
        let mut cu = X86DebugCompileUnit::new_x86_64("f.c", ".", "cc");
        cu.set_language(dwarf_lang::DW_LANG_C11);
        assert_eq!(cu.language, dwarf_lang::DW_LANG_C11);
    }

    #[test]
    fn test_cu_add_subprogram() {
        let mut cu = X86DebugCompileUnit::new_x86_64("f.c", ".", "cc");
        cu.add_subprogram(X86DebugSubprogram::new("foo", 0x1000, 0x1100));
        assert_eq!(cu.subprogram_count(), 1);
    }

    #[test]
    fn test_cu_add_global_variable() {
        let mut cu = X86DebugCompileUnit::new_x86_64("f.c", ".", "cc");
        cu.add_global_variable(X86DebugVariable::new_local("g_var"));
        assert_eq!(cu.global_var_count(), 1);
    }

    #[test]
    fn test_cu_build_die() {
        let mut cu = X86DebugCompileUnit::new_x86_64("test.c", "/tmp", "clang");
        cu.set_pc_range(0x4000, 0x5000);
        let die = cu.build_die();
        assert_eq!(die.tag, dwarf_tag::DW_TAG_compile_unit);
        assert!(die.attributes.len() >= 4);
    }

    // --- Subprogram Tests ---

    #[test]
    fn test_subprogram_new() {
        let sp = X86DebugSubprogram::new("myfunc", 0x1000, 0x1200);
        assert_eq!(sp.name, "myfunc");
        assert_eq!(sp.low_pc, 0x1000);
        assert_eq!(sp.high_pc, 0x1200);
    }

    #[test]
    fn test_subprogram_with_variables() {
        let mut sp = X86DebugSubprogram::new("calc", 0x2000, 0x2100);
        sp.add_variable(X86DebugVariable::new_local("x"));
        sp.add_parameter(X86DebugVariable::new_parameter("n"));
        assert_eq!(sp.variables.len(), 1);
        assert_eq!(sp.parameters.len(), 1);
    }

    #[test]
    fn test_subprogram_set_frame_base() {
        let mut sp = X86DebugSubprogram::new("fn", 0x1000, 0x1100);
        let mut fb = X86DebugLocationExpr::new_x86_64();
        fb.call_frame_cfa();
        sp.set_frame_base(fb);
        assert!(sp.frame_base.is_some());
    }

    #[test]
    fn test_subprogram_compute_frame_base() {
        let mut sp = X86DebugSubprogram::new("fn", 0x1000, 0x1100);
        sp.compute_x86_64_frame_base();
        assert!(sp.frame_base.is_some());
        let fb = sp.frame_base.unwrap();
        assert_eq!(fb.bytes[0], dwarf_op::DW_OP_call_frame_cfa);
    }

    #[test]
    fn test_subprogram_set_linkage_name() {
        let mut sp = X86DebugSubprogram::new("fn", 0x1000, 0x1100);
        sp.set_linkage_name("_Z2fnv");
        assert_eq!(sp.linkage_name, Some("_Z2fnv".to_string()));
    }

    #[test]
    fn test_subprogram_build_die() {
        let mut sp = X86DebugSubprogram::new("main", 0x4000, 0x4100);
        sp.compute_x86_64_frame_base();
        sp.set_linkage_name("_Z4mainv");
        let die = sp.build_die();
        assert_eq!(die.tag, dwarf_tag::DW_TAG_subprogram);
        assert!(die
            .attributes
            .iter()
            .any(|a| a.name == dwarf_attr::DW_AT_name));
    }

    // --- Variable Tests ---

    #[test]
    fn test_variable_new_local() {
        let var = X86DebugVariable::new_local("counter");
        assert_eq!(var.tag, dwarf_tag::DW_TAG_variable);
        assert_eq!(var.name, "counter");
    }

    #[test]
    fn test_variable_new_parameter() {
        let var = X86DebugVariable::new_parameter("argc");
        assert_eq!(var.tag, dwarf_tag::DW_TAG_formal_parameter);
    }

    #[test]
    fn test_variable_set_type() {
        let mut var = X86DebugVariable::new_local("x");
        var.set_type("int", 42);
        assert_eq!(var.type_name, Some("int".to_string()));
        assert_eq!(var.type_offset, Some(42));
    }

    #[test]
    fn test_variable_set_location() {
        let mut var = X86DebugVariable::new_local("x");
        let mut loc = X86DebugLocationExpr::new_x86_64();
        loc.rbp_offset_64(-4);
        var.set_location(loc);
        assert!(var.location.is_some());
    }

    #[test]
    fn test_variable_build_die() {
        let mut var = X86DebugVariable::new_local("x");
        var.set_type("int", 10);
        let mut loc = X86DebugLocationExpr::new_x86_64();
        loc.rbp_offset_64(-4);
        var.set_location(loc);
        let die = var.build_die();
        assert_eq!(die.tag, dwarf_tag::DW_TAG_variable);
    }

    // --- Lexical Block Tests ---

    #[test]
    fn test_lexical_block_new() {
        let block = X86DebugLexicalBlock::new(0x4000, 0x4100);
        assert_eq!(block.low_pc, 0x4000);
        assert_eq!(block.high_pc, 0x4100);
        assert!(block.variables.is_empty());
    }

    #[test]
    fn test_lexical_block_add_variable() {
        let mut block = X86DebugLexicalBlock::new(0x4000, 0x4100);
        block.add_variable(X86DebugVariable::new_local("tmp"));
        assert_eq!(block.variables.len(), 1);
    }

    #[test]
    fn test_lexical_block_build_die() {
        let mut block = X86DebugLexicalBlock::new(0x4000, 0x4100);
        block.add_variable(X86DebugVariable::new_local("v"));
        let die = block.build_die();
        assert_eq!(die.tag, dwarf_tag::DW_TAG_lexical_block);
        assert_eq!(die.children.len(), 1);
    }

    // --- Inlined Subroutine Tests ---

    #[test]
    fn test_inlined_subroutine_new() {
        let inline = X86DebugInlinedSubroutine::new(42, 0x5000, 0x5100);
        assert_eq!(inline.abstract_origin, 42);
        assert_eq!(inline.low_pc, 0x5000);
    }

    #[test]
    fn test_inlined_subroutine_set_call_site() {
        let mut inline = X86DebugInlinedSubroutine::new(42, 0x5000, 0x5100);
        inline.set_call_site(1, 100, 5);
        assert_eq!(inline.call_file, 1);
        assert_eq!(inline.call_line, 100);
    }

    #[test]
    fn test_inlined_subroutine_build_die() {
        let mut inline = X86DebugInlinedSubroutine::new(42, 0x5000, 0x5100);
        inline.set_call_site(1, 100, 5);
        let die = inline.build_die();
        assert_eq!(die.tag, dwarf_tag::DW_TAG_inlined_subroutine);
    }

    // --- Var Loc Tracker Tests ---

    #[test]
    fn test_var_loc_tracker_new() {
        let tracker = X86DebugVarLocTracker::new("test_func");
        assert_eq!(tracker.function_name, "test_func");
        assert!(tracker.var_ranges.is_empty());
    }

    #[test]
    fn test_var_loc_tracker_record_dbg_value() {
        let mut tracker = X86DebugVarLocTracker::new("f");
        let loc = X86DebugLocationExpr::new_x86_64();
        tracker.record_dbg_value(X86DbgValue::new("x", loc.clone(), 0));
        tracker.record_dbg_value(X86DbgValue::new("x", loc, 1));
        assert_eq!(tracker.dbg_value_count(), 2);
    }

    #[test]
    fn test_var_loc_tracker_register_in_reg() {
        let mut tracker = X86DebugVarLocTracker::new("f");
        tracker.register_in_reg("y", "rax", 0, 10, true);
        assert_eq!(tracker.tracked_variables(), vec!["y"]);
    }

    #[test]
    fn test_var_loc_tracker_register_on_stack() {
        let mut tracker = X86DebugVarLocTracker::new("f");
        tracker.register_on_stack("z", -8, 0, 10, true);
        assert!(tracker.get_locations("z").is_some());
    }

    // --- CodeView Tests ---

    #[test]
    fn test_cv_line_table_new() {
        let tbl = X86CVLineTable::new(1);
        assert_eq!(tbl.section_index, 1);
        assert!(tbl.is_empty());
    }

    #[test]
    fn test_cv_line_table_add_line() {
        let mut tbl = X86CVLineTable::new(1);
        tbl.add_line(0, 10);
        tbl.add_line(4, 12);
        assert_eq!(tbl.entry_count(), 2);
    }

    #[test]
    fn test_cv_line_table_add_source_file() {
        let mut tbl = X86CVLineTable::new(1);
        tbl.add_source_file("main.cpp");
        tbl.add_source_file("main.cpp"); // duplicate
        assert_eq!(tbl.source_files.len(), 1);
    }

    // --- X86DebugCodeGen Tests ---

    #[test]
    fn test_codegen_new_x86_64() {
        let dc = X86DebugCodeGen::new_x86_64();
        assert!(dc.is_64bit);
        assert!(!dc.use_codeview);
        assert_eq!(dc.compile_units.len(), 0);
    }

    #[test]
    fn test_codegen_new_x86_32() {
        let dc = X86DebugCodeGen::new_x86_32();
        assert!(!dc.is_64bit);
    }

    #[test]
    fn test_codegen_as_windows() {
        let mut dc = X86DebugCodeGen::new_x86_64();
        dc.as_windows();
        assert!(dc.use_codeview);
        assert!(dc.target_triple.contains("windows"));
    }

    #[test]
    fn test_codegen_create_compile_unit() {
        let mut dc = X86DebugCodeGen::new_x86_64();
        dc.create_compile_unit("test.c", "/build", "mycc");
        assert_eq!(dc.compile_units.len(), 1);
        assert_eq!(dc.stats.compile_units, 1);
    }

    #[test]
    fn test_codegen_add_subprogram() {
        let mut dc = X86DebugCodeGen::new_x86_64();
        dc.create_compile_unit("test.c", ".", "cc");
        dc.add_subprogram("main", 0x4000, 0x4100);
        let cu = dc.current_compile_unit().unwrap();
        assert_eq!(cu.subprogram_count(), 1);
        assert_eq!(dc.stats.subprograms, 1);
    }

    #[test]
    fn test_codegen_add_local_variable() {
        let mut dc = X86DebugCodeGen::new_x86_64();
        dc.create_compile_unit("t.c", ".", "cc");
        dc.add_subprogram("f", 0x1000, 0x1100);
        dc.add_local_variable("x", -4, "int", 10);
        let cu = dc.current_compile_unit().unwrap();
        let sp = &cu.subprograms[0];
        assert_eq!(sp.variables.len(), 1);
        assert_eq!(dc.stats.variables, 1);
    }

    #[test]
    fn test_codegen_add_parameter() {
        let mut dc = X86DebugCodeGen::new_x86_64();
        dc.create_compile_unit("p.c", ".", "cc");
        dc.add_subprogram("g", 0x2000, 0x2100);
        dc.add_parameter("argc", "rdi", "int", 10);
        let cu = dc.current_compile_unit().unwrap();
        assert_eq!(cu.subprograms[0].parameters.len(), 1);
    }

    #[test]
    fn test_codegen_add_line_entry() {
        let mut dc = X86DebugCodeGen::new_x86_64();
        dc.create_compile_unit("lines.c", ".", "cc");
        dc.add_line_entry(10, 5, 1, 0x5000);
        dc.add_line_entry(11, 5, 1, 0x5004);
        let cu = dc.current_compile_unit().unwrap();
        assert_eq!(cu.line_table.entry_count(), 2);
        assert_eq!(dc.stats.line_entries, 2);
    }

    #[test]
    fn test_codegen_add_line_file() {
        let mut dc = X86DebugCodeGen::new_x86_64();
        dc.create_compile_unit("f.c", ".", "cc");
        let idx = dc.add_line_file("f.c", 0);
        assert_eq!(idx, 1);
    }

    #[test]
    fn test_codegen_add_line_directory() {
        let mut dc = X86DebugCodeGen::new_x86_64();
        dc.create_compile_unit("f.c", ".", "cc");
        let idx = dc.add_line_directory("/include");
        assert_eq!(idx, 1);
    }

    #[test]
    fn test_codegen_add_lexical_block() {
        let mut dc = X86DebugCodeGen::new_x86_64();
        dc.create_compile_unit("b.c", ".", "cc");
        dc.add_subprogram("loop", 0x3000, 0x3100);
        dc.add_lexical_block(0x3020, 0x3080);
        let cu = dc.current_compile_unit().unwrap();
        assert_eq!(cu.subprograms[0].lexical_blocks.len(), 1);
        assert_eq!(dc.stats.lexical_blocks, 1);
    }

    #[test]
    fn test_codegen_add_inlined_subroutine() {
        let mut dc = X86DebugCodeGen::new_x86_64();
        dc.create_compile_unit("i.c", ".", "cc");
        dc.add_subprogram("outer", 0x4000, 0x4200);
        dc.add_inlined_subroutine(100, 0x4100, 0x4150, 1, 5);
        let cu = dc.current_compile_unit().unwrap();
        assert_eq!(cu.subprograms[0].inlined_subroutines.len(), 1);
        assert_eq!(dc.stats.inlined_subroutines, 1);
    }

    #[test]
    fn test_codegen_add_global_variable() {
        let mut dc = X86DebugCodeGen::new_x86_64();
        dc.create_compile_unit("g.c", ".", "cc");
        dc.add_global_variable("global_counter", 0x600000, "int", 10);
        let cu = dc.current_compile_unit().unwrap();
        assert_eq!(cu.global_var_count(), 1);
    }

    #[test]
    fn test_codegen_variable_location_tracking() {
        let mut dc = X86DebugCodeGen::new_x86_64();
        dc.begin_function("work");

        let mut loc = X86DebugLocationExpr::new_x86_64();
        loc.rbp_offset_64(-8);
        dc.record_dbg_value("work", "result", loc.clone(), 0);

        dc.track_var_in_reg("work", "tmp", "rax", 2, 8);
        dc.track_var_on_stack("work", "buf", -16, 0, 10);

        let tracker = dc.end_function("work").unwrap();
        assert_eq!(tracker.tracked_variables().len(), 3);
        assert_eq!(dc.stats.dbg_values, 1);
    }

    #[test]
    fn test_codegen_codeview_types() {
        let mut dc = X86DebugCodeGen::new_x86_64();
        dc.as_windows();
        dc.cv_add_type_record(0x1002, vec![0x01, 0x02]);
        dc.cv_add_symbol_record(0x1110, vec![0x03]);
        assert_eq!(dc.stats.cv_types, 1);
        assert_eq!(dc.stats.cv_symbols, 1);
    }

    #[test]
    fn test_codegen_codeview_line_table() {
        let mut dc = X86DebugCodeGen::new_x86_64();
        dc.as_windows();
        let idx = dc.cv_create_line_table(1);
        dc.cv_add_line_entry(idx, 0, 5);
        dc.cv_add_line_entry(idx, 4, 6);
        assert_eq!(dc.cv_line_tables[idx].entry_count(), 2);
    }

    #[test]
    fn test_codegen_get_stats() {
        let mut dc = X86DebugCodeGen::new_x86_64();
        dc.create_compile_unit("s.c", ".", "cc");
        dc.add_subprogram("f", 0x1000, 0x1100);
        let stats = dc.get_stats();
        assert_eq!(stats.compile_units, 1);
        assert_eq!(stats.subprograms, 1);
    }

    #[test]
    fn test_codegen_reset() {
        let mut dc = X86DebugCodeGen::new_x86_64();
        dc.create_compile_unit("t.c", ".", "cc");
        dc.add_subprogram("f", 0x1000, 0x1100);
        dc.reset();
        assert_eq!(dc.compile_units.len(), 0);
        assert_eq!(dc.stats.compile_units, 0);
        assert_eq!(dc.stats.subprograms, 0);
    }

    #[test]
    fn test_codegen_end_to_end() {
        let mut dc = X86DebugCodeGen::new_x86_64();
        let cu = dc.create_compile_unit("app.cpp", "/project", "X86DebugCompiler 1.0");

        dc.add_line_directory("/usr/include");
        dc.add_line_file("app.cpp", 0);
        dc.add_line_file("header.h", 1);

        dc.add_subprogram("main", 0x401000, 0x401200);
        dc.add_parameter("argc", "rdi", "int", 1);
        dc.add_parameter("argv", "rsi", "char**", 2);
        dc.add_local_variable("result", -4, "int", 1);
        dc.add_local_variable("buffer", -64, "char[64]", 3);

        dc.add_line_entry(3, 1, 1, 0x401000);
        dc.add_line_entry(4, 5, 1, 0x401010);
        dc.add_line_entry(5, 5, 1, 0x401020);

        dc.add_lexical_block(0x401010, 0x401050);
        dc.add_inlined_subroutine(10, 0x401100, 0x401180, 1, 4);

        cu.set_pc_range(0x401000, 0x401200);

        assert_eq!(cu.subprogram_count(), 1);
        assert_eq!(cu.line_table.entry_count(), 3);
        assert_eq!(cu.line_table.file_count(), 2);
        assert_eq!(cu.subprograms[0].inlined_subroutines.len(), 1);
    }

    #[test]
    fn test_dwarf_constants() {
        assert_eq!(dwarf_tag::DW_TAG_compile_unit, 0x11);
        assert_eq!(dwarf_tag::DW_TAG_subprogram, 0x2e);
        assert_eq!(dwarf_attr::DW_AT_name, 0x03);
        assert_eq!(dwarf_op::DW_OP_addr, 0x03);
        assert_eq!(dwarf_lang::DW_LANG_C_plus_plus_17, 0x002e);
        assert_eq!(x86_64_dwarf_reg::RBP, 6);
        assert_eq!(x86_64_dwarf_reg::XMM0, 17);
    }

    #[test]
    fn test_loc_expr_entry_value() {
        let mut inner = X86DebugLocationExpr::new_x86_64();
        inner.reg(0);
        let mut outer = X86DebugLocationExpr::new_x86_64();
        outer.entry_value(&inner);
        assert!(outer.bytes.contains(&dwarf_op::DW_OP_entry_value));
    }

    #[test]
    fn test_loc_expr_form_tls_address() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.reg(0).form_tls_address();
        assert!(expr.bytes.contains(&dwarf_op::DW_OP_form_tls_address));
    }

    #[test]
    fn test_loc_expr_call_frame_cfa() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.call_frame_cfa();
        assert_eq!(expr.bytes[0], dwarf_op::DW_OP_call_frame_cfa);
    }

    #[test]
    fn test_loc_expr_param_in_register() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.param_in_register("rdi");
        assert_eq!(expr.bytes[0], dwarf_op::DW_OP_reg0 + 5); // RDI
    }

    #[test]
    fn test_loc_expr_param_on_stack() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.call_frame_cfa();
        expr.plus_uconst(16);
        // Just testing no panic
    }

    #[test]
    fn test_loc_expr_convert_reinterpret() {
        let mut expr = X86DebugLocationExpr::new_x86_64();
        expr.reg(0);
        expr.convert(100);
        expr.reinterpret(200);
        assert!(expr.bytes.contains(&dwarf_op::DW_OP_convert));
        assert!(expr.bytes.contains(&dwarf_op::DW_OP_reinterpret));
    }

    #[test]
    fn test_loc_expr_default() {
        let expr = X86DebugLocationExpr::default();
        assert_eq!(expr.address_size, 8);
        assert!(expr.is_empty());
    }

    #[test]
    fn test_line_table_prologue_end() {
        let mut tbl = X86DebugLineTable::new_x86_64();
        tbl.add_prologue_end(2, 0x1000);
        assert!(tbl.entries[0].prologue_end);
    }

    #[test]
    fn test_line_table_epilogue_begin() {
        let mut tbl = X86DebugLineTable::new_x86_64();
        tbl.add_epilogue_begin(10, 0x2000);
        assert!(tbl.entries[0].epilogue_begin);
    }

    #[test]
    fn test_die_add_attr_exprloc() {
        let mut die = X86DebugDIE::new(dwarf_tag::DW_TAG_variable);
        let mut loc = X86DebugLocationExpr::new_x86_64();
        loc.rbp_offset_64(-8);
        die.add_attr_exprloc(dwarf_attr::DW_AT_location, &loc);
        assert_eq!(die.attributes.len(), 1);
    }

    #[test]
    fn test_die_add_attr_udata_sdata() {
        let mut die = X86DebugDIE::new(dwarf_tag::DW_TAG_enumerator);
        die.add_attr_udata(dwarf_attr::DW_AT_const_value, 42);
        die.add_attr_sdata(dwarf_attr::DW_AT_const_value, -1);
        assert_eq!(die.attributes.len(), 2);
    }

    #[test]
    fn test_line_table_set_comp_dir() {
        let mut tbl = X86DebugLineTable::new_x86_64();
        tbl.set_comp_dir("/home/project");
        assert_eq!(tbl.comp_dir, "/home/project");
    }

    #[test]
    fn test_db_value_undef() {
        let dbg = X86DbgValue::undef("opt_out", 5);
        assert!(dbg.is_undef);
        assert_eq!(dbg.variable_name, "opt_out");
        assert_eq!(dbg.instruction_index, 5);
    }
}