tl-lang 0.4.8

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

use inkwell::context::Context;
use inkwell::execution_engine::ExecutionEngine;
use inkwell::module::Module as InkwellModule;
use inkwell::AddressSpace;

use crate::compiler::ast::Type;
use tl_runtime as runtime;
use tl_cpu::ffi as cpu_ffi;

unsafe extern "C" {
    fn malloc(size: usize) -> *mut std::ffi::c_void;
    fn calloc(count: usize, size: usize) -> *mut std::ffi::c_void;
    fn realloc(ptr: *mut std::ffi::c_void, size: usize) -> *mut std::ffi::c_void;
    fn free(ptr: *mut std::ffi::c_void);
    fn abort();
}

pub fn declare_runtime_functions<'ctx>(
    context: &'ctx Context,
    module: &InkwellModule<'ctx>,
    execution_engine: &ExecutionEngine<'ctx>,
    ret_types: &mut HashMap<String, Type>,
) {

    // Debug helper
    #[unsafe(no_mangle)]
    extern "C" fn tl_debug_print_ptr(name: *const i8, ptr: *const i8) {
        let name_str = unsafe { std::ffi::CStr::from_ptr(name).to_string_lossy() };
        eprintln!("Cleanup: {} Ptr: {:p}", name_str, ptr);
    }

    // ゼロオーバーヘッド CPU/GPU 切替: JIT リンク時にシンボルを差し替え
    let is_cpu = std::env::var("TL_DEVICE").map_or(false, |d| d == "cpu");

    let i64_type = context.i64_type(); // usize
    let i32_type = context.i32_type();
    // let i8_type = context.i8_type();
    let f32_type = context.f32_type();
    let f32_ptr = context.ptr_type(AddressSpace::default());
    let usize_ptr = context.ptr_type(AddressSpace::default());
    let i64_ptr = context.ptr_type(AddressSpace::default());
    let void_ptr = context.ptr_type(AddressSpace::default()); // OpaqueTensor*
    let void_type = context.void_type();
    let i8_ptr = context.ptr_type(AddressSpace::default());

    // FFI Result struct: { tensor, error_msg, error_code, file, line, col }
    let c_tensor_result_type = context.struct_type(
        &[
            void_ptr.into(), // tensor (0)
            i8_ptr.into(),   // error_msg (1)
            i32_type.into(), // error_code (2)
            i8_ptr.into(),   // file (3)
            i32_type.into(), // line (4)
            i32_type.into(), // col (5)
        ],
        false,
    );

    // Helper to add function only if not exists
    let add_fn = |name: &str, ty: inkwell::types::FunctionType<'ctx>| {
        if module.get_function(name).is_none() {
            module.add_function(name, ty, None);
        }
    };

    // Helper: LLVM宣言 + セマンティクス型を同時登録(ポインタ返却FFI用)
    // これにより register_builtin_return_types での登録漏れが構造的に防止される
    let add_fn_typed = |name: &str, ty: inkwell::types::FunctionType<'ctx>, ret_type: Type, ret_types: &mut HashMap<String, Type>| {
        if module.get_function(name).is_none() {
            module.add_function(name, ty, None);
        }
        ret_types.insert(name.to_string(), ret_type);
    };

    let print_i64_type = void_type.fn_type(&[i64_type.into()], false);
    add_fn("tl_print_i64", print_i64_type.clone());
    add_fn("tl_display_i64", print_i64_type);

    let print_i32_type = void_type.fn_type(&[i32_type.into()], false);
    add_fn("tl_print_i32", print_i32_type.clone());
    add_fn("tl_display_i32", print_i32_type);

    // tl_print_char(c: i32)
    let print_char_type = void_type.fn_type(&[i32_type.into()], false);
    add_fn("tl_print_char", print_char_type.clone());
    add_fn("tl_display_char", print_char_type);

    let print_f32_type = void_type.fn_type(&[f32_type.into()], false);
    add_fn("tl_print_f32", print_f32_type.clone());
    add_fn("tl_display_f32", print_f32_type);

    let f64_type = context.f64_type();
    let print_f64_type = void_type.fn_type(&[f64_type.into()], false);
    add_fn("tl_print_f64", print_f64_type.clone());
    add_fn("tl_display_f64", print_f64_type);

    let print_bool_type = void_type.fn_type(&[context.bool_type().into()], false);
    add_fn("tl_print_bool", print_bool_type.clone());
    add_fn("tl_display_bool", print_bool_type);

    let f32_unary_type = f32_type.fn_type(&[f32_type.into()], false);
    let f32_binary_type = f32_type.fn_type(&[f32_type.into(), f32_type.into()], false);
    let f32_powi_type = f32_type.fn_type(&[f32_type.into(), i64_type.into()], false);
    let f64_unary_type = f64_type.fn_type(&[f64_type.into()], false);
    let f64_binary_type = f64_type.fn_type(&[f64_type.into(), f64_type.into()], false);
    let f64_powi_type = f64_type.fn_type(&[f64_type.into(), i64_type.into()], false);
    let i64_unary_type = i64_type.fn_type(&[i64_type.into()], false);
    let i64_binary_type = i64_type.fn_type(&[i64_type.into(), i64_type.into()], false);
    let i32_unary_type = i32_type.fn_type(&[i32_type.into()], false);
    let i32_binary_type = i32_type.fn_type(&[i32_type.into(), i32_type.into()], false);
    let i64_bool_unary_type = context.bool_type().fn_type(&[i64_type.into()], false);
    let i32_bool_unary_type = context.bool_type().fn_type(&[i32_type.into()], false);

    let f32_unary_methods = [
        "abs",
        "acos",
        "acosh",
        "asin",
        "asinh",
        "atan",
        "atanh",
        "cbrt",
        "ceil",
        "cos",
        "cosh",
        "exp",
        "exp2",
        "exp_m1",
        "floor",
        "fract",
        "ln",
        "ln_1p",
        "log10",
        "log2",
        "recip",
        "round",
        "signum",
        "sin",
        "sinh",
        "sqrt",
        "tan",
        "tanh",
        "to_degrees",
        "to_radians",
        "trunc",
    ];
    for name in f32_unary_methods {
        add_fn(&format!("tl_f32_{}", name), f32_unary_type);
    }

    let f32_binary_methods = ["atan2", "copysign", "hypot", "log", "powf"];
    for name in f32_binary_methods {
        add_fn(&format!("tl_f32_{}", name), f32_binary_type);
    }
    add_fn("tl_f32_powi", f32_powi_type);

    let f64_unary_methods = [
        "abs",
        "acos",
        "acosh",
        "asin",
        "asinh",
        "atan",
        "atanh",
        "cbrt",
        "ceil",
        "cos",
        "cosh",
        "exp",
        "exp2",
        "exp_m1",
        "floor",
        "fract",
        "ln",
        "ln_1p",
        "log10",
        "log2",
        "recip",
        "round",
        "signum",
        "sin",
        "sinh",
        "sqrt",
        "tan",
        "tanh",
        "to_degrees",
        "to_radians",
        "trunc",
    ];
    for name in f64_unary_methods {
        add_fn(&format!("tl_f64_{}", name), f64_unary_type);
    }
    let f64_binary_methods = ["atan2", "copysign", "hypot", "log", "powf"];
    for name in f64_binary_methods {
        add_fn(&format!("tl_f64_{}", name), f64_binary_type);
    }
    add_fn("tl_f64_powi", f64_powi_type);

    let i64_unary_methods = ["abs", "signum"];
    for name in i64_unary_methods {
        add_fn(&format!("tl_i64_{}", name), i64_unary_type);
    }
    let i64_binary_methods = ["div_euclid", "rem_euclid", "pow"];
    for name in i64_binary_methods {
        add_fn(&format!("tl_i64_{}", name), i64_binary_type);
    }
    add_fn("tl_i64_is_positive", i64_bool_unary_type);
    add_fn("tl_i64_is_negative", i64_bool_unary_type);

    let i32_unary_methods = ["abs", "signum"];
    for name in i32_unary_methods {
        add_fn(&format!("tl_i32_{}", name), i32_unary_type);
    }
    let i32_binary_methods = ["div_euclid", "rem_euclid", "pow"];
    for name in i32_binary_methods {
        add_fn(&format!("tl_i32_{}", name), i32_binary_type);
    }
    add_fn("tl_i32_is_positive", i32_bool_unary_type);
    add_fn("tl_i32_is_negative", i32_bool_unary_type);

    let print_str_type = void_type.fn_type(&[void_ptr.into()], false);
    add_fn("tl_print_string", print_str_type.clone());
    add_fn("tl_display_string", print_str_type);

    // tl_file_exists(path: *const c_char) -> bool
    let file_exists_type = context.bool_type().fn_type(&[i8_ptr.into()], false);
    add_fn("tl_file_exists", file_exists_type);

    // Workaround: i64 return type
    let file_exists_i64_type = i64_type.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_file_exists_i64", file_exists_i64_type);

    // tl_download_file(url: *const c_char, path: *const c_char) -> i64
    let download_file_type = i64_type.fn_type(&[i8_ptr.into(), i8_ptr.into()], false);
    add_fn("tl_download_file", download_file_type);

    // tl_read_file(path: *const c_char) -> *mut StringStruct
    let read_file_type = i8_ptr.fn_type(&[i8_ptr.into()], false);
    add_fn_typed("tl_read_file", read_file_type, Type::String("String".to_string()), ret_types);

    // tl_write_file(path: *const c_char, content: *const c_char) -> i64
    let write_file_type = i64_type.fn_type(&[i8_ptr.into(), i8_ptr.into()], false);
    add_fn("tl_write_file", write_file_type);

    // tl_print_ptr for debugging tensor pointers
    let print_ptr_type = void_type.fn_type(&[void_ptr.into()], false);
    add_fn("tl_print_ptr", print_ptr_type);

    // tl_report_runtime_error(msg: *const c_char) -> void
    let report_err_type = void_type.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_report_runtime_error", report_err_type);

    // tl_handle_runtime_error(code: u32, msg: *const i8, file: *const i8, line: u32, col: u32) -> void
    let handle_err_type = void_type.fn_type(
        &[
            i32_type.into(),
            i8_ptr.into(),
            i8_ptr.into(),
            i32_type.into(),
            i32_type.into(),
        ],
        false,
    );
    add_fn("tl_handle_runtime_error", handle_err_type.clone());

    // tl_amend_error_loc(file: *const i8, line: u32, col: u32) -> void
    let amend_err_type =
        void_type.fn_type(&[i8_ptr.into(), i32_type.into(), i32_type.into()], false);
    add_fn("tl_amend_error_loc", amend_err_type);

    // tl_report_runtime_error_loc(file: *const i8, line: i32, col: i32) -> void
    let report_err_loc_type =
        void_type.fn_type(&[i8_ptr.into(), i32_type.into(), i32_type.into()], false);
    add_fn("tl_report_runtime_error_loc", report_err_loc_type);

    if let Some(f) = module.get_function("tl_handle_runtime_error") {
        execution_engine.add_global_mapping(&f, runtime::tl_handle_runtime_error as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_amend_error_loc") {
        execution_engine.add_global_mapping(&f, runtime::tl_amend_error_loc as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_report_runtime_error_loc") {
        execution_engine.add_global_mapping(&f, runtime::tl_report_runtime_error_loc as *const () as usize);
    }

    // tl_get_last_error() -> CTensorResult
    let get_last_error_type = c_tensor_result_type.fn_type(&[], false);
    add_fn("tl_get_last_error", get_last_error_type);

    // tl_set_device(name: *const i8) -> void
    let set_dev_type = void_type.fn_type(&[void_ptr.into()], false);
    add_fn("tl_set_device", set_dev_type);

    // tl_tensor_enable_grad(t: *mut OpaqueTensor) -> void
    let enable_grad_type = void_type.fn_type(&[void_ptr.into()], false);
    add_fn("tl_tensor_enable_grad", enable_grad_type);

    // tl_tensor_to_device(tensor: *mut Opaque, name: *const i8) -> *mut Opaque
    let to_dev_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_tensor_to_device", to_dev_type);

    // malloc(size: i64) -> *u8
    let malloc_type = void_ptr.fn_type(&[i64_type.into()], false);
    add_fn("malloc", malloc_type);

    // calloc(num: i64, size: i64) -> *u8
    let calloc_type = void_ptr.fn_type(&[i64_type.into(), i64_type.into()], false);
    add_fn("calloc", calloc_type);

    // free(ptr: *u8) -> void
    let free_type = void_type.fn_type(&[void_ptr.into()], false);
    add_fn("free", free_type);

    // realloc(ptr: *u8, size: i64) -> *u8
    let realloc_type = void_ptr.fn_type(&[void_ptr.into(), i64_type.into()], false);
    add_fn("realloc", realloc_type);

    // abort() -> void (for panic! support)
    let abort_type = void_type.fn_type(&[], false);
    add_fn("abort", abort_type);

    // tl_tensor_dim(t: *mut OpaqueTensor, dim_idx: usize) -> i64
    let dim_type = i64_type.fn_type(&[void_ptr.into(), i64_type.into()], false);
    add_fn("tl_tensor_dim", dim_type);

    // tl_tensor_get_f32_md(t: *mut OpaqueTensor, indices: *const i64, rank: usize) -> f32
    let get_md_type = f32_type.fn_type(&[void_ptr.into(), i64_ptr.into(), i64_type.into()], false);
    add_fn("tl_tensor_get_f32_md", get_md_type);
    // tl_tensor_get_i64_md(t: *mut OpaqueTensor, indices: *const i64, rank: usize) -> i64
    let get_md_i64_type =
        i64_type.fn_type(&[void_ptr.into(), i64_ptr.into(), i64_type.into()], false);
    add_fn("tl_tensor_get_i64_md", get_md_i64_type);

    // tl_tensor_set_f32_md(t: *mut OpaqueTensor, indices: *const i64, rank: usize, val: f32) -> *mut OpaqueTensor
    let set_md_type = void_ptr.fn_type(
        &[
            void_ptr.into(),
            i64_ptr.into(),
            i64_type.into(),
            f32_type.into(),
        ],
        false,
    );
    add_fn("tl_tensor_set_f32_md", set_md_type);

    // tl_tensor_new(data: *const f32, rank: usize, shape: *const usize) -> *mut OpaqueTensor
    let new_type = void_ptr.fn_type(&[f32_ptr.into(), i64_type.into(), usize_ptr.into()], false);
    add_fn("tl_tensor_new", new_type);

    // tl_tensor_from_i64_array(data: *const i64, len: usize) -> *mut OpaqueTensor
    let from_i64_type = void_ptr.fn_type(&[i64_ptr.into(), i64_type.into()], false);
    add_fn("tl_tensor_from_i64_array", from_i64_type);

    // tl_tensor_new_i64(data: *const i64, rank: usize, shape: *const usize) -> *mut OpaqueTensor
    let new_i64_type =
        void_ptr.fn_type(&[i64_ptr.into(), i64_type.into(), usize_ptr.into()], false);
    add_fn("tl_tensor_new_i64", new_i64_type);

    let binop_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_tensor_sub", binop_type);

    // tl_tensor_free(t: *mut) -> void
    let free_type = void_type.fn_type(&[void_ptr.into()], false);
    add_fn("tl_tensor_free", free_type);

    // tl_tensor_clone(t: *mut) -> *mut OpaqueTensor
    let clone_type = void_ptr.fn_type(&[void_ptr.into()], false);
    add_fn("tl_tensor_clone", clone_type);

    // tl_tensor_acquire(t: *mut) -> *mut
    add_fn("tl_tensor_acquire", clone_type);

    // tl_tensor_release(t: *mut) -> void
    add_fn("tl_tensor_release", free_type);

    // tl_tensor_release_safe(t: *mut) -> void
    add_fn("tl_tensor_release_safe", free_type);

    // tl_qtensor_retain(t: *mut) -> *mut
    add_fn("tl_qtensor_retain", clone_type);

    // tl_qtensor_release_safe(t: *mut) -> void
    add_fn("tl_qtensor_release_safe", free_type);

    // tl_tensor_promote(t: *mut) -> void
    add_fn("tl_tensor_promote", free_type);

    // tl_tensor_register(t: *mut) -> void
    add_fn("tl_tensor_register", free_type);

    // tl_tensor_data(t: *mut) -> *mut
    let data_type = void_ptr.fn_type(&[void_ptr.into()], false);
    add_fn("tl_tensor_data", data_type);

    // tl_tensor_numel(t: *mut) -> i64
    let numel_type = i64_type.fn_type(&[void_ptr.into()], false);
    add_fn("tl_tensor_numel", numel_type);

    // tl_ptr_dec_ref(ptr: *mut) -> i32
    let dec_ref_type = i32_type.fn_type(&[void_ptr.into()], false);
    add_fn("tl_ptr_dec_ref", dec_ref_type);

    // tl_ptr_inc_ref(ptr: *mut) -> void
    let inc_ref_type = void_type.fn_type(&[void_ptr.into()], false);
    add_fn("tl_ptr_inc_ref", inc_ref_type);

    // tl_ptr_inc_ref_i64(addr: i64) -> void
    let inc_ref_i64_type = void_type.fn_type(&[i64_type.into()], false);
    add_fn("tl_ptr_inc_ref_i64", inc_ref_i64_type);

    // tl_mem_free(ptr: *mut) -> void
    add_fn("tl_mem_free", free_type);


    // tl_tensor_add(a: *mut, b: *mut) -> *mut OpaqueTensor
    let bin_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_tensor_add", bin_type);
    add_fn("tl_tensor_mul", bin_type);

    let print_type = void_type.fn_type(&[void_ptr.into()], false);
    add_fn("tl_print_string", print_type.clone());
    add_fn("tl_string_print", print_type.clone());
    add_fn("tl_display_string", print_type.clone());
    add_fn("tl_tensor_print", print_type.clone());
    add_fn("tl_tensor_display", print_type.clone());
    add_fn("tl_tensor_print_1", print_type.clone());
    add_fn("tl_tensor_print_2", print_type.clone());
    add_fn("tl_tensor_print_3", print_type.clone());

    // tl_tensor_get(t: *mut, index: usize) -> f32 (Simplification: 1D get)
    let get_type = f32_type.fn_type(&[void_ptr.into(), i64_type.into()], false);
    add_fn("tl_tensor_get", get_type);

    // tl_tensor_slice(t: *mut, dim: i64, start: i64, end: i64, step: i64) -> *mut
    let slice_type = void_ptr.fn_type(&[void_ptr.into(), i64_type.into(), i64_type.into(), i64_type.into(), i64_type.into()], false);
    add_fn("tl_tensor_slice", slice_type);




    // tl_string_len(s: *const c_char) -> i64
    let len_str_type = i64_type.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_string_len", len_str_type);
    
    // tl_string_from_char(c: i32) -> *mut StringStruct
    let from_char_type = i8_ptr.fn_type(&[i32_type.into()], false);
    add_fn_typed("tl_string_from_char", from_char_type, Type::String("String".to_string()), ret_types);

    // tl_string_char_at(s: *mut StringStruct, index: i64) -> i64 (char as i64)
    let char_at_type = i64_type.fn_type(&[void_ptr.into(), i64_type.into()], false);
    add_fn("tl_string_char_at", char_at_type);

    // tl_string_eq(s1: *mut StringStruct, s2: *mut StringStruct) -> bool
    let string_eq_type = context.bool_type().fn_type(&[void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_string_eq", string_eq_type);

    // tl_string_new(s: *const c_char) -> *mut StringStruct
    // StringStruct is { ptr, len }, pointer to it is void* (or specific struct type?)
    // In LLVM IR we invoke it as returning pointer to { i8*, i64 }.
    // So we can declare it returning ptr.
    // The struct type definition is local in expr.rs usually, but we can treat as void* here for declaration?
    // No, expr.rs casts return value anyway? 
    // Wait, expr.rs uses build_call. The return type of the FUNCTION matches build_call expectation.
    // If function returns void*, then build_call returns void*.
    // But expr.rs expects pointer to StringStruct. void* is fine.
    let new_string_type = void_ptr.fn_type(&[i8_ptr.into()], false);
    add_fn_typed("tl_string_new", new_string_type, Type::String("String".to_string()), ret_types);
    
    // tl_string_free(s: *mut StringStruct) -> void
    add_fn("tl_string_free", free_type);

    // tl_tensor_len(t: *mut) -> i64
    let len_type = i64_type.fn_type(&[void_ptr.into()], false);
    add_fn("tl_tensor_len", len_type);

    // tl_tensor_neg(t: *mut) -> *mut
    let neg_type = void_ptr.fn_type(&[void_ptr.into()], false);
    add_fn("tl_tensor_neg", neg_type);

    // tl_tensor_transpose(t: *mut, d0: usize, d1: usize) -> *mut
    let transpose_type =
        void_ptr.fn_type(&[void_ptr.into(), i64_type.into(), i64_type.into()], false);
    add_fn("tl_tensor_transpose", transpose_type);

    // tl_tensor_pow(t: *mut Tensor, exponent: *mut Tensor) -> *mut OpaqueTensor
    let pow_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_tensor_pow", pow_type);

    // tl_tensor_pow_scalar(t: *mut Tensor, exponent: f32) -> *mut OpaqueTensor
    let pow_scalar_type = void_ptr.fn_type(&[void_ptr.into(), f32_type.into()], false);
    add_fn("tl_tensor_pow_scalar", pow_scalar_type);

    // Scalar ops (add, sub, mul, div) taking f64
    let scalar_op_type = void_ptr.fn_type(&[void_ptr.into(), f64_type.into()], false);
    add_fn("tl_tensor_add_scalar", scalar_op_type.clone());
    add_fn("tl_tensor_sub_scalar", scalar_op_type.clone());
    add_fn("tl_tensor_mul_scalar", scalar_op_type.clone());
    add_fn("tl_tensor_div_scalar", scalar_op_type);

    // tl_tensor_sqrt(t: *mut Tensor) -> *mut Tensor
    let unary_type = void_ptr.fn_type(&[void_ptr.into()], false);
    add_fn("tl_tensor_sqrt", unary_type);

    // Transformer Ops
    // tl_tensor_sin(t: *mut Tensor) -> *mut Tensor
    add_fn("tl_tensor_sin", unary_type); // Same signature as sqrt

    // tl_tensor_cos(t: *mut Tensor) -> *mut Tensor
    add_fn("tl_tensor_cos", unary_type);

    // tl_tensor_relu(t: *mut Tensor) -> *mut Tensor
    add_fn("tl_tensor_relu", unary_type);

    // tl_tensor_gelu(t: *mut Tensor) -> *mut Tensor
    add_fn("tl_tensor_gelu", unary_type);

    // tl_tensor_tril(t: *mut Tensor, diagonal: i64) -> *mut Tensor
    let tril_type = void_ptr.fn_type(&[void_ptr.into(), i64_type.into()], false);
    add_fn("tl_tensor_tril", tril_type);

    // Explicitly add tl_clear_grads
    let clear_grads_type = void_type.fn_type(&[], false);
    add_fn("tl_clear_grads", clear_grads_type);

    // tl_tensor_set_f32_md(t: *mut, indices: *const i64, rank: usize, val: f32) -> *mut
    let set_md_type = void_ptr.fn_type(
        &[
            void_ptr.into(),
            void_ptr.into(), // indices ptr
            i64_type.into(), // rank
            f32_type.into(), // val
        ],
        false,
    );
    add_fn("tl_tensor_set_f32_md", set_md_type);

    // tl_tensor_get_f32_md(t: *mut, indices: *const i64, rank: usize) -> f32
    let get_md_type = f32_type.fn_type(
        &[
            void_ptr.into(),
            void_ptr.into(), // indices ptr
            i64_type.into(), // rank
        ],
        false,
    );
    add_fn("tl_tensor_get_f32_md", get_md_type);

    // [LIBC] Explicit mapping for JIT engine to resolve memory functions
    if let Some(f) = module.get_function("malloc") {
        execution_engine.add_global_mapping(&f, malloc as *const () as usize);
    }
    if let Some(f) = module.get_function("calloc") {
        execution_engine.add_global_mapping(&f, calloc as *const () as usize);
    }
    if let Some(f) = module.get_function("realloc") {
        execution_engine.add_global_mapping(&f, realloc as *const () as usize);
    }
    if let Some(f) = module.get_function("free") {
        execution_engine.add_global_mapping(&f, free as *const () as usize);
    }
    if let Some(f) = module.get_function("abort") {
        execution_engine.add_global_mapping(&f, abort as *const () as usize);
    }

    // [IDevice] tl_clear_grads → device_ffi
    if let Some(f) = module.get_function("tl_clear_grads") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_clear_grads as *const () as usize); }
    if let Some(f) = module.get_function("tl_file_exists") {
        execution_engine.add_global_mapping(&f, runtime::tl_file_exists as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_file_exists_i64") {
        execution_engine.add_global_mapping(&f, runtime::tl_file_exists_i64 as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_download_file") {
        execution_engine.add_global_mapping(&f, runtime::tl_download_file as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_read_file") {
        execution_engine.add_global_mapping(&f, runtime::tl_read_file as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_write_file") {
        execution_engine.add_global_mapping(&f, runtime::tl_write_file as *const () as usize);
    }

    // String mappings
    if let Some(f) = module.get_function("tl_string_new") {
        execution_engine.add_global_mapping(&f, runtime::tl_string_new as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_print_string") {
        execution_engine.add_global_mapping(&f, runtime::tl_print_string as *const () as usize);
    }
    // Add mapping for legacy/extern default name
    if let Some(f) = module.get_function("tl_string_print") {
        execution_engine.add_global_mapping(&f, runtime::tl_string_print as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_display_string") {
        execution_engine.add_global_mapping(&f, runtime::tl_display_string as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_string_concat") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_concat as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_string_len") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_len as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_string_from_char") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_from_char as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_string_to_i64") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_to_i64 as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_string_contains") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_contains as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_string_char_at") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_char_at as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_string_eq") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_eq as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_string_free") {
        execution_engine.add_global_mapping(&f, runtime::string_ffi::tl_string_free as *const () as usize);
    }
    
    // tl_hash_string(s: *mut StringStruct) -> i64
    let hash_string_type = i64_type.fn_type(&[void_ptr.into()], false);
    add_fn("tl_hash_string", hash_string_type);
    
    if let Some(f) = module.get_function("tl_hash_string") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_hash_string as *const () as usize);
    }

    // tl_checkpoint(ctx: *mut, func: *mut, input: *mut) -> *mut
    let checkpoint_type =
        void_ptr.fn_type(&[void_ptr.into(), void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_checkpoint", checkpoint_type);

    if let Some(f) = module.get_function("tl_checkpoint") {
        execution_engine.add_global_mapping(&f, runtime::checkpoint::tl_checkpoint as *const () as usize);
    }

    // --- Channel and Atomic FFI ---
    // Channel FFI
    let channel_new_type = i64_type.fn_type(&[i64_type.into()], false);
    add_fn("tl_channel_new", channel_new_type);
    
    let channel_send_type = context.bool_type().fn_type(&[i64_type.into(), i64_type.into()], false);
    add_fn("tl_channel_send", channel_send_type);
    
    let channel_recv_type = i64_type.fn_type(&[i64_type.into()], false);
    add_fn("tl_channel_recv", channel_recv_type);
    
    let channel_try_recv_type = i64_type.fn_type(&[i64_type.into(), context.ptr_type(AddressSpace::default()).into()], false);
    add_fn("tl_channel_try_recv", channel_try_recv_type);

    add_fn("tl_channel_clone", clone_type);
    add_fn("tl_channel_free", free_type);

    if let Some(f) = module.get_function("tl_channel_new") { execution_engine.add_global_mapping(&f, runtime::channel_ffi::tl_channel_new as *const () as usize); }
    if let Some(f) = module.get_function("tl_channel_send") { execution_engine.add_global_mapping(&f, runtime::channel_ffi::tl_channel_send as *const () as usize); }
    if let Some(f) = module.get_function("tl_channel_recv") { execution_engine.add_global_mapping(&f, runtime::channel_ffi::tl_channel_recv as *const () as usize); }
    if let Some(f) = module.get_function("tl_channel_try_recv") { execution_engine.add_global_mapping(&f, runtime::channel_ffi::tl_channel_try_recv as *const () as usize); }
    if let Some(f) = module.get_function("tl_channel_clone") { execution_engine.add_global_mapping(&f, runtime::channel_ffi::tl_channel_clone as *const () as usize); }
    if let Some(f) = module.get_function("tl_channel_free") { execution_engine.add_global_mapping(&f, runtime::channel_ffi::tl_channel_free as *const () as usize); }

    // Atomic I64
    let atomic_new_type = i64_type.fn_type(&[i64_type.into()], false);
    add_fn("tl_atomic_i64_new", atomic_new_type);
    
    let atomic_load_type = i64_type.fn_type(&[i64_type.into()], false);
    add_fn("tl_atomic_i64_load", atomic_load_type);
    
    let atomic_store_type = void_type.fn_type(&[i64_type.into(), i64_type.into()], false);
    add_fn("tl_atomic_i64_store", atomic_store_type);
    
    let atomic_op_type = i64_type.fn_type(&[i64_type.into(), i64_type.into()], false);
    add_fn("tl_atomic_i64_add", atomic_op_type);
    add_fn("tl_atomic_i64_sub", atomic_op_type);
    add_fn("tl_atomic_i64_swap", atomic_op_type);
    
    let atomic_cmpxchg_type = context.bool_type().fn_type(&[i64_type.into(), i64_type.into(), i64_type.into()], false);
    add_fn("tl_atomic_i64_compare_exchange", atomic_cmpxchg_type);
    
    add_fn("tl_atomic_i64_clone", clone_type);
    add_fn("tl_atomic_i64_free", free_type);

    if let Some(f) = module.get_function("tl_atomic_i64_new") { execution_engine.add_global_mapping(&f, runtime::atomic_ffi::tl_atomic_i64_new as *const () as usize); }
    if let Some(f) = module.get_function("tl_atomic_i64_load") { execution_engine.add_global_mapping(&f, runtime::atomic_ffi::tl_atomic_i64_load as *const () as usize); }
    if let Some(f) = module.get_function("tl_atomic_i64_store") { execution_engine.add_global_mapping(&f, runtime::atomic_ffi::tl_atomic_i64_store as *const () as usize); }
    if let Some(f) = module.get_function("tl_atomic_i64_add") { execution_engine.add_global_mapping(&f, runtime::atomic_ffi::tl_atomic_i64_add as *const () as usize); }
    if let Some(f) = module.get_function("tl_atomic_i64_sub") { execution_engine.add_global_mapping(&f, runtime::atomic_ffi::tl_atomic_i64_sub as *const () as usize); }
    if let Some(f) = module.get_function("tl_atomic_i64_swap") { execution_engine.add_global_mapping(&f, runtime::atomic_ffi::tl_atomic_i64_swap as *const () as usize); }
    if let Some(f) = module.get_function("tl_atomic_i64_compare_exchange") { execution_engine.add_global_mapping(&f, runtime::atomic_ffi::tl_atomic_i64_compare_exchange as *const () as usize); }
    if let Some(f) = module.get_function("tl_atomic_i64_clone") { execution_engine.add_global_mapping(&f, runtime::atomic_ffi::tl_atomic_i64_clone as *const () as usize); }
    if let Some(f) = module.get_function("tl_atomic_i64_free") { execution_engine.add_global_mapping(&f, runtime::atomic_ffi::tl_atomic_i64_free as *const () as usize); }

    // Atomic I32
    let atomic_i32_new_type = i64_type.fn_type(&[i32_type.into()], false);
    add_fn("tl_atomic_i32_new", atomic_i32_new_type);
    
    let atomic_i32_load_type = i32_type.fn_type(&[i64_type.into()], false);
    add_fn("tl_atomic_i32_load", atomic_i32_load_type);
    
    let atomic_i32_store_type = void_type.fn_type(&[i64_type.into(), i32_type.into()], false);
    add_fn("tl_atomic_i32_store", atomic_i32_store_type);
    
    let atomic_i32_op_type = i32_type.fn_type(&[i64_type.into(), i32_type.into()], false);
    add_fn("tl_atomic_i32_add", atomic_i32_op_type);
    add_fn("tl_atomic_i32_sub", atomic_i32_op_type);
    add_fn("tl_atomic_i32_swap", atomic_i32_op_type);
    
    let atomic_i32_cmpxchg_type = context.bool_type().fn_type(&[i64_type.into(), i32_type.into(), i32_type.into()], false);
    add_fn("tl_atomic_i32_compare_exchange", atomic_i32_cmpxchg_type);
    
    add_fn("tl_atomic_i32_clone", clone_type);
    add_fn("tl_atomic_i32_free", free_type);

    if let Some(f) = module.get_function("tl_atomic_i32_new") { execution_engine.add_global_mapping(&f, runtime::atomic_ffi::tl_atomic_i32_new as *const () as usize); }
    if let Some(f) = module.get_function("tl_atomic_i32_load") { execution_engine.add_global_mapping(&f, runtime::atomic_ffi::tl_atomic_i32_load as *const () as usize); }
    if let Some(f) = module.get_function("tl_atomic_i32_store") { execution_engine.add_global_mapping(&f, runtime::atomic_ffi::tl_atomic_i32_store as *const () as usize); }
    if let Some(f) = module.get_function("tl_atomic_i32_add") { execution_engine.add_global_mapping(&f, runtime::atomic_ffi::tl_atomic_i32_add as *const () as usize); }
    if let Some(f) = module.get_function("tl_atomic_i32_sub") { execution_engine.add_global_mapping(&f, runtime::atomic_ffi::tl_atomic_i32_sub as *const () as usize); }
    if let Some(f) = module.get_function("tl_atomic_i32_swap") { execution_engine.add_global_mapping(&f, runtime::atomic_ffi::tl_atomic_i32_swap as *const () as usize); }
    if let Some(f) = module.get_function("tl_atomic_i32_compare_exchange") { execution_engine.add_global_mapping(&f, runtime::atomic_ffi::tl_atomic_i32_compare_exchange as *const () as usize); }
    if let Some(f) = module.get_function("tl_atomic_i32_clone") { execution_engine.add_global_mapping(&f, runtime::atomic_ffi::tl_atomic_i32_clone as *const () as usize); }
    if let Some(f) = module.get_function("tl_atomic_i32_free") { execution_engine.add_global_mapping(&f, runtime::atomic_ffi::tl_atomic_i32_free as *const () as usize); }

    // --- Time FFI (Duration, Instant, DateTime) ---
    // Duration: (i64) -> i64
    let duration_fn_type = i64_type.fn_type(&[i64_type.into()], false);
    add_fn("tl_rt_duration_from_secs", duration_fn_type);
    add_fn("tl_rt_duration_from_millis", duration_fn_type);
    add_fn("tl_rt_duration_from_nanos", duration_fn_type);
    add_fn("tl_rt_duration_as_secs", duration_fn_type);
    add_fn("tl_rt_duration_as_millis", duration_fn_type);

    // Instant: () -> i64, (i64) -> i64
    let instant_now_type = i64_type.fn_type(&[], false);
    add_fn("tl_rt_instant_now", instant_now_type);
    add_fn("tl_rt_instant_elapsed", duration_fn_type);

    // DateTime
    let datetime_now_type = i64_type.fn_type(&[context.ptr_type(AddressSpace::default()).into()], false);
    add_fn("tl_rt_datetime_now", datetime_now_type);
    add_fn("tl_rt_datetime_utc_now", instant_now_type); // () -> i64
    add_fn("tl_rt_datetime_from_timestamp", duration_fn_type); // (i64) -> i64
    add_fn("tl_rt_datetime_local_offset", instant_now_type); // () -> i64
    let datetime_component_type = i64_type.fn_type(&[i64_type.into(), i64_type.into()], false);
    add_fn("tl_rt_datetime_year", datetime_component_type);
    add_fn("tl_rt_datetime_month", datetime_component_type);
    add_fn("tl_rt_datetime_day", datetime_component_type);
    add_fn("tl_rt_datetime_hour", datetime_component_type);
    add_fn("tl_rt_datetime_minute", datetime_component_type);
    add_fn("tl_rt_datetime_second", datetime_component_type);
    // format: (i64, i64, ptr) -> ptr
    let datetime_format_type = void_ptr.fn_type(&[i64_type.into(), i64_type.into(), void_ptr.into()], false);
    add_fn("tl_rt_datetime_format", datetime_format_type);

    // Duration mappings
    if let Some(f) = module.get_function("tl_rt_duration_from_secs") { execution_engine.add_global_mapping(&f, runtime::time_ffi::tl_rt_duration_from_secs as *const () as usize); }
    if let Some(f) = module.get_function("tl_rt_duration_from_millis") { execution_engine.add_global_mapping(&f, runtime::time_ffi::tl_rt_duration_from_millis as *const () as usize); }
    if let Some(f) = module.get_function("tl_rt_duration_from_nanos") { execution_engine.add_global_mapping(&f, runtime::time_ffi::tl_rt_duration_from_nanos as *const () as usize); }
    if let Some(f) = module.get_function("tl_rt_duration_as_secs") { execution_engine.add_global_mapping(&f, runtime::time_ffi::tl_rt_duration_as_secs as *const () as usize); }
    if let Some(f) = module.get_function("tl_rt_duration_as_millis") { execution_engine.add_global_mapping(&f, runtime::time_ffi::tl_rt_duration_as_millis as *const () as usize); }

    // Instant mappings
    if let Some(f) = module.get_function("tl_rt_instant_now") { execution_engine.add_global_mapping(&f, runtime::time_ffi::tl_rt_instant_now as *const () as usize); }
    if let Some(f) = module.get_function("tl_rt_instant_elapsed") { execution_engine.add_global_mapping(&f, runtime::time_ffi::tl_rt_instant_elapsed as *const () as usize); }

    // DateTime mappings
    if let Some(f) = module.get_function("tl_rt_datetime_now") { execution_engine.add_global_mapping(&f, runtime::time_ffi::tl_rt_datetime_now as *const () as usize); }
    if let Some(f) = module.get_function("tl_rt_datetime_utc_now") { execution_engine.add_global_mapping(&f, runtime::time_ffi::tl_rt_datetime_utc_now as *const () as usize); }
    if let Some(f) = module.get_function("tl_rt_datetime_from_timestamp") { execution_engine.add_global_mapping(&f, runtime::time_ffi::tl_rt_datetime_from_timestamp as *const () as usize); }
    if let Some(f) = module.get_function("tl_rt_datetime_local_offset") { execution_engine.add_global_mapping(&f, runtime::time_ffi::tl_rt_datetime_local_offset as *const () as usize); }
    if let Some(f) = module.get_function("tl_rt_datetime_year") { execution_engine.add_global_mapping(&f, runtime::time_ffi::tl_rt_datetime_year as *const () as usize); }
    if let Some(f) = module.get_function("tl_rt_datetime_month") { execution_engine.add_global_mapping(&f, runtime::time_ffi::tl_rt_datetime_month as *const () as usize); }
    if let Some(f) = module.get_function("tl_rt_datetime_day") { execution_engine.add_global_mapping(&f, runtime::time_ffi::tl_rt_datetime_day as *const () as usize); }
    if let Some(f) = module.get_function("tl_rt_datetime_hour") { execution_engine.add_global_mapping(&f, runtime::time_ffi::tl_rt_datetime_hour as *const () as usize); }
    if let Some(f) = module.get_function("tl_rt_datetime_minute") { execution_engine.add_global_mapping(&f, runtime::time_ffi::tl_rt_datetime_minute as *const () as usize); }
    if let Some(f) = module.get_function("tl_rt_datetime_second") { execution_engine.add_global_mapping(&f, runtime::time_ffi::tl_rt_datetime_second as *const () as usize); }
    if let Some(f) = module.get_function("tl_rt_datetime_format") { execution_engine.add_global_mapping(&f, runtime::time_ffi::tl_rt_datetime_format as *const () as usize); }

    if let Some(f) = module.get_function("tl_set_device") {
        execution_engine.add_global_mapping(&f, runtime::tl_set_device as *const () as usize);
    }

    // [IDevice] device_ffi 統一マッピング
    if let Some(f) = module.get_function("tl_tensor_to_device") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_to_device as *const () as usize);
    }

    if let Some(f) = module.get_function("tl_report_runtime_error") {
        execution_engine.add_global_mapping(&f, runtime::tl_report_runtime_error as *const () as usize);
    }

    if let Some(f) = module.get_function("tl_tensor_acquire") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_acquire as *const () as usize);
    }

    // [IDevice] device_ffi 統一マッピング
    if let Some(f) = module.get_function("tl_tensor_replace_data") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_replace_data as *const () as usize);
    }

    // tl_tensor_sum_dim(t: *mut Tensor, dim: usize, keep: bool) -> *mut OpaqueTensor
    // usize -> i64 on 64-bit
    let sum_dim_type = void_ptr.fn_type(
        &[void_ptr.into(), i64_type.into(), context.bool_type().into()],
        false,
    );
    add_fn("tl_tensor_sum_dim", sum_dim_type);

    // tl_tensor_embedding(weight: *mut, indices: *mut, padding_idx: i64, scale_grad_by_freq: bool, sparse: bool) -> *mut
    let embedding_type = void_ptr.fn_type(&[
        void_ptr.into(),                // weight
        void_ptr.into(),                // indices
        i64_type.into(),                // padding_idx
        context.bool_type().into(),     // scale_grad_by_freq
        context.bool_type().into(),     // sparse
    ], false);
    add_fn("tl_tensor_embedding", embedding_type);

    // tl_tensor_sum(t: *mut) -> *mut OpaqueTensor
    let unary_res_type = void_ptr.fn_type(&[void_ptr.into()], false);
    add_fn("tl_tensor_sum", unary_res_type);

    // tl_tensor_div(a: *mut, b: *mut) -> *mut
    add_fn("tl_tensor_div", bin_type);

    // Comparisons
    add_fn("tl_tensor_eq", bin_type);
    add_fn("tl_tensor_neq", bin_type);
    add_fn("tl_tensor_gt", bin_type);
    add_fn("tl_tensor_lt", bin_type);
    add_fn("tl_tensor_ge", bin_type);
    add_fn("tl_tensor_le", bin_type);


    // tl_tensor_matmul(a: *mut, b: *mut) -> *mut
    add_fn("tl_tensor_matmul", bin_type);

    // tl_tensor_rem(a: *mut, b: *mut) -> *mut
    add_fn("tl_tensor_rem", bin_type);


    // Unary ops: exp, log
    add_fn("tl_tensor_exp", unary_res_type);
    add_fn("tl_tensor_log", unary_res_type);

    // Assign ops: add_assign, sub_assign, mul_assign, div_assign (return void)
    let assign_type = void_type.fn_type(&[void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_tensor_add_assign", assign_type);
    add_fn("tl_tensor_sub_assign", assign_type);
    add_fn("tl_tensor_mul_assign", assign_type);
    add_fn("tl_tensor_div_assign", assign_type);

    // Scalar assign ops: *_scalar_f32(tensor, f32) -> void
    let scalar_assign_type =
        void_type.fn_type(&[void_ptr.into(), context.f32_type().into()], false);
    add_fn("tl_tensor_add_assign_scalar_f32", scalar_assign_type);
    add_fn("tl_tensor_sub_assign_scalar_f32", scalar_assign_type);
    add_fn("tl_tensor_mul_assign_scalar_f32", scalar_assign_type);
    add_fn("tl_tensor_div_assign_scalar_f32", scalar_assign_type);
    add_fn("tl_tensor_mod_assign_scalar_f32", scalar_assign_type);

    // Mod assign (tensor, tensor) -> void
    add_fn("tl_tensor_mod_assign", assign_type);

    let i8_ptr = context.ptr_type(AddressSpace::default());
    let register_type = void_type.fn_type(&[i8_ptr.into(), void_ptr.into()], false);
    add_fn("tl_register_tensor", register_type);

    // tl_device_tensor_set_requires_grad(t: *mut Tensor, req_grad: bool) -> void
    let set_req_grad_type = void_type.fn_type(&[void_ptr.into(), context.bool_type().into()], false);
    add_fn("tl_device_tensor_set_requires_grad", set_req_grad_type);

    // tl_device_tensor_clip_grad_value(t: *mut Tensor, min: f64, max: f64) -> void
    let clip_grad_value_type = void_type.fn_type(&[void_ptr.into(), context.f64_type().into(), context.f64_type().into()], false);
    add_fn("tl_device_tensor_clip_grad_value", clip_grad_value_type);

    // tl_device_tensor_clip_grad_norm(t: *mut Tensor, max_norm: f64, norm_type: f64) -> f64
    let clip_grad_norm_type = context.f64_type().fn_type(&[void_ptr.into(), context.f64_type().into(), context.f64_type().into()], false);
    add_fn("tl_device_tensor_clip_grad_norm", clip_grad_norm_type);

    // strcmp(s1: *const i8, s2: *const i8) -> i32
    let strcmp_type = context
        .i32_type()
        .fn_type(&[i8_ptr.into(), i8_ptr.into()], false);
    add_fn("strcmp", strcmp_type);

    // tl_tensor_save(t: *mut Tensor, path: *const i8) -> void
    let save_type = void_type.fn_type(&[void_ptr.into(), i8_ptr.into()], false);
    add_fn("tl_tensor_save", save_type);

    // tl_tensor_load(path: *const i8) -> *mut Tensor
    let load_type = void_ptr.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_tensor_load", load_type);

    // tl_tensor_replace_data(dest: *mut Tensor, src: *mut Tensor) -> void
    let replace_data_type = void_type.fn_type(&[void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_tensor_replace_data", replace_data_type);

    // --- Logic / Knowledge Base Builtins ---

    // tl_kb_add_entity(name: *const i8) -> i64
    let add_entity_type = context.i64_type().fn_type(&[i8_ptr.into()], false);
    add_fn("tl_kb_add_entity", add_entity_type);

    // tl_kb_add_fact_serialized(relation: *const i8) -> void
    let add_fact_serialized_type = void_type.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_kb_add_fact_serialized", add_fact_serialized_type);

    // tl_kb_fact_args_clear()
    add_fn("tl_kb_fact_args_clear", void_type.fn_type(&[], false));

    // tl_kb_fact_args_add_*
    add_fn("tl_kb_fact_args_add_int", void_type.fn_type(&[context.i64_type().into()], false));
    add_fn("tl_kb_fact_args_add_float", void_type.fn_type(&[context.f64_type().into()], false));
    add_fn("tl_kb_fact_args_add_bool", void_type.fn_type(&[context.bool_type().into()], false));
    add_fn("tl_kb_fact_args_add_entity", void_type.fn_type(&[context.i64_type().into()], false));
    add_fn("tl_kb_fact_args_add_string", void_type.fn_type(&[i8_ptr.into()], false));

    // Old API for compatibility
    let args_ptr_type = context.ptr_type(AddressSpace::default());
    let add_fact_type = void_type.fn_type(
        &[
            i8_ptr.into(),
            args_ptr_type.into(),
            context.i64_type().into(), // arity
        ],
        false,
    );
    add_fn("tl_kb_add_fact", add_fact_type);

    // tl_kb_infer() -> void
    let infer_type = void_type.fn_type(&[], false);
    add_fn("tl_kb_infer", infer_type);

    // Rule Builder API
    // tl_kb_rule_start(head_rel: *const i8)
    let rule_start_type = void_type.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_kb_rule_start", rule_start_type);

    // tl_kb_rule_add_head_arg_var(index: i64)
    let arg_i64_type = void_type.fn_type(&[context.i64_type().into()], false);
    add_fn("tl_kb_rule_add_head_arg_var", arg_i64_type);
    add_fn("tl_kb_rule_add_head_arg_const_int", arg_i64_type);
    let arg_f64_type = void_type.fn_type(&[context.f64_type().into()], false);
    add_fn("tl_kb_rule_add_head_arg_const_float", arg_f64_type);
    add_fn("tl_kb_rule_add_head_arg_const_entity", arg_i64_type);

    add_fn("tl_kb_rule_add_body_atom", rule_start_type);
    add_fn("tl_kb_rule_add_body_atom_neg", rule_start_type);

    // tl_kb_rule_add_body_arg_var(index: i64)
    add_fn("tl_kb_rule_add_body_arg_var", arg_i64_type);
    add_fn("tl_kb_rule_add_body_arg_const_int", arg_i64_type);
    add_fn("tl_kb_rule_add_body_arg_const_float", arg_f64_type);
    add_fn("tl_kb_rule_add_body_arg_const_entity", arg_i64_type);

    // tl_kb_rule_finish()
    add_fn("tl_kb_rule_finish", infer_type);

    // --- Map Support ---
    // tl_tensor_map_new() -> *mut Map
    let map_new_type = void_ptr.fn_type(&[], false);
    add_fn("tl_tensor_map_new", map_new_type);

    // tl_tensor_map_insert(map, name, tensor)
    let map_insert_type =
        void_type.fn_type(&[void_ptr.into(), i8_ptr.into(), void_ptr.into()], false);
    add_fn("tl_tensor_map_insert", map_insert_type);

    // tl_tensor_map_save(map, path)
    let map_save_type = void_type.fn_type(&[void_ptr.into(), i8_ptr.into()], false);
    add_fn("tl_tensor_map_save", map_save_type);

    // tl_tensor_map_load(path) -> *mut Map
    let map_load_type = void_ptr.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_tensor_map_load", map_load_type);

    // tl_tensor_map_free(map)
    let map_free_type = void_type.fn_type(&[void_ptr.into()], false);
    add_fn("tl_tensor_map_free", map_free_type);




    // Reshape
    let reshape_dims_type =
        void_ptr.fn_type(&[void_ptr.into(), i64_ptr.into(), i64_type.into()], false);
    add_fn("tl_tensor_reshape_dims", reshape_dims_type);

    let reshape_tensor_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_tensor_reshape_new", reshape_tensor_type);

    // Randn
    // tl_tensor_randn_debug(rank: usize, shape: *const usize, seed: u64, req_grad: bool) -> *mut OpaqueTensor
    let randn_type = void_ptr.fn_type(
        &[
            i64_type.into(),            // Rank
            usize_ptr.into(),           // Shape Ptr
            i64_type.into(),            // Seed (unused, pass 0)
            context.bool_type().into(), // Req Grad
        ],
        false,
    );
    add_fn("tl_tensor_randn_debug", randn_type);

    // tl_tensor_zeros(rank, shape_ptr, req_grad) -> *mut OpaqueTensor
    let zeros_type = void_ptr.fn_type(
        &[
            i64_type.into(),            // rank
            usize_ptr.into(),           // shape pointer
            context.bool_type().into(), // req_grad
        ],
        false,
    );

    add_fn("tl_tensor_zeros", zeros_type);
    add_fn("tl_tensor_ones", zeros_type); // Reusing zeros_type (signature matches)

    // tl_tensor_full(rank, shape_ptr, value: f32, req_grad: bool) -> *mut OpaqueTensor
    let full_type = void_ptr.fn_type(
        &[
            i64_type.into(),            // rank
            usize_ptr.into(),           // shape pointer
            f32_type.into(),            // value
            context.bool_type().into(), // req_grad
        ],
        false,
    );
    add_fn("tl_tensor_full", full_type);

    // tl_tensor_eye(n: i64, req_grad: bool) -> *mut OpaqueTensor
    let eye_type = void_ptr.fn_type(
        &[
            i64_type.into(),            // n
            context.bool_type().into(), // req_grad
        ],
        false,
    );
    add_fn("tl_tensor_eye", eye_type);

    // tl_tensor_arange(start: f64, end: f64, step: f64) -> *mut OpaqueTensor
    let arange_type = void_ptr.fn_type(
        &[
            f64_type.into(), // start
            f64_type.into(), // end
            f64_type.into(), // step
        ],
        false,
    );
    add_fn("tl_tensor_arange", arange_type);

    // tl_tensor_zeros_like(t) -> *mut OpaqueTensor
    // tl_tensor_ones_like(t) -> *mut OpaqueTensor
    add_fn("tl_tensor_zeros_like", unary_type);
    add_fn("tl_tensor_ones_like", unary_type);

    // tl_tensor_from_vec_f32(data_vec: void*, shape_vec: void*) -> Tensor*
    let from_vec_f32_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_tensor_from_vec_f32", from_vec_f32_type);

    // tl_tensor_from_vec_u8(data: void*, offset: i64, shape_ptr: void*, rank: i64) -> Tensor*
    let from_vec_u8_type = void_ptr.fn_type(&[void_ptr.into(), i64_type.into(), void_ptr.into(), i64_type.into()], false);
    add_fn("tl_tensor_from_vec_u8", from_vec_u8_type);
    
    // tl_tensor_from_vec_u8_f32_shape(data: void*, offset: i64, shape_ptr: void*, rank: i64) -> Tensor*
    add_fn("tl_tensor_from_vec_u8_f32_shape", from_vec_u8_type);
    
    // tl_tensor_from_u8_labels(data: i8*, len: i64) -> Tensor*
    let from_u8_labels_type = void_ptr.fn_type(&[i8_ptr.into(), i64_type.into()], false);
    add_fn("tl_tensor_from_u8_labels", from_u8_labels_type);

    // tl_tensor_to_vec_f32(t: Tensor*) -> Vec<f32>*
    let to_vec_f32_type = void_ptr.fn_type(&[void_ptr.into()], false);
    add_fn("tl_tensor_to_vec_f32", to_vec_f32_type);

    // tl_tensor_linspace(start: f64, end: f64, steps: i64) -> *mut OpaqueTensor
    let linspace_type = void_ptr.fn_type(
        &[
            f64_type.into(), // start
            f64_type.into(), // end
            i64_type.into(), // steps
        ],
        false,
    );
    add_fn("tl_tensor_linspace", linspace_type);

    // tl_tensor_rand(rank, shape_ptr, req_grad) -> *mut OpaqueTensor (same sig as zeros)
    add_fn("tl_tensor_rand", zeros_type);

    // tl_tensor_rand_like / tl_tensor_randn_like (unary tensor -> tensor)
    add_fn("tl_tensor_rand_like", unary_type);
    add_fn("tl_tensor_randn_like", unary_type);

    // tl_tensor_where_cond(cond, x, y) -> Tensor*
    let ternary_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_tensor_where_cond", ternary_type);

    // tl_tensor_masked_fill_scalar(t, mask, value) -> Tensor*
    let masked_fill_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into(), f64_type.into()], false);
    add_fn("tl_tensor_masked_fill_scalar", masked_fill_type);

    // tl_tensor_var_dim(t, dim, keepdim) -> Tensor*  (same sig as mean_dim)
    // tl_tensor_std_dim(t, dim, keepdim) -> Tensor*
    let reduce_dim_type = void_ptr.fn_type(&[void_ptr.into(), i64_type.into(), context.bool_type().into()], false);
    add_fn("tl_tensor_var_dim", reduce_dim_type);
    add_fn("tl_tensor_std_dim", reduce_dim_type);
    // tl_tensor_var(t) -> Tensor*  / tl_tensor_std(t) -> Tensor*
    add_fn("tl_tensor_var", unary_type);
    add_fn("tl_tensor_std", unary_type);

    // tl_tensor_prod_dim / tl_tensor_prod (same sigs as var/std)
    add_fn("tl_tensor_prod_dim", reduce_dim_type);
    add_fn("tl_tensor_prod", unary_type);

    // tl_tensor_fill_(t: void*, value: f32) -> void
    let fill_type = context.void_type().fn_type(&[void_ptr.into(), f32_type.into()], false);
    add_fn("tl_tensor_fill_", fill_type);

    // cumsum / norm / topk / logical_*
    let cumsum_type = void_ptr.fn_type(&[void_ptr.into(), i64_type.into()], false);
    add_fn("tl_tensor_cumsum", cumsum_type);
    let norm_type = void_ptr.fn_type(&[void_ptr.into(), f32_type.into(), i64_type.into()], false);
    add_fn("tl_tensor_norm", norm_type);
    let topk_type = void_ptr.fn_type(&[void_ptr.into(), i64_type.into(), i64_type.into()], false);
    add_fn("tl_tensor_topk", topk_type);
    let logical_binary_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_tensor_logical_and", logical_binary_type);
    add_fn("tl_tensor_logical_or", logical_binary_type);
    add_fn("tl_tensor_logical_not", unary_type);

    // expand / stack / chunk / split
    // expand uses same sig as reshape_dims: (void*, ptr, i64) -> void*
    let expand_type = void_ptr.fn_type(&[void_ptr.into(), context.ptr_type(inkwell::AddressSpace::default()).into(), i64_type.into()], false);
    add_fn("tl_tensor_expand", expand_type);
    // expand_new: Tensor shape variant (same sig as reshape_new: (void*, void*) -> void*)
    let expand_new_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_tensor_expand_new", expand_new_type);
    let stack_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into(), i64_type.into()], false);
    add_fn("tl_tensor_stack", stack_type);
    // chunk(t, num_chunks, dim, index) -> Tensor*  / split(t, split_size, dim, index) -> Tensor*
    let chunk_split_type = void_ptr.fn_type(&[void_ptr.into(), i64_type.into(), i64_type.into(), i64_type.into()], false);
    add_fn("tl_tensor_chunk", chunk_split_type);
    add_fn("tl_tensor_split", chunk_split_type);

    // leaky_relu(t, slope) -> Tensor
    let leaky_relu_type = void_ptr.fn_type(&[void_ptr.into(), f32_type.into()], false);
    add_fn("tl_tensor_leaky_relu", leaky_relu_type);

    // elu(t, alpha) -> Tensor (same sig as leaky_relu)
    add_fn("tl_tensor_elu", leaky_relu_type);
    // mish(t) -> Tensor (same sig as unary)
    add_fn("tl_tensor_mish", unary_type);

    // loss functions
    let loss_binary_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_tensor_mse_loss", loss_binary_type);
    add_fn("tl_tensor_l1_loss", loss_binary_type);
    add_fn("tl_tensor_bce_loss", loss_binary_type);
    add_fn("tl_tensor_nll_loss", loss_binary_type);

    // linear(input, weight, bias) -> Tensor
    let linear_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_tensor_linear", linear_type);
    // hardswish/hardsigmoid (same sig as unary)
    add_fn("tl_tensor_hardswish", unary_type);
    add_fn("tl_tensor_hardsigmoid", unary_type);

    // group_norm(input, num_groups, weight, bias, eps) -> Tensor
    let group_norm_type = void_ptr.fn_type(&[void_ptr.into(), i64_type.into(), void_ptr.into(), void_ptr.into(), f64_type.into()], false);
    add_fn("tl_tensor_group_norm", group_norm_type);
    // adaptive_avg_pool2d(input, output_h, output_w) -> Tensor
    let adaptive_pool_type = void_ptr.fn_type(&[void_ptr.into(), i64_type.into(), i64_type.into()], false);
    add_fn("tl_tensor_adaptive_avg_pool2d", adaptive_pool_type);
    // pad(input, pad_left, pad_right, value) -> Tensor
    let pad_type = void_ptr.fn_type(&[void_ptr.into(), i64_type.into(), i64_type.into(), f32_type.into()], false);
    add_fn("tl_tensor_pad", pad_type);
    // instance_norm(input, weight, bias, eps) -> Tensor
    let instance_norm_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into(), void_ptr.into(), f64_type.into()], false);
    add_fn("tl_tensor_instance_norm", instance_norm_type);

    // conv1d(input, weight, bias, stride, padding) -> Tensor
    let conv1d_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into(), void_ptr.into(), i64_type.into(), i64_type.into()], false);
    add_fn("tl_tensor_conv1d", conv1d_type);
    // kl_div_loss(pred, target) -> Tensor
    add_fn("tl_tensor_kl_div_loss", loss_binary_type);

    // conv_transpose2d(input, weight, bias, stride, padding, output_padding) -> Tensor
    let conv_transpose2d_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into(), void_ptr.into(), i64_type.into(), i64_type.into(), i64_type.into()], false);
    add_fn("tl_tensor_conv_transpose2d", conv_transpose2d_type);
    // interpolate(input, output_h, output_w, mode) -> Tensor
    let interpolate_type = void_ptr.fn_type(&[void_ptr.into(), i64_type.into(), i64_type.into(), i64_type.into()], false);
    add_fn("tl_tensor_interpolate", interpolate_type);

    // scaled_dot_product_attention(q, k, v, mask) -> Tensor
    let sdpa_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into(), void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_tensor_sdpa", sdpa_type);
    // top_k_sample(logits, k) -> Tensor
    let topk_type = void_ptr.fn_type(&[void_ptr.into(), i64_type.into()], false);
    add_fn("tl_tensor_top_k_sample", topk_type);
    // top_p_sample(logits, p) -> Tensor
    let topp_type = void_ptr.fn_type(&[void_ptr.into(), f64_type.into()], false);
    add_fn("tl_tensor_top_p_sample", topp_type);
    // temperature_scale(logits, temperature) -> Tensor
    add_fn("tl_tensor_temperature_scale", topp_type); // same sig: (ptr, f64) -> ptr
    // repetition_penalty(logits, tokens, penalty) -> Tensor
    let rep_penalty_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into(), f64_type.into()], false);
    add_fn("tl_tensor_repetition_penalty", rep_penalty_type);
    // dot(a, b) -> Tensor
    add_fn("tl_tensor_dot", loss_binary_type); // same sig: (ptr, ptr) -> ptr

    // VarBuilder
    // tl_varbuilder_get(name: *const c_char, rank: usize, shape: *const usize) -> *mut OpaqueTensor
    let varbuilder_get_type =
        void_ptr.fn_type(&[i8_ptr.into(), i64_type.into(), usize_ptr.into()], false);
    add_fn("tl_varbuilder_get", varbuilder_get_type);

    // tl_varbuilder_get_from_tensor(name: *const c_char, shape_tensor: *mut OpaqueTensor) -> *mut OpaqueTensor
    let varbuilder_get_tensor_type = void_ptr.fn_type(&[i8_ptr.into(), void_ptr.into()], false);
    add_fn("tl_varbuilder_get_from_tensor", varbuilder_get_tensor_type);

    // update_all_params(lr: f32)
    let update_type = void_type.fn_type(&[f32_type.into()], false);
    add_fn("tl_update_all_params", update_type);

    // grad(name: *const c_char) -> *mut OpaqueTensor
    let grad_type = void_ptr.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_varbuilder_grad", grad_type);

    // Autograd helpers
    let backward_type = void_type.fn_type(&[void_ptr.into()], false);
    add_fn("tl_tensor_backward", backward_type);

    let grad_fn_type = void_ptr.fn_type(&[void_ptr.into()], false);
    add_fn("tl_tensor_grad", grad_fn_type);

    let detach_type = void_ptr.fn_type(&[void_ptr.into(), context.bool_type().into()], false);
    add_fn("tl_tensor_detach", detach_type);

    // Contiguous (メモリレイアウト連続化)
    let contiguous_type = void_ptr.fn_type(&[void_ptr.into()], false);
    add_fn("tl_tensor_contiguous", contiguous_type);

    // Softmax / CrossEntropy
    let softmax_type = void_ptr.fn_type(&[void_ptr.into(), i64_type.into()], false);
    add_fn("tl_tensor_softmax", softmax_type);

    let cross_entropy_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_tensor_cross_entropy", cross_entropy_type);

    // Checkpointing: save_all_params(dir), load_all...
    let params_io_type = void_type.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_save_all_params", params_io_type);
    let add_param_type = void_type.fn_type(&[i8_ptr.into(), void_ptr.into()], false);
    add_fn("tl_add_parameter", add_param_type);
    add_fn("tl_load_all_params", params_io_type);

    // Parameter Registration
    let register_param_type = void_ptr.fn_type(&[void_ptr.into()], false);
    add_fn("tl_register_parameter", register_param_type);

    // String ops
    let str_new_type = i8_ptr.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_string_new", str_new_type);

    let str_concat_type = i8_ptr.fn_type(&[i8_ptr.into(), i8_ptr.into()], false);
    add_fn("tl_string_concat", str_concat_type);

    // File ops
    let file_open_type = void_ptr.fn_type(&[i8_ptr.into(), i8_ptr.into()], false);
    add_fn("tl_file_open", file_open_type);

    let file_read_type = i8_ptr.fn_type(&[void_ptr.into()], false); // Returns String (i8*)
    add_fn("tl_file_read_string", file_read_type);

    let file_write_type = void_type.fn_type(&[void_ptr.into(), i8_ptr.into()], false);
    add_fn("tl_file_write_string", file_write_type);

    let file_close_type = void_type.fn_type(&[void_ptr.into()], false);
    add_fn("tl_file_close", file_close_type);

    // Path
    let path_new_type = void_ptr.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_path_new", path_new_type);

    let path_join_type = void_ptr.fn_type(&[void_ptr.into(), i8_ptr.into()], false);
    add_fn("tl_path_join", path_join_type);

    let path_exists_type = context.bool_type().fn_type(&[void_ptr.into()], false);
    add_fn("tl_path_exists", path_exists_type);
    add_fn("tl_path_is_dir", path_exists_type);
    add_fn("tl_path_is_file", path_exists_type);

    // tl_mem_get_buffer(slot_id: i64, min_size: i64) -> *mut c_void
    let get_buffer_type = void_ptr.fn_type(&[i64_type.into(), i64_type.into()], false);
    add_fn("tl_mem_get_buffer", get_buffer_type);
    
    // tl_log_alloc(ptr, size, file, line)
    let log_alloc_type = void_type.fn_type(&[void_ptr.into(), i64_type.into(), i8_ptr.into(), i32_type.into()], false);
    add_fn("tl_log_alloc", log_alloc_type);

    // tl_log_free(ptr, file, line)
    let log_free_type = void_type.fn_type(&[void_ptr.into(), i8_ptr.into(), i32_type.into()], false);
    add_fn("tl_log_free", log_free_type);
    
    // tl_trace_mem(file, line, col, tag)
    let trace_mem_type = void_type.fn_type(
        &[
             i8_ptr.into(),
             i32_type.into(),
             i32_type.into(),
             i8_ptr.into(),
        ],
        false
    );
    add_fn("tl_trace_mem", trace_mem_type);

    if let Some(f) = module.get_function("tl_log_alloc") {
        execution_engine.add_global_mapping(&f, runtime::tl_log_alloc as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_log_free") {
        execution_engine.add_global_mapping(&f, runtime::tl_log_free as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_trace_mem") {
        execution_engine.add_global_mapping(&f, runtime::tl_trace_mem as *const () as usize);
    }
    
    if let Some(f) = module.get_function("tl_mem_get_buffer") {
        execution_engine.add_global_mapping(&f, runtime::tl_mem_get_buffer as *const () as usize);
    }

    // Function Frames
    let fn_enter_type = void_type.fn_type(&[i64_type.into()], false);
    add_fn("tl_mem_function_enter", fn_enter_type);
    let fn_exit_type = void_type.fn_type(&[], false);
    add_fn("tl_mem_function_exit", fn_exit_type);

    if let Some(f) = module.get_function("tl_mem_function_enter") {
        execution_engine.add_global_mapping(&f, runtime::tl_mem_function_enter as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_mem_function_exit") {
        execution_engine.add_global_mapping(&f, runtime::tl_mem_function_exit as *const () as usize);
    }
    
    let path_to_str_type = i8_ptr.fn_type(&[void_ptr.into()], false);
    add_fn("tl_path_to_string", path_to_str_type);

    // DEBUG: Explicitly map tl_print_string
    if let Some(f) = module.get_function("tl_print_string") {
        execution_engine.add_global_mapping(&f, runtime::tl_print_string as *const () as usize);
    }
    
    // Explicitly map tl_mem_function_exit
    let exit_fn_type = void_type.fn_type(&[], false);
    add_fn("tl_mem_function_exit", exit_fn_type);
    if let Some(f) = module.get_function("tl_mem_function_exit") {
        execution_engine.add_global_mapping(&f, runtime::memory_manager::tl_mem_function_exit as *const () as usize);
    }

    // Explicitly map tl_arena_init
    let arena_init_type = void_type.fn_type(&[i64_type.into()], false);
    add_fn("tl_arena_init", arena_init_type);
    // Duplicate mapping removed (handled at 1835)

    let path_free_type = void_type.fn_type(&[void_ptr.into()], false);
    add_fn("tl_path_free", path_free_type);

    // Http
    let http_dl_type = context
        .bool_type()
        .fn_type(&[i8_ptr.into(), i8_ptr.into()], false);
    add_fn("tl_http_download", http_dl_type);

    let http_get_type = i8_ptr.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_http_get", http_get_type);

    // Env
    let env_get_type = i8_ptr.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_env_get", env_get_type);

    let env_set_type = void_type.fn_type(&[i8_ptr.into(), i8_ptr.into()], false);
    add_fn("tl_env_set", env_set_type);

    // Args (command line arguments)
    let args_count_type = i64_type.fn_type(&[], false);
    add_fn("tl_args_count", args_count_type);

    let args_get_type = i8_ptr.fn_type(&[i64_type.into()], false);
    add_fn("tl_args_get", args_get_type);

    // tl_string_to_i64(s: *const i8) -> i64
    let str_to_int_type = i64_type.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_string_to_i64", str_to_int_type);

    // (tl_string_char_at は上で宣言済み - 重複削除)


    let string_len_type = i64_type.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_string_len", string_len_type);

    // tl_read_line(prompt: *mut StringStruct) -> *mut StringStruct (void_ptr -> i8_ptr/void_ptr)
    // TL String is passed as pointer to struct, usually treated as void* in declarations if struct type not avail.
    let read_line_type = i8_ptr.fn_type(&[void_ptr.into()], false); // prompt is StringStruct*
    add_fn("tl_read_line", read_line_type);

    // System
    let sys_time_type = f32_type.fn_type(&[], false); // Return f32 timestamp
    add_fn("tl_system_time", sys_time_type);

    let sys_sleep_type = void_type.fn_type(&[f32_type.into()], false);
    add_fn("tl_system_sleep", sys_sleep_type);

    let mem_mb_type = f64_type.fn_type(&[], false);
    add_fn("tl_get_memory_mb", mem_mb_type);
    add_fn("tl_get_metal_pool_mb", mem_mb_type);

    let purge_type = void_type.fn_type(&[], false);
    add_fn("tl_mem_purge", purge_type);

    let mem_count_type = i64_type.fn_type(&[], false);
    add_fn("tl_get_memory_bytes", mem_count_type);
    add_fn("tl_get_metal_pool_bytes", mem_count_type);
    add_fn("tl_get_metal_pool_count", mem_count_type);
    add_fn("tl_get_pool_count", mem_count_type);
    add_fn("tl_get_refcount_count", mem_count_type);
    add_fn("tl_get_scope_depth", mem_count_type);
    let trace_type = void_type.fn_type(
        &[
            i8_ptr.into(),
            context.i32_type().into(),
            context.i32_type().into(),
            i8_ptr.into(),
        ],
        false,
    );
    add_fn("tl_trace_mem", trace_type);
    let metal_sync_type = void_type.fn_type(&[], false);
    add_fn("tl_metal_sync", metal_sync_type);

    // tl_system_mem_report() -> void — メモリ統計レポート
    let mem_report_type = void_type.fn_type(&[], false);
    add_fn("tl_system_mem_report", mem_report_type);

    // Memory Scope
    let enter_scope_type = void_type.fn_type(&[], false);
    add_fn("tl_mem_enter_scope", enter_scope_type);

    let exit_scope_type = void_type.fn_type(&[], false);
    add_fn("tl_mem_exit_scope", exit_scope_type);

    let reg_struct_type = void_type.fn_type(&[void_ptr.into()], false);
    add_fn("tl_mem_register_struct", reg_struct_type);
    add_fn("tl_mem_register_tensor", reg_struct_type);
    add_fn("tl_mem_unregister", reg_struct_type);

    let prepare_ret_type = void_ptr.fn_type(&[void_ptr.into()], false);
    add_fn("tl_tensor_prepare_return", prepare_ret_type);

    // Pool / Arena
    let pool_acq = void_ptr.fn_type(&[i64_type.into()], false);
    add_fn("tl_pool_acquire", pool_acq);

    let pool_rel = void_type.fn_type(&[void_ptr.into(), i64_type.into()], false);
    add_fn("tl_pool_release", pool_rel);

    let arena_init = void_type.fn_type(&[i64_type.into()], false);
    add_fn("tl_arena_init", arena_init);

    let arena_alloc = void_ptr.fn_type(&[i64_type.into()], false);
    add_fn("tl_arena_alloc", arena_alloc);

    let arena_free = void_type.fn_type(&[], false);
    add_fn("tl_arena_free", arena_free);

    let arena_active = context.bool_type().fn_type(&[], false);
    add_fn("tl_arena_is_active", arena_active);

    let arena_reset = void_type.fn_type(&[], false);
    add_fn("tl_arena_reset", arena_reset);

    let arena_offset = i64_type.fn_type(&[], false);
    add_fn("tl_arena_get_offset", arena_offset);

    let arena_capacity = i64_type.fn_type(&[], false);
    add_fn("tl_arena_get_capacity", arena_capacity);

    // --- LLM Builtins ---
    // tl_tokenizer_new(path: *const c_char) -> i64 (handle)
    let tok_new_type = i64_type.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_tokenizer_new", tok_new_type);

    // tl_tokenizer_encode(tok: i64, prompt: *const c_char) -> *mut OpaqueTensor
    let tok_enc_type = void_ptr.fn_type(&[i64_type.into(), i8_ptr.into()], false);
    add_fn("tl_tokenizer_encode", tok_enc_type);

    // tl_tokenizer_encode_chat(tok: i64, user_text: *const c_char) -> *mut OpaqueTensor
    let tok_enc_chat_type = void_ptr.fn_type(&[i64_type.into(), i8_ptr.into()], false);
    add_fn("tl_tokenizer_encode_chat", tok_enc_chat_type);

    // tl_tokenizer_encode_chat_zephyr(tok: i64, user_text: *const c_char) -> *mut OpaqueTensor
    let tok_enc_chat_zephyr_type = void_ptr.fn_type(&[i64_type.into(), i8_ptr.into()], false);
    add_fn("tl_tokenizer_encode_chat_zephyr", tok_enc_chat_zephyr_type);

    // tl_tokenizer_decode(tok: i64, ids: *mut OpaqueTensor) -> *const c_char
    let tok_dec_type = i8_ptr.fn_type(&[i64_type.into(), void_ptr.into()], false);
    add_fn("tl_tokenizer_decode", tok_dec_type);

    // tl_gguf_load(path: *const c_char) -> *mut OpaqueTensorMap
    let gguf_load_type = void_ptr.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_gguf_load", gguf_load_type);

    // tl_tensor_map_get(map: *mut Map, name: *const c_char) -> *mut Tensor
    let map_get_type = void_ptr.fn_type(&[void_ptr.into(), i8_ptr.into()], false);
    add_fn("tl_tensor_map_get", map_get_type);

    // tl_tensor_cat(tensors: *mut Vec, dim: i64) -> *mut Tensor
    let cat_type = void_ptr.fn_type(&[void_ptr.into(), i64_type.into()], false);
    add_fn("tl_tensor_cat", cat_type);

    // tl_tensor_silu(t: *mut) -> *mut
    add_fn("tl_tensor_silu", unary_type);

    let scale_type = void_ptr.fn_type(&[void_ptr.into(), f32_type.into()], false);
    add_fn("tl_tensor_scale", scale_type);
    // tl_tensor_cat2(a: *mut, b: *mut, dim: i64) -> *mut
    let cat2_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into(), i64_type.into()], false);
    add_fn("tl_tensor_cat2", cat2_type);

    // tl_tensor_cat_4d(a: *mut, b: *mut, dim: i64) -> *mut (alias for type safety)
    add_fn("tl_tensor_cat_4d", cat2_type);

    // tl_tensor_rms_norm(x: *mut, w: *mut, eps: f32) -> *mut
    let rms_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into(), f32_type.into()], false);
    add_fn("tl_tensor_rms_norm", rms_type);

    // tl_tensor_apply_rope(x: *mut, cos: *mut, sin: *mut) -> *mut
    let rope_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_tensor_apply_rope", rope_type);

    // Aliases for different ranks
    add_fn("tl_tensor_transpose_2d", transpose_type);
    add_fn("tl_tensor_matmul_4d", bin_type);
    add_fn("tl_tensor_add_4d", bin_type);
    add_fn("tl_tensor_silu_4d", unary_type);
    let tensor_reshape_2d_type =
        void_ptr.fn_type(&[void_ptr.into(), void_ptr.into(), i64_type.into()], false);
    add_fn("tl_tensor_reshape_2d", tensor_reshape_2d_type);
    add_fn("tl_tensor_reshape_3d_to_2d", tensor_reshape_2d_type); // alias

    // Map get alias (first arg is ptr handle from tl_gguf_load)
    let map_get_1d_type = void_ptr.fn_type(&[void_ptr.into(), i8_ptr.into()], false);
    add_fn("tl_tensor_map_get_1d", map_get_1d_type);

    // Narrow (slice): tl_tensor_narrow(t, dim, start, length) -> t
    let narrow_type = void_ptr.fn_type(
        &[
            void_ptr.into(),
            i64_type.into(),
            i64_type.into(),
            i64_type.into(),
        ],
        false,
    );
    add_fn("tl_tensor_narrow", narrow_type);

    // Repeat interleave: tl_tensor_repeat_interleave(t, repeats, dim) -> t
    let repeat_interleave_type =
        void_ptr.fn_type(&[void_ptr.into(), i64_type.into(), i64_type.into()], false);
    add_fn("tl_tensor_repeat_interleave", repeat_interleave_type);

    // RoPE Factories: tl_tensor_rope_new_cos(dim: i64, len: i64, theta: f32) -> *mut
    let rope_new_type =
        void_ptr.fn_type(&[i64_type.into(), i64_type.into(), f32_type.into()], false);
    add_fn("tl_tensor_rope_new_cos", rope_new_type);
    add_fn("tl_tensor_rope_new_sin", rope_new_type);

    // Causal Mask: tl_tensor_new_causal_mask(dim: i64) -> tensor
    let causal_mask_type = void_ptr.fn_type(&[i64_type.into()], false);
    add_fn("tl_tensor_new_causal_mask", causal_mask_type);

    // tl_tensor_cat_i64(a, b, dim) -> t
    let cat_i64_type =
        void_ptr.fn_type(&[void_ptr.into(), void_ptr.into(), i64_type.into()], false);
    add_fn("tl_tensor_cat_i64", cat_i64_type);

    // tl_tensor_device_id(t) -> i64
    let device_id_type = i64_type.fn_type(&[void_ptr.into()], false);
    add_fn("tl_tensor_device_id", device_id_type);

    // --- Global Mappings ---
    // Mapping symbols is critical for JIT.
    // We do it here to keep CodeGenerator::new clean.

    if let Some(f) = module.get_function("tl_print_string") {
        execution_engine.add_global_mapping(&f, runtime::tl_print_string as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_display_string") {
        execution_engine.add_global_mapping(&f, runtime::tl_display_string as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_prompt") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_prompt as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_print_f32") {
        execution_engine.add_global_mapping(&f, runtime::tl_print_f32 as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_display_f32") {
        execution_engine.add_global_mapping(&f, runtime::tl_display_f32 as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_print_f64") {
        execution_engine.add_global_mapping(&f, runtime::tl_print_f64 as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_display_f64") {
        execution_engine.add_global_mapping(&f, runtime::tl_display_f64 as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_print_bool") {
        execution_engine.add_global_mapping(&f, runtime::tl_print_bool as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_display_bool") {
        execution_engine.add_global_mapping(&f, runtime::tl_display_bool as *const () as usize);
    }
    let f32_unary_mappings: [(&str, usize); 31] = [
        ("tl_f32_abs", runtime::tl_f32_abs as *const () as usize),
        ("tl_f32_acos", runtime::tl_f32_acos as *const () as usize),
        ("tl_f32_acosh", runtime::tl_f32_acosh as *const () as usize),
        ("tl_f32_asin", runtime::tl_f32_asin as *const () as usize),
        ("tl_f32_asinh", runtime::tl_f32_asinh as *const () as usize),
        ("tl_f32_atan", runtime::tl_f32_atan as *const () as usize),
        ("tl_f32_atanh", runtime::tl_f32_atanh as *const () as usize),
        ("tl_f32_cbrt", runtime::tl_f32_cbrt as *const () as usize),
        ("tl_f32_ceil", runtime::tl_f32_ceil as *const () as usize),
        ("tl_f32_cos", runtime::tl_f32_cos as *const () as usize),
        ("tl_f32_cosh", runtime::tl_f32_cosh as *const () as usize),
        ("tl_f32_exp", runtime::tl_f32_exp as *const () as usize),
        ("tl_f32_exp2", runtime::tl_f32_exp2 as *const () as usize),
        (
            "tl_f32_exp_m1",
            runtime::tl_f32_exp_m1 as *const () as usize,
        ),
        ("tl_f32_floor", runtime::tl_f32_floor as *const () as usize),
        ("tl_f32_fract", runtime::tl_f32_fract as *const () as usize),
        ("tl_f32_ln", runtime::tl_f32_ln as *const () as usize),
        ("tl_f32_ln_1p", runtime::tl_f32_ln_1p as *const () as usize),
        ("tl_f32_log10", runtime::tl_f32_log10 as *const () as usize),
        ("tl_f32_log2", runtime::tl_f32_log2 as *const () as usize),
        ("tl_f32_recip", runtime::tl_f32_recip as *const () as usize),
        ("tl_f32_round", runtime::tl_f32_round as *const () as usize),
        (
            "tl_f32_signum",
            runtime::tl_f32_signum as *const () as usize,
        ),
        ("tl_f32_sin", runtime::tl_f32_sin as *const () as usize),
        ("tl_f32_sinh", runtime::tl_f32_sinh as *const () as usize),
        ("tl_f32_sqrt", runtime::tl_f32_sqrt as *const () as usize),
        ("tl_f32_tan", runtime::tl_f32_tan as *const () as usize),
        ("tl_f32_tanh", runtime::tl_f32_tanh as *const () as usize),
        (
            "tl_f32_to_degrees",
            runtime::tl_f32_to_degrees as *const () as usize,
        ),
        (
            "tl_f32_to_radians",
            runtime::tl_f32_to_radians as *const () as usize,
        ),
        ("tl_f32_trunc", runtime::tl_f32_trunc as *const () as usize),
    ];
    for (name, addr) in f32_unary_mappings {
        if let Some(f) = module.get_function(name) {
            execution_engine.add_global_mapping(&f, addr);
        }
    }

    // f32.to_string() -> *mut StringStruct (returns pointer, not f32)
    let f32_to_string_type = i8_ptr.fn_type(&[context.f32_type().into()], false);
    add_fn("tl_f32_to_string", f32_to_string_type);
    if let Some(f) = module.get_function("tl_f32_to_string") {
        execution_engine.add_global_mapping(&f, runtime::tl_f32_to_string as *const () as usize);
    }

    // f64.to_string() -> *mut StringStruct (returns pointer, not f64)
    let f64_to_string_type = i8_ptr.fn_type(&[context.f64_type().into()], false);
    add_fn("tl_f64_to_string", f64_to_string_type);
    if let Some(f) = module.get_function("tl_f64_to_string") {
        execution_engine.add_global_mapping(&f, runtime::tl_f64_to_string as *const () as usize);
    }
    let f32_binary_mappings: [(&str, usize); 5] = [
        ("tl_f32_atan2", runtime::tl_f32_atan2 as *const () as usize),
        (
            "tl_f32_copysign",
            runtime::tl_f32_copysign as *const () as usize,
        ),
        ("tl_f32_hypot", runtime::tl_f32_hypot as *const () as usize),
        ("tl_f32_log", runtime::tl_f32_log as *const () as usize),
        ("tl_f32_powf", runtime::tl_f32_powf as *const () as usize),
    ];
    for (name, addr) in f32_binary_mappings {
        if let Some(f) = module.get_function(name) {
            execution_engine.add_global_mapping(&f, addr);
        }
    }
    if let Some(f) = module.get_function("tl_f32_powi") {
        execution_engine.add_global_mapping(&f, runtime::tl_f32_powi as *const () as usize);
    }
    let f64_unary_mappings: [(&str, usize); 31] = [
        ("tl_f64_abs", runtime::tl_f64_abs as *const () as usize),
        ("tl_f64_acos", runtime::tl_f64_acos as *const () as usize),
        ("tl_f64_acosh", runtime::tl_f64_acosh as *const () as usize),
        ("tl_f64_asin", runtime::tl_f64_asin as *const () as usize),
        ("tl_f64_asinh", runtime::tl_f64_asinh as *const () as usize),
        ("tl_f64_atan", runtime::tl_f64_atan as *const () as usize),
        ("tl_f64_atanh", runtime::tl_f64_atanh as *const () as usize),
        ("tl_f64_cbrt", runtime::tl_f64_cbrt as *const () as usize),
        ("tl_f64_ceil", runtime::tl_f64_ceil as *const () as usize),
        ("tl_f64_cos", runtime::tl_f64_cos as *const () as usize),
        ("tl_f64_cosh", runtime::tl_f64_cosh as *const () as usize),
        ("tl_f64_exp", runtime::tl_f64_exp as *const () as usize),
        ("tl_f64_exp2", runtime::tl_f64_exp2 as *const () as usize),
        (
            "tl_f64_exp_m1",
            runtime::tl_f64_exp_m1 as *const () as usize,
        ),
        ("tl_f64_floor", runtime::tl_f64_floor as *const () as usize),
        ("tl_f64_fract", runtime::tl_f64_fract as *const () as usize),
        ("tl_f64_ln", runtime::tl_f64_ln as *const () as usize),
        ("tl_f64_ln_1p", runtime::tl_f64_ln_1p as *const () as usize),
        ("tl_f64_log10", runtime::tl_f64_log10 as *const () as usize),
        ("tl_f64_log2", runtime::tl_f64_log2 as *const () as usize),
        ("tl_f64_recip", runtime::tl_f64_recip as *const () as usize),
        ("tl_f64_round", runtime::tl_f64_round as *const () as usize),
        (
            "tl_f64_signum",
            runtime::tl_f64_signum as *const () as usize,
        ),
        ("tl_f64_sin", runtime::tl_f64_sin as *const () as usize),
        ("tl_f64_sinh", runtime::tl_f64_sinh as *const () as usize),
        ("tl_f64_sqrt", runtime::tl_f64_sqrt as *const () as usize),
        ("tl_f64_tan", runtime::tl_f64_tan as *const () as usize),
        ("tl_f64_tanh", runtime::tl_f64_tanh as *const () as usize),
        (
            "tl_f64_to_degrees",
            runtime::tl_f64_to_degrees as *const () as usize,
        ),
        (
            "tl_f64_to_radians",
            runtime::tl_f64_to_radians as *const () as usize,
        ),
        ("tl_f64_trunc", runtime::tl_f64_trunc as *const () as usize),
    ];
    for (name, addr) in f64_unary_mappings {
        if let Some(f) = module.get_function(name) {
            execution_engine.add_global_mapping(&f, addr);
        }
    }
    let f64_binary_mappings: [(&str, usize); 5] = [
        ("tl_f64_atan2", runtime::tl_f64_atan2 as *const () as usize),
        (
            "tl_f64_copysign",
            runtime::tl_f64_copysign as *const () as usize,
        ),
        ("tl_f64_hypot", runtime::tl_f64_hypot as *const () as usize),
        ("tl_f64_log", runtime::tl_f64_log as *const () as usize),
        ("tl_f64_powf", runtime::tl_f64_powf as *const () as usize),
    ];
    for (name, addr) in f64_binary_mappings {
        if let Some(f) = module.get_function(name) {
            execution_engine.add_global_mapping(&f, addr);
        }
    }
    if let Some(f) = module.get_function("tl_f64_powi") {
        execution_engine.add_global_mapping(&f, runtime::tl_f64_powi as *const () as usize);
    }
    let i64_mappings: [(&str, usize); 5] = [
        ("tl_i64_abs", runtime::tl_i64_abs as *const () as usize),
        (
            "tl_i64_signum",
            runtime::tl_i64_signum as *const () as usize,
        ),
        ("tl_i64_pow", runtime::tl_i64_pow as *const () as usize),
        (
            "tl_i64_div_euclid",
            runtime::tl_i64_div_euclid as *const () as usize,
        ),
        (
            "tl_i64_rem_euclid",
            runtime::tl_i64_rem_euclid as *const () as usize,
        ),
    ];
    for (name, addr) in i64_mappings {
        if let Some(f) = module.get_function(name) {
            execution_engine.add_global_mapping(&f, addr);
        }
    }
    if let Some(f) = module.get_function("tl_i64_is_positive") {
        execution_engine.add_global_mapping(&f, runtime::tl_i64_is_positive as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_i64_is_negative") {
        execution_engine.add_global_mapping(&f, runtime::tl_i64_is_negative as *const () as usize);
    }
    let i32_mappings: [(&str, usize); 5] = [
        ("tl_i32_abs", runtime::tl_i32_abs as *const () as usize),
        (
            "tl_i32_signum",
            runtime::tl_i32_signum as *const () as usize,
        ),
        ("tl_i32_pow", runtime::tl_i32_pow as *const () as usize),
        (
            "tl_i32_div_euclid",
            runtime::tl_i32_div_euclid as *const () as usize,
        ),
        (
            "tl_i32_rem_euclid",
            runtime::tl_i32_rem_euclid as *const () as usize,
        ),
    ];
    for (name, addr) in i32_mappings {
        if let Some(f) = module.get_function(name) {
            execution_engine.add_global_mapping(&f, addr);
        }
    }
    if let Some(f) = module.get_function("tl_i32_is_positive") {
        execution_engine.add_global_mapping(&f, runtime::tl_i32_is_positive as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_i32_is_negative") {
        execution_engine.add_global_mapping(&f, runtime::tl_i32_is_negative as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_print_i64") {
        execution_engine.add_global_mapping(&f, runtime::tl_print_i64 as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_print_i32") {
        execution_engine.add_global_mapping(&f, runtime::tl_print_i32 as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_display_i64") {
        execution_engine.add_global_mapping(&f, runtime::tl_display_i64 as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_display_i32") {
        execution_engine.add_global_mapping(&f, runtime::tl_display_i32 as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_print_char") {
        execution_engine.add_global_mapping(&f, runtime::tl_print_char as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_display_char") {
        execution_engine.add_global_mapping(&f, runtime::tl_display_char as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_print_ptr") {
        execution_engine.add_global_mapping(&f, runtime::tl_print_ptr as *const () as usize);
    }
    // ========== テンソル作成/メモリ/情報: CPU/GPU 切替 ==========
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_new") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_new as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_new_i64") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_new_i64 as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_from_i64_array") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_from_i64_array as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi 統一マッピング
    if let Some(f) = module.get_function("tl_tensor_matmul") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_matmul as *const () as usize);
    }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_contiguous") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_contiguous as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_print") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_print as *const () as usize); }
    // display も print と同じ関数にマッピング
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_display") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_display as *const () as usize); }
    if !is_cpu {
        if let Some(f) = module.get_function("tl_tensor_print_1") {
            execution_engine.add_global_mapping(&f, runtime::tl_tensor_print_1 as *const () as usize);
        }
        if let Some(f) = module.get_function("tl_tensor_print_2") {
            execution_engine.add_global_mapping(&f, runtime::tl_tensor_print_2 as *const () as usize);
        }
        if let Some(f) = module.get_function("tl_tensor_print_3") {
            execution_engine.add_global_mapping(&f, runtime::tl_tensor_print_3 as *const () as usize);
        }
        // [IDevice] device_ffi 統一マッピング
        if let Some(f) = module.get_function("tl_tensor_device_id") {
            execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_device_id as *const () as usize);
        }
        if let Some(f) = module.get_function("tl_tensor_prepare_return") {
            execution_engine.add_global_mapping(
                &f,
                runtime::tl_tensor_prepare_return as *const () as usize,
            );
        }
    }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_acquire") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_acquire as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_release_safe") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_release_safe as *const () as usize); }
    if let Some(f) = module.get_function("tl_qtensor_retain") { execution_engine.add_global_mapping(&f, runtime::system::tl_qtensor_retain as *const () as usize); }
    if let Some(f) = module.get_function("tl_qtensor_release_safe") { execution_engine.add_global_mapping(&f, runtime::system::tl_qtensor_release_safe as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_add_scalar") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_add_scalar as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_sub_scalar") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_sub_scalar as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_mul_scalar") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_mul_scalar as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_div_scalar") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_div_scalar as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_len") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_len as *const () as usize); }

    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_dim") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_dim as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_get_f32_md") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_get_f32_md as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_get_i64_md") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_get_i64_md as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi 統一マッピング
    if let Some(f) = module.get_function("tl_tensor_neg") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_neg as *const () as usize);
    }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_transpose") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_transpose as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_reshape_new") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_reshape_new as *const () as usize); }

    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_get") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_get as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_slice") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_slice as *const () as usize); }
    if let Some(f) = module.get_function("tl_register_tensor") {
        execution_engine.add_global_mapping(&f, runtime::registry::tl_register_tensor as *const () as usize);
    }
    // Additional mappings from previous list...
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_randn_debug") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_randn_debug as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_zeros") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_zeros as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_backward") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_backward as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_grad") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_grad as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_detach") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_detach as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_promote") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_promote as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_register") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_register as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_enable_grad") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_enable_grad as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_softmax") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_softmax as *const () as usize); }
    // [IDevice] device_ffi 統一マッピング
    if let Some(f) = module.get_function("tl_tensor_cross_entropy") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_cross_entropy as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_conv2d") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_conv2d as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_clamp") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_clamp as *const () as usize);
    }
    // ========== テンソル演算: CPU/GPU 切替 (map_tensor_fn! マクロ使用) ==========
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_ones") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_ones as *const () as usize); }
    // [IDevice] tensor_full → device_ffi
    if let Some(f) = module.get_function("tl_tensor_full") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_full as *const () as usize); }
    // [IDevice] tensor_eye → device_ffi
    if let Some(f) = module.get_function("tl_tensor_eye") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_eye as *const () as usize); }
    // [IDevice] tensor_arange → device_ffi
    if let Some(f) = module.get_function("tl_tensor_arange") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_arange as *const () as usize); }
    // [IDevice] zeros_like / ones_like → device_ffi
    if let Some(f) = module.get_function("tl_tensor_zeros_like") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_zeros_like as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_ones_like") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_ones_like as *const () as usize); }
    // [IDevice] from_vec_f32 → device_ffi
    if let Some(f) = module.get_function("tl_tensor_from_vec_f32") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_from_vec_f32 as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_to_vec_f32") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_to_vec_f32 as *const () as usize); }
    // [IDevice] linspace / rand / rand_like / randn_like → device_ffi
    if let Some(f) = module.get_function("tl_tensor_linspace") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_linspace as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_rand") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_rand as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_rand_like") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_rand_like as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_randn_like") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_randn_like as *const () as usize); }
    // [IDevice] where_cond → device_ffi
    if let Some(f) = module.get_function("tl_tensor_where_cond") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_where_cond as *const () as usize); }
    // [IDevice] masked_fill / var / std → device_ffi
    if let Some(f) = module.get_function("tl_tensor_masked_fill_scalar") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_masked_fill_scalar as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_var_dim") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_var_dim as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_std_dim") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_std_dim as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_var") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_var as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_std") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_std as *const () as usize); }
    // [IDevice] prod / fill_ → device_ffi
    if let Some(f) = module.get_function("tl_tensor_prod_dim") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_prod_dim as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_prod") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_prod as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_fill_") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_fill_ as *const () as usize); }
    // [IDevice] cumsum / norm / topk / logical_* → device_ffi
    if let Some(f) = module.get_function("tl_tensor_cumsum") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_cumsum as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_norm") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_norm as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_topk") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_topk as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_logical_and") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_logical_and as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_logical_or") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_logical_or as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_logical_not") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_logical_not as *const () as usize); }
    // [IDevice] expand / stack → device_ffi
    if let Some(f) = module.get_function("tl_tensor_expand") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_expand as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_expand_new") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_expand_new as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_stack") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_stack as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_chunk") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_chunk as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_split") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_split as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_leaky_relu") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_leaky_relu as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_elu") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_elu as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_mish") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_mish as *const () as usize); }
    // [IDevice] loss functions → device_ffi
    if let Some(f) = module.get_function("tl_tensor_mse_loss") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_mse_loss as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_l1_loss") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_l1_loss as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_bce_loss") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_bce_loss as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_nll_loss") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_nll_loss as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_linear") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_linear as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_hardswish") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_hardswish as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_hardsigmoid") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_hardsigmoid as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_group_norm") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_group_norm as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_adaptive_avg_pool2d") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_adaptive_avg_pool2d as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_pad") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_pad as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_instance_norm") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_instance_norm as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_conv1d") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_conv1d as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_kl_div_loss") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_kl_div_loss as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_conv_transpose2d") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_conv_transpose2d as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_interpolate") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_interpolate as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_sdpa") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_sdpa as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_top_k_sample") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_top_k_sample as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_top_p_sample") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_top_p_sample as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_temperature_scale") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_temperature_scale as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_repetition_penalty") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_repetition_penalty as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_dot") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_dot as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_sub_assign") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_sub_assign as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_sum") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_sum as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi 統一マッピング
    if let Some(f) = module.get_function("tl_tensor_add") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_add as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_sub") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_sub as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_mul") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_mul as *const () as usize);
    }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_div") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_div as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_rem") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_rem as *const () as usize); }
    // Comparisons
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_eq") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_eq as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_neq") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_neq as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_gt") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_gt as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_lt") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_lt as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_ge") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_ge as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_le") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_le as *const () as usize); }

    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_pow") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_pow as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_pow_scalar") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_pow_scalar as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_add_assign") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_add_assign as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_set_f32_md") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_set_f32_md as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_mul_assign") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_mul_assign as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_div_assign") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_div_assign as *const () as usize); }
    // Scalar assign variants
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_mul_assign_scalar_f32") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_mul_assign_scalar_f32 as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_div_assign_scalar_f32") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_div_assign_scalar_f32 as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_mod_assign_scalar_f32") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_mod_assign_scalar_f32 as *const () as usize); }

    // ========== Phase 1: 既存実装のマッピング追加 ==========
    // Note: abs, tanh, tan は add_fn が L1988-2006 にあるのでそちらで map_tensor_fn!
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_reshape_dims") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_reshape_dims as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_cat") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_cat as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_cat_i64") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_cat_i64 as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_narrow") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_narrow as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_replace_data") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_replace_data as *const () as usize); }

    // ========== Phase 2: テスト影響の大きい新規実装のマッピング ==========
    // Note: sigmoid, max_dim, min_dim, mean_dim は add_fn が L1994-2030 にあるのでそちらで map_tensor_fn!
    // Note: to_f32, to_i64 は add_fn が L2322-2323 にあるのでそちらで map_tensor_fn!
    // Note: sample は add_fn が L2871 にあるのでそちらで map_tensor_fn!
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_scale") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_scale as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_silu") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_silu as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_cross_entropy") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_cross_entropy as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_device_id") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_device_id as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_to_device") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_to_device as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_repeat_interleave") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_repeat_interleave as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_new_causal_mask") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_new_causal_mask as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_cat2") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_cat2 as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_cat_4d") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_cat_4d as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_rms_norm") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_rms_norm as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_print_1") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_print_1 as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_print_2") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_print_2 as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_print_3") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_print_3 as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_save") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_save as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_load") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_load as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_rope_new_cos") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_rope_new_cos as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_rope_new_sin") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_rope_new_sin as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_apply_rope") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_apply_rope as *const () as usize); }

    // 新規実装関数: CPU/GPU 両対応
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_clone") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_clone as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_free") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_free as *const () as usize); } // free も共通化
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_release") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_release as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_numel") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_numel as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_data") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_data as *const () as usize); }

    // ========== CPU 専用マッピング (runtime に対応関数がないもの) ==========
    // GPU 時は既存の if let Some ブロック (上記) で runtime 関数にマッピング済み
    if is_cpu {
        if let Some(f) = module.get_function("tl_tensor_transpose_2d") {
            execution_engine.add_global_mapping(&f, cpu_ffi::tl_cpu_tensor_transpose_2d as *const () as usize);
        }
        if let Some(f) = module.get_function("tl_tensor_prepare_return") {
            execution_engine.add_global_mapping(&f, cpu_ffi::tl_cpu_tensor_prepare_return as *const () as usize);
        }
        if let Some(f) = module.get_function("tl_tensor_reshape_2d") {
            execution_engine.add_global_mapping(&f, cpu_ffi::tl_cpu_tensor_reshape_2d as *const () as usize);
        }
        if let Some(f) = module.get_function("tl_tensor_reshape_3d_to_2d") {
            execution_engine.add_global_mapping(&f, cpu_ffi::tl_cpu_tensor_reshape_3d_to_2d as *const () as usize);
        }
        if let Some(f) = module.get_function("tl_tensor_matmul_4d") {
            execution_engine.add_global_mapping(&f, cpu_ffi::tl_cpu_tensor_matmul_4d as *const () as usize);
        }
        if let Some(f) = module.get_function("tl_tensor_add_4d") {
            execution_engine.add_global_mapping(&f, cpu_ffi::tl_cpu_tensor_add_4d as *const () as usize);
        }
        if let Some(f) = module.get_function("tl_tensor_silu_4d") {
            execution_engine.add_global_mapping(&f, cpu_ffi::tl_cpu_tensor_silu_4d as *const () as usize);
        }
    }

    if let Some(f) = module.get_function("tl_kb_add_entity") {
        execution_engine.add_global_mapping(&f, runtime::knowledge_base::tl_kb_add_entity as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_kb_add_fact") {
        execution_engine.add_global_mapping(&f, runtime::knowledge_base::tl_kb_add_fact as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_kb_infer") {
        execution_engine.add_global_mapping(&f, runtime::knowledge_base::tl_kb_infer as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_kb_rule_start") {
        execution_engine.add_global_mapping(&f, runtime::knowledge_base::tl_kb_rule_start as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_kb_rule_add_head_arg_var") {
        execution_engine.add_global_mapping(
            &f,
            runtime::knowledge_base::tl_kb_rule_add_head_arg_var as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_kb_add_fact_serialized") {
        execution_engine.add_global_mapping(
            &f,
            runtime::knowledge_base::tl_kb_add_fact_serialized as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_kb_fact_args_clear") {
        execution_engine.add_global_mapping(
            &f,
            runtime::knowledge_base::tl_kb_fact_args_clear as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_kb_fact_args_add_int") {
        execution_engine.add_global_mapping(
            &f,
            runtime::knowledge_base::tl_kb_fact_args_add_int as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_kb_fact_args_add_float") {
        execution_engine.add_global_mapping(
            &f,
            runtime::knowledge_base::tl_kb_fact_args_add_float as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_kb_fact_args_add_bool") {
        execution_engine.add_global_mapping(
            &f,
            runtime::knowledge_base::tl_kb_fact_args_add_bool as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_kb_fact_args_add_entity") {
        execution_engine.add_global_mapping(
            &f,
            runtime::knowledge_base::tl_kb_fact_args_add_entity as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_kb_fact_args_add_string") {
        execution_engine.add_global_mapping(
            &f,
            runtime::knowledge_base::tl_kb_fact_args_add_string as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_kb_rule_add_head_arg_const_int") {
        execution_engine.add_global_mapping(
            &f,
            runtime::knowledge_base::tl_kb_rule_add_head_arg_const_int as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_kb_rule_add_head_arg_const_float") {
        execution_engine.add_global_mapping(
            &f,
            runtime::knowledge_base::tl_kb_rule_add_head_arg_const_float as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_kb_rule_add_head_arg_const_entity") {
        execution_engine.add_global_mapping(
            &f,
            runtime::knowledge_base::tl_kb_rule_add_head_arg_const_entity as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_kb_rule_add_body_atom") {
        execution_engine.add_global_mapping(
            &f,
            runtime::knowledge_base::tl_kb_rule_add_body_atom as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_kb_rule_add_body_atom_neg") {
        execution_engine.add_global_mapping(
            &f,
            runtime::knowledge_base::tl_kb_rule_add_body_atom_neg as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_kb_rule_add_body_arg_var") {
        execution_engine.add_global_mapping(
            &f,
            runtime::knowledge_base::tl_kb_rule_add_body_arg_var as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_kb_rule_add_body_arg_const_int") {
        execution_engine.add_global_mapping(
            &f,
            runtime::knowledge_base::tl_kb_rule_add_body_arg_const_int as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_kb_rule_add_body_arg_const_float") {
        execution_engine.add_global_mapping(
            &f,
            runtime::knowledge_base::tl_kb_rule_add_body_arg_const_float as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_kb_rule_add_body_arg_const_entity") {
        execution_engine.add_global_mapping(
            &f,
            runtime::knowledge_base::tl_kb_rule_add_body_arg_const_entity as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_kb_rule_finish") {
        execution_engine
            .add_global_mapping(&f, runtime::knowledge_base::tl_kb_rule_finish as *const () as usize);
    }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_add_assign_scalar_f32") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_add_assign_scalar_f32 as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_sub_assign_scalar_f32") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_sub_assign_scalar_f32 as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_mod_assign") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_mod_assign as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_mod_assign_scalar_f32") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_mod_assign_scalar_f32 as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_exp") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_exp as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_log") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_log as *const () as usize); }
    // tl_tensor_sqrt はCPU版実装済み
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_sqrt") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_sqrt as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_sin") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_sin as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_cos") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_cos as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_relu") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_relu as *const () as usize); }
    // tl_tensor_gelu, tl_tensor_tril, tl_tensor_sum_dim, tl_tensor_embedding: CPU版実装済み
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_gelu") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_gelu as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_tril") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_tril as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_sum_dim") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_sum_dim as *const () as usize); }
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_embedding") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_embedding as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_save") {
        execution_engine.add_global_mapping(&f, runtime::tl_tensor_save as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_load") {
        execution_engine.add_global_mapping(&f, runtime::tl_tensor_load as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_save_all_params") {
        execution_engine.add_global_mapping(&f, runtime::tl_save_all_params as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_add_parameter") {
        execution_engine.add_global_mapping(&f, runtime::tl_add_parameter as *const () as usize);
    }
    // TensorMap: runtime 側で CPU/GPU 抽象化済みなので共通マッピング
    if let Some(f) = module.get_function("tl_tensor_map_new") {
        execution_engine.add_global_mapping(&f, runtime::tl_tensor_map_new as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_map_insert") {
        execution_engine.add_global_mapping(&f, runtime::tl_tensor_map_insert as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_map_get") {
        execution_engine.add_global_mapping(&f, runtime::tl_tensor_map_get as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_map_free") {
        execution_engine.add_global_mapping(&f, runtime::tl_tensor_map_free as *const () as usize);
    }
    // tl_tensor_set_f32_md はL1478で既にマッピング済み
    if let Some(f) = module.get_function("tl_mem_unregister") {
        execution_engine
            .add_global_mapping(&f, runtime::memory_manager::tl_mem_unregister as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_load_all_params") {
        execution_engine.add_global_mapping(&f, runtime::tl_load_all_params as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_register_parameter") {
        execution_engine.add_global_mapping(&f, runtime::tl_register_parameter as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_string_new") {
        execution_engine.add_global_mapping(&f, runtime::tl_string_new as *const () as usize);
    }

    // VarBuilder-based parameter management
    if let Some(f) = module.get_function("tl_varbuilder_get") {
        execution_engine.add_global_mapping(&f, runtime::tl_varbuilder_get as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_varbuilder_get_from_tensor") {
        execution_engine.add_global_mapping(&f, runtime::tl_varbuilder_get_from_tensor as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_varbuilder_grad") {
        execution_engine.add_global_mapping(&f, runtime::tl_varbuilder_grad as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_update_all_params") {
        execution_engine.add_global_mapping(&f, runtime::tl_update_all_params as *const () as usize);
    }

    if let Some(f) = module.get_function("tl_get_memory_mb") {
        execution_engine.add_global_mapping(&f, runtime::tl_get_memory_mb as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_mem_purge") {
        execution_engine.add_global_mapping(&f, runtime::tl_mem_purge as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_get_memory_bytes") {
        execution_engine.add_global_mapping(&f, runtime::tl_get_memory_bytes as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_get_metal_pool_bytes") {
        if is_cpu {
            execution_engine.add_global_mapping(&f, cpu_ffi::tl_cpu_get_pool_bytes as *const () as usize);
        } else {
            execution_engine.add_global_mapping(&f, runtime::tl_get_metal_pool_bytes as *const () as usize);
        }
    }
    if let Some(f) = module.get_function("tl_get_metal_pool_mb") {
        if is_cpu {
            execution_engine.add_global_mapping(&f, cpu_ffi::tl_cpu_get_pool_mb as *const () as usize);
        } else {
            execution_engine.add_global_mapping(&f, runtime::tl_get_metal_pool_mb as *const () as usize);
        }
    }
    if let Some(f) = module.get_function("tl_get_metal_pool_count") {
        if is_cpu {
            execution_engine.add_global_mapping(&f, cpu_ffi::tl_cpu_get_pool_count as *const () as usize);
        } else {
            execution_engine.add_global_mapping(&f, runtime::tl_get_metal_pool_count as *const () as usize);
        }
    }
    if let Some(f) = module.get_function("tl_metal_sync") {
        execution_engine.add_global_mapping(&f, runtime::tl_metal_sync as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_system_mem_report") {
        execution_engine.add_global_mapping(&f, runtime::tl_system_mem_report as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_trace_mem") {
        execution_engine.add_global_mapping(&f, runtime::tl_trace_mem as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_get_pool_count") {
        execution_engine.add_global_mapping(&f, runtime::tl_get_pool_count as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_get_refcount_count") {
        execution_engine.add_global_mapping(&f, runtime::tl_get_refcount_count as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_get_scope_depth") {
        execution_engine.add_global_mapping(&f, runtime::tl_get_scope_depth as *const () as usize);
    }

    // Args (command line arguments)
    if let Some(f) = module.get_function("tl_args_count") {
        execution_engine.add_global_mapping(&f, runtime::args::tl_args_count as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_args_get") {
        execution_engine.add_global_mapping(&f, runtime::args::tl_args_get as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_string_to_i64") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_to_i64 as *const () as usize);
    }

    // String utilities
    if let Some(f) = module.get_function("tl_string_char_at") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_char_at as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_string_len") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_len as *const () as usize);
    }

    // Memory manager mappings
    if let Some(f) = module.get_function("tl_mem_enter_scope") {
        execution_engine
            .add_global_mapping(&f, runtime::memory_manager::tl_mem_enter_scope as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_mem_exit_scope") {
        execution_engine
            .add_global_mapping(&f, runtime::memory_manager::tl_mem_exit_scope as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_mem_register_struct") {
        execution_engine
            .add_global_mapping(&f, runtime::memory_manager::tl_mem_register_struct as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_mem_register_struct_named") {
        execution_engine.add_global_mapping(
            &f,
            runtime::memory_manager::tl_mem_register_struct_named as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_mem_register_tensor") {
        execution_engine
            .add_global_mapping(&f, runtime::memory_manager::tl_mem_register_tensor as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_mem_unregister") {
        execution_engine
            .add_global_mapping(&f, runtime::memory_manager::tl_mem_unregister as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_ptr_dec_ref") {
        execution_engine.add_global_mapping(
            &f,
            runtime::memory_manager::tl_ptr_dec_ref as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_ptr_inc_ref") {
        execution_engine.add_global_mapping(
            &f,
            runtime::memory_manager::tl_ptr_inc_ref as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_ptr_acquire") {
        execution_engine.add_global_mapping(
            &f,
            runtime::memory_manager::tl_ptr_acquire as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_ptr_release") {
        execution_engine.add_global_mapping(
            &f,
            runtime::memory_manager::tl_ptr_release as *const () as usize,
        );
    }
    if let Some(f) = module.get_function("tl_mem_free") {
        execution_engine.add_global_mapping(&f, runtime::tl_mem_free as *const () as usize);
    }

    // Arena Allocator mappings
    if let Some(f) = module.get_function("tl_arena_init") {
        execution_engine.add_global_mapping(&f, runtime::arena::tl_arena_init as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_arena_alloc") {
        execution_engine.add_global_mapping(&f, runtime::arena::tl_arena_alloc as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_arena_free") {
        execution_engine.add_global_mapping(&f, runtime::arena::tl_arena_free as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_arena_is_active") {
        execution_engine.add_global_mapping(&f, runtime::arena::tl_arena_is_active as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_arena_reset") {
        execution_engine.add_global_mapping(&f, runtime::arena::tl_arena_reset as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_arena_get_offset") {
        execution_engine.add_global_mapping(&f, runtime::arena::tl_arena_get_offset as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_arena_get_capacity") {
        execution_engine.add_global_mapping(&f, runtime::arena::tl_arena_get_capacity as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_arena_malloc") {
        execution_engine.add_global_mapping(&f, runtime::arena::tl_arena_malloc as *const () as usize);
    }

    if let Some(f) = module.get_function("tl_update_all_params") {
        execution_engine.add_global_mapping(&f, runtime::tl_update_all_params as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_varbuilder_grad") {
        execution_engine.add_global_mapping(&f, runtime::tl_varbuilder_grad as *const () as usize);
    }
    // [IDevice] device_ffi 統一マッピング
    if let Some(f) = module.get_function("tl_tensor_reshape_dims") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_reshape_dims as *const () as usize);
    }
    // Map Support (runtime 側で CPU/GPU 抽象化済み)
    if let Some(f) = module.get_function("tl_tensor_map_save") {
        execution_engine.add_global_mapping(&f, runtime::tl_tensor_map_save as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_map_load") {
        execution_engine.add_global_mapping(&f, runtime::tl_tensor_map_load as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_alloc_tmp") {
        execution_engine.add_global_mapping(&f, runtime::tl_alloc_tmp as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_free_tmp") {
        execution_engine.add_global_mapping(&f, runtime::tl_free_tmp as *const () as usize);
    }

    // [IDevice] device_ffi 統一マッピング
    if let Some(f) = module.get_function("tl_tensor_argmax") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_argmax as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_to_i64") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_to_i64 as *const () as usize);
    }
    // tl_tensor_item / tl_tensor_item_i64 のマッピングは
    // 宣言セクション (L2225/L2231) の直後で map_tensor_fn! により実施

    // CLI Args

    // Added missing ones (Define type locally as declared later)
    let _tensor_type = Type::Tensor(Box::new(Type::F32), 1);
    let _tensor_type_local = Type::Tensor(Box::new(Type::I64), 1);
    // Removed duplicate tl_tensor_to_i64

    // Added for Tensor Refactor
    add_fn("tl_tensor_tan", unary_type);
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_tan") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_tan as *const () as usize); }
    add_fn("tl_tensor_abs", unary_type);
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_abs") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_abs as *const () as usize); }
    add_fn("tl_tensor_sigmoid", unary_type);
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_sigmoid") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_sigmoid as *const () as usize); }
    add_fn("tl_tensor_tanh", unary_type);
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_tanh") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_tanh as *const () as usize); }
    add_fn("tl_tensor_max", unary_type);
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_max") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_max as *const () as usize); }
    add_fn("tl_tensor_max_dim", sum_dim_type);
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_max_dim") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_max_dim as *const () as usize); }
    add_fn("tl_tensor_min", unary_type);
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_min") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_min as *const () as usize); }
    add_fn("tl_tensor_min_dim", sum_dim_type);
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_min_dim") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_min_dim as *const () as usize); }
    add_fn("tl_tensor_mean", unary_type);
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_mean") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_mean as *const () as usize); }
    add_fn("tl_tensor_mean_dim", sum_dim_type);
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_mean_dim") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_mean_dim as *const () as usize); }
    add_fn("tl_tensor_argmin", sum_dim_type);
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_argmin") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_argmin as *const () as usize); }
    add_fn("tl_tensor_argmax", sum_dim_type);
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_argmax") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_argmax as *const () as usize); }


    // --- LLM Mappings ---
    if let Some(f) = module.get_function("tl_tokenizer_new") {
        execution_engine.add_global_mapping(&f, runtime::llm::tl_tokenizer_new as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tokenizer_encode") {
        execution_engine.add_global_mapping(&f, runtime::llm::tl_tokenizer_encode as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tokenizer_encode_chat") {
        execution_engine.add_global_mapping(&f, runtime::llm::tl_tokenizer_encode_chat as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tokenizer_encode_chat_zephyr") {
        execution_engine.add_global_mapping(&f, runtime::llm::tl_tokenizer_encode_chat_zephyr as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tokenizer_decode") {
        execution_engine.add_global_mapping(&f, runtime::llm::tl_tokenizer_decode as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_gguf_load") {
        execution_engine.add_global_mapping(&f, runtime::tl_gguf_load as *const () as usize);
    }
    if !is_cpu {
        if let Some(f) = module.get_function("tl_tensor_map_get") {
            execution_engine.add_global_mapping(&f, runtime::tl_tensor_map_get as *const () as usize);
        }
    }
    // [IDevice] device_ffi 統一マッピング — LLM 関連
    if let Some(f) = module.get_function("tl_tensor_cat") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_cat as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_silu") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_silu as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_apply_rope") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_apply_rope as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_rms_norm") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_rms_norm as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_cat2") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_cat2 as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_cat_4d") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_cat_4d as *const () as usize);
    }
    // [IDevice] device_ffi 統一マッピング — Alias
    if let Some(f) = module.get_function("tl_tensor_transpose_2d") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_transpose_2d as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_matmul_4d") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_matmul_4d as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_add_4d") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_add_4d as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_silu_4d") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_silu_4d as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_scale") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_scale as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_rope_new_cos") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_rope_new_cos as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_rope_new_sin") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_rope_new_sin as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_new_causal_mask") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_new_causal_mask as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_cat_i64") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_cat_i64 as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_narrow") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_narrow as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_repeat_interleave") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_repeat_interleave as *const () as usize);
    }
    // [IDevice] device_ffi 統一マッピング — 形状操作
    if let Some(f) = module.get_function("tl_tensor_get_shape") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_get_shape as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_reshape_2d") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_reshape_2d as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_reshape_3d_to_2d") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_reshape_3d_to_2d as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_map_get_1d") {
        execution_engine.add_global_mapping(&f, runtime::tl_tensor_map_get as *const () as usize);
    }


    // [IDevice] device_ffi 統一マッピング
    if let Some(f) = module.get_function("tl_tensor_from_vec_u8") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_from_vec_u8 as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_from_vec_u8_f32_shape") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_from_vec_u8_f32_shape as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_from_u8_labels") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_from_u8_labels as *const () as usize);
    }


    // Binary file I/O mappings
    if let Some(f) = module.get_function("tl_file_read_binary_all") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_file_read_binary_all as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_file_write_binary") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_file_write_binary as *const () as usize);
    }

    // Image loading mappings
    if let Some(f) = module.get_function("tl_image_load_grayscale") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_image_load_grayscale as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_image_width") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_image_width as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_image_height") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_image_height as *const () as usize);
    }
    // [IDevice] device_ffi 統一マッピング
    if let Some(f) = module.get_function("tl_tensor_to_f32") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_to_f32 as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_tensor_to_i64") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_to_i64 as *const () as usize);
    }

    // End of function

    let _tensor_type = Type::Tensor(Box::new(Type::F32), 1); // Common return type for many tensor ops

    let f32_unary_methods = [
        "abs",
        "acos",
        "acosh",
        "asin",
        "asinh",
        "atan",
        "atanh",
        "cbrt",
        "ceil",
        "cos",
        "cosh",
        "exp",
        "exp2",
        "exp_m1",
        "floor",
        "fract",
        "ln",
        "ln_1p",
        "log10",
        "log2",
        "recip",
        "round",
        "signum",
        "sin",
        "sinh",
        "sqrt",
        "tan",
        "tanh",
        "to_degrees",
        "to_radians",
        "trunc",
    ];
    for _name in f32_unary_methods {
    }
    let f32_binary_methods = ["atan2", "copysign", "hypot", "log", "powf"];
    for _name in f32_binary_methods {
    }
    let f64_unary_methods = [
        "abs",
        "acos",
        "acosh",
        "asin",
        "asinh",
        "atan",
        "atanh",
        "cbrt",
        "ceil",
        "cos",
        "cosh",
        "exp",
        "exp2",
        "exp_m1",
        "floor",
        "fract",
        "ln",
        "ln_1p",
        "log10",
        "log2",
        "recip",
        "round",
        "signum",
        "sin",
        "sinh",
        "sqrt",
        "tan",
        "tanh",
        "to_degrees",
        "to_radians",
        "trunc",
    ];
    for _name in f64_unary_methods {
    }
    let f64_binary_methods = ["atan2", "copysign", "hypot", "log", "powf"];
    for _name in f64_binary_methods {
    }
    let i64_unary_methods = ["abs", "signum"];
    for _name in i64_unary_methods {
    }
    let i64_binary_methods = ["div_euclid", "rem_euclid", "pow"];
    for _name in i64_binary_methods {
    }
    let i32_unary_methods = ["abs", "signum"];
    for _name in i32_unary_methods {
    }
    let i32_binary_methods = ["div_euclid", "rem_euclid", "pow"];
    for _name in i32_binary_methods {
    }
    
    // ... complete as needed based on original CodeGen
                                                                    // tl_tensor_reshape_dims(tensor: *mut OpaqueTensor, dims: *const i64, num_dims: i64) -> *mut OpaqueTensor
    let tensor_reshape_dims_type = void_ptr.fn_type(
        &[
            void_ptr.into(),                                           // tensor
            context.ptr_type(inkwell::AddressSpace::default()).into(), // dims ptr
            context.i64_type().into(),                                 // num_dims
        ],
        false,
    );
    module.add_function("tl_tensor_reshape_dims", tensor_reshape_dims_type, None);

    // tl_tensor_reshape(tensor: *mut OpaqueTensor, new_shape: *mut OpaqueTensor) -> *mut OpaqueTensor
    let tensor_reshape_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into()], false);
    module.add_function("tl_tensor_reshape", tensor_reshape_type, None);

    // tl_tensor_randn(rank: usize, shape: *const usize, req_grad: bool) -> *mut OpaqueTensor

    // VarBuilder-based parameter management (following Candle's official pattern)
    // tl_varbuilder_get(name: *const c_char, rank: i64, shape: *const usize) -> *mut OpaqueTensor
    let varbuilder_get_type =
        void_ptr.fn_type(&[i8_ptr.into(), i64_type.into(), usize_ptr.into()], false);
    module.add_function("tl_varbuilder_get", varbuilder_get_type, None);

    // tl_varbuilder_get_from_tensor(name: *const c_char, shape_tensor: *mut OpaqueTensor)
    let varbuilder_get_tensor_type = void_ptr.fn_type(&[i8_ptr.into(), void_ptr.into()], false);
    module.add_function(
        "tl_varbuilder_get_from_tensor",
        varbuilder_get_tensor_type,
        None,
    );

    // tl_update_all_params(learning_rate: f32) -> void
    let update_params_type = void_type.fn_type(&[context.f32_type().into()], false);
    module.add_function("tl_update_all_params", update_params_type, None);

    // tl_varbuilder_grad(name: *const c_char) -> *mut OpaqueTensor
    let varbuilder_grad_type = void_ptr.fn_type(&[i8_ptr.into()], false);
    module.add_function("tl_varbuilder_grad", varbuilder_grad_type, None);

    // tl_tensor_backward(t: *mut OpaqueTensor) -> void
    let backward_type = void_type.fn_type(&[void_ptr.into()], false);
    module.add_function("tl_tensor_backward", backward_type, None);

    // tl_tensor_grad(t: *mut OpaqueTensor) -> *mut OpaqueTensor
    let grad_type = void_ptr.fn_type(&[void_ptr.into()], false);
    module.add_function("tl_tensor_grad", grad_type, None);

    // tl_tensor_detach(t: *mut, req_grad: bool) -> *mut
    let detach_type = void_ptr.fn_type(&[void_ptr.into(), context.bool_type().into()], false);
    module.add_function("tl_tensor_detach", detach_type, None);

    // tl_tensor_softmax(t: *mut, dim: i64) -> *mut
    let softmax_type = void_ptr.fn_type(&[void_ptr.into(), i64_type.into()], false);
    module.add_function("tl_tensor_softmax", softmax_type, None);

    // tl_tensor_cross_entropy(logits: *mut, targets: *mut) -> *mut
    let ce_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into()], false);
    module.add_function("tl_tensor_cross_entropy", ce_type, None);

    // tl_tensor_save(path: *const i8, t: *mut OpaqueTensor) -> void
    let save_type = void_type.fn_type(&[i8_ptr.into(), void_ptr.into()], false);
    module.add_function("tl_tensor_save", save_type, None);

    // tl_tensor_load(path: *const i8) -> *mut OpaqueTensor
    let load_type = void_ptr.fn_type(&[i8_ptr.into()], false);
    module.add_function("tl_tensor_load", load_type, None);

    // Cast
    let cast_type = void_ptr.fn_type(&[void_ptr.into()], false);
    add_fn("tl_tensor_to_f32", cast_type);
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_to_f32") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_to_f32 as *const () as usize); }
    add_fn("tl_tensor_to_i64", cast_type);
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_to_i64") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_to_i64 as *const () as usize); }

    // tl_save_all_params(path: *const i8) -> void
    let save_all_type = void_type.fn_type(&[i8_ptr.into()], false);
    module.add_function("tl_save_all_params", save_all_type, None);

    // tl_add_parameter(name: *str, t: *mut Tensor) -> void
    let add_param_type = void_type.fn_type(&[void_ptr.into(), void_ptr.into()], false);
    module.add_function("tl_add_parameter", add_param_type, None);

    // tl_tensor_argmax(t: *mut, dim: i64, keep_dim: bool) -> *mut
    let argmax_type = void_ptr.fn_type(
        &[void_ptr.into(), i64_type.into(), context.bool_type().into()],
        false,
    );
    module.add_function("tl_tensor_argmax", argmax_type, None);

    // tl_tensor_item(t: *mut) -> f32
    let item_type = f32_type.fn_type(&[void_ptr.into()], false);
    module.add_function("tl_tensor_item", item_type, None);
    // CPU/GPU 切替マッピング(宣言直後に配置する必要がある)
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_item") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_item as *const () as usize); }

    // tl_tensor_item_i64(t: *mut) -> i64
    let item_i64_type = i64_type.fn_type(&[void_ptr.into()], false);
    module.add_function("tl_tensor_item_i64", item_i64_type, None);
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_item_i64") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_item_i64 as *const () as usize); }

    // tl_tensor_to_i64(t: *mut) -> *mut
    let to_i64_type = void_ptr.fn_type(&[void_ptr.into()], false);
    module.add_function("tl_tensor_to_i64", to_i64_type, None);

    // tl_tensor_shape(t: *mut) -> *mut Vec
    let shape_type = void_ptr.fn_type(&[void_ptr.into()], false);
    module.add_function("tl_tensor_shape", shape_type, None);
    if let Some(f) = module.get_function("tl_tensor_shape") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_shape_vec as *const () as usize); }

    // tl_load_all_params(path: *const i8) -> void
    let load_all_type = void_type.fn_type(&[i8_ptr.into()], false);
    module.add_function("tl_load_all_params", load_all_type, None);

    // tl_tensor_sub_assign(ref_t: *mut, val: *mut) -> void
    let sub_assign_type = void_type.fn_type(&[void_ptr.into(), void_ptr.into()], false);
    module.add_function("tl_tensor_sub_assign", sub_assign_type, None);

    // tl_add_parameter(name: *const i8, t: *mut OpaqueTensor) -> void
    let add_param_type = void_type.fn_type(&[i8_ptr.into(), void_ptr.into()], false);
    module.add_function("tl_add_parameter", add_param_type, None);

    // tl_register_parameter(t: *mut OpaqueTensor) -> *mut OpaqueTensor
    let reg_param_type = void_ptr.fn_type(&[void_ptr.into()], false);
    module.add_function("tl_register_parameter", reg_param_type, None);

    // tl_tensor_conv2d(input: *mut, weight: *mut, padding: i64, stride: i64) -> *mut
    let conv2d_type = void_ptr.fn_type(
        &[
            void_ptr.into(),
            void_ptr.into(),
            i64_type.into(),
            i64_type.into(),
        ],
        false,
    );
    module.add_function("tl_tensor_conv2d", conv2d_type, None);
    // Simple wrapper: 4-arg (input, weight, padding, stride) → 7-arg device_ffi
    if let Some(f) = module.get_function("tl_tensor_conv2d") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_conv2d_simple_wrapper as *const () as usize); }

    // tl_tensor_batch_norm(input, running_mean, running_var, weight, bias, training, momentum, eps) -> *mut
    let batch_norm_type = void_ptr.fn_type(
        &[
            void_ptr.into(),           // input
            void_ptr.into(),           // running_mean
            void_ptr.into(),           // running_var
            void_ptr.into(),           // weight
            void_ptr.into(),           // bias
            context.bool_type().into(), // training
            f64_type.into(),           // momentum
            f64_type.into(),           // eps
        ],
        false,
    );
    module.add_function("tl_tensor_batch_norm", batch_norm_type, None);
    if let Some(f) = module.get_function("tl_tensor_batch_norm") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_batch_norm as *const () as usize); }

    // tl_tensor_layer_norm(input, weight, bias, eps) -> *mut
    let layer_norm_type = void_ptr.fn_type(
        &[void_ptr.into(), void_ptr.into(), void_ptr.into(), f64_type.into()],
        false,
    );
    module.add_function("tl_tensor_layer_norm", layer_norm_type, None);
    if let Some(f) = module.get_function("tl_tensor_layer_norm") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_layer_norm as *const () as usize); }

    // tl_tensor_dropout(input, p, training) -> *mut
    let dropout_type = void_ptr.fn_type(
        &[void_ptr.into(), f64_type.into(), context.bool_type().into()],
        false,
    );
    module.add_function("tl_tensor_dropout", dropout_type, None);
    if let Some(f) = module.get_function("tl_tensor_dropout") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_dropout as *const () as usize); }

    // tl_tensor_dropout2d(input, p, training) -> *mut (same sig as dropout)
    module.add_function("tl_tensor_dropout2d", dropout_type, None);
    if let Some(f) = module.get_function("tl_tensor_dropout2d") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_dropout2d as *const () as usize); }

    // tl_tensor_max_pool2d(input, kernel_size, stride, padding) -> *mut
    let pool2d_type = void_ptr.fn_type(
        &[void_ptr.into(), i64_type.into(), i64_type.into(), i64_type.into()],
        false,
    );
    module.add_function("tl_tensor_max_pool2d", pool2d_type, None);
    if let Some(f) = module.get_function("tl_tensor_max_pool2d") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_max_pool2d as *const () as usize); }

    // tl_tensor_avg_pool2d(input, kernel_size, stride, padding) -> *mut
    module.add_function("tl_tensor_avg_pool2d", pool2d_type, None);
    if let Some(f) = module.get_function("tl_tensor_avg_pool2d") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_avg_pool2d as *const () as usize); }

    // tl_tensor_clamp(t: *mut, min: f64, max: f64) -> *mut
    let clamp_type = void_ptr.fn_type(&[void_ptr.into(), f64_type.into(), f64_type.into()], false);
    module.add_function("tl_tensor_clamp", clamp_type, None);
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_clamp") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_clamp as *const () as usize); }

    // tl_tensor_ones(rank: i64, shape: *const usize, req_grad: bool) -> *mut OpaqueTensor
    let ones_type = void_ptr.fn_type(
        &[
            i64_type.into(),
            usize_ptr.into(),
            context.bool_type().into(),
        ],
        false,
    );
    module.add_function("tl_tensor_ones", ones_type, None);

    // Register new return types

    // VarBuilder-based parameter management

    // --- Standard Library Phase 1 ---

    let i8_ptr = context.ptr_type(AddressSpace::default());

    // Strings
    let str_concat_type = i8_ptr.fn_type(&[i8_ptr.into(), i8_ptr.into()], false);
    module.add_function("tl_string_concat", str_concat_type, None);

    // File I/O
    // tl_file_open(path: *const i8, mode: *const i8) -> *mut File
    let file_open_type = void_ptr.fn_type(&[i8_ptr.into(), i8_ptr.into()], false);
    module.add_function("tl_file_open", file_open_type, None);

    // tl_file_read_string(file: *mut File) -> *mut i8
    let file_read_type = i8_ptr.fn_type(&[void_ptr.into()], false);
    module.add_function("tl_file_read_string", file_read_type, None);

    // tl_file_write_string(file: *mut File, content: *const i8) -> void
    let file_write_type = void_type.fn_type(&[void_ptr.into(), i8_ptr.into()], false);
    module.add_function("tl_file_write_string", file_write_type, None);

    // tl_file_close(file: *mut File) -> void
    let file_close_type = void_type.fn_type(&[void_ptr.into()], false);
    module.add_function("tl_file_close", file_close_type, None);

    // Path
    // tl_path_new(path: *const i8) -> *mut Path
    let path_new_type = void_ptr.fn_type(&[i8_ptr.into()], false);
    module.add_function("tl_path_new", path_new_type, None);

    // tl_path_join(base: *mut Path, part: *const i8) -> *mut Path
    let path_join_type = void_ptr.fn_type(&[void_ptr.into(), i8_ptr.into()], false);
    module.add_function("tl_path_join", path_join_type, None);

    // tl_path_exists(path: *mut Path) -> bool
    let path_exists_type = context.bool_type().fn_type(&[void_ptr.into()], false);
    module.add_function("tl_path_exists", path_exists_type, None);

    // tl_path_is_dir(path: *mut Path) -> bool
    let path_is_dir_type = context.bool_type().fn_type(&[void_ptr.into()], false);
    module.add_function("tl_path_is_dir", path_is_dir_type, None);

    // tl_path_is_file(path: *mut Path) -> bool
    let path_is_file_type = context.bool_type().fn_type(&[void_ptr.into()], false);
    module.add_function("tl_path_is_file", path_is_file_type, None);

    // tl_path_to_string(path: *mut Path) -> *mut i8
    let path_to_str_type = i8_ptr.fn_type(&[void_ptr.into()], false);
    module.add_function("tl_path_to_string", path_to_str_type, None);

    // tl_path_free(path: *mut Path) -> void
    let path_free_type = void_type.fn_type(&[void_ptr.into()], false);
    module.add_function("tl_path_free", path_free_type, None);

    // Http
    // tl_http_download(url: *const i8, dest: *const i8) -> bool
    let http_dl_type = context
        .bool_type()
        .fn_type(&[i8_ptr.into(), i8_ptr.into()], false);
    module.add_function("tl_http_download", http_dl_type, None);

    // tl_http_get(url: *const i8) -> *mut i8
    let http_get_type = i8_ptr.fn_type(&[i8_ptr.into()], false);
    module.add_function("tl_http_get", http_get_type, None);

    // Env
    // tl_env_get(key: *const i8) -> *mut i8
    let env_get_type = i8_ptr.fn_type(&[i8_ptr.into()], false);
    module.add_function("tl_env_get", env_get_type, None);

    // tl_env_set(key: *const i8, value: *const i8) -> void
    let env_set_type = void_type.fn_type(&[i8_ptr.into(), i8_ptr.into()], false);
    module.add_function("tl_env_set", env_set_type, None);

    // Phase D: File/Path/System 拡張
    // tl_file_append(path: *const i8, content: *const i8) -> bool
    let file_append_type = context.bool_type().fn_type(&[i8_ptr.into(), i8_ptr.into()], false);
    module.add_function("tl_file_append", file_append_type, None);

    // tl_file_delete(path: *const i8) -> bool
    let file_delete_type = context.bool_type().fn_type(&[i8_ptr.into()], false);
    module.add_function("tl_file_delete", file_delete_type, None);

    // tl_file_create_dir(path: *const i8) -> bool
    let file_create_dir_type = context.bool_type().fn_type(&[i8_ptr.into()], false);
    module.add_function("tl_file_create_dir", file_create_dir_type, None);

    // tl_file_list_dir(path: *const i8) -> *mut VecStruct
    let file_list_dir_type = void_ptr.fn_type(&[i8_ptr.into()], false);
    module.add_function("tl_file_list_dir", file_list_dir_type, None);

    // tl_path_parent(path: *mut Path) -> *mut String
    let path_parent_type = i8_ptr.fn_type(&[void_ptr.into()], false);
    module.add_function("tl_path_parent", path_parent_type, None);

    // tl_path_file_name(path: *mut Path) -> *mut String
    let path_file_name_type = i8_ptr.fn_type(&[void_ptr.into()], false);
    module.add_function("tl_path_file_name", path_file_name_type, None);

    // tl_path_extension(path: *mut Path) -> *mut String
    let path_extension_type = i8_ptr.fn_type(&[void_ptr.into()], false);
    module.add_function("tl_path_extension", path_extension_type, None);

    // tl_system_exit(code: i64) -> void
    let system_exit_type = void_type.fn_type(&[context.i64_type().into()], false);
    module.add_function("tl_system_exit", system_exit_type, None);

    // tl_system_platform() -> *mut StringStruct
    let system_platform_type = i8_ptr.fn_type(&[], false);
    module.add_function("tl_system_platform", system_platform_type, None);

    // tl_system_command(cmd: *mut StringStruct) -> *mut StringStruct
    let system_command_type = i8_ptr.fn_type(&[void_ptr.into()], false);
    module.add_function("tl_system_command", system_command_type, None);

    // System
    // tl_system_time() -> f32
    let system_time_type = context.f32_type().fn_type(&[], false);
    module.add_function("tl_system_time", system_time_type, None);

    // tl_system_sleep(seconds: f32) -> void
    let system_sleep_type = void_type.fn_type(&[context.f32_type().into()], false);
    module.add_function("tl_system_sleep", system_sleep_type, None);

    // Mappings
    if let Some(f) = module.get_function("tl_string_concat") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_concat as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_string_from_int") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_from_int as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_file_open") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_file_open as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_file_read_string") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_file_read_string as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_file_write_string") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_file_write_string as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_file_close") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_file_close as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_path_new") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_path_new as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_path_join") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_path_join as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_path_exists") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_path_exists as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_path_is_dir") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_path_is_dir as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_path_is_file") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_path_is_file as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_path_to_string") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_path_to_string as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_path_free") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_path_free as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_http_download") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_http_download as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_http_get") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_http_get as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_env_get") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_env_get as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_env_set") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_env_set as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_system_time") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_system_time as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_system_sleep") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_system_sleep as *const () as usize);
    }
    // Phase D mappings
    if let Some(f) = module.get_function("tl_file_append") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_file_append as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_file_delete") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_file_delete as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_file_create_dir") {
        execution_engine.add_global_mapping(&f, runtime::file_io::tl_file_create_dir as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_file_list_dir") {
        execution_engine.add_global_mapping(&f, runtime::file_io::tl_file_list_dir as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_path_parent") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_path_parent as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_path_file_name") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_path_file_name as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_path_extension") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_path_extension as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_system_exit") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_system_exit as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_system_platform") {
        execution_engine.add_global_mapping(&f, runtime::system::tl_system_platform as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_system_command") {
        execution_engine.add_global_mapping(&f, runtime::system::tl_system_command as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_read_line") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_read_line as *const () as usize);
    }

    // Memory Manager mappings
    if let Some(f) = module.get_function("tl_mem_enter_scope") {
        execution_engine
            .add_global_mapping(&f, runtime::memory_manager::tl_mem_enter_scope as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_mem_exit_scope") {
        execution_engine
            .add_global_mapping(&f, runtime::memory_manager::tl_mem_exit_scope as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_mem_register_struct") {
        execution_engine
            .add_global_mapping(&f, runtime::memory_manager::tl_mem_register_struct as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_mem_register_tensor") {
        execution_engine
            .add_global_mapping(&f, runtime::memory_manager::tl_mem_register_tensor as *const () as usize);
    }
    if let Some(f) = module.get_function("tl_mem_unregister") {
        execution_engine
            .add_global_mapping(&f, runtime::memory_manager::tl_mem_unregister as *const () as usize);
    }

    if let Some(f) = module.get_function("tl_query") {
        execution_engine.add_global_mapping(&f, runtime::logic::tl_query as *const () as usize);
    }

    // tl_kb_entity_name(id: i64) -> *mut StringStruct
    let kb_entity_name_type = i8_ptr.fn_type(&[i64_type.into()], false);
    add_fn_typed("tl_kb_entity_name", kb_entity_name_type, Type::String("String".to_string()), ret_types);
    if let Some(f) = module.get_function("tl_kb_entity_name") {
        execution_engine.add_global_mapping(&f, runtime::logic::tl_kb_entity_name as *const () as usize);
    }

    // tl_get_memory_mb() -> i64
    let get_memory_type = i64_type.fn_type(&[], false);
    module.add_function("tl_get_memory_mb", get_memory_type, None);

    // tl_get_metal_pool_bytes() -> i64
    let get_metal_pool_bytes_type = i64_type.fn_type(&[], false);
    module.add_function("tl_get_metal_pool_bytes", get_metal_pool_bytes_type, None);

    // tl_get_metal_pool_mb() -> i64
    let get_metal_pool_mb_type = i64_type.fn_type(&[], false);
    module.add_function("tl_get_metal_pool_mb", get_metal_pool_mb_type, None);

    // tl_get_metal_pool_count() -> i64
    let get_metal_pool_count_type = i64_type.fn_type(&[], false);
    module.add_function("tl_get_metal_pool_count", get_metal_pool_count_type, None);
    // tl_metal_sync() -> void
    let metal_sync_type = context.void_type().fn_type(&[], false);
    module.add_function("tl_metal_sync", metal_sync_type, None);
    // tl_trace_mem(file: i8*, line: i32, col: i32, tag: i8*) -> void
    let trace_type = context.void_type().fn_type(
        &[
            i8_ptr.into(),
            context.i32_type().into(),
            context.i32_type().into(),
            i8_ptr.into(),
        ],
        false,
    );
    module.add_function("tl_trace_mem", trace_type, None);
    module.add_function("tl_get_pool_count", get_memory_type, None);
    module.add_function("tl_get_refcount_count", get_memory_type, None);
    module.add_function("tl_get_scope_depth", get_memory_type, None);

    // Memory manager functions
    let void_type = context.void_type();
    let ptr_type = context.ptr_type(inkwell::AddressSpace::default());

    // tl_mem_enter_scope() -> void
    let mem_enter_type = void_type.fn_type(&[], false);
    module.add_function("tl_mem_enter_scope", mem_enter_type, None);

    // tl_mem_exit_scope() -> void
    let mem_exit_type = void_type.fn_type(&[], false);
    module.add_function("tl_mem_exit_scope", mem_exit_type, None);

    // tl_mem_register_struct(ptr) -> void
    let mem_register_struct_type = void_type.fn_type(&[ptr_type.into()], false);
    module.add_function("tl_mem_register_struct", mem_register_struct_type, None);

    // tl_mem_register_tensor(ptr) -> void
    let mem_register_tensor_type = void_type.fn_type(&[ptr_type.into()], false);
    module.add_function("tl_mem_register_tensor", mem_register_tensor_type, None);

    // tl_mem_unregister(ptr) -> void
    let mem_unregister_type = void_type.fn_type(&[ptr_type.into()], false);
    module.add_function("tl_mem_unregister", mem_unregister_type, None);

    // tl_mem_register_struct_named(ptr, name) -> void
    let reg_struct_named_type = void_type.fn_type(&[ptr_type.into(), ptr_type.into()], false);
    module.add_function("tl_mem_register_struct_named", reg_struct_named_type, None);

    // tl_ptr_acquire(ptr) -> void
    let ptr_acquire_type = void_type.fn_type(&[ptr_type.into()], false);
    module.add_function("tl_ptr_acquire", ptr_acquire_type, None);

    // tl_pool_acquire(usize) -> ptr
    let pool_acquire_type = ptr_type.fn_type(&[i64_type.into()], false);
    module.add_function("tl_pool_acquire", pool_acquire_type, None);

    // tl_pool_release(ptr, usize) -> void
    let pool_release_type = void_type.fn_type(&[ptr_type.into(), i64_type.into()], false);
    module.add_function("tl_pool_release", pool_release_type, None);

    // --- KV Cache (Normalized to tl_kvcache_* to match compile_impl_blocks logic) ---
    // Mapped to Wrappers in runtime/llm.rs which handle ptr -> i64 conversion.

    // tl_kvcache_new(sret: ptr, layers: i64) -> void
    let kv_new_type = void_type.fn_type(&[ptr_type.into(), i64_type.into()], false);
    add_fn("tl_kvcache_new", kv_new_type);

    if let Some(f) = module.get_function("tl_kvcache_new") {
        execution_engine.add_global_mapping(&f, runtime::llm::tl_kvcache_new as *const () as usize);
    }

    // tl_kvcache_free(ptr: ptr) -> void
    let kv_free_type = void_type.fn_type(&[ptr_type.into()], false);
    add_fn("tl_kvcache_free", kv_free_type);

    if let Some(f) = module.get_function("tl_kvcache_free") {
        execution_engine.add_global_mapping(&f, runtime::llm::tl_kvcache_free as *const () as usize);
    }

    // tl_kvcache_clear(ptr: ptr) -> void
    let kv_clear_type = void_type.fn_type(&[ptr_type.into()], false);
    add_fn("tl_kvcache_clear", kv_clear_type);
    if let Some(f) = module.get_function("tl_kvcache_clear") {
        execution_engine.add_global_mapping(&f, runtime::llm::tl_kvcache_clear as *const () as usize);
    }

    // tl_kvcache_len(ptr: ptr) -> i64
    let kv_len_type = i64_type.fn_type(&[ptr_type.into()], false);
    add_fn("tl_kvcache_len", kv_len_type);
    if let Some(f) = module.get_function("tl_kvcache_len") {
        execution_engine.add_global_mapping(&f, runtime::llm::tl_kvcache_len as *const () as usize);
    }

    // tl_kvcache_resize(ptr: ptr, max_len: i64) -> void
    let kv_resize_type = void_type.fn_type(&[ptr_type.into(), i64_type.into()], false);
    add_fn("tl_kvcache_resize", kv_resize_type);
    if let Some(f) = module.get_function("tl_kvcache_resize") {
        execution_engine.add_global_mapping(&f, runtime::llm::tl_kvcache_resize as *const () as usize);
    }


    // tl_kvcache_get_k(ptr: ptr, layer: i64) -> Tensor
    let kv_get_type = ptr_type.fn_type(&[ptr_type.into(), i64_type.into()], false);
    add_fn("tl_kvcache_get_k", kv_get_type);

    if let Some(f) = module.get_function("tl_kvcache_get_k") {
        execution_engine.add_global_mapping(&f, runtime::llm::tl_kvcache_get_k as *const () as usize);
    }

    // tl_kvcache_get_v(ptr: ptr, layer: i64) -> Tensor
    add_fn("tl_kvcache_get_v", kv_get_type);

    if let Some(f) = module.get_function("tl_kvcache_get_v") {
        execution_engine.add_global_mapping(&f, runtime::llm::tl_kvcache_get_v as *const () as usize);
    }

    // tl_kvcache_update(ptr, layer, k, v) -> void
    let kv_update_type = void_type.fn_type(
        &[
            ptr_type.into(),
            i64_type.into(),
            ptr_type.into(),
            ptr_type.into(),
        ],
        false,
    );
    add_fn("tl_kvcache_update", kv_update_type);

    if let Some(f) = module.get_function("tl_kvcache_update") {
        execution_engine.add_global_mapping(&f, runtime::llm::tl_kvcache_update as *const () as usize);
    }



    // tl_alloc_tmp(size) -> void*
    let alloc_tmp_type = ptr_type.fn_type(&[i64_type.into()], false);
    module.add_function("tl_alloc_tmp", alloc_tmp_type, None);

    // tl_free_tmp(ptr) -> void
    let free_tmp_type = void_type.fn_type(&[ptr_type.into()], false);
    module.add_function("tl_free_tmp", free_tmp_type, None);

    // tl_query(name: *i8, mask: i64, args: *Tensor, tags: *u8) -> *Tensor
    let query_type = void_ptr.fn_type(
        &[i8_ptr.into(), i64_type.into(), void_ptr.into(), i8_ptr.into()],
        false,
    );
    module.add_function("tl_query", query_type, None);




    // --- Binary file I/O ---
    let i8_ptr = context.ptr_type(inkwell::AddressSpace::default());

    // tl_file_read_binary_all(path) -> *mut Vec<u8>
    let file_read_binary_type = ptr_type.fn_type(&[i8_ptr.into()], false);
    module.add_function("tl_file_read_binary_all", file_read_binary_type, None);

    // tl_file_write_binary(path, data) -> bool
    let file_write_binary_type = context
        .bool_type()
        .fn_type(&[i8_ptr.into(), ptr_type.into()], false);
    module.add_function("tl_file_write_binary", file_write_binary_type, None);

    // --- Image loading functions ---

    // tl_image_load_grayscale(path) -> *mut Vec<u8>
    let image_load_type = ptr_type.fn_type(&[i8_ptr.into()], false);
    module.add_function("tl_image_load_grayscale", image_load_type, None);

    // tl_image_width(path) -> i64
    let image_dim_type = i64_type.fn_type(&[i8_ptr.into()], false);
    module.add_function("tl_image_width", image_dim_type, None);

    // tl_image_height(path) -> i64
    module.add_function("tl_image_height", image_dim_type, None);
    // --- Missing Mappings for Llama 3 ---

    // tl_tensor_map_get_quantized -> ptr (OpaqueQTensor*)
    let qt_get_type = void_ptr.fn_type(&[void_ptr.into(), i8_ptr.into()], false);
    add_fn("tl_tensor_map_get_quantized", qt_get_type);
    if let Some(f) = module.get_function("tl_tensor_map_get_quantized") {
        execution_engine.add_global_mapping(&f, runtime::tl_tensor_map_get_quantized as *const () as usize);
    }

    // tl_qtensor_matmul -> ptr (handle) as 2nd arg
    let qmatmul_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_qtensor_matmul", qmatmul_type);
    if let Some(f) = module.get_function("tl_qtensor_matmul") {
        execution_engine.add_global_mapping(&f, runtime::tl_qtensor_matmul as *const () as usize);
    }

    // tl_qtensor_free
    let qfree_type = void_type.fn_type(&[i64_type.into()], false);
    add_fn("tl_qtensor_free", qfree_type);
    if let Some(f) = module.get_function("tl_qtensor_free") {
        execution_engine.add_global_mapping(&f, runtime::tl_qtensor_free as *const () as usize);
    }

    // tl_string_contains
    let str_contains_type = context
        .bool_type()
        .fn_type(&[i8_ptr.into(), i8_ptr.into()], false);
    add_fn("tl_string_contains", str_contains_type);
    if let Some(f) = module.get_function("tl_string_contains") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_contains as *const () as usize);
    }

    // tl_string_from_int
    let str_from_int_type = i8_ptr.fn_type(&[i64_type.into()], false);
    add_fn_typed("tl_string_from_int", str_from_int_type, Type::String("String".to_string()), ret_types);
    if let Some(f) = module.get_function("tl_string_from_int") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_from_int as *const () as usize);
    }

    // tl_string_trim(s: *mut StringStruct) -> *mut StringStruct
    let str_unary_type = i8_ptr.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_string_trim", str_unary_type);
    if let Some(f) = module.get_function("tl_string_trim") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_trim as *const () as usize);
    }

    // tl_string_starts_with(s, prefix) -> bool
    let str_bool_binary_type = context.bool_type().fn_type(&[i8_ptr.into(), i8_ptr.into()], false);
    add_fn("tl_string_starts_with", str_bool_binary_type);
    if let Some(f) = module.get_function("tl_string_starts_with") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_starts_with as *const () as usize);
    }

    // tl_string_ends_with(s, suffix) -> bool
    add_fn("tl_string_ends_with", str_bool_binary_type);
    if let Some(f) = module.get_function("tl_string_ends_with") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_ends_with as *const () as usize);
    }

    // tl_string_replace(s, from, to) -> *mut StringStruct
    let str_replace_type = i8_ptr.fn_type(&[i8_ptr.into(), i8_ptr.into(), i8_ptr.into()], false);
    add_fn("tl_string_replace", str_replace_type);
    if let Some(f) = module.get_function("tl_string_replace") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_replace as *const () as usize);
    }

    // tl_string_substring(s, start: i64, len: i64) -> *mut StringStruct
    let str_substring_type = i8_ptr.fn_type(&[i8_ptr.into(), i64_type.into(), i64_type.into()], false);
    add_fn("tl_string_substring", str_substring_type);
    if let Some(f) = module.get_function("tl_string_substring") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_substring as *const () as usize);
    }

    // tl_string_is_empty(s) -> bool
    let str_is_empty_type = context.bool_type().fn_type(&[i8_ptr.into()], false);
    add_fn("tl_string_is_empty", str_is_empty_type);
    if let Some(f) = module.get_function("tl_string_is_empty") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_is_empty as *const () as usize);
    }

    // tl_string_to_uppercase(s) -> *mut StringStruct
    add_fn("tl_string_to_uppercase", str_unary_type);
    if let Some(f) = module.get_function("tl_string_to_uppercase") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_to_uppercase as *const () as usize);
    }

    // tl_string_to_lowercase(s) -> *mut StringStruct
    add_fn("tl_string_to_lowercase", str_unary_type);
    if let Some(f) = module.get_function("tl_string_to_lowercase") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_to_lowercase as *const () as usize);
    }

    // tl_string_index_of(s, needle) -> i64
    let str_index_of_type = i64_type.fn_type(&[i8_ptr.into(), i8_ptr.into()], false);
    add_fn("tl_string_index_of", str_index_of_type);
    if let Some(f) = module.get_function("tl_string_index_of") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_index_of as *const () as usize);
    }

    // tl_string_split(s, sep) -> *mut VecStruct (pointer)
    let str_split_type = i8_ptr.fn_type(&[i8_ptr.into(), i8_ptr.into()], false);
    add_fn("tl_string_split", str_split_type);
    if let Some(f) = module.get_function("tl_string_split") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_split as *const () as usize);
    }

    // tl_string_to_f64(s: *mut StringStruct) -> f64
    let str_to_f64_type = f64_type.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_string_to_f64", str_to_f64_type);
    if let Some(f) = module.get_function("tl_string_to_f64") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_to_f64 as *const () as usize);
    }

    // tl_string_repeat(s: *mut StringStruct, n: i64) -> *mut StringStruct
    let str_repeat_type = i8_ptr.fn_type(&[i8_ptr.into(), i64_type.into()], false);
    add_fn("tl_string_repeat", str_repeat_type);
    if let Some(f) = module.get_function("tl_string_repeat") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_repeat as *const () as usize);
    }

    // tl_string_chars(s: *mut StringStruct) -> *mut VecStruct
    let str_chars_type = i8_ptr.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_string_chars", str_chars_type);
    if let Some(f) = module.get_function("tl_string_chars") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_chars as *const () as usize);
    }

    // tl_string_from_chars(vec: *mut VecStruct) -> *mut StringStruct
    let str_from_chars_type = i8_ptr.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_string_from_chars", str_from_chars_type);
    if let Some(f) = module.get_function("tl_string_from_chars") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_from_chars as *const () as usize);
    }

    // tl_string_to_bytes(s: *mut StringStruct) -> *mut VecStruct
    let str_to_bytes_type = i8_ptr.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_string_to_bytes", str_to_bytes_type);
    if let Some(f) = module.get_function("tl_string_to_bytes") {
        execution_engine.add_global_mapping(&f, runtime::string_ffi::tl_string_to_bytes as *const () as usize);
    }

    // tl_string_from_utf8(vec: *mut VecStruct) -> *mut StringStruct
    let str_from_utf8_type = i8_ptr.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_string_from_utf8", str_from_utf8_type);
    if let Some(f) = module.get_function("tl_string_from_utf8") {
        execution_engine.add_global_mapping(&f, runtime::string_ffi::tl_string_from_utf8 as *const () as usize);
    }

    // Regex FFI
    let fn_regex_new_type = i64_type.fn_type(&[i8_ptr.into()], false);
    add_fn("tl_regex_new", fn_regex_new_type);
    if let Some(f) = module.get_function("tl_regex_new") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_regex_new as *const () as usize);
    }

    let fn_regex_is_match_type = context.bool_type().fn_type(&[i64_type.into(), i8_ptr.into()], false);
    add_fn("tl_regex_is_match", fn_regex_is_match_type);
    if let Some(f) = module.get_function("tl_regex_is_match") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_regex_is_match as *const () as usize);
    }

    let fn_regex_replace_type = i8_ptr.fn_type(&[i64_type.into(), i8_ptr.into(), i8_ptr.into()], false);
    add_fn("tl_regex_replace", fn_regex_replace_type);
    if let Some(f) = module.get_function("tl_regex_replace") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_regex_replace as *const () as usize);
    }

    let fn_regex_release_type = void_type.fn_type(&[i64_type.into()], false);
    add_fn("tl_regex_release", fn_regex_release_type);
    if let Some(f) = module.get_function("tl_regex_release") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_regex_release as *const () as usize);
    }

    // Thread FFI
    let fn_thread_spawn_type = i64_type.fn_type(&[usize_ptr.into(), void_ptr.into()], false);
    add_fn("tl_thread_spawn", fn_thread_spawn_type);
    if let Some(f) = module.get_function("tl_thread_spawn") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_thread_spawn as *const () as usize);
    }
    
    let fn_thread_join_type = ptr_type.fn_type(&[i64_type.into()], false);
    add_fn("tl_thread_join", fn_thread_join_type);
    if let Some(f) = module.get_function("tl_thread_join") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_thread_join as *const () as usize);
    }

    // Mutex FFI
    let fn_mutex_new_type = i64_type.fn_type(&[i64_type.into(), void_ptr.into()], false);
    add_fn("tl_mutex_new", fn_mutex_new_type);
    if let Some(f) = module.get_function("tl_mutex_new") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_mutex_new as *const () as usize);
    }
    
    let fn_mutex_modify_type = void_type.fn_type(&[i64_type.into(), usize_ptr.into(), void_ptr.into()], false);
    add_fn("tl_mutex_modify", fn_mutex_modify_type);
    if let Some(f) = module.get_function("tl_mutex_modify") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_mutex_modify as *const () as usize);
    }
    
    let fn_mutex_read_type = void_type.fn_type(&[i64_type.into(), usize_ptr.into(), void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_mutex_read", fn_mutex_read_type);
    if let Some(f) = module.get_function("tl_mutex_read") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_mutex_read as *const () as usize);
    }
    
    let fn_mutex_release_type = void_type.fn_type(&[i64_type.into()], false);
    add_fn("tl_mutex_release", fn_mutex_release_type);
    if let Some(f) = module.get_function("tl_mutex_release") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_mutex_release as *const () as usize);
    }

    // tl_string_from_f64(f: f64) -> *mut StringStruct
    let str_from_f64_type = i8_ptr.fn_type(&[f64_type.into()], false);
    add_fn("tl_string_from_f64", str_from_f64_type);
    if let Some(f) = module.get_function("tl_string_from_f64") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_from_f64 as *const () as usize);
    }

    // tl_string_from_bool(b: bool) -> *mut StringStruct
    let str_from_bool_type = i8_ptr.fn_type(&[context.bool_type().into()], false);
    add_fn("tl_string_from_bool", str_from_bool_type);
    if let Some(f) = module.get_function("tl_string_from_bool") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_string_from_bool as *const () as usize);
    }

    // tl_assert(cond: bool, msg: *mut StringStruct) -> void
    let assert_type = context.void_type().fn_type(&[context.bool_type().into(), i8_ptr.into()], false);
    add_fn("tl_assert", assert_type);
    if let Some(f) = module.get_function("tl_assert") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_assert as *const () as usize);
    }

    // tl_random() -> f64
    let random_type = f64_type.fn_type(&[], false);
    add_fn("tl_random", random_type);
    if let Some(f) = module.get_function("tl_random") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_random as *const () as usize);
    }

    // tl_random_int(min: i64, max: i64) -> i64
    let random_int_type = i64_type.fn_type(&[i64_type.into(), i64_type.into()], false);
    add_fn("tl_random_int", random_int_type);
    if let Some(f) = module.get_function("tl_random_int") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_random_int as *const () as usize);
    }

    // tl_min_i64(a: i64, b: i64) -> i64
    let min_max_i64_type = i64_type.fn_type(&[i64_type.into(), i64_type.into()], false);
    add_fn("tl_min_i64", min_max_i64_type);
    if let Some(f) = module.get_function("tl_min_i64") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_min_i64 as *const () as usize);
    }

    // tl_max_i64(a: i64, b: i64) -> i64
    add_fn("tl_max_i64", min_max_i64_type);
    if let Some(f) = module.get_function("tl_max_i64") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_max_i64 as *const () as usize);
    }

    // tl_min_f64(a: f64, b: f64) -> f64
    let min_max_f64_type = f64_type.fn_type(&[f64_type.into(), f64_type.into()], false);
    add_fn("tl_min_f64", min_max_f64_type);
    if let Some(f) = module.get_function("tl_min_f64") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_min_f64 as *const () as usize);
    }

    // tl_max_f64(a: f64, b: f64) -> f64
    add_fn("tl_max_f64", min_max_f64_type);
    if let Some(f) = module.get_function("tl_max_f64") {
        execution_engine.add_global_mapping(&f, runtime::stdlib::tl_max_f64 as *const () as usize);
    }

    // tl_tensor_argmax(t, dim, keepdim) -> CTensorResult
    let argmax_type = c_tensor_result_type.fn_type(
        &[void_ptr.into(), i64_type.into(), context.bool_type().into()],
        false,
    );
    add_fn("tl_tensor_argmax", argmax_type);
    // [IDevice] device_ffi 統一マッピング
    if let Some(f) = module.get_function("tl_tensor_argmax") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_argmax as *const () as usize);
    }

    // tl_tensor_item_i64 — 宣言のみ (マッピングは L2233 の map_tensor_fn! で実施済み)
    let item_i64_type = i64_type.fn_type(&[void_ptr.into()], false);
    add_fn("tl_tensor_item_i64", item_i64_type);

    // tl_tensor_cat_i64
    // [IDevice] device_ffi 統一マッピング
    if let Some(f) = module.get_function("tl_tensor_cat_i64") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_cat_i64 as *const () as usize);
    }
    // Fix: register return type

    // tl_tensor_reshape -> tl_tensor_reshape_new alias for generic fallback
    // Define types locally since this is late in function
    let void_ptr_local = context.ptr_type(AddressSpace::default());
    let reshape_type =
        void_ptr_local.fn_type(&[void_ptr_local.into(), void_ptr_local.into()], false);

    if module.get_function("tl_tensor_reshape").is_none() {
        module.add_function("tl_tensor_reshape", reshape_type, None);
    }
    // Also need return type
    let _tensor_type_local = Type::Tensor(Box::new(Type::F32), 1);

    // [IDevice] device_ffi 統一マッピング
    if let Some(f) = module.get_function("tl_tensor_reshape") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_reshape_new as *const () as usize);
    }

    // tl_tensor_sample(t, temp, topp) -> tensor (llm.rs)
    let sample_type = void_ptr.fn_type(&[void_ptr.into(), f32_type.into(), f32_type.into()], false);
    add_fn("tl_tensor_sample", sample_type);
    // [IDevice] map_tensor_fn! → device_ffi
    if let Some(f) = module.get_function("tl_tensor_sample") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_sample as *const () as usize); }

    // tl_tensor_shallow_clone(t) -> t
    add_fn("tl_tensor_shallow_clone", clone_type);
    if let Some(f) = module.get_function("tl_tensor_shallow_clone") {
        execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_shallow_clone as *const () as usize);
    }
    
    // Debug Print
    let i8_ptr = context.ptr_type(AddressSpace::default());
    let void_type = context.void_type();
    let debug_print_type = void_type.fn_type(&[i8_ptr.into(), i8_ptr.into()], false);
    module.add_function("tl_debug_print_ptr", debug_print_type, None);
    
    if let Some(f) = module.get_function("tl_debug_print_ptr") {
        execution_engine.add_global_mapping(&f, tl_debug_print_ptr as *const () as usize);
    }

    // ========== chunk / split ==========
    let chunk_type = void_ptr.fn_type(&[void_ptr.into(), i64_type.into(), i64_type.into(), i64_type.into()], false);
    add_fn("tl_device_tensor_chunk", chunk_type);
    add_fn("tl_device_tensor_split", chunk_type);
    if let Some(f) = module.get_function("tl_device_tensor_chunk") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_chunk as *const () as usize); }
    if let Some(f) = module.get_function("tl_device_tensor_split") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_device_tensor_split as *const () as usize); }

    // ========== 線形代数 ==========
    let unary_linalg = void_ptr.fn_type(&[void_ptr.into()], false);
    add_fn("tl_tensor_inverse", unary_linalg);
    add_fn("tl_tensor_det", unary_linalg);
    add_fn("tl_tensor_svd_u", unary_linalg);
    add_fn("tl_tensor_svd_s", unary_linalg);
    add_fn("tl_tensor_svd_v", unary_linalg);
    add_fn("tl_tensor_eig_values", unary_linalg);
    add_fn("tl_tensor_eig_vectors", unary_linalg);
    let binary_linalg = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_tensor_solve", binary_linalg);
    if let Some(f) = module.get_function("tl_tensor_inverse") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_tensor_inverse as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_det") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_tensor_det as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_svd_u") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_tensor_svd_u as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_svd_s") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_tensor_svd_s as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_svd_v") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_tensor_svd_v as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_eig_values") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_tensor_eig_values as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_eig_vectors") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_tensor_eig_vectors as *const () as usize); }
    if let Some(f) = module.get_function("tl_tensor_solve") { execution_engine.add_global_mapping(&f, runtime::device_ffi::tl_tensor_solve as *const () as usize); }

    // ========== オプティマイザ ==========
    // tl_adam_step(param, grad, m, v, step, lr, beta1, beta2, eps, weight_decay)
    let adam_type = void_type.fn_type(&[
        void_ptr.into(), void_ptr.into(), void_ptr.into(), void_ptr.into(),
        i64_type.into(), f32_type.into(), f32_type.into(), f32_type.into(),
        f32_type.into(), f32_type.into(),
    ], false);
    add_fn("tl_adam_step", adam_type);
    if let Some(f) = module.get_function("tl_adam_step") { execution_engine.add_global_mapping(&f, runtime::tl_adam_step as *const () as usize); }

    // tl_sgd_step(param, grad, velocity, lr, momentum, weight_decay, dampening, nesterov)
    let sgd_type = void_type.fn_type(&[
        void_ptr.into(), void_ptr.into(), void_ptr.into(),
        f32_type.into(), f32_type.into(), f32_type.into(), f32_type.into(),
        context.bool_type().into(),
    ], false);
    add_fn("tl_sgd_step", sgd_type);
    if let Some(f) = module.get_function("tl_sgd_step") { execution_engine.add_global_mapping(&f, runtime::tl_sgd_step as *const () as usize); }

    // 学習率スケジューラ
    let lr_sched_type = f32_type.fn_type(&[f32_type.into(), i64_type.into(), i64_type.into(), f32_type.into()], false);
    add_fn("tl_lr_cosine_annealing", lr_sched_type);
    add_fn("tl_lr_step", lr_sched_type);
    if let Some(f) = module.get_function("tl_lr_cosine_annealing") { execution_engine.add_global_mapping(&f, runtime::tl_lr_cosine_annealing as *const () as usize); }
    if let Some(f) = module.get_function("tl_lr_step") { execution_engine.add_global_mapping(&f, runtime::tl_lr_step as *const () as usize); }

    // ========== Image ==========
    let img_load_type = void_ptr.fn_type(&[void_ptr.into()], false);
    add_fn("tl_image_load_rgb", img_load_type);
    let img_resize_type = void_ptr.fn_type(&[void_ptr.into(), i64_type.into(), i64_type.into()], false);
    add_fn("tl_image_resize", img_resize_type);
    let img_save_type = void_type.fn_type(&[void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_image_save", img_save_type);
    let img_norm_type = void_ptr.fn_type(&[void_ptr.into(), void_ptr.into(), void_ptr.into()], false);
    add_fn("tl_image_normalize", img_norm_type);
    let img_crop_type = void_ptr.fn_type(&[void_ptr.into(), i64_type.into(), i64_type.into(), i64_type.into(), i64_type.into()], false);
    add_fn("tl_image_crop", img_crop_type);
    if let Some(f) = module.get_function("tl_image_load_rgb") { execution_engine.add_global_mapping(&f, runtime::tl_image_load_rgb as *const () as usize); }
    if let Some(f) = module.get_function("tl_image_resize") { execution_engine.add_global_mapping(&f, runtime::tl_image_resize as *const () as usize); }
    if let Some(f) = module.get_function("tl_image_save") { execution_engine.add_global_mapping(&f, runtime::tl_image_save as *const () as usize); }
    if let Some(f) = module.get_function("tl_image_normalize") { execution_engine.add_global_mapping(&f, runtime::tl_image_normalize as *const () as usize); }
    if let Some(f) = module.get_function("tl_image_crop") { execution_engine.add_global_mapping(&f, runtime::tl_image_crop as *const () as usize); }

    // ========== Data (CSV / JSON / DataLoader) ==========
    let csv_load_type = void_ptr.fn_type(&[void_ptr.into()], false);
    add_fn("tl_csv_load", csv_load_type);
    let json_load_type = void_ptr.fn_type(&[void_ptr.into()], false);
    add_fn("tl_json_load", json_load_type);
    let dl_new_type = i64_type.fn_type(&[void_ptr.into(), void_ptr.into(), i64_type.into(), context.bool_type().into()], false);
    add_fn("tl_dataloader_new", dl_new_type);
    let dl_len_type = i64_type.fn_type(&[i64_type.into()], false);
    add_fn("tl_dataloader_len", dl_len_type);
    let dl_reset_type = void_type.fn_type(&[i64_type.into()], false);
    add_fn("tl_dataloader_reset", dl_reset_type);
    add_fn("tl_dataloader_free", dl_reset_type);
    if let Some(f) = module.get_function("tl_csv_load") { execution_engine.add_global_mapping(&f, runtime::tl_csv_load as *const () as usize); }
    if let Some(f) = module.get_function("tl_json_load") { execution_engine.add_global_mapping(&f, runtime::tl_json_load as *const () as usize); }
    if let Some(f) = module.get_function("tl_dataloader_new") { execution_engine.add_global_mapping(&f, runtime::tl_dataloader_new as *const () as usize); }
    if let Some(f) = module.get_function("tl_dataloader_len") { execution_engine.add_global_mapping(&f, runtime::tl_dataloader_len as *const () as usize); }
    if let Some(f) = module.get_function("tl_dataloader_reset") { execution_engine.add_global_mapping(&f, runtime::tl_dataloader_reset as *const () as usize); }
    if let Some(f) = module.get_function("tl_dataloader_free") { execution_engine.add_global_mapping(&f, runtime::tl_dataloader_free as *const () as usize); }
}