aboutsummaryrefslogtreecommitdiff
path: root/src/value.zig
blob: a4e3bf68a11396d2385fbe730cc90b49f6becaea (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
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
const std = @import("std");
const Type = @import("type.zig").Type;
const log2 = std.math.log2;
const assert = std.debug.assert;
const BigIntConst = std.math.big.int.Const;
const BigIntMutable = std.math.big.int.Mutable;
const Target = std.Target;
const Allocator = std.mem.Allocator;
const Module = @import("Module.zig");
const Air = @import("Air.zig");

/// This is the raw data, with no bookkeeping, no memory awareness,
/// no de-duplication, and no type system awareness.
/// It's important for this type to be small.
/// This union takes advantage of the fact that the first page of memory
/// is unmapped, giving us 4096 possible enum tags that have no payload.
pub const Value = extern union {
    /// If the tag value is less than Tag.no_payload_count, then no pointer
    /// dereference is needed.
    tag_if_small_enough: Tag,
    ptr_otherwise: *Payload,

    pub const Tag = enum(usize) {
        // The first section of this enum are tags that require no payload.
        u1_type,
        u8_type,
        i8_type,
        u16_type,
        i16_type,
        u32_type,
        i32_type,
        u64_type,
        i64_type,
        u128_type,
        i128_type,
        usize_type,
        isize_type,
        c_short_type,
        c_ushort_type,
        c_int_type,
        c_uint_type,
        c_long_type,
        c_ulong_type,
        c_longlong_type,
        c_ulonglong_type,
        c_longdouble_type,
        f16_type,
        f32_type,
        f64_type,
        f80_type,
        f128_type,
        anyopaque_type,
        bool_type,
        void_type,
        type_type,
        anyerror_type,
        comptime_int_type,
        comptime_float_type,
        noreturn_type,
        anyframe_type,
        null_type,
        undefined_type,
        enum_literal_type,
        atomic_order_type,
        atomic_rmw_op_type,
        calling_convention_type,
        address_space_type,
        float_mode_type,
        reduce_op_type,
        call_options_type,
        prefetch_options_type,
        export_options_type,
        extern_options_type,
        type_info_type,
        manyptr_u8_type,
        manyptr_const_u8_type,
        manyptr_const_u8_sentinel_0_type,
        fn_noreturn_no_args_type,
        fn_void_no_args_type,
        fn_naked_noreturn_no_args_type,
        fn_ccc_void_no_args_type,
        single_const_pointer_to_comptime_int_type,
        const_slice_u8_type,
        const_slice_u8_sentinel_0_type,
        anyerror_void_error_union_type,
        generic_poison_type,

        undef,
        zero,
        one,
        void_value,
        unreachable_value,
        /// The only possible value for a particular type, which is stored externally.
        the_only_possible_value,
        null_value,
        bool_true,
        bool_false,
        generic_poison,

        abi_align_default,
        empty_struct_value,
        empty_array, // See last_no_payload_tag below.
        // After this, the tag requires a payload.

        ty,
        int_type,
        int_u64,
        int_i64,
        int_big_positive,
        int_big_negative,
        function,
        extern_fn,
        variable,
        /// Represents a pointer to a Decl.
        /// When machine codegen backend sees this, it must set the Decl's `alive` field to true.
        decl_ref,
        /// Pointer to a Decl, but allows comptime code to mutate the Decl's Value.
        /// This Tag will never be seen by machine codegen backends. It is changed into a
        /// `decl_ref` when a comptime variable goes out of scope.
        decl_ref_mut,
        /// Pointer to a specific element of an array, vector or slice.
        elem_ptr,
        /// Pointer to a specific field of a struct or union.
        field_ptr,
        /// A slice of u8 whose memory is managed externally.
        bytes,
        /// This value is repeated some number of times. The amount of times to repeat
        /// is stored externally.
        repeated,
        /// Each element stored as a `Value`.
        /// In the case of sentinel-terminated arrays, the sentinel value *is* stored,
        /// so the slice length will be one more than the type's array length.
        array,
        /// An array with length 0 but it has a sentinel.
        empty_array_sentinel,
        /// Pointer and length as sub `Value` objects.
        slice,
        float_16,
        float_32,
        float_64,
        float_80,
        float_128,
        enum_literal,
        /// A specific enum tag, indicated by the field index (declaration order).
        enum_field_index,
        @"error",
        /// When the type is error union:
        /// * If the tag is `.@"error"`, the error union is an error.
        /// * If the tag is `.eu_payload`, the error union is a payload.
        /// * A nested error such as `anyerror!(anyerror!T)` in which the the outer error union
        ///   is non-error, but the inner error union is an error, is represented as
        ///   a tag of `.eu_payload`, with a sub-tag of `.@"error"`.
        eu_payload,
        /// A pointer to the payload of an error union, based on a pointer to an error union.
        eu_payload_ptr,
        /// When the type is optional:
        /// * If the tag is `.null_value`, the optional is null.
        /// * If the tag is `.opt_payload`, the optional is a payload.
        /// * A nested optional such as `??T` in which the the outer optional
        ///   is non-null, but the inner optional is null, is represented as
        ///   a tag of `.opt_payload`, with a sub-tag of `.null_value`.
        opt_payload,
        /// A pointer to the payload of an optional, based on a pointer to an optional.
        opt_payload_ptr,
        /// An instance of a struct.
        @"struct",
        /// An instance of a union.
        @"union",
        /// This is a special value that tracks a set of types that have been stored
        /// to an inferred allocation. It does not support any of the normal value queries.
        inferred_alloc,
        /// Used to coordinate alloc_inferred, store_to_inferred_ptr, and resolve_inferred_alloc
        /// instructions for comptime code.
        inferred_alloc_comptime,
        /// Used sometimes as the result of field_call_bind.  This value is always temporary,
        /// and refers directly to the air.  It will never be referenced by the air itself.
        /// TODO: This is probably a bad encoding, maybe put temp data in the sema instead.
        bound_fn,

        pub const last_no_payload_tag = Tag.empty_array;
        pub const no_payload_count = @enumToInt(last_no_payload_tag) + 1;

        pub fn Type(comptime t: Tag) type {
            return switch (t) {
                .u1_type,
                .u8_type,
                .i8_type,
                .u16_type,
                .i16_type,
                .u32_type,
                .i32_type,
                .u64_type,
                .i64_type,
                .u128_type,
                .i128_type,
                .usize_type,
                .isize_type,
                .c_short_type,
                .c_ushort_type,
                .c_int_type,
                .c_uint_type,
                .c_long_type,
                .c_ulong_type,
                .c_longlong_type,
                .c_ulonglong_type,
                .c_longdouble_type,
                .f16_type,
                .f32_type,
                .f64_type,
                .f80_type,
                .f128_type,
                .anyopaque_type,
                .bool_type,
                .void_type,
                .type_type,
                .anyerror_type,
                .comptime_int_type,
                .comptime_float_type,
                .noreturn_type,
                .null_type,
                .undefined_type,
                .fn_noreturn_no_args_type,
                .fn_void_no_args_type,
                .fn_naked_noreturn_no_args_type,
                .fn_ccc_void_no_args_type,
                .single_const_pointer_to_comptime_int_type,
                .anyframe_type,
                .const_slice_u8_type,
                .const_slice_u8_sentinel_0_type,
                .anyerror_void_error_union_type,
                .generic_poison_type,
                .enum_literal_type,
                .undef,
                .zero,
                .one,
                .void_value,
                .unreachable_value,
                .the_only_possible_value,
                .empty_struct_value,
                .empty_array,
                .null_value,
                .bool_true,
                .bool_false,
                .abi_align_default,
                .manyptr_u8_type,
                .manyptr_const_u8_type,
                .manyptr_const_u8_sentinel_0_type,
                .atomic_order_type,
                .atomic_rmw_op_type,
                .calling_convention_type,
                .address_space_type,
                .float_mode_type,
                .reduce_op_type,
                .call_options_type,
                .prefetch_options_type,
                .export_options_type,
                .extern_options_type,
                .type_info_type,
                .generic_poison,
                => @compileError("Value Tag " ++ @tagName(t) ++ " has no payload"),

                .int_big_positive,
                .int_big_negative,
                => Payload.BigInt,

                .extern_fn => Payload.ExternFn,

                .decl_ref => Payload.Decl,

                .repeated,
                .eu_payload,
                .eu_payload_ptr,
                .opt_payload,
                .opt_payload_ptr,
                .empty_array_sentinel,
                => Payload.SubValue,

                .bytes,
                .enum_literal,
                => Payload.Bytes,

                .array => Payload.Array,
                .slice => Payload.Slice,

                .enum_field_index => Payload.U32,

                .ty => Payload.Ty,
                .int_type => Payload.IntType,
                .int_u64 => Payload.U64,
                .int_i64 => Payload.I64,
                .function => Payload.Function,
                .variable => Payload.Variable,
                .decl_ref_mut => Payload.DeclRefMut,
                .elem_ptr => Payload.ElemPtr,
                .field_ptr => Payload.FieldPtr,
                .float_16 => Payload.Float_16,
                .float_32 => Payload.Float_32,
                .float_64 => Payload.Float_64,
                .float_80 => Payload.Float_80,
                .float_128 => Payload.Float_128,
                .@"error" => Payload.Error,
                .inferred_alloc => Payload.InferredAlloc,
                .inferred_alloc_comptime => Payload.InferredAllocComptime,
                .@"struct" => Payload.Struct,
                .@"union" => Payload.Union,
                .bound_fn => Payload.BoundFn,
            };
        }

        pub fn create(comptime t: Tag, ally: Allocator, data: Data(t)) error{OutOfMemory}!Value {
            const ptr = try ally.create(t.Type());
            ptr.* = .{
                .base = .{ .tag = t },
                .data = data,
            };
            return Value{ .ptr_otherwise = &ptr.base };
        }

        pub fn Data(comptime t: Tag) type {
            return std.meta.fieldInfo(t.Type(), .data).field_type;
        }
    };

    pub fn initTag(small_tag: Tag) Value {
        assert(@enumToInt(small_tag) < Tag.no_payload_count);
        return .{ .tag_if_small_enough = small_tag };
    }

    pub fn initPayload(payload: *Payload) Value {
        assert(@enumToInt(payload.tag) >= Tag.no_payload_count);
        return .{ .ptr_otherwise = payload };
    }

    pub fn tag(self: Value) Tag {
        if (@enumToInt(self.tag_if_small_enough) < Tag.no_payload_count) {
            return self.tag_if_small_enough;
        } else {
            return self.ptr_otherwise.tag;
        }
    }

    /// Prefer `castTag` to this.
    pub fn cast(self: Value, comptime T: type) ?*T {
        if (@hasField(T, "base_tag")) {
            return self.castTag(T.base_tag);
        }
        if (@enumToInt(self.tag_if_small_enough) < Tag.no_payload_count) {
            return null;
        }
        inline for (@typeInfo(Tag).Enum.fields) |field| {
            if (field.value < Tag.no_payload_count)
                continue;
            const t = @intToEnum(Tag, field.value);
            if (self.ptr_otherwise.tag == t) {
                if (T == t.Type()) {
                    return @fieldParentPtr(T, "base", self.ptr_otherwise);
                }
                return null;
            }
        }
        unreachable;
    }

    pub fn castTag(self: Value, comptime t: Tag) ?*t.Type() {
        if (@enumToInt(self.tag_if_small_enough) < Tag.no_payload_count)
            return null;

        if (self.ptr_otherwise.tag == t)
            return @fieldParentPtr(t.Type(), "base", self.ptr_otherwise);

        return null;
    }

    /// It's intentional that this function is not passed a corresponding Type, so that
    /// a Value can be copied from a Sema to a Decl prior to resolving struct/union field types.
    pub fn copy(self: Value, arena: Allocator) error{OutOfMemory}!Value {
        if (@enumToInt(self.tag_if_small_enough) < Tag.no_payload_count) {
            return Value{ .tag_if_small_enough = self.tag_if_small_enough };
        } else switch (self.ptr_otherwise.tag) {
            .u1_type,
            .u8_type,
            .i8_type,
            .u16_type,
            .i16_type,
            .u32_type,
            .i32_type,
            .u64_type,
            .i64_type,
            .u128_type,
            .i128_type,
            .usize_type,
            .isize_type,
            .c_short_type,
            .c_ushort_type,
            .c_int_type,
            .c_uint_type,
            .c_long_type,
            .c_ulong_type,
            .c_longlong_type,
            .c_ulonglong_type,
            .c_longdouble_type,
            .f16_type,
            .f32_type,
            .f64_type,
            .f80_type,
            .f128_type,
            .anyopaque_type,
            .bool_type,
            .void_type,
            .type_type,
            .anyerror_type,
            .comptime_int_type,
            .comptime_float_type,
            .noreturn_type,
            .null_type,
            .undefined_type,
            .fn_noreturn_no_args_type,
            .fn_void_no_args_type,
            .fn_naked_noreturn_no_args_type,
            .fn_ccc_void_no_args_type,
            .single_const_pointer_to_comptime_int_type,
            .anyframe_type,
            .const_slice_u8_type,
            .const_slice_u8_sentinel_0_type,
            .anyerror_void_error_union_type,
            .generic_poison_type,
            .enum_literal_type,
            .undef,
            .zero,
            .one,
            .void_value,
            .unreachable_value,
            .the_only_possible_value,
            .empty_array,
            .null_value,
            .bool_true,
            .bool_false,
            .empty_struct_value,
            .abi_align_default,
            .manyptr_u8_type,
            .manyptr_const_u8_type,
            .manyptr_const_u8_sentinel_0_type,
            .atomic_order_type,
            .atomic_rmw_op_type,
            .calling_convention_type,
            .address_space_type,
            .float_mode_type,
            .reduce_op_type,
            .call_options_type,
            .prefetch_options_type,
            .export_options_type,
            .extern_options_type,
            .type_info_type,
            .generic_poison,
            .bound_fn,
            => unreachable,

            .ty => {
                const payload = self.castTag(.ty).?;
                const new_payload = try arena.create(Payload.Ty);
                new_payload.* = .{
                    .base = payload.base,
                    .data = try payload.data.copy(arena),
                };
                return Value{ .ptr_otherwise = &new_payload.base };
            },
            .int_type => return self.copyPayloadShallow(arena, Payload.IntType),
            .int_u64 => return self.copyPayloadShallow(arena, Payload.U64),
            .int_i64 => return self.copyPayloadShallow(arena, Payload.I64),
            .int_big_positive, .int_big_negative => {
                const old_payload = self.cast(Payload.BigInt).?;
                const new_payload = try arena.create(Payload.BigInt);
                new_payload.* = .{
                    .base = .{ .tag = self.ptr_otherwise.tag },
                    .data = try arena.dupe(std.math.big.Limb, old_payload.data),
                };
                return Value{ .ptr_otherwise = &new_payload.base };
            },
            .function => return self.copyPayloadShallow(arena, Payload.Function),
            .extern_fn => return self.copyPayloadShallow(arena, Payload.ExternFn),
            .variable => return self.copyPayloadShallow(arena, Payload.Variable),
            .decl_ref => return self.copyPayloadShallow(arena, Payload.Decl),
            .decl_ref_mut => return self.copyPayloadShallow(arena, Payload.DeclRefMut),
            .elem_ptr => {
                const payload = self.castTag(.elem_ptr).?;
                const new_payload = try arena.create(Payload.ElemPtr);
                new_payload.* = .{
                    .base = payload.base,
                    .data = .{
                        .array_ptr = try payload.data.array_ptr.copy(arena),
                        .index = payload.data.index,
                    },
                };
                return Value{ .ptr_otherwise = &new_payload.base };
            },
            .field_ptr => {
                const payload = self.castTag(.field_ptr).?;
                const new_payload = try arena.create(Payload.FieldPtr);
                new_payload.* = .{
                    .base = payload.base,
                    .data = .{
                        .container_ptr = try payload.data.container_ptr.copy(arena),
                        .field_index = payload.data.field_index,
                    },
                };
                return Value{ .ptr_otherwise = &new_payload.base };
            },
            .bytes => return self.copyPayloadShallow(arena, Payload.Bytes),
            .repeated,
            .eu_payload,
            .eu_payload_ptr,
            .opt_payload,
            .opt_payload_ptr,
            .empty_array_sentinel,
            => {
                const payload = self.cast(Payload.SubValue).?;
                const new_payload = try arena.create(Payload.SubValue);
                new_payload.* = .{
                    .base = payload.base,
                    .data = try payload.data.copy(arena),
                };
                return Value{ .ptr_otherwise = &new_payload.base };
            },
            .array => {
                const payload = self.castTag(.array).?;
                const new_payload = try arena.create(Payload.Array);
                new_payload.* = .{
                    .base = payload.base,
                    .data = try arena.alloc(Value, payload.data.len),
                };
                for (new_payload.data) |*elem, i| {
                    elem.* = try payload.data[i].copy(arena);
                }
                return Value{ .ptr_otherwise = &new_payload.base };
            },
            .slice => {
                const payload = self.castTag(.slice).?;
                const new_payload = try arena.create(Payload.Slice);
                new_payload.* = .{
                    .base = payload.base,
                    .data = .{
                        .ptr = try payload.data.ptr.copy(arena),
                        .len = try payload.data.len.copy(arena),
                    },
                };
                return Value{ .ptr_otherwise = &new_payload.base };
            },
            .float_16 => return self.copyPayloadShallow(arena, Payload.Float_16),
            .float_32 => return self.copyPayloadShallow(arena, Payload.Float_32),
            .float_64 => return self.copyPayloadShallow(arena, Payload.Float_64),
            .float_80 => return self.copyPayloadShallow(arena, Payload.Float_80),
            .float_128 => return self.copyPayloadShallow(arena, Payload.Float_128),
            .enum_literal => {
                const payload = self.castTag(.enum_literal).?;
                const new_payload = try arena.create(Payload.Bytes);
                new_payload.* = .{
                    .base = payload.base,
                    .data = try arena.dupe(u8, payload.data),
                };
                return Value{ .ptr_otherwise = &new_payload.base };
            },
            .enum_field_index => return self.copyPayloadShallow(arena, Payload.U32),
            .@"error" => return self.copyPayloadShallow(arena, Payload.Error),

            .@"struct" => {
                const old_field_values = self.castTag(.@"struct").?.data;
                const new_payload = try arena.create(Payload.Struct);
                new_payload.* = .{
                    .base = .{ .tag = .@"struct" },
                    .data = try arena.alloc(Value, old_field_values.len),
                };
                for (old_field_values) |old_field_val, i| {
                    new_payload.data[i] = try old_field_val.copy(arena);
                }
                return Value{ .ptr_otherwise = &new_payload.base };
            },

            .@"union" => {
                const tag_and_val = self.castTag(.@"union").?.data;
                const new_payload = try arena.create(Payload.Union);
                new_payload.* = .{
                    .base = .{ .tag = .@"union" },
                    .data = .{
                        .tag = try tag_and_val.tag.copy(arena),
                        .val = try tag_and_val.val.copy(arena),
                    },
                };
                return Value{ .ptr_otherwise = &new_payload.base };
            },

            .inferred_alloc => unreachable,
            .inferred_alloc_comptime => unreachable,
        }
    }

    fn copyPayloadShallow(self: Value, arena: Allocator, comptime T: type) error{OutOfMemory}!Value {
        const payload = self.cast(T).?;
        const new_payload = try arena.create(T);
        new_payload.* = payload.*;
        return Value{ .ptr_otherwise = &new_payload.base };
    }

    /// TODO this should become a debug dump() function. In order to print values in a meaningful way
    /// we also need access to the type.
    pub fn format(
        start_val: Value,
        comptime fmt: []const u8,
        options: std.fmt.FormatOptions,
        out_stream: anytype,
    ) !void {
        comptime assert(fmt.len == 0);
        var val = start_val;
        while (true) switch (val.tag()) {
            .u1_type => return out_stream.writeAll("u1"),
            .u8_type => return out_stream.writeAll("u8"),
            .i8_type => return out_stream.writeAll("i8"),
            .u16_type => return out_stream.writeAll("u16"),
            .i16_type => return out_stream.writeAll("i16"),
            .u32_type => return out_stream.writeAll("u32"),
            .i32_type => return out_stream.writeAll("i32"),
            .u64_type => return out_stream.writeAll("u64"),
            .i64_type => return out_stream.writeAll("i64"),
            .u128_type => return out_stream.writeAll("u128"),
            .i128_type => return out_stream.writeAll("i128"),
            .isize_type => return out_stream.writeAll("isize"),
            .usize_type => return out_stream.writeAll("usize"),
            .c_short_type => return out_stream.writeAll("c_short"),
            .c_ushort_type => return out_stream.writeAll("c_ushort"),
            .c_int_type => return out_stream.writeAll("c_int"),
            .c_uint_type => return out_stream.writeAll("c_uint"),
            .c_long_type => return out_stream.writeAll("c_long"),
            .c_ulong_type => return out_stream.writeAll("c_ulong"),
            .c_longlong_type => return out_stream.writeAll("c_longlong"),
            .c_ulonglong_type => return out_stream.writeAll("c_ulonglong"),
            .c_longdouble_type => return out_stream.writeAll("c_longdouble"),
            .f16_type => return out_stream.writeAll("f16"),
            .f32_type => return out_stream.writeAll("f32"),
            .f64_type => return out_stream.writeAll("f64"),
            .f80_type => return out_stream.writeAll("f80"),
            .f128_type => return out_stream.writeAll("f128"),
            .anyopaque_type => return out_stream.writeAll("anyopaque"),
            .bool_type => return out_stream.writeAll("bool"),
            .void_type => return out_stream.writeAll("void"),
            .type_type => return out_stream.writeAll("type"),
            .anyerror_type => return out_stream.writeAll("anyerror"),
            .comptime_int_type => return out_stream.writeAll("comptime_int"),
            .comptime_float_type => return out_stream.writeAll("comptime_float"),
            .noreturn_type => return out_stream.writeAll("noreturn"),
            .null_type => return out_stream.writeAll("@Type(.Null)"),
            .undefined_type => return out_stream.writeAll("@Type(.Undefined)"),
            .fn_noreturn_no_args_type => return out_stream.writeAll("fn() noreturn"),
            .fn_void_no_args_type => return out_stream.writeAll("fn() void"),
            .fn_naked_noreturn_no_args_type => return out_stream.writeAll("fn() callconv(.Naked) noreturn"),
            .fn_ccc_void_no_args_type => return out_stream.writeAll("fn() callconv(.C) void"),
            .single_const_pointer_to_comptime_int_type => return out_stream.writeAll("*const comptime_int"),
            .anyframe_type => return out_stream.writeAll("anyframe"),
            .const_slice_u8_type => return out_stream.writeAll("[]const u8"),
            .const_slice_u8_sentinel_0_type => return out_stream.writeAll("[:0]const u8"),
            .anyerror_void_error_union_type => return out_stream.writeAll("anyerror!void"),
            .generic_poison_type => return out_stream.writeAll("(generic poison type)"),
            .generic_poison => return out_stream.writeAll("(generic poison)"),
            .enum_literal_type => return out_stream.writeAll("@Type(.EnumLiteral)"),
            .manyptr_u8_type => return out_stream.writeAll("[*]u8"),
            .manyptr_const_u8_type => return out_stream.writeAll("[*]const u8"),
            .manyptr_const_u8_sentinel_0_type => return out_stream.writeAll("[*:0]const u8"),
            .atomic_order_type => return out_stream.writeAll("std.builtin.AtomicOrder"),
            .atomic_rmw_op_type => return out_stream.writeAll("std.builtin.AtomicRmwOp"),
            .calling_convention_type => return out_stream.writeAll("std.builtin.CallingConvention"),
            .address_space_type => return out_stream.writeAll("std.builtin.AddressSpace"),
            .float_mode_type => return out_stream.writeAll("std.builtin.FloatMode"),
            .reduce_op_type => return out_stream.writeAll("std.builtin.ReduceOp"),
            .call_options_type => return out_stream.writeAll("std.builtin.CallOptions"),
            .prefetch_options_type => return out_stream.writeAll("std.builtin.PrefetchOptions"),
            .export_options_type => return out_stream.writeAll("std.builtin.ExportOptions"),
            .extern_options_type => return out_stream.writeAll("std.builtin.ExternOptions"),
            .type_info_type => return out_stream.writeAll("std.builtin.TypeInfo"),
            .abi_align_default => return out_stream.writeAll("(default ABI alignment)"),

            .empty_struct_value => return out_stream.writeAll("struct {}{}"),
            .@"struct" => {
                return out_stream.writeAll("(struct value)");
            },
            .@"union" => {
                return out_stream.writeAll("(union value)");
            },
            .null_value => return out_stream.writeAll("null"),
            .undef => return out_stream.writeAll("undefined"),
            .zero => return out_stream.writeAll("0"),
            .one => return out_stream.writeAll("1"),
            .void_value => return out_stream.writeAll("{}"),
            .unreachable_value => return out_stream.writeAll("unreachable"),
            .the_only_possible_value => return out_stream.writeAll("(the only possible value)"),
            .bool_true => return out_stream.writeAll("true"),
            .bool_false => return out_stream.writeAll("false"),
            .ty => return val.castTag(.ty).?.data.format("", options, out_stream),
            .int_type => {
                const int_type = val.castTag(.int_type).?.data;
                return out_stream.print("{s}{d}", .{
                    if (int_type.signed) "s" else "u",
                    int_type.bits,
                });
            },
            .int_u64 => return std.fmt.formatIntValue(val.castTag(.int_u64).?.data, "", options, out_stream),
            .int_i64 => return std.fmt.formatIntValue(val.castTag(.int_i64).?.data, "", options, out_stream),
            .int_big_positive => return out_stream.print("{}", .{val.castTag(.int_big_positive).?.asBigInt()}),
            .int_big_negative => return out_stream.print("{}", .{val.castTag(.int_big_negative).?.asBigInt()}),
            .function => return out_stream.print("(function '{s}')", .{val.castTag(.function).?.data.owner_decl.name}),
            .extern_fn => return out_stream.writeAll("(extern function)"),
            .variable => return out_stream.writeAll("(variable)"),
            .decl_ref_mut => {
                const decl = val.castTag(.decl_ref_mut).?.data.decl;
                return out_stream.print("(decl_ref_mut '{s}')", .{decl.name});
            },
            .decl_ref => {
                const decl = val.castTag(.decl_ref).?.data;
                return out_stream.print("(decl ref '{s}')", .{decl.name});
            },
            .elem_ptr => {
                const elem_ptr = val.castTag(.elem_ptr).?.data;
                try out_stream.print("&[{}] ", .{elem_ptr.index});
                val = elem_ptr.array_ptr;
            },
            .field_ptr => {
                const field_ptr = val.castTag(.field_ptr).?.data;
                try out_stream.print("fieldptr({d}) ", .{field_ptr.field_index});
                val = field_ptr.container_ptr;
            },
            .empty_array => return out_stream.writeAll(".{}"),
            .enum_literal => return out_stream.print(".{}", .{std.zig.fmtId(val.castTag(.enum_literal).?.data)}),
            .enum_field_index => return out_stream.print("(enum field {d})", .{val.castTag(.enum_field_index).?.data}),
            .bytes => return out_stream.print("\"{}\"", .{std.zig.fmtEscapes(val.castTag(.bytes).?.data)}),
            .repeated => {
                try out_stream.writeAll("(repeated) ");
                val = val.castTag(.repeated).?.data;
            },
            .array => return out_stream.writeAll("(array)"),
            .empty_array_sentinel => return out_stream.writeAll("(empty array with sentinel)"),
            .slice => return out_stream.writeAll("(slice)"),
            .float_16 => return out_stream.print("{}", .{val.castTag(.float_16).?.data}),
            .float_32 => return out_stream.print("{}", .{val.castTag(.float_32).?.data}),
            .float_64 => return out_stream.print("{}", .{val.castTag(.float_64).?.data}),
            .float_80 => return out_stream.print("{}", .{val.castTag(.float_80).?.data}),
            .float_128 => return out_stream.print("{}", .{val.castTag(.float_128).?.data}),
            .@"error" => return out_stream.print("error.{s}", .{val.castTag(.@"error").?.data.name}),
            // TODO to print this it should be error{ Set, Items }!T(val), but we need the type for that
            .eu_payload => {
                try out_stream.writeAll("(eu_payload) ");
                val = val.castTag(.eu_payload).?.data;
            },
            .opt_payload => {
                try out_stream.writeAll("(opt_payload) ");
                val = val.castTag(.opt_payload).?.data;
            },
            .inferred_alloc => return out_stream.writeAll("(inferred allocation value)"),
            .inferred_alloc_comptime => return out_stream.writeAll("(inferred comptime allocation value)"),
            .eu_payload_ptr => {
                try out_stream.writeAll("(eu_payload_ptr)");
                val = val.castTag(.eu_payload_ptr).?.data;
            },
            .opt_payload_ptr => {
                try out_stream.writeAll("(opt_payload_ptr)");
                val = val.castTag(.opt_payload_ptr).?.data;
            },
            .bound_fn => {
                const bound_func = val.castTag(.bound_fn).?.data;
                return out_stream.print("(bound_fn %{}(%{})", .{ bound_func.func_inst, bound_func.arg0_inst });
            },
        };
    }

    /// Asserts that the value is representable as an array of bytes.
    /// Copies the value into a freshly allocated slice of memory, which is owned by the caller.
    pub fn toAllocatedBytes(val: Value, ty: Type, allocator: Allocator) ![]u8 {
        switch (val.tag()) {
            .bytes => {
                const bytes = val.castTag(.bytes).?.data;
                const adjusted_len = bytes.len - @boolToInt(ty.sentinel() != null);
                const adjusted_bytes = bytes[0..adjusted_len];
                return allocator.dupe(u8, adjusted_bytes);
            },
            .enum_literal => return allocator.dupe(u8, val.castTag(.enum_literal).?.data),
            .repeated => {
                const byte = @intCast(u8, val.castTag(.repeated).?.data.toUnsignedInt());
                const result = try allocator.alloc(u8, @intCast(usize, ty.arrayLen()));
                std.mem.set(u8, result, byte);
                return result;
            },
            .decl_ref => {
                const decl = val.castTag(.decl_ref).?.data;
                const decl_val = try decl.value();
                return decl_val.toAllocatedBytes(decl.ty, allocator);
            },
            .the_only_possible_value => return &[_]u8{},
            .slice => return toAllocatedBytes(val.castTag(.slice).?.data.ptr, ty, allocator),
            else => {
                const result = try allocator.alloc(u8, @intCast(usize, ty.arrayLen()));
                var elem_value_buf: ElemValueBuffer = undefined;
                for (result) |*elem, i| {
                    const elem_val = val.elemValueBuffer(i, &elem_value_buf);
                    elem.* = @intCast(u8, elem_val.toUnsignedInt());
                }
                return result;
            },
        }
    }

    pub const ToTypeBuffer = Type.Payload.Bits;

    /// Asserts that the value is representable as a type.
    pub fn toType(self: Value, buffer: *ToTypeBuffer) Type {
        return switch (self.tag()) {
            .ty => self.castTag(.ty).?.data,
            .u1_type => Type.initTag(.u1),
            .u8_type => Type.initTag(.u8),
            .i8_type => Type.initTag(.i8),
            .u16_type => Type.initTag(.u16),
            .i16_type => Type.initTag(.i16),
            .u32_type => Type.initTag(.u32),
            .i32_type => Type.initTag(.i32),
            .u64_type => Type.initTag(.u64),
            .i64_type => Type.initTag(.i64),
            .u128_type => Type.initTag(.u128),
            .i128_type => Type.initTag(.i128),
            .usize_type => Type.initTag(.usize),
            .isize_type => Type.initTag(.isize),
            .c_short_type => Type.initTag(.c_short),
            .c_ushort_type => Type.initTag(.c_ushort),
            .c_int_type => Type.initTag(.c_int),
            .c_uint_type => Type.initTag(.c_uint),
            .c_long_type => Type.initTag(.c_long),
            .c_ulong_type => Type.initTag(.c_ulong),
            .c_longlong_type => Type.initTag(.c_longlong),
            .c_ulonglong_type => Type.initTag(.c_ulonglong),
            .c_longdouble_type => Type.initTag(.c_longdouble),
            .f16_type => Type.initTag(.f16),
            .f32_type => Type.initTag(.f32),
            .f64_type => Type.initTag(.f64),
            .f80_type => Type.initTag(.f80),
            .f128_type => Type.initTag(.f128),
            .anyopaque_type => Type.initTag(.anyopaque),
            .bool_type => Type.initTag(.bool),
            .void_type => Type.initTag(.void),
            .type_type => Type.initTag(.type),
            .anyerror_type => Type.initTag(.anyerror),
            .comptime_int_type => Type.initTag(.comptime_int),
            .comptime_float_type => Type.initTag(.comptime_float),
            .noreturn_type => Type.initTag(.noreturn),
            .null_type => Type.initTag(.@"null"),
            .undefined_type => Type.initTag(.@"undefined"),
            .fn_noreturn_no_args_type => Type.initTag(.fn_noreturn_no_args),
            .fn_void_no_args_type => Type.initTag(.fn_void_no_args),
            .fn_naked_noreturn_no_args_type => Type.initTag(.fn_naked_noreturn_no_args),
            .fn_ccc_void_no_args_type => Type.initTag(.fn_ccc_void_no_args),
            .single_const_pointer_to_comptime_int_type => Type.initTag(.single_const_pointer_to_comptime_int),
            .anyframe_type => Type.initTag(.@"anyframe"),
            .const_slice_u8_type => Type.initTag(.const_slice_u8),
            .const_slice_u8_sentinel_0_type => Type.initTag(.const_slice_u8_sentinel_0),
            .anyerror_void_error_union_type => Type.initTag(.anyerror_void_error_union),
            .generic_poison_type => Type.initTag(.generic_poison),
            .enum_literal_type => Type.initTag(.enum_literal),
            .manyptr_u8_type => Type.initTag(.manyptr_u8),
            .manyptr_const_u8_type => Type.initTag(.manyptr_const_u8),
            .manyptr_const_u8_sentinel_0_type => Type.initTag(.manyptr_const_u8_sentinel_0),
            .atomic_order_type => Type.initTag(.atomic_order),
            .atomic_rmw_op_type => Type.initTag(.atomic_rmw_op),
            .calling_convention_type => Type.initTag(.calling_convention),
            .address_space_type => Type.initTag(.address_space),
            .float_mode_type => Type.initTag(.float_mode),
            .reduce_op_type => Type.initTag(.reduce_op),
            .call_options_type => Type.initTag(.call_options),
            .prefetch_options_type => Type.initTag(.prefetch_options),
            .export_options_type => Type.initTag(.export_options),
            .extern_options_type => Type.initTag(.extern_options),
            .type_info_type => Type.initTag(.type_info),

            .int_type => {
                const payload = self.castTag(.int_type).?.data;
                buffer.* = .{
                    .base = .{
                        .tag = if (payload.signed) .int_signed else .int_unsigned,
                    },
                    .data = payload.bits,
                };
                return Type.initPayload(&buffer.base);
            },

            else => unreachable,
        };
    }

    /// Asserts the type is an enum type.
    pub fn toEnum(val: Value, comptime E: type) E {
        switch (val.tag()) {
            .enum_field_index => {
                const field_index = val.castTag(.enum_field_index).?.data;
                // TODO should `@intToEnum` do this `@intCast` for you?
                return @intToEnum(E, @intCast(@typeInfo(E).Enum.tag_type, field_index));
            },
            .the_only_possible_value => {
                const fields = std.meta.fields(E);
                assert(fields.len == 1);
                return @intToEnum(E, fields[0].value);
            },
            else => unreachable,
        }
    }

    pub fn enumToInt(val: Value, ty: Type, buffer: *Payload.U64) Value {
        const field_index = switch (val.tag()) {
            .enum_field_index => val.castTag(.enum_field_index).?.data,
            .the_only_possible_value => blk: {
                assert(ty.enumFieldCount() == 1);
                break :blk 0;
            },
            // Assume it is already an integer and return it directly.
            else => return val,
        };

        switch (ty.tag()) {
            .enum_full, .enum_nonexhaustive => {
                const enum_full = ty.cast(Type.Payload.EnumFull).?.data;
                if (enum_full.values.count() != 0) {
                    return enum_full.values.keys()[field_index];
                } else {
                    // Field index and integer values are the same.
                    buffer.* = .{
                        .base = .{ .tag = .int_u64 },
                        .data = field_index,
                    };
                    return Value.initPayload(&buffer.base);
                }
            },
            .enum_numbered => {
                const enum_obj = ty.castTag(.enum_numbered).?.data;
                if (enum_obj.values.count() != 0) {
                    return enum_obj.values.keys()[field_index];
                } else {
                    // Field index and integer values are the same.
                    buffer.* = .{
                        .base = .{ .tag = .int_u64 },
                        .data = field_index,
                    };
                    return Value.initPayload(&buffer.base);
                }
            },
            .enum_simple => {
                // Field index and integer values are the same.
                buffer.* = .{
                    .base = .{ .tag = .int_u64 },
                    .data = field_index,
                };
                return Value.initPayload(&buffer.base);
            },
            else => unreachable,
        }
    }

    /// Asserts the value is an integer.
    pub fn toBigInt(self: Value, space: *BigIntSpace) BigIntConst {
        switch (self.tag()) {
            .zero,
            .bool_false,
            .the_only_possible_value, // i0, u0
            => return BigIntMutable.init(&space.limbs, 0).toConst(),

            .one,
            .bool_true,
            => return BigIntMutable.init(&space.limbs, 1).toConst(),

            .int_u64 => return BigIntMutable.init(&space.limbs, self.castTag(.int_u64).?.data).toConst(),
            .int_i64 => return BigIntMutable.init(&space.limbs, self.castTag(.int_i64).?.data).toConst(),
            .int_big_positive => return self.castTag(.int_big_positive).?.asBigInt(),
            .int_big_negative => return self.castTag(.int_big_negative).?.asBigInt(),

            .undef => unreachable,
            else => unreachable,
        }
    }

    /// If the value fits in a u64, return it, otherwise null.
    /// Asserts not undefined.
    pub fn getUnsignedInt(val: Value) ?u64 {
        switch (val.tag()) {
            .zero,
            .bool_false,
            .the_only_possible_value, // i0, u0
            => return 0,

            .one,
            .bool_true,
            => return 1,

            .int_u64 => return val.castTag(.int_u64).?.data,
            .int_i64 => return @intCast(u64, val.castTag(.int_i64).?.data),
            .int_big_positive => return val.castTag(.int_big_positive).?.asBigInt().to(u64) catch null,
            .int_big_negative => return val.castTag(.int_big_negative).?.asBigInt().to(u64) catch null,

            .undef => unreachable,
            else => return null,
        }
    }

    /// Asserts the value is an integer and it fits in a u64
    pub fn toUnsignedInt(val: Value) u64 {
        return getUnsignedInt(val).?;
    }

    /// Asserts the value is an integer and it fits in a i64
    pub fn toSignedInt(self: Value) i64 {
        switch (self.tag()) {
            .zero,
            .bool_false,
            .the_only_possible_value, // i0, u0
            => return 0,

            .one,
            .bool_true,
            => return 1,

            .int_u64 => return @intCast(i64, self.castTag(.int_u64).?.data),
            .int_i64 => return self.castTag(.int_i64).?.data,
            .int_big_positive => return self.castTag(.int_big_positive).?.asBigInt().to(i64) catch unreachable,
            .int_big_negative => return self.castTag(.int_big_negative).?.asBigInt().to(i64) catch unreachable,

            .undef => unreachable,
            else => unreachable,
        }
    }

    pub fn toBool(self: Value) bool {
        return switch (self.tag()) {
            .bool_true, .one => true,
            .bool_false, .zero => false,
            else => unreachable,
        };
    }

    pub fn writeToMemory(val: Value, ty: Type, target: Target, buffer: []u8) void {
        if (val.isUndef()) {
            const size = @intCast(usize, ty.abiSize(target));
            std.mem.set(u8, buffer[0..size], 0xaa);
            return;
        }
        switch (ty.zigTypeTag()) {
            .Int => {
                var bigint_buffer: BigIntSpace = undefined;
                const bigint = val.toBigInt(&bigint_buffer);
                const bits = ty.intInfo(target).bits;
                const abi_size = @intCast(usize, ty.abiSize(target));
                bigint.writeTwosComplement(buffer, bits, abi_size, target.cpu.arch.endian());
            },
            .Enum => {
                var enum_buffer: Payload.U64 = undefined;
                const int_val = val.enumToInt(ty, &enum_buffer);
                var bigint_buffer: BigIntSpace = undefined;
                const bigint = int_val.toBigInt(&bigint_buffer);
                const bits = ty.intInfo(target).bits;
                const abi_size = @intCast(usize, ty.abiSize(target));
                bigint.writeTwosComplement(buffer, bits, abi_size, target.cpu.arch.endian());
            },
            .Float => switch (ty.floatBits(target)) {
                16 => return floatWriteToMemory(f16, val.toFloat(f16), target, buffer),
                32 => return floatWriteToMemory(f32, val.toFloat(f32), target, buffer),
                64 => return floatWriteToMemory(f64, val.toFloat(f64), target, buffer),
                128 => return floatWriteToMemory(f128, val.toFloat(f128), target, buffer),
                else => unreachable,
            },
            .Array, .Vector => {
                const len = ty.arrayLen();
                const elem_ty = ty.childType();
                const elem_size = @intCast(usize, elem_ty.abiSize(target));
                var elem_i: usize = 0;
                var elem_value_buf: ElemValueBuffer = undefined;
                var buf_off: usize = 0;
                while (elem_i < len) : (elem_i += 1) {
                    const elem_val = val.elemValueBuffer(elem_i, &elem_value_buf);
                    writeToMemory(elem_val, elem_ty, target, buffer[buf_off..]);
                    buf_off += elem_size;
                }
            },
            .Struct => {
                const fields = ty.structFields().values();
                const field_vals = val.castTag(.@"struct").?.data;
                for (fields) |field, i| {
                    const off = @intCast(usize, ty.structFieldOffset(i, target));
                    writeToMemory(field_vals[i], field.ty, target, buffer[off..]);
                }
            },
            else => @panic("TODO implement writeToMemory for more types"),
        }
    }

    pub fn readFromMemory(
        ty: Type,
        target: Target,
        buffer: []const u8,
        arena: Allocator,
    ) Allocator.Error!Value {
        switch (ty.zigTypeTag()) {
            .Int => {
                const int_info = ty.intInfo(target);
                const endian = target.cpu.arch.endian();
                const Limb = std.math.big.Limb;
                const limb_count = (buffer.len + @sizeOf(Limb) - 1) / @sizeOf(Limb);
                const limbs_buffer = try arena.alloc(Limb, limb_count);
                const abi_size = @intCast(usize, ty.abiSize(target));
                var bigint = BigIntMutable.init(limbs_buffer, 0);
                bigint.readTwosComplement(buffer, int_info.bits, abi_size, endian, int_info.signedness);
                return fromBigInt(arena, bigint.toConst());
            },
            .Float => switch (ty.floatBits(target)) {
                16 => return Value.Tag.float_16.create(arena, floatReadFromMemory(f16, target, buffer)),
                32 => return Value.Tag.float_32.create(arena, floatReadFromMemory(f32, target, buffer)),
                64 => return Value.Tag.float_64.create(arena, floatReadFromMemory(f64, target, buffer)),
                80 => return Value.Tag.float_80.create(arena, floatReadFromMemory(f80, target, buffer)),
                128 => return Value.Tag.float_128.create(arena, floatReadFromMemory(f128, target, buffer)),
                else => unreachable,
            },
            .Array => {
                const elem_ty = ty.childType();
                const elem_size = elem_ty.abiSize(target);
                const elems = try arena.alloc(Value, @intCast(usize, ty.arrayLen()));
                var offset: usize = 0;
                for (elems) |*elem| {
                    elem.* = try readFromMemory(elem_ty, target, buffer[offset..], arena);
                    offset += @intCast(usize, elem_size);
                }
                return Tag.array.create(arena, elems);
            },
            else => @panic("TODO implement readFromMemory for more types"),
        }
    }

    fn floatWriteToMemory(comptime F: type, f: F, target: Target, buffer: []u8) void {
        if (F == f80) {
            switch (target.cpu.arch) {
                .i386, .x86_64 => {
                    const repr = std.math.break_f80(f);
                    std.mem.writeIntLittle(u64, buffer[0..8], repr.fraction);
                    std.mem.writeIntLittle(u16, buffer[8..10], repr.exp);
                    // TODO set the rest of the bytes to undefined. should we use 0xaa
                    // or is there a different way?
                    return;
                },
                else => {},
            }
        }
        const Int = @Type(.{ .Int = .{
            .signedness = .unsigned,
            .bits = @typeInfo(F).Float.bits,
        } });
        const int = @bitCast(Int, f);
        std.mem.writeInt(Int, buffer[0..@sizeOf(Int)], int, target.cpu.arch.endian());
    }

    fn floatReadFromMemory(comptime F: type, target: Target, buffer: []const u8) F {
        if (F == f80) {
            switch (target.cpu.arch) {
                .i386, .x86_64 => return std.math.make_f80(.{
                    .fraction = std.mem.readIntLittle(u64, buffer[0..8]),
                    .exp = std.mem.readIntLittle(u16, buffer[8..10]),
                }),
                else => {},
            }
        }
        const Int = @Type(.{ .Int = .{
            .signedness = .unsigned,
            .bits = @typeInfo(F).Float.bits,
        } });
        const int = readInt(Int, buffer[0..@sizeOf(Int)], target.cpu.arch.endian());
        return @bitCast(F, int);
    }

    fn readInt(comptime Int: type, buffer: *const [@sizeOf(Int)]u8, endian: std.builtin.Endian) Int {
        var result: Int = 0;
        switch (endian) {
            .Big => {
                for (buffer) |byte| {
                    result <<= 8;
                    result |= byte;
                }
            },
            .Little => {
                var i: usize = buffer.len;
                while (i != 0) {
                    i -= 1;
                    result <<= 8;
                    result |= buffer[i];
                }
            },
        }
        return result;
    }

    /// Asserts that the value is a float or an integer.
    pub fn toFloat(val: Value, comptime T: type) T {
        return switch (val.tag()) {
            .float_16 => @floatCast(T, val.castTag(.float_16).?.data),
            .float_32 => @floatCast(T, val.castTag(.float_32).?.data),
            .float_64 => @floatCast(T, val.castTag(.float_64).?.data),
            .float_80 => @floatCast(T, val.castTag(.float_80).?.data),
            .float_128 => @floatCast(T, val.castTag(.float_128).?.data),

            .zero => 0,
            .one => 1,
            .int_u64 => {
                if (T == f80) {
                    @panic("TODO we can't lower this properly on non-x86 llvm backend yet");
                }
                return @intToFloat(T, val.castTag(.int_u64).?.data);
            },
            .int_i64 => {
                if (T == f80) {
                    @panic("TODO we can't lower this properly on non-x86 llvm backend yet");
                }
                return @intToFloat(T, val.castTag(.int_i64).?.data);
            },

            .int_big_positive => @floatCast(T, bigIntToFloat(val.castTag(.int_big_positive).?.data, true)),
            .int_big_negative => @floatCast(T, bigIntToFloat(val.castTag(.int_big_negative).?.data, false)),
            else => unreachable,
        };
    }

    /// TODO move this to std lib big int code
    fn bigIntToFloat(limbs: []const std.math.big.Limb, positive: bool) f128 {
        if (limbs.len == 0) return 0;

        const base = std.math.maxInt(std.math.big.Limb) + 1;
        var result: f128 = 0;
        var i: usize = limbs.len;
        while (i != 0) {
            i -= 1;
            const limb: f128 = @intToFloat(f128, limbs[i]);
            result = @mulAdd(f128, base, limb, result);
        }
        if (positive) {
            return result;
        } else {
            return -result;
        }
    }

    pub fn clz(val: Value, ty: Type, target: Target) u64 {
        const ty_bits = ty.intInfo(target).bits;
        switch (val.tag()) {
            .zero, .bool_false => return ty_bits,
            .one, .bool_true => return ty_bits - 1,

            .int_u64 => {
                const big = @clz(u64, val.castTag(.int_u64).?.data);
                return big + ty_bits - 64;
            },
            .int_i64 => {
                @panic("TODO implement i64 Value clz");
            },
            .int_big_positive => {
                // TODO: move this code into std lib big ints
                const bigint = val.castTag(.int_big_positive).?.asBigInt();
                // Limbs are stored in little-endian order but we need
                // to iterate big-endian.
                var total_limb_lz: u64 = 0;
                var i: usize = bigint.limbs.len;
                const bits_per_limb = @sizeOf(std.math.big.Limb) * 8;
                while (i != 0) {
                    i -= 1;
                    const limb = bigint.limbs[i];
                    const this_limb_lz = @clz(std.math.big.Limb, limb);
                    total_limb_lz += this_limb_lz;
                    if (this_limb_lz != bits_per_limb) break;
                }
                const total_limb_bits = bigint.limbs.len * bits_per_limb;
                return total_limb_lz + ty_bits - total_limb_bits;
            },
            .int_big_negative => {
                @panic("TODO implement int_big_negative Value clz");
            },

            .the_only_possible_value => {
                assert(ty_bits == 0);
                return ty_bits;
            },

            else => unreachable,
        }
    }

    pub fn ctz(val: Value, ty: Type, target: Target) u64 {
        const ty_bits = ty.intInfo(target).bits;
        switch (val.tag()) {
            .zero, .bool_false => return ty_bits,
            .one, .bool_true => return 0,

            .int_u64 => {
                const big = @ctz(u64, val.castTag(.int_u64).?.data);
                return if (big == 64) ty_bits else big;
            },
            .int_i64 => {
                @panic("TODO implement i64 Value ctz");
            },
            .int_big_positive => {
                // TODO: move this code into std lib big ints
                const bigint = val.castTag(.int_big_positive).?.asBigInt();
                // Limbs are stored in little-endian order.
                var result: u64 = 0;
                for (bigint.limbs) |limb| {
                    const limb_tz = @ctz(std.math.big.Limb, limb);
                    result += limb_tz;
                    if (limb_tz != @sizeOf(std.math.big.Limb) * 8) break;
                }
                return result;
            },
            .int_big_negative => {
                @panic("TODO implement int_big_negative Value ctz");
            },

            .the_only_possible_value => {
                assert(ty_bits == 0);
                return ty_bits;
            },

            else => unreachable,
        }
    }

    pub fn popCount(val: Value, ty: Type, target: Target) u64 {
        assert(!val.isUndef());
        switch (val.tag()) {
            .zero, .bool_false => return 0,
            .one, .bool_true => return 1,

            .int_u64 => return @popCount(u64, val.castTag(.int_u64).?.data),

            else => {
                const info = ty.intInfo(target);

                var buffer: Value.BigIntSpace = undefined;
                const operand_bigint = val.toBigInt(&buffer);

                var limbs_buffer: [4]std.math.big.Limb = undefined;
                var result_bigint = BigIntMutable{
                    .limbs = &limbs_buffer,
                    .positive = undefined,
                    .len = undefined,
                };
                result_bigint.popCount(operand_bigint, info.bits);

                return result_bigint.toConst().to(u64) catch unreachable;
            },
        }
    }

    pub fn bitReverse(val: Value, ty: Type, target: Target, arena: Allocator) !Value {
        assert(!val.isUndef());

        const info = ty.intInfo(target);

        var buffer: Value.BigIntSpace = undefined;
        const operand_bigint = val.toBigInt(&buffer);

        const limbs = try arena.alloc(
            std.math.big.Limb,
            std.math.big.int.calcTwosCompLimbCount(info.bits),
        );
        var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
        result_bigint.bitReverse(operand_bigint, info.signedness, info.bits);

        return fromBigInt(arena, result_bigint.toConst());
    }

    pub fn byteSwap(val: Value, ty: Type, target: Target, arena: Allocator) !Value {
        assert(!val.isUndef());

        const info = ty.intInfo(target);

        // Bit count must be evenly divisible by 8
        assert(info.bits % 8 == 0);

        var buffer: Value.BigIntSpace = undefined;
        const operand_bigint = val.toBigInt(&buffer);

        const limbs = try arena.alloc(
            std.math.big.Limb,
            std.math.big.int.calcTwosCompLimbCount(info.bits),
        );
        var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
        result_bigint.byteSwap(operand_bigint, info.signedness, info.bits / 8);

        return fromBigInt(arena, result_bigint.toConst());
    }

    /// Asserts the value is an integer and not undefined.
    /// Returns the number of bits the value requires to represent stored in twos complement form.
    pub fn intBitCountTwosComp(self: Value, target: Target) usize {
        switch (self.tag()) {
            .zero,
            .bool_false,
            .the_only_possible_value,
            => return 0,

            .one,
            .bool_true,
            => return 1,

            .int_u64 => {
                const x = self.castTag(.int_u64).?.data;
                if (x == 0) return 0;
                return @intCast(usize, std.math.log2(x) + 1);
            },
            .int_big_positive => return self.castTag(.int_big_positive).?.asBigInt().bitCountTwosComp(),
            .int_big_negative => return self.castTag(.int_big_negative).?.asBigInt().bitCountTwosComp(),

            .decl_ref_mut,
            .extern_fn,
            .decl_ref,
            .function,
            .variable,
            .eu_payload_ptr,
            .opt_payload_ptr,
            => return target.cpu.arch.ptrBitWidth(),

            else => {
                var buffer: BigIntSpace = undefined;
                return self.toBigInt(&buffer).bitCountTwosComp();
            },
        }
    }

    /// Asserts the value is an integer, and the destination type is ComptimeInt or Int.
    pub fn intFitsInType(self: Value, ty: Type, target: Target) bool {
        switch (self.tag()) {
            .zero,
            .undef,
            .bool_false,
            => return true,

            .one,
            .bool_true,
            => switch (ty.zigTypeTag()) {
                .Int => {
                    const info = ty.intInfo(target);
                    return switch (info.signedness) {
                        .signed => info.bits >= 2,
                        .unsigned => info.bits >= 1,
                    };
                },
                .ComptimeInt => return true,
                else => unreachable,
            },

            .int_u64 => switch (ty.zigTypeTag()) {
                .Int => {
                    const x = self.castTag(.int_u64).?.data;
                    if (x == 0) return true;
                    const info = ty.intInfo(target);
                    const needed_bits = std.math.log2(x) + 1 + @boolToInt(info.signedness == .signed);
                    return info.bits >= needed_bits;
                },
                .ComptimeInt => return true,
                else => unreachable,
            },
            .int_i64 => switch (ty.zigTypeTag()) {
                .Int => {
                    const x = self.castTag(.int_i64).?.data;
                    if (x == 0) return true;
                    const info = ty.intInfo(target);
                    if (info.signedness == .unsigned and x < 0)
                        return false;
                    var buffer: BigIntSpace = undefined;
                    return self.toBigInt(&buffer).fitsInTwosComp(info.signedness, info.bits);
                },
                .ComptimeInt => return true,
                else => unreachable,
            },
            .int_big_positive => switch (ty.zigTypeTag()) {
                .Int => {
                    const info = ty.intInfo(target);
                    return self.castTag(.int_big_positive).?.asBigInt().fitsInTwosComp(info.signedness, info.bits);
                },
                .ComptimeInt => return true,
                else => unreachable,
            },
            .int_big_negative => switch (ty.zigTypeTag()) {
                .Int => {
                    const info = ty.intInfo(target);
                    return self.castTag(.int_big_negative).?.asBigInt().fitsInTwosComp(info.signedness, info.bits);
                },
                .ComptimeInt => return true,
                else => unreachable,
            },

            .the_only_possible_value => {
                assert(ty.intInfo(target).bits == 0);
                return true;
            },

            .decl_ref_mut,
            .extern_fn,
            .decl_ref,
            .function,
            .variable,
            => switch (ty.zigTypeTag()) {
                .Int => {
                    const info = ty.intInfo(target);
                    const ptr_bits = target.cpu.arch.ptrBitWidth();
                    return switch (info.signedness) {
                        .signed => info.bits > ptr_bits,
                        .unsigned => info.bits >= ptr_bits,
                    };
                },
                .ComptimeInt => return true,
                else => unreachable,
            },

            else => unreachable,
        }
    }

    /// Converts an integer or a float to a float. May result in a loss of information.
    /// Caller can find out by equality checking the result against the operand.
    pub fn floatCast(self: Value, arena: Allocator, dest_ty: Type, target: Target) !Value {
        switch (dest_ty.floatBits(target)) {
            16 => return Value.Tag.float_16.create(arena, self.toFloat(f16)),
            32 => return Value.Tag.float_32.create(arena, self.toFloat(f32)),
            64 => return Value.Tag.float_64.create(arena, self.toFloat(f64)),
            80 => return Value.Tag.float_80.create(arena, self.toFloat(f80)),
            128 => return Value.Tag.float_128.create(arena, self.toFloat(f128)),
            else => unreachable,
        }
    }

    /// Asserts the value is a float
    pub fn floatHasFraction(self: Value) bool {
        return switch (self.tag()) {
            .zero,
            .one,
            => false,

            .float_16 => @rem(self.castTag(.float_16).?.data, 1) != 0,
            .float_32 => @rem(self.castTag(.float_32).?.data, 1) != 0,
            .float_64 => @rem(self.castTag(.float_64).?.data, 1) != 0,
            //.float_80 => @rem(self.castTag(.float_80).?.data, 1) != 0,
            .float_80 => @panic("TODO implement __remx in compiler-rt"),
            .float_128 => @rem(self.castTag(.float_128).?.data, 1) != 0,

            else => unreachable,
        };
    }

    /// Asserts the value is numeric
    pub fn isZero(self: Value) bool {
        return switch (self.tag()) {
            .zero, .the_only_possible_value => true,
            .one => false,

            .int_u64 => self.castTag(.int_u64).?.data == 0,
            .int_i64 => self.castTag(.int_i64).?.data == 0,

            .float_16 => self.castTag(.float_16).?.data == 0,
            .float_32 => self.castTag(.float_32).?.data == 0,
            .float_64 => self.castTag(.float_64).?.data == 0,
            .float_80 => self.castTag(.float_80).?.data == 0,
            .float_128 => self.castTag(.float_128).?.data == 0,

            .int_big_positive => self.castTag(.int_big_positive).?.asBigInt().eqZero(),
            .int_big_negative => self.castTag(.int_big_negative).?.asBigInt().eqZero(),
            else => unreachable,
        };
    }

    pub fn orderAgainstZero(lhs: Value) std.math.Order {
        return switch (lhs.tag()) {
            .zero,
            .bool_false,
            .the_only_possible_value,
            => .eq,

            .one,
            .bool_true,
            .decl_ref,
            .decl_ref_mut,
            .extern_fn,
            .function,
            .variable,
            => .gt,

            .int_u64 => std.math.order(lhs.castTag(.int_u64).?.data, 0),
            .int_i64 => std.math.order(lhs.castTag(.int_i64).?.data, 0),
            .int_big_positive => lhs.castTag(.int_big_positive).?.asBigInt().orderAgainstScalar(0),
            .int_big_negative => lhs.castTag(.int_big_negative).?.asBigInt().orderAgainstScalar(0),

            .float_16 => std.math.order(lhs.castTag(.float_16).?.data, 0),
            .float_32 => std.math.order(lhs.castTag(.float_32).?.data, 0),
            .float_64 => std.math.order(lhs.castTag(.float_64).?.data, 0),
            .float_80 => std.math.order(lhs.castTag(.float_80).?.data, 0),
            .float_128 => std.math.order(lhs.castTag(.float_128).?.data, 0),

            else => unreachable,
        };
    }

    /// Asserts the value is comparable.
    pub fn order(lhs: Value, rhs: Value) std.math.Order {
        const lhs_tag = lhs.tag();
        const rhs_tag = rhs.tag();
        const lhs_against_zero = lhs.orderAgainstZero();
        const rhs_against_zero = rhs.orderAgainstZero();
        switch (lhs_against_zero) {
            .lt => if (rhs_against_zero != .lt) return .lt,
            .eq => return rhs_against_zero.invert(),
            .gt => {},
        }
        switch (rhs_against_zero) {
            .lt => if (lhs_against_zero != .lt) return .gt,
            .eq => return lhs_against_zero,
            .gt => {},
        }

        const lhs_float = lhs.isFloat();
        const rhs_float = rhs.isFloat();
        if (lhs_float and rhs_float) {
            if (lhs_tag == rhs_tag) {
                return switch (lhs.tag()) {
                    .float_16 => return std.math.order(lhs.castTag(.float_16).?.data, rhs.castTag(.float_16).?.data),
                    .float_32 => return std.math.order(lhs.castTag(.float_32).?.data, rhs.castTag(.float_32).?.data),
                    .float_64 => return std.math.order(lhs.castTag(.float_64).?.data, rhs.castTag(.float_64).?.data),
                    .float_80 => return std.math.order(lhs.castTag(.float_80).?.data, rhs.castTag(.float_80).?.data),
                    .float_128 => return std.math.order(lhs.castTag(.float_128).?.data, rhs.castTag(.float_128).?.data),
                    else => unreachable,
                };
            }
        }
        if (lhs_float or rhs_float) {
            const lhs_f128 = lhs.toFloat(f128);
            const rhs_f128 = rhs.toFloat(f128);
            return std.math.order(lhs_f128, rhs_f128);
        }

        var lhs_bigint_space: BigIntSpace = undefined;
        var rhs_bigint_space: BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_bigint_space);
        const rhs_bigint = rhs.toBigInt(&rhs_bigint_space);
        return lhs_bigint.order(rhs_bigint);
    }

    /// Asserts the value is comparable. Does not take a type parameter because it supports
    /// comparisons between heterogeneous types.
    pub fn compareHetero(lhs: Value, op: std.math.CompareOperator, rhs: Value) bool {
        if (lhs.pointerDecl()) |lhs_decl| {
            if (rhs.pointerDecl()) |rhs_decl| {
                switch (op) {
                    .eq => return lhs_decl == rhs_decl,
                    .neq => return lhs_decl != rhs_decl,
                    else => {},
                }
            } else {
                switch (op) {
                    .eq => return false,
                    .neq => return true,
                    else => {},
                }
            }
        } else if (rhs.pointerDecl()) |_| {
            switch (op) {
                .eq => return false,
                .neq => return true,
                else => {},
            }
        }
        return order(lhs, rhs).compare(op);
    }

    /// Asserts the value is comparable. Both operands have type `ty`.
    pub fn compare(lhs: Value, op: std.math.CompareOperator, rhs: Value, ty: Type) bool {
        return switch (op) {
            .eq => lhs.eql(rhs, ty),
            .neq => !lhs.eql(rhs, ty),
            else => compareHetero(lhs, op, rhs),
        };
    }

    /// Asserts the value is comparable.
    pub fn compareWithZero(lhs: Value, op: std.math.CompareOperator) bool {
        return orderAgainstZero(lhs).compare(op);
    }

    pub fn eql(a: Value, b: Value, ty: Type) bool {
        const a_tag = a.tag();
        const b_tag = b.tag();
        assert(a_tag != .undef);
        assert(b_tag != .undef);
        if (a_tag == b_tag) switch (a_tag) {
            .void_value, .null_value, .the_only_possible_value => return true,
            .enum_literal => {
                const a_name = a.castTag(.enum_literal).?.data;
                const b_name = b.castTag(.enum_literal).?.data;
                return std.mem.eql(u8, a_name, b_name);
            },
            .enum_field_index => {
                const a_field_index = a.castTag(.enum_field_index).?.data;
                const b_field_index = b.castTag(.enum_field_index).?.data;
                return a_field_index == b_field_index;
            },
            .opt_payload => {
                const a_payload = a.castTag(.opt_payload).?.data;
                const b_payload = b.castTag(.opt_payload).?.data;
                var buffer: Type.Payload.ElemType = undefined;
                return eql(a_payload, b_payload, ty.optionalChild(&buffer));
            },
            .slice => {
                const a_payload = a.castTag(.slice).?.data;
                const b_payload = b.castTag(.slice).?.data;
                if (!eql(a_payload.len, b_payload.len, Type.usize)) return false;

                var ptr_buf: Type.SlicePtrFieldTypeBuffer = undefined;
                const ptr_ty = ty.slicePtrFieldType(&ptr_buf);

                return eql(a_payload.ptr, b_payload.ptr, ptr_ty);
            },
            .elem_ptr => @panic("TODO: Implement more pointer eql cases"),
            .field_ptr => @panic("TODO: Implement more pointer eql cases"),
            .eu_payload_ptr => @panic("TODO: Implement more pointer eql cases"),
            .opt_payload_ptr => @panic("TODO: Implement more pointer eql cases"),
            .array => {
                const a_array = a.castTag(.array).?.data;
                const b_array = b.castTag(.array).?.data;

                if (a_array.len != b_array.len) return false;

                const elem_ty = ty.childType();
                for (a_array) |a_elem, i| {
                    const b_elem = b_array[i];

                    if (!eql(a_elem, b_elem, elem_ty)) return false;
                }
                return true;
            },
            .function => {
                const a_payload = a.castTag(.function).?.data;
                const b_payload = b.castTag(.function).?.data;
                return a_payload == b_payload;
            },
            .@"struct" => {
                const fields = ty.structFields().values();
                const a_field_vals = a.castTag(.@"struct").?.data;
                const b_field_vals = b.castTag(.@"struct").?.data;
                assert(a_field_vals.len == b_field_vals.len);
                assert(fields.len == a_field_vals.len);
                for (fields) |field, i| {
                    if (!eql(a_field_vals[i], b_field_vals[i], field.ty)) return false;
                }
                return true;
            },
            else => {},
        } else if (a_tag == .null_value or b_tag == .null_value) {
            return false;
        }

        if (a.pointerDecl()) |a_decl| {
            if (b.pointerDecl()) |b_decl| {
                return a_decl == b_decl;
            } else {
                return false;
            }
        } else if (b.pointerDecl()) |_| {
            return false;
        }

        switch (ty.zigTypeTag()) {
            .Type => {
                var buf_a: ToTypeBuffer = undefined;
                var buf_b: ToTypeBuffer = undefined;
                const a_type = a.toType(&buf_a);
                const b_type = b.toType(&buf_b);
                return a_type.eql(b_type);
            },
            .Enum => {
                var buf_a: Payload.U64 = undefined;
                var buf_b: Payload.U64 = undefined;
                const a_val = a.enumToInt(ty, &buf_a);
                const b_val = b.enumToInt(ty, &buf_b);
                var buf_ty: Type.Payload.Bits = undefined;
                const int_ty = ty.intTagType(&buf_ty);
                return eql(a_val, b_val, int_ty);
            },
            .Array, .Vector => {
                const len = ty.arrayLen();
                const elem_ty = ty.childType();
                var i: usize = 0;
                var a_buf: ElemValueBuffer = undefined;
                var b_buf: ElemValueBuffer = undefined;
                while (i < len) : (i += 1) {
                    const a_elem = elemValueBuffer(a, i, &a_buf);
                    const b_elem = elemValueBuffer(b, i, &b_buf);
                    if (!eql(a_elem, b_elem, elem_ty)) return false;
                }
                return true;
            },
            .Struct => {
                // must be a struct with no fields since we checked for if
                // both have the struct tag above.
                const fields = ty.structFields().values();
                assert(fields.len == 0);
                return true;
            },
            else => return order(a, b).compare(.eq),
        }
    }

    pub fn hash(val: Value, ty: Type, hasher: *std.hash.Wyhash) void {
        const zig_ty_tag = ty.zigTypeTag();
        std.hash.autoHash(hasher, zig_ty_tag);
        if (val.isUndef()) return;

        switch (zig_ty_tag) {
            .BoundFn => unreachable, // TODO remove this from the language
            .Opaque => unreachable, // Cannot hash opaque types

            .Void,
            .NoReturn,
            .Undefined,
            .Null,
            => {},

            .Type => {
                var buf: ToTypeBuffer = undefined;
                return val.toType(&buf).hashWithHasher(hasher);
            },
            .Float, .ComptimeFloat => {
                // TODO double check the lang spec. should we to bitwise hashing here,
                // or a hash that normalizes the float value?
                const float = val.toFloat(f128);
                std.hash.autoHash(hasher, @bitCast(u128, float));
            },
            .Bool, .Int, .ComptimeInt, .Pointer => switch (val.tag()) {
                .slice => {
                    const slice = val.castTag(.slice).?.data;
                    var ptr_buf: Type.SlicePtrFieldTypeBuffer = undefined;
                    const ptr_ty = ty.slicePtrFieldType(&ptr_buf);
                    hash(slice.ptr, ptr_ty, hasher);
                    hash(slice.len, Type.usize, hasher);
                },

                else => return hashPtr(val, hasher),
            },
            .Array, .Vector => {
                const len = ty.arrayLen();
                const elem_ty = ty.childType();
                var index: usize = 0;
                var elem_value_buf: ElemValueBuffer = undefined;
                while (index < len) : (index += 1) {
                    const elem_val = val.elemValueBuffer(index, &elem_value_buf);
                    elem_val.hash(elem_ty, hasher);
                }
            },
            .Struct => {
                const fields = ty.structFields().values();
                if (fields.len == 0) return;
                const field_values = val.castTag(.@"struct").?.data;
                for (field_values) |field_val, i| {
                    field_val.hash(fields[i].ty, hasher);
                }
            },
            .Optional => {
                if (val.castTag(.opt_payload)) |payload| {
                    std.hash.autoHash(hasher, true); // non-null
                    const sub_val = payload.data;
                    var buffer: Type.Payload.ElemType = undefined;
                    const sub_ty = ty.optionalChild(&buffer);
                    sub_val.hash(sub_ty, hasher);
                } else {
                    std.hash.autoHash(hasher, false); // non-null
                }
            },
            .ErrorUnion => {
                @panic("TODO implement hashing error union values");
            },
            .ErrorSet => {
                @panic("TODO implement hashing error set values");
            },
            .Enum => {
                var enum_space: Payload.U64 = undefined;
                const int_val = val.enumToInt(ty, &enum_space);
                hashInt(int_val, hasher);
            },
            .Union => {
                const union_obj = val.cast(Payload.Union).?.data;
                if (ty.unionTagType()) |tag_ty| {
                    union_obj.tag.hash(tag_ty, hasher);
                }
                const active_field_ty = ty.unionFieldType(union_obj.tag);
                union_obj.val.hash(active_field_ty, hasher);
            },
            .Fn => {
                const func: *Module.Fn = val.castTag(.function).?.data;
                // Note that his hashes the *Fn rather than the *Decl. This is
                // to differentiate function bodies from function pointers.
                // This is currently redundant since we already hash the zig type tag
                // at the top of this function.
                std.hash.autoHash(hasher, func);
            },
            .Frame => {
                @panic("TODO implement hashing frame values");
            },
            .AnyFrame => {
                @panic("TODO implement hashing anyframe values");
            },
            .EnumLiteral => {
                const bytes = val.castTag(.enum_literal).?.data;
                hasher.update(bytes);
            },
        }
    }

    pub const ArrayHashContext = struct {
        ty: Type,

        pub fn hash(self: @This(), val: Value) u32 {
            const other_context: HashContext = .{ .ty = self.ty };
            return @truncate(u32, other_context.hash(val));
        }
        pub fn eql(self: @This(), a: Value, b: Value, b_index: usize) bool {
            _ = b_index;
            return a.eql(b, self.ty);
        }
    };

    pub const HashContext = struct {
        ty: Type,

        pub fn hash(self: @This(), val: Value) u64 {
            var hasher = std.hash.Wyhash.init(0);
            val.hash(self.ty, &hasher);
            return hasher.final();
        }

        pub fn eql(self: @This(), a: Value, b: Value) bool {
            return a.eql(b, self.ty);
        }
    };

    pub fn isComptimeMutablePtr(val: Value) bool {
        return switch (val.tag()) {
            .decl_ref_mut => true,
            .elem_ptr => isComptimeMutablePtr(val.castTag(.elem_ptr).?.data.array_ptr),
            .field_ptr => isComptimeMutablePtr(val.castTag(.field_ptr).?.data.container_ptr),
            .eu_payload_ptr => isComptimeMutablePtr(val.castTag(.eu_payload_ptr).?.data),
            .opt_payload_ptr => isComptimeMutablePtr(val.castTag(.opt_payload_ptr).?.data),

            else => false,
        };
    }

    /// Gets the decl referenced by this pointer.  If the pointer does not point
    /// to a decl, or if it points to some part of a decl (like field_ptr or element_ptr),
    /// this function returns null.
    pub fn pointerDecl(val: Value) ?*Module.Decl {
        return switch (val.tag()) {
            .decl_ref_mut => val.castTag(.decl_ref_mut).?.data.decl,
            .extern_fn => val.castTag(.extern_fn).?.data.owner_decl,
            .function => val.castTag(.function).?.data.owner_decl,
            .variable => val.castTag(.variable).?.data.owner_decl,
            .decl_ref => val.cast(Payload.Decl).?.data,
            else => null,
        };
    }

    fn hashInt(int_val: Value, hasher: *std.hash.Wyhash) void {
        var buffer: BigIntSpace = undefined;
        const big = int_val.toBigInt(&buffer);
        std.hash.autoHash(hasher, big.positive);
        for (big.limbs) |limb| {
            std.hash.autoHash(hasher, limb);
        }
    }

    fn hashPtr(ptr_val: Value, hasher: *std.hash.Wyhash) void {
        switch (ptr_val.tag()) {
            .decl_ref,
            .decl_ref_mut,
            .extern_fn,
            .function,
            .variable,
            => {
                const decl: *Module.Decl = ptr_val.pointerDecl().?;
                std.hash.autoHash(hasher, decl);
            },

            .elem_ptr => {
                const elem_ptr = ptr_val.castTag(.elem_ptr).?.data;
                hashPtr(elem_ptr.array_ptr, hasher);
                std.hash.autoHash(hasher, Value.Tag.elem_ptr);
                std.hash.autoHash(hasher, elem_ptr.index);
            },
            .field_ptr => {
                const field_ptr = ptr_val.castTag(.field_ptr).?.data;
                std.hash.autoHash(hasher, Value.Tag.field_ptr);
                hashPtr(field_ptr.container_ptr, hasher);
                std.hash.autoHash(hasher, field_ptr.field_index);
            },
            .eu_payload_ptr => {
                const err_union_ptr = ptr_val.castTag(.eu_payload_ptr).?.data;
                std.hash.autoHash(hasher, Value.Tag.eu_payload_ptr);
                hashPtr(err_union_ptr, hasher);
            },
            .opt_payload_ptr => {
                const opt_ptr = ptr_val.castTag(.opt_payload_ptr).?.data;
                std.hash.autoHash(hasher, Value.Tag.opt_payload_ptr);
                hashPtr(opt_ptr, hasher);
            },

            .zero,
            .one,
            .int_u64,
            .int_i64,
            .int_big_positive,
            .int_big_negative,
            .bool_false,
            .bool_true,
            .the_only_possible_value,
            => return hashInt(ptr_val, hasher),

            else => unreachable,
        }
    }

    pub fn markReferencedDeclsAlive(val: Value) void {
        switch (val.tag()) {
            .decl_ref_mut => return val.castTag(.decl_ref_mut).?.data.decl.markAlive(),
            .extern_fn => return val.castTag(.extern_fn).?.data.owner_decl.markAlive(),
            .function => return val.castTag(.function).?.data.owner_decl.markAlive(),
            .variable => return val.castTag(.variable).?.data.owner_decl.markAlive(),
            .decl_ref => return val.cast(Payload.Decl).?.data.markAlive(),

            .repeated,
            .eu_payload,
            .eu_payload_ptr,
            .opt_payload,
            .opt_payload_ptr,
            .empty_array_sentinel,
            => return markReferencedDeclsAlive(val.cast(Payload.SubValue).?.data),

            .array => {
                for (val.cast(Payload.Array).?.data) |elem_val| {
                    markReferencedDeclsAlive(elem_val);
                }
            },
            .slice => {
                const slice = val.cast(Payload.Slice).?.data;
                markReferencedDeclsAlive(slice.ptr);
                markReferencedDeclsAlive(slice.len);
            },

            .elem_ptr => {
                const elem_ptr = val.cast(Payload.ElemPtr).?.data;
                return markReferencedDeclsAlive(elem_ptr.array_ptr);
            },
            .field_ptr => {
                const field_ptr = val.cast(Payload.FieldPtr).?.data;
                return markReferencedDeclsAlive(field_ptr.container_ptr);
            },
            .@"struct" => {
                for (val.cast(Payload.Struct).?.data) |field_val| {
                    markReferencedDeclsAlive(field_val);
                }
            },
            .@"union" => {
                const data = val.cast(Payload.Union).?.data;
                markReferencedDeclsAlive(data.tag);
                markReferencedDeclsAlive(data.val);
            },

            else => {},
        }
    }

    pub fn slicePtr(val: Value) Value {
        return switch (val.tag()) {
            .slice => val.castTag(.slice).?.data.ptr,
            // TODO this should require being a slice tag, and not allow decl_ref, field_ptr, etc.
            .decl_ref, .decl_ref_mut, .field_ptr, .elem_ptr => val,
            else => unreachable,
        };
    }

    pub fn sliceLen(val: Value) u64 {
        return switch (val.tag()) {
            .slice => val.castTag(.slice).?.data.len.toUnsignedInt(),
            .decl_ref => {
                const decl = val.castTag(.decl_ref).?.data;
                if (decl.ty.zigTypeTag() == .Array) {
                    return decl.ty.arrayLen();
                } else {
                    return 1;
                }
            },
            else => unreachable,
        };
    }

    /// Asserts the value is a single-item pointer to an array, or an array,
    /// or an unknown-length pointer, and returns the element value at the index.
    pub fn elemValue(val: Value, arena: Allocator, index: usize) !Value {
        return elemValueAdvanced(val, index, arena, undefined);
    }

    pub const ElemValueBuffer = Payload.U64;

    pub fn elemValueBuffer(val: Value, index: usize, buffer: *ElemValueBuffer) Value {
        return elemValueAdvanced(val, index, null, buffer) catch unreachable;
    }

    pub fn elemValueAdvanced(
        val: Value,
        index: usize,
        arena: ?Allocator,
        buffer: *ElemValueBuffer,
    ) error{OutOfMemory}!Value {
        switch (val.tag()) {
            .empty_array => unreachable, // out of bounds array index
            .empty_struct_value => unreachable, // out of bounds array index

            .empty_array_sentinel => {
                assert(index == 0); // The only valid index for an empty array with sentinel.
                return val.castTag(.empty_array_sentinel).?.data;
            },

            .bytes => {
                const byte = val.castTag(.bytes).?.data[index];
                if (arena) |a| {
                    return Tag.int_u64.create(a, byte);
                } else {
                    buffer.* = .{
                        .base = .{ .tag = .int_u64 },
                        .data = byte,
                    };
                    return initPayload(&buffer.base);
                }
            },

            // No matter the index; all the elements are the same!
            .repeated => return val.castTag(.repeated).?.data,

            .array => return val.castTag(.array).?.data[index],
            .slice => return val.castTag(.slice).?.data.ptr.elemValueAdvanced(index, arena, buffer),

            .decl_ref => return val.castTag(.decl_ref).?.data.val.elemValueAdvanced(index, arena, buffer),
            .decl_ref_mut => return val.castTag(.decl_ref_mut).?.data.decl.val.elemValueAdvanced(index, arena, buffer),
            .elem_ptr => {
                const data = val.castTag(.elem_ptr).?.data;
                return data.array_ptr.elemValueAdvanced(index + data.index, arena, buffer);
            },

            // The child type of arrays which have only one possible value need
            // to have only one possible value itself.
            .the_only_possible_value => return val,

            else => unreachable,
        }
    }

    pub fn fieldValue(val: Value, allocator: Allocator, index: usize) error{OutOfMemory}!Value {
        _ = allocator;
        switch (val.tag()) {
            .@"struct" => {
                const field_values = val.castTag(.@"struct").?.data;
                return field_values[index];
            },
            .@"union" => {
                const payload = val.castTag(.@"union").?.data;
                // TODO assert the tag is correct
                return payload.val;
            },
            // Structs which have only one possible value need to consist of members which have only one possible value.
            .the_only_possible_value => return val,

            else => unreachable,
        }
    }

    pub fn unionTag(val: Value) Value {
        switch (val.tag()) {
            .undef, .enum_field_index => return val,
            .@"union" => return val.castTag(.@"union").?.data.tag,
            else => unreachable,
        }
    }

    /// Returns a pointer to the element value at the index.
    pub fn elemPtr(self: Value, allocator: Allocator, index: usize) !Value {
        switch (self.tag()) {
            .elem_ptr => {
                const elem_ptr = self.castTag(.elem_ptr).?.data;
                return Tag.elem_ptr.create(allocator, .{
                    .array_ptr = elem_ptr.array_ptr,
                    .index = elem_ptr.index + index,
                });
            },
            .slice => return Tag.elem_ptr.create(allocator, .{
                .array_ptr = self.castTag(.slice).?.data.ptr,
                .index = index,
            }),
            else => return Tag.elem_ptr.create(allocator, .{
                .array_ptr = self,
                .index = index,
            }),
        }
    }

    pub fn isUndef(self: Value) bool {
        return self.tag() == .undef;
    }

    /// TODO: check for cases such as array that is not marked undef but all the element
    /// values are marked undef, or struct that is not marked undef but all fields are marked
    /// undef, etc.
    pub fn isUndefDeep(self: Value) bool {
        return self.isUndef();
    }

    /// Asserts the value is not undefined and not unreachable.
    /// Integer value 0 is considered null because of C pointers.
    pub fn isNull(self: Value) bool {
        return switch (self.tag()) {
            .null_value => true,
            .opt_payload => false,

            // If it's not one of those two tags then it must be a C pointer value,
            // in which case the value 0 is null and other values are non-null.

            .zero,
            .bool_false,
            .the_only_possible_value,
            => true,

            .one,
            .bool_true,
            => false,

            .int_u64,
            .int_i64,
            .int_big_positive,
            .int_big_negative,
            => compareWithZero(self, .eq),

            .undef => unreachable,
            .unreachable_value => unreachable,
            .inferred_alloc => unreachable,
            .inferred_alloc_comptime => unreachable,

            else => false,
        };
    }

    /// Valid for all types. Asserts the value is not undefined and not unreachable.
    /// Prefer `errorUnionIsPayload` to find out whether something is an error or not
    /// because it works without having to figure out the string.
    pub fn getError(self: Value) ?[]const u8 {
        return switch (self.tag()) {
            .@"error" => self.castTag(.@"error").?.data.name,
            .int_u64 => @panic("TODO"),
            .int_i64 => @panic("TODO"),
            .int_big_positive => @panic("TODO"),
            .int_big_negative => @panic("TODO"),
            .one => @panic("TODO"),
            .undef => unreachable,
            .unreachable_value => unreachable,
            .inferred_alloc => unreachable,
            .inferred_alloc_comptime => unreachable,

            else => null,
        };
    }

    /// Assumes the type is an error union. Returns true if and only if the value is
    /// the error union payload, not an error.
    pub fn errorUnionIsPayload(val: Value) bool {
        return switch (val.tag()) {
            .eu_payload => true,
            else => false,

            .undef => unreachable,
            .inferred_alloc => unreachable,
            .inferred_alloc_comptime => unreachable,
        };
    }

    /// Valid for all types. Asserts the value is not undefined.
    pub fn isFloat(self: Value) bool {
        return switch (self.tag()) {
            .undef => unreachable,
            .inferred_alloc => unreachable,
            .inferred_alloc_comptime => unreachable,

            .float_16,
            .float_32,
            .float_64,
            .float_80,
            .float_128,
            => true,
            else => false,
        };
    }

    pub fn intToFloat(val: Value, arena: Allocator, dest_ty: Type, target: Target) !Value {
        switch (val.tag()) {
            .undef, .zero, .one => return val,
            .the_only_possible_value => return Value.initTag(.zero), // for i0, u0
            .int_u64 => {
                return intToFloatInner(val.castTag(.int_u64).?.data, arena, dest_ty, target);
            },
            .int_i64 => {
                return intToFloatInner(val.castTag(.int_i64).?.data, arena, dest_ty, target);
            },
            .int_big_positive => {
                const limbs = val.castTag(.int_big_positive).?.data;
                const float = bigIntToFloat(limbs, true);
                return floatToValue(float, arena, dest_ty, target);
            },
            .int_big_negative => {
                const limbs = val.castTag(.int_big_negative).?.data;
                const float = bigIntToFloat(limbs, false);
                return floatToValue(float, arena, dest_ty, target);
            },
            else => unreachable,
        }
    }

    fn intToFloatInner(x: anytype, arena: Allocator, dest_ty: Type, target: Target) !Value {
        switch (dest_ty.floatBits(target)) {
            16 => return Value.Tag.float_16.create(arena, @intToFloat(f16, x)),
            32 => return Value.Tag.float_32.create(arena, @intToFloat(f32, x)),
            64 => return Value.Tag.float_64.create(arena, @intToFloat(f64, x)),
            // We can't lower this properly on non-x86 llvm backends yet
            //80 => return Value.Tag.float_80.create(arena, @intToFloat(f80, x)),
            80 => @panic("TODO f80 intToFloat"),
            128 => return Value.Tag.float_128.create(arena, @intToFloat(f128, x)),
            else => unreachable,
        }
    }

    fn floatToValue(float: f128, arena: Allocator, dest_ty: Type, target: Target) !Value {
        switch (dest_ty.floatBits(target)) {
            16 => return Value.Tag.float_16.create(arena, @floatCast(f16, float)),
            32 => return Value.Tag.float_32.create(arena, @floatCast(f32, float)),
            64 => return Value.Tag.float_64.create(arena, @floatCast(f64, float)),
            80 => return Value.Tag.float_80.create(arena, @floatCast(f80, float)),
            128 => return Value.Tag.float_128.create(arena, float),
            else => unreachable,
        }
    }

    pub fn floatToInt(val: Value, arena: Allocator, dest_ty: Type, target: Target) error{ FloatCannotFit, OutOfMemory }!Value {
        const Limb = std.math.big.Limb;

        var value = val.toFloat(f64); // TODO: f128 ?
        if (std.math.isNan(value) or std.math.isInf(value)) {
            return error.FloatCannotFit;
        }

        const isNegative = std.math.signbit(value);
        value = std.math.fabs(value);

        const floored = std.math.floor(value);

        var rational = try std.math.big.Rational.init(arena);
        defer rational.deinit();
        rational.setFloat(f64, floored) catch |err| switch (err) {
            error.NonFiniteFloat => unreachable,
            error.OutOfMemory => return error.OutOfMemory,
        };

        // The float is reduced in rational.setFloat, so we assert that denominator is equal to one
        const bigOne = std.math.big.int.Const{ .limbs = &.{1}, .positive = true };
        assert(rational.q.toConst().eqAbs(bigOne));

        const result_limbs = try arena.dupe(Limb, rational.p.toConst().limbs);
        const result = if (isNegative)
            try Value.Tag.int_big_negative.create(arena, result_limbs)
        else
            try Value.Tag.int_big_positive.create(arena, result_limbs);

        if (result.intFitsInType(dest_ty, target)) {
            return result;
        } else {
            return error.FloatCannotFit;
        }
    }

    fn calcLimbLenFloat(scalar: anytype) usize {
        if (scalar == 0) {
            return 1;
        }

        const w_value = std.math.fabs(scalar);
        return @divFloor(@floatToInt(std.math.big.Limb, std.math.log2(w_value)), @typeInfo(std.math.big.Limb).Int.bits) + 1;
    }

    pub const OverflowArithmeticResult = struct {
        overflowed: bool,
        wrapped_result: Value,
    };

    pub fn intAddWithOverflow(
        lhs: Value,
        rhs: Value,
        ty: Type,
        arena: Allocator,
        target: Target,
    ) !OverflowArithmeticResult {
        const info = ty.intInfo(target);

        var lhs_space: Value.BigIntSpace = undefined;
        var rhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const rhs_bigint = rhs.toBigInt(&rhs_space);
        const limbs = try arena.alloc(
            std.math.big.Limb,
            std.math.big.int.calcTwosCompLimbCount(info.bits),
        );
        var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
        const overflowed = result_bigint.addWrap(lhs_bigint, rhs_bigint, info.signedness, info.bits);
        const result = try fromBigInt(arena, result_bigint.toConst());
        return OverflowArithmeticResult{
            .overflowed = overflowed,
            .wrapped_result = result,
        };
    }

    /// Supports both floats and ints; handles undefined.
    pub fn numberAddWrap(
        lhs: Value,
        rhs: Value,
        ty: Type,
        arena: Allocator,
        target: Target,
    ) !Value {
        if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);

        if (ty.zigTypeTag() == .ComptimeInt) {
            return intAdd(lhs, rhs, arena);
        }

        if (ty.isAnyFloat()) {
            return floatAdd(lhs, rhs, ty, arena, target);
        }

        const overflow_result = try intAddWithOverflow(lhs, rhs, ty, arena, target);
        return overflow_result.wrapped_result;
    }

    fn fromBigInt(arena: Allocator, big_int: BigIntConst) !Value {
        if (big_int.positive) {
            if (big_int.to(u64)) |x| {
                return Value.Tag.int_u64.create(arena, x);
            } else |_| {
                return Value.Tag.int_big_positive.create(arena, big_int.limbs);
            }
        } else {
            if (big_int.to(i64)) |x| {
                return Value.Tag.int_i64.create(arena, x);
            } else |_| {
                return Value.Tag.int_big_negative.create(arena, big_int.limbs);
            }
        }
    }

    /// Supports integers only; asserts neither operand is undefined.
    pub fn intAddSat(
        lhs: Value,
        rhs: Value,
        ty: Type,
        arena: Allocator,
        target: Target,
    ) !Value {
        assert(!lhs.isUndef());
        assert(!rhs.isUndef());

        const info = ty.intInfo(target);

        var lhs_space: Value.BigIntSpace = undefined;
        var rhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const rhs_bigint = rhs.toBigInt(&rhs_space);
        const limbs = try arena.alloc(
            std.math.big.Limb,
            std.math.big.int.calcTwosCompLimbCount(info.bits),
        );
        var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
        result_bigint.addSat(lhs_bigint, rhs_bigint, info.signedness, info.bits);
        return fromBigInt(arena, result_bigint.toConst());
    }

    pub fn intSubWithOverflow(
        lhs: Value,
        rhs: Value,
        ty: Type,
        arena: Allocator,
        target: Target,
    ) !OverflowArithmeticResult {
        const info = ty.intInfo(target);

        var lhs_space: Value.BigIntSpace = undefined;
        var rhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const rhs_bigint = rhs.toBigInt(&rhs_space);
        const limbs = try arena.alloc(
            std.math.big.Limb,
            std.math.big.int.calcTwosCompLimbCount(info.bits),
        );
        var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
        const overflowed = result_bigint.subWrap(lhs_bigint, rhs_bigint, info.signedness, info.bits);
        const wrapped_result = try fromBigInt(arena, result_bigint.toConst());
        return OverflowArithmeticResult{
            .overflowed = overflowed,
            .wrapped_result = wrapped_result,
        };
    }

    /// Supports both floats and ints; handles undefined.
    pub fn numberSubWrap(
        lhs: Value,
        rhs: Value,
        ty: Type,
        arena: Allocator,
        target: Target,
    ) !Value {
        if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);

        if (ty.zigTypeTag() == .ComptimeInt) {
            return intSub(lhs, rhs, arena);
        }

        if (ty.isAnyFloat()) {
            return floatSub(lhs, rhs, ty, arena, target);
        }

        const overflow_result = try intSubWithOverflow(lhs, rhs, ty, arena, target);
        return overflow_result.wrapped_result;
    }

    /// Supports integers only; asserts neither operand is undefined.
    pub fn intSubSat(
        lhs: Value,
        rhs: Value,
        ty: Type,
        arena: Allocator,
        target: Target,
    ) !Value {
        assert(!lhs.isUndef());
        assert(!rhs.isUndef());

        const info = ty.intInfo(target);

        var lhs_space: Value.BigIntSpace = undefined;
        var rhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const rhs_bigint = rhs.toBigInt(&rhs_space);
        const limbs = try arena.alloc(
            std.math.big.Limb,
            std.math.big.int.calcTwosCompLimbCount(info.bits),
        );
        var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
        result_bigint.subSat(lhs_bigint, rhs_bigint, info.signedness, info.bits);
        return fromBigInt(arena, result_bigint.toConst());
    }

    pub fn intMulWithOverflow(
        lhs: Value,
        rhs: Value,
        ty: Type,
        arena: Allocator,
        target: Target,
    ) !OverflowArithmeticResult {
        const info = ty.intInfo(target);

        var lhs_space: Value.BigIntSpace = undefined;
        var rhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const rhs_bigint = rhs.toBigInt(&rhs_space);
        const limbs = try arena.alloc(
            std.math.big.Limb,
            lhs_bigint.limbs.len + rhs_bigint.limbs.len,
        );
        var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
        var limbs_buffer = try arena.alloc(
            std.math.big.Limb,
            std.math.big.int.calcMulLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len, 1),
        );
        result_bigint.mul(lhs_bigint, rhs_bigint, limbs_buffer, arena);

        const overflowed = !result_bigint.toConst().fitsInTwosComp(info.signedness, info.bits);
        if (overflowed) {
            result_bigint.truncate(result_bigint.toConst(), info.signedness, info.bits);
        }

        return OverflowArithmeticResult{
            .overflowed = overflowed,
            .wrapped_result = try fromBigInt(arena, result_bigint.toConst()),
        };
    }

    /// Supports both floats and ints; handles undefined.
    pub fn numberMulWrap(
        lhs: Value,
        rhs: Value,
        ty: Type,
        arena: Allocator,
        target: Target,
    ) !Value {
        if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);

        if (ty.zigTypeTag() == .ComptimeInt) {
            return intMul(lhs, rhs, arena);
        }

        if (ty.isAnyFloat()) {
            return floatMul(lhs, rhs, ty, arena, target);
        }

        const overflow_result = try intMulWithOverflow(lhs, rhs, ty, arena, target);
        return overflow_result.wrapped_result;
    }

    /// Supports integers only; asserts neither operand is undefined.
    pub fn intMulSat(
        lhs: Value,
        rhs: Value,
        ty: Type,
        arena: Allocator,
        target: Target,
    ) !Value {
        assert(!lhs.isUndef());
        assert(!rhs.isUndef());

        const info = ty.intInfo(target);

        var lhs_space: Value.BigIntSpace = undefined;
        var rhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const rhs_bigint = rhs.toBigInt(&rhs_space);
        const limbs = try arena.alloc(
            std.math.big.Limb,
            std.math.max(
                // For the saturate
                std.math.big.int.calcTwosCompLimbCount(info.bits),
                lhs_bigint.limbs.len + rhs_bigint.limbs.len,
            ),
        );
        var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
        var limbs_buffer = try arena.alloc(
            std.math.big.Limb,
            std.math.big.int.calcMulLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len, 1),
        );
        result_bigint.mul(lhs_bigint, rhs_bigint, limbs_buffer, arena);
        result_bigint.saturate(result_bigint.toConst(), info.signedness, info.bits);
        return fromBigInt(arena, result_bigint.toConst());
    }

    /// Supports both floats and ints; handles undefined.
    pub fn numberMax(lhs: Value, rhs: Value) !Value {
        if (lhs.isUndef() or rhs.isUndef()) return undef;
        if (lhs.isNan()) return rhs;
        if (rhs.isNan()) return lhs;

        return switch (order(lhs, rhs)) {
            .lt => rhs,
            .gt, .eq => lhs,
        };
    }

    /// Supports both floats and ints; handles undefined.
    pub fn numberMin(lhs: Value, rhs: Value) !Value {
        if (lhs.isUndef() or rhs.isUndef()) return undef;
        if (lhs.isNan()) return rhs;
        if (rhs.isNan()) return lhs;

        return switch (order(lhs, rhs)) {
            .lt => lhs,
            .gt, .eq => rhs,
        };
    }

    /// operands must be integers; handles undefined.
    pub fn bitwiseNot(val: Value, ty: Type, arena: Allocator, target: Target) !Value {
        if (val.isUndef()) return Value.initTag(.undef);

        const info = ty.intInfo(target);

        // TODO is this a performance issue? maybe we should try the operation without
        // resorting to BigInt first.
        var val_space: Value.BigIntSpace = undefined;
        const val_bigint = val.toBigInt(&val_space);
        const limbs = try arena.alloc(
            std.math.big.Limb,
            std.math.big.int.calcTwosCompLimbCount(info.bits),
        );

        var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
        result_bigint.bitNotWrap(val_bigint, info.signedness, info.bits);
        return fromBigInt(arena, result_bigint.toConst());
    }

    /// operands must be integers; handles undefined. 
    pub fn bitwiseAnd(lhs: Value, rhs: Value, arena: Allocator) !Value {
        if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);

        // TODO is this a performance issue? maybe we should try the operation without
        // resorting to BigInt first.
        var lhs_space: Value.BigIntSpace = undefined;
        var rhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const rhs_bigint = rhs.toBigInt(&rhs_space);
        const limbs = try arena.alloc(
            std.math.big.Limb,
            // + 1 for negatives
            std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
        );
        var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
        result_bigint.bitAnd(lhs_bigint, rhs_bigint);
        return fromBigInt(arena, result_bigint.toConst());
    }

    /// operands must be integers; handles undefined. 
    pub fn bitwiseNand(lhs: Value, rhs: Value, ty: Type, arena: Allocator, target: Target) !Value {
        if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);

        const anded = try bitwiseAnd(lhs, rhs, arena);

        const all_ones = if (ty.isSignedInt())
            try Value.Tag.int_i64.create(arena, -1)
        else
            try ty.maxInt(arena, target);

        return bitwiseXor(anded, all_ones, arena);
    }

    /// operands must be integers; handles undefined. 
    pub fn bitwiseOr(lhs: Value, rhs: Value, arena: Allocator) !Value {
        if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);

        // TODO is this a performance issue? maybe we should try the operation without
        // resorting to BigInt first.
        var lhs_space: Value.BigIntSpace = undefined;
        var rhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const rhs_bigint = rhs.toBigInt(&rhs_space);
        const limbs = try arena.alloc(
            std.math.big.Limb,
            std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len),
        );
        var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
        result_bigint.bitOr(lhs_bigint, rhs_bigint);
        return fromBigInt(arena, result_bigint.toConst());
    }

    /// operands must be integers; handles undefined. 
    pub fn bitwiseXor(lhs: Value, rhs: Value, arena: Allocator) !Value {
        if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);

        // TODO is this a performance issue? maybe we should try the operation without
        // resorting to BigInt first.
        var lhs_space: Value.BigIntSpace = undefined;
        var rhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const rhs_bigint = rhs.toBigInt(&rhs_space);
        const limbs = try arena.alloc(
            std.math.big.Limb,
            // + 1 for negatives
            std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
        );
        var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
        result_bigint.bitXor(lhs_bigint, rhs_bigint);
        return fromBigInt(arena, result_bigint.toConst());
    }

    pub fn intAdd(lhs: Value, rhs: Value, allocator: Allocator) !Value {
        // TODO is this a performance issue? maybe we should try the operation without
        // resorting to BigInt first.
        var lhs_space: Value.BigIntSpace = undefined;
        var rhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const rhs_bigint = rhs.toBigInt(&rhs_space);
        const limbs = try allocator.alloc(
            std.math.big.Limb,
            std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
        );
        var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
        result_bigint.add(lhs_bigint, rhs_bigint);
        return fromBigInt(allocator, result_bigint.toConst());
    }

    pub fn intSub(lhs: Value, rhs: Value, allocator: Allocator) !Value {
        // TODO is this a performance issue? maybe we should try the operation without
        // resorting to BigInt first.
        var lhs_space: Value.BigIntSpace = undefined;
        var rhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const rhs_bigint = rhs.toBigInt(&rhs_space);
        const limbs = try allocator.alloc(
            std.math.big.Limb,
            std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
        );
        var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
        result_bigint.sub(lhs_bigint, rhs_bigint);
        return fromBigInt(allocator, result_bigint.toConst());
    }

    pub fn intDiv(lhs: Value, rhs: Value, allocator: Allocator) !Value {
        // TODO is this a performance issue? maybe we should try the operation without
        // resorting to BigInt first.
        var lhs_space: Value.BigIntSpace = undefined;
        var rhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const rhs_bigint = rhs.toBigInt(&rhs_space);
        const limbs_q = try allocator.alloc(
            std.math.big.Limb,
            lhs_bigint.limbs.len,
        );
        const limbs_r = try allocator.alloc(
            std.math.big.Limb,
            rhs_bigint.limbs.len,
        );
        const limbs_buffer = try allocator.alloc(
            std.math.big.Limb,
            std.math.big.int.calcDivLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len),
        );
        var result_q = BigIntMutable{ .limbs = limbs_q, .positive = undefined, .len = undefined };
        var result_r = BigIntMutable{ .limbs = limbs_r, .positive = undefined, .len = undefined };
        result_q.divTrunc(&result_r, lhs_bigint, rhs_bigint, limbs_buffer);
        return fromBigInt(allocator, result_q.toConst());
    }

    pub fn intDivFloor(lhs: Value, rhs: Value, allocator: Allocator) !Value {
        // TODO is this a performance issue? maybe we should try the operation without
        // resorting to BigInt first.
        var lhs_space: Value.BigIntSpace = undefined;
        var rhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const rhs_bigint = rhs.toBigInt(&rhs_space);
        const limbs_q = try allocator.alloc(
            std.math.big.Limb,
            lhs_bigint.limbs.len,
        );
        const limbs_r = try allocator.alloc(
            std.math.big.Limb,
            rhs_bigint.limbs.len,
        );
        const limbs_buffer = try allocator.alloc(
            std.math.big.Limb,
            std.math.big.int.calcDivLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len),
        );
        var result_q = BigIntMutable{ .limbs = limbs_q, .positive = undefined, .len = undefined };
        var result_r = BigIntMutable{ .limbs = limbs_r, .positive = undefined, .len = undefined };
        result_q.divFloor(&result_r, lhs_bigint, rhs_bigint, limbs_buffer);
        return fromBigInt(allocator, result_q.toConst());
    }

    pub fn intRem(lhs: Value, rhs: Value, allocator: Allocator) !Value {
        // TODO is this a performance issue? maybe we should try the operation without
        // resorting to BigInt first.
        var lhs_space: Value.BigIntSpace = undefined;
        var rhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const rhs_bigint = rhs.toBigInt(&rhs_space);
        const limbs_q = try allocator.alloc(
            std.math.big.Limb,
            lhs_bigint.limbs.len,
        );
        const limbs_r = try allocator.alloc(
            std.math.big.Limb,
            // TODO: consider reworking Sema to re-use Values rather than
            // always producing new Value objects.
            rhs_bigint.limbs.len,
        );
        const limbs_buffer = try allocator.alloc(
            std.math.big.Limb,
            std.math.big.int.calcDivLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len),
        );
        var result_q = BigIntMutable{ .limbs = limbs_q, .positive = undefined, .len = undefined };
        var result_r = BigIntMutable{ .limbs = limbs_r, .positive = undefined, .len = undefined };
        result_q.divTrunc(&result_r, lhs_bigint, rhs_bigint, limbs_buffer);
        return fromBigInt(allocator, result_r.toConst());
    }

    pub fn intMod(lhs: Value, rhs: Value, allocator: Allocator) !Value {
        // TODO is this a performance issue? maybe we should try the operation without
        // resorting to BigInt first.
        var lhs_space: Value.BigIntSpace = undefined;
        var rhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const rhs_bigint = rhs.toBigInt(&rhs_space);
        const limbs_q = try allocator.alloc(
            std.math.big.Limb,
            lhs_bigint.limbs.len,
        );
        const limbs_r = try allocator.alloc(
            std.math.big.Limb,
            rhs_bigint.limbs.len,
        );
        const limbs_buffer = try allocator.alloc(
            std.math.big.Limb,
            std.math.big.int.calcDivLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len),
        );
        var result_q = BigIntMutable{ .limbs = limbs_q, .positive = undefined, .len = undefined };
        var result_r = BigIntMutable{ .limbs = limbs_r, .positive = undefined, .len = undefined };
        result_q.divFloor(&result_r, lhs_bigint, rhs_bigint, limbs_buffer);
        return fromBigInt(allocator, result_r.toConst());
    }

    /// Returns true if the value is a floating point type and is NaN. Returns false otherwise.
    pub fn isNan(val: Value) bool {
        return switch (val.tag()) {
            .float_16 => std.math.isNan(val.castTag(.float_16).?.data),
            .float_32 => std.math.isNan(val.castTag(.float_32).?.data),
            .float_64 => std.math.isNan(val.castTag(.float_64).?.data),
            .float_80 => std.math.isNan(val.castTag(.float_80).?.data),
            .float_128 => std.math.isNan(val.castTag(.float_128).?.data),
            else => false,
        };
    }

    pub fn floatRem(lhs: Value, rhs: Value, float_type: Type, arena: Allocator, target: Target) !Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const lhs_val = lhs.toFloat(f16);
                const rhs_val = rhs.toFloat(f16);
                return Value.Tag.float_16.create(arena, @rem(lhs_val, rhs_val));
            },
            32 => {
                const lhs_val = lhs.toFloat(f32);
                const rhs_val = rhs.toFloat(f32);
                return Value.Tag.float_32.create(arena, @rem(lhs_val, rhs_val));
            },
            64 => {
                const lhs_val = lhs.toFloat(f64);
                const rhs_val = rhs.toFloat(f64);
                return Value.Tag.float_64.create(arena, @rem(lhs_val, rhs_val));
            },
            80 => {
                if (true) {
                    @panic("TODO implement compiler_rt __remx");
                }
                const lhs_val = lhs.toFloat(f80);
                const rhs_val = rhs.toFloat(f80);
                return Value.Tag.float_80.create(arena, @rem(lhs_val, rhs_val));
            },
            128 => {
                const lhs_val = lhs.toFloat(f128);
                const rhs_val = rhs.toFloat(f128);
                return Value.Tag.float_128.create(arena, @rem(lhs_val, rhs_val));
            },
            else => unreachable,
        }
    }

    pub fn floatMod(lhs: Value, rhs: Value, float_type: Type, arena: Allocator, target: Target) !Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const lhs_val = lhs.toFloat(f16);
                const rhs_val = rhs.toFloat(f16);
                return Value.Tag.float_16.create(arena, @mod(lhs_val, rhs_val));
            },
            32 => {
                const lhs_val = lhs.toFloat(f32);
                const rhs_val = rhs.toFloat(f32);
                return Value.Tag.float_32.create(arena, @mod(lhs_val, rhs_val));
            },
            64 => {
                const lhs_val = lhs.toFloat(f64);
                const rhs_val = rhs.toFloat(f64);
                return Value.Tag.float_64.create(arena, @mod(lhs_val, rhs_val));
            },
            80 => {
                if (true) {
                    @panic("TODO implement compiler_rt __modx");
                }
                const lhs_val = lhs.toFloat(f80);
                const rhs_val = rhs.toFloat(f80);
                return Value.Tag.float_80.create(arena, @mod(lhs_val, rhs_val));
            },
            128 => {
                const lhs_val = lhs.toFloat(f128);
                const rhs_val = rhs.toFloat(f128);
                return Value.Tag.float_128.create(arena, @mod(lhs_val, rhs_val));
            },
            else => unreachable,
        }
    }

    pub fn intMul(lhs: Value, rhs: Value, allocator: Allocator) !Value {
        // TODO is this a performance issue? maybe we should try the operation without
        // resorting to BigInt first.
        var lhs_space: Value.BigIntSpace = undefined;
        var rhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const rhs_bigint = rhs.toBigInt(&rhs_space);
        const limbs = try allocator.alloc(
            std.math.big.Limb,
            lhs_bigint.limbs.len + rhs_bigint.limbs.len,
        );
        var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
        var limbs_buffer = try allocator.alloc(
            std.math.big.Limb,
            std.math.big.int.calcMulLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len, 1),
        );
        defer allocator.free(limbs_buffer);
        result_bigint.mul(lhs_bigint, rhs_bigint, limbs_buffer, allocator);
        return fromBigInt(allocator, result_bigint.toConst());
    }

    pub fn intTrunc(val: Value, allocator: Allocator, signedness: std.builtin.Signedness, bits: u16) !Value {
        var val_space: Value.BigIntSpace = undefined;
        const val_bigint = val.toBigInt(&val_space);

        const limbs = try allocator.alloc(
            std.math.big.Limb,
            std.math.big.int.calcTwosCompLimbCount(bits),
        );
        var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };

        result_bigint.truncate(val_bigint, signedness, bits);
        return fromBigInt(allocator, result_bigint.toConst());
    }

    pub fn shl(lhs: Value, rhs: Value, allocator: Allocator) !Value {
        // TODO is this a performance issue? maybe we should try the operation without
        // resorting to BigInt first.
        var lhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const shift = @intCast(usize, rhs.toUnsignedInt());
        const limbs = try allocator.alloc(
            std.math.big.Limb,
            lhs_bigint.limbs.len + (shift / (@sizeOf(std.math.big.Limb) * 8)) + 1,
        );
        var result_bigint = BigIntMutable{
            .limbs = limbs,
            .positive = undefined,
            .len = undefined,
        };
        result_bigint.shiftLeft(lhs_bigint, shift);
        return fromBigInt(allocator, result_bigint.toConst());
    }

    pub fn shlWithOverflow(
        lhs: Value,
        rhs: Value,
        ty: Type,
        allocator: Allocator,
        target: Target,
    ) !OverflowArithmeticResult {
        const info = ty.intInfo(target);
        var lhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const shift = @intCast(usize, rhs.toUnsignedInt());
        const limbs = try allocator.alloc(
            std.math.big.Limb,
            lhs_bigint.limbs.len + (shift / (@sizeOf(std.math.big.Limb) * 8)) + 1,
        );
        var result_bigint = BigIntMutable{
            .limbs = limbs,
            .positive = undefined,
            .len = undefined,
        };
        result_bigint.shiftLeft(lhs_bigint, shift);
        const overflowed = !result_bigint.toConst().fitsInTwosComp(info.signedness, info.bits);
        if (overflowed) {
            result_bigint.truncate(result_bigint.toConst(), info.signedness, info.bits);
        }
        return OverflowArithmeticResult{
            .overflowed = overflowed,
            .wrapped_result = try fromBigInt(allocator, result_bigint.toConst()),
        };
    }

    pub fn shlSat(
        lhs: Value,
        rhs: Value,
        ty: Type,
        arena: Allocator,
        target: Target,
    ) !Value {
        // TODO is this a performance issue? maybe we should try the operation without
        // resorting to BigInt first.
        const info = ty.intInfo(target);

        var lhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const shift = @intCast(usize, rhs.toUnsignedInt());
        const limbs = try arena.alloc(
            std.math.big.Limb,
            std.math.big.int.calcTwosCompLimbCount(info.bits),
        );
        var result_bigint = BigIntMutable{
            .limbs = limbs,
            .positive = undefined,
            .len = undefined,
        };
        result_bigint.shiftLeftSat(lhs_bigint, shift, info.signedness, info.bits);
        return fromBigInt(arena, result_bigint.toConst());
    }

    pub fn shlTrunc(
        lhs: Value,
        rhs: Value,
        ty: Type,
        arena: Allocator,
        target: Target,
    ) !Value {
        const shifted = try lhs.shl(rhs, arena);
        const int_info = ty.intInfo(target);
        const truncated = try shifted.intTrunc(arena, int_info.signedness, int_info.bits);
        return truncated;
    }

    pub fn shr(lhs: Value, rhs: Value, allocator: Allocator) !Value {
        // TODO is this a performance issue? maybe we should try the operation without
        // resorting to BigInt first.
        var lhs_space: Value.BigIntSpace = undefined;
        const lhs_bigint = lhs.toBigInt(&lhs_space);
        const shift = @intCast(usize, rhs.toUnsignedInt());

        const result_limbs = lhs_bigint.limbs.len -| (shift / (@sizeOf(std.math.big.Limb) * 8));
        if (result_limbs == 0) {
            // The shift is enough to remove all the bits from the number, which means the
            // result is zero.
            return Value.zero;
        }

        const limbs = try allocator.alloc(
            std.math.big.Limb,
            result_limbs,
        );
        var result_bigint = BigIntMutable{
            .limbs = limbs,
            .positive = undefined,
            .len = undefined,
        };
        result_bigint.shiftRight(lhs_bigint, shift);
        return fromBigInt(allocator, result_bigint.toConst());
    }

    pub fn floatAdd(
        lhs: Value,
        rhs: Value,
        float_type: Type,
        arena: Allocator,
        target: Target,
    ) !Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const lhs_val = lhs.toFloat(f16);
                const rhs_val = rhs.toFloat(f16);
                return Value.Tag.float_16.create(arena, lhs_val + rhs_val);
            },
            32 => {
                const lhs_val = lhs.toFloat(f32);
                const rhs_val = rhs.toFloat(f32);
                return Value.Tag.float_32.create(arena, lhs_val + rhs_val);
            },
            64 => {
                const lhs_val = lhs.toFloat(f64);
                const rhs_val = rhs.toFloat(f64);
                return Value.Tag.float_64.create(arena, lhs_val + rhs_val);
            },
            80 => {
                const lhs_val = lhs.toFloat(f80);
                const rhs_val = rhs.toFloat(f80);
                return Value.Tag.float_80.create(arena, lhs_val + rhs_val);
            },
            128 => {
                const lhs_val = lhs.toFloat(f128);
                const rhs_val = rhs.toFloat(f128);
                return Value.Tag.float_128.create(arena, lhs_val + rhs_val);
            },
            else => unreachable,
        }
    }

    pub fn floatSub(
        lhs: Value,
        rhs: Value,
        float_type: Type,
        arena: Allocator,
        target: Target,
    ) !Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const lhs_val = lhs.toFloat(f16);
                const rhs_val = rhs.toFloat(f16);
                return Value.Tag.float_16.create(arena, lhs_val - rhs_val);
            },
            32 => {
                const lhs_val = lhs.toFloat(f32);
                const rhs_val = rhs.toFloat(f32);
                return Value.Tag.float_32.create(arena, lhs_val - rhs_val);
            },
            64 => {
                const lhs_val = lhs.toFloat(f64);
                const rhs_val = rhs.toFloat(f64);
                return Value.Tag.float_64.create(arena, lhs_val - rhs_val);
            },
            80 => {
                const lhs_val = lhs.toFloat(f80);
                const rhs_val = rhs.toFloat(f80);
                return Value.Tag.float_80.create(arena, lhs_val - rhs_val);
            },
            128 => {
                const lhs_val = lhs.toFloat(f128);
                const rhs_val = rhs.toFloat(f128);
                return Value.Tag.float_128.create(arena, lhs_val - rhs_val);
            },
            else => unreachable,
        }
    }

    pub fn floatDiv(
        lhs: Value,
        rhs: Value,
        float_type: Type,
        arena: Allocator,
        target: Target,
    ) !Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const lhs_val = lhs.toFloat(f16);
                const rhs_val = rhs.toFloat(f16);
                return Value.Tag.float_16.create(arena, lhs_val / rhs_val);
            },
            32 => {
                const lhs_val = lhs.toFloat(f32);
                const rhs_val = rhs.toFloat(f32);
                return Value.Tag.float_32.create(arena, lhs_val / rhs_val);
            },
            64 => {
                const lhs_val = lhs.toFloat(f64);
                const rhs_val = rhs.toFloat(f64);
                return Value.Tag.float_64.create(arena, lhs_val / rhs_val);
            },
            80 => {
                if (true) {
                    @panic("TODO implement compiler_rt __divxf3");
                }
                const lhs_val = lhs.toFloat(f80);
                const rhs_val = rhs.toFloat(f80);
                return Value.Tag.float_80.create(arena, lhs_val / rhs_val);
            },
            128 => {
                const lhs_val = lhs.toFloat(f128);
                const rhs_val = rhs.toFloat(f128);
                return Value.Tag.float_128.create(arena, lhs_val / rhs_val);
            },
            else => unreachable,
        }
    }

    pub fn floatDivFloor(
        lhs: Value,
        rhs: Value,
        float_type: Type,
        arena: Allocator,
        target: Target,
    ) !Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const lhs_val = lhs.toFloat(f16);
                const rhs_val = rhs.toFloat(f16);
                return Value.Tag.float_16.create(arena, @divFloor(lhs_val, rhs_val));
            },
            32 => {
                const lhs_val = lhs.toFloat(f32);
                const rhs_val = rhs.toFloat(f32);
                return Value.Tag.float_32.create(arena, @divFloor(lhs_val, rhs_val));
            },
            64 => {
                const lhs_val = lhs.toFloat(f64);
                const rhs_val = rhs.toFloat(f64);
                return Value.Tag.float_64.create(arena, @divFloor(lhs_val, rhs_val));
            },
            80 => {
                if (true) {
                    @panic("TODO implement compiler_rt __floorx");
                }
                const lhs_val = lhs.toFloat(f80);
                const rhs_val = rhs.toFloat(f80);
                return Value.Tag.float_80.create(arena, @divFloor(lhs_val, rhs_val));
            },
            128 => {
                const lhs_val = lhs.toFloat(f128);
                const rhs_val = rhs.toFloat(f128);
                return Value.Tag.float_128.create(arena, @divFloor(lhs_val, rhs_val));
            },
            else => unreachable,
        }
    }

    pub fn floatDivTrunc(
        lhs: Value,
        rhs: Value,
        float_type: Type,
        arena: Allocator,
        target: Target,
    ) !Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const lhs_val = lhs.toFloat(f16);
                const rhs_val = rhs.toFloat(f16);
                return Value.Tag.float_16.create(arena, @divTrunc(lhs_val, rhs_val));
            },
            32 => {
                const lhs_val = lhs.toFloat(f32);
                const rhs_val = rhs.toFloat(f32);
                return Value.Tag.float_32.create(arena, @divTrunc(lhs_val, rhs_val));
            },
            64 => {
                const lhs_val = lhs.toFloat(f64);
                const rhs_val = rhs.toFloat(f64);
                return Value.Tag.float_64.create(arena, @divTrunc(lhs_val, rhs_val));
            },
            80 => {
                if (true) {
                    @panic("TODO implement compiler_rt __truncx");
                }
                const lhs_val = lhs.toFloat(f80);
                const rhs_val = rhs.toFloat(f80);
                return Value.Tag.float_80.create(arena, @divTrunc(lhs_val, rhs_val));
            },
            128 => {
                const lhs_val = lhs.toFloat(f128);
                const rhs_val = rhs.toFloat(f128);
                return Value.Tag.float_128.create(arena, @divTrunc(lhs_val, rhs_val));
            },
            else => unreachable,
        }
    }

    pub fn floatMul(
        lhs: Value,
        rhs: Value,
        float_type: Type,
        arena: Allocator,
        target: Target,
    ) !Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const lhs_val = lhs.toFloat(f16);
                const rhs_val = rhs.toFloat(f16);
                return Value.Tag.float_16.create(arena, lhs_val * rhs_val);
            },
            32 => {
                const lhs_val = lhs.toFloat(f32);
                const rhs_val = rhs.toFloat(f32);
                return Value.Tag.float_32.create(arena, lhs_val * rhs_val);
            },
            64 => {
                const lhs_val = lhs.toFloat(f64);
                const rhs_val = rhs.toFloat(f64);
                return Value.Tag.float_64.create(arena, lhs_val * rhs_val);
            },
            80 => {
                if (true) {
                    @panic("TODO implement compiler_rt __mulxf3");
                }
                const lhs_val = lhs.toFloat(f80);
                const rhs_val = rhs.toFloat(f80);
                return Value.Tag.float_80.create(arena, lhs_val * rhs_val);
            },
            128 => {
                const lhs_val = lhs.toFloat(f128);
                const rhs_val = rhs.toFloat(f128);
                return Value.Tag.float_128.create(arena, lhs_val * rhs_val);
            },
            else => unreachable,
        }
    }

    pub fn sqrt(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const f = val.toFloat(f16);
                return Value.Tag.float_16.create(arena, @sqrt(f));
            },
            32 => {
                const f = val.toFloat(f32);
                return Value.Tag.float_32.create(arena, @sqrt(f));
            },
            64 => {
                const f = val.toFloat(f64);
                return Value.Tag.float_64.create(arena, @sqrt(f));
            },
            80 => {
                if (true) {
                    @panic("TODO implement compiler_rt __sqrtx");
                }
                const f = val.toFloat(f80);
                return Value.Tag.float_80.create(arena, @sqrt(f));
            },
            128 => {
                if (true) {
                    @panic("TODO implement compiler_rt sqrtq");
                }
                const f = val.toFloat(f128);
                return Value.Tag.float_128.create(arena, @sqrt(f));
            },
            else => unreachable,
        }
    }

    pub fn sin(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const f = val.toFloat(f16);
                return Value.Tag.float_16.create(arena, @sin(f));
            },
            32 => {
                const f = val.toFloat(f32);
                return Value.Tag.float_32.create(arena, @sin(f));
            },
            64 => {
                const f = val.toFloat(f64);
                return Value.Tag.float_64.create(arena, @sin(f));
            },
            80 => {
                if (true) {
                    @panic("TODO implement compiler_rt sin for f80");
                }
                const f = val.toFloat(f80);
                return Value.Tag.float_80.create(arena, @sin(f));
            },
            128 => {
                if (true) {
                    @panic("TODO implement compiler_rt sin for f128");
                }
                const f = val.toFloat(f128);
                return Value.Tag.float_128.create(arena, @sin(f));
            },
            else => unreachable,
        }
    }

    pub fn cos(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const f = val.toFloat(f16);
                return Value.Tag.float_16.create(arena, @cos(f));
            },
            32 => {
                const f = val.toFloat(f32);
                return Value.Tag.float_32.create(arena, @cos(f));
            },
            64 => {
                const f = val.toFloat(f64);
                return Value.Tag.float_64.create(arena, @cos(f));
            },
            80 => {
                if (true) {
                    @panic("TODO implement compiler_rt cos for f80");
                }
                const f = val.toFloat(f80);
                return Value.Tag.float_80.create(arena, @cos(f));
            },
            128 => {
                if (true) {
                    @panic("TODO implement compiler_rt cos for f128");
                }
                const f = val.toFloat(f128);
                return Value.Tag.float_128.create(arena, @cos(f));
            },
            else => unreachable,
        }
    }

    pub fn exp(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const f = val.toFloat(f16);
                return Value.Tag.float_16.create(arena, @exp(f));
            },
            32 => {
                const f = val.toFloat(f32);
                return Value.Tag.float_32.create(arena, @exp(f));
            },
            64 => {
                const f = val.toFloat(f64);
                return Value.Tag.float_64.create(arena, @exp(f));
            },
            80 => {
                if (true) {
                    @panic("TODO implement compiler_rt exp for f80");
                }
                const f = val.toFloat(f80);
                return Value.Tag.float_80.create(arena, @exp(f));
            },
            128 => {
                if (true) {
                    @panic("TODO implement compiler_rt exp for f128");
                }
                const f = val.toFloat(f128);
                return Value.Tag.float_128.create(arena, @exp(f));
            },
            else => unreachable,
        }
    }

    pub fn exp2(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const f = val.toFloat(f16);
                return Value.Tag.float_16.create(arena, @exp2(f));
            },
            32 => {
                const f = val.toFloat(f32);
                return Value.Tag.float_32.create(arena, @exp2(f));
            },
            64 => {
                const f = val.toFloat(f64);
                return Value.Tag.float_64.create(arena, @exp2(f));
            },
            80 => {
                if (true) {
                    @panic("TODO implement compiler_rt exp2 for f80");
                }
                const f = val.toFloat(f80);
                return Value.Tag.float_80.create(arena, @exp2(f));
            },
            128 => {
                if (true) {
                    @panic("TODO implement compiler_rt exp2 for f128");
                }
                const f = val.toFloat(f128);
                return Value.Tag.float_128.create(arena, @exp2(f));
            },
            else => unreachable,
        }
    }

    pub fn log(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const f = val.toFloat(f16);
                return Value.Tag.float_16.create(arena, @log(f));
            },
            32 => {
                const f = val.toFloat(f32);
                return Value.Tag.float_32.create(arena, @log(f));
            },
            64 => {
                const f = val.toFloat(f64);
                return Value.Tag.float_64.create(arena, @log(f));
            },
            80 => {
                if (true) {
                    @panic("TODO implement compiler_rt log for f80");
                }
                const f = val.toFloat(f80);
                return Value.Tag.float_80.create(arena, @log(f));
            },
            128 => {
                if (true) {
                    @panic("TODO implement compiler_rt log for f128");
                }
                const f = val.toFloat(f128);
                return Value.Tag.float_128.create(arena, @log(f));
            },
            else => unreachable,
        }
    }

    pub fn log2(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const f = val.toFloat(f16);
                return Value.Tag.float_16.create(arena, @log2(f));
            },
            32 => {
                const f = val.toFloat(f32);
                return Value.Tag.float_32.create(arena, @log2(f));
            },
            64 => {
                const f = val.toFloat(f64);
                return Value.Tag.float_64.create(arena, @log2(f));
            },
            80 => {
                if (true) {
                    @panic("TODO implement compiler_rt log2 for f80");
                }
                const f = val.toFloat(f80);
                return Value.Tag.float_80.create(arena, @log2(f));
            },
            128 => {
                if (true) {
                    @panic("TODO implement compiler_rt log2 for f128");
                }
                const f = val.toFloat(f128);
                return Value.Tag.float_128.create(arena, @log2(f));
            },
            else => unreachable,
        }
    }

    pub fn log10(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const f = val.toFloat(f16);
                return Value.Tag.float_16.create(arena, @log10(f));
            },
            32 => {
                const f = val.toFloat(f32);
                return Value.Tag.float_32.create(arena, @log10(f));
            },
            64 => {
                const f = val.toFloat(f64);
                return Value.Tag.float_64.create(arena, @log10(f));
            },
            80 => {
                if (true) {
                    @panic("TODO implement compiler_rt log10 for f80");
                }
                const f = val.toFloat(f80);
                return Value.Tag.float_80.create(arena, @log10(f));
            },
            128 => {
                if (true) {
                    @panic("TODO implement compiler_rt log10 for f128");
                }
                const f = val.toFloat(f128);
                return Value.Tag.float_128.create(arena, @log10(f));
            },
            else => unreachable,
        }
    }

    pub fn fabs(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const f = val.toFloat(f16);
                return Value.Tag.float_16.create(arena, @fabs(f));
            },
            32 => {
                const f = val.toFloat(f32);
                return Value.Tag.float_32.create(arena, @fabs(f));
            },
            64 => {
                const f = val.toFloat(f64);
                return Value.Tag.float_64.create(arena, @fabs(f));
            },
            80 => {
                if (true) {
                    @panic("TODO implement compiler_rt fabs for f80");
                }
                const f = val.toFloat(f80);
                return Value.Tag.float_80.create(arena, @fabs(f));
            },
            128 => {
                if (true) {
                    @panic("TODO implement compiler_rt fabs for f128");
                }
                const f = val.toFloat(f128);
                return Value.Tag.float_128.create(arena, @fabs(f));
            },
            else => unreachable,
        }
    }

    pub fn floor(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const f = val.toFloat(f16);
                return Value.Tag.float_16.create(arena, @floor(f));
            },
            32 => {
                const f = val.toFloat(f32);
                return Value.Tag.float_32.create(arena, @floor(f));
            },
            64 => {
                const f = val.toFloat(f64);
                return Value.Tag.float_64.create(arena, @floor(f));
            },
            80 => {
                if (true) {
                    @panic("TODO implement compiler_rt floor for f80");
                }
                const f = val.toFloat(f80);
                return Value.Tag.float_80.create(arena, @floor(f));
            },
            128 => {
                if (true) {
                    @panic("TODO implement compiler_rt floor for f128");
                }
                const f = val.toFloat(f128);
                return Value.Tag.float_128.create(arena, @floor(f));
            },
            else => unreachable,
        }
    }

    pub fn ceil(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const f = val.toFloat(f16);
                return Value.Tag.float_16.create(arena, @ceil(f));
            },
            32 => {
                const f = val.toFloat(f32);
                return Value.Tag.float_32.create(arena, @ceil(f));
            },
            64 => {
                const f = val.toFloat(f64);
                return Value.Tag.float_64.create(arena, @ceil(f));
            },
            80 => {
                if (true) {
                    @panic("TODO implement compiler_rt ceil for f80");
                }
                const f = val.toFloat(f80);
                return Value.Tag.float_80.create(arena, @ceil(f));
            },
            128 => {
                if (true) {
                    @panic("TODO implement compiler_rt ceil for f128");
                }
                const f = val.toFloat(f128);
                return Value.Tag.float_128.create(arena, @ceil(f));
            },
            else => unreachable,
        }
    }

    pub fn round(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const f = val.toFloat(f16);
                return Value.Tag.float_16.create(arena, @round(f));
            },
            32 => {
                const f = val.toFloat(f32);
                return Value.Tag.float_32.create(arena, @round(f));
            },
            64 => {
                const f = val.toFloat(f64);
                return Value.Tag.float_64.create(arena, @round(f));
            },
            80 => {
                if (true) {
                    @panic("TODO implement compiler_rt round for f80");
                }
                const f = val.toFloat(f80);
                return Value.Tag.float_80.create(arena, @round(f));
            },
            128 => {
                if (true) {
                    @panic("TODO implement compiler_rt round for f128");
                }
                const f = val.toFloat(f128);
                return Value.Tag.float_128.create(arena, @round(f));
            },
            else => unreachable,
        }
    }

    pub fn trunc(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
        switch (float_type.floatBits(target)) {
            16 => {
                const f = val.toFloat(f16);
                return Value.Tag.float_16.create(arena, @trunc(f));
            },
            32 => {
                const f = val.toFloat(f32);
                return Value.Tag.float_32.create(arena, @trunc(f));
            },
            64 => {
                const f = val.toFloat(f64);
                return Value.Tag.float_64.create(arena, @trunc(f));
            },
            80 => {
                if (true) {
                    @panic("TODO implement compiler_rt trunc for f80");
                }
                const f = val.toFloat(f80);
                return Value.Tag.float_80.create(arena, @trunc(f));
            },
            128 => {
                if (true) {
                    @panic("TODO implement compiler_rt trunc for f128");
                }
                const f = val.toFloat(f128);
                return Value.Tag.float_128.create(arena, @trunc(f));
            },
            else => unreachable,
        }
    }

    /// This type is not copyable since it may contain pointers to its inner data.
    pub const Payload = struct {
        tag: Tag,

        pub const U32 = struct {
            base: Payload,
            data: u32,
        };

        pub const U64 = struct {
            base: Payload,
            data: u64,
        };

        pub const I64 = struct {
            base: Payload,
            data: i64,
        };

        pub const BigInt = struct {
            base: Payload,
            data: []const std.math.big.Limb,

            pub fn asBigInt(self: BigInt) BigIntConst {
                const positive = switch (self.base.tag) {
                    .int_big_positive => true,
                    .int_big_negative => false,
                    else => unreachable,
                };
                return BigIntConst{ .limbs = self.data, .positive = positive };
            }
        };

        pub const Function = struct {
            base: Payload,
            data: *Module.Fn,
        };

        pub const ExternFn = struct {
            base: Payload,
            data: *Module.ExternFn,
        };

        pub const Decl = struct {
            base: Payload,
            data: *Module.Decl,
        };

        pub const Variable = struct {
            base: Payload,
            data: *Module.Var,
        };

        pub const SubValue = struct {
            base: Payload,
            data: Value,
        };

        pub const DeclRefMut = struct {
            pub const base_tag = Tag.decl_ref_mut;

            base: Payload = Payload{ .tag = base_tag },
            data: Data,

            pub const Data = struct {
                decl: *Module.Decl,
                runtime_index: u32,
            };
        };

        pub const ElemPtr = struct {
            pub const base_tag = Tag.elem_ptr;

            base: Payload = Payload{ .tag = base_tag },
            data: struct {
                array_ptr: Value,
                index: usize,
            },
        };

        pub const FieldPtr = struct {
            pub const base_tag = Tag.field_ptr;

            base: Payload = Payload{ .tag = base_tag },
            data: struct {
                container_ptr: Value,
                field_index: usize,
            },
        };

        pub const Bytes = struct {
            base: Payload,
            /// Includes the sentinel, if any.
            data: []const u8,
        };

        pub const Array = struct {
            base: Payload,
            data: []Value,
        };

        pub const Slice = struct {
            base: Payload,
            data: struct {
                ptr: Value,
                len: Value,
            },
        };

        pub const Ty = struct {
            base: Payload,
            data: Type,
        };

        pub const IntType = struct {
            pub const base_tag = Tag.int_type;

            base: Payload = Payload{ .tag = base_tag },
            data: struct {
                bits: u16,
                signed: bool,
            },
        };

        pub const Float_16 = struct {
            pub const base_tag = Tag.float_16;

            base: Payload = .{ .tag = base_tag },
            data: f16,
        };

        pub const Float_32 = struct {
            pub const base_tag = Tag.float_32;

            base: Payload = .{ .tag = base_tag },
            data: f32,
        };

        pub const Float_64 = struct {
            pub const base_tag = Tag.float_64;

            base: Payload = .{ .tag = base_tag },
            data: f64,
        };

        pub const Float_80 = struct {
            pub const base_tag = Tag.float_80;

            base: Payload = .{ .tag = base_tag },
            data: f80,
        };

        pub const Float_128 = struct {
            pub const base_tag = Tag.float_128;

            base: Payload = .{ .tag = base_tag },
            data: f128,
        };

        pub const Error = struct {
            base: Payload = .{ .tag = .@"error" },
            data: struct {
                /// `name` is owned by `Module` and will be valid for the entire
                /// duration of the compilation.
                /// TODO revisit this when we have the concept of the error tag type
                name: []const u8,
            },
        };

        pub const InferredAlloc = struct {
            pub const base_tag = Tag.inferred_alloc;

            base: Payload = .{ .tag = base_tag },
            data: struct {
                /// The value stored in the inferred allocation. This will go into
                /// peer type resolution. This is stored in a separate list so that
                /// the items are contiguous in memory and thus can be passed to
                /// `Module.resolvePeerTypes`.
                stored_inst_list: std.ArrayListUnmanaged(Air.Inst.Ref) = .{},
                /// 0 means ABI-aligned.
                alignment: u16,
            },
        };

        pub const InferredAllocComptime = struct {
            pub const base_tag = Tag.inferred_alloc_comptime;

            base: Payload = .{ .tag = base_tag },
            data: struct {
                decl: *Module.Decl,
                /// 0 means ABI-aligned.
                alignment: u16,
            },
        };

        pub const Struct = struct {
            pub const base_tag = Tag.@"struct";

            base: Payload = .{ .tag = base_tag },
            /// Field values. The types are according to the struct type.
            /// The length is provided here so that copying a Value does not depend on the Type.
            data: []Value,
        };

        pub const Union = struct {
            pub const base_tag = Tag.@"union";

            base: Payload = .{ .tag = base_tag },
            data: struct {
                tag: Value,
                val: Value,
            },
        };

        pub const BoundFn = struct {
            pub const base_tag = Tag.bound_fn;

            base: Payload = Payload{ .tag = base_tag },
            data: struct {
                func_inst: Air.Inst.Ref,
                arg0_inst: Air.Inst.Ref,
            },
        };
    };

    /// Big enough to fit any non-BigInt value
    pub const BigIntSpace = struct {
        /// The +1 is headroom so that operations such as incrementing once or decrementing once
        /// are possible without using an allocator.
        limbs: [(@sizeOf(u64) / @sizeOf(std.math.big.Limb)) + 1]std.math.big.Limb,
    };

    pub const zero = initTag(.zero);
    pub const one = initTag(.one);
    pub const negative_one: Value = .{ .ptr_otherwise = &negative_one_payload.base };
    pub const undef = initTag(.undef);
    pub const @"void" = initTag(.void_value);
    pub const @"null" = initTag(.null_value);
    pub const @"false" = initTag(.bool_false);
    pub const @"true" = initTag(.bool_true);

    pub fn makeBool(x: bool) Value {
        return if (x) Value.@"true" else Value.@"false";
    }
};

var negative_one_payload: Value.Payload.I64 = .{
    .base = .{ .tag = .int_i64 },
    .data = -1,
};