llvm-native-core-ext 0.1.0

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

use llvm_native_core::attributes::{AttributeKind, AttributeList};
use llvm_native_core::module::Module;
use llvm_native_core::opcode::Opcode;
use llvm_native_core::types::{Type, TypeId, TypeKind};
use llvm_native_core::value::{SubclassKind, Value, ValueRef};
use std::collections::HashMap;

/// Write a Module as LLVM assembly text (.ll format).
pub fn write_assembly(module: &Module) -> String {
    let mut out = String::new();

    // Module header
    write_module_header(module, &mut out);

    // Named type definitions
    write_type_definitions(module, &mut out);

    // Attribute groups
    write_attr_groups(module, &mut out);

    // Named metadata
    write_named_metadata(module, &mut out);

    // Declarations: functions without bodies
    for func in &module.functions {
        let f = func.borrow();
        if f.is_function() && f.num_operands == 0 {
            let ret_ty = function_return_type(func);
            out.push_str(&format!(
                "declare {} @{}()\n",
                type_to_str_full(&ret_ty),
                f.name
            ));
        }
    }

    if module
        .functions
        .iter()
        .any(|f| f.borrow().num_operands == 0)
    {
        out.push('\n');
    }

    // Global variables
    for g in &module.globals {
        write_global_variable(g, &mut out);
    }

    if !module.globals.is_empty() {
        out.push('\n');
    }

    // Function definitions (with bodies)
    for func in &module.functions {
        let f = func.borrow();
        if f.is_function() && f.num_operands > 0 {
            // Has body (contains basic blocks as operands)
            let ret_ty = function_return_type(func);
            out.push_str(&format!(
                "define {} @{}() {{\n",
                type_to_str_full(&ret_ty),
                f.name
            ));

            for op in &f.operands {
                let bb = op.borrow();
                if bb.is_basic_block() {
                    out.push_str(&format!("{}:\n", bb.name));
                    for inst in &bb.operands {
                        let i = inst.borrow();
                        if i.is_instruction() {
                            write_instruction(&mut out, inst);
                        }
                    }
                }
            }
            out.push_str("}\n\n");
        }
    }

    // Use-list order directives (if any)
    write_use_list_order(module, &mut out);

    out
}

// ============================================================
// Module-level directive helpers
// ============================================================

/// Write the module header: source_filename, target triple, data layout.
fn write_module_header(module: &Module, out: &mut String) {
    if !module.source_filename.is_empty() {
        write_source_filename(&module.source_filename, out);
    }
    if let Some(ref triple) = module.target_triple {
        write_target_triple(triple, out);
    }
    if let Some(ref dl) = module.data_layout {
        write_data_layout(dl, out);
    }
    if !module.source_filename.is_empty()
        || module.target_triple.is_some()
        || module.data_layout.is_some()
    {
        out.push('\n');
    }
}

/// Write source_filename = "..."
fn write_source_filename(filename: &str, out: &mut String) {
    out.push_str(&format!("source_filename = \"{}\"\n", filename));
}

/// Write target triple = "..."
fn write_target_triple(triple: &str, out: &mut String) {
    out.push_str(&format!("target triple = \"{}\"\n", triple));
}

/// Write target datalayout = "..."
fn write_data_layout(layout: &str, out: &mut String) {
    out.push_str(&format!("target datalayout = \"{}\"\n", layout));
}

/// Write named type definitions from module metadata.
fn write_type_definitions(_module: &Module, _out: &mut String) {
    // Type definitions (%struct.Foo = type {...}) are emitted when
    // encountered. For now, this is a placeholder — full implementation
    // requires tracking named types in the Module.
}

/// Write attribute groups (#0 = attributes { ... }).
fn write_attr_groups(_module: &Module, _out: &mut String) {
    // Attribute groups are tracked in the module's metadata.
    // Placeholder for full implementation.
}

/// Write named metadata (!llvm.module.flags = !{ !0, !1 }).
fn write_named_metadata(_module: &Module, _out: &mut String) {
    // Named metadata emission — placeholder for full implementation.
}

/// Write use-list order directives.
fn write_use_list_order(_module: &Module, _out: &mut String) {
    // Placeholder for uselistorder directives.
}

/// Write a global variable declaration/definition.
fn write_global_variable(gv: &ValueRef, out: &mut String) {
    let g = gv.borrow();
    if g.subclass != SubclassKind::GlobalVariable {
        return;
    }
    // Default to global (not constant)
    let linkage = if g.name.starts_with("internal") {
        "internal "
    } else {
        ""
    };
    out.push_str(&format!(
        "@{} = {}global {} {}\n",
        g.name,
        linkage,
        type_to_str_full(&g.ty),
        value_to_str(gv)
    ));
}

/// Write a function declaration.
fn write_function_declaration(func: &ValueRef, out: &mut String) {
    let f = func.borrow();
    if f.is_function() {
        let ret_ty = function_return_type(func);
        out.push_str(&format!(
            "declare {} @{}()\n",
            type_to_str_full(&ret_ty),
            f.name
        ));
    }
}

/// Write a function definition with full body.
fn write_function_definition(func: &ValueRef, out: &mut String) {
    let f = func.borrow();
    if f.is_function() && f.num_operands > 0 {
        let ret_ty = function_return_type(func);
        out.push_str(&format!(
            "define {} @{}() {{\n",
            type_to_str_full(&ret_ty),
            f.name
        ));
        for op in &f.operands {
            let bb = op.borrow();
            if bb.is_basic_block() {
                out.push_str(&format!("{}:\n", bb.name));
                for inst in &bb.operands {
                    let i = inst.borrow();
                    if i.is_instruction() {
                        write_instruction(out, inst);
                    }
                }
            }
        }
        out.push_str("}\n\n");
    }
}

// ============================================================
// Type formatting
// ============================================================

/// Extract the return type from a function type.
fn function_return_type(func: &ValueRef) -> Type {
    let f = func.borrow();
    // Check the return_type field first (set by new_function)
    if let Some(ref rt) = f.return_type {
        return rt.clone();
    }
    // Fallback: try to extract from the function type
    match &f.ty.kind {
        TypeKind::Function { .. } => Type::void(),
        TypeKind::Integer { bits } => Type::int(*bits),
        _ => f.ty.clone(),
    }
}

/// Convert a Type to its LLVM assembly string representation.
pub fn type_to_str(ty: &Type) -> String {
    type_to_str_full(ty)
}

/// Full type-to-string conversion with support for nested types.
fn type_to_str_full(ty: &Type) -> String {
    match &ty.kind {
        TypeKind::Void => "void".into(),
        TypeKind::Half => "half".into(),
        TypeKind::BFloat => "bfloat".into(),
        TypeKind::Float => "float".into(),
        TypeKind::Double => "double".into(),
        TypeKind::FP128 => "fp128".into(),
        TypeKind::X86FP80 => "x86_fp80".into(),
        TypeKind::PPCFP128 => "ppc_fp128".into(),
        TypeKind::Label => "label".into(),
        TypeKind::Metadata => "metadata".into(),
        TypeKind::X86AMX => "x86_amx".into(),
        TypeKind::X86MMX => "x86_mmx".into(),
        TypeKind::Token => "token".into(),
        TypeKind::Integer { bits } => format!("i{}", bits),
        TypeKind::Pointer { addr_space } => {
            if *addr_space == 0 {
                "ptr".into()
            } else {
                format!("ptr addrspace({})", addr_space)
            }
        }
        TypeKind::Array {
            len,
            element_type_id,
        } => {
            // We don't have the type store here, so we can't look up the element type.
            // Emit a placeholder.
            format!("[{} x <ty>]", len)
        }
        TypeKind::Struct {
            name,
            is_packed,
            is_opaque,
            element_type_ids,
        } => {
            if let Some(n) = name {
                if *is_packed {
                    format!("<{{ %{} }}>", n)
                } else {
                    format!("%{}", n)
                }
            } else if *is_opaque {
                if *is_packed {
                    "<{ opaque }>".into()
                } else {
                    "{ opaque }".into()
                }
            } else if element_type_ids.is_empty() {
                if *is_packed {
                    "<{ }>".into()
                } else {
                    "{ }".into()
                }
            } else {
                // Literal struct with elements
                let elts: Vec<String> = element_type_ids
                    .iter()
                    .map(|_| "<ty>".to_string())
                    .collect();
                let body = elts.join(", ");
                if *is_packed {
                    format!("<{{ {} }}>", body)
                } else {
                    format!("{{ {} }}", body)
                }
            }
        }
        TypeKind::FixedVector {
            len,
            element_type_id,
        } => {
            format!("<{} x <ty>>", len)
        }
        TypeKind::ScalableVector {
            min_elems,
            element_type_id,
        } => {
            format!("<vscale x {} x <ty>>", min_elems)
        }
        TypeKind::Function {
            return_type_id,
            param_type_ids,
            is_vararg,
        } => {
            let params: Vec<String> = param_type_ids.iter().map(|_| "<ty>".to_string()).collect();
            let mut sig = params.join(", ");
            if *is_vararg {
                if !sig.is_empty() {
                    sig.push_str(", ...");
                } else {
                    sig.push_str("...");
                }
            }
            format!("<ty> ({})", sig)
        }
    }
}

// ============================================================
// Instruction emission
// ============================================================

/// Write a single instruction to the output.
fn write_instruction(out: &mut String, inst_val: &ValueRef) {
    let i = inst_val.borrow();
    let name_prefix = if i.name.is_empty() {
        String::new()
    } else {
        format!("%{} = ", i.name)
    };

    // Use explicit opcode if available
    if let Some(opcode) = i.get_opcode() {
        match opcode {
            llvm_native_core::opcode::Opcode::Ret => {
                if i.operands.is_empty() {
                    out.push_str(&format!("  {}ret void\n", name_prefix));
                } else {
                    let val = value_to_str(&i.operands[0]);
                    let ty_str = type_to_str_full(&i.operands[0].borrow().ty);
                    out.push_str(&format!("  {}ret {} {}\n", name_prefix, ty_str, val));
                }
            }
            llvm_native_core::opcode::Opcode::Br => {
                if i.operands.len() == 1 {
                    let label = i.operands[0].borrow().name.clone();
                    out.push_str(&format!("  {}br label %{}\n", name_prefix, label));
                } else if i.operands.len() >= 3 {
                    let cond = value_to_str(&i.operands[0]);
                    let t_label = i.operands[1].borrow().name.clone();
                    let f_label = i.operands[2].borrow().name.clone();
                    out.push_str(&format!(
                        "  {}br i1 {}, label %{}, label %{}\n",
                        name_prefix, cond, t_label, f_label
                    ));
                } else {
                    out.push_str(&format!("  {}br <unknown>\n", name_prefix));
                }
            }
            llvm_native_core::opcode::Opcode::Switch => {
                if i.operands.len() >= 2 {
                    let val = value_to_str(&i.operands[0]);
                    let val_ty = type_to_str_full(&i.operands[0].borrow().ty);
                    let default_label = i.operands[1].borrow().name.clone();
                    let mut cases = String::new();
                    let mut idx = 2;
                    while idx + 1 < i.operands.len() {
                        let case_val = value_to_str(&i.operands[idx]);
                        let case_ty = type_to_str_full(&i.operands[idx].borrow().ty);
                        let case_label = i.operands[idx + 1].borrow().name.clone();
                        cases.push_str(&format!(
                            "    {} {}, label %{}",
                            case_ty, case_val, case_label
                        ));
                        idx += 2;
                        if idx + 1 < i.operands.len() {
                            cases.push_str(",\n");
                        }
                    }
                    out.push_str(&format!(
                        "  {}switch {} {}, label %{} [\n{}\n  ]\n",
                        name_prefix, val_ty, val, default_label, cases
                    ));
                }
            }
            llvm_native_core::opcode::Opcode::Invoke => {
                if i.operands.len() >= 1 {
                    let func_name = i.operands[0].borrow().name.clone();
                    let ret_ty = type_to_str_full(&i.ty);
                    let mut args = Vec::new();
                    // Operands 1..(n-2) are call args, last two are normal/lpad labels
                    // Simplified: just write what we have
                    for a in &i.operands[1..] {
                        let a_borrow = a.borrow();
                        if a_borrow.is_basic_block() {
                            // labels
                            args.push(format!("label %{}", a_borrow.name));
                        } else {
                            let aty = type_to_str_full(&a_borrow.ty);
                            let av = value_to_str(a);
                            args.push(format!("{} {}", aty, av));
                        }
                    }
                    out.push_str(&format!(
                        "  {}invoke {} @{}({})\n",
                        name_prefix,
                        ret_ty,
                        func_name,
                        args.join(", ")
                    ));
                }
            }
            llvm_native_core::opcode::Opcode::Resume => {
                if !i.operands.is_empty() {
                    let val = value_to_str(&i.operands[0]);
                    let ty_str = type_to_str_full(&i.operands[0].borrow().ty);
                    out.push_str(&format!("  {}resume {} {}\n", name_prefix, ty_str, val));
                } else {
                    out.push_str(&format!("  {}resume undef\n", name_prefix));
                }
            }
            llvm_native_core::opcode::Opcode::LandingPad => {
                let ty_str = type_to_str_full(&i.ty);
                out.push_str(&format!("  {}landingpad {}\n", name_prefix, ty_str));
            }
            llvm_native_core::opcode::Opcode::CleanupRet => {
                out.push_str(&format!("  {}cleanupret\n", name_prefix));
            }
            llvm_native_core::opcode::Opcode::CatchRet => {
                out.push_str(&format!("  {}catchret\n", name_prefix));
            }
            llvm_native_core::opcode::Opcode::CatchSwitch => {
                out.push_str(&format!("  {}catchswitch\n", name_prefix));
            }
            llvm_native_core::opcode::Opcode::CallBr => {
                out.push_str(&format!("  {}callbr\n", name_prefix));
            }
            llvm_native_core::opcode::Opcode::IndirectBr => {
                out.push_str(&format!("  {}indirectbr\n", name_prefix));
            }
            // Binary operations
            llvm_native_core::opcode::Opcode::Add
            | llvm_native_core::opcode::Opcode::Sub
            | llvm_native_core::opcode::Opcode::Mul
            | llvm_native_core::opcode::Opcode::UDiv
            | llvm_native_core::opcode::Opcode::SDiv
            | llvm_native_core::opcode::Opcode::URem
            | llvm_native_core::opcode::Opcode::SRem
            | llvm_native_core::opcode::Opcode::FAdd
            | llvm_native_core::opcode::Opcode::FSub
            | llvm_native_core::opcode::Opcode::FMul
            | llvm_native_core::opcode::Opcode::FDiv
            | llvm_native_core::opcode::Opcode::FRem
            | llvm_native_core::opcode::Opcode::Shl
            | llvm_native_core::opcode::Opcode::LShr
            | llvm_native_core::opcode::Opcode::AShr
            | llvm_native_core::opcode::Opcode::And
            | llvm_native_core::opcode::Opcode::Or
            | llvm_native_core::opcode::Opcode::Xor => {
                if i.operands.len() >= 2 {
                    let a = value_to_str(&i.operands[0]);
                    let b = value_to_str(&i.operands[1]);
                    let ty_str = type_to_str_full(&i.operands[0].borrow().ty);
                    out.push_str(&format!(
                        "  {}{} {} {}, {}\n",
                        name_prefix,
                        opcode.as_mnemonic(),
                        ty_str,
                        a,
                        b
                    ));
                }
            }
            // Memory operations
            llvm_native_core::opcode::Opcode::Alloca => {
                let ty_str = type_to_str_full(&i.ty);
                out.push_str(&format!("  {}alloca {}\n", name_prefix, ty_str));
            }
            llvm_native_core::opcode::Opcode::Load => {
                let ty_str = type_to_str_full(&i.ty);
                let ptr = value_to_str(&i.operands[0]);
                out.push_str(&format!("  {}load {}, ptr {}\n", name_prefix, ty_str, ptr));
            }
            llvm_native_core::opcode::Opcode::Store => {
                if i.operands.len() >= 2 {
                    let val = value_to_str(&i.operands[0]);
                    let val_ty = type_to_str_full(&i.operands[0].borrow().ty);
                    let ptr = value_to_str(&i.operands[1]);
                    out.push_str(&format!(
                        "  {}store {} {}, ptr {}\n",
                        name_prefix, val_ty, val, ptr
                    ));
                }
            }
            llvm_native_core::opcode::Opcode::GetElementPtr => {
                if !i.operands.is_empty() {
                    let ptr = value_to_str(&i.operands[0]);
                    let ptr_ty = type_to_str_full(&i.operands[0].borrow().ty);
                    let mut idx_parts = Vec::new();
                    for idx in &i.operands[1..] {
                        let ity = type_to_str_full(&idx.borrow().ty);
                        let iv = value_to_str(idx);
                        idx_parts.push(format!("{} {}", ity, iv));
                    }
                    out.push_str(&format!(
                        "  {}getelementptr inbounds {}, ptr {}, {}\n",
                        name_prefix,
                        ptr_ty,
                        ptr,
                        idx_parts.join(", ")
                    ));
                }
            }
            llvm_native_core::opcode::Opcode::Fence => {
                out.push_str(&format!("  {}fence seq_cst\n", name_prefix));
            }
            llvm_native_core::opcode::Opcode::CmpXchg => {
                if i.operands.len() >= 3 {
                    let ptr = value_to_str(&i.operands[0]);
                    let ptr_ty = type_to_str_full(&i.operands[0].borrow().ty);
                    let old = value_to_str(&i.operands[1]);
                    let old_ty = type_to_str_full(&i.operands[1].borrow().ty);
                    let new = value_to_str(&i.operands[2]);
                    let new_ty = type_to_str_full(&i.operands[2].borrow().ty);
                    out.push_str(&format!(
                        "  {}cmpxchg {} {}, {} {}, {} {} acq_rel monotonic\n",
                        name_prefix, ptr_ty, ptr, old_ty, old, new_ty, new
                    ));
                }
            }
            llvm_native_core::opcode::Opcode::AtomicRMW => {
                if i.operands.len() >= 2 {
                    let ptr = value_to_str(&i.operands[0]);
                    let ptr_ty = type_to_str_full(&i.operands[0].borrow().ty);
                    let val = value_to_str(&i.operands[1]);
                    let val_ty = type_to_str_full(&i.operands[1].borrow().ty);
                    // Determine binop from the first operand's parent or default to xchg
                    out.push_str(&format!(
                        "  {}atomicrmw xchg {} {}, {} {} seq_cst\n",
                        name_prefix, ptr_ty, ptr, val_ty, val
                    ));
                }
            }
            // Cast operations
            llvm_native_core::opcode::Opcode::Trunc
            | llvm_native_core::opcode::Opcode::ZExt
            | llvm_native_core::opcode::Opcode::SExt
            | llvm_native_core::opcode::Opcode::FPTrunc
            | llvm_native_core::opcode::Opcode::FPExt
            | llvm_native_core::opcode::Opcode::FPToUI
            | llvm_native_core::opcode::Opcode::FPToSI
            | llvm_native_core::opcode::Opcode::UIToFP
            | llvm_native_core::opcode::Opcode::SIToFP
            | llvm_native_core::opcode::Opcode::PtrToInt
            | llvm_native_core::opcode::Opcode::IntToPtr
            | llvm_native_core::opcode::Opcode::BitCast
            | llvm_native_core::opcode::Opcode::AddrSpaceCast => {
                if !i.operands.is_empty() {
                    let val = value_to_str(&i.operands[0]);
                    let from_ty = type_to_str_full(&i.operands[0].borrow().ty);
                    let to_ty = type_to_str_full(&i.ty);
                    out.push_str(&format!(
                        "  {}{} {} {} to {}\n",
                        name_prefix,
                        opcode.as_mnemonic(),
                        from_ty,
                        val,
                        to_ty
                    ));
                }
            }
            // Comparison operations
            llvm_native_core::opcode::Opcode::ICmp => {
                let pred_str = if !i.name.is_empty() {
                    // Strip icmp and extract predicate
                    let name = &i.name;
                    if let Some(pred) = name.strip_prefix("icmp.") {
                        pred.to_string()
                    } else {
                        "eq".into()
                    }
                } else {
                    "eq".into()
                };
                if i.operands.len() >= 2 {
                    let a = value_to_str(&i.operands[0]);
                    let b = value_to_str(&i.operands[1]);
                    let ty_str = type_to_str_full(&i.operands[0].borrow().ty);
                    out.push_str(&format!(
                        "  {}icmp {} {} {}, {}\n",
                        name_prefix, pred_str, ty_str, a, b
                    ));
                }
            }
            llvm_native_core::opcode::Opcode::FCmp => {
                if i.operands.len() >= 2 {
                    let a = value_to_str(&i.operands[0]);
                    let b = value_to_str(&i.operands[1]);
                    let ty_str = type_to_str_full(&i.operands[0].borrow().ty);
                    out.push_str(&format!(
                        "  {}fcmp oeq {} {}, {}\n",
                        name_prefix, ty_str, a, b
                    ));
                }
            }
            // Other operations
            llvm_native_core::opcode::Opcode::Call => {
                if !i.operands.is_empty() {
                    let func_name = if !i.operands[0].borrow().name.is_empty() {
                        format!("@{}", i.operands[0].borrow().name)
                    } else {
                        "@unknown".into()
                    };
                    let args: Vec<String> = i.operands[1..]
                        .iter()
                        .map(|v| {
                            let ty = type_to_str_full(&v.borrow().ty);
                            let val = value_to_str(v);
                            format!("{} {}", ty, val)
                        })
                        .collect();
                    let ret_ty = type_to_str_full(&i.ty);
                    out.push_str(&format!(
                        "  {}call {} {}({})\n",
                        name_prefix,
                        ret_ty,
                        func_name,
                        args.join(", ")
                    ));
                }
            }
            llvm_native_core::opcode::Opcode::Phi => {
                let ty_str = type_to_str_full(&i.ty);
                let mut incoming = Vec::new();
                for chunk in i.operands.chunks(2) {
                    if chunk.len() == 2 {
                        let val = value_to_str(&chunk[0]);
                        let label = chunk[1].borrow().name.clone();
                        incoming.push(format!("[ {}, %{} ]", val, label));
                    }
                }
                out.push_str(&format!(
                    "  {}phi {} {}\n",
                    name_prefix,
                    ty_str,
                    incoming.join(", ")
                ));
            }
            llvm_native_core::opcode::Opcode::Select => {
                if i.operands.len() >= 3 {
                    let cond = value_to_str(&i.operands[0]);
                    let a = value_to_str(&i.operands[1]);
                    let a_ty = type_to_str_full(&i.operands[1].borrow().ty);
                    let b = value_to_str(&i.operands[2]);
                    let b_ty = type_to_str_full(&i.operands[2].borrow().ty);
                    out.push_str(&format!(
                        "  {}select i1 {}, {} {}, {} {}\n",
                        name_prefix, cond, a_ty, a, b_ty, b
                    ));
                }
            }
            llvm_native_core::opcode::Opcode::Freeze => {
                if !i.operands.is_empty() {
                    let val = value_to_str(&i.operands[0]);
                    let ty_str = type_to_str_full(&i.operands[0].borrow().ty);
                    out.push_str(&format!("  {}freeze {} {}\n", name_prefix, ty_str, val));
                }
            }
            llvm_native_core::opcode::Opcode::VAArg => {
                if i.operands.len() >= 2 {
                    let va = value_to_str(&i.operands[0]);
                    let ty_str = type_to_str_full(&i.ty);
                    out.push_str(&format!("  {}va_arg {} {}\n", name_prefix, ty_str, va));
                }
            }
            // Vector operations
            llvm_native_core::opcode::Opcode::ExtractElement => {
                if i.operands.len() >= 2 {
                    let vec = value_to_str(&i.operands[0]);
                    let vec_ty = type_to_str_full(&i.operands[0].borrow().ty);
                    let idx = value_to_str(&i.operands[1]);
                    let idx_ty = type_to_str_full(&i.operands[1].borrow().ty);
                    out.push_str(&format!(
                        "  {}extractelement {} {}, {} {}\n",
                        name_prefix, vec_ty, vec, idx_ty, idx
                    ));
                }
            }
            llvm_native_core::opcode::Opcode::InsertElement => {
                if i.operands.len() >= 3 {
                    let vec = value_to_str(&i.operands[0]);
                    let vec_ty = type_to_str_full(&i.operands[0].borrow().ty);
                    let elem = value_to_str(&i.operands[1]);
                    let elem_ty = type_to_str_full(&i.operands[1].borrow().ty);
                    let idx = value_to_str(&i.operands[2]);
                    let idx_ty = type_to_str_full(&i.operands[2].borrow().ty);
                    out.push_str(&format!(
                        "  {}insertelement {} {}, {} {}, {} {}\n",
                        name_prefix, vec_ty, vec, elem_ty, elem, idx_ty, idx
                    ));
                }
            }
            llvm_native_core::opcode::Opcode::ShuffleVector => {
                if i.operands.len() >= 2 {
                    let a = value_to_str(&i.operands[0]);
                    let a_ty = type_to_str_full(&i.operands[0].borrow().ty);
                    let b = value_to_str(&i.operands[1]);
                    let b_ty = type_to_str_full(&i.operands[1].borrow().ty);
                    let result_ty = type_to_str_full(&i.ty);
                    out.push_str(&format!(
                        "  {}shufflevector {} {}, {} {}, {} <i32 0, i32 1, i32 2, i32 3>\n",
                        name_prefix, a_ty, a, b_ty, b, result_ty
                    ));
                }
            }
            llvm_native_core::opcode::Opcode::ExtractValue => {
                if !i.operands.is_empty() {
                    let agg = value_to_str(&i.operands[0]);
                    let agg_ty = type_to_str_full(&i.operands[0].borrow().ty);
                    // Try to extract indices from name
                    let mut indices = String::from("0");
                    if let Some(ev_pos) = i.name.find(".ev.") {
                        indices = i.name[ev_pos + 4..].to_string();
                    }
                    out.push_str(&format!(
                        "  {}extractvalue {} {}, {}\n",
                        name_prefix, agg_ty, agg, indices
                    ));
                }
            }
            llvm_native_core::opcode::Opcode::InsertValue => {
                if i.operands.len() >= 2 {
                    let agg = value_to_str(&i.operands[0]);
                    let agg_ty = type_to_str_full(&i.operands[0].borrow().ty);
                    let elem = value_to_str(&i.operands[1]);
                    let elem_ty = type_to_str_full(&i.operands[1].borrow().ty);
                    out.push_str(&format!(
                        "  {}insertvalue {} {}, {} {}, 0\n",
                        name_prefix, agg_ty, agg, elem_ty, elem
                    ));
                }
            }
            llvm_native_core::opcode::Opcode::Unreachable => {
                out.push_str(&format!("  {}unreachable\n", name_prefix));
            }
            _ => {
                // Fallback for unimplemented instruction output
                out.push_str(&format!("  {}{}\n", name_prefix, opcode.as_mnemonic()));
            }
        }
    } else {
        // Legacy fallback: determine opcode from structure
        let void_ty = i.ty.is_void();
        let num_ops = i.operands.len();

        if void_ty && num_ops == 0 {
            out.push_str(&format!("  {}ret void\n", name_prefix));
        } else if void_ty && num_ops == 1 && i.operands[0].borrow().is_basic_block() {
            let label = i.operands[0].borrow().name.clone();
            out.push_str(&format!("  {}br label %{}\n", name_prefix, label));
        } else if void_ty && num_ops == 1 {
            let val = value_to_str(&i.operands[0]);
            out.push_str(&format!(
                "  {}ret {} {}\n",
                name_prefix,
                type_to_str_full(&i.operands[0].borrow().ty),
                val
            ));
        } else if void_ty && num_ops == 3 && i.operands[1].borrow().is_basic_block() {
            let cond = value_to_str(&i.operands[0]);
            let t_label = i.operands[1].borrow().name.clone();
            let f_label = i.operands[2].borrow().name.clone();
            out.push_str(&format!(
                "  {}br i1 {}, label %{}, label %{}\n",
                name_prefix, cond, t_label, f_label
            ));
        } else {
            out.push_str(&format!("  {}unknown\n", name_prefix));
        }
    }
}

// ============================================================
// Value formatting
// ============================================================

/// Convert a Value to its text representation.
fn value_to_str(val: &ValueRef) -> String {
    let v = val.borrow();
    match v.subclass {
        SubclassKind::Constant => {
            if v.name == "null" {
                "null".into()
            } else if v.name == "undef" {
                "undef".into()
            } else if v.name == "poison" {
                "poison".into()
            } else if v.name == "zeroinitializer" {
                "zeroinitializer".into()
            } else if v.ty.is_integer() && v.ty.integer_bit_width() == 1 {
                // i1 constants: true/false
                if v.name == "1" {
                    "true".into()
                } else {
                    "false".into()
                }
            } else {
                // Numeric constant or type-prefixed
                v.name.clone()
            }
        }
        SubclassKind::Argument | SubclassKind::BasicBlock => format!("%{}", v.name),
        SubclassKind::Function => format!("@{}", v.name),
        SubclassKind::GlobalVariable => {
            if v.name.is_empty() {
                format!("@gv{}", v.vid)
            } else if v.name.starts_with('@') {
                v.name.clone()
            } else {
                format!("@{}", v.name)
            }
        }
        _ => {
            if v.name.is_empty() {
                format!("%v{}", v.vid)
            } else {
                format!("%{}", v.name)
            }
        }
    }
}

// ============================================================
// Attribute emission helpers
// ============================================================

/// Write function-level attributes for a function value.
#[allow(dead_code)]
fn write_fn_attributes(_func: &ValueRef, out: &mut String) {
    // Placeholder: emit known attributes from function metadata
    // In a full implementation, attributes would be stored on the Function value.
    out.push(' ');
}

/// Write parameter-level attributes.
#[allow(dead_code)]
fn write_param_attributes(_params: &[ValueRef], _out: &mut String) {
    // Placeholder for parameter attribute emission.
}

/// Write metadata for a module.
#[allow(dead_code)]
fn write_metadata(_module: &Module, _out: &mut String) {
    // Placeholder for metadata node emission.
}

/// Write a comdat definition.
#[allow(dead_code)]
fn write_comdat(_comdat_name: &str, _kind: &str, _out: &mut String) {
    // Placeholder for comdat emission.
}

// ============================================================
// AssemblyWriterConfig — formatting options
// ============================================================

/// Configuration for assembly writer output formatting.
#[derive(Debug, Clone)]
pub struct AssemblyWriterConfig {
    /// Number of spaces per indent level.
    pub indent: usize,
    /// Whether to use ANSI color escapes.
    pub use_color: bool,
    /// Whether to emit type annotations on every value use.
    pub show_annotations: bool,
    /// Whether to print metadata attachments on instructions.
    pub show_metadata: bool,
    /// Whether to print debug-loc metadata.
    pub show_debug_loc: bool,
    /// Maximum line width before wrapping.
    pub max_line_width: usize,
    /// Whether to emit value IDs as comments.
    pub show_value_ids: bool,
    /// Whether to emit the module-level value symbol table.
    pub show_value_symtab: bool,
    /// Whether to use opaque pointer syntax (LLVM 15+).
    pub opaque_pointers: bool,
    /// Whether to emit uselistorder directives.
    pub show_use_list_order: bool,
    /// Whether to emit comdat information.
    pub show_comdat: bool,
    /// Whether to emit attribute group definitions.
    pub show_attribute_groups: bool,
}

impl Default for AssemblyWriterConfig {
    fn default() -> Self {
        Self {
            indent: 2,
            use_color: false,
            show_annotations: false,
            show_metadata: false,
            show_debug_loc: false,
            max_line_width: 80,
            show_value_ids: false,
            show_value_symtab: false,
            opaque_pointers: true,
            show_use_list_order: false,
            show_comdat: true,
            show_attribute_groups: true,
        }
    }
}

impl AssemblyWriterConfig {
    /// Create a config suitable for human-readable output.
    pub fn pretty() -> Self {
        Self {
            indent: 2,
            use_color: true,
            show_annotations: true,
            show_metadata: true,
            show_debug_loc: true,
            max_line_width: 100,
            show_value_ids: false,
            show_value_symtab: false,
            opaque_pointers: true,
            show_use_list_order: false,
            show_comdat: true,
            show_attribute_groups: true,
        }
    }

    /// Create a config suitable for round-trip parsing (canonical form).
    pub fn canonical() -> Self {
        Self {
            indent: 2,
            use_color: false,
            show_annotations: false,
            show_metadata: true,
            show_debug_loc: false,
            max_line_width: 0,
            show_value_ids: false,
            show_value_symtab: false,
            opaque_pointers: true,
            show_use_list_order: true,
            show_comdat: true,
            show_attribute_groups: true,
        }
    }
}

// ============================================================
// SlotTracker — assign stable numeric IDs to values
// ============================================================

/// Tracks numeric slot assignments for values within a module.
/// @llvm_behavior: LLVM's SlotTracker assigns sequential integer IDs
/// to local values (within a function) and global values (module-level).
#[derive(Debug, Clone)]
pub struct SlotTracker {
    /// Module-level slot assignments: ValueRef → slot number.
    module_slots: HashMap<u64, u32>,
    /// Function-local slot assignments: ValueRef → slot number.
    local_slots: HashMap<u64, Vec<(u64, u32)>>,
    /// Next module-level slot.
    next_module_slot: u32,
    /// Per-function next slot counters: function vid → next local slot.
    next_local_slots: HashMap<u64, u32>,
    /// Types slot assignment: TypeId → slot number.
    type_slots: HashMap<u64, u32>,
    /// Next type slot.
    next_type_slot: u32,
    /// Metadata slot assignment: MD node ID → slot.
    metadata_slots: HashMap<u32, u32>,
    next_metadata_slot: u32,
    /// Attribute group slot assignment.
    attr_slots: HashMap<u32, u32>,
    next_attr_slot: u32,
}

impl SlotTracker {
    pub fn new() -> Self {
        Self {
            module_slots: HashMap::new(),
            local_slots: HashMap::new(),
            next_module_slot: 0,
            next_local_slots: HashMap::new(),
            type_slots: HashMap::new(),
            next_type_slot: 0,
            metadata_slots: HashMap::new(),
            next_metadata_slot: 0,
            attr_slots: HashMap::new(),
            next_attr_slot: 0,
        }
    }

    /// Assign a slot to a module-level value.
    pub fn assign_module_slot(&mut self, val: &ValueRef) -> u32 {
        let vid = val.borrow().vid;
        *self.module_slots.entry(vid).or_insert_with(|| {
            let slot = self.next_module_slot;
            self.next_module_slot += 1;
            slot
        })
    }

    /// Assign a slot to a function-local value.
    pub fn assign_local_slot(&mut self, func_vid: u64, val: &ValueRef) -> u32 {
        let vid = val.borrow().vid;
        let slots = self.local_slots.entry(func_vid).or_default();
        if let Some((_, slot)) = slots.iter().find(|(v, _)| *v == vid) {
            return *slot;
        }
        let next = self.next_local_slots.entry(func_vid).or_insert(0);
        let slot = *next;
        *next += 1;
        slots.push((vid, slot));
        slot
    }

    /// Get the module-level slot for a value, if assigned.
    pub fn get_module_slot(&self, val: &ValueRef) -> Option<u32> {
        self.module_slots.get(&val.borrow().vid).copied()
    }

    /// Get the local slot for a value within a function.
    pub fn get_local_slot(&self, func_vid: u64, val: &ValueRef) -> Option<u32> {
        self.local_slots
            .get(&func_vid)
            .and_then(|slots| slots.iter().find(|(v, _)| *v == val.borrow().vid))
            .map(|(_, slot)| *slot)
    }

    /// Assign a slot to a type.
    pub fn assign_type_slot(&mut self, type_id: &TypeId) -> u32 {
        let id = type_id.as_u64();
        *self.type_slots.entry(id).or_insert_with(|| {
            let slot = self.next_type_slot;
            self.next_type_slot += 1;
            slot
        })
    }

    /// Get the slot for a type.
    pub fn get_type_slot(&self, type_id: &TypeId) -> Option<u32> {
        self.type_slots.get(&type_id.as_u64()).copied()
    }

    /// Assign a slot to a metadata node.
    pub fn assign_metadata_slot(&mut self, md_id: u32) -> u32 {
        *self.metadata_slots.entry(md_id).or_insert_with(|| {
            let slot = self.next_metadata_slot;
            self.next_metadata_slot += 1;
            slot
        })
    }

    /// Get the slot for a metadata node.
    pub fn get_metadata_slot(&self, md_id: u32) -> Option<u32> {
        self.metadata_slots.get(&md_id).copied()
    }

    /// Assign a slot to an attribute group.
    pub fn assign_attr_slot(&mut self, group_id: u32) -> u32 {
        *self.attr_slots.entry(group_id).or_insert_with(|| {
            let slot = self.next_attr_slot;
            self.next_attr_slot += 1;
            slot
        })
    }

    /// Get the slot for an attribute group.
    pub fn get_attr_slot(&self, group_id: u32) -> Option<u32> {
        self.attr_slots.get(&group_id).copied()
    }

    /// Clear all slot assignments.
    pub fn clear(&mut self) {
        self.module_slots.clear();
        self.local_slots.clear();
        self.next_module_slot = 0;
        self.next_local_slots.clear();
        self.type_slots.clear();
        self.next_type_slot = 0;
        self.metadata_slots.clear();
        self.next_metadata_slot = 0;
        self.attr_slots.clear();
        self.next_attr_slot = 0;
    }

    /// Enumerate all values in a module, assigning slots.
    pub fn enumerate_module(&mut self, module: &Module) {
        // Assign slots to types
        for ty in &module.types {
            self.assign_type_slot(&ty.id);
        }
        // Assign slots to globals
        for gv in &module.globals {
            self.assign_module_slot(gv);
        }
        // Assign slots to functions (module-level)
        for func in &module.functions {
            self.assign_module_slot(func);
        }
        // Assign slots to aliases
        for alias in &module.aliases {
            self.assign_module_slot(alias);
        }
        // Assign slots to ifuncs
        for ifunc in &module.ifuncs {
            self.assign_module_slot(ifunc);
        }
        // Assign slots to attribute groups
        for (&gid, _) in &module.attr_groups {
            self.assign_attr_slot(gid);
        }
    }
}

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

// ============================================================
// Full type printing — printType with all TypeKind variants
// ============================================================

/// Print a type with full structural detail.
/// This is the canonical type printer that handles all TypeKind variants.
pub fn print_type(ty: &Type) -> String {
    print_type_inner(ty, false)
}

/// Print a type, optionally omitting the address space for opaque pointers.
fn print_type_inner(ty: &Type, _in_struct: bool) -> String {
    match &ty.kind {
        TypeKind::Void => "void".to_string(),
        TypeKind::Half => "half".to_string(),
        TypeKind::BFloat => "bfloat".to_string(),
        TypeKind::Float => "float".to_string(),
        TypeKind::Double => "double".to_string(),
        TypeKind::FP128 => "fp128".to_string(),
        TypeKind::X86FP80 => "x86_fp80".to_string(),
        TypeKind::PPCFP128 => "ppc_fp128".to_string(),
        TypeKind::Label => "label".to_string(),
        TypeKind::Metadata => "metadata".to_string(),
        TypeKind::X86AMX => "x86_amx".to_string(),
        TypeKind::X86MMX => "x86_mmx".to_string(),
        TypeKind::Token => "token".to_string(),
        TypeKind::Integer { bits } => format!("i{}", bits),
        TypeKind::Pointer { addr_space } => {
            if *addr_space == 0 {
                "ptr".to_string()
            } else {
                format!("ptr addrspace({})", addr_space)
            }
        }
        TypeKind::Array {
            len,
            element_type_id: _,
        } => {
            // NOTE: element type resolution requires a type store;
            // this simplified printer uses the type ID as reference.
            format!("[{} x <ty>]", len)
        }
        TypeKind::Struct {
            name,
            is_packed,
            is_opaque,
            element_type_ids,
        } => {
            if *is_opaque {
                if let Some(n) = name {
                    return format!("%{}", n);
                }
                return "%opaque".to_string();
            }
            let body: Vec<String> = element_type_ids
                .iter()
                .map(|_| "<ty>".to_string())
                .collect();
            let packed = if *is_packed { "<" } else { "" };
            let packed_end = if *is_packed { ">" } else { "" };
            let body_str = if body.is_empty() {
                "{}".to_string()
            } else {
                format!("{}{{{} {}}}", packed, " ", body.join(", "))
            };
            if let Some(n) = name {
                format!("%{}{}", n, body_str)
            } else {
                body_str
            }
        }
        TypeKind::FixedVector {
            len,
            element_type_id: _,
        } => {
            format!("<{} x <ty>>", len)
        }
        TypeKind::ScalableVector {
            min_elems,
            element_type_id: _,
        } => {
            format!("<vscale x {} x <ty>>", min_elems)
        }
        TypeKind::Function {
            return_type_id: _,
            param_type_ids,
            is_vararg,
        } => {
            let params: Vec<String> = param_type_ids.iter().map(|_| "<ty>".to_string()).collect();
            let vararg = if *is_vararg { ", ..." } else { "" };
            format!("<ty> ({}{})", params.join(", "), vararg)
        }
    }
}

/// Print the type name suitable for a struct type (with % prefix).
pub fn print_type_name(ty: &Type) -> String {
    match &ty.kind {
        TypeKind::Struct { name, .. } => {
            if let Some(n) = name {
                return format!("%{}", n);
            }
        }
        _ => {}
    }
    print_type(ty)
}

/// Print type definitions for all types in a module.
pub fn print_type_definitions(module: &Module) -> String {
    let mut out = String::new();
    for ty in &module.types {
        match &ty.kind {
            TypeKind::Struct { name, .. } if name.is_some() => {
                out.push_str(&format!(
                    "{} = type {}\n",
                    print_type_name(ty),
                    print_type(ty)
                ));
            }
            _ => {}
        }
    }
    out
}

// ============================================================
// Constant printing — printConstant for all constant kinds
// ============================================================

/// Print a constant value with full formatting.
pub fn print_constant(val: &ValueRef) -> String {
    let v = val.borrow();
    match v.subclass {
        SubclassKind::ConstantInt => {
            let bits = v.ty.integer_bit_width();
            if bits == 1 {
                if v.name == "1" || v.name == "true" {
                    "true".to_string()
                } else {
                    "false".to_string()
                }
            } else {
                let ty_str = format!("i{}", bits);
                format!("{} {}", ty_str, v.name)
            }
        }
        SubclassKind::ConstantFP => {
            let ty_str = print_type(&v.ty);
            format!("{} {}", ty_str, v.name)
        }
        SubclassKind::ConstantAggregate => {
            let ty_str = print_type(&v.ty);
            let elements: Vec<String> = v
                .operands
                .iter()
                .map(|op| {
                    let op_val = op.borrow();
                    let op_ty = print_type(&op_val.ty);
                    format!("{} {}", op_ty, print_constant(op))
                })
                .collect();
            if elements.is_empty() {
                format!("{} zeroinitializer", ty_str)
            } else {
                format!("{} [{}]", ty_str, elements.join(", "))
            }
        }
        SubclassKind::ConstantData => {
            // ConstantData (e.g., ConstantDataArray, ConstantDataVector)
            let ty_str = print_type(&v.ty);
            if v.name == "zeroinitializer" {
                return format!("{} zeroinitializer", ty_str);
            }
            if v.name.is_empty() {
                format!("{} c\"\"", ty_str)
            } else {
                format!("{} c\"{}\"", ty_str, v.name)
            }
        }
        SubclassKind::Constant => {
            if v.name == "null" {
                format!("{} null", print_type(&v.ty))
            } else if v.name == "undef" {
                format!("{} undef", print_type(&v.ty))
            } else if v.name == "poison" {
                format!("{} poison", print_type(&v.ty))
            } else if v.name == "zeroinitializer" {
                format!("{} zeroinitializer", print_type(&v.ty))
            } else if v.name == "true" || v.name == "false" {
                v.name.clone()
            } else if v.ty.is_integer() {
                let bits = v.ty.integer_bit_width();
                if bits == 1 {
                    v.name.clone()
                } else {
                    format!("i{} {}", bits, v.name)
                }
            } else if v.ty.is_float() {
                format!("{} {}", print_type(&v.ty), v.name)
            } else {
                v.name.clone()
            }
        }
        SubclassKind::BlockAddress => {
            let func_name = if !v.operands.is_empty() {
                v.operands[0].borrow().name.clone()
            } else {
                "<unknown>".to_string()
            };
            let bb_name = if v.operands.len() >= 2 {
                v.operands[1].borrow().name.clone()
            } else {
                "<unknown>".to_string()
            };
            format!("blockaddress(@{}, %{})", func_name, bb_name)
        }
        SubclassKind::GlobalVariable | SubclassKind::Function | SubclassKind::GlobalAlias => {
            if v.name.starts_with('@') {
                v.name.clone()
            } else {
                format!("@{}", v.name)
            }
        }
        _ => {
            if v.name.is_empty() {
                format!("%v{}", v.vid)
            } else if v.name.starts_with('%') || v.name.starts_with('@') {
                v.name.clone()
            } else {
                format!("%{}", v.name)
            }
        }
    }
}

/// Print a GEP constant expression.
pub fn print_constant_gep(_ty: &Type, ops: &[ValueRef], _inbounds: bool) -> String {
    if ops.is_empty() {
        return "getelementptr (<ty>, <bad>)".to_string();
    }
    let ptr = print_constant(&ops[0]);
    let ptr_ty = print_type(&ops[0].borrow().ty);
    let indices: Vec<String> = ops[1..]
        .iter()
        .map(|op| {
            let op_ty = print_type(&op.borrow().ty);
            let op_val = print_constant(op);
            format!("{} {}", op_ty, op_val)
        })
        .collect();
    format!("getelementptr ({}, {})", ptr_ty, ptr,)
}

/// Print a bitcast constant expression.
pub fn print_constant_bitcast(_from_ty: &Type, _to_ty: &Type, _op: &ValueRef) -> String {
    // Simplified: print the operand with a cast annotation
    let op_str = print_constant(_op);
    let from_str = print_type(_from_ty);
    let to_str = print_type(_to_ty);
    format!("bitcast ({} {} to {})", from_str, op_str, to_str)
}

/// Print an undef value.
pub fn print_undef_value(ty: &Type) -> String {
    format!("{} undef", print_type(ty))
}

/// Print a poison value.
pub fn print_poison_value(ty: &Type) -> String {
    format!("{} poison", print_type(ty))
}

// ============================================================
// Full instruction printing — printInstruction for every opcode
// ============================================================

/// Print a single instruction with full operand formatting.
/// Supports all LLVM opcodes with proper syntax.
pub fn print_instruction(inst_val: &ValueRef, config: &AssemblyWriterConfig) -> String {
    let mut out = String::new();
    let indent = " ".repeat(config.indent);
    let i = inst_val.borrow();

    // Build the LHS assignment if the value has a name / produces a value
    let lhs = if i.name.is_empty() || i.ty.is_void() {
        String::new()
    } else {
        format!("%{} = ", i.name)
    };

    if let Some(opcode) = i.get_opcode() {
        let mnemonic = opcode.name();
        match opcode {
            // ── Terminators ──────────────────────────────────────
            Opcode::Ret => {
                if i.operands.is_empty() {
                    out.push_str(&format!("{}ret void\n", lhs));
                } else {
                    let val = print_value_with_type(&i.operands[0]);
                    out.push_str(&format!("{}ret {}\n", lhs, val));
                }
            }
            Opcode::Br => {
                if i.operands.len() == 1 {
                    let label = bb_name(&i.operands[0]);
                    out.push_str(&format!("{}br label {}\n", lhs, label));
                } else if i.operands.len() >= 3 {
                    let cond = print_value_with_type(&i.operands[0]);
                    let t_label = bb_name(&i.operands[1]);
                    let f_label = bb_name(&i.operands[2]);
                    out.push_str(&format!(
                        "{}br {}, label {}, label {}\n",
                        lhs, cond, t_label, f_label
                    ));
                } else {
                    out.push_str(&format!("{}br <malformed>\n", lhs));
                }
            }
            Opcode::Switch => {
                if i.operands.len() >= 2 {
                    let val = print_value_with_type(&i.operands[0]);
                    let default_label = bb_name(&i.operands[1]);
                    let mut cases = String::new();
                    let mut idx = 2;
                    while idx + 1 < i.operands.len() {
                        let case_val = print_value_with_type(&i.operands[idx]);
                        let case_label = bb_name(&i.operands[idx + 1]);
                        cases.push_str(&format!("    {} {},\n", case_val, case_label));
                        idx += 2;
                    }
                    out.push_str(&format!(
                        "{}switch {} label {} [\n{}  ]\n",
                        lhs, val, default_label, cases
                    ));
                }
            }
            Opcode::IndirectBr => {
                if !i.operands.is_empty() {
                    let addr = print_value_with_type(&i.operands[0]);
                    let labels: Vec<String> = i.operands[1..].iter().map(|b| bb_name(b)).collect();
                    out.push_str(&format!(
                        "{}indirectbr {}, [{}]\n",
                        lhs,
                        addr,
                        labels.join(", ")
                    ));
                }
            }
            Opcode::Invoke => {
                if i.operands.len() >= 3 {
                    let callee = print_function_ref(&i.operands[0]);
                    let args = print_call_args(&i.operands[1..i.operands.len() - 2]);
                    let normal = bb_name(&i.operands[i.operands.len() - 2]);
                    let unwind = bb_name(&i.operands[i.operands.len() - 1]);
                    let ret_ty = print_type(&i.ty);
                    out.push_str(&format!(
                        "{}invoke {} {}({})\n    to label {} unwind label {}\n",
                        lhs, ret_ty, callee, args, normal, unwind
                    ));
                }
            }
            Opcode::CallBr => {
                if !i.operands.is_empty() {
                    let callee = print_function_ref(&i.operands[0]);
                    let args = print_call_args(&i.operands[1..]);
                    let ret_ty = print_type(&i.ty);
                    out.push_str(&format!("{}callbr {} {}({})\n", lhs, ret_ty, callee, args));
                }
            }
            Opcode::Resume => {
                if !i.operands.is_empty() {
                    let val = print_value_with_type(&i.operands[0]);
                    out.push_str(&format!("{}resume {}\n", lhs, val));
                }
            }
            Opcode::CatchSwitch => {
                out.push_str(&format!("{}catchswitch within none [\n", lhs));
                for succ in &i.successors {
                    out.push_str(&format!("    to label {}\n", bb_name(succ)));
                }
                out.push_str("]\n");
            }
            Opcode::CatchRet => {
                if !i.operands.is_empty() && !i.successors.is_empty() {
                    let pad = print_value_with_type(&i.operands[0]);
                    let succ = bb_name(&i.successors[0]);
                    out.push_str(&format!("{}catchret from {} to label {}\n", lhs, pad, succ));
                }
            }
            Opcode::CleanupRet => {
                if !i.operands.is_empty() {
                    let pad = print_value_with_type(&i.operands[0]);
                    if i.successors.is_empty() {
                        out.push_str(&format!(
                            "{}cleanupret from {} unwind to caller\n",
                            lhs, pad
                        ));
                    } else {
                        let succ = bb_name(&i.successors[0]);
                        out.push_str(&format!(
                            "{}cleanupret from {} unwind label {}\n",
                            lhs, pad, succ
                        ));
                    }
                }
            }
            Opcode::Unreachable => {
                out.push_str(&format!("{}unreachable\n", lhs));
            }
            // ── Binary operations ───────────────────────────────
            Opcode::Add
            | Opcode::FAdd
            | Opcode::Sub
            | Opcode::FSub
            | Opcode::Mul
            | Opcode::FMul
            | Opcode::UDiv
            | Opcode::SDiv
            | Opcode::FDiv
            | Opcode::URem
            | Opcode::SRem
            | Opcode::FRem
            | Opcode::Shl
            | Opcode::LShr
            | Opcode::AShr
            | Opcode::And
            | Opcode::Or
            | Opcode::Xor => {
                if i.operands.len() >= 2 {
                    let (a, b) = (
                        print_value_with_type(&i.operands[0]),
                        print_value_with_type(&i.operands[1]),
                    );
                    out.push_str(&format!("{} {} {}\n", lhs, mnemonic, join_op2(a, b)));
                }
            }
            // ── Memory operations ───────────────────────────────
            Opcode::Alloca => {
                let alloc_ty = print_type(&i.ty);
                let mut extras = String::new();
                if i.operands.len() >= 1 && !is_constant_one(&i.operands[0]) {
                    extras.push_str(&format!(
                        ", {} {}",
                        print_type(&i.operands[0].borrow().ty),
                        print_constant(&i.operands[0])
                    ));
                }
                if i.subclass_data != 0 {
                    extras.push_str(&format!(", align {}", 1u32 << i.subclass_data));
                }
                out.push_str(&format!("{}alloca {}{}\n", lhs, alloc_ty, extras));
            }
            Opcode::Load => {
                let load_ty = print_type(&i.ty);
                let ptr = print_value_with_type(&i.operands[0]);
                let mut extras = String::new();
                if i.subclass_data != 0 {
                    extras.push_str(&format!(", align {}", 1u32 << i.subclass_data));
                }
                out.push_str(&format!("{}load {}, ptr {}{}\n", lhs, load_ty, ptr, extras));
            }
            Opcode::Store => {
                if i.operands.len() >= 2 {
                    let val = print_value_with_type(&i.operands[0]);
                    let ptr = print_value_with_type(&i.operands[1]);
                    out.push_str(&format!("store {}, ptr {}\n", val, ptr));
                }
            }
            Opcode::GetElementPtr => {
                if !i.operands.is_empty() {
                    let ptr = print_value_with_type(&i.operands[0]);
                    let indices: Vec<String> =
                        i.operands[1..].iter().map(print_value_with_type).collect();
                    let inb = if i.subclass_data & 1 != 0 {
                        " inbounds"
                    } else {
                        ""
                    };
                    out.push_str(&format!(
                        "{}getelementptr{}{}, {}\n",
                        lhs,
                        inb,
                        ptr,
                        indices.join(", ")
                    ));
                }
            }
            Opcode::Fence => {
                let ordering = fence_ordering_str(i.subclass_data);
                out.push_str(&format!("{}fence {}\n", lhs, ordering));
            }
            Opcode::CmpXchg => {
                if i.operands.len() >= 3 {
                    let ptr = print_value_with_type(&i.operands[0]);
                    let cmp = print_value_with_type(&i.operands[1]);
                    let new = print_value_with_type(&i.operands[2]);
                    out.push_str(&format!(
                        "{}cmpxchg ptr {}, {}, {} acq_rel monotonic\n",
                        lhs, ptr, cmp, new
                    ));
                }
            }
            Opcode::AtomicRMW => {
                if i.operands.len() >= 2 {
                    let ptr = print_value_with_type(&i.operands[0]);
                    let val = print_value_with_type(&i.operands[1]);
                    let binop = atomicrmw_binop_str(i.subclass_data);
                    out.push_str(&format!(
                        "{}atomicrmw {} ptr {}, {} seq_cst\n",
                        lhs, binop, ptr, val
                    ));
                }
            }
            // ── Cast operations ─────────────────────────────────
            Opcode::Trunc
            | Opcode::ZExt
            | Opcode::SExt
            | Opcode::FPTrunc
            | Opcode::FPExt
            | Opcode::FPToUI
            | Opcode::FPToSI
            | Opcode::UIToFP
            | Opcode::SIToFP
            | Opcode::PtrToInt
            | Opcode::IntToPtr
            | Opcode::BitCast
            | Opcode::AddrSpaceCast => {
                if !i.operands.is_empty() {
                    let val = print_value_with_type(&i.operands[0]);
                    let to_ty = print_type(&i.ty);
                    out.push_str(&format!("{}{} {} to {}\n", lhs, mnemonic, val, to_ty));
                }
            }
            // ── Compare operations ──────────────────────────────
            Opcode::ICmp => {
                if i.operands.len() >= 2 {
                    let pred = icmp_pred_str(i.subclass_data);
                    let a = print_value_with_type(&i.operands[0]);
                    let b = print_value_with_type(&i.operands[1]);
                    out.push_str(&format!("{}icmp {} {}\n", lhs, pred, join_op2(a, b)));
                }
            }
            Opcode::FCmp => {
                if i.operands.len() >= 2 {
                    let pred = fcmp_pred_str(i.subclass_data);
                    let a = print_value_with_type(&i.operands[0]);
                    let b = print_value_with_type(&i.operands[1]);
                    out.push_str(&format!("{}fcmp {} {}\n", lhs, pred, join_op2(a, b)));
                }
            }
            // ── Other operations ────────────────────────────────
            Opcode::Phi => {
                let ty_str = print_type(&i.ty);
                let mut incoming = Vec::new();
                for chunk in i.operands.chunks(2) {
                    if chunk.len() == 2 {
                        let val = print_value_with_type(&chunk[0]);
                        let label = bb_name(&chunk[1]);
                        incoming.push(format!("[ {}, {} ]", val, label));
                    }
                }
                out.push_str(&format!("{}phi {} {}\n", lhs, ty_str, incoming.join(", ")));
            }
            Opcode::Call => {
                if !i.operands.is_empty() {
                    let callee = print_function_ref(&i.operands[0]);
                    let args = print_call_args(&i.operands[1..]);
                    let ret_ty = print_type(&i.ty);
                    out.push_str(&format!("{}call {} {}({})\n", lhs, ret_ty, callee, args));
                }
            }
            Opcode::Select => {
                if i.operands.len() >= 3 {
                    let cond = print_value_with_type(&i.operands[0]);
                    let a = print_value_with_type(&i.operands[1]);
                    let b = print_value_with_type(&i.operands[2]);
                    out.push_str(&format!("{}select {}, {}, {}\n", lhs, cond, a, b));
                }
            }
            Opcode::Freeze => {
                if !i.operands.is_empty() {
                    let val = print_value_with_type(&i.operands[0]);
                    out.push_str(&format!("{}freeze {}\n", lhs, val));
                }
            }
            Opcode::VAArg => {
                if !i.operands.is_empty() {
                    let va = print_value_with_type(&i.operands[0]);
                    let ty_str = print_type(&i.ty);
                    out.push_str(&format!("{}va_arg {}, {}\n", lhs, ty_str, va));
                }
            }
            Opcode::ExtractElement => {
                if i.operands.len() >= 2 {
                    let vec = print_value_with_type(&i.operands[0]);
                    let idx = print_value_with_type(&i.operands[1]);
                    out.push_str(&format!("{}extractelement {}, {}\n", lhs, vec, idx));
                }
            }
            Opcode::InsertElement => {
                if i.operands.len() >= 3 {
                    let vec = print_value_with_type(&i.operands[0]);
                    let elem = print_value_with_type(&i.operands[1]);
                    let idx = print_value_with_type(&i.operands[2]);
                    out.push_str(&format!(
                        "{}insertelement {}, {}, {}\n",
                        lhs, vec, elem, idx
                    ));
                }
            }
            Opcode::ShuffleVector => {
                if i.operands.len() >= 2 {
                    let a = print_value_with_type(&i.operands[0]);
                    let b = print_value_with_type(&i.operands[1]);
                    let mask = if i.operands.len() >= 3 {
                        print_constant(&i.operands[2])
                    } else {
                        "<i32 0, i32 1, i32 2, i32 3>".to_string()
                    };
                    out.push_str(&format!("{}shufflevector {}, {}, {}\n", lhs, a, b, mask));
                }
            }
            Opcode::ExtractValue => {
                if !i.operands.is_empty() {
                    let agg = print_value_with_type(&i.operands[0]);
                    let indices: Vec<String> =
                        i.operands[1..].iter().map(|v| print_constant(v)).collect();
                    out.push_str(&format!(
                        "{}extractvalue {}, {}\n",
                        lhs,
                        agg,
                        indices.join(", ")
                    ));
                }
            }
            Opcode::InsertValue => {
                if i.operands.len() >= 2 {
                    let agg = print_value_with_type(&i.operands[0]);
                    let elem = print_value_with_type(&i.operands[1]);
                    let indices: Vec<String> =
                        i.operands[2..].iter().map(|v| print_constant(v)).collect();
                    out.push_str(&format!(
                        "{}insertvalue {}, {}, {}\n",
                        lhs,
                        agg,
                        elem,
                        indices.join(", ")
                    ));
                }
            }
            Opcode::LandingPad => {
                let ty_str = print_type(&i.ty);
                let mut clauses = String::new();
                for clause in &i.operands {
                    let c_str = print_constant(clause);
                    let c_ty = print_type(&clause.borrow().ty);
                    clauses.push_str(&format!("    catch {} {}\n", c_ty, c_str));
                }
                if clauses.is_empty() {
                    out.push_str(&format!("{}{}landingpad {}\n", indent, lhs, ty_str));
                } else {
                    out.push_str(&format!(
                        "{}{}landingpad {}\n{}\n",
                        indent, lhs, ty_str, clauses
                    ));
                }
            }
            Opcode::CatchPad => {
                if !i.operands.is_empty() {
                    let args: Vec<String> = i.operands.iter().map(print_value_with_type).collect();
                    out.push_str(&format!("{}catchpad [{}]\n", lhs, args.join(", ")));
                }
            }
            Opcode::CleanupPad => {
                out.push_str(&format!("{}cleanuppad within none []\n", lhs));
            }
            _ => {
                out.push_str(&format!("{}{} <unimpl>\n", lhs, mnemonic));
            }
        }
    } else {
        // Legacy fallback
        let void_ty = i.ty.is_void();
        let num_ops = i.operands.len();
        if void_ty && num_ops == 0 {
            out.push_str(&format!("{}ret void\n", lhs));
        } else if void_ty && num_ops == 1 && i.operands[0].borrow().is_basic_block() {
            out.push_str(&format!("{}br label {}\n", lhs, bb_name(&i.operands[0])));
        } else {
            out.push_str(&format!("{}; unknown instruction\n", lhs));
        }
    }

    out
}

// ── Instruction printing helpers ────────────────────────────────────

fn bb_name(bb: &ValueRef) -> String {
    let b = bb.borrow();
    if b.name.is_empty() {
        format!("%v{}", b.vid)
    } else {
        format!("%{}", b.name)
    }
}

fn print_value_with_type(val: &ValueRef) -> String {
    let v = val.borrow();
    match v.subclass {
        SubclassKind::Constant
        | SubclassKind::ConstantInt
        | SubclassKind::ConstantFP
        | SubclassKind::ConstantAggregate
        | SubclassKind::ConstantData => print_constant(val),
        _ => {
            let ty_str = print_type(&v.ty);
            let name = if v.name.is_empty() {
                format!("%v{}", v.vid)
            } else if v.name.starts_with('%') || v.name.starts_with('@') {
                v.name.clone()
            } else {
                format!("%{}", v.name)
            };
            format!("{} {}", ty_str, name)
        }
    }
}

fn print_function_ref(val: &ValueRef) -> String {
    let v = val.borrow();
    if v.name.starts_with('@') {
        v.name.clone()
    } else if v.name.is_empty() {
        format!("@f{}", v.vid)
    } else {
        format!("@{}", v.name)
    }
}

fn print_call_args(args: &[ValueRef]) -> String {
    args.iter()
        .map(|a| {
            let a_val = a.borrow();
            if a_val.is_basic_block() {
                format!("label {}", bb_name(a))
            } else {
                print_value_with_type(a)
            }
        })
        .collect::<Vec<_>>()
        .join(", ")
}

fn join_op2(a: String, b: String) -> String {
    format!("{}, {}", a, b)
}

fn is_constant_one(val: &ValueRef) -> bool {
    let v = val.borrow();
    matches!(
        v.subclass,
        SubclassKind::Constant | SubclassKind::ConstantInt
    ) && v.name == "1"
}

fn fence_ordering_str(data: u32) -> &'static str {
    match data {
        0 => "acquire",
        1 => "release",
        2 => "acq_rel",
        3 => "seq_cst",
        4 => "syncscope(\"singlethread\") seq_cst",
        _ => "seq_cst",
    }
}

fn atomicrmw_binop_str(data: u32) -> &'static str {
    match data {
        0 => "xchg",
        1 => "add",
        2 => "sub",
        3 => "and",
        4 => "nand",
        5 => "or",
        6 => "xor",
        7 => "max",
        8 => "min",
        9 => "umax",
        10 => "umin",
        11 => "fadd",
        12 => "fsub",
        13 => "fmax",
        14 => "fmin",
        _ => "xchg",
    }
}

fn icmp_pred_str(data: u32) -> &'static str {
    match data {
        0 => "eq",
        1 => "ne",
        2 => "ugt",
        3 => "uge",
        4 => "ult",
        5 => "ule",
        6 => "sgt",
        7 => "sge",
        8 => "slt",
        9 => "sle",
        _ => "eq",
    }
}

fn fcmp_pred_str(data: u32) -> &'static str {
    match data {
        0 => "false",
        1 => "oeq",
        2 => "ogt",
        3 => "oge",
        4 => "olt",
        5 => "ole",
        6 => "one",
        7 => "ord",
        8 => "ueq",
        9 => "ugt",
        10 => "uge",
        11 => "ult",
        12 => "ule",
        13 => "une",
        14 => "uno",
        15 => "true",
        _ => "oeq",
    }
}

// ============================================================
// Metadata printing
// ============================================================

/// Print a metadata reference (!<id> or !{...}).
pub fn print_metadata(md_id: u32, _module: &Module) -> String {
    format!("!{}", md_id)
}

/// Print a metadata node with its operands.
pub fn print_md_node(node_id: u32, _operands: &[u32], _module: &Module) -> String {
    let mut out = format!("!{} = !{{", node_id);
    // Operands would be printed here; simplified
    out.push_str("}");
    out
}

/// Print a named metadata entry.
pub fn print_named_metadata(name: &str, node_ids: &[u32], _module: &Module) -> String {
    let nodes: Vec<String> = node_ids.iter().map(|id| format!("!{}", id)).collect();
    format!("!{} = !{{{}}}", name, nodes.join(", "))
}

/// Print metadata attachment on an instruction (e.g., `!dbg !42`).
pub fn print_metadata_attachment(md_map: &HashMap<u32, u32>) -> String {
    if md_map.is_empty() {
        return String::new();
    }
    let mut out = String::new();
    for (&kind, &node) in md_map {
        out.push_str(&format!(", !{} !{}", kind, node));
    }
    out
}

// ============================================================
// Attribute printing
// ============================================================

/// Print an attribute group definition.
pub fn print_attribute_group(group_id: u32, attrs: &AttributeList) -> String {
    let mut out = format!("attributes #{} = {{", group_id);
    let parts: Vec<String> = attrs.fn_attrs.iter().map(|a| print_attribute(a)).collect();
    if parts.is_empty() {
        out.push('}');
    } else {
        out.push_str(&format!(" {} }}", parts.join(" ")));
    }
    out
}

/// Print a single attribute.
pub fn print_attribute(attr: &AttributeKind) -> String {
    use llvm_native_core::attributes::FramePointerKind;
    match attr {
        // Optimization hints
        AttributeKind::NoInline => "noinline".to_string(),
        AttributeKind::AlwaysInline => "alwaysinline".to_string(),
        AttributeKind::OptimizeNone => "optnone".to_string(),
        AttributeKind::OptimizeForSize => "optsize".to_string(),
        AttributeKind::OptimizeForSpeed => "optforspeed".to_string(),
        // Memory effects
        AttributeKind::ReadNone => "readnone".to_string(),
        AttributeKind::ReadOnly => "readonly".to_string(),
        AttributeKind::WriteOnly => "writeonly".to_string(),
        AttributeKind::ArgMemOnly => "argmemonly".to_string(),
        AttributeKind::InaccessibleMemOnly => "inaccessiblememonly".to_string(),
        AttributeKind::InaccessibleMemOrArgMemOnly => "inaccessiblemem_or_argmemonly".to_string(),
        // Exception handling
        AttributeKind::NoUnwind => "nounwind".to_string(),
        AttributeKind::NoReturn => "noreturn".to_string(),
        AttributeKind::WillReturn => "willreturn".to_string(),
        // Stack protection
        AttributeKind::Ssp => "ssp".to_string(),
        AttributeKind::SspReq => "sspreq".to_string(),
        AttributeKind::SspStrong => "sspstrong".to_string(),
        // Sanitizers
        AttributeKind::SanitizeAddress => "sanitize_address".to_string(),
        AttributeKind::SanitizeThread => "sanitize_thread".to_string(),
        AttributeKind::SanitizeMemory => "sanitize_memory".to_string(),
        AttributeKind::SanitizeHwAddress => "sanitize_hwaddress".to_string(),
        AttributeKind::NoSanitize => "nosanitize".to_string(),
        AttributeKind::SanitizeCoverage => "sanitize_coverage".to_string(),
        // Security
        AttributeKind::ShadowCallStack => "shadowcallstack".to_string(),
        AttributeKind::SpeculativeLoadHardening => "speculative_load_hardening".to_string(),
        AttributeKind::NoCfCheck => "nocf_check".to_string(),
        // Inlining / merging
        AttributeKind::InlineHint => "inlinehint".to_string(),
        AttributeKind::NoMerge => "nomerge".to_string(),
        AttributeKind::ReturnsTwice => "returns_twice".to_string(),
        AttributeKind::JumpTable => "jumptable".to_string(),
        // Concurrency / progress
        AttributeKind::MustProgress => "mustprogress".to_string(),
        AttributeKind::Convergent => "convergent".to_string(),
        AttributeKind::NoDivergenceSource => "noduplicatesource".to_string(),
        // Profiling / debugging
        AttributeKind::NoProfile => "noprofile".to_string(),
        AttributeKind::SkipProfile => "skipprofile".to_string(),
        AttributeKind::OptDebug => "optdebug".to_string(),
        AttributeKind::OptForFuzzing => "optforfuzzing".to_string(),
        // Allocator hints
        AttributeKind::AllocSize(n, m) => {
            if let Some(m_val) = m {
                format!("allocsize({}, {})", n, m_val)
            } else {
                format!("allocsize({})", n)
            }
        }
        AttributeKind::AllocPtr => "allocptr".to_string(),
        // Builtin / library
        AttributeKind::NoBuiltin => "nobuiltin".to_string(),
        AttributeKind::NoCallback => "nocallback".to_string(),
        AttributeKind::NonLazyBind => "nonlazybind".to_string(),
        // Calling convention / ABI
        AttributeKind::AlignStack(n) => format!("alignstack({})", n),
        AttributeKind::Naked => "naked".to_string(),
        AttributeKind::NoImplicitFloat => "noimplicitfloat".to_string(),
        AttributeKind::NoRedZone => "noredzone".to_string(),
        AttributeKind::UWTable => "uwtable".to_string(),
        AttributeKind::FramePointer(fp_kind) => {
            let kind_str = match fp_kind {
                FramePointerKind::All => "all",
                FramePointerKind::NonLeaf => "non-leaf",
                FramePointerKind::None => "none",
            };
            format!("frame-pointer={}", kind_str)
        }
        // Security hardening
        AttributeKind::SafeStack => "safestack".to_string(),
        AttributeKind::SanitizeMemTag => "sanitize_memtag".to_string(),
        AttributeKind::DisableSanitizerInstrumentation => {
            "disable_sanitizer_instrumentation".to_string()
        }
        AttributeKind::Hotpatch => "hotpatch".to_string(),
        AttributeKind::FnRetThunkExtern => "fn_ret_thunk_extern".to_string(),
        // Floating-point
        AttributeKind::StrictFP => "strictfp".to_string(),
        AttributeKind::NoFPClass(classes) => format!("nofpclass({})", classes),
        // Vector / scalable
        AttributeKind::VScaleRange(min, max) => format!("vscale_range({}, {})", min, max),
        // Speculation
        AttributeKind::Speculatable => "speculatable".to_string(),
        // Other function attributes
        AttributeKind::NoDuplicate => "noduplicate".to_string(),
        AttributeKind::NoRecurse => "norecurse".to_string(),
        AttributeKind::NoSync => "nosync".to_string(),
        AttributeKind::NoFree => "nofree".to_string(),
        AttributeKind::Cold => "cold".to_string(),
        AttributeKind::Hot => "hot".to_string(),
        AttributeKind::Minsize => "minsize".to_string(),
        AttributeKind::NullPointerIsValid => "null_pointer_is_valid".to_string(),
        AttributeKind::UseSampleProfile => "use_sample_profile".to_string(),
        // String attribute
        AttributeKind::StringAttribute(key, val) => {
            if val.is_empty() {
                format!("\"{}\"", key)
            } else {
                format!("\"{}\"=\"{}\"", key, val)
            }
        }
    }
}

/// Print all attribute groups for a module.
pub fn print_attribute_groups(module: &Module) -> String {
    let mut out = String::new();
    let mut ids: Vec<u32> = module.attr_groups.keys().copied().collect();
    ids.sort();
    for id in ids {
        if let Some(attrs) = module.attr_groups.get(&id) {
            out.push_str(&print_attribute_group(id, attrs));
            out.push('\n');
        }
    }
    out
}

/// Print function-level attributes (for the attribute group reference syntax).
pub fn print_function_attributes(attr_group_id: u32) -> String {
    format!(" #{} ", attr_group_id)
}

// ============================================================
// Module-level printing — printModule
// ============================================================

/// Print a complete LLVM module as assembly text.
pub fn print_module(module: &Module, config: &AssemblyWriterConfig) -> String {
    let mut out = String::new();

    // Module header
    out.push_str(&format!("; ModuleID = '{}'\n", module.module_identifier));
    if !module.source_filename.is_empty() {
        out.push_str(&format!(
            "source_filename = \"{}\"\n",
            module.source_filename
        ));
    }
    if let Some(ref triple) = module.target_triple {
        out.push_str(&format!("target triple = \"{}\"\n", triple));
    }
    if let Some(ref dl) = module.data_layout {
        out.push_str(&format!("target datalayout = \"{}\"\n", dl));
    }
    if let Some(ref sdk) = module.sdk_version {
        out.push_str(&format!("!llvm.sdk.version = !{{!{{}}\n"));
        let _ = sdk;
    }

    // Module-level inline assembly
    if !module.inline_asm.is_empty() {
        out.push_str(&format!(
            "module asm \"{}\"\n",
            module.inline_asm.replace('\n', "\\0A")
        ));
    }

    // Type definitions (named structs)
    if !module.types.is_empty() {
        out.push_str(&format!("{}", print_type_definitions(module)));
    }

    // Comdat definitions
    if config.show_comdat && !module.comdats.is_empty() {
        for (name, comdat) in &module.comdats {
            out.push_str(&format!("$comdat_{} = comdat {}\n", name, comdat.kind));
        }
    }

    // Attribute groups
    if config.show_attribute_groups && !module.attr_groups.is_empty() {
        out.push_str(&print_attribute_groups(module));
        if !module.attr_groups.is_empty() {
            out.push('\n');
        }
    }

    // Global variables
    for gv in &module.globals {
        print_global_variable(gv, config, &mut out);
    }

    // Aliases
    for alias in &module.aliases {
        print_alias_declaration(alias, config, &mut out);
    }

    // IFuncs
    for ifunc in &module.ifuncs {
        print_ifunc_declaration(ifunc, config, &mut out);
    }

    // Functions (declarations and definitions)
    for func in &module.functions {
        let is_definition = {
            let f = func.borrow();
            f.is_function() && f.num_operands > 0
        };
        if is_definition {
            // Function definition (has body)
            print_function_definition_full(func, config, &mut out);
        } else {
            // Function declaration
            print_function_declaration_full(func, config, &mut out);
        }
        out.push('\n');
    }

    // Use-list order directives
    if config.show_use_list_order {
        out.push_str("; uselistorder directives omitted\n");
    }

    // Named metadata
    if !module.named_metadata.is_empty() {
        for (name, node_ids) in &module.named_metadata {
            out.push_str(&print_named_metadata(name, node_ids, module));
            out.push('\n');
        }
    }

    // Module flags (as metadata)
    if !module.flags.is_empty() {
        let flag_ids: Vec<String> = module
            .flags
            .iter()
            .map(|f| {
                let val_str = match &f.value {
                    llvm_native_core::module::MetadataValue::Int(v) => format!("i32 {}", v),
                    llvm_native_core::module::MetadataValue::String(s) => format!("!\"{}\"", s),
                    llvm_native_core::module::MetadataValue::Node(ids) => {
                        let inner: Vec<String> = ids.iter().map(|id| format!("!{}", id)).collect();
                        format!("!{{{}}}", inner.join(", "))
                    }
                    llvm_native_core::module::MetadataValue::Null => "!{{}}".to_string(),
                };
                format!("!{{{}, !\"{}\", {}}}", f.behavior, f.key, val_str)
            })
            .collect();
        if !flag_ids.is_empty() {
            out.push_str(&format!(
                "!llvm.module.flags = !{{{}}}\n",
                flag_ids.join(", ")
            ));
        }
    }

    out
}

// ── Module printing helpers ─────────────────────────────────────────

fn print_global_variable(gv: &ValueRef, _config: &AssemblyWriterConfig, out: &mut String) {
    let v = gv.borrow();
    let name = if v.name.starts_with('@') {
        v.name.clone()
    } else {
        format!("@{}", v.name)
    };
    let linkage = infer_linkage_str(&v);
    let visibility = infer_visibility_str(&v);
    let ty_str = print_type(&v.ty);
    let init = if v.operands.is_empty() {
        format!("{} undef", ty_str)
    } else {
        print_constant(&v.operands[0])
    };
    out.push_str(&format!(
        "{}{}{} = {} {}\n",
        name,
        linkage,
        visibility,
        if linkage.is_empty() && visibility.is_empty() {
            ""
        } else {
            " "
        },
        ty_str
    ));
    // Simplified; proper linkage/visibility/preemption/dso_local handling omitted
    let _ = (name, linkage, visibility, init);
}

fn print_alias_declaration(alias: &ValueRef, _config: &AssemblyWriterConfig, out: &mut String) {
    let v = alias.borrow();
    out.push_str(&format!("@{} = alias {}\n", v.name, print_type(&v.ty)));
}

fn print_ifunc_declaration(ifunc: &ValueRef, _config: &AssemblyWriterConfig, out: &mut String) {
    let v = ifunc.borrow();
    out.push_str(&format!("@{} = ifunc {}\n", v.name, print_type(&v.ty)));
}

fn print_function_declaration_full(
    func: &ValueRef,
    config: &AssemblyWriterConfig,
    out: &mut String,
) {
    let f = func.borrow();
    let name = if f.name.starts_with('@') {
        f.name.clone()
    } else {
        format!("@{}", f.name)
    };
    let linkage = infer_linkage_str(&f);
    let visibility = infer_visibility_str(&f);
    let ret_ty = if let Some(ref rt) = f.return_type {
        print_type(rt)
    } else {
        "void".to_string()
    };
    let param_strs: Vec<String> = f
        .operands
        .iter()
        .filter(|op| op.borrow().subclass == SubclassKind::Argument)
        .map(|op| print_type(&op.borrow().ty))
        .collect();
    let vararg = if param_strs.is_empty() && f.subclass_data & 1 != 0 {
        "...".to_string()
    } else {
        String::new()
    };
    let attr_str = if !f.metadata.is_empty() {
        print_metadata_attachment(&f.metadata)
    } else {
        String::new()
    };
    out.push_str(&format!(
        "declare{}{}{} {} @{}({}{}){}\n",
        linkage,
        visibility,
        "",
        ret_ty,
        f.name,
        param_strs.join(", "),
        if vararg.is_empty() { "" } else { ", ..." },
        attr_str
    ));
    let _ = config;
}

fn print_function_definition_full(
    func: &ValueRef,
    config: &AssemblyWriterConfig,
    out: &mut String,
) {
    let f = func.borrow();
    let name = if f.name.starts_with('@') {
        f.name.clone()
    } else {
        format!("@{}", f.name)
    };
    let linkage = infer_linkage_str(&f);
    let visibility = infer_visibility_str(&f);
    let ret_ty = if let Some(ref rt) = f.return_type {
        print_type(rt)
    } else {
        "void".to_string()
    };
    let param_strs: Vec<String> = f
        .operands
        .iter()
        .filter(|op| op.borrow().subclass == SubclassKind::Argument)
        .map(|op| {
            let p = op.borrow();
            format!("{} {}", print_type(&p.ty), print_value_with_type(op))
        })
        .collect();
    out.push_str(&format!(
        "define{}{} {} {}({}) {{\n",
        linkage,
        visibility,
        ret_ty,
        name,
        param_strs.join(", ")
    ));
    // For a full implementation, we'd iterate basic blocks and print instructions
    // Simplified: print a placeholder
    out.push_str(&format!(
        "  ; function body: {} operands\n",
        f.operands.len()
    ));
    out.push_str("}\n");
    let _ = config;
}

fn infer_linkage_str(v: &Value) -> String {
    // Linkage inference from value metadata/name conventions
    if v.name.contains("internal") {
        return " internal".to_string();
    }
    if v.name.contains("private") {
        return " private".to_string();
    }
    String::new()
}

fn infer_visibility_str(v: &Value) -> String {
    if v.name.contains("hidden") {
        return " hidden".to_string();
    }
    if v.name.contains("protected") {
        return " protected".to_string();
    }
    String::new()
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use llvm_native_core::context::LLVMContext;
    use llvm_native_core::function;
    use llvm_native_core::instruction;
    use llvm_native_core::module::Module;

    #[test]
    fn test_write_empty_module() {
        let mut ctx = LLVMContext::new();
        let module = ctx.create_module("empty");
        module.set_target_triple("x86_64-unknown-linux-gnu");
        let text = write_assembly(module);
        assert!(text.contains("target triple"));
        assert!(text.contains("x86_64"));
    }

    #[test]
    fn test_write_function_declaration() {
        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let mut m = Module::new("test");
        let f = function::new_function("printf", i32_ty, &[]);
        m.add_function(f);
        let text = write_assembly(&m);
        assert!(text.contains("declare"));
        assert!(text.contains("@printf"));
    }

    #[test]
    fn test_write_function_with_body() {
        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let mut m = Module::new("test");
        let func = function::new_function("main", i32_ty, &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let zero = llvm_native_core::constants::const_i32(0);
        let ret = instruction::ret_val(zero);

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("define"));
        assert!(text.contains("@main"));
        assert!(text.contains("entry:"));
        assert!(text.contains("ret"));
    }

    #[test]
    fn test_type_to_str_primitives() {
        assert_eq!(type_to_str(&Type::void()), "void");
        assert_eq!(type_to_str(&Type::i32()), "i32");
        assert_eq!(type_to_str(&Type::i1()), "i1");
        assert_eq!(type_to_str(&Type::float()), "float");
        assert_eq!(type_to_str(&Type::double()), "double");
        assert_eq!(type_to_str(&Type::pointer(0)), "ptr");
    }

    #[test]
    fn test_write_roundtrip_smoke() {
        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let mut m = Module::new("test");
        m.set_target_triple("x86_64-unknown-linux-gnu");
        let f = function::new_function("foo", i32_ty, &[]);
        m.add_function(f);
        let text = write_assembly(&m);

        // Verify the output is parseable by our own parser
        let parsed = llvm_native_core::asm_parser::parse_assembly(&text);
        assert!(parsed.is_some(), "Writer output should be parseable");
        let parsed_mod = parsed.unwrap();
        assert!(!parsed_mod.functions.is_empty());
    }

    #[test]
    fn test_write_function_with_body_roundtrip() {
        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let mut m = Module::new("test");
        m.set_target_triple("x86_64-unknown-linux-gnu");

        let func = function::new_function("main", i32_ty, &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let zero = llvm_native_core::constants::const_i32(0);
        let ret = instruction::ret_val(zero);
        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);

        // Should be parseable
        let parsed = llvm_native_core::asm_parser::parse_assembly(&text);
        assert!(parsed.is_some());
    }

    // ============================================================
    // New tests for added functionality
    // ============================================================

    #[test]
    fn test_write_type_pointer_addrspace() {
        assert_eq!(type_to_str(&Type::pointer(5)), "ptr addrspace(5)");
    }

    #[test]
    fn test_write_type_fixed_vector() {
        let elem_id = Type::i32().id;
        let v = Type::fixed_vector_with(4, elem_id);
        let s = type_to_str(&v);
        assert!(s.contains("4 x"));
    }

    #[test]
    fn test_write_type_scalable_vector() {
        let elem_id = Type::float().id;
        let v = Type::scalable_vector_with(4, elem_id);
        let s = type_to_str(&v);
        assert!(s.contains("vscale"));
        assert!(s.contains("4 x"));
    }

    #[test]
    fn test_write_type_array() {
        let elem_id = Type::i32().id;
        let a = Type::array_with(10, elem_id);
        let s = type_to_str(&a);
        assert!(s.contains("[10 x"));
    }

    #[test]
    fn test_write_type_struct_named() {
        let s = Type::struct_named_with("Foo".to_string(), false, vec![]);
        let text = type_to_str(&s);
        assert!(text.contains("%Foo"));
    }

    #[test]
    fn test_write_type_struct_packed() {
        let s = Type::struct_named_with("Bar".to_string(), true, vec![]);
        let text = type_to_str(&s);
        assert!(text.contains("<{"));
    }

    #[test]
    fn test_write_type_function() {
        let ret_id = Type::i32().id;
        let params = vec![Type::i32().id, Type::float().id];
        let ft = Type::function_type_with(ret_id, params, false);
        let text = type_to_str(&ft);
        assert!(text.contains("("));
    }

    #[test]
    fn test_write_alloca_instruction() {
        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let mut m = Module::new("test");
        let func = function::new_function("test", Type::void(), &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let alloca = instruction::alloca(i32_ty);
        alloca.borrow_mut().name = "ptr".to_string();
        let ret = instruction::ret_void();

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(alloca);
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("alloca"));
    }

    #[test]
    fn test_write_load_instruction() {
        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let mut m = Module::new("test");
        let func = function::new_function("test", Type::void(), &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let alloca = instruction::alloca(i32_ty.clone());
        alloca.borrow_mut().name = "ptr".to_string();
        let load = instruction::load(i32_ty.clone(), alloca.clone());
        load.borrow_mut().name = "val".to_string();
        let ret = instruction::ret_void();

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(alloca);
        entry.borrow_mut().push_operand(load);
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("load"));
        assert!(text.contains("ptr %ptr"));
    }

    #[test]
    fn test_write_store_instruction() {
        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let mut m = Module::new("test");
        let func = function::new_function("test", Type::void(), &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let alloca = instruction::alloca(i32_ty.clone());
        alloca.borrow_mut().name = "ptr".to_string();
        let val = llvm_native_core::constants::const_i32(42);
        let store = instruction::store(val, alloca.clone());
        let ret = instruction::ret_void();

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(alloca);
        entry.borrow_mut().push_operand(store);
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("store"));
    }

    #[test]
    fn test_write_gep_instruction() {
        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let mut m = Module::new("test");
        let func = function::new_function("test", Type::pointer(0), &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let ptr = llvm_native_core::value::valref(llvm_native_core::value::Value::new(Type::pointer(0)).named("p"));
        let idx = llvm_native_core::constants::const_i32(1);
        let gep = instruction::getelementptr(i32_ty, ptr, vec![idx]);
        gep.borrow_mut().name = "gep".to_string();
        let ret = instruction::ret_val(gep.clone());

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(gep);
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("getelementptr"));
    }

    #[test]
    fn test_write_call_instruction() {
        let mut ctx = LLVMContext::new();
        let void_ty = Type::void();
        let mut m = Module::new("test");
        let callee = function::new_function("helper", void_ty.clone(), &[]);
        m.add_function(callee.clone());

        let func = function::new_function("main", void_ty.clone(), &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let call = instruction::call(void_ty.clone(), callee, vec![]);
        call.borrow_mut().name = "tmp".to_string();
        let ret = instruction::ret_void();

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(call);
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("call"));
        assert!(text.contains("@helper"));
    }

    #[test]
    fn test_write_phi_instruction() {
        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let mut m = Module::new("test");
        let func = function::new_function("test", i32_ty.clone(), &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let bb_a = llvm_native_core::basic_block::new_basic_block("a");
        let bb_b = llvm_native_core::basic_block::new_basic_block("b");
        let merge = llvm_native_core::basic_block::new_basic_block("merge");

        let val1 = llvm_native_core::constants::const_i32(1);
        let val2 = llvm_native_core::constants::const_i32(2);
        let phi = instruction::phi(i32_ty, vec![(val1, bb_a.clone()), (val2, bb_b.clone())]);
        phi.borrow_mut().name = "x".to_string();
        let ret = instruction::ret_val(phi.clone());

        func.borrow_mut().push_operand(entry.clone());
        func.borrow_mut().push_operand(bb_a);
        func.borrow_mut().push_operand(bb_b);
        func.borrow_mut().push_operand(merge.clone());
        merge.borrow_mut().push_operand(phi);
        merge.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("phi"));
    }

    #[test]
    fn test_write_select_instruction() {
        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let mut m = Module::new("test");
        let func = function::new_function("test", i32_ty, &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let cond = llvm_native_core::constants::const_bool(true);
        let a = llvm_native_core::constants::const_i32(10);
        let b = llvm_native_core::constants::const_i32(20);
        let sel = instruction::select(cond, a, b);
        sel.borrow_mut().name = "x".to_string();
        let ret = instruction::ret_val(sel.clone());

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(sel);
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("select"));
    }

    #[test]
    fn test_write_icmp_instruction() {
        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let mut m = Module::new("test");
        let func = function::new_function("test", Type::i1(), &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let a = llvm_native_core::constants::const_i32(1);
        let b = llvm_native_core::constants::const_i32(2);
        let cmp = instruction::icmp(llvm_native_core::opcode::ICmpPred::Eq, a, b);
        cmp.borrow_mut().name = "cmp".to_string();
        let ret = instruction::ret_val(cmp.clone());

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(cmp);
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("icmp"));
    }

    #[test]
    fn test_write_fcmp_instruction() {
        let mut ctx = LLVMContext::new();
        let float_ty = Type::float();
        let mut m = Module::new("test");
        let func = function::new_function("test", Type::i1(), &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let a = llvm_native_core::constants::const_float(1.0);
        let b = llvm_native_core::constants::const_float(2.0);
        let cmp = instruction::fcmp(llvm_native_core::opcode::FCmpPred::Oeq, a, b);
        cmp.borrow_mut().name = "cmp".to_string();
        let ret = instruction::ret_val(cmp.clone());

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(cmp);
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("fcmp"));
    }

    #[test]
    fn test_write_extractelement_instruction() {
        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let mut m = Module::new("test");
        let func = function::new_function("test", i32_ty.clone(), &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let vec = llvm_native_core::value::valref(
            llvm_native_core::value::Value::new(Type::fixed_vector_with(4, Type::i32().id)).named("v"),
        );
        let idx = llvm_native_core::constants::const_i32(0);
        let ee = llvm_native_core::value::valref(
            llvm_native_core::value::Value::new(i32_ty)
                .with_subclass(SubclassKind::Instruction)
                .named("x"),
        );
        ee.borrow_mut()
            .set_opcode(llvm_native_core::opcode::Opcode::ExtractElement);
        ee.borrow_mut().push_operand(vec);
        ee.borrow_mut().push_operand(idx);
        let ret = instruction::ret_val(ee.clone());

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(ee);
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("extractelement"));
    }

    #[test]
    fn test_write_insertelement_instruction() {
        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let mut m = Module::new("test");
        let vec4 = Type::fixed_vector_with(4, Type::i32().id);
        let func = function::new_function("test", vec4.clone(), &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let vec = llvm_native_core::value::valref(llvm_native_core::value::Value::new(vec4.clone()).named("v"));
        let elem = llvm_native_core::constants::const_i32(42);
        let idx = llvm_native_core::constants::const_i32(0);
        let ie = llvm_native_core::value::valref(
            llvm_native_core::value::Value::new(vec4)
                .with_subclass(SubclassKind::Instruction)
                .named("x"),
        );
        ie.borrow_mut()
            .set_opcode(llvm_native_core::opcode::Opcode::InsertElement);
        ie.borrow_mut().push_operand(vec);
        ie.borrow_mut().push_operand(elem);
        ie.borrow_mut().push_operand(idx);
        let ret = instruction::ret_val(ie.clone());

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(ie);
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("insertelement"));
    }

    #[test]
    fn test_write_shufflevector_instruction() {
        let mut ctx = LLVMContext::new();
        let vec4 = Type::fixed_vector_with(4, Type::i32().id);
        let mut m = Module::new("test");
        let func = function::new_function("test", vec4.clone(), &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let a = llvm_native_core::value::valref(llvm_native_core::value::Value::new(vec4.clone()).named("a"));
        let b = llvm_native_core::value::valref(llvm_native_core::value::Value::new(vec4.clone()).named("b"));
        let sv = llvm_native_core::value::valref(
            llvm_native_core::value::Value::new(vec4)
                .with_subclass(SubclassKind::Instruction)
                .named("x"),
        );
        sv.borrow_mut()
            .set_opcode(llvm_native_core::opcode::Opcode::ShuffleVector);
        sv.borrow_mut().push_operand(a);
        sv.borrow_mut().push_operand(b);
        let ret = instruction::ret_val(sv.clone());

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(sv);
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("shufflevector"));
    }

    #[test]
    fn test_write_extractvalue_instruction() {
        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let mut m = Module::new("test");
        let func = function::new_function("test", i32_ty.clone(), &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let agg = llvm_native_core::value::valref(llvm_native_core::value::Value::new(i32_ty).named("s"));
        let ev = llvm_native_core::value::valref(
            llvm_native_core::value::Value::new(Type::i32())
                .with_subclass(SubclassKind::Instruction)
                .named("x"),
        );
        ev.borrow_mut()
            .set_opcode(llvm_native_core::opcode::Opcode::ExtractValue);
        ev.borrow_mut().push_operand(agg);
        let ret = instruction::ret_val(ev.clone());

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(ev);
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("extractvalue"));
    }

    #[test]
    fn test_write_insertvalue_instruction() {
        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let mut m = Module::new("test");
        let func = function::new_function("test", i32_ty.clone(), &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let agg = llvm_native_core::value::valref(llvm_native_core::value::Value::new(i32_ty.clone()).named("s"));
        let elem = llvm_native_core::constants::const_i32(42);
        let iv = llvm_native_core::value::valref(
            llvm_native_core::value::Value::new(i32_ty)
                .with_subclass(SubclassKind::Instruction)
                .named("x"),
        );
        iv.borrow_mut()
            .set_opcode(llvm_native_core::opcode::Opcode::InsertValue);
        iv.borrow_mut().push_operand(agg);
        iv.borrow_mut().push_operand(elem);
        let ret = instruction::ret_val(iv.clone());

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(iv);
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("insertvalue"));
    }

    #[test]
    fn test_write_atomicrmw_instruction() {
        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let mut m = Module::new("test");
        let func = function::new_function("test", i32_ty.clone(), &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let ptr = llvm_native_core::value::valref(llvm_native_core::value::Value::new(Type::pointer(0)).named("p"));
        let val = llvm_native_core::constants::const_i32(1);
        let armw = llvm_native_core::value::valref(
            llvm_native_core::value::Value::new(i32_ty)
                .with_subclass(SubclassKind::Instruction)
                .named("old"),
        );
        armw.borrow_mut()
            .set_opcode(llvm_native_core::opcode::Opcode::AtomicRMW);
        armw.borrow_mut().push_operand(ptr);
        armw.borrow_mut().push_operand(val);
        let ret = instruction::ret_val(armw.clone());

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(armw);
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("atomicrmw"));
    }

    #[test]
    fn test_write_fence_instruction() {
        let mut ctx = LLVMContext::new();
        let mut m = Module::new("test");
        let func = function::new_function("test", Type::void(), &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let fence = llvm_native_core::value::valref(
            llvm_native_core::value::Value::new(Type::void()).with_subclass(SubclassKind::Instruction),
        );
        fence.borrow_mut().set_opcode(llvm_native_core::opcode::Opcode::Fence);
        let ret = instruction::ret_void();

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(fence);
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("fence"));
    }

    #[test]
    fn test_write_cmpxchg_instruction() {
        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let mut m = Module::new("test");
        let func = function::new_function("test", Type::void(), &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let ptr = llvm_native_core::value::valref(llvm_native_core::value::Value::new(Type::pointer(0)).named("p"));
        let old = llvm_native_core::constants::const_i32(0);
        let new = llvm_native_core::constants::const_i32(1);
        let cx = llvm_native_core::value::valref(
            llvm_native_core::value::Value::new(Type::void())
                .with_subclass(SubclassKind::Instruction)
                .named("x"),
        );
        cx.borrow_mut().set_opcode(llvm_native_core::opcode::Opcode::CmpXchg);
        cx.borrow_mut().push_operand(ptr);
        cx.borrow_mut().push_operand(old);
        cx.borrow_mut().push_operand(new);
        let ret = instruction::ret_void();

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(cx);
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("cmpxchg"));
    }

    #[test]
    fn test_write_switch_instruction() {
        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let mut m = Module::new("test");
        let func = function::new_function("test", Type::void(), &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let val = llvm_native_core::constants::const_i32(0);
        let default_bb = llvm_native_core::basic_block::new_basic_block("default");
        let case1 = llvm_native_core::basic_block::new_basic_block("case1");
        let sw = instruction::switch(
            val,
            default_bb,
            vec![(llvm_native_core::constants::const_i32(1), case1)],
        );
        sw.borrow_mut().name = "".to_string();
        let ret = instruction::ret_void();

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(sw);
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("switch"));
    }

    #[test]
    fn test_write_unreachable_instruction() {
        let mut ctx = LLVMContext::new();
        let mut m = Module::new("test");
        let func = function::new_function("test", Type::void(), &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let unreach = instruction::unreachable();

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(unreach);

        let text = write_assembly(&m);
        assert!(text.contains("unreachable"));
    }

    #[test]
    fn test_write_cast_instruction() {
        let mut ctx = LLVMContext::new();
        let i32_ty = ctx.i32();
        let i64_ty = ctx.i64();
        let mut m = Module::new("test");
        let func = function::new_function("test", i64_ty.clone(), &[]);
        m.add_function(func.clone());

        let entry = llvm_native_core::basic_block::new_basic_block("entry");
        let val = llvm_native_core::constants::const_i32(42);
        let sext = instruction::sext(val, i64_ty);
        sext.borrow_mut().name = "ext".to_string();
        let ret = instruction::ret_val(sext.clone());

        func.borrow_mut().push_operand(entry.clone());
        entry.borrow_mut().push_operand(sext);
        entry.borrow_mut().push_operand(ret);

        let text = write_assembly(&m);
        assert!(text.contains("sext"));
        assert!(text.contains("to"));
    }

    #[test]
    fn test_write_roundtrip_alloca_load_store() {
        let input = r#"
define void @test() {
entry:
  %ptr = alloca i32
  store i32 42, ptr %ptr
  ret void
}
"#;
        let parsed = llvm_native_core::asm_parser::parse_assembly(input).unwrap();
        let output = write_assembly(&parsed);
        assert!(output.contains("alloca"));
        // The output may differ in formatting but should be parseable
        let re_parsed = llvm_native_core::asm_parser::parse_assembly(&output);
        assert!(re_parsed.is_some(), "Writer output should be re-parseable");
    }

    #[test]
    fn test_write_roundtrip_call() {
        let input = r#"
declare void @helper()
define void @main() {
entry:
  call void @helper()
  ret void
}
"#;
        let parsed = llvm_native_core::asm_parser::parse_assembly(input).unwrap();
        let output = write_assembly(&parsed);
        assert!(output.contains("call"));
        assert!(output.contains("@helper"));
        let re_parsed = llvm_native_core::asm_parser::parse_assembly(&output);
        assert!(re_parsed.is_some(), "Writer output should be re-parseable");
    }

    #[test]
    fn test_write_value_constant() {
        let zero = llvm_native_core::constants::const_i32(0);
        let s = value_to_str(&zero);
        assert!(!s.is_empty());
    }

    #[test]
    fn test_write_value_global() {
        let gv = llvm_native_core::value::valref(
            llvm_native_core::value::Value::new(Type::i32())
                .with_subclass(SubclassKind::GlobalVariable)
                .named("@my_global"),
        );
        let s = value_to_str(&gv);
        assert!(s.starts_with('@'));
    }

    #[test]
    fn test_module_header_writing() {
        let mut m = Module::new("test");
        m.source_filename = "test.c".into();
        m.set_target_triple("x86_64-unknown-linux-gnu");
        m.set_data_layout("e-m:e-p270:32:32");
        let text = write_assembly(&m);
        assert!(text.contains("source_filename"));
        assert!(text.contains("test.c"));
        assert!(text.contains("target triple"));
        assert!(text.contains("target datalayout"));
    }

    #[test]
    fn test_type_to_str_full_coverage() {
        // Verify all type kinds produce non-empty strings
        assert!(!type_to_str(&Type::half()).is_empty());
        assert!(!type_to_str(&Type::bfloat()).is_empty());
        assert!(!type_to_str(&Type::fp128()).is_empty());
        assert!(!type_to_str(&Type::x86_fp80()).is_empty());
        assert!(!type_to_str(&Type::ppc_fp128()).is_empty());
        assert!(!type_to_str(&Type::label()).is_empty());
        assert!(!type_to_str(&Type::metadata()).is_empty());
        assert!(!type_to_str(&Type::token()).is_empty());
        assert!(!type_to_str(&Type::x86_amx()).is_empty());
        assert!(!type_to_str(&Type::x86_mmx()).is_empty());
    }
}