summaryrefslogtreecommitdiff
path: root/tools/standalone_miri/miri.cpp
blob: c832628377438e74877de437dd1cb896e4805146 (plain)
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
/*
 * mrustc Standalone MIRI
 * - by John Hodge (Mutabah)
 *
 * miri.cpp
 * - Interpreter core
 */
#include <iostream>
#include "module_tree.hpp"
#include "value.hpp"
#include <algorithm>
#include <iomanip>
#include "debug.hpp"
#include "miri.hpp"
// VVV FFI
#include <cstring>  // memrchr
#ifdef _WIN32
# define NOMINMAX
# include <Windows.h>
#endif
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#undef DEBUG

unsigned ThreadState::s_next_tls_key = 1;

class PrimitiveValue
{
public:
    virtual ~PrimitiveValue() {}

    virtual bool is_zero() const = 0;
    virtual bool add(const PrimitiveValue& v) = 0;
    virtual bool subtract(const PrimitiveValue& v) = 0;
    virtual bool multiply(const PrimitiveValue& v) = 0;
    virtual bool divide(const PrimitiveValue& v) = 0;
    virtual bool modulo(const PrimitiveValue& v) = 0;
    virtual void write_to_value(ValueCommonWrite& tgt, size_t ofs) const = 0;

    template<typename T>
    const T& check(const char* opname) const
    {
        const auto* xp = dynamic_cast<const T*>(this);
        LOG_ASSERT(xp, "Attempting to " << opname << " mismatched types, expected " << typeid(T).name() << " got " << typeid(*this).name());
        return *xp;
    }
};
template<typename T>
struct PrimitiveUInt:
    public PrimitiveValue
{
    typedef PrimitiveUInt<T>    Self;
    T   v;

    PrimitiveUInt(T v): v(v) {}
    ~PrimitiveUInt() override {}

    virtual bool is_zero() const {
        return this->v == 0;
    }
    bool add(const PrimitiveValue& x) override {
        const auto* xp = &x.check<Self>("add");
        T newv = this->v + xp->v;
        bool did_overflow = newv < this->v;
        this->v = newv;
        return !did_overflow;
    }
    bool subtract(const PrimitiveValue& x) override {
        const auto* xp = &x.check<Self>("subtract");
        T newv = this->v - xp->v;
        bool did_overflow = newv > this->v;
        this->v = newv;
        return !did_overflow;
    }
    bool multiply(const PrimitiveValue& x) override {
        const auto* xp = &x.check<Self>("multiply");
        T newv = this->v * xp->v;
        bool did_overflow = newv < this->v && newv < xp->v;
        this->v = newv;
        return !did_overflow;
    }
    bool divide(const PrimitiveValue& x) override {
        const auto* xp = &x.check<Self>("divide");
        if(xp->v == 0)  return false;
        T newv = this->v / xp->v;
        this->v = newv;
        return true;
    }
    bool modulo(const PrimitiveValue& x) override {
        const auto* xp = &x.check<Self>("modulo");
        if(xp->v == 0)  return false;
        T newv = this->v % xp->v;
        this->v = newv;
        return true;
    }
};
struct PrimitiveU64: public PrimitiveUInt<uint64_t>
{
    PrimitiveU64(uint64_t v): PrimitiveUInt(v) {}
    void write_to_value(ValueCommonWrite& tgt, size_t ofs) const override {
        tgt.write_u64(ofs, this->v);
    }
};
struct PrimitiveU32: public PrimitiveUInt<uint32_t>
{
    PrimitiveU32(uint32_t v): PrimitiveUInt(v) {}
    void write_to_value(ValueCommonWrite& tgt, size_t ofs) const override {
        tgt.write_u32(ofs, this->v);
    }
};
struct PrimitiveU16: public PrimitiveUInt<uint16_t>
{
    PrimitiveU16(uint16_t v): PrimitiveUInt(v) {}
    void write_to_value(ValueCommonWrite& tgt, size_t ofs) const override {
        tgt.write_u16(ofs, this->v);
    }
};
struct PrimitiveU8: public PrimitiveUInt<uint8_t>
{
    PrimitiveU8(uint8_t v): PrimitiveUInt(v) {}
    void write_to_value(ValueCommonWrite& tgt, size_t ofs) const override {
        tgt.write_u8(ofs, this->v);
    }
};
template<typename T>
struct PrimitiveSInt:
    public PrimitiveValue
{
    typedef PrimitiveSInt<T>    Self;
    T   v;

    PrimitiveSInt(T v): v(v) {}
    ~PrimitiveSInt() override {}

    virtual bool is_zero() const {
        return this->v == 0;
    }
    // TODO: Make this correct.
    bool add(const PrimitiveValue& x) override {
        const auto* xp = &x.check<Self>("add");
        T newv = this->v + xp->v;
        bool did_overflow = newv < this->v;
        this->v = newv;
        return !did_overflow;
    }
    bool subtract(const PrimitiveValue& x) override {
        const auto* xp = &x.check<Self>("subtract");
        T newv = this->v - xp->v;
        bool did_overflow = newv > this->v;
        this->v = newv;
        return !did_overflow;
    }
    bool multiply(const PrimitiveValue& x) override {
        const auto* xp = &x.check<Self>("multiply");
        T newv = this->v * xp->v;
        bool did_overflow = newv < this->v && newv < xp->v;
        this->v = newv;
        return !did_overflow;
    }
    bool divide(const PrimitiveValue& x) override {
        const auto* xp = &x.check<Self>("divide");
        if(xp->v == 0)  return false;
        T newv = this->v / xp->v;
        this->v = newv;
        return true;
    }
    bool modulo(const PrimitiveValue& x) override {
        const auto* xp = &x.check<Self>("modulo");
        if(xp->v == 0)  return false;
        T newv = this->v % xp->v;
        this->v = newv;
        return true;
    }
};
struct PrimitiveI64: public PrimitiveSInt<int64_t>
{
    PrimitiveI64(int64_t v): PrimitiveSInt(v) {}
    void write_to_value(ValueCommonWrite& tgt, size_t ofs) const override {
        tgt.write_i64(ofs, this->v);
    }
};
struct PrimitiveI32: public PrimitiveSInt<int32_t>
{
    PrimitiveI32(int32_t v): PrimitiveSInt(v) {}
    void write_to_value(ValueCommonWrite& tgt, size_t ofs) const override {
        tgt.write_i32(ofs, this->v);
    }
};

class PrimitiveValueVirt
{
    uint64_t    buf[3]; // Allows i128 plus a vtable pointer
    PrimitiveValueVirt() {}
public:
    // HACK: No copy/move constructors, assumes that contained data is always POD
    ~PrimitiveValueVirt() {
        reinterpret_cast<PrimitiveValue*>(&this->buf)->~PrimitiveValue();
    }
    PrimitiveValue& get() { return *reinterpret_cast<PrimitiveValue*>(&this->buf); }
    const PrimitiveValue& get() const { return *reinterpret_cast<const PrimitiveValue*>(&this->buf); }

    static PrimitiveValueVirt from_value(const ::HIR::TypeRef& t, const ValueRef& v) {
        PrimitiveValueVirt  rv;
        LOG_ASSERT(t.get_wrapper() == nullptr, "PrimitiveValueVirt::from_value: " << t);
        switch(t.inner_type)
        {
        case RawType::U8:
            new(&rv.buf) PrimitiveU8(v.read_u8(0));
            break;
        case RawType::U16:
            new(&rv.buf) PrimitiveU16(v.read_u16(0));
            break;
        case RawType::U32:
            new(&rv.buf) PrimitiveU32(v.read_u32(0));
            break;
        case RawType::U64:
            new(&rv.buf) PrimitiveU64(v.read_u64(0));
            break;
        case RawType::USize:
            if( POINTER_SIZE == 8 )
                new(&rv.buf) PrimitiveU64(v.read_u64(0));
            else
                new(&rv.buf) PrimitiveU32(v.read_u32(0));
            break;

        case RawType::I32:
            new(&rv.buf) PrimitiveI32(v.read_i32(0));
            break;
        case RawType::I64:
            new(&rv.buf) PrimitiveI64(v.read_i64(0));
            break;
        case RawType::ISize:
            if( POINTER_SIZE == 8 )
                new(&rv.buf) PrimitiveI64(v.read_i64(0));
            else
                new(&rv.buf) PrimitiveI32(v.read_i32(0));
            break;
        default:
            LOG_TODO("PrimitiveValueVirt::from_value: " << t);
        }
        return rv;
    }
};

struct Ops {
    template<typename T>
    static int do_compare(T l, T r) {
        if( l == r ) {
            return 0;
        }
        else if( !(l != r) ) {
            // Special return value for NaN w/ NaN
            return 2;
        }
        else if( l < r ) {
            return -1;
        }
        else {
            return 1;
        }
    }
    template<typename T>
    static T do_bitwise(T l, T r, ::MIR::eBinOp op) {
        switch(op)
        {
        case ::MIR::eBinOp::BIT_AND:    return l & r;
        case ::MIR::eBinOp::BIT_OR:     return l | r;
        case ::MIR::eBinOp::BIT_XOR:    return l ^ r;
        case ::MIR::eBinOp::BIT_SHL:    return l << r;
        case ::MIR::eBinOp::BIT_SHR:    return l >> r;
        default:
            LOG_BUG("Unexpected operation in Ops::do_bitwise");
        }
    }
};

struct MirHelpers
{
    InterpreterThread&  thread;
    InterpreterThread::StackFrame&  frame;

    MirHelpers(InterpreterThread& thread, InterpreterThread::StackFrame& frame):
        thread(thread),
        frame(frame)
    {
    }

    ValueRef get_value_and_type_root(const ::MIR::LValue::Storage& lv_root, ::HIR::TypeRef& ty)
    {
        switch(lv_root.tag())
        {
        case ::MIR::LValue::Storage::TAGDEAD:    throw "";
        // --> Slots
        TU_ARM(lv_root, Return, _e) {
            ty = this->frame.fcn->ret_ty;
            return ValueRef(this->frame.ret);
            } break;
        TU_ARM(lv_root, Local, e) {
            ty = this->frame.fcn->m_mir.locals.at(e);
            return ValueRef(this->frame.locals.at(e));
            } break;
        TU_ARM(lv_root, Argument, e) {
            ty = this->frame.fcn->args.at(e);
            return ValueRef(this->frame.args.at(e));
            } break;
        TU_ARM(lv_root, Static, e) {
            /*const*/ auto& s = this->thread.m_modtree.get_static(e);
            ty = s.ty;
            return ValueRef(s.val);
            } break;
        }
        throw "";
    }
    ValueRef get_value_and_type(const ::MIR::LValue& lv, ::HIR::TypeRef& ty)
    {
        auto vr = get_value_and_type_root(lv.m_root, ty);
        for(const auto& w : lv.m_wrappers)
        {
            switch(w.tag())
            {
            case ::MIR::LValue::Wrapper::TAGDEAD:    throw "";
            // --> Modifiers
            TU_ARM(w, Index, idx_var) {
                auto idx = this->frame.locals.at(idx_var).read_usize(0);
                const auto* wrapper = ty.get_wrapper();
                if( !wrapper )
                {
                    LOG_ERROR("Indexing non-array/slice - " << ty);
                    throw "ERROR";
                }
                else if( wrapper->type == TypeWrapper::Ty::Array )
                {
                    ty = ty.get_inner();
                    vr.m_offset += ty.get_size() * idx;
                }
                else if( wrapper->type == TypeWrapper::Ty::Slice )
                {
                    ty = ty.get_inner();
                    LOG_ASSERT(vr.m_metadata, "No slice metadata");
                    auto len = vr.m_metadata->read_usize(0);
                    LOG_ASSERT(idx < len, "Slice index out of range");
                    vr.m_offset += ty.get_size() * idx;
                }
                else
                {
                    LOG_ERROR("Indexing non-array/slice - " << ty);
                    throw "ERROR";
                }
                } break;
            TU_ARM(w, Field, fld_idx) {
                // TODO: if there's metadata present in the base, but the inner doesn't have metadata, clear the metadata
                size_t inner_ofs;
                auto inner_ty = ty.get_field(fld_idx, inner_ofs);
                LOG_DEBUG("Field - " << ty << "#" << fld_idx << " = @" << inner_ofs << " " << inner_ty);
                vr.m_offset += inner_ofs;
                if( inner_ty.get_meta_type() == HIR::TypeRef(RawType::Unreachable) )
                {
                    LOG_ASSERT(vr.m_size >= inner_ty.get_size(), "Field didn't fit in the value - " << inner_ty.get_size() << " required, but " << vr.m_size << " available");
                    vr.m_size = inner_ty.get_size();
                }
                ty = ::std::move(inner_ty);
                }
            TU_ARM(w, Downcast, variant_index) {
                auto composite_ty = ::std::move(ty);
                LOG_DEBUG("Downcast - " << composite_ty);

                size_t inner_ofs;
                ty = composite_ty.get_field(variant_index, inner_ofs);
                vr.m_offset += inner_ofs;
                }
            TU_ARM(w, Deref, _) {
                auto ptr_ty = ::std::move(ty);
                ty = ptr_ty.get_inner();
                LOG_DEBUG("Deref - " << vr << " into " << ty);

                LOG_ASSERT(vr.m_size >= POINTER_SIZE, "Deref pointer isn't large enough to be a pointer");
                // TODO: Move the metadata machinery into `deref` (or at least the logic needed to get the value size)
                //auto inner_val = vr.deref(0, ty);
                size_t ofs = vr.read_usize(0);
                LOG_ASSERT(ofs != 0, "Dereferencing NULL pointer");
                auto alloc = vr.get_relocation(0);
                if( alloc )
                {
                    // TODO: It's valid to dereference (but not read) a non-null invalid pointer.
                    LOG_ASSERT(ofs >= Allocation::PTR_BASE, "Dereferencing invalid pointer - " << ofs << " into " << alloc);
                    ofs -= Allocation::PTR_BASE;
                }
                else
                {
                }

                // There MUST be a relocation at this point with a valid allocation.
                LOG_TRACE("Interpret " << alloc << " + " << ofs << " as value of type " << ty);
                // NOTE: No alloc can happen when dereferencing a zero-sized pointer
                if( alloc.is_alloc() )
                {
                    //LOG_DEBUG("Deref - lvr=" << ::MIR::LValue::CRef(lv, &w - &lv.m_wrappers.front()) << " alloc=" << alloc.alloc());
                }
                else
                {
                    LOG_ASSERT(ty.get_meta_type() != RawType::Unreachable || ty.get_size() >= 0, "Dereference (giving a non-ZST) with no allocation");
                }
                size_t size;

                const auto meta_ty = ty.get_meta_type();
                ::std::shared_ptr<Value>    meta_val;
                // If the type has metadata, store it.
                if( meta_ty != RawType::Unreachable )
                {
                    auto meta_size = meta_ty.get_size();
                    LOG_ASSERT(vr.m_size == POINTER_SIZE + meta_size, "Deref of " << ty << ", but pointer isn't correct size");
                    meta_val = ::std::make_shared<Value>( vr.read_value(POINTER_SIZE, meta_size) );

                    size_t    slice_inner_size;
                    if( ty.has_slice_meta(slice_inner_size) ) {
                        // Slice metadata, add the base size (if it's a struct) to the variable size
                        // - `get_wrapper` will return non-null for `[T]`, special-case `str`
                        size = (ty != RawType::Str && ty.get_wrapper() == nullptr ? ty.get_size() : 0) + meta_val->read_usize(0) * slice_inner_size;
                    }
                    //else if( ty == RawType::TraitObject) {
                    //    // NOTE: Getting the size from the allocation is semi-valid, as you can't sub-slice trait objects
                    //    size = alloc.get_size() - ofs;
                    //}
                    else {
                        LOG_DEBUG("> Meta " << *meta_val << ", size = " << alloc.get_size() << " - " << ofs);
                        // TODO: if the inner type is a trait object, then check that it has an allocation.
                        size = alloc.get_size() - ofs;
                    }
                }
                else
                {
                    LOG_DEBUG("sizeof(" << ty << ") = " << ty.get_size());
                    LOG_ASSERT(vr.m_size == POINTER_SIZE, "Deref of a value that isn't a pointer-sized value (size=" << vr << ") - " << vr << ": " << ptr_ty);
                    size = ty.get_size();
                    if( !alloc ) {
                        LOG_ERROR("Deref of a value with no relocation - " << vr);
                    }
                }

                LOG_DEBUG("Deref - New VR: alloc=" << alloc << ", ofs=" << ofs << ", size=" << size);
                vr = ValueRef(::std::move(alloc), ofs, size);
                vr.m_metadata = ::std::move(meta_val);
                } break;
            }
        }
        return vr;
    }
    ValueRef get_value_ref(const ::MIR::LValue& lv)
    {
        ::HIR::TypeRef  tmp;
        return get_value_and_type(lv, tmp);
    }

    ::HIR::TypeRef get_lvalue_ty(const ::MIR::LValue& lv)
    {
        ::HIR::TypeRef  ty;
        get_value_and_type(lv, ty);
        return ty;
    }

    Value read_lvalue_with_ty(const ::MIR::LValue& lv, ::HIR::TypeRef& ty)
    {
        auto base_value = get_value_and_type(lv, ty);

        return base_value.read_value(0, ty.get_size());
    }
    Value read_lvalue(const ::MIR::LValue& lv)
    {
        ::HIR::TypeRef  ty;
        return read_lvalue_with_ty(lv, ty);
    }
    void write_lvalue(const ::MIR::LValue& lv, Value val)
    {
        // TODO: Ensure that target is writable? Or should write_value do that?
        //LOG_DEBUG(lv << " = " << val);
        ::HIR::TypeRef  ty;
        auto base_value = get_value_and_type(lv, ty);

        if(base_value.m_alloc) {
            base_value.m_alloc.alloc().write_value(base_value.m_offset, ::std::move(val));
        }
        else {
            base_value.m_value->write_value(base_value.m_offset, ::std::move(val));
        }
    }

    Value const_to_value(const ::MIR::Constant& c, ::HIR::TypeRef& ty)
    {
        switch(c.tag())
        {
        case ::MIR::Constant::TAGDEAD:  throw "";
        TU_ARM(c, Int, ce) {
            ty = ::HIR::TypeRef(ce.t);
            Value val = Value(ty);
            val.write_bytes(0, &ce.v, ::std::min(ty.get_size(), sizeof(ce.v)));  // TODO: Endian
            // TODO: If the write was clipped, sign-extend
            // TODO: i128/u128 need the upper bytes cleared+valid
            return val;
            } break;
        TU_ARM(c, Uint, ce) {
            ty = ::HIR::TypeRef(ce.t);
            Value val = Value(ty);
            val.write_bytes(0, &ce.v, ::std::min(ty.get_size(), sizeof(ce.v)));  // TODO: Endian
            // TODO: i128/u128 need the upper bytes cleared+valid
            return val;
            } break;
        TU_ARM(c, Bool, ce) {
            Value val = Value(::HIR::TypeRef { RawType::Bool });
            val.write_bytes(0, &ce.v, 1);
            return val;
            } break;
        TU_ARM(c, Float, ce) {
            ty = ::HIR::TypeRef(ce.t);
            Value val = Value(ty);
            if( ce.t.raw_type == RawType::F64 ) {
                val.write_bytes(0, &ce.v, ::std::min(ty.get_size(), sizeof(ce.v)));  // TODO: Endian/format?
            }
            else if( ce.t.raw_type == RawType::F32 ) {
                float v = static_cast<float>(ce.v);
                val.write_bytes(0, &v, ::std::min(ty.get_size(), sizeof(v)));  // TODO: Endian/format?
            }
            else {
                throw ::std::runtime_error("BUG: Invalid type in Constant::Float");
            }
            return val;
            } break;
        TU_ARM(c, Const, ce) {
            LOG_BUG("Constant::Const in mmir");
            } break;
        TU_ARM(c, Bytes, ce) {
            ty = ::HIR::TypeRef(RawType::U8).wrap(TypeWrapper::Ty::Slice, 0).wrap(TypeWrapper::Ty::Borrow, 0);
            Value val = Value(ty);
            val.write_ptr(0, Allocation::PTR_BASE + 0, RelocationPtr::new_ffi(FFIPointer::new_const_bytes("Constant::Bytes", ce.data(), ce.size())));
            val.write_usize(POINTER_SIZE, ce.size());
            LOG_DEBUG(c << " = " << val);
            return val;
            } break;
        TU_ARM(c, StaticString, ce) {
            ty = ::HIR::TypeRef(RawType::Str).wrap(TypeWrapper::Ty::Borrow, 0);
            Value val = Value(ty);
            val.write_ptr(0, Allocation::PTR_BASE + 0, RelocationPtr::new_string(&ce));
            val.write_usize(POINTER_SIZE, ce.size());
            LOG_DEBUG(c << " = " << val);
            return val;
            } break;
        // --> Accessor
        TU_ARM(c, ItemAddr, ce) {
            // Create a value with a special backing allocation of zero size that references the specified item.
            if( /*const auto* fn =*/ this->thread.m_modtree.get_function_opt(*ce) ) {
                ty = ::HIR::TypeRef(RawType::Function);
                return Value::new_fnptr(*ce);
            }
            if( const auto* s = this->thread.m_modtree.get_static_opt(*ce) ) {
                ty = s->ty.wrapped(TypeWrapper::Ty::Borrow, 0);
                return Value::new_pointer(ty, Allocation::PTR_BASE + 0, RelocationPtr::new_alloc(s->val.allocation));
            }
            LOG_ERROR("Constant::ItemAddr - " << *ce << " - not found");
            } break;
        }
        throw "";
    }
    Value const_to_value(const ::MIR::Constant& c)
    {
        ::HIR::TypeRef  ty;
        return const_to_value(c, ty);
    }
    Value param_to_value(const ::MIR::Param& p, ::HIR::TypeRef& ty)
    {
        switch(p.tag())
        {
        case ::MIR::Param::TAGDEAD: throw "";
        TU_ARM(p, Constant, pe)
            return const_to_value(pe, ty);
        TU_ARM(p, LValue, pe)
            return read_lvalue_with_ty(pe, ty);
        }
        throw "";
    }
    Value param_to_value(const ::MIR::Param& p)
    {
        ::HIR::TypeRef  ty;
        return param_to_value(p, ty);
    }

    ValueRef get_value_ref_param(const ::MIR::Param& p, Value& tmp, ::HIR::TypeRef& ty)
    {
        switch(p.tag())
        {
        case ::MIR::Param::TAGDEAD: throw "";
        TU_ARM(p, Constant, pe)
            tmp = const_to_value(pe, ty);
            return ValueRef(tmp, 0, ty.get_size());
        TU_ARM(p, LValue, pe)
            return get_value_and_type(pe, ty);
        }
        throw "";
    }
};

// ====================================================================
//
// ====================================================================
InterpreterThread::~InterpreterThread()
{
    for(size_t i = 0; i < m_stack.size(); i++)
    {
        const auto& frame = m_stack[m_stack.size() - 1 - i];
        ::std::cout << "#" << i << ": ";
        if( frame.cb )
        {
            ::std::cout << "WRAPPER";
        }
        else
        {
            ::std::cout << frame.fcn->my_path << " BB" << frame.bb_idx << "/";
            if( frame.stmt_idx == frame.fcn->m_mir.blocks.at(frame.bb_idx).statements.size() )
                ::std::cout << "TERM";
            else
                ::std::cout << frame.stmt_idx;
        }
        ::std::cout << ::std::endl;
    }
}
void InterpreterThread::start(const ::HIR::Path& p, ::std::vector<Value> args)
{
    assert( this->m_stack.empty() );
    Value   v;
    if( this->call_path(v, p, ::std::move(args)) )
    {
        LOG_TODO("Handle immediate return thread entry");
    }
}
bool InterpreterThread::step_one(Value& out_thread_result)
{
    assert( !this->m_stack.empty() );
    assert( !this->m_stack.back().cb );
    auto& cur_frame = this->m_stack.back();
    TRACE_FUNCTION_R(cur_frame.fcn->my_path << " BB" << cur_frame.bb_idx << "/" << cur_frame.stmt_idx, "");
    const auto& bb = cur_frame.fcn->m_mir.blocks.at( cur_frame.bb_idx );

    const size_t    MAX_STACK_DEPTH = 60;
    if( this->m_stack.size() > MAX_STACK_DEPTH )
    {
        LOG_ERROR("Maximum stack depth of " << MAX_STACK_DEPTH << " exceeded");
    }

    MirHelpers  state { *this, cur_frame };

    if( cur_frame.stmt_idx < bb.statements.size() )
    {
        const auto& stmt = bb.statements[cur_frame.stmt_idx];
        LOG_DEBUG("=== BB" << cur_frame.bb_idx << "/" << cur_frame.stmt_idx << ": " << stmt);
        switch(stmt.tag())
        {
        case ::MIR::Statement::TAGDEAD: throw "";
        TU_ARM(stmt, Assign, se) {
            Value   new_val;
            switch(se.src.tag())
            {
            case ::MIR::RValue::TAGDEAD: throw "";
            TU_ARM(se.src, Use, re) {
                new_val = state.read_lvalue(re);
                } break;
            TU_ARM(se.src, Constant, re) {
                new_val = state.const_to_value(re);
                } break;
            TU_ARM(se.src, Borrow, re) {
                ::HIR::TypeRef  src_ty;
                ValueRef src_base_value = state.get_value_and_type(re.val, src_ty);
                auto alloc = src_base_value.m_alloc;
                // If the source doesn't yet have a relocation, give it a backing allocation so we can borrow
                if( !alloc && src_base_value.m_value )
                {
                    LOG_DEBUG("Borrow - Creating allocation for " << src_base_value);
                    if( !src_base_value.m_value->allocation )
                    {
                        src_base_value.m_value->create_allocation();
                    }
                    alloc = RelocationPtr::new_alloc( src_base_value.m_value->allocation );
                }
                if( alloc.is_alloc() )
                    LOG_DEBUG("Borrow - alloc=" << alloc << " (" << alloc.alloc() << ")");
                else
                    LOG_DEBUG("Borrow - alloc=" << alloc);
                size_t ofs = src_base_value.m_offset;
                const auto meta = src_ty.get_meta_type();
                auto dst_ty = src_ty.wrapped(TypeWrapper::Ty::Borrow, static_cast<size_t>(re.type));
                LOG_DEBUG("Borrow - ofs=" << ofs << ", meta_ty=" << meta);

                // Create the pointer (can this just store into the target?)
                new_val = Value(dst_ty);
                new_val.write_ptr(0, Allocation::PTR_BASE + ofs, ::std::move(alloc));
                // - Add metadata if required
                if( meta != RawType::Unreachable )
                {
                    LOG_ASSERT(src_base_value.m_metadata, "Borrow of an unsized value, but no metadata avaliable");
                    new_val.write_value(POINTER_SIZE, *src_base_value.m_metadata);
                }
                } break;
            TU_ARM(se.src, Cast, re) {
                // Determine the type of cast, is it a reinterpret or is it a value transform?
                // - Float <-> integer is a transform, anything else should be a reinterpret.
                ::HIR::TypeRef  src_ty;
                auto src_value = state.get_value_and_type(re.val, src_ty);

                new_val = Value(re.type);
                if( re.type == src_ty )
                {
                    // No-op cast
                    new_val = src_value.read_value(0, re.type.get_size());
                }
                else if( const auto* dst_w = re.type.get_wrapper() )
                {
                    // Destination can only be a raw pointer
                    if( dst_w->type != TypeWrapper::Ty::Pointer ) {
                        LOG_ERROR("Attempting to cast to a type other than a raw pointer - " << re.type);
                    }
                    if( const auto* src_w = src_ty.get_wrapper() )
                    {
                        // Source can be either
                        if( src_w->type != TypeWrapper::Ty::Pointer && src_w->type != TypeWrapper::Ty::Borrow ) {
                            LOG_ERROR("Attempting to cast to a pointer from a non-pointer - " << src_ty);
                        }

                        if( src_ty.get_size() < re.type.get_size() )
                        {
                            LOG_ERROR("Casting to a fatter pointer, " << src_ty << " -> " << re.type);
                        }
                        else
                        {
                            new_val = src_value.read_value(0, re.type.get_size());
                        }
                    }
                    else
                    {
                        if( src_ty == RawType::Function )
                        {
                        }
                        else if( src_ty == RawType::USize )
                        {
                        }
                        else
                        {
                            LOG_ERROR("Trying to cast to pointer (" << re.type <<" ) from invalid type (" << src_ty << ")\n");
                        }
                        new_val = src_value.read_value(0, re.type.get_size());
                    }
                }
                else if( const auto* src_w = src_ty.get_wrapper() )
                {
                    if( src_w->type != TypeWrapper::Ty::Pointer && src_w->type != TypeWrapper::Ty::Borrow ) {
                        LOG_ERROR("Attempting to cast from a non-pointer - " << src_ty);
                    }
                    // TODO: MUST be a thin pointer?

                    // TODO: MUST be an integer (usize only?)
                    switch(re.type.wrappers.empty() ? re.type.inner_type : RawType::Unreachable)
                    {
                    case RawType::USize:
                    case RawType::ISize:
                        break;
                    case RawType::U64:
                    case RawType::I64:
                        // TODO: Only if 64-bit?
                        break;
                    default:
                        LOG_ERROR("Casting from a pointer to non-usize - " << src_ty << " to " << re.type);
                        throw "ERROR";
                    }
                    new_val = src_value.read_value(0, re.type.get_size());
                }
                else
                {
                    // TODO: What happens if there'a cast of something with a relocation?
                    switch(re.type.inner_type)
                    {
                    case RawType::Unreachable:  throw "BUG";
                    case RawType::Composite:
                    case RawType::TraitObject:
                    case RawType::Function:
                    case RawType::Str:
                    case RawType::Unit:
                        LOG_ERROR("Casting to " << re.type << " is invalid");
                        throw "ERROR";
                    case RawType::F32: {
                        float dst_val = 0.0;
                        // Can be an integer, or F64 (pointer is impossible atm)
                        switch(src_ty.inner_type)
                        {
                        case RawType::Unreachable:  throw "BUG";
                        case RawType::Composite:    throw "ERROR";
                        case RawType::TraitObject:  throw "ERROR";
                        case RawType::Function:     throw "ERROR";
                        case RawType::Char: throw "ERROR";
                        case RawType::Str:  throw "ERROR";
                        case RawType::Unit: throw "ERROR";
                        case RawType::Bool: throw "ERROR";
                        case RawType::F32:  throw "BUG";
                        case RawType::F64:  dst_val = static_cast<float>( src_value.read_f64(0) ); break;
                        case RawType::USize:    throw "TODO";// /*dst_val = src_value.read_usize();*/   break;
                        case RawType::ISize:    throw "TODO";// /*dst_val = src_value.read_isize();*/   break;
                        case RawType::U8:   dst_val = static_cast<float>( src_value.read_u8 (0) );  break;
                        case RawType::I8:   dst_val = static_cast<float>( src_value.read_i8 (0) );  break;
                        case RawType::U16:  dst_val = static_cast<float>( src_value.read_u16(0) );  break;
                        case RawType::I16:  dst_val = static_cast<float>( src_value.read_i16(0) );  break;
                        case RawType::U32:  dst_val = static_cast<float>( src_value.read_u32(0) );  break;
                        case RawType::I32:  dst_val = static_cast<float>( src_value.read_i32(0) );  break;
                        case RawType::U64:  dst_val = static_cast<float>( src_value.read_u64(0) );  break;
                        case RawType::I64:  dst_val = static_cast<float>( src_value.read_i64(0) );  break;
                        case RawType::U128: throw "TODO";// /*dst_val = src_value.read_u128();*/ break;
                        case RawType::I128: throw "TODO";// /*dst_val = src_value.read_i128();*/ break;
                        }
                        new_val.write_f32(0, dst_val);
                        } break;
                    case RawType::F64: {
                        double dst_val = 0.0;
                        // Can be an integer, or F32 (pointer is impossible atm)
                        switch(src_ty.inner_type)
                        {
                        case RawType::Unreachable:  throw "BUG";
                        case RawType::Composite:    throw "ERROR";
                        case RawType::TraitObject:  throw "ERROR";
                        case RawType::Function:     throw "ERROR";
                        case RawType::Char: throw "ERROR";
                        case RawType::Str:  throw "ERROR";
                        case RawType::Unit: throw "ERROR";
                        case RawType::Bool: throw "ERROR";
                        case RawType::F64:  throw "BUG";
                        case RawType::F32:  dst_val = static_cast<double>( src_value.read_f32(0) ); break;
                        case RawType::USize:    dst_val = static_cast<double>( src_value.read_usize(0) );   break;
                        case RawType::ISize:    dst_val = static_cast<double>( src_value.read_isize(0) );   break;
                        case RawType::U8:   dst_val = static_cast<double>( src_value.read_u8 (0) );  break;
                        case RawType::I8:   dst_val = static_cast<double>( src_value.read_i8 (0) );  break;
                        case RawType::U16:  dst_val = static_cast<double>( src_value.read_u16(0) );  break;
                        case RawType::I16:  dst_val = static_cast<double>( src_value.read_i16(0) );  break;
                        case RawType::U32:  dst_val = static_cast<double>( src_value.read_u32(0) );  break;
                        case RawType::I32:  dst_val = static_cast<double>( src_value.read_i32(0) );  break;
                        case RawType::U64:  dst_val = static_cast<double>( src_value.read_u64(0) );  break;
                        case RawType::I64:  dst_val = static_cast<double>( src_value.read_i64(0) );  break;
                        case RawType::U128: throw "TODO"; /*dst_val = src_value.read_u128();*/ break;
                        case RawType::I128: throw "TODO"; /*dst_val = src_value.read_i128();*/ break;
                        }
                        new_val.write_f64(0, dst_val);
                        } break;
                    case RawType::Bool:
                        LOG_TODO("Cast to " << re.type);
                    case RawType::Char:
                        switch(src_ty.inner_type)
                        {
                        case RawType::Char: new_val.write_u32(0, src_value.read_u32(0) );  break;
                        case RawType::U8:   new_val.write_u32(0, src_value.read_u8(0) );   break;
                        default:
                            LOG_ERROR("Cast from " << src_ty << " to char isn't valid");
                            break;
                        }
                        break;
                    case RawType::USize:
                    case RawType::U8:
                    case RawType::U16:
                    case RawType::U32:
                    case RawType::U64:
                    case RawType::ISize:
                    case RawType::I8:
                    case RawType::I16:
                    case RawType::I32:
                    case RawType::I64:
                        {
                        uint64_t dst_val = 0;
                        // Can be an integer, or F32 (pointer is impossible atm)
                        switch(src_ty.inner_type)
                        {
                        case RawType::Unreachable:
                            LOG_BUG("Casting unreachable");
                        case RawType::TraitObject:
                        case RawType::Str:
                            LOG_FATAL("Cast of unsized type - " << src_ty);
                        case RawType::Function:
                            LOG_ASSERT(re.type.inner_type == RawType::USize, "Function pointers can only be casted to usize, instead " << re.type);
                            new_val = src_value.read_value(0, re.type.get_size());
                            break;
                        case RawType::Char: {
                            uint32_t v = src_value.read_u32(0);
                            switch(re.type.inner_type)
                            {
                            case RawType::U8:
                                if( v > 0xFF ) {
                                    LOG_NOTICE("Casting to u8 from char above 255");
                                }
                                new_val.write_u8(0, v & 0xFF);
                                break;
                            case RawType::U32:
                                new_val = src_value.read_value(0, 4);
                                break;
                            case RawType::USize:
                                new_val.write_usize(0, v);
                                break;
                            default:
                                LOG_ERROR("Char can only be casted to u32/u8, instead " << re.type);
                            }
                            } break;
                        case RawType::Unit:
                            LOG_FATAL("Cast of unit");
                        case RawType::Composite: {
                            const auto& dt = *src_ty.composite_type;
                            if( dt.variants.size() == 0 ) {
                                LOG_FATAL("Cast of composite - " << src_ty);
                            }
                            // TODO: Check that all variants have the same tag offset
                            LOG_ASSERT(dt.fields.size() == 1, "");
                            LOG_ASSERT(dt.fields[0].first == 0, "");
                            for(size_t i = 0; i < dt.variants.size(); i ++ ) {
                                LOG_ASSERT(dt.variants[i].base_field == 0, "");
                                LOG_ASSERT(dt.variants[i].field_path.empty(), "");
                            }
                            ::HIR::TypeRef  tag_ty = dt.fields[0].second;
                            LOG_ASSERT(tag_ty.get_wrapper() == nullptr, "");
                            switch(tag_ty.inner_type)
                            {
                            case RawType::USize:
                                dst_val = static_cast<uint64_t>( src_value.read_usize(0) );
                                if(0)
                            case RawType::ISize:
                                dst_val = static_cast<uint64_t>( src_value.read_isize(0) );
                                if(0)
                            case RawType::U8:
                                dst_val = static_cast<uint64_t>( src_value.read_u8 (0) );
                                if(0)
                            case RawType::I8:
                                dst_val = static_cast<uint64_t>( src_value.read_i8 (0) );
                                if(0)
                            case RawType::U16:
                                dst_val = static_cast<uint64_t>( src_value.read_u16(0) );
                                if(0)
                            case RawType::I16:
                                dst_val = static_cast<uint64_t>( src_value.read_i16(0) );
                                if(0)
                            case RawType::U32:
                                dst_val = static_cast<uint64_t>( src_value.read_u32(0) );
                                if(0)
                            case RawType::I32:
                                dst_val = static_cast<uint64_t>( src_value.read_i32(0) );
                                if(0)
                            case RawType::U64:
                                dst_val = static_cast<uint64_t>( src_value.read_u64(0) );
                                if(0)
                            case RawType::I64:
                                dst_val = static_cast<uint64_t>( src_value.read_i64(0) );
                                break;
                            default:
                                LOG_FATAL("Bad tag type in cast - " << tag_ty);
                            }
                            } if(0)
                        case RawType::Bool:
                            dst_val = static_cast<uint64_t>( src_value.read_u8 (0) );
                            if(0)
                        case RawType::F64:
                            dst_val = static_cast<uint64_t>( src_value.read_f64(0) );
                            if(0)
                        case RawType::F32:
                            dst_val = static_cast<uint64_t>( src_value.read_f32(0) );
                            if(0)
                        case RawType::USize:
                            dst_val = static_cast<uint64_t>( src_value.read_usize(0) );
                            if(0)
                        case RawType::ISize:
                            dst_val = static_cast<uint64_t>( src_value.read_isize(0) );
                            if(0)
                        case RawType::U8:
                            dst_val = static_cast<uint64_t>( src_value.read_u8 (0) );
                            if(0)
                        case RawType::I8:
                            dst_val = static_cast<uint64_t>( src_value.read_i8 (0) );
                            if(0)
                        case RawType::U16:
                            dst_val = static_cast<uint64_t>( src_value.read_u16(0) );
                            if(0)
                        case RawType::I16:
                            dst_val = static_cast<uint64_t>( src_value.read_i16(0) );
                            if(0)
                        case RawType::U32:
                            dst_val = static_cast<uint64_t>( src_value.read_u32(0) );
                            if(0)
                        case RawType::I32:
                            dst_val = static_cast<uint64_t>( src_value.read_i32(0) );
                            if(0)
                        case RawType::U64:
                            dst_val = static_cast<uint64_t>( src_value.read_u64(0) );
                            if(0)
                        case RawType::I64:
                            dst_val = static_cast<uint64_t>( src_value.read_i64(0) );

                            switch(re.type.inner_type)
                            {
                            case RawType::USize:
                                new_val.write_usize(0, dst_val);
                                break;
                            case RawType::U8:
                                new_val.write_u8(0, static_cast<uint8_t>(dst_val));
                                break;
                            case RawType::U16:
                                new_val.write_u16(0, static_cast<uint16_t>(dst_val));
                                break;
                            case RawType::U32:
                                new_val.write_u32(0, static_cast<uint32_t>(dst_val));
                                break;
                            case RawType::U64:
                                new_val.write_u64(0, dst_val);
                                break;
                            case RawType::ISize:
                                new_val.write_usize(0, static_cast<int64_t>(dst_val));
                                break;
                            case RawType::I8:
                                new_val.write_i8(0, static_cast<int8_t>(dst_val));
                                break;
                            case RawType::I16:
                                new_val.write_i16(0, static_cast<int16_t>(dst_val));
                                break;
                            case RawType::I32:
                                new_val.write_i32(0, static_cast<int32_t>(dst_val));
                                break;
                            case RawType::I64:
                                new_val.write_i64(0, static_cast<int64_t>(dst_val));
                                break;
                            default:
                                throw "";
                            }
                            break;
                        case RawType::U128: throw "TODO"; /*dst_val = src_value.read_u128();*/ break;
                        case RawType::I128: throw "TODO"; /*dst_val = src_value.read_i128();*/ break;
                        }
                        } break;
                    case RawType::U128:
                    case RawType::I128:
                        LOG_TODO("Cast to " << re.type);
                    }
                }
                } break;
            TU_ARM(se.src, BinOp, re) {
                ::HIR::TypeRef  ty_l, ty_r;
                Value   tmp_l, tmp_r;
                auto v_l = state.get_value_ref_param(re.val_l, tmp_l, ty_l);
                auto v_r = state.get_value_ref_param(re.val_r, tmp_r, ty_r);
                LOG_DEBUG(v_l << " (" << ty_l <<") ? " << v_r << " (" << ty_r <<")");

                switch(re.op)
                {
                case ::MIR::eBinOp::EQ:
                case ::MIR::eBinOp::NE:
                case ::MIR::eBinOp::GT:
                case ::MIR::eBinOp::GE:
                case ::MIR::eBinOp::LT:
                case ::MIR::eBinOp::LE: {
                    LOG_ASSERT(ty_l == ty_r, "BinOp type mismatch - " << ty_l << " != " << ty_r);
                    int res = 0;

                    auto reloc_l = v_l.get_relocation(0);
                    auto reloc_r = v_r.get_relocation(0);


                    // TODO: Handle comparison of the relocations too
                    // - If both sides have a relocation:
                    //   > EQ/NE always valid
                    //   > others require the same relocation
                    // - If one side has a relocation:
                    //   > EQ/NE only allow zero on the non-reloc side
                    //   > others are invalid?
                    if( reloc_l && reloc_r )
                    {
                        // Both have relocations, check if they're equal
                        if( reloc_l != reloc_r )
                        {
                            switch(re.op)
                            {
                            case ::MIR::eBinOp::EQ:
                            case ::MIR::eBinOp::NE:
                                res = 1;
                                break;
                            default:
                                LOG_FATAL("Unable to compare " << v_l << " and " << v_r << " - different relocations");
                            }
                            // - Equality will always fail
                            // - Ordering is a bug
                        }
                        else
                        {
                            // Equal: Allow all comparisons
                        }
                    }
                    else if( reloc_l || reloc_r )
                    {
                        // Only one side
                        // - Ordering is a bug
                        // - Equalities are allowed, but only for `0`?
                        switch(re.op)
                        {
                        case ::MIR::eBinOp::EQ:
                        case ::MIR::eBinOp::NE:
                            // - Allow success, as addresses can be masked down
                            break;
                        default:
                            LOG_FATAL("Unable to compare " << v_l << " and " << v_r << " - different relocations");
                        }
                    }
                    else
                    {
                        // No relocations, no need to check more
                    }

                    if( const auto* w = ty_l.get_wrapper() )
                    {
                        if( w->type == TypeWrapper::Ty::Pointer )
                        {
                            // TODO: Technically only EQ/NE are valid.

                            res = res != 0 ? res : Ops::do_compare(v_l.read_usize(0), v_r.read_usize(0));

                            // Compare fat metadata.
                            if( res == 0 && v_l.m_size > POINTER_SIZE )
                            {
                                reloc_l = v_l.get_relocation(POINTER_SIZE);
                                reloc_r = v_r.get_relocation(POINTER_SIZE);

                                if( res == 0 && reloc_l != reloc_r )
                                {
                                    res = (reloc_l < reloc_r ? -1 : 1);
                                }
                                res = res != 0 ? res : Ops::do_compare(v_l.read_usize(POINTER_SIZE), v_r.read_usize(POINTER_SIZE));
                            }
                        }
                        else
                        {
                            LOG_TODO("BinOp comparisons - " << se.src << " w/ " << ty_l);
                        }
                    }
                    else
                    {
                        switch(ty_l.inner_type)
                        {
                        case RawType::U64:  res = res != 0 ? res : Ops::do_compare(v_l.read_u64(0), v_r.read_u64(0));   break;
                        case RawType::U32:  res = res != 0 ? res : Ops::do_compare(v_l.read_u32(0), v_r.read_u32(0));   break;
                        case RawType::U16:  res = res != 0 ? res : Ops::do_compare(v_l.read_u16(0), v_r.read_u16(0));   break;
                        case RawType::U8 :  res = res != 0 ? res : Ops::do_compare(v_l.read_u8 (0), v_r.read_u8 (0));   break;
                        case RawType::I64:  res = res != 0 ? res : Ops::do_compare(v_l.read_i64(0), v_r.read_i64(0));   break;
                        case RawType::I32:  res = res != 0 ? res : Ops::do_compare(v_l.read_i32(0), v_r.read_i32(0));   break;
                        case RawType::I16:  res = res != 0 ? res : Ops::do_compare(v_l.read_i16(0), v_r.read_i16(0));   break;
                        case RawType::I8 :  res = res != 0 ? res : Ops::do_compare(v_l.read_i8 (0), v_r.read_i8 (0));   break;
                        case RawType::USize: res = res != 0 ? res : Ops::do_compare(v_l.read_usize(0), v_r.read_usize(0)); break;
                        case RawType::ISize: res = res != 0 ? res : Ops::do_compare(v_l.read_isize(0), v_r.read_isize(0)); break;
                        case RawType::Char: res = res != 0 ? res : Ops::do_compare(v_l.read_u32(0), v_r.read_u32(0)); break;
                        case RawType::Bool: res = res != 0 ? res : Ops::do_compare(v_l.read_u8(0), v_r.read_u8(0)); break;  // TODO: `read_bool` that checks for bool values?
                        default:
                            LOG_TODO("BinOp comparisons - " << se.src << " w/ " << ty_l);
                        }
                    }
                    bool res_bool;
                    switch(re.op)
                    {
                    case ::MIR::eBinOp::EQ: res_bool = (res == 0);  break;
                    case ::MIR::eBinOp::NE: res_bool = (res != 0);  break;
                    case ::MIR::eBinOp::GT: res_bool = (res == 1);  break;
                    case ::MIR::eBinOp::GE: res_bool = (res == 1 || res == 0);  break;
                    case ::MIR::eBinOp::LT: res_bool = (res == -1); break;
                    case ::MIR::eBinOp::LE: res_bool = (res == -1 || res == 0); break;
                        break;
                    default:
                        LOG_BUG("Unknown comparison");
                    }
                    new_val = Value(::HIR::TypeRef(RawType::Bool));
                    new_val.write_u8(0, res_bool ? 1 : 0);
                    } break;
                case ::MIR::eBinOp::BIT_SHL:
                case ::MIR::eBinOp::BIT_SHR: {
                    LOG_ASSERT(ty_l.get_wrapper() == nullptr, "Bitwise operator on non-primitive - " << ty_l);
                    LOG_ASSERT(ty_r.get_wrapper() == nullptr, "Bitwise operator with non-primitive - " << ty_r);
                    size_t max_bits = ty_l.get_size() * 8;
                    uint8_t shift;
                    auto check_cast_u = [&](auto v){ LOG_ASSERT(0 <= v && v <= max_bits, "Shift out of range - " << v); return static_cast<uint8_t>(v); };
                    auto check_cast_s = [&](auto v){ LOG_ASSERT(v <= static_cast<int64_t>(max_bits), "Shift out of range - " << v); return static_cast<uint8_t>(v); };
                    switch(ty_r.inner_type)
                    {
                    case RawType::U64:  shift = check_cast_u(v_r.read_u64(0));    break;
                    case RawType::U32:  shift = check_cast_u(v_r.read_u32(0));    break;
                    case RawType::U16:  shift = check_cast_u(v_r.read_u16(0));    break;
                    case RawType::U8 :  shift = check_cast_u(v_r.read_u8 (0));    break;
                    case RawType::I64:  shift = check_cast_s(v_r.read_i64(0));    break;
                    case RawType::I32:  shift = check_cast_s(v_r.read_i32(0));    break;
                    case RawType::I16:  shift = check_cast_s(v_r.read_i16(0));    break;
                    case RawType::I8 :  shift = check_cast_s(v_r.read_i8 (0));    break;
                    case RawType::USize:  shift = check_cast_u(v_r.read_usize(0));    break;
                    case RawType::ISize:  shift = check_cast_s(v_r.read_isize(0));    break;
                    default:
                        LOG_TODO("BinOp shift RHS unknown type - " << se.src << " w/ " << ty_r);
                    }
                    new_val = Value(ty_l);
                    switch(ty_l.inner_type)
                    {
                    // TODO: U128
                    case RawType::U64:  new_val.write_u64(0, Ops::do_bitwise(v_l.read_u64(0), static_cast<uint64_t>(shift), re.op));   break;
                    case RawType::U32:  new_val.write_u32(0, Ops::do_bitwise(v_l.read_u32(0), static_cast<uint32_t>(shift), re.op));   break;
                    case RawType::U16:  new_val.write_u16(0, Ops::do_bitwise(v_l.read_u16(0), static_cast<uint16_t>(shift), re.op));   break;
                    case RawType::U8 :  new_val.write_u8 (0, Ops::do_bitwise(v_l.read_u8 (0), static_cast<uint8_t >(shift), re.op));   break;
                    case RawType::USize: new_val.write_usize(0, Ops::do_bitwise(v_l.read_usize(0), static_cast<uint64_t>(shift), re.op));   break;
                    // Is signed allowed? (yes)
                    // - What's the exact semantics? For now assuming it's unsigned+reinterpret
                    case RawType::ISize: new_val.write_usize(0, Ops::do_bitwise(v_l.read_usize(0), static_cast<uint64_t>(shift), re.op));   break;
                    default:
                        LOG_TODO("BinOp shift LHS unknown type - " << se.src << " w/ " << ty_l);
                    }
                    } break;
                case ::MIR::eBinOp::BIT_AND:
                case ::MIR::eBinOp::BIT_OR:
                case ::MIR::eBinOp::BIT_XOR:
                    LOG_ASSERT(ty_l == ty_r, "BinOp type mismatch - " << ty_l << " != " << ty_r);
                    LOG_ASSERT(ty_l.get_wrapper() == nullptr, "Bitwise operator on non-primitive - " << ty_l);
                    new_val = Value(ty_l);
                    switch(ty_l.inner_type)
                    {
                    // TODO: U128/I128
                    case RawType::U64:
                    case RawType::I64:
                        new_val.write_u64( 0, Ops::do_bitwise(v_l.read_u64(0), v_r.read_u64(0), re.op) );
                        break;
                    case RawType::U32:
                    case RawType::I32:
                        new_val.write_u32( 0, static_cast<uint32_t>(Ops::do_bitwise(v_l.read_u32(0), v_r.read_u32(0), re.op)) );
                        break;
                    case RawType::U16:
                    case RawType::I16:
                        new_val.write_u16( 0, static_cast<uint16_t>(Ops::do_bitwise(v_l.read_u16(0), v_r.read_u16(0), re.op)) );
                        break;
                    case RawType::U8:
                    case RawType::I8:
                    case RawType::Bool:
                        new_val.write_u8 ( 0, static_cast<uint8_t >(Ops::do_bitwise(v_l.read_u8 (0), v_r.read_u8 (0), re.op)) );
                        break;
                    case RawType::USize:
                    case RawType::ISize:
                        new_val.write_usize( 0, Ops::do_bitwise(v_l.read_usize(0), v_r.read_usize(0), re.op) );
                        break;
                    default:
                        LOG_TODO("BinOp bitwise - " << se.src << " w/ " << ty_l);
                    }
                    // If the LHS had a relocation, propagate it over
                    if( auto r = v_l.get_relocation(0) )
                    {
                        LOG_DEBUG("- Restore relocation " << r);
                        new_val.create_allocation();
                        new_val.allocation->set_reloc(0, ::std::min(POINTER_SIZE, new_val.size()), r);
                    }

                    break;
                default:
                    LOG_ASSERT(ty_l == ty_r, "BinOp type mismatch - " << ty_l << " != " << ty_r);
                    auto val_l = PrimitiveValueVirt::from_value(ty_l, v_l);
                    auto val_r = PrimitiveValueVirt::from_value(ty_r, v_r);
                    RelocationPtr   new_val_reloc;
                    switch(re.op)
                    {
                    case ::MIR::eBinOp::ADD:
                        LOG_ASSERT(!v_r.get_relocation(0), "RHS of `+` has a relocation");
                        new_val_reloc = v_l.get_relocation(0);
                        val_l.get().add( val_r.get() );
                        break;
                    case ::MIR::eBinOp::SUB:
                        if( auto r = v_l.get_relocation(0) )
                        {
                            if( v_r.get_relocation(0) )
                            {
                                // Pointer difference, no relocation in output
                            }
                            else
                            {
                                new_val_reloc = ::std::move(r);
                            }
                        }
                        else
                        {
                            LOG_ASSERT(!v_r.get_relocation(0), "RHS of `-` has a relocation but LHS does not");
                        }
                        val_l.get().subtract( val_r.get() );
                        break;
                    case ::MIR::eBinOp::MUL:    val_l.get().multiply( val_r.get() ); break;
                    case ::MIR::eBinOp::DIV:    val_l.get().divide( val_r.get() ); break;
                    case ::MIR::eBinOp::MOD:    val_l.get().modulo( val_r.get() ); break;

                    default:
                        LOG_TODO("Unsupported binary operator?");
                    }
                    new_val = Value(ty_l);
                    val_l.get().write_to_value(new_val, 0);
                    if( new_val_reloc )
                    {
                        new_val.create_allocation();
                        new_val.allocation->set_reloc(0, ::std::min(POINTER_SIZE, new_val.size()), ::std::move(new_val_reloc));
                    }
                    break;
                }
                } break;
            TU_ARM(se.src, UniOp, re) {
                ::HIR::TypeRef  ty;
                auto v = state.get_value_and_type(re.val, ty);
                LOG_ASSERT(ty.get_wrapper() == nullptr, "UniOp on wrapped type - " << ty);
                new_val = Value(ty);
                switch(re.op)
                {
                case ::MIR::eUniOp::INV:
                    switch(ty.inner_type)
                    {
                    case RawType::U128:
                    case RawType::I128:
                        LOG_TODO("UniOp::INV U128");
                    case RawType::U64:
                    case RawType::I64:
                        new_val.write_u64( 0, ~v.read_u64(0) );
                        break;
                    case RawType::U32:
                    case RawType::I32:
                        new_val.write_u32( 0, ~v.read_u32(0) );
                        break;
                    case RawType::U16:
                    case RawType::I16:
                        new_val.write_u16( 0, ~v.read_u16(0) );
                        break;
                    case RawType::U8:
                    case RawType::I8:
                        new_val.write_u8 ( 0, ~v.read_u8 (0) );
                        break;
                    case RawType::USize:
                    case RawType::ISize:
                        new_val.write_usize( 0, ~v.read_usize(0) );
                        break;
                    case RawType::Bool:
                        new_val.write_u8 ( 0, v.read_u8 (0) == 0 );
                        break;
                    default:
                        LOG_TODO("UniOp::INV - w/ type " << ty);
                    }
                    break;
                case ::MIR::eUniOp::NEG:
                    switch(ty.inner_type)
                    {
                    case RawType::I128:
                        LOG_TODO("UniOp::NEG I128");
                    case RawType::I64:
                        new_val.write_i64( 0, -v.read_i64(0) );
                        break;
                    case RawType::I32:
                        new_val.write_i32( 0, -v.read_i32(0) );
                        break;
                    case RawType::I16:
                        new_val.write_i16( 0, -v.read_i16(0) );
                        break;
                    case RawType::I8:
                        new_val.write_i8 ( 0, -v.read_i8 (0) );
                        break;
                    case RawType::ISize:
                        new_val.write_isize( 0, -v.read_isize(0) );
                        break;
                    default:
                        LOG_ERROR("UniOp::INV not valid on type " << ty);
                    }
                    break;
                }
                } break;
            TU_ARM(se.src, DstMeta, re) {
                auto ptr = state.get_value_ref(re.val);

                ::HIR::TypeRef  dst_ty;
                state.get_value_and_type(se.dst, dst_ty);
                new_val = ptr.read_value(POINTER_SIZE, dst_ty.get_size());
                } break;
            TU_ARM(se.src, DstPtr, re) {
                auto ptr = state.get_value_ref(re.val);

                new_val = ptr.read_value(0, POINTER_SIZE);
                } break;
            TU_ARM(se.src, MakeDst, re) {
                // - Get target type, just for some assertions
                ::HIR::TypeRef  dst_ty;
                state.get_value_and_type(se.dst, dst_ty);
                new_val = Value(dst_ty);

                auto ptr  = state.param_to_value(re.ptr_val );
                auto meta = state.param_to_value(re.meta_val);
                LOG_DEBUG("ty=" << dst_ty << ", ptr=" << ptr << ", meta=" << meta);

                new_val.write_value(0, ::std::move(ptr));
                new_val.write_value(POINTER_SIZE, ::std::move(meta));
                } break;
            TU_ARM(se.src, Tuple, re) {
                ::HIR::TypeRef  dst_ty;
                state.get_value_and_type(se.dst, dst_ty);
                new_val = Value(dst_ty);

                for(size_t i = 0; i < re.vals.size(); i++)
                {
                    auto fld_ofs = dst_ty.composite_type->fields.at(i).first;
                    new_val.write_value(fld_ofs, state.param_to_value(re.vals[i]));
                }
                } break;
            TU_ARM(se.src, Array, re) {
                ::HIR::TypeRef  dst_ty;
                state.get_value_and_type(se.dst, dst_ty);
                new_val = Value(dst_ty);
                // TODO: Assert that type is an array
                auto inner_ty = dst_ty.get_inner();
                size_t stride = inner_ty.get_size();

                size_t ofs = 0;
                for(const auto& v : re.vals)
                {
                    new_val.write_value(ofs, state.param_to_value(v));
                    ofs += stride;
                }
                } break;
            TU_ARM(se.src, SizedArray, re) {
                ::HIR::TypeRef  dst_ty;
                state.get_value_and_type(se.dst, dst_ty);
                new_val = Value(dst_ty);
                // TODO: Assert that type is an array
                auto inner_ty = dst_ty.get_inner();
                size_t stride = inner_ty.get_size();

                size_t ofs = 0;
                for(size_t i = 0; i < re.count; i++)
                {
                    new_val.write_value(ofs, state.param_to_value(re.val));
                    ofs += stride;
                }
                } break;
            TU_ARM(se.src, Variant, re) {
                // 1. Get the composite by path.
                const auto& data_ty = this->m_modtree.get_composite(re.path);
                auto dst_ty = ::HIR::TypeRef(&data_ty);
                new_val = Value(dst_ty);
                // Three cases:
                // - Unions (no tag)
                // - Data enums (tag and data)
                // - Value enums (no data)
                const auto& var = data_ty.variants.at(re.index);
                if( var.data_field != SIZE_MAX )
                {
                    const auto& fld = data_ty.fields.at(re.index);

                    new_val.write_value(fld.first, state.param_to_value(re.val));
                }
                if( var.base_field != SIZE_MAX )
                {
                    ::HIR::TypeRef  tag_ty;
                    size_t tag_ofs = dst_ty.get_field_ofs(var.base_field, var.field_path, tag_ty);
                    LOG_ASSERT(tag_ty.get_size() == var.tag_data.size(), "");
                    new_val.write_bytes(tag_ofs, var.tag_data.data(), var.tag_data.size());
                }
                else
                {
                    // Union, no tag
                }
                LOG_DEBUG("Variant " << new_val);
                } break;
            TU_ARM(se.src, Struct, re) {
                const auto& data_ty = m_modtree.get_composite(re.path);

                ::HIR::TypeRef  dst_ty;
                state.get_value_and_type(se.dst, dst_ty);
                new_val = Value(dst_ty);
                LOG_ASSERT(dst_ty.composite_type == &data_ty, "Destination type of RValue::Struct isn't the same as the input");

                for(size_t i = 0; i < re.vals.size(); i++)
                {
                    auto fld_ofs = data_ty.fields.at(i).first;
                    auto v = state.param_to_value(re.vals[i]);
                    LOG_DEBUG("Struct - @" << fld_ofs << " = " << v);
                    new_val.write_value(fld_ofs, ::std::move(v));
                }
                } break;
            }
            LOG_DEBUG("- new_val=" << new_val);
            state.write_lvalue(se.dst, ::std::move(new_val));
            } break;
        case ::MIR::Statement::TAG_Asm:
            LOG_TODO(stmt);
            break;
        TU_ARM(stmt, Drop, se) {
            if( se.flag_idx == ~0u || cur_frame.drop_flags.at(se.flag_idx) )
            {
                ::HIR::TypeRef  ty;
                auto v = state.get_value_and_type(se.slot, ty);

                // - Take a pointer to the inner
                auto alloc = v.m_alloc;
                if( !alloc )
                {
                    if( !v.m_value->allocation )
                    {
                        v.m_value->create_allocation();
                    }
                    alloc = RelocationPtr::new_alloc( v.m_value->allocation );
                }
                size_t ofs = v.m_offset;
                //LOG_ASSERT(ty.get_meta_type() == RawType::Unreachable, "Dropping an unsized type with Statement::Drop - " << ty);

                auto ptr_ty = ty.wrapped(TypeWrapper::Ty::Borrow, /*BorrowTy::Unique*/2);

                auto ptr_val = Value::new_pointer(ptr_ty, Allocation::PTR_BASE + ofs, ::std::move(alloc));
                if( v.m_metadata )
                {
                    ptr_val.write_value(POINTER_SIZE, *v.m_metadata);
                }

                if( !drop_value(ptr_val, ty, /*shallow=*/se.kind == ::MIR::eDropKind::SHALLOW) )
                {
                    return false;
                }
            }
            } break;
        TU_ARM(stmt, SetDropFlag, se) {
            bool val = (se.other == ~0u ? false : cur_frame.drop_flags.at(se.other)) != se.new_val;
            LOG_DEBUG("- " << val);
            cur_frame.drop_flags.at(se.idx) = val;
            } break;
        case ::MIR::Statement::TAG_ScopeEnd:
            LOG_TODO(stmt);
            break;
        }

        cur_frame.stmt_idx += 1;
    }
    else
    {
        LOG_DEBUG("=== BB" << cur_frame.bb_idx << "/TERM: " << bb.terminator);
        switch(bb.terminator.tag())
        {
        case ::MIR::Terminator::TAGDEAD:    throw "";
        TU_ARM(bb.terminator, Incomplete, _te)
            LOG_TODO("Terminator::Incomplete hit");
        TU_ARM(bb.terminator, Diverge, _te)
            LOG_DEBUG("DIVERGE (continue panic)");
            assert(m_thread.panic_count > 0);
            m_thread.panic_active = true;
            return this->pop_stack(out_thread_result);
        TU_ARM(bb.terminator, Panic, _te)
            LOG_TODO("Terminator::Panic");
        TU_ARM(bb.terminator, Goto, te)
            cur_frame.bb_idx = te;
            break;
        TU_ARM(bb.terminator, Return, _te)
            LOG_DEBUG("RETURN " << cur_frame.ret);
            return this->pop_stack(out_thread_result);
        TU_ARM(bb.terminator, If, te) {
            uint8_t v = state.get_value_ref(te.cond).read_u8(0);
            LOG_ASSERT(v == 0 || v == 1, "");
            cur_frame.bb_idx = v ? te.bb0 : te.bb1;
            } break;
        TU_ARM(bb.terminator, Switch, te) {
            ::HIR::TypeRef ty;
            auto v = state.get_value_and_type(te.val, ty);
            LOG_ASSERT(ty.get_wrapper() == nullptr, "Matching on wrapped value - " << ty);
            LOG_ASSERT(ty.inner_type == RawType::Composite, "Matching on non-coposite - " << ty);

            // TODO: Convert the variant list into something that makes it easier to switch on.
            size_t found_target = SIZE_MAX;
            size_t default_target = SIZE_MAX;
            for(size_t i = 0; i < ty.composite_type->variants.size(); i ++)
            {
                const auto& var = ty.composite_type->variants[i];
                if( var.tag_data.size() == 0 )
                {
                    // Save as the default, error for multiple defaults
                    if( default_target != SIZE_MAX )
                    {
                        LOG_FATAL("Two variants with no tag in Switch - " << ty);
                    }
                    default_target = i;
                }
                else
                {
                    // Get offset, read the value.
                    ::HIR::TypeRef  tag_ty;
                    size_t tag_ofs = ty.get_field_ofs(var.base_field, var.field_path, tag_ty);
                    // Read the value bytes
                    ::std::vector<char> tmp( var.tag_data.size() );
                    v.read_bytes(tag_ofs, const_cast<char*>(tmp.data()), tmp.size());
                    if( v.get_relocation(tag_ofs) )
                        continue ;
                    if( ::std::memcmp(tmp.data(), var.tag_data.data(), tmp.size()) == 0 )
                    {
                        found_target = i;
                        break ;
                    }
                }
            }

            if( found_target == SIZE_MAX )
            {
                found_target = default_target;
            }
            if( found_target == SIZE_MAX )
            {
                LOG_FATAL("Terminator::Switch on " << ty << " didn't find a variant");
            }
            cur_frame.bb_idx = te.targets.at(found_target);
            } break;
        TU_ARM(bb.terminator, SwitchValue, te) {
            ::HIR::TypeRef ty;
            auto v = state.get_value_and_type(te.val, ty);
            TU_MATCH_HDRA( (te.values), {)
            TU_ARMA(Unsigned, vals) {
                LOG_ASSERT(vals.size() == te.targets.size(), "Mismatch in SwitchValue target/value list lengths");
                // Read an unsigned value 
                if( ty.get_wrapper() ) {
                    LOG_ERROR("Terminator::SwitchValue::Unsigned with wrapped type - " << ty);
                }
                uint64_t switch_val;
                switch(ty.inner_type)
                {
                case RawType::U8:   switch_val = v.read_u8(0); break;
                case RawType::U16:  switch_val = v.read_u16(0); break;
                case RawType::U32:  switch_val = v.read_u32(0); break;
                case RawType::U64:  switch_val = v.read_u64(0); break;
                case RawType::U128: LOG_TODO("Terminator::SwitchValue::Unsigned with u128");
                case RawType::USize:    switch_val = v.read_usize(0); break;
                default:
                    LOG_ERROR("Terminator::SwitchValue::Unsigned with unexpected type - " << ty);
                }

                auto it = ::std::find(vals.begin(), vals.end(), switch_val);
                if( it != vals.end() )
                {
                    auto idx = it - vals.begin();
                    LOG_TRACE("- " << switch_val << " matched arm " << idx);
                    cur_frame.bb_idx = te.targets.at(idx);
                }
                else
                {
                    LOG_TRACE("- " << switch_val << " not matched, taking default arm");
                    cur_frame.bb_idx = te.def_target;
                }
                }
            TU_ARMA(Signed, vals) {
                if( ty.get_wrapper() ) {
                    LOG_ERROR("Terminator::SwitchValue::Signed with wrapped type - " << ty);
                }
                int64_t switch_val;
                switch(ty.inner_type)
                {
                case RawType::I8:   switch_val = v.read_i8(0); break;
                case RawType::I16:  switch_val = v.read_i16(0); break;
                case RawType::I32:  switch_val = v.read_i32(0); break;
                case RawType::I64:  switch_val = v.read_i64(0); break;
                case RawType::I128: LOG_TODO("Terminator::SwitchValue::Signed with i128");
                case RawType::ISize:    switch_val = v.read_isize(0); break;
                default:
                    LOG_ERROR("Terminator::SwitchValue::Signed with unexpected type - " << ty);
                }

                auto it = ::std::find(vals.begin(), vals.end(), switch_val);
                if( it != vals.end() )
                {
                    auto idx = it - vals.begin();
                    LOG_TRACE("- " << switch_val << " matched arm " << idx);
                    cur_frame.bb_idx = te.targets.at(idx);
                }
                else
                {
                    LOG_TRACE("- " << switch_val << " not matched, taking default arm");
                    cur_frame.bb_idx = te.def_target;
                }
                }
            TU_ARMA(String, vals) {
                LOG_TODO("Terminator::SwitchValue (string) - " << ty << " " << v);
                }
            }
            }
        TU_ARM(bb.terminator, Call, te) {
            ::std::vector<Value>    sub_args; sub_args.reserve(te.args.size());
            for(const auto& a : te.args)
            {
                sub_args.push_back( state.param_to_value(a) );
                LOG_DEBUG("#" << (sub_args.size() - 1) << " " << sub_args.back());
            }
            Value   rv;
            if( te.fcn.is_Intrinsic() )
            {
                const auto& fe = te.fcn.as_Intrinsic();
                if( !this->call_intrinsic(rv, fe.name, fe.params, ::std::move(sub_args)) )
                {
                    // Early return, don't want to update stmt_idx yet
                    return false;
                }
            }
            else
            {
                RelocationPtr   fcn_alloc_ptr;
                const ::HIR::Path* fcn_p;
                if( te.fcn.is_Path() ) {
                    fcn_p = &te.fcn.as_Path();
                }
                else {
                    ::HIR::TypeRef ty;
                    auto v = state.get_value_and_type(te.fcn.as_Value(), ty);
                    LOG_DEBUG("> Indirect call " << v);
                    // TODO: Assert type
                    // TODO: Assert offset/content.
                    LOG_ASSERT(v.read_usize(0) == Allocation::PTR_BASE, "Function pointer value invalid - " << v);
                    fcn_alloc_ptr = v.get_relocation(0);
                    LOG_ASSERT(fcn_alloc_ptr, "Calling value with no relocation - " << v);
                    LOG_ASSERT(fcn_alloc_ptr.get_ty() == RelocationPtr::Ty::Function, "Calling value that isn't a function pointer");
                    fcn_p = &fcn_alloc_ptr.fcn();
                }

                LOG_DEBUG("Call " << *fcn_p);
                if( !this->call_path(rv, *fcn_p, ::std::move(sub_args)) )
                {
                    // Early return, don't want to update stmt_idx yet
                    LOG_DEBUG("- Non-immediate return, do not advance yet");
                    return false;
                }
            }
            // If a panic is in progress (in thread state), take the panic block instead
            if( m_thread.panic_active )
            {
                m_thread.panic_active = false;
                LOG_DEBUG("Panic into " << cur_frame.fcn->my_path);
                cur_frame.bb_idx = te.panic_block;
            }
            else
            {
                LOG_DEBUG(te.ret_val << " = " << rv << " (resume " << cur_frame.fcn->my_path << ")");
                state.write_lvalue(te.ret_val, rv);
                cur_frame.bb_idx = te.ret_block;
            }
            } break;
        }
        cur_frame.stmt_idx = 0;
    }

    return false;
}
bool InterpreterThread::pop_stack(Value& out_thread_result)
{
    assert( !this->m_stack.empty() );

    auto res_v = ::std::move(this->m_stack.back().ret);
    this->m_stack.pop_back();

    if( this->m_stack.empty() )
    {
        LOG_DEBUG("Thread complete, result " << res_v);
        out_thread_result = ::std::move(res_v);
        return true;
    }
    else
    {
        // Handle callback wrappers (e.g. for __rust_maybe_catch_panic, drop_value)
        if( this->m_stack.back().cb )
        {
            if( !this->m_stack.back().cb(res_v, ::std::move(res_v)) )
            {
                return false;
            }
            this->m_stack.pop_back();
            assert( !this->m_stack.empty() );
            assert( !this->m_stack.back().cb );
        }

        auto& cur_frame = this->m_stack.back();
        MirHelpers  state { *this, cur_frame };

        const auto& blk = cur_frame.fcn->m_mir.blocks.at( cur_frame.bb_idx );
        if( cur_frame.stmt_idx < blk.statements.size() )
        {
            assert( blk.statements[cur_frame.stmt_idx].is_Drop() );
            cur_frame.stmt_idx ++;
            LOG_DEBUG("DROP complete (resume " << cur_frame.fcn->my_path << ")");
        }
        else
        {
            assert( blk.terminator.is_Call() );
            const auto& te = blk.terminator.as_Call();

            LOG_DEBUG(te.ret_val << " = " << res_v << " (resume " << cur_frame.fcn->my_path << ")");

            cur_frame.stmt_idx = 0;
            // If a panic is in progress (in thread state), take the panic block instead
            if( m_thread.panic_active )
            {
                m_thread.panic_active = false;
                LOG_DEBUG("Panic into " << cur_frame.fcn->my_path);
                cur_frame.bb_idx = te.panic_block;
            }
            else
            {
                state.write_lvalue(te.ret_val, res_v);
                cur_frame.bb_idx = te.ret_block;
            }
        }

        return false;
    }
}

InterpreterThread::StackFrame::StackFrame(const Function& fcn, ::std::vector<Value> args):
    fcn(&fcn),
    ret( fcn.ret_ty == RawType::Unreachable ? Value() : Value(fcn.ret_ty) ),
    args( ::std::move(args) ),
    locals( ),
    drop_flags( fcn.m_mir.drop_flags ),
    bb_idx(0),
    stmt_idx(0)
{
    LOG_DEBUG("- Initializing " << fcn.m_mir.locals.size() << " locals");
    this->locals.reserve( fcn.m_mir.locals.size() );
    for(const auto& ty : fcn.m_mir.locals)
    {
        LOG_DEBUG("_" << (&ty - &fcn.m_mir.locals.front()) << ": " << ty);
        if( ty == RawType::Unreachable ) {
            // HACK: Locals can be !, but they can NEVER be accessed
            this->locals.push_back( Value() );
        }
        else {
            this->locals.push_back( Value(ty) );
        }
    }
}
bool InterpreterThread::call_path(Value& ret, const ::HIR::Path& path, ::std::vector<Value> args)
{
    // TODO: Support overriding certain functions
    {
        if( path == ::HIR::SimplePath { "std", { "sys", "imp", "c", "SetThreadStackGuarantee" } } )
        {
            ret = Value::new_i32(120);  //ERROR_CALL_NOT_IMPLEMENTED
            return true;
        }

        // - No guard page needed
        if( path == ::HIR::SimplePath { "std",  {"sys", "imp", "thread", "guard", "init" } }
         ||  path == ::HIR::SimplePath { "std",  {"sys", "unix", "thread", "guard", "init" } }
         )
        {
            ret = Value::with_size(16, false);
            ret.write_u64(0, 0);
            ret.write_u64(8, 0);
            return true;
        }

        // - No stack overflow handling needed
        if( path == ::HIR::SimplePath { "std", { "sys", "imp", "stack_overflow", "imp", "init" } } )
        {
            return true;
        }
    }

    const auto& fcn = m_modtree.get_function(path);

    if( fcn.external.link_name != "" )
    {
        // TODO: Search for a function with both code and this link name
        if(const auto* ext_fcn = m_modtree.get_ext_function(fcn.external.link_name.c_str()))
        {
            this->m_stack.push_back(StackFrame(*ext_fcn, ::std::move(args)));
            return false;
        }
        else
        {
            // External function!
            return this->call_extern(ret, fcn.external.link_name, fcn.external.link_abi, ::std::move(args));
        }
    }

    this->m_stack.push_back(StackFrame(fcn, ::std::move(args)));
    return false;
}

#ifdef _WIN32
const char* memrchr(const void* p, int c, size_t s) {
    const char* p2 = reinterpret_cast<const char*>(p);
    while( s > 0 )
    {
        s -= 1;
        if( p2[s] == c )
            return &p2[s];
    }
    return nullptr;
}
#else
extern "C" {
    long sysconf(int);
    ssize_t write(int, const void*, size_t);
}
#endif
bool InterpreterThread::call_extern(Value& rv, const ::std::string& link_name, const ::std::string& abi, ::std::vector<Value> args)
{
    struct FfiHelpers {
        static const char* read_cstr(const Value& v, size_t ptr_ofs, size_t* out_strlen=nullptr)
        {
            bool _is_mut;
            size_t  size;
            // Get the base pointer and allocation size (checking for at least one valid byte to start with)
            const char* ptr = reinterpret_cast<const char*>( v.read_pointer_unsafe(0, 1, /*out->*/ size, _is_mut) );
            size_t len = 0;
            // Seek until either out of space, or a NUL is found
            while(size -- && *ptr)
            {
                ptr ++;
                len ++;
            }
            if( out_strlen )
            {
                *out_strlen = len;
            }
            return reinterpret_cast<const char*>(v.read_pointer_const(0, len + 1));  // Final read will trigger an error if the NUL isn't there
        }
    };
    if( link_name == "__rust_allocate" || link_name == "__rust_alloc" )
    {
        static unsigned s_alloc_count = 0;

        auto alloc_idx = s_alloc_count ++;
        auto alloc_name = FMT_STRING("__rust_alloc#" << alloc_idx);
        auto size = args.at(0).read_usize(0);
        auto align = args.at(1).read_usize(0);
        LOG_DEBUG("__rust_allocate(size=" << size << ", align=" << align << "): name=" << alloc_name);
        auto alloc = Allocation::new_alloc(size, ::std::move(alloc_name));
        LOG_TRACE("- alloc=" << alloc << " (" << alloc->size() << " bytes)");
        auto rty = ::HIR::TypeRef(RawType::Unit).wrap( TypeWrapper::Ty::Pointer, 0 );

        // TODO: Use the alignment when making an allocation?
        rv = Value::new_pointer(rty, Allocation::PTR_BASE, RelocationPtr::new_alloc(::std::move(alloc)));
    }
    else if( link_name == "__rust_reallocate" || link_name == "__rust_realloc" )
    {
        LOG_ASSERT(args.at(0).allocation, "__rust_reallocate first argument doesn't have an allocation");
        auto alloc_ptr = args.at(0).get_relocation(0);
        auto ptr_ofs = args.at(0).read_usize(0);
        auto oldsize = args.at(1).read_usize(0);
        // NOTE: The ordering here depends on the rust version (1.19 has: old, new, align - 1.29 has: old, align, new)
        auto align = args.at(true /*1.29*/ ? 2 : 3).read_usize(0);
        auto newsize = args.at(true /*1.29*/ ? 3 : 2).read_usize(0);
        LOG_DEBUG("__rust_reallocate(ptr=" << alloc_ptr << ", oldsize=" << oldsize << ", newsize=" << newsize << ", align=" << align << ")");
        LOG_ASSERT(ptr_ofs == Allocation::PTR_BASE, "__rust_reallocate with offset pointer");

        LOG_ASSERT(alloc_ptr, "__rust_reallocate with no backing allocation attached to pointer");
        LOG_ASSERT(alloc_ptr.is_alloc(), "__rust_reallocate with no backing allocation attached to pointer");
        auto& alloc = alloc_ptr.alloc();
        // TODO: Check old size and alignment against allocation.
        alloc.resize(newsize);
        // TODO: Should this instead make a new allocation to catch use-after-free?
        rv = ::std::move(args.at(0));
    }
    else if( link_name == "__rust_deallocate" || link_name == "__rust_dealloc" )
    {
        LOG_ASSERT(args.at(0).allocation, "__rust_deallocate first argument doesn't have an allocation");
        auto alloc_ptr = args.at(0).get_relocation(0);
        auto ptr_ofs = args.at(0).read_usize(0);
        LOG_ASSERT(ptr_ofs == Allocation::PTR_BASE, "__rust_deallocate with offset pointer");
        LOG_DEBUG("__rust_deallocate(ptr=" << alloc_ptr << ")");

        LOG_ASSERT(alloc_ptr, "__rust_deallocate with no backing allocation attached to pointer");
        LOG_ASSERT(alloc_ptr.is_alloc(), "__rust_deallocate with no backing allocation attached to pointer");
        auto& alloc = alloc_ptr.alloc();
        alloc.mark_as_freed();
        // Just let it drop.
        rv = Value();
    }
    else if( link_name == "__rust_maybe_catch_panic" )
    {
        auto fcn_path = args.at(0).get_relocation(0).fcn();
        auto arg = args.at(1);
        auto data_ptr = args.at(2).read_pointer_valref_mut(0, POINTER_SIZE);
        auto vtable_ptr = args.at(3).read_pointer_valref_mut(0, POINTER_SIZE);

        ::std::vector<Value>    sub_args;
        sub_args.push_back( ::std::move(arg) );

        this->m_stack.push_back(StackFrame::make_wrapper([=](Value& out_rv, Value /*rv*/)->bool{
            out_rv = Value::new_u32(0);
            return true;
            }));

        // TODO: Catch the panic out of this.
        if( this->call_path(rv, fcn_path, ::std::move(sub_args)) )
        {
            bool v = this->pop_stack(rv);
            assert( v == false );
            return true;
        }
        else
        {
            return false;
        }
    }
    else if( link_name == "panic_impl" )
    {
        LOG_TODO("panic_impl");
    }
    else if( link_name == "__rust_start_panic" )
    {
        LOG_TODO("__rust_start_panic");
    }
    else if( link_name == "rust_begin_unwind" )
    {
        LOG_TODO("rust_begin_unwind");
    }
    // libunwind
    else if( link_name == "_Unwind_RaiseException" )
    {
        LOG_DEBUG("_Unwind_RaiseException(" << args.at(0) << ")");
        // Save the first argument in TLS, then return a status that indicates unwinding should commence.
        m_thread.panic_active = true;
        m_thread.panic_count += 1;
        m_thread.panic_value = ::std::move(args.at(0));
    }
    else if( link_name == "_Unwind_DeleteException" )
    {
        LOG_DEBUG("_Unwind_DeleteException(" << args.at(0) << ")");
    }
#ifdef _WIN32
    // WinAPI functions used by libstd
    else if( link_name == "AddVectoredExceptionHandler" )
    {
        LOG_DEBUG("Call `AddVectoredExceptionHandler` - Ignoring and returning non-null");
        rv = Value::new_usize(1);
    }
    else if( link_name == "GetModuleHandleW" )
    {
        LOG_ASSERT(args.at(0).allocation, "");
        const auto& tgt_alloc = args.at(0).get_relocation(0);
        const void* arg0 = (tgt_alloc ? tgt_alloc.alloc().data_ptr() : nullptr);
        //extern void* GetModuleHandleW(const void* s);
        if(arg0) {
            LOG_DEBUG("GetModuleHandleW(" << tgt_alloc.alloc() << ")");
        }
        else {
            LOG_DEBUG("GetModuleHandleW(NULL)");
        }

        auto ret = GetModuleHandleW(static_cast<LPCWSTR>(arg0));
        if(ret)
        {
            rv = Value::new_ffiptr(FFIPointer { "GetModuleHandleW", ret, 0 });
        }
        else
        {
            rv = Value(::HIR::TypeRef(RawType::USize));
            rv.create_allocation();
            rv.write_usize(0,0);
        }
    }
    else if( link_name == "GetProcAddress" )
    {
        const auto& handle_alloc = args.at(0).get_relocation(0);
        const auto& sym_alloc = args.at(1).get_relocation(0);

        // TODO: Ensure that first arg is a FFI pointer with offset+size of zero
        void* handle = handle_alloc.ffi().ptr_value;
        // TODO: Get either a FFI data pointer, or a inner data pointer
        const void* symname = sym_alloc.alloc().data_ptr();
        // TODO: Sanity check that it's a valid c string within its allocation
        LOG_DEBUG("FFI GetProcAddress(" << handle << ", \"" << static_cast<const char*>(symname) << "\")");

        auto ret = GetProcAddress(static_cast<HMODULE>(handle), static_cast<LPCSTR>(symname));

        if( ret )
        {
            rv = Value::new_ffiptr(FFIPointer { "GetProcAddress", ret, 0 });
        }
        else
        {
            rv = Value(::HIR::TypeRef(RawType::USize));
            rv.create_allocation();
            rv.write_usize(0,0);
        }
    }
#else
    // POSIX
    else if( link_name == "write" )
    {
        auto fd = args.at(0).read_i32(0);
        auto count = args.at(2).read_isize(0);
        const auto* buf = args.at(1).read_pointer_const(0, count);

        ssize_t val = write(fd, buf, count);

        rv = Value::new_isize(val);
    }
    else if( link_name == "read" )
    {
        auto fd = args.at(0).read_i32(0);
        auto count = args.at(2).read_isize(0);
        auto buf_vr = args.at(1).read_pointer_valref_mut(0, count);

        LOG_DEBUG("read(" << fd << ", " << buf_vr.data_ptr_mut() << ", " << count << ")");
        ssize_t val = read(fd, buf_vr.data_ptr_mut(), count);
        LOG_DEBUG("= " << val);

        if( val > 0 )
        {
            buf_vr.mark_bytes_valid(0, val);
        }

        rv = Value::new_isize(val);
    }
    else if( link_name == "close" )
    {
        auto fd = args.at(0).read_i32(0);
        LOG_DEBUG("close(" << fd << ")");
        // TODO: Ensure that this FD is from the set known by the FFI layer
        close(fd);
    }
    else if( link_name == "isatty" )
    {
        auto fd = args.at(0).read_i32(0);
        LOG_DEBUG("isatty(" << fd << ")");
        int rv_i = isatty(fd);
        LOG_DEBUG("= " << rv_i);
        rv = Value::new_i32(rv_i);
    }
    else if( link_name == "fcntl" )
    {
        // `fcntl` has custom handling for the third argument, as some are pointers
        int fd = args.at(0).read_i32(0);
        int command = args.at(1).read_i32(0);

        int rv_i;
        const char* name;
        switch(command)
        {
        // - No argument
        case F_GETFD: name = "F_GETFD"; if(0)
            ;
            {
                LOG_DEBUG("fcntl(" << fd << ", " << name << ")");
                rv_i = fcntl(fd, command);
            } break;
        // - Integer arguments
        case F_DUPFD: name = "F_DUPFD"; if(0)
        case F_DUPFD_CLOEXEC: name = "F_DUPFD_CLOEXEC"; if(0)
        case F_SETFD: name = "F_SETFD"; if(0)
            ;
            {
                int arg = args.at(2).read_i32(0);
                LOG_DEBUG("fcntl(" << fd << ", " << name << ", " << arg << ")");
                rv_i = fcntl(fd, command, arg);
            } break;
        default:
            if( args.size() > 2 )
            {
                LOG_TODO("fnctl(..., " << command << ", " << args[2] << ")");
            }
            else
            {
                LOG_TODO("fnctl(..., " << command << ")");
            }
        }

        LOG_DEBUG("= " << rv_i);
        rv = Value(::HIR::TypeRef(RawType::I32));
        rv.write_i32(0, rv_i);
    }
    else if( link_name == "prctl" )
    {
        auto option = args.at(0).read_i32(0);
        int rv_i;
        switch(option)
        {
        case 15: {   // PR_SET_NAME - set thread name
            auto name = FfiHelpers::read_cstr(args.at(1), 0);
            LOG_DEBUG("prctl(PR_SET_NAME, \"" << name << "\"");
            rv_i = 0;
            } break;
        default:
            LOG_TODO("prctl(" << option << ", ...");
        }
        rv = Value::new_i32(rv_i);
    }
    else if( link_name == "sysconf" )
    {
        auto name = args.at(0).read_i32(0);
        LOG_DEBUG("FFI sysconf(" << name << ")");

        long val = sysconf(name);

        rv = Value::new_usize(val);
    }
    else if( link_name == "pthread_self" )
    {
        rv = Value::new_i32(0);
    }
    else if( link_name == "pthread_mutex_init" || link_name == "pthread_mutex_lock" || link_name == "pthread_mutex_unlock" || link_name == "pthread_mutex_destroy" )
    {
        rv = Value::new_i32(0);
    }
    else if( link_name == "pthread_rwlock_rdlock" )
    {
        rv = Value::new_i32(0);
    }
    else if( link_name == "pthread_rwlock_unlock" )
    {
        // TODO: Check that this thread holds the lock?
        rv = Value::new_i32(0);
    }
    else if( link_name == "pthread_mutexattr_init" || link_name == "pthread_mutexattr_settype" || link_name == "pthread_mutexattr_destroy" )
    {
        rv = Value::new_i32(0);
    }
    else if( link_name == "pthread_condattr_init" || link_name == "pthread_condattr_destroy" || link_name == "pthread_condattr_setclock" )
    {
        rv = Value::new_i32(0);
    }
    else if( link_name == "pthread_attr_init" || link_name == "pthread_attr_destroy" || link_name == "pthread_getattr_np" )
    {
        rv = Value::new_i32(0);
    }
    else if( link_name == "pthread_attr_setstacksize" )
    {
        // Lie and return succeess
        rv = Value::new_i32(0);
    }
    else if( link_name == "pthread_attr_getguardsize" )
    {
        const auto attr_p = args.at(0).read_pointer_const(0, 1);
        auto out_size = args.at(1).deref(0, HIR::TypeRef(RawType::USize));

        out_size.m_alloc.alloc().write_usize(out_size.m_offset, 0x1000);

        rv = Value::new_i32(0);
    }
    else if( link_name == "pthread_attr_getstack" )
    {
        const auto attr_p = args.at(0).read_pointer_const(0, 1);
        auto out_ptr = args.at(2).deref(0, HIR::TypeRef(RawType::USize));
        auto out_size = args.at(2).deref(0, HIR::TypeRef(RawType::USize));

        out_size.m_alloc.alloc().write_usize(out_size.m_offset, 0x4000);

        rv = Value::new_i32(0);
    }
    else if( link_name == "pthread_create" )
    {
        auto thread_handle_out = args.at(0).read_pointer_valref_mut(0, sizeof(pthread_t));
        auto attrs = args.at(1).read_pointer_const(0, sizeof(pthread_attr_t));
        auto fcn_path = args.at(2).get_relocation(0).fcn();
        LOG_ASSERT(args.at(2).read_usize(0) == Allocation::PTR_BASE, "");
        auto arg = args.at(3);
        LOG_NOTICE("TODO: pthread_create(" << thread_handle_out << ", " << attrs << ", " << fcn_path << ", " << arg << ")");
        // TODO: Create a new interpreter context with this thread, use co-operative scheduling
        // HACK: Just run inline
        if( true )
        {
            auto tls = ::std::move(m_thread.tls_values);
            this->m_stack.push_back(StackFrame::make_wrapper([=](Value& out_rv, Value /*rv*/)mutable ->bool {
                out_rv = Value::new_i32(0);
                m_thread.tls_values = ::std::move(tls);
                return true;
                }));

            // TODO: Catch the panic out of this.
            if( this->call_path(rv, fcn_path, { ::std::move(arg) }) )
            {
                bool v = this->pop_stack(rv);
                assert( v == false );
                return true;
            }
            else
            {
                return false;
            }
        }
        else {
            //this->m_parent.create_thread(fcn_path, arg);
            rv = Value::new_i32(EPERM);
        }
    }
    else if( link_name == "pthread_cond_init" || link_name == "pthread_cond_destroy" )
    {
        rv = Value::new_i32(0);
    }
    else if( link_name == "pthread_key_create" )
    {
        auto key_ref = args.at(0).read_pointer_valref_mut(0, 4);

        auto key = ThreadState::s_next_tls_key ++;
        key_ref.m_alloc.alloc().write_u32( key_ref.m_offset, key );

        rv = Value::new_i32(0);
    }
    else if( link_name == "pthread_getspecific" )
    {
        auto key = args.at(0).read_u32(0);

        // Get a pointer-sized value from storage
        if( key < m_thread.tls_values.size() )
        {
            const auto& e = m_thread.tls_values[key];
            rv = Value::new_usize(e.first);
            rv.create_allocation();
            if( e.second )
            {
                rv.allocation->set_reloc(0, POINTER_SIZE, e.second);
            }
        }
        else
        {
            // Return zero until populated
            rv = Value::new_usize(0);
        }
    }
    else if( link_name == "pthread_setspecific" )
    {
        auto key = args.at(0).read_u32(0);
        auto v = args.at(1).read_u64(0);
        auto v_reloc = args.at(1).get_relocation(0);

        // Store a pointer-sized value in storage
        if( key >= m_thread.tls_values.size() ) {
            m_thread.tls_values.resize(key+1);
        }
        m_thread.tls_values[key] = ::std::make_pair(v, v_reloc);

        rv = Value::new_i32(0);
    }
    else if( link_name == "pthread_key_delete" )
    {
        rv = Value::new_i32(0);
    }
    // - Time
    else if( link_name == "clock_gettime" )
    {
        // int clock_gettime(clockid_t clk_id, struct timespec *tp);
        auto clk_id = args.at(0).read_u32(0);
        auto tp_vr = args.at(1).read_pointer_valref_mut(0, sizeof(struct timespec));

        LOG_DEBUG("clock_gettime(" << clk_id << ", " << tp_vr);
        int rv_i = clock_gettime(clk_id, reinterpret_cast<struct timespec*>(tp_vr.data_ptr_mut()));
        if(rv_i == 0)
            tp_vr.mark_bytes_valid(0, tp_vr.m_size);
        LOG_DEBUG("= " << rv_i << " (" << tp_vr << ")");
        rv = Value::new_i32(rv_i);
    }
    // - Linux extensions
    else if( link_name == "open64" )
    {
        const auto* path = FfiHelpers::read_cstr(args.at(0), 0);
        auto flags = args.at(1).read_i32(0);
        auto mode = (args.size() > 2 ? args.at(2).read_i32(0) : 0);

        LOG_DEBUG("open64(\"" << path << "\", " << flags << ")");
        int rv_i = open(path, flags, mode);
        LOG_DEBUG("= " << rv_i);

        rv = Value(::HIR::TypeRef(RawType::I32));
        rv.write_i32(0, rv_i);
    }
    else if( link_name == "stat64" )
    {
        const auto* path = FfiHelpers::read_cstr(args.at(0), 0);
        auto outbuf_vr = args.at(1).read_pointer_valref_mut(0, sizeof(struct stat));

        LOG_DEBUG("stat64(\"" << path << "\", " << outbuf_vr << ")");
        int rv_i = stat(path, reinterpret_cast<struct stat*>(outbuf_vr.data_ptr_mut()));
        LOG_DEBUG("= " << rv_i);

        if( rv_i == 0 )
        {
            // TODO: Mark the buffer as valid?
        }

        rv = Value(::HIR::TypeRef(RawType::I32));
        rv.write_i32(0, rv_i);
    }
    else if( link_name == "__errno_location" )
    {
        rv = Value::new_ffiptr(FFIPointer::new_const_bytes("errno", &errno, sizeof(errno)));
    }
    else if( link_name == "syscall" )
    {
        auto num = args.at(0).read_u32(0);

        LOG_DEBUG("syscall(" << num << ", ...) - hack return ENOSYS");
        errno = ENOSYS;
        rv = Value::new_i64(-1);
    }
    else if( link_name == "dlsym" )
    {
        auto handle = args.at(0).read_usize(0);
        const char* name = FfiHelpers::read_cstr(args.at(1), 0);

        LOG_DEBUG("dlsym(0x" << ::std::hex << handle << ", '" << name << "')");
        LOG_NOTICE("dlsym stubbed to zero");
        rv = Value::new_usize(0);
    }
#endif
    // std C
    else if( link_name == "signal" )
    {
        LOG_DEBUG("Call `signal` - Ignoring and returning SIG_IGN");
        rv = Value(::HIR::TypeRef(RawType::USize));
        rv.write_usize(0, 1);
    }
    else if( link_name == "sigaction" )
    {
        rv = Value::new_i32(-1);
    }
    else if( link_name == "sigaltstack" )   // POSIX: Set alternate signal stack
    {
        rv = Value::new_i32(-1);
    }
    // - `void *memchr(const void *s, int c, size_t n);`
    else if( link_name == "memchr" )
    {
        auto ptr_alloc = args.at(0).get_relocation(0);
        auto c = args.at(1).read_i32(0);
        auto n = args.at(2).read_usize(0);
        const void* ptr = args.at(0).read_pointer_const(0, n);

        const void* ret = memchr(ptr, c, n);

        rv = Value(::HIR::TypeRef(RawType::USize));
        rv.create_allocation();
        if( ret )
        {
            rv.write_usize(0, args.at(0).read_usize(0) + ( static_cast<const uint8_t*>(ret) - static_cast<const uint8_t*>(ptr) ));
            rv.allocation->relocations.push_back({ 0, ptr_alloc });
        }
        else
        {
            rv.write_usize(0, 0);
        }
    }
    else if( link_name == "memrchr" )
    {
        auto ptr_alloc = args.at(0).get_relocation(0);
        auto c = args.at(1).read_i32(0);
        auto n = args.at(2).read_usize(0);
        const void* ptr = args.at(0).read_pointer_const(0, n);

        const void* ret = memrchr(ptr, c, n);

        rv = Value(::HIR::TypeRef(RawType::USize));
        rv.create_allocation();
        if( ret )
        {
            rv.write_usize(0, args.at(0).read_usize(0) + ( static_cast<const uint8_t*>(ret) - static_cast<const uint8_t*>(ptr) ));
            rv.allocation->relocations.push_back({ 0, ptr_alloc });
        }
        else
        {
            rv.write_usize(0, 0);
        }
    }
    else if( link_name == "strlen" )
    {
        // strlen - custom implementation to ensure validity
        size_t len = 0;
        FfiHelpers::read_cstr(args.at(0), 0, &len);

        //rv = Value::new_usize(len);
        rv = Value(::HIR::TypeRef(RawType::USize));
        rv.write_usize(0, len);
    }
    else if( link_name == "getenv" )
    {
        const auto* name = FfiHelpers::read_cstr(args.at(0), 0);
        LOG_DEBUG("getenv(\"" << name << "\")");
        const auto* ret_ptr = getenv(name);
        if( ret_ptr )
        {
            LOG_DEBUG("= \"" << ret_ptr << "\"");
            rv = Value::new_ffiptr(FFIPointer::new_const_bytes("getenv", ret_ptr, strlen(ret_ptr)+1));
        }
        else
        {
            LOG_DEBUG("= NULL");
            rv = Value(::HIR::TypeRef(RawType::USize));
            rv.create_allocation();
            rv.write_usize(0,0);
        }
    }
    else if( link_name == "setenv" )
    {
        LOG_TODO("Allow `setenv` without incurring thread unsafety");
    }
    // Allocators!
    else
    {
        LOG_TODO("Call external function " << link_name);
    }
    return true;
}

bool InterpreterThread::call_intrinsic(Value& rv, const RcString& name, const ::HIR::PathParams& ty_params, ::std::vector<Value> args)
{
    TRACE_FUNCTION_R(name, rv);
    for(const auto& a : args)
        LOG_DEBUG("#" << (&a - args.data()) << ": " << a);
    if( name == "type_id" )
    {
        const auto& ty_T = ty_params.tys.at(0);
        static ::std::vector<HIR::TypeRef>  type_ids;
        auto it = ::std::find(type_ids.begin(), type_ids.end(), ty_T);
        if( it == type_ids.end() )
        {
            it = type_ids.insert(it, ty_T);
        }

        rv = Value::with_size(POINTER_SIZE, false);
        rv.write_usize(0, it - type_ids.begin());
    }
    else if( name == "type_name" )
    {
        const auto& ty_T = ty_params.tys.at(0);

        static ::std::map<HIR::TypeRef, ::std::string>  s_type_names;
        auto it = s_type_names.find(ty_T);
        if( it == s_type_names.end() )
        {
            it = s_type_names.insert( ::std::make_pair(ty_T, FMT_STRING(ty_T)) ).first;
        }

        rv = Value::with_size(2*POINTER_SIZE, /*needs_alloc=*/true);
        rv.write_ptr(0*POINTER_SIZE, Allocation::PTR_BASE, RelocationPtr::new_string(&it->second));
        rv.write_usize(1*POINTER_SIZE, 0);
    }
    else if( name == "discriminant_value" )
    {
        const auto& ty = ty_params.tys.at(0);
        ValueRef val = args.at(0).deref(0, ty);

        size_t fallback = SIZE_MAX;
        size_t found_index = SIZE_MAX;
        assert(ty.composite_type);
        for(size_t i = 0; i < ty.composite_type->variants.size(); i ++)
        {
            const auto& var = ty.composite_type->variants[i];
            if( var.tag_data.size() == 0 )
            {
                // Only seen in Option<NonNull>
                assert(fallback == SIZE_MAX);
                fallback = i;
            }
            else
            {
                // Get offset to the tag
                ::HIR::TypeRef  tag_ty;
                size_t tag_ofs = ty.get_field_ofs(var.base_field, var.field_path, tag_ty);
                // Compare
                if( val.compare(tag_ofs, var.tag_data.data(), var.tag_data.size()) == 0 )
                {
                    found_index = i;
                    break ;
                }
            }
        }

        if( found_index == SIZE_MAX )
        {
            LOG_ASSERT(fallback != SIZE_MAX, "Can't find variant of " << ty << " for " << val);
            found_index = fallback;
        }

        rv = Value::new_usize(found_index);
    }
    else if( name == "atomic_fence" || name == "atomic_fence_acq" )
    {
        rv = Value();
    }
    else if( name == "atomic_store" || name == "atomic_store_relaxed" || name == "atomic_store_rel" )
    {
        auto& ptr_val = args.at(0);
        auto& data_val = args.at(1);

        LOG_ASSERT(ptr_val.size() == POINTER_SIZE, "atomic_store of a value that isn't a pointer-sized value");

        // There MUST be a relocation at this point with a valid allocation.
        auto alloc = ptr_val.get_relocation(0);
        LOG_ASSERT(alloc, "Deref of a value with no relocation");

        // TODO: Atomic side of this?
        size_t ofs = ptr_val.read_usize(0) - Allocation::PTR_BASE;
        alloc.alloc().write_value(ofs, ::std::move(data_val));
    }
    else if( name == "atomic_load" || name == "atomic_load_relaxed" || name == "atomic_load_acq" )
    {
        auto& ptr_val = args.at(0);
        LOG_ASSERT(ptr_val.size() == POINTER_SIZE, "atomic_load of a value that isn't a pointer-sized value");

        // There MUST be a relocation at this point with a valid allocation.
        auto alloc = ptr_val.get_relocation(0);
        LOG_ASSERT(alloc, "Deref of a value with no relocation");
        // TODO: Atomic lock the allocation.

        size_t ofs = ptr_val.read_usize(0) - Allocation::PTR_BASE;
        const auto& ty = ty_params.tys.at(0);

        rv = alloc.alloc().read_value(ofs, ty.get_size());
    }
    else if( name == "atomic_xadd" || name == "atomic_xadd_relaxed" )
    {
        const auto& ty_T = ty_params.tys.at(0);
        auto ptr_ofs = args.at(0).read_usize(0) - Allocation::PTR_BASE;
        auto ptr_alloc = args.at(0).get_relocation(0);
        auto v = args.at(1).read_value(0, ty_T.get_size());

        // TODO: Atomic lock the allocation.
        if( !ptr_alloc || !ptr_alloc.is_alloc() ) {
            LOG_ERROR("atomic pointer has no allocation");
        }

        // - Result is the original value
        rv = ptr_alloc.alloc().read_value(ptr_ofs, ty_T.get_size());

        auto val_l = PrimitiveValueVirt::from_value(ty_T, rv);
        const auto val_r = PrimitiveValueVirt::from_value(ty_T, v);
        val_l.get().add( val_r.get() );

        val_l.get().write_to_value( ptr_alloc.alloc(), ptr_ofs );
    }
    else if( name == "atomic_xsub" || name == "atomic_xsub_relaxed" || name == "atomic_xsub_rel" )
    {
        const auto& ty_T = ty_params.tys.at(0);
        auto ptr_ofs = args.at(0).read_usize(0) - Allocation::PTR_BASE;
        auto ptr_alloc = args.at(0).get_relocation(0);
        auto v = args.at(1).read_value(0, ty_T.get_size());

        // TODO: Atomic lock the allocation.
        if( !ptr_alloc || !ptr_alloc.is_alloc() ) {
            LOG_ERROR("atomic pointer has no allocation");
        }

        // - Result is the original value
        rv = ptr_alloc.alloc().read_value(ptr_ofs, ty_T.get_size());

        auto val_l = PrimitiveValueVirt::from_value(ty_T, rv);
        const auto val_r = PrimitiveValueVirt::from_value(ty_T, v);
        val_l.get().subtract( val_r.get() );

        val_l.get().write_to_value( ptr_alloc.alloc(), ptr_ofs );
    }
    else if( name == "atomic_xchg" || name == "atomic_xchg_acqrel" )
    {
        const auto& ty_T = ty_params.tys.at(0);
        auto data_ref = args.at(0).read_pointer_valref_mut(0, ty_T.get_size());
        const auto& new_v = args.at(1);

        rv = data_ref.read_value(0, new_v.size());
        data_ref.m_alloc.alloc().write_value( data_ref.m_offset, new_v );
    }
    else if( name == "atomic_cxchg" )
    {
        const auto& ty_T = ty_params.tys.at(0);
        // TODO: Get a ValueRef to the target location
        auto data_ref = args.at(0).read_pointer_valref_mut(0, ty_T.get_size());
        const auto& old_v = args.at(1);
        const auto& new_v = args.at(2);
        rv = Value::with_size( ty_T.get_size() + 1, false );
        rv.write_value(0, data_ref.read_value(0, old_v.size()));
        LOG_DEBUG("> *ptr = " << data_ref);
        if( data_ref.compare(0, old_v.data_ptr(), old_v.size()) == true ) {
            data_ref.m_alloc.alloc().write_value( data_ref.m_offset, new_v );
            rv.write_u8( old_v.size(), 1 );
        }
        else {
            rv.write_u8( old_v.size(), 0 );
        }
    }
    else if( name == "transmute" )
    {
        // Transmute requires the same size, so just copying the value works
        rv = ::std::move(args.at(0));
    }
    else if( name == "assume" )
    {
        // Assume is a no-op which returns unit
    }
    else if( name == "offset" )
    {
        auto ptr_alloc = args.at(0).get_relocation(0);
        auto ptr_ofs = args.at(0).read_usize(0);
        LOG_ASSERT(ptr_ofs >= Allocation::PTR_BASE, "`offset` with invalid pointer - " << args.at(0));
        ptr_ofs -= Allocation::PTR_BASE;
        auto& ofs_val = args.at(1);

        auto delta_counts = ofs_val.read_usize(0);
        auto new_ofs = ptr_ofs + delta_counts * ty_params.tys.at(0).get_size();
        if(POINTER_SIZE != 8) {
            new_ofs &= 0xFFFFFFFF;
        }

        rv = ::std::move(args.at(0));
        rv.write_ptr(0, Allocation::PTR_BASE + new_ofs, ptr_alloc);
    }
    // effectively ptr::write
    else if( name == "move_val_init" )
    {
        auto& ptr_val = args.at(0);
        auto& data_val = args.at(1);

        // There MUST be a relocation at this point with a valid allocation.
        // - TODO: What about FFI? (can't be a string or function though)
        auto dst_vr = ptr_val.deref(0, ty_params.tys.at(0));
        LOG_ASSERT(dst_vr.m_alloc, "Deref didn't yeild an allocation (error?)");
        LOG_ASSERT(dst_vr.m_alloc.is_alloc(), "Deref didn't yield an allocation");

        dst_vr.m_alloc.alloc().write_value(dst_vr.m_offset, ::std::move(data_val));
    }
    else if( name == "uninit" )
    {
        rv = Value(ty_params.tys.at(0));
    }
    else if( name == "init" )
    {
        rv = Value(ty_params.tys.at(0));
        rv.mark_bytes_valid(0, rv.size());
    }
    else if( name == "write_bytes" )
    {
        auto& dst_ptr_v = args.at(0);
        auto byte = args.at(1).read_u8(0);
        auto count = args.at(2).read_usize(0);
        auto bytes = count * ty_params.tys.at(0).get_size();

        LOG_DEBUG("'write_bytes'(" << dst_ptr_v << ", " << (int)byte << ", " << count << "): bytes=" << bytes);

        if( count > 0 )
        {
            auto dst_vr = dst_ptr_v.read_pointer_valref_mut(0, bytes);
            memset(dst_vr.data_ptr_mut(), byte, bytes);
            dst_vr.mark_bytes_valid(0, bytes);
        }
    }
    // - Unsized stuff
    else if( name == "size_of_val" )
    {
        auto& val = args.at(0);
        const auto& ty = ty_params.tys.at(0);
        rv = Value(::HIR::TypeRef(RawType::USize));
        // Get unsized type somehow.
        // - _HAS_ to be the last type, so that makes it easier
        size_t fixed_size = 0;
        if( const auto* ity = ty.get_unsized_type(fixed_size) )
        {
            const auto meta_ty = ty.get_meta_type();
            LOG_DEBUG("size_of_val - " << ty << " ity=" << *ity << " meta_ty=" << meta_ty << " fixed_size=" << fixed_size);
            size_t flex_size = 0;
            if( const auto* w = ity->get_wrapper() )
            {
                LOG_ASSERT(w->type == TypeWrapper::Ty::Slice, "size_of_val on wrapped type that isn't a slice - " << *ity);
                size_t item_size = ity->get_inner().get_size();
                size_t item_count = val.read_usize(POINTER_SIZE);
                flex_size = item_count * item_size;
                LOG_DEBUG("> item_size=" << item_size << " item_count=" << item_count << " flex_size=" << flex_size);
            }
            else if( ity->inner_type == RawType::Str )
            {
                flex_size = val.read_usize(POINTER_SIZE);
            }
            else if( ity->inner_type == RawType::TraitObject )
            {
                auto vtable_ty = meta_ty.get_inner();
                LOG_DEBUG("> vtable_ty = " << vtable_ty << " (size= " << vtable_ty.get_size() << ")");
                auto vtable = val.deref(POINTER_SIZE, vtable_ty);
                LOG_DEBUG("> vtable = " << vtable);
                auto size = vtable.read_usize(1*POINTER_SIZE);
                flex_size = size;
            }
            else
            {
                LOG_BUG("Inner unsized type unknown - " << *ity);
            }

            rv.write_usize(0, fixed_size + flex_size);
        }
        else
        {
            rv.write_usize(0, ty.get_size());
        }
    }
    else if( name == "min_align_of_val" )
    {
        /*const*/ auto& val = args.at(0);
        const auto& ty = ty_params.tys.at(0);
        rv = Value(::HIR::TypeRef(RawType::USize));
        size_t fixed_size = 0;  // unused
        size_t flex_align = 0;
        if( const auto* ity = ty.get_unsized_type(fixed_size) )
        {
            if( const auto* w = ity->get_wrapper() )
            {
                LOG_ASSERT(w->type == TypeWrapper::Ty::Slice, "align_of_val on wrapped type that isn't a slice - " << *ity);
                flex_align = ity->get_inner().get_align();
            }
            else if( ity->inner_type == RawType::Str )
            {
                flex_align = 1;
            }
            else if( ity->inner_type == RawType::TraitObject )
            {
                const auto meta_ty = ty.get_meta_type();
                auto vtable_ty = meta_ty.get_inner();
                LOG_DEBUG("> vtable_ty = " << vtable_ty << " (size= " << vtable_ty.get_size() << ")");
                auto vtable = val.deref(POINTER_SIZE, vtable_ty);
                LOG_DEBUG("> vtable = " << vtable);
                flex_align = vtable.read_usize(2*POINTER_SIZE);
            }
            else
            {
                LOG_BUG("Inner unsized type unknown - " << *ity);
            }
        }
        rv.write_usize(0, ::std::max( ty.get_align(), flex_align ));
    }
    else if( name == "drop_in_place" )
    {
        auto& val = args.at(0);
        const auto& ty = ty_params.tys.at(0);
        return drop_value(val, ty);
    }
    else if( name == "try" )
    {
        auto fcn_path = args.at(0).get_relocation(0).fcn();
        auto arg = args.at(1);
        auto out_panic_value = args.at(2).read_pointer_valref_mut(0, POINTER_SIZE);

        ::std::vector<Value>    sub_args;
        sub_args.push_back( ::std::move(arg) );

        this->m_stack.push_back(StackFrame::make_wrapper([=](Value& out_rv, Value /*rv*/)mutable->bool{
            if( m_thread.panic_active )
            {
                assert(m_thread.panic_count > 0);
                m_thread.panic_active = false;
                m_thread.panic_count --;
                LOG_ASSERT(m_thread.panic_value.size() == out_panic_value.m_size, "Panic value " << m_thread.panic_value << " doesn't fit in " << out_panic_value);
                out_panic_value.m_alloc.alloc().write_value( out_panic_value.m_offset, ::std::move(m_thread.panic_value) );
                out_rv = Value::new_u32(1);
                return true;
            }
            else
            {
                LOG_ASSERT(m_thread.panic_count == 0, "Panic count non-zero, but previous function returned non-panic");
                out_rv = Value::new_u32(0);
                return true;
            }
            }));

        // TODO: Catch the panic out of this.
        if( this->call_path(rv, fcn_path, ::std::move(sub_args)) )
        {
            bool v = this->pop_stack(rv);
            assert( v == false );
            return true;
        }
        else
        {
            return false;
        }
    }
    // ----------------------------------------------------------------
    // Checked arithmatic
    else if( name == "add_with_overflow" )
    {
        const auto& ty = ty_params.tys.at(0);

        auto lhs = PrimitiveValueVirt::from_value(ty, args.at(0));
        auto rhs = PrimitiveValueVirt::from_value(ty, args.at(1));
        bool didnt_overflow = lhs.get().add( rhs.get() );

        // Get return type - a tuple of `(T, bool,)`
        ::HIR::GenericPath  gp;
        gp.m_params.tys.push_back(ty);
        gp.m_params.tys.push_back(::HIR::TypeRef { RawType::Bool });
        const auto& dty = m_modtree.get_composite(gp);

        rv = Value(::HIR::TypeRef(&dty));
        lhs.get().write_to_value(rv, dty.fields[0].first);
        rv.write_u8( dty.fields[1].first, didnt_overflow ? 0 : 1 ); // Returns true if overflow happened
    }
    else if( name == "sub_with_overflow" )
    {
        const auto& ty = ty_params.tys.at(0);

        auto lhs = PrimitiveValueVirt::from_value(ty, args.at(0));
        auto rhs = PrimitiveValueVirt::from_value(ty, args.at(1));
        bool didnt_overflow = lhs.get().subtract( rhs.get() );

        // Get return type - a tuple of `(T, bool,)`
        ::HIR::GenericPath  gp;
        gp.m_params.tys.push_back(ty);
        gp.m_params.tys.push_back(::HIR::TypeRef { RawType::Bool });
        const auto& dty = m_modtree.get_composite(gp);

        rv = Value(::HIR::TypeRef(&dty));
        lhs.get().write_to_value(rv, dty.fields[0].first);
        rv.write_u8( dty.fields[1].first, didnt_overflow ? 0 : 1 ); // Returns true if overflow happened
    }
    else if( name == "mul_with_overflow" )
    {
        const auto& ty = ty_params.tys.at(0);

        auto lhs = PrimitiveValueVirt::from_value(ty, args.at(0));
        auto rhs = PrimitiveValueVirt::from_value(ty, args.at(1));
        bool didnt_overflow = lhs.get().multiply( rhs.get() );

        // Get return type - a tuple of `(T, bool,)`
        ::HIR::GenericPath  gp;
        gp.m_params.tys.push_back(ty);
        gp.m_params.tys.push_back(::HIR::TypeRef { RawType::Bool });
        const auto& dty = m_modtree.get_composite(gp);

        rv = Value(::HIR::TypeRef(&dty));
        lhs.get().write_to_value(rv, dty.fields[0].first);
        rv.write_u8( dty.fields[1].first, didnt_overflow ? 0 : 1 ); // Returns true if overflow happened
    }
    // - "exact_div" :: Normal divide, but UB if not an exact multiple
    else if( name == "exact_div" )
    {
        const auto& ty = ty_params.tys.at(0);

        auto lhs = PrimitiveValueVirt::from_value(ty, args.at(0));
        auto rhs = PrimitiveValueVirt::from_value(ty, args.at(1));

        LOG_ASSERT(!rhs.get().is_zero(), "`exact_div` with zero divisor: " << args.at(0) << " / " << args.at(1));
        auto rem = lhs;
        rem.get().modulo( rhs.get() );
        LOG_ASSERT(rem.get().is_zero(), "`exact_div` with yielded non-zero remainder: " << args.at(0) << " / " << args.at(1));
        bool didnt_overflow = lhs.get().divide( rhs.get() );
        LOG_ASSERT(didnt_overflow, "`exact_div` failed for unknown reason: " << args.at(0) << " /" << args.at(1));

        rv = Value(ty);
        lhs.get().write_to_value(rv, 0);
    }
    // Overflowing artithmatic
    else if( name == "overflowing_sub" )
    {
        const auto& ty = ty_params.tys.at(0);

        auto lhs = PrimitiveValueVirt::from_value(ty, args.at(0));
        auto rhs = PrimitiveValueVirt::from_value(ty, args.at(1));
        lhs.get().subtract( rhs.get() );
        // TODO: Overflowing part

        rv = Value(ty);
        lhs.get().write_to_value(rv, 0);
    }
    else if( name == "overflowing_add" )
    {
        const auto& ty = ty_params.tys.at(0);

        auto lhs = PrimitiveValueVirt::from_value(ty, args.at(0));
        auto rhs = PrimitiveValueVirt::from_value(ty, args.at(1));
        lhs.get().add( rhs.get() );

        rv = Value(ty);
        lhs.get().write_to_value(rv, 0);
    }
    // ----------------------------------------------------------------
    // memcpy
    else if( name == "copy_nonoverlapping" )
    {
        //auto src_ofs = args.at(0).read_usize(0);
        //auto src_alloc = args.at(0).get_relocation(0);
        //auto dst_ofs = args.at(1).read_usize(0);
        //auto dst_alloc = args.at(1).get_relocation(0);
        size_t ent_count = args.at(2).read_usize(0);
        size_t ent_size = ty_params.tys.at(0).get_size();
        auto byte_count = ent_count * ent_size;
        LOG_DEBUG("`copy_nonoverlapping`: byte_count=" << byte_count);

        // A count of zero doesn't need to do any of the checks (TODO: Validate this rule)
        if( byte_count > 0 )
        {
            auto src_vr = args.at(0).read_pointer_valref_mut(0, byte_count);
            auto dst_vr = args.at(1).read_pointer_valref_mut(0, byte_count);

            auto& dst_alloc = dst_vr.m_alloc;
            LOG_ASSERT(dst_alloc, "Destination of copy* must be a memory allocation");
            LOG_ASSERT(dst_alloc.is_alloc(), "Destination of copy* must be a memory allocation");

            // TODO: is this inefficient?
            auto src_val = src_vr.read_value(0, byte_count);
            LOG_DEBUG("src_val = " << src_val);
            dst_alloc.alloc().write_value(dst_vr.m_offset, ::std::move(src_val));
        }
    }
    else
    {
        LOG_TODO("Call intrinsic \"" << name << "\"");
    }
    return true;
}

// TODO: Use a ValueRef instead?
bool InterpreterThread::drop_value(Value ptr, const ::HIR::TypeRef& ty, bool is_shallow/*=false*/)
{
    TRACE_FUNCTION_R(ptr << ": " << ty << (is_shallow ? " (shallow)" : ""), "");
    // TODO: After the drop is done, flag the backing allocation for `ptr` as freed
    if( is_shallow )
    {
        // HACK: Only works for Box<T> where the first pointer is the data pointer
        auto box_ptr_vr = ptr.read_pointer_valref_mut(0, POINTER_SIZE);
        auto ofs = box_ptr_vr.read_usize(0);
        auto alloc = box_ptr_vr.get_relocation(0);
        if( ofs != Allocation::PTR_BASE || !alloc || !alloc.is_alloc() ) {
            LOG_ERROR("Attempting to shallow drop with invalid pointer (no relocation or non-zero offset) - " << box_ptr_vr);
        }

        LOG_DEBUG("drop_value SHALLOW deallocate " << alloc);
        alloc.alloc().mark_as_freed();
        return true;
    }
    if( const auto* w = ty.get_wrapper() )
    {
        switch( w->type )
        {
        case TypeWrapper::Ty::Borrow:
            if( w->size == static_cast<size_t>(::HIR::BorrowType::Move) )
            {
                LOG_TODO("Drop - " << ty << " - dereference and go to inner");
                // TODO: Clear validity on the entire inner value.
                //auto iptr = ptr.read_value(0, ty.get_size());
                //drop_value(iptr, ty.get_inner());
            }
            else
            {
                // No destructor
            }
            break;
        case TypeWrapper::Ty::Pointer:
            // No destructor
            break;
        case TypeWrapper::Ty::Slice: {
            // - Get thin pointer and count
            auto ofs = ptr.read_usize(0);
            LOG_ASSERT(ofs >= Allocation::PTR_BASE, "");
            auto ptr_reloc = ptr.get_relocation(0);
            auto count = ptr.read_usize(POINTER_SIZE);

            auto ity = ty.get_inner();
            auto pty = ity.wrapped(TypeWrapper::Ty::Borrow, static_cast<size_t>(::HIR::BorrowType::Move));
            for(uint64_t i = 0; i < count; i ++)
            {
                auto ptr = Value::new_pointer(pty, ofs, ptr_reloc);
                if( !drop_value(ptr, ity) )
                {
                    // - This is trying to invoke custom drop glue, need to suspend this operation and come back later

                    // > insert a new frame shim BEFORE the current top (which would be the frame created by
                    // `drop_value` calling a function)
                    m_stack.insert( m_stack.end() - 1, StackFrame::make_wrapper([this,pty,ity,ptr_reloc,count, i,ofs](Value& rv, Value drop_rv) mutable {
                        assert(i < count);
                        i ++;
                        if( i < count )
                        {
                            auto ptr = Value::new_pointer(pty, ofs, ptr_reloc);
                            ofs += ity.get_size();
                            assert(!drop_value(ptr, ity));
                            return false;
                        }
                        else
                        {
                            return true;
                        }
                        }) );
                    return false;
                }
                ofs += ity.get_size();
            }
            } break;
        // TODO: Arrays?
        default:
            LOG_TODO("Drop - " << ty << " - array?");
            break;
        }
    }
    else
    {
        if( ty.inner_type == RawType::Composite )
        {
            if( ty.composite_type->drop_glue != ::HIR::Path() )
            {
                LOG_DEBUG("Drop - " << ty);

                Value   tmp;
                return this->call_path(tmp, ty.composite_type->drop_glue, { ptr });
            }
            else
            {
                // No drop glue
            }
        }
        else if( ty.inner_type == RawType::TraitObject )
        {
            // Get the drop glue from the vtable (first entry)
            auto inner_ptr = ptr.read_value(0, POINTER_SIZE);
            auto vtable = ptr.deref(POINTER_SIZE, ty.get_meta_type().get_inner());
            auto drop_r = vtable.get_relocation(0);
            if( drop_r )
            {
                LOG_ASSERT(drop_r.get_ty() == RelocationPtr::Ty::Function, "");
                auto fcn = drop_r.fcn();
                static Value    tmp;
                return this->call_path(tmp, fcn, { ::std::move(inner_ptr) });
            }
            else
            {
                // None
            }
        }
        else
        {
            // No destructor
        }
    }
    return true;
}